tmux-weblink 2.2.48 → 2.2.49
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,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,
|
|
3
|
-
`)}getSelection(){return this.terminal.getSelection()}clearSelection(){this.terminal.clearSelection()}hasSelectionSupport(){return!0}};function
|
|
1
|
+
var ei=/\x1b\](?:10|11|110|111|104)(?:;[^\x07\x1b]*)?\x1b?(?:\\|\x07)/g;function vt(e){return e.replace(/\x1b\[\?1049[hl]/g,"")}function Se(e){return e.replace(ei,"")}var Je;function ti(){return Je||(document.querySelector("link[data-tmux-web-xterm-css]")?Je=Promise.resolve():(Je=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)}),Je))}var ni=class Mn{terminal;fitAddon;container;webglActive=!1;repaintTimer=0;webglAddon=null;constructor(t,n,i){this.container=t,this.terminal=n,this.fitAddon=i,this.terminal.loadAddon(this.fitAddon),this.terminal.open(t),this.enableWebglRenderer(),document.addEventListener("visibilitychange",()=>{document.hidden||this.refreshPaintedRows()})}enableWebglRenderer(){if(ai()==="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"),ti()]),o="'JetBrains Mono', 'SF Mono', 'Menlo', monospace",l=new a({fontSize:ii(14,o),fontFamily:o,cursorBlink:!0,cursorStyle:"bar",scrollback:n,convertEol:!1,smoothScrollDuration:120,theme:i});return new Mn(t,l,new r)}get cols(){return this.terminal.cols}get rows(){return this.terminal.rows}write(t){return new Promise(n=>this.terminal.write(t,n))}reset(){this.terminal.reset()}scrollToBottom(){this.terminal.scrollToBottom()}scrollToLine(t,n=!1){this.terminal.scrollToLine(Math.max(0,t),n),this.scheduleRepaintCheck()}scrollLines(t){this.terminal.scrollLines(t),this.scheduleRepaintCheck()}scheduleRepaintCheck(){this.webglActive&&(this.repaintTimer&&clearTimeout(this.repaintTimer),this.repaintTimer=setTimeout(()=>{this.repaintTimer=0,this.refreshPaintedRows()},150))}isNearScrollbackTop(){return this.terminal.buffer.active.viewportY<=1}viewportY(){return this.terminal.buffer.active.viewportY}baseY(){return this.terminal.buffer.active.baseY}cellHeight(){let t=this.terminal.element?.querySelector(".xterm-screen")?.getBoundingClientRect().height??0,n=this.terminal.rows;return t>0&&n>0?t/n:16}fit(){let t=oi(this.container);if(t.width<=0||t.height<=0)return!1;let n=this.terminal.cols,i=this.terminal.rows,a=this.paintedCellWidth();a<=0&&(this.fitAddon.fit(),a=this.paintedCellWidth());let r=this.fitAddon.proposeDimensions?.();if(!r)return this.fitAddon.fit(),!0;let o=this.overlayScrollbarWidth(),l=o>0?o+2:0,p=a>0?Math.max(10,Math.min(r.cols,Math.floor((t.width-l)/a))):r.cols,u=r.rows;return(p!==this.terminal.cols||u!==this.terminal.rows)&&this.terminal.resize(p,u),this.webglActive&&(n!==this.terminal.cols||i!==this.terminal.rows)&&this.refreshPaintedRows(),!0}paintedCellWidth(){let t=this.terminal.element?.querySelector(".xterm-screen")?.getBoundingClientRect().width??0,n=this.terminal.cols;return t>0&&n>0?t/n:0}overlayScrollbarWidth(){let t=this.terminal.element?.querySelector(".vertical.scrollbar");if(!t)return 0;let n=t.getBoundingClientRect();return!(n.width>0)||!(n.height>0)?0:Math.round(n.width)}focus(){this.terminal.focus()}pasteText(t){this.terminal.paste(t)}input(t){this.terminal.input(t,!1)}onData(t){this.terminal.onData(t),this.terminal.onBinary(t)}onResize(t){this.terminal.onResize(t)}onScroll(t){this.terminal.onScroll(t)}attachCustomKeyEventHandler(t){this.terminal.attachCustomKeyEventHandler(t)}isFocused(){let t=document.activeElement;return t?t===this.container||t===this.terminal.textarea||this.container.contains(t)||!!t.closest?.(".xterm"):!1}getScreenText(){return this.getRowsText(0,this.terminal.rows-1)}getRowsText(t,n){let i=this.terminal.buffer.active,[a,r]=t<=n?[t,n]:[n,t],o=i.viewportY,l=[];for(let p=a;p<=r;p++){let u=i.getLine(o+p);l.push(u?u.translateToString(!0):"")}return l.join(`
|
|
2
|
+
`)}selectRows(t,n){let i=this.terminal.buffer.active,[a,r]=t<=n?[t,n]:[n,t];this.terminal.selectLines(i.viewportY+a,i.viewportY+r)}selectCells(t,n,i,a){let r=this.terminal.buffer.active,o=Math.min(n,a),l=Math.max(n,a);if(o===l){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+l)}getCellsText(t,n,i,a){let r=this.terminal.buffer.active,o=Math.min(n,a),l=Math.max(n,a),p=n<a?t:n>a?i:Math.min(t,i),u=n<a?i:n>a?t:Math.max(t,i),v=r.viewportY,y=[];for(let D=o;D<=l;D++){let x=r.getLine(v+D);if(!x){y.push("");continue}let w=D===o?p:0,g=D===l?u:this.terminal.cols-1,A="";for(let J=w;J<=g;J++){let O=x.getCell(J);O&&(A+=O.getChars())}y.push(A.replace(/\s+$/,""))}return y.join(`
|
|
3
|
+
`)}getSelection(){return this.terminal.getSelection()}clearSelection(){this.terminal.clearSelection()}hasSelectionSupport(){return!0}};function ii(e,t){try{let n=document.createElement("canvas").getContext("2d");if(!n)return e;let i=100;n.font=`${i}px ${t}`;let a=n.measureText("M").width/i;if(!Number.isFinite(a)||a<=0)return e;let r=window.devicePixelRatio||1,o=e,l=Number.POSITIVE_INFINITY;for(let p=4;p<=40;p++){let u=p/(a*r);if(u<e-1.5||u>e+1.5)continue;let v=Math.abs(u-e);v<l&&(l=v,o=u)}return Math.round(o*100)/100}catch{return e}}function ai(){try{let e=new URLSearchParams(window.location.search).get("renderer");return e==="dom"||e==="webgl"?e:null}catch{return null}}function oi(e){let t=e.getBoundingClientRect(),n=window.visualViewport;return n?{width:Math.min(t.width,n.width),height:Math.max(0,Math.min(t.height,n.height-Math.max(0,t.top)))}:t}function si(e,t,n){return e.innerHTML="",e.classList.add("terminal-pending"),(async()=>{let i=await ni.create(e,n.scrollback,n.theme),a,r=0,o,l=null,p=0,u=0,v=.2,y=10,D=.95,x=.04,w=null,g=null;function A(s){w||(w=document.createElement("div"),w.style.cssText=["position:absolute","left:0","width:40%","padding:10px 0","text-align:center","font:600 14px/1.4 system-ui, -apple-system, sans-serif","color:rgba(255,255,255,0.95)","background:rgba(20,30,50,0.55)","border:1px solid rgba(255,255,255,0.25)","border-radius:10px","pointer-events:none","opacity:0","transition:opacity 0.15s ease","z-index:6"].join(";"),e.appendChild(w)),w.textContent=s?"\u2191 \u4E0A\u7FFB\u4E00\u9875 (PgUp)":"\u2193 \u4E0B\u7FFB\u4E00\u9875 (PgDn)",w.style.top=s?"10%":"auto",w.style.bottom=s?"auto":"10%",w.style.opacity="1",g&&clearTimeout(g),g=setTimeout(()=>{w&&(w.style.opacity="0")},900)}function J(){g&&clearTimeout(g),w&&(w.style.opacity="0")}function O(){p&&(cancelAnimationFrame(p),p=0),u=0}function _(s){if(O(),Math.abs(s)<v)return;u=Math.max(-y,Math.min(y,s));let d=()=>{if(B){p=0;return}let f=i.cellHeight(),E=f>0?Math.round(u*16/f):u>0?1:-1;E===0&&(E=u>0?1:-1);let I=i.viewportY()-E,ee=i.baseY(),se=Math.max(0,Math.min(I,ee));if(i.scrollToLine(se,!0),u*=D,se!==I){p=0;return}if(Math.abs(u)<x){p=0;return}p=requestAnimationFrame(d)};p=requestAnimationFrame(d)}let z=0,b="connecting",L=0,G=!1,h=[],U="",B=!1,le=1e3,$=location.protocol==="https:"?"wss:":"ws:",Pt=n.wsBase||"/ws",Dn=$+"//"+location.host+Pt+"/"+encodeURIComponent(t),An=(Pt.replace(/^\/ws/,"")||"")+"/api/session/"+encodeURIComponent(t)+"/upload",Fn=/^((?!chrome|android|crios|fxios|edgios).)*safari/i.test(navigator.userAgent);function $n(){return h.join("")+U}async function Pn(s,d=0){let f=s?i.viewportY():0,E=Se($n());if(i.reset(),!E){s||i.scrollToBottom();return}await i.write(E),s?i.scrollToLine(d+f):i.scrollToBottom()}function re(s){a?.readyState===WebSocket.OPEN&&a.send(JSON.stringify(s))}function Nn(s){let d;try{d=JSON.parse(s)}catch{b==="live"&&(U+=s,i.write(Se(s)));return}if(d.type==="auth.required"){let f=localStorage.getItem("tmux-web-token");f?re({type:"auth.token",token:f}):location.href="/login?returnTo="+encodeURIComponent(location.pathname+location.search);return}if(d.type==="attach_failed"&&typeof d.message=="string"){Re=!0,b="dead",i.reset(),i.write(`\r
|
|
4
4
|
\x1B[31m`+Se(d.message)+`\x1B[0m\r
|
|
5
|
-
`).then(()=>{
|
|
5
|
+
`).then(()=>{_e();try{a?.close()}catch{}});return}if(d.type==="auth.ok"){d.token&&localStorage.setItem("tmux-web-token",d.token),le=1e3,de(),re({type:"resize",cols:i.cols,rows:i.rows}),q();return}if(d.type==="auth.failed"){if(d.permanentLock||d.retryAfterMs&&d.retryAfterMs>6e4){localStorage.removeItem("tmux-web-token"),location.href="/login?error="+encodeURIComponent(d.message);return}return}if(d.type==="snapshot"&&typeof d.data=="string"){let f=vt(Se(d.data));h=[f],U="",L=typeof d.lines=="number"?d.lines:n.terminal.initialLines,b="live",i.reset(),de(),re({type:"resize",cols:i.cols,rows:i.rows}),i.write(f).then(()=>i.scrollToBottom());return}if(d.type==="window_changed"&&typeof d.activeIndex=="number"){let f=new URL(location.href);f.searchParams.get("window")!==String(d.activeIndex)&&(f.searchParams.set("window",String(d.activeIndex)),history.replaceState(history.state,"",f)),window.dispatchEvent(new CustomEvent("tmux:windows",{detail:d.windows}));return}if(d.type==="history"&&typeof d.data=="string"){d.lines>0&&d.data?(h.unshift(vt(d.data)),L+=d.lines,Pn(!0,d.lines).finally(()=>{G=!1})):G=!1;return}if(d.type==="data"&&typeof d.data=="string"){let f=vt(Se(d.data));if(b==="connecting"){b="live",U=f,i.write(f);return}b==="live"&&(U+=f,i.write(f))}}let Re=!1;function Nt(){if(Re)return;let s=Dn,d=localStorage.getItem("tmux-web-token");d&&(s+=(s.includes("?")?"&":"?")+"token="+encodeURIComponent(d)),s+=(s.includes("?")?"&":"?")+"cols="+i.cols+"&rows="+i.rows,a=new WebSocket(s),a.onopen=()=>{b="connecting",L=0,G=!1,h=[],U="",i.reset(),le=1e3},a.onmessage=f=>{typeof f.data=="string"&&Nn(f.data)},a.onclose=()=>{B||(b="connecting",!Re&&setTimeout(()=>{le=Math.min(le*2,1e4),!B&&!Re&&Nt()},le))},a.onerror=()=>a?.close()}function he(s){re({type:"input",data:s})}function de(){return i.fit()}function _e(){e.classList.remove("terminal-pending")}function q(){r&&cancelAnimationFrame(r),o&&clearTimeout(o),de(),r=requestAnimationFrame(()=>{r=0,de()&&_e()}),o=setTimeout(()=>{de()&&_e()},120)}function On(){q(),setTimeout(q,50),setTimeout(q,150),setTimeout(q,300)}function Ot(s){return typeof s=="string"&&s.startsWith("image/")}function jt(s){return s?.files?.length?s.files[0]??null:null}function jn(s){if(!s?.items)return null;for(let d=0;d<s.items.length;d++){let f=s.items[d];if(f?.kind==="file"&&Ot(f.type))return f.getAsFile()}return null}async function Hn(s){let d=new FormData,f=s instanceof File&&s.name?s.name:"upload";d.append("file",s,f);let E=localStorage.getItem("tmux-web-token"),I={};E&&(I.Authorization="Bearer "+E);let ee=await fetch(An,{method:"POST",body:d,headers:I});if(!ee.ok){let Jt="upload failed";try{let Wt=await ee.json();Wt.error&&(Jt=Wt.error)}catch{}throw new Error(Jt)}let se=await ee.json();if(!se.path)throw new Error("no path in response");return se.path}async function mt(s){try{let d=await Hn(s);he(d)}catch{}}i.onData(s=>he(s)),i.onResize(({cols:s,rows:d})=>re({type:"resize",cols:s,rows:d})),i.onScroll(()=>{b!=="live"||G||!i.isNearScrollbackTop()||(G=!0,re({type:"load_history",before:L}))});let Ee=!1,ke=!1,P=null,j=null,Ce=document.createElement("div");Ce.className="terminal-copy-banner",Ce.innerHTML='<strong>Copy mode</strong><span class="hint">drag to copy \xB7 Esc exits</span>',Ce.hidden=!0,e.appendChild(Ce);let ne=document.createElement("div");ne.className="terminal-copy-banner terminal-copy-toast",ne.textContent="Copied",ne.hidden=!0,e.appendChild(ne);function Ht(s,d){let f=e.querySelector(".xterm-screen, canvas"),E=(f&&f.getBoundingClientRect().width>0?f:e).getBoundingClientRect(),I=E.height>0&&i.rows>0?E.height/i.rows:18,ee=E.width>0&&i.cols>0?E.width/i.cols:9;return{row:Math.max(0,Math.min(i.rows-1,Math.floor((d-E.top)/I))),col:Math.max(0,Math.min(i.cols-1,Math.floor((s-E.left)/ee)))}}async function ze(s){if(!s)return;try{if(navigator.clipboard?.writeText){await navigator.clipboard.writeText(s);return}}catch{}let d=document.createElement("textarea");d.value=s,d.style.position="fixed",d.style.opacity="0",d.style.pointerEvents="none",document.body.appendChild(d),d.focus(),d.select();try{document.execCommand("copy")}catch{}d.remove()}let xe;function Ue(){ne.hidden=!1,xe&&clearTimeout(xe),xe=setTimeout(()=>{ne.hidden=!0},1e3)}function ve(s){Ee=s,Ce.hidden=!s,e.classList.toggle("terminal-copy-mode-active",s),s&&i.focus()}function Rt(){ve(!Ee)}function Rn(s){B||s.button!==0||ke||(Ee||s.shiftKey)&&(s.preventDefault(),s.stopPropagation(),ke=!0,P=Ht(s.clientX,s.clientY),j=P,i.selectCells(P.col,P.row,j.col,j.row),document.addEventListener("mousemove",ft,!0),document.addEventListener("mouseup",ht,!0))}function ft(s){B||!ke||!P||(s.preventDefault(),s.stopPropagation(),j=Ht(s.clientX,s.clientY),i.selectCells(P.col,P.row,j.col,j.row))}function ht(s){if(B||!ke||!P||!j)return;s.preventDefault(),s.stopPropagation(),document.removeEventListener("mousemove",ft,!0),document.removeEventListener("mouseup",ht,!0),ke=!1;let d=i.getCellsText(P.col,P.row,j.col,j.row);P=null,j=null,i.clearSelection(),ve(!1),d&&(ne.textContent="\u5DF2\u590D\u5236",ze(d).then(Ue)),i.focus()}e.addEventListener("mousedown",Rn,!0),document.addEventListener("keydown",_n,!0);function _n(s){if(!(B||!i.isFocused()||s.defaultPrevented||s.isComposing)){if(Ee){if(s.key==="Escape"){s.preventDefault(),s.stopPropagation(),P=null,j=null,i.clearSelection(),ve(!1);return}if(s.key==="Enter"||(s.ctrlKey||s.metaKey)&&s.code==="KeyC"){s.preventDefault(),s.stopPropagation(),ze(i.getScreenText()).then(Ue),ve(!1);return}}if(s.altKey&&s.code==="KeyC"&&!s.ctrlKey&&!s.metaKey){if(s.preventDefault(),s.stopPropagation(),P&&j){let d=i.getCellsText(P.col,P.row,j.col,j.row);P=null,j=null,i.clearSelection(),ve(!1),d&&(ne.textContent="Copied",ze(d).then(Ue))}else{let d=i.getSelection();d?(i.clearSelection(),ne.textContent="Copied",ze(d).then(Ue)):Rt()}return}if((s.ctrlKey||s.metaKey)&&s.code==="KeyV"){s.preventDefault(),s.stopPropagation(),(async()=>{try{if(navigator.clipboard?.read){let d=await navigator.clipboard.read();for(let f of d)for(let E of f.types)if(Ot(E)){let I=await f.getType(E);await mt(I);return}}}catch{}try{let d=await navigator.clipboard?.readText();d&&i.pasteText(_t(d))}catch{}})();return}}}let qe=0;function _t(s){return s.split(`\r
|
|
6
6
|
`).join(`
|
|
7
7
|
`).split(`
|
|
8
|
-
`).join("\r")}async function _n(o){let d=On(o.clipboardData);if(d){o.preventDefault(),o.stopPropagation();let I=Date.now();if(I-ze<50)return;ze=I,await pt(d);return}let f=o.clipboardData?.getData("text/plain");if(!f)return;o.preventDefault(),o.stopPropagation();let E=Date.now();E-ze<50||(ze=E,i.pasteText(Rt(f)))}let xe=0;function zn(o){o.preventDefault(),xe++,Ot(o.dataTransfer)&&e.classList.add("terminal-drag-over")}function Un(o){o.preventDefault(),o.dataTransfer&&(o.dataTransfer.dropEffect="copy")}function Wn(o){o.preventDefault(),xe--,xe<=0&&(xe=0,e.classList.remove("terminal-drag-over"))}async function Jn(o){o.preventDefault(),xe=0,e.classList.remove("terminal-drag-over");let d=Ot(o.dataTransfer);d&&await pt(d)}function _t(o){!An||o.key!=="Escape"||we||o.defaultPrevented||o.repeat||o.metaKey||o.ctrlKey||o.altKey||i.isFocused()&&(o.preventDefault(),o.stopPropagation(),he("\x1B"))}e.addEventListener("paste",_n),e.addEventListener("dragenter",zn),e.addEventListener("dragover",Un),e.addEventListener("dragleave",Wn),e.addEventListener("drop",Jn),document.addEventListener("keydown",_t,!0);function qn(o){if(o.touches.length!==1){l=null;return}let d=o.touches[0];if(!d)return;O();let f=e.getBoundingClientRect(),E=d.clientX-f.left<f.width*.4?"tui":"history",I=d.clientY-f.top<f.height*.5;l={startX:d.clientX,startY:d.clientY,lastX:d.clientX,lastY:d.clientY,lastT:performance.now(),velocity:0,scrolling:!1,zone:E,tuiUp:I,sent:!1},o.stopPropagation()}function Yn(o){if(!l||o.touches.length!==1)return;let d=o.touches[0];if(!d)return;let f=d.clientY-l.startY,E=d.clientX-l.startX;if(!l.scrolling){if(Math.abs(f)<8||Math.abs(f)<Math.abs(E))return;l.scrolling=!0,Z=Date.now()+500}o.preventDefault(),o.stopPropagation();let I=performance.now(),ee=d.clientY-l.lastY;if(l.zone==="tui"){l.sent||(l.sent=!0,he(l.tuiUp?"\x1B[5~":"\x1B[6~"),A(l.tuiUp)),l.lastX=d.clientX,l.lastY=d.clientY,l.lastT=I;return}let oe=I-l.lastT;oe>0&&(l.velocity=ee/oe),Qn(-ee),l.lastX=d.clientX,l.lastY=d.clientY,l.lastT=I}function Vn(o){if(!l)return;let d=l.scrolling,f=l.zone,E=l.tuiUp,I=l.velocity;if(l=null,o.stopPropagation(),f==="tui"){d||(he(E?"\x1B[5~":"\x1B[6~"),A(E),Z=Date.now()+500,o.preventDefault());return}if(!d){i.focus();return}Z=Date.now()+500,o.preventDefault(),I&&_(I)}function Kn(o){l=null,O(),o.stopPropagation()}function Xn(o){o.pointerType==="touch"&&Date.now()<Z&&(o.preventDefault(),o.stopPropagation())}function Qn(o){let d=i.cellHeight(),f=d>0?Math.round(o/d):o>0?1:-1;f===0&&(f=o>0?1:-1),i.scrollLines(f)}e.addEventListener("touchstart",qn,{passive:!0,capture:!0}),e.addEventListener("touchmove",Yn,{passive:!1,capture:!0}),e.addEventListener("touchend",Vn,{passive:!1,capture:!0}),e.addEventListener("touchcancel",Kn,{passive:!0,capture:!0}),e.addEventListener("pointerup",Xn,!0);function zt(){U()}window.addEventListener("resize",zt),window.visualViewport?.addEventListener("resize",U),window.visualViewport?.addEventListener("scroll",U);let Ut=new ResizeObserver(()=>U());Ut.observe(e),document.fonts?.ready.then(()=>{U(),setTimeout(U,50),setTimeout(U,200)}),e.addEventListener("focusin",Nn,!0);async function Zn(){if(document.fonts?.ready)try{await Promise.race([document.fonts.ready,new Promise(o=>setTimeout(o,1e3))])}catch{}}return requestAnimationFrame(()=>{de()&&He(),(async()=>(await Zn(),de()&&re({type:"resize",cols:i.cols,rows:i.rows}),Pt(),U()))()}),{destroy(){if(B=!0,O(),ve(!1),Ce&&clearTimeout(Ce),document.removeEventListener("mousemove",mt,!0),document.removeEventListener("mouseup",ft,!0),a){try{a.close(1e3,"session switch")}catch{}a=void 0}e.innerHTML="",e.classList.remove("terminal-pending"),window.removeEventListener("resize",zt),Ut.disconnect(),document.removeEventListener("keydown",_t,!0)},focus(){i.focus()},sendInput(o){he(o)},toggleCopyMode(){Ht()}}})()}var m={catalog:null,templates:[],bots:[],approvals:[],activeId:null,items:new Map,ws:null,pollTimer:0,renderQueued:!1};function vt(){try{return localStorage.getItem("tmux-web-token")||""}catch{return""}}async function T(e,t){let n=await fetch(e,{...t,headers:{"content-type":"application/json",Authorization:`Bearer ${vt()}`,...t?.headers||{}}}),i=await n.text(),a=i?JSON.parse(i):null;if(!n.ok)throw new Error(a&&a.error||`HTTP ${n.status}`);return a}function c(e,t,n){let i=document.createElement(e);return t&&(i.className=t),n!==void 0&&(i.textContent=n),i}function oi(e){return e==="running"?"var(--panel-success)":e==="waiting_approval"||e==="waiting_input"?"#e0a23c":e==="failed"?"var(--panel-danger, #e5534b)":e==="completed"?"var(--panel-accent)":"var(--panel-muted)"}function We(){let e=m.approvals.length,t=document.getElementById("bots-inbox-badge");t&&(t.style.display=e?"inline-block":"none",t.textContent=String(e));let n=document.getElementById("bv-inbox-count");n&&(n.textContent=e?`(${e})`:""),window.__botsSnapshot=m.bots,window.__refreshSidebar?.()}function li(){let e=document.getElementById("set-bot-templates"),t=document.getElementById("set-bot-new"),n=document.getElementById("set-bot-inbox"),i=()=>{document.getElementById("settings-popover")?.classList.remove("open"),document.getElementById("settings-backdrop")?.classList.remove("open")};e?.addEventListener("click",()=>{i(),Le()}),t?.addEventListener("click",()=>{i(),bi()}),n?.addEventListener("click",()=>{i(),Ct()})}function ri(){let e=c("div","bots-view");e.id="bots-view",e.hidden=!0;let t=c("div","bots-view-head"),n=c("div","bv-title"),i=c("span","bots-dot");i.id="bv-dot";let a=c("span","bv-title-text");a.id="bv-title";let r=c("span","bv-status");r.id="bv-status",n.append(i,a,r);let s=c("div","bv-actions"),l=c("div","bv-mode"),p=c("button","bv-mode-btn");p.id="bv-mode-btn",p.type="button",p.title="\u5BA1\u6279\u6A21\u5F0F\uFF08\u70B9\u5F00\u770B\u8BF4\u660E\uFF09";let u=c("div","bv-mode-menu");u.id="bv-mode-menu",u.hidden=!0;for(let[y,S,G]of[["supervised","\u9ED8\u8BA4","\u53EA\u8BFB\u5DE5\u5177\uFF08read/grep/find/ls\uFF09\u76F4\u63A5\u653E\u884C\uFF1Bbash\u3001edit\u3001write\u3001\u6269\u5C55/MCP \u5DE5\u5177\u4F1A\u95EE\u4F60"],["parent-supervised","\u76D1\u7BA1","\u5176\u4F59\u5DE5\u5177\u4EA4\u7ED9\u4E0A\u7EA7 bot \u51B3\u5B9A\uFF08\u5E26\u7406\u7531\uFF09\uFF1B\u4F60\u4ECD\u7136\u80FD\u770B\u5230\u5E76\u56DE\u7B54\uFF0C\u5148\u7B54\u5148\u5F97\uFF1B\u6CA1\u6709\u4E0A\u7EA7\u65F6\u56DE\u843D\u5230\u9ED8\u8BA4"],["full-access","\u5168\u653E\u884C","\u6240\u6709\u5DE5\u5177\u76F4\u63A5\u6267\u884C\uFF0C\u4E0D\u518D\u8BE2\u95EE\u3002\u6CE8\u610F\u8FD9\u4E0D\u662F\u6C99\u7BB1"]]){let h=c("button");h.dataset.mode=y,h.innerHTML=`<b>${S}</b><span>${G}</span>`,h.onclick=()=>{u.hidden=!0,di(y)},u.appendChild(h)}p.onclick=y=>{y.stopPropagation(),u.hidden=!u.hidden},l.append(p,u),document.addEventListener("click",y=>{l.contains(y.target)||(u.hidden=!0)});let v=c("button","btn","Allow all");v.id="bv-allow-all",v.title="Approve every pending request for this bot",v.onclick=()=>{if(!m.activeId)return;let y=m.approvals.filter(S=>S.botId===m.activeId);Promise.all(y.map(S=>T(`/api/bots/${S.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:S.id,allow:!0})}))).finally(()=>void Y(!0))};let b=c("button","btn","Needs you "),D=c("span");D.id="bv-inbox-count",b.appendChild(D),b.onclick=()=>void Ct();let x=c("button","btn","Resume");x.onclick=()=>void Yt(y=>T(`/api/bots/${y}/resume`,{method:"POST"}).then(()=>Y(!0)));let w=c("button","btn danger","Stop");w.onclick=()=>void Yt(y=>T(`/api/bots/${y}/stop`,{method:"POST"}).then(()=>Y(!0)));let g=c("button","btn","Delete");g.onclick=()=>{m.activeId&&confirm("Delete this bot and its session?")&&T(`/api/bots/${m.activeId}`,{method:"DELETE"}).then(()=>{gt(),Y(!0)})};let A=c("button","btn","\u2715");A.onclick=()=>gt(),s.append(l,v,b,x,w,g,A),t.append(n,s);let W=c("div","bots-messages");W.id="bots-messages";let O=c("div","bots-composer"),_=c("textarea");_.id="bots-input",_.rows=1,_.placeholder="Message the bot\u2026 (Enter to send, Shift+Enter for newline)",_.onkeydown=y=>{y.key==="Enter"&&!y.shiftKey&&(y.preventDefault(),qt())};let Z=c("button","btn primary","Send");Z.onclick=()=>void qt(),O.append(_,Z),e.append(t,W,O),document.querySelector(".main-area")?.appendChild(e),document.getElementById("bots-modal")||vi()}async function qt(){let e=document.getElementById("bots-input");if(!e||!m.activeId||!e.value.trim())return;let t=e.value;e.value="";try{await T(`/api/bots/${m.activeId}/input`,{method:"POST",body:JSON.stringify({text:t})})}catch(n){ce({kind:"notice",level:"error",text:n instanceof Error?n.message:String(n)})}}function Yt(e){m.activeId&&e(m.activeId).catch(t=>ce({kind:"notice",level:"error",text:t instanceof Error?t.message:String(t)}))}function gt(){m.activeId=null;let e=document.getElementById("bots-view");e&&(e.hidden=!0);try{m.ws?.close()}catch{}m.ws=null,We();let t=document.getElementById("terminal-container"),n=document.getElementById("main-placeholder"),i=!!document.querySelector(".session-item.active:not(.bot-item)");t&&i?(t.style.display="",n&&(n.style.display="none")):n&&(n.style.display="")}async function Vt(e){m.activeId=e,m.items.set(e,[]);let t=document.getElementById("bots-view");t&&(t.hidden=!1);let n=document.getElementById("main-placeholder");n&&(n.style.display="none");let i=document.getElementById("terminal-container");i&&(i.style.display="none");let a=document.getElementById("file-editor");a&&(a.style.display="none"),We(),wt();try{m.ws?.close()}catch{}let r=location.protocol==="https:"?"wss:":"ws:",s=new WebSocket(`${r}//${location.host}/ws/bots/${encodeURIComponent(e)}?token=${encodeURIComponent(vt())}`);m.ws=s,s.onmessage=l=>{try{Xt(JSON.parse(String(l.data)))}catch{}},s.onclose=()=>{m.activeId===e&&setTimeout(()=>{m.activeId===e&&Y(!0)},1500)},await Y(!0)}function bt(){return m.bots.find(e=>e.id===m.activeId)||null}function yt(){let e=bt();if(!e)return;let t=document.getElementById("bv-title"),n=document.getElementById("bv-status"),i=document.getElementById("bv-dot");t&&(t.textContent=e.title),n&&(n.textContent=`${e.status.replace(/_/g," ")} \xB7 ${e.templateId} \xB7 ${e.projectPath}`);let a=document.getElementById("bv-mode-btn");a&&e.runtimeMode&&(a.textContent=`${Kt[e.runtimeMode]||e.runtimeMode} \u25BE`);for(let l of document.querySelectorAll("#bv-mode-menu button"))l.classList.toggle("active",l.dataset.mode===e.runtimeMode);let r=document.getElementById("bv-allow-all"),s=m.approvals.filter(l=>l.botId===e.id).length;r&&(r.hidden=s===0,r.textContent=`Allow all (${s})`),i&&(i.style.background=oi(e.status))}var Kt={supervised:"\u9ED8\u8BA4","parent-supervised":"\u76D1\u7BA1","full-access":"\u5168\u653E\u884C"};async function di(e){if(m.activeId)try{await T(`/api/bots/${m.activeId}/mode`,{method:"POST",body:JSON.stringify({mode:e})});let t=bt();t&&(t.runtimeMode=e),yt(),ce({kind:"notice",level:"info",text:`\u5BA1\u6279\u6A21\u5F0F\uFF1A${Kt[e]||e}`})}catch(t){ce({kind:"notice",level:"error",text:t instanceof Error?t.message:String(t)})}}function ce(e,t=m.activeId){if(!t)return;let n=m.items.get(t)||[];n.push(e),m.items.set(t,n),t===m.activeId&&ue()}function ue(){m.renderQueued||(m.renderQueued=!0,requestAnimationFrame(()=>{m.renderQueued=!1,wt()}))}function wt(){let e=document.getElementById("bots-messages");if(!e||!m.activeId)return;let t=m.items.get(m.activeId)||[];e.textContent="";let n=null;for(let i of t)if(i.kind==="user"){let a=c("div","bv-msg bv-user");a.textContent=i.text,e.appendChild(a),n=null}else if(i.kind==="assistant"){let a=c("div","bv-msg bv-assistant");if(i.thinking){let s=c("details","bv-thinking");s.appendChild(c("summary",void 0,"thinking")),s.appendChild(c("div",void 0,i.thinking)),a.appendChild(s)}let r=c("div","bv-text");r.textContent=i.text,a.appendChild(r),e.appendChild(a),n=r}else if(i.kind==="tool")e.appendChild(ci(i)),n=null;else if(i.kind==="approval")e.appendChild(ui(i)),n=null;else if(i.kind==="notice"){let a=c("div",`bv-notice bv-notice-${i.level}`,i.text);e.appendChild(a)}n&&(n.scrollTop=n.scrollHeight),e.scrollTop=e.scrollHeight}function ci(e){let t=c("details","bv-tool");t.open=e.phase!=="end"||!!e.isError;let n=c("summary"),i=c("span","bv-tool-name",e.name);if(n.appendChild(i),e.phase!=="end"&&n.appendChild(c("span","bv-tool-phase",e.phase)),e.isError&&n.appendChild(c("span","bv-tool-error","error")),typeof e.durationMs=="number"&&n.appendChild(c("span","bv-tool-meta",`${Math.round(e.durationMs)}ms`)),t.appendChild(n),e.args!==void 0){let a=c("pre","bv-pre");a.textContent=typeof e.args=="string"?e.args:JSON.stringify(e.args,null,2),t.appendChild(a)}if(e.output){let a=c("pre","bv-pre bv-output");a.textContent=e.output,t.appendChild(a)}return t}function ui(e){let t=c("div","bv-approval"),n=e.approval;if(t.appendChild(c("div","bv-approval-title",n.title)),n.message&&t.appendChild(c("pre","bv-pre",n.message)),e.decided)return t.appendChild(c("div","bv-approval-decided",e.decided==="allowed"?"Allowed":"Denied")),t;let i=c("input","bv-reason");i.placeholder="reason (optional)";let a=c("div","bv-approval-actions"),r=c("button","btn primary","Allow"),s=c("button","btn",n.method==="confirm"&&/^Allow (.+?)\?$/.test(n.title)?`Always allow ${/^Allow (.+?)\?$/.exec(n.title)?.[1]}`:"Always allow");s.hidden=n.method!=="confirm";let l=c("button","btn danger","Deny"),p=async(u,v=!1)=>{try{await T(`/api/bots/${n.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:n.id,allow:u,always:v,reason:i.value||void 0})}),e.decided=u?"allowed":"denied",ue(),Y(!0)}catch(b){ce({kind:"notice",level:"error",text:b instanceof Error?b.message:String(b)})}};return r.onclick=()=>void p(!0),s.onclick=()=>void p(!0,!0),l.onclick=()=>void p(!1),a.append(i,r,s,l),t.appendChild(a),t}function Xt(e){let t=String(e.type||""),n=m.activeId;if(!n)return;let i=m.items.get(n)||[];if(t==="snapshot")m.items.set(n,[]);else if(t==="user")ce({kind:"user",text:String(e.text||"")});else if(t==="status"){let a=bt();a&&(a.status=String(e.status||a.status)),yt(),fi()}else if(t==="message"){let a=e.message;if(!a||String(a.role||"")!=="assistant")return;let r=pi(a),s=mi(a),l=i[i.length-1];l&&l.kind==="assistant"?(l.text=r||l.text,l.thinking=s||l.thinking):i.push({kind:"assistant",text:r,thinking:s}),m.items.set(n,i),ue()}else if(t==="delta"){let a=String(e.kind||""),r=String(e.delta||""),s=i[i.length-1];(!s||s.kind!=="assistant")&&(i.push({kind:"assistant",text:"",thinking:""}),s=i[i.length-1]),s.kind==="assistant"&&(a==="text"?s.text+=r:a==="thinking"&&(s.thinking+=r)),m.items.set(n,i),ue()}else if(t==="tool"){let a=String(e.callId||""),r=i.find(l=>l.kind==="tool"&&l.callId===a),s=String(e.phase||"start");r?(r.phase=s,s==="update"&&e.output&&(r.output=String(e.output)),s==="end"&&(e.output&&(r.output=String(e.output)),r.isError=e.isError===!0,typeof e.durationMs=="number"&&(r.durationMs=e.durationMs))):i.push({kind:"tool",callId:a,name:String(e.name||"tool"),args:e.args,output:e.output?String(e.output):void 0,isError:e.isError===!0,durationMs:typeof e.durationMs=="number"?e.durationMs:void 0,phase:s}),m.items.set(n,i),ue()}else if(t==="approval"){let a=e.approval;if(!a)return;let r=i;for(let s=r.length-1;s>=0;s--){let l=r[s];if(l.kind==="approval"&&l.approval.id===a.id){l.approval=a,a.state!=="pending"&&(l.decided=a.state==="allowed"?"allowed":"denied"),m.items.set(n,r),ue();return}}r.push({kind:"approval",approval:a}),m.items.set(n,r),ue()}else t==="notice"&&ce({kind:"notice",level:String(e.level||"info"),text:String(e.text||"")})}function pi(e){let t=e.content;return Array.isArray(t)?t.map(n=>n&&typeof n=="object"&&n.type==="text"?String(n.text||""):"").join(""):String(e.text||"")}function mi(e){let t=e.content;return Array.isArray(t)?t.map(n=>n&&typeof n=="object"&&n.type==="thinking"?String(n.thinking||""):"").join(""):""}async function Y(e=!1){try{let[t,n]=await Promise.all([T("/api/bots"),T("/api/bots/approvals")]);if(m.bots=t,m.approvals=n,We(),yt(),e&&m.activeId){let i=await T(`/api/bots/${m.activeId}/events?limit=300`);hi(i)}}catch{}}async function fi(){try{m.bots=await T("/api/bots"),We()}catch{}}function hi(e){if(m.activeId){m.items.set(m.activeId,[]);for(let t of e)Xt(t);wt()}}function vi(){let e=c("div","bots-modal");e.id="bots-modal",e.hidden=!0;let t=c("div","bots-modal-card"),n=c("div","bots-modal-head"),i=c("span");i.id="bots-modal-title";let a=c("button","btn","\u2715");a.onclick=()=>Je(),n.append(i,a);let r=c("div","bots-modal-body");r.id="bots-modal-body",t.append(n,r),e.appendChild(t),e.onclick=s=>{s.target===e&&Je()},document.body.appendChild(e)}function Et(e){let t=document.getElementById("bots-modal"),n=document.getElementById("bots-modal-title"),i=document.getElementById("bots-modal-body");if(!t||!i)throw new Error("modal missing");return n&&(n.textContent=e),i.textContent="",t.hidden=!1,i}function Je(){let e=document.getElementById("bots-modal");e&&(e.hidden=!0)}async function gi(){return m.catalog||(m.catalog=await T("/api/bots/catalog")),m.catalog}async function Qt(){return m.templates=await T("/api/bots/templates"),m.templates}async function Le(){let e=Et("Bot templates"),[t,n]=await Promise.all([gi(),Qt()]),i=c("div","bv-template-list");for(let p of n){let u=c("div","bv-template-row");u.appendChild(c("span","bv-template-name",p.manifest.name)),u.appendChild(c("span","bv-template-desc",p.manifest.description||""));let v=c("button","btn","Edit");v.onclick=()=>Zt(e,t,p);let b=c("button","btn","Copy");b.title="Duplicate this template",b.onclick=()=>{let w=JSON.parse(JSON.stringify(p.manifest));w.name=`${p.manifest.name} copy`,T("/api/bots/templates",{method:"POST",body:JSON.stringify({manifest:w})}).then(()=>Le()).catch(g=>alert(g instanceof Error?g.message:String(g)))};let D=c("button","btn danger","Delete");D.onclick=()=>{confirm(`Delete template ${p.manifest.name}?`)&&T(`/api/bots/templates/${p.id}`,{method:"DELETE"}).then(()=>Le())};let x=c("span","bv-template-actions");x.append(v,b,D),u.appendChild(x),i.appendChild(u)}n.length===0&&i.appendChild(c("div","bots-empty","No templates yet")),e.appendChild(i);let a=c("div","bv-template-actions"),r=c("button","btn primary","New template");r.onclick=()=>Zt(e,t,null);let s=c("button","btn","Export");s.title="Download templates + library as JSON",s.onclick=()=>{(async()=>{try{let p=await fetch("/api/bots/export",{headers:{Authorization:`Bearer ${vt()}`}});if(!p.ok)throw new Error(`HTTP ${p.status}`);let u=await p.blob(),v=document.createElement("a");v.href=URL.createObjectURL(u),v.download=`tmux-weblink-bots-${new Date().toISOString().slice(0,10)}.json`,v.click(),setTimeout(()=>URL.revokeObjectURL(v.href),2e3)}catch(p){alert(p instanceof Error?p.message:String(p))}})()};let l=c("button","btn","Import");l.title="Restore templates from a JSON bundle",l.onclick=()=>{let p=document.createElement("input");p.type="file",p.accept="application/json,.json",p.onchange=()=>{let u=p.files?.[0];u&&(async()=>{try{let v=JSON.parse(await u.text()),b=await T("/api/bots/import",{method:"POST",body:JSON.stringify(v)});alert(`Imported ${b.templates} templates, ${b.files} library files (${b.skipped} kept)`),await Le()}catch(v){alert(v instanceof Error?v.message:String(v))}})()},p.click()},a.append(r,s,l),e.appendChild(a)}function kt(e,t,n){let i=c("div","bv-field");i.appendChild(c("label","bv-label",e));let a=c("div","bv-check-grid"),r=[];for(let s of t){let l=c("label","bv-check"),p=document.createElement("input");p.type="checkbox",p.checked=n.includes(s.id),l.append(p,c("span",void 0,s.label)),s.hint&&(l.title=s.hint),a.appendChild(l),r.push({id:s.id,input:p})}return i.appendChild(a),{element:i,get:()=>r.filter(s=>s.input.checked).map(s=>s.id)}}function Zt(e,t,n){e.textContent="";let i=n?JSON.parse(JSON.stringify(n.manifest)):{name:"new-bot",description:""},a=c("input","bv-input");a.value=i.name,a.placeholder="Template name";let r=c("input","bv-input");r.value=i.description||"",r.placeholder="One line description";let s=c("textarea","bv-textarea");s.rows=6,s.value=i.system||"",s.placeholder="System prompt for this bot (written to SYSTEM.md)";let l=kt("Skills",t.skills.map(h=>({id:h.id,label:h.name,hint:h.description})),i.skills||[]),p=kt("Extensions (Pi builtins + library)",t.extensions.map(h=>({id:h.id,label:`${h.name}${h.kind==="builtin"?" (builtin)":""}`,hint:h.description})),(i.extensions||[]).map(h=>h.replace(/^.*\//,"").replace(/\.(js|ts)$/,""))),u=kt("Prompt templates",t.prompts.map(h=>({id:h.id,label:h.name})),i.prompts||[]),v=c("select","bv-input");v.appendChild(new Option("none",""));for(let h of t.mcp)v.appendChild(new Option(h.name,h.id));i.mcp&&(v.value=t.mcp.find(h=>JSON.stringify(h.servers)===JSON.stringify(i.mcp?.mcpServers))?.id||"");let b=c("div","bv-field");b.appendChild(c("label","bv-label","Tools (allow list; deny always blocks)"));let D=c("div","bv-check-grid"),x=[];for(let h of t.tools){let z=c("label","bv-check"),B=document.createElement("input");B.type="checkbox",B.checked=(i.tools?.allow||[]).includes(h.name)||!i.tools?.allow?.length&&["read","grep","find","ls","edit","write","bash"].includes(h.name),z.append(B,c("span",void 0,h.name)),D.appendChild(z),x.push({name:h.name,input:B})}b.appendChild(D);let w=c("input","bv-input");w.value=(i.tools?.deny||[]).join(", "),w.placeholder="Always deny (comma separated), e.g. bash, write";let g=c("textarea","bv-textarea");g.rows=2,g.value=(i.packages||[]).join(`
|
|
8
|
+
`).join("\r")}async function zn(s){let d=jn(s.clipboardData);if(d){s.preventDefault(),s.stopPropagation();let I=Date.now();if(I-qe<50)return;qe=I,await mt(d);return}let f=s.clipboardData?.getData("text/plain");if(!f)return;s.preventDefault(),s.stopPropagation();let E=Date.now();E-qe<50||(qe=E,i.pasteText(_t(f)))}let Le=0;function Un(s){s.preventDefault(),Le++,jt(s.dataTransfer)&&e.classList.add("terminal-drag-over")}function qn(s){s.preventDefault(),s.dataTransfer&&(s.dataTransfer.dropEffect="copy")}function Jn(s){s.preventDefault(),Le--,Le<=0&&(Le=0,e.classList.remove("terminal-drag-over"))}async function Wn(s){s.preventDefault(),Le=0,e.classList.remove("terminal-drag-over");let d=jt(s.dataTransfer);d&&await mt(d)}function zt(s){!Fn||s.key!=="Escape"||Ee||s.defaultPrevented||s.repeat||s.metaKey||s.ctrlKey||s.altKey||i.isFocused()&&(s.preventDefault(),s.stopPropagation(),he("\x1B"))}e.addEventListener("paste",zn),e.addEventListener("dragenter",Un),e.addEventListener("dragover",qn),e.addEventListener("dragleave",Jn),e.addEventListener("drop",Wn),document.addEventListener("keydown",zt,!0);function Yn(s){if(s.touches.length!==1){l=null;return}let d=s.touches[0];if(!d)return;O();let f=e.getBoundingClientRect(),E=d.clientX-f.left<f.width*.4?"tui":"history",I=d.clientY-f.top<f.height*.5;l={startX:d.clientX,startY:d.clientY,lastX:d.clientX,lastY:d.clientY,lastT:performance.now(),velocity:0,scrolling:!1,zone:E,tuiUp:I,sent:!1},s.stopPropagation()}function Vn(s){if(!l||s.touches.length!==1)return;let d=s.touches[0];if(!d)return;let f=d.clientY-l.startY,E=d.clientX-l.startX;if(!l.scrolling){if(Math.abs(f)<8||Math.abs(f)<Math.abs(E))return;l.scrolling=!0,z=Date.now()+500}s.preventDefault(),s.stopPropagation();let I=performance.now(),ee=d.clientY-l.lastY;if(l.zone==="tui"){l.sent||(l.sent=!0,he(l.tuiUp?"\x1B[5~":"\x1B[6~"),A(l.tuiUp)),l.lastX=d.clientX,l.lastY=d.clientY,l.lastT=I;return}let se=I-l.lastT;se>0&&(l.velocity=ee/se),Zn(-ee),l.lastX=d.clientX,l.lastY=d.clientY,l.lastT=I}function Kn(s){if(!l)return;let d=l.scrolling,f=l.zone,E=l.tuiUp,I=l.velocity;if(l=null,s.stopPropagation(),f==="tui"){d||(he(E?"\x1B[5~":"\x1B[6~"),A(E),z=Date.now()+500,s.preventDefault());return}if(!d){i.focus();return}z=Date.now()+500,s.preventDefault(),I&&_(I)}function Xn(s){l=null,O(),s.stopPropagation()}function Qn(s){s.pointerType==="touch"&&Date.now()<z&&(s.preventDefault(),s.stopPropagation())}function Zn(s){let d=i.cellHeight(),f=d>0?Math.round(s/d):s>0?1:-1;f===0&&(f=s>0?1:-1),i.scrollLines(f)}e.addEventListener("touchstart",Yn,{passive:!0,capture:!0}),e.addEventListener("touchmove",Vn,{passive:!1,capture:!0}),e.addEventListener("touchend",Kn,{passive:!1,capture:!0}),e.addEventListener("touchcancel",Xn,{passive:!0,capture:!0}),e.addEventListener("pointerup",Qn,!0);function Ut(){q()}window.addEventListener("resize",Ut),window.visualViewport?.addEventListener("resize",q),window.visualViewport?.addEventListener("scroll",q);let qt=new ResizeObserver(()=>q());qt.observe(e),document.fonts?.ready.then(()=>{q(),setTimeout(q,50),setTimeout(q,200)}),e.addEventListener("focusin",On,!0);async function Gn(){if(document.fonts?.ready)try{await Promise.race([document.fonts.ready,new Promise(s=>setTimeout(s,1e3))])}catch{}}return requestAnimationFrame(()=>{de()&&_e(),(async()=>(await Gn(),de()&&re({type:"resize",cols:i.cols,rows:i.rows}),Nt(),q()))()}),{destroy(){if(B=!0,O(),ve(!1),xe&&clearTimeout(xe),document.removeEventListener("mousemove",ft,!0),document.removeEventListener("mouseup",ht,!0),a){try{a.close(1e3,"session switch")}catch{}a=void 0}e.innerHTML="",e.classList.remove("terminal-pending"),window.removeEventListener("resize",Ut),qt.disconnect(),document.removeEventListener("keydown",zt,!0)},focus(){i.focus()},sendInput(s){he(s)},toggleCopyMode(){Rt()}}})()}var m={catalog:null,templates:[],bots:[],approvals:[],activeId:null,items:new Map,ws:null,pollTimer:0,renderQueued:!1};function gt(){try{return localStorage.getItem("tmux-web-token")||""}catch{return""}}async function T(e,t){let n=await fetch(e,{...t,headers:{"content-type":"application/json",Authorization:`Bearer ${gt()}`,...t?.headers||{}}}),i=await n.text(),a=i?JSON.parse(i):null;if(!n.ok)throw new Error(a&&a.error||`HTTP ${n.status}`);return a}function c(e,t,n){let i=document.createElement(e);return t&&(i.className=t),n!==void 0&&(i.textContent=n),i}function li(e){return e==="running"?"var(--panel-success)":e==="waiting_approval"||e==="waiting_input"?"#e0a23c":e==="failed"?"var(--panel-danger, #e5534b)":e==="completed"?"var(--panel-accent)":"var(--panel-muted)"}function ge(){let e=document.getElementById("bots-view");if(!e)return;let t=window.visualViewport,n=window.matchMedia("(max-width: 640px)").matches,i=!document.querySelector(".sidebar")?.classList.contains("collapsed");if(m.activeId&&t&&n&&!i){let a=document.querySelector(".fixed-header"),r=a?Math.round(a.getBoundingClientRect().height):0;e.style.position="fixed",e.style.top=`${Math.round(t.offsetTop)+r}px`,e.style.left=`${Math.round(t.offsetLeft)}px`,e.style.width=`${Math.round(t.width)}px`,e.style.height=`${Math.max(120,Math.round(t.height)-r)}px`,e.style.right="auto",e.style.bottom="auto"}else e.style.position="",e.style.top="",e.style.left="",e.style.width="",e.style.height="",e.style.right="",e.style.bottom=""}window.visualViewport?.addEventListener("resize",ge),window.visualViewport?.addEventListener("scroll",ge),window.addEventListener("resize",ge),document.addEventListener("click",()=>setTimeout(ge,0));function We(){let e=m.approvals.length,t=document.getElementById("bots-inbox-badge");t&&(t.style.display=e?"inline-block":"none",t.textContent=String(e));let n=document.getElementById("bv-inbox-count");n&&(n.textContent=e?`(${e})`:""),window.__botsSnapshot=m.bots,window.__refreshSidebar?.()}function ri(){let e=document.getElementById("set-bot-templates"),t=document.getElementById("set-bot-new"),n=document.getElementById("set-bot-inbox"),i=()=>{document.getElementById("settings-popover")?.classList.remove("open"),document.getElementById("settings-backdrop")?.classList.remove("open")};e?.addEventListener("click",()=>{i(),Ie()}),t?.addEventListener("click",()=>{i(),bi()}),n?.addEventListener("click",()=>{i(),xt()})}function di(){let e=c("div","bots-view");e.id="bots-view",e.hidden=!0;let t=c("div","bots-view-head"),n=c("div","bv-title"),i=c("span","bots-dot");i.id="bv-dot";let a=c("span","bv-title-text");a.id="bv-title";let r=c("span","bv-status");r.id="bv-status",n.append(i,a,r);let o=c("div","bv-actions"),l=c("div","bv-mode"),p=c("button","bv-mode-btn");p.id="bv-mode-btn",p.type="button",p.title="\u5BA1\u6279\u6A21\u5F0F\uFF08\u70B9\u5F00\u770B\u8BF4\u660E\uFF09";let u=c("div","bv-mode-menu");u.id="bv-mode-menu",u.hidden=!0;for(let[b,L,G]of[["supervised","\u9ED8\u8BA4","\u53EA\u8BFB\u5DE5\u5177\uFF08read/grep/find/ls\uFF09\u76F4\u63A5\u653E\u884C\uFF1Bbash\u3001edit\u3001write\u3001\u6269\u5C55/MCP \u5DE5\u5177\u4F1A\u95EE\u4F60"],["parent-supervised","\u76D1\u7BA1","\u5176\u4F59\u5DE5\u5177\u4EA4\u7ED9\u4E0A\u7EA7 bot \u51B3\u5B9A\uFF08\u5E26\u7406\u7531\uFF09\uFF1B\u4F60\u4ECD\u7136\u80FD\u770B\u5230\u5E76\u56DE\u7B54\uFF0C\u5148\u7B54\u5148\u5F97\uFF1B\u6CA1\u6709\u4E0A\u7EA7\u65F6\u56DE\u843D\u5230\u9ED8\u8BA4"],["full-access","\u5168\u653E\u884C","\u6240\u6709\u5DE5\u5177\u76F4\u63A5\u6267\u884C\uFF0C\u4E0D\u518D\u8BE2\u95EE\u3002\u6CE8\u610F\u8FD9\u4E0D\u662F\u6C99\u7BB1"]]){let h=c("button");h.dataset.mode=b,h.innerHTML=`<b>${L}</b><span>${G}</span>`,h.onclick=()=>{u.hidden=!0,ci(b)},u.appendChild(h)}p.onclick=b=>{b.stopPropagation(),u.hidden=!u.hidden},l.append(p,u),document.addEventListener("click",b=>{l.contains(b.target)||(u.hidden=!0)});let v=c("button","btn","Allow all");v.id="bv-allow-all",v.title="Approve every pending request for this bot",v.onclick=()=>{if(!m.activeId)return;let b=m.approvals.filter(L=>L.botId===m.activeId);Promise.all(b.map(L=>T(`/api/bots/${L.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:L.id,allow:!0})}))).finally(()=>void V(!0))};let y=c("button","btn","Needs you "),D=c("span");D.id="bv-inbox-count",y.appendChild(D),y.onclick=()=>void xt();let x=c("button","btn","Resume");x.onclick=()=>void Vt(b=>T(`/api/bots/${b}/resume`,{method:"POST"}).then(()=>V(!0)));let w=c("button","btn danger","Stop");w.onclick=()=>void Vt(b=>T(`/api/bots/${b}/stop`,{method:"POST"}).then(()=>V(!0)));let g=c("button","btn","Delete");g.onclick=()=>{m.activeId&&confirm("Delete this bot and its session?")&&T(`/api/bots/${m.activeId}`,{method:"DELETE"}).then(()=>{yt(),V(!0)})};let A=c("button","btn","\u2715");A.onclick=()=>yt(),o.append(l,v,y,x,w,g,A),t.append(n,o);let J=c("div","bots-messages");J.id="bots-messages";let O=c("div","bots-composer"),_=c("textarea");_.id="bots-input",_.rows=1,_.placeholder="Message the bot\u2026 (Enter to send, Shift+Enter for newline)",_.onkeydown=b=>{b.key==="Enter"&&!b.shiftKey&&(b.preventDefault(),Yt())};let z=c("button","btn primary");z.title="Send",z.setAttribute("aria-label","Send"),z.innerHTML='<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19V5M5 12l7-7 7 7"/></svg>',z.onclick=()=>void Yt(),O.append(_,z),e.append(t,J,O),document.querySelector(".main-area")?.appendChild(e),document.getElementById("bots-modal")||gi()}async function Yt(){let e=document.getElementById("bots-input");if(!e||!m.activeId||!e.value.trim())return;let t=e.value;e.value="";try{await T(`/api/bots/${m.activeId}/input`,{method:"POST",body:JSON.stringify({text:t})})}catch(n){ce({kind:"notice",level:"error",text:n instanceof Error?n.message:String(n)})}}function Vt(e){m.activeId&&e(m.activeId).catch(t=>ce({kind:"notice",level:"error",text:t instanceof Error?t.message:String(t)}))}function yt(){m.activeId=null,ge();let e=document.getElementById("bots-view");e&&(e.hidden=!0);try{m.ws?.close()}catch{}m.ws=null,We();let t=document.getElementById("terminal-container"),n=document.getElementById("main-placeholder"),i=!!document.querySelector(".session-item.active:not(.bot-item)");t&&i?(t.style.display="",n&&(n.style.display="none")):n&&(n.style.display="")}async function Kt(e){m.activeId=e,window.__collapseSidebar?.(),ge(),m.items.set(e,[]);let t=document.getElementById("bots-view");t&&(t.hidden=!1);let n=document.getElementById("main-placeholder");n&&(n.style.display="none");let i=document.getElementById("terminal-container");i&&(i.style.display="none");let a=document.getElementById("file-editor");a&&(a.style.display="none"),We(),Et();try{m.ws?.close()}catch{}let r=location.protocol==="https:"?"wss:":"ws:",o=new WebSocket(`${r}//${location.host}/ws/bots/${encodeURIComponent(e)}?token=${encodeURIComponent(gt())}`);m.ws=o,o.onmessage=l=>{try{Qt(JSON.parse(String(l.data)))}catch{}},o.onclose=()=>{m.activeId===e&&setTimeout(()=>{m.activeId===e&&V(!0)},1500)},await V(!0)}function bt(){return m.bots.find(e=>e.id===m.activeId)||null}function wt(){let e=bt();if(!e)return;let t=document.getElementById("bv-title"),n=document.getElementById("bv-status"),i=document.getElementById("bv-dot");t&&(t.textContent=e.title),n&&(n.textContent=`${e.status.replace(/_/g," ")} \xB7 ${e.templateId} \xB7 ${e.projectPath}`);let a=document.getElementById("bv-mode-btn");a&&e.runtimeMode&&(a.textContent=`${Xt[e.runtimeMode]||e.runtimeMode} \u25BE`);for(let l of document.querySelectorAll("#bv-mode-menu button"))l.classList.toggle("active",l.dataset.mode===e.runtimeMode);let r=document.getElementById("bv-allow-all"),o=m.approvals.filter(l=>l.botId===e.id).length;r&&(r.hidden=o===0,r.textContent=`Allow all (${o})`),i&&(i.style.background=li(e.status))}var Xt={supervised:"\u9ED8\u8BA4","parent-supervised":"\u76D1\u7BA1","full-access":"\u5168\u653E\u884C"};async function ci(e){if(m.activeId)try{await T(`/api/bots/${m.activeId}/mode`,{method:"POST",body:JSON.stringify({mode:e})});let t=bt();t&&(t.runtimeMode=e),wt(),ce({kind:"notice",level:"info",text:`\u5BA1\u6279\u6A21\u5F0F\uFF1A${Xt[e]||e}`})}catch(t){ce({kind:"notice",level:"error",text:t instanceof Error?t.message:String(t)})}}function ce(e,t=m.activeId){if(!t)return;let n=m.items.get(t)||[];n.push(e),m.items.set(t,n),t===m.activeId&&ue()}function ue(){m.renderQueued||(m.renderQueued=!0,requestAnimationFrame(()=>{m.renderQueued=!1,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=c("div","bv-msg bv-user");a.textContent=i.text,e.appendChild(a),n=null}else if(i.kind==="assistant"){let a=c("div","bv-msg bv-assistant");if(i.thinking){let o=c("details","bv-thinking");o.appendChild(c("summary",void 0,"thinking")),o.appendChild(c("div",void 0,i.thinking)),a.appendChild(o)}let r=c("div","bv-text");r.textContent=i.text,a.appendChild(r),e.appendChild(a),n=r}else if(i.kind==="tool")e.appendChild(ui(i)),n=null;else if(i.kind==="approval")e.appendChild(pi(i)),n=null;else if(i.kind==="notice"){let a=c("div",`bv-notice bv-notice-${i.level}`,i.text);e.appendChild(a)}n&&(n.scrollTop=n.scrollHeight),e.scrollTop=e.scrollHeight}function ui(e){let t=c("details","bv-tool");t.open=e.phase!=="end"||!!e.isError;let n=c("summary"),i=c("span","bv-tool-name",e.name);if(n.appendChild(i),e.phase!=="end"&&n.appendChild(c("span","bv-tool-phase",e.phase)),e.isError&&n.appendChild(c("span","bv-tool-error","error")),typeof e.durationMs=="number"&&n.appendChild(c("span","bv-tool-meta",`${Math.round(e.durationMs)}ms`)),t.appendChild(n),e.args!==void 0){let a=c("pre","bv-pre");a.textContent=typeof e.args=="string"?e.args:JSON.stringify(e.args,null,2),t.appendChild(a)}if(e.output){let a=c("pre","bv-pre bv-output");a.textContent=e.output,t.appendChild(a)}return t}function pi(e){let t=c("div","bv-approval"),n=e.approval;if(t.appendChild(c("div","bv-approval-title",n.title)),n.message&&t.appendChild(c("pre","bv-pre",n.message)),e.decided)return t.appendChild(c("div","bv-approval-decided",e.decided==="allowed"?"Allowed":"Denied")),t;let i=c("input","bv-reason");i.placeholder="reason (optional)";let a=c("div","bv-approval-actions"),r=c("button","btn primary","Allow"),o=c("button","btn",n.method==="confirm"&&/^Allow (.+?)\?$/.test(n.title)?`Always allow ${/^Allow (.+?)\?$/.exec(n.title)?.[1]}`:"Always allow");o.hidden=n.method!=="confirm";let l=c("button","btn danger","Deny"),p=async(u,v=!1)=>{try{await T(`/api/bots/${n.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:n.id,allow:u,always:v,reason:i.value||void 0})}),e.decided=u?"allowed":"denied",ue(),V(!0)}catch(y){ce({kind:"notice",level:"error",text:y instanceof Error?y.message:String(y)})}};return r.onclick=()=>void p(!0),o.onclick=()=>void p(!0,!0),l.onclick=()=>void p(!1),a.append(i,r,o,l),t.appendChild(a),t}function Qt(e){let t=String(e.type||""),n=m.activeId;if(!n)return;let i=m.items.get(n)||[];if(t==="snapshot")m.items.set(n,[]);else if(t==="user")ce({kind:"user",text:String(e.text||"")});else if(t==="status"){let a=bt();a&&(a.status=String(e.status||a.status)),wt(),hi()}else if(t==="message"){let a=e.message;if(!a||String(a.role||"")!=="assistant")return;let r=mi(a),o=fi(a),l=i[i.length-1];l&&l.kind==="assistant"?(l.text=r||l.text,l.thinking=o||l.thinking):i.push({kind:"assistant",text:r,thinking:o}),m.items.set(n,i),ue()}else if(t==="delta"){let a=String(e.kind||""),r=String(e.delta||""),o=i[i.length-1];(!o||o.kind!=="assistant")&&(i.push({kind:"assistant",text:"",thinking:""}),o=i[i.length-1]),o.kind==="assistant"&&(a==="text"?o.text+=r:a==="thinking"&&(o.thinking+=r)),m.items.set(n,i),ue()}else if(t==="tool"){let a=String(e.callId||""),r=i.find(l=>l.kind==="tool"&&l.callId===a),o=String(e.phase||"start");r?(r.phase=o,o==="update"&&e.output&&(r.output=String(e.output)),o==="end"&&(e.output&&(r.output=String(e.output)),r.isError=e.isError===!0,typeof e.durationMs=="number"&&(r.durationMs=e.durationMs))):i.push({kind:"tool",callId:a,name:String(e.name||"tool"),args:e.args,output:e.output?String(e.output):void 0,isError:e.isError===!0,durationMs:typeof e.durationMs=="number"?e.durationMs:void 0,phase:o}),m.items.set(n,i),ue()}else if(t==="approval"){let a=e.approval;if(!a)return;let r=i;for(let o=r.length-1;o>=0;o--){let l=r[o];if(l.kind==="approval"&&l.approval.id===a.id){l.approval=a,a.state!=="pending"&&(l.decided=a.state==="allowed"?"allowed":"denied"),m.items.set(n,r),ue();return}}r.push({kind:"approval",approval:a}),m.items.set(n,r),ue()}else t==="notice"&&ce({kind:"notice",level:String(e.level||"info"),text:String(e.text||"")})}function 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 V(e=!1){try{let[t,n]=await Promise.all([T("/api/bots"),T("/api/bots/approvals")]);if(m.bots=t,m.approvals=n,We(),wt(),e&&m.activeId){let i=await T(`/api/bots/${m.activeId}/events?limit=300`);vi(i)}}catch{}}async function hi(){try{m.bots=await T("/api/bots"),We()}catch{}}function vi(e){if(m.activeId){m.items.set(m.activeId,[]);for(let t of e)Qt(t);Et()}}function gi(){let e=c("div","bots-modal");e.id="bots-modal",e.hidden=!0;let t=c("div","bots-modal-card"),n=c("div","bots-modal-head"),i=c("span");i.id="bots-modal-title";let a=c("button","btn","\u2715");a.onclick=()=>Ye(),n.append(i,a);let r=c("div","bots-modal-body");r.id="bots-modal-body",t.append(n,r),e.appendChild(t),e.onclick=o=>{o.target===e&&Ye()},document.body.appendChild(e)}function 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 Ye(){let e=document.getElementById("bots-modal");e&&(e.hidden=!0)}async function yi(){return m.catalog||(m.catalog=await T("/api/bots/catalog")),m.catalog}async function Zt(){return m.templates=await T("/api/bots/templates"),m.templates}async function Ie(){let e=kt("Bot templates"),[t,n]=await Promise.all([yi(),Zt()]),i=c("div","bv-template-list");for(let p of n){let u=c("div","bv-template-row");u.appendChild(c("span","bv-template-name",p.manifest.name)),u.appendChild(c("span","bv-template-desc",p.manifest.description||""));let v=c("button","btn","Edit");v.onclick=()=>Gt(e,t,p);let y=c("button","btn","Copy");y.title="Duplicate this template",y.onclick=()=>{let w=JSON.parse(JSON.stringify(p.manifest));w.name=`${p.manifest.name} copy`,T("/api/bots/templates",{method:"POST",body:JSON.stringify({manifest:w})}).then(()=>Ie()).catch(g=>alert(g instanceof Error?g.message:String(g)))};let D=c("button","btn danger","Delete");D.onclick=()=>{confirm(`Delete template ${p.manifest.name}?`)&&T(`/api/bots/templates/${p.id}`,{method:"DELETE"}).then(()=>Ie())};let x=c("span","bv-template-actions");x.append(v,y,D),u.appendChild(x),i.appendChild(u)}n.length===0&&i.appendChild(c("div","bots-empty","No templates yet")),e.appendChild(i);let a=c("div","bv-template-actions"),r=c("button","btn primary","New template");r.onclick=()=>Gt(e,t,null);let o=c("button","btn","Export");o.title="Download templates + library as JSON",o.onclick=()=>{(async()=>{try{let p=await fetch("/api/bots/export",{headers:{Authorization:`Bearer ${gt()}`}});if(!p.ok)throw new Error(`HTTP ${p.status}`);let u=await p.blob(),v=document.createElement("a");v.href=URL.createObjectURL(u),v.download=`tmux-weblink-bots-${new Date().toISOString().slice(0,10)}.json`,v.click(),setTimeout(()=>URL.revokeObjectURL(v.href),2e3)}catch(p){alert(p instanceof Error?p.message:String(p))}})()};let l=c("button","btn","Import");l.title="Restore templates from a JSON bundle",l.onclick=()=>{let p=document.createElement("input");p.type="file",p.accept="application/json,.json",p.onchange=()=>{let u=p.files?.[0];u&&(async()=>{try{let v=JSON.parse(await u.text()),y=await T("/api/bots/import",{method:"POST",body:JSON.stringify(v)});alert(`Imported ${y.templates} templates, ${y.files} library files (${y.skipped} kept)`),await Ie()}catch(v){alert(v instanceof Error?v.message:String(v))}})()},p.click()},a.append(r,o,l),e.appendChild(a)}function Ct(e,t,n){let i=c("div","bv-field");i.appendChild(c("label","bv-label",e));let a=c("div","bv-check-grid"),r=[];for(let o of t){let l=c("label","bv-check"),p=document.createElement("input");p.type="checkbox",p.checked=n.includes(o.id),l.append(p,c("span",void 0,o.label)),o.hint&&(l.title=o.hint),a.appendChild(l),r.push({id:o.id,input:p})}return i.appendChild(a),{element:i,get:()=>r.filter(o=>o.input.checked).map(o=>o.id)}}function Gt(e,t,n){e.textContent="";let i=n?JSON.parse(JSON.stringify(n.manifest)):{name:"new-bot",description:""},a=c("input","bv-input");a.value=i.name,a.placeholder="Template name";let r=c("input","bv-input");r.value=i.description||"",r.placeholder="One line description";let o=c("textarea","bv-textarea");o.rows=6,o.value=i.system||"",o.placeholder="System prompt for this bot (written to SYSTEM.md)";let l=Ct("Skills",t.skills.map(h=>({id:h.id,label:h.name,hint:h.description})),i.skills||[]),p=Ct("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=Ct("Prompt templates",t.prompts.map(h=>({id:h.id,label:h.name})),i.prompts||[]),v=c("select","bv-input");v.appendChild(new Option("none",""));for(let h of t.mcp)v.appendChild(new Option(h.name,h.id));i.mcp&&(v.value=t.mcp.find(h=>JSON.stringify(h.servers)===JSON.stringify(i.mcp?.mcpServers))?.id||"");let y=c("div","bv-field");y.appendChild(c("label","bv-label","Tools (allow list; deny always blocks)"));let D=c("div","bv-check-grid"),x=[];for(let h of t.tools){let U=c("label","bv-check"),B=document.createElement("input");B.type="checkbox",B.checked=(i.tools?.allow||[]).includes(h.name)||!i.tools?.allow?.length&&["read","grep","find","ls","edit","write","bash"].includes(h.name),U.append(B,c("span",void 0,h.name)),D.appendChild(U),x.push({name:h.name,input:B})}y.appendChild(D);let w=c("input","bv-input");w.value=(i.tools?.deny||[]).join(", "),w.placeholder="Always deny (comma separated), e.g. bash, write";let g=c("textarea","bv-textarea");g.rows=2,g.value=(i.packages||[]).join(`
|
|
9
9
|
`),g.placeholder="Pi packages, one per line (npm:@scope/pkg@1.2.3, git:..., ./path)";let A=c("select","bv-input");A.appendChild(new Option("default (Pi settings)",""));for(let h of t.models)A.appendChild(new Option(`${h.provider}/${h.model}`,`${h.provider}
|
|
10
10
|
${h.model}`));i.model?.provider&&i.model?.id&&(A.value=`${i.model.provider}
|
|
11
|
-
${i.model.id}`);let
|
|
12
|
-
`),B=t.mcp.find($=>$.id===v.value),le={name:a.value.trim()||"bot",description:r.value.trim()||void 0,system:
|
|
13
|
-
`).map($=>$.trim()).filter(Boolean),mcp:B?{mcpServers:B.servers}:void 0,tools:{allow:x.filter($=>$.input.checked).map($=>$.name),deny:w.value.split(",").map($=>$.trim()).filter(Boolean)},model:h?{provider:h,id:
|
|
11
|
+
${i.model.id}`);let J=c("select","bv-input");for(let h of["","off","minimal","low","medium","high","xhigh","max"])J.appendChild(new Option(h||"default",h));i.model?.thinking&&(J.value=i.model.thinking);let O=c("select","bv-input");for(let h of["supervised","auto-accept-edits","full-access"])O.appendChild(new Option(h,h));O.value=i.permissions?.runtimeMode||"supervised";let _=c("select","bv-input");_.appendChild(new Option("ignore project .pi (recommended)","ignore")),_.appendChild(new Option("inherit project .pi (needs trust)","inherit")),_.value=i.projectResources||"ignore";let z=c("label","bv-check"),b=document.createElement("input");b.type="checkbox",b.checked=!!i.orchestrator,z.append(b,c("span",void 0,"Super bot: gets orchestration tools (create/stop/status child bots)"));let L=(h,U)=>{let B=c("div","bv-field");return B.appendChild(c("label","bv-label",h)),B.appendChild(U),B};e.append(L("Name",a),L("Description",r),L("System prompt",o),l.element,p.element,u.element,L("MCP preset",v),y,L("Always deny tools",w),L("Packages",g),L("Model",A),L("Thinking level",J),L("Approval mode",O),L("Project resources",_),z);let G=c("button","btn primary",n?"Save template":"Create template");G.onclick=async()=>{let[h,U]=A.value.split(`
|
|
12
|
+
`),B=t.mcp.find($=>$.id===v.value),le={name:a.value.trim()||"bot",description:r.value.trim()||void 0,system:o.value.trim()||void 0,skills:l.get(),extensions:p.get().map($=>($.startsWith("builtin:"),$)),prompts:u.get(),packages:g.value.split(`
|
|
13
|
+
`).map($=>$.trim()).filter(Boolean),mcp:B?{mcpServers:B.servers}:void 0,tools:{allow:x.filter($=>$.input.checked).map($=>$.name),deny:w.value.split(",").map($=>$.trim()).filter(Boolean)},model:h?{provider:h,id:U,thinking:J.value||void 0}:void 0,permissions:{runtimeMode:O.value},projectResources:_.value==="inherit"?"inherit":"ignore",orchestrator:b.checked||void 0};try{await T("/api/bots/templates",{method:"POST",body:JSON.stringify({id:n?.id,manifest:le})}),Ye(),await Ie()}catch($){alert($ instanceof Error?$.message:String($))}},e.appendChild(G)}async function bi(){return en("")}async function en(e){let t=kt("New bot"),n=await Zt();if(n.length===0){t.appendChild(c("div","bots-empty","Create a template first (\u2699)."));return}let i=c("select","bv-input");for(let u of n)i.appendChild(new Option(u.manifest.name,u.id));let a=c("input","bv-input");a.placeholder="Title (defaults to template name)";let r=c("input","bv-input");r.placeholder="/path/to/project";let o=e||m.bots[0]?.projectPath||"";r.value=o;let l=c("select","bv-input");l.appendChild(new Option("shared \u2014 run in the project folder","shared")),l.appendChild(new Option("worktree \u2014 isolated git worktree","worktree")),t.append(Ve("Template",i),Ve("Title",a),Ve("Project path",r),Ve("Workspace",l));let p=c("button","btn primary","Create bot");p.onclick=async()=>{try{let u=await T("/api/bots",{method:"POST",body:JSON.stringify({templateId:i.value,title:a.value.trim()||void 0,projectPath:r.value.trim()||void 0,isolation:l.value})});Ye(),await V(!0),await Kt(u.id)}catch(u){alert(u instanceof Error?u.message:String(u))}},t.appendChild(p)}function Ve(e,t){let n=c("div","bv-field");return n.appendChild(c("label","bv-label",e)),n.appendChild(t),n}async function xt(){let e=kt("Needs you");if(m.approvals=await T("/api/bots/approvals"),m.approvals.length===0){e.appendChild(c("div","bots-empty","Nothing waiting."));return}for(let t of m.approvals){let n=c("div","bv-approval");n.appendChild(c("div","bv-approval-title",`${t.botTitle}: ${t.title}`)),t.message&&n.appendChild(c("pre","bv-pre",t.message));let i=c("input","bv-reason");i.placeholder="reason (optional)";let a=c("div","bv-approval-actions"),r=c("button","btn primary","Allow"),o=c("button","btn danger","Deny"),l=async p=>{await T(`/api/bots/${t.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:t.id,allow:p,reason:i.value||void 0})}),await V(!0),await xt()};r.onclick=()=>void l(!0),o.onclick=()=>void l(!1),a.append(i,r,o),n.appendChild(a),e.appendChild(n)}}function wi(){window.__botsInited||(window.__botsInited=!0,di(),ri(),window.__openBot=Kt,document.addEventListener("click",e=>{let t=e.target;t&&(t.closest(".session-item.bot-item")||t.closest(".session-item")&&m.activeId&&setTimeout(()=>yt(),0))},!0),V(!0),m.pollTimer=window.setInterval(()=>{document.hidden||V()},6e3),window.addEventListener("beforeunload",()=>window.clearInterval(m.pollTimer)))}var Be=window.__TMUX_WEB_SHELL__,S=null,M=null,Te=typeof window.__TMUX_WEB_SCOPE__?.agentId=="string"?window.__TMUX_WEB_SCOPE__.agentId:null,H=Te;window.__tmuxWebScopeAgent=Te;var Lt="sessions",ie="",Ke="",Xe="",tn="";function N(e){return H?"/a/"+encodeURIComponent(H)+e:e}var k=document.getElementById("sidebar-content"),pe=document.getElementById("main-placeholder"),W=document.getElementById("terminal-container"),Me=document.getElementById("file-editor"),Ei=document.getElementById("fe-path"),K=document.getElementById("fe-status"),De=document.getElementById("fe-content"),me=document.getElementById("fe-save"),ki=document.getElementById("fe-delete"),Ci=document.getElementById("fe-back"),nn=document.getElementById("fe-new-name"),xi=document.getElementById("fe-new-btn"),St=document.getElementById("settings-backdrop"),an=document.getElementById("settings-popover"),on=document.querySelector(".sidebar"),sn="tmux-web-force-narrow";function Qe(){try{return localStorage.getItem(sn)==="1"}catch{return!1}}function ln(){document.documentElement.classList.toggle("force-narrow",Qe()),Qe()&&rn()&&Ae()}function rn(){return Qe()?!0:window.matchMedia("(max-width: 640px)").matches}function Ae(){rn()&&on.classList.add("collapsed")}function dn(){on.classList.remove("collapsed")}window.__collapseSidebar=Ae,document.getElementById("mode-sessions").addEventListener("click",()=>{dn(),cn("sessions")}),document.getElementById("mode-files").addEventListener("click",()=>{dn(),cn("files")});function cn(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="",ae()):Hi()}var It="";async function ae(){if(Lt!=="sessions")return;try{let t=await(await fetch("/api/sidebar/sessions")).json(),n=(window.__botsSnapshot||[]).map(a=>[a.id,a.title,a.status,a.projectPath]),i=JSON.stringify({recent:t.recent,agents:t.agents,tombstones:t.tombstones,bots:n});if(i===It)return;It=i,Mi(t)}catch{k.innerHTML+='<div class="file-tree-empty">Failed to load sessions</div>'}let e=document.getElementById("ns-btn");e&&e.addEventListener("click",()=>{let t=window.__openNewSessionModal;typeof t=="function"?t():document.getElementById("new-session-modal")?.classList.add("open")}),$t()}var un="tmux-web-sidebar-group-collapsed";function pn(){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,a=i.split("/").filter(Boolean);if(a.length===0)return e;for(let r=1;r<=a.length;r++){let o=a.slice(-r).join("/");if(!t.some(l=>!l||l===e?!1:(n&&(l===n||l.startsWith(n+"/"))?"~"+l.slice(n.length):l).split("/").filter(Boolean).slice(-r).join("/")===o))return o}return i}function Ii(e){let t=document.createElement("div");t.className="session-item bot-item",t.setAttribute("data-bot-id",e.id),t.title=`Bot \xB7 ${e.projectPath}`;let n=e.status==="running"?"var(--panel-success)":e.status==="waiting_approval"||e.status==="waiting_input"?"#e0a23c":e.status==="failed"?"var(--panel-danger, #e5534b)":"var(--panel-muted)";return t.innerHTML=`<svg class="bot-icon" viewBox="0 0 24 24" fill="currentColor"><path d="M11 2h2v3h2a3 3 0 0 1 3 3v1h1a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2h-1v1a3 3 0 0 1-3 3H9a3 3 0 0 1-3-3v-1H5a2 2 0 0 1-2-2v-6a2 2 0 0 1 2-2h1V8a3 3 0 0 1 3-3h2V2zm-2 6v1h6V8H9zm-2 5a1.5 1.5 0 1 0 0 3 1.5 1.5 0 0 0 0-3zm10 0a1.5 1.5 0 1 0 0 3 1.5 1.5 0 0 0 0-3z"/></svg><span>${C(e.title)}</span><span class="bot-status-dot" style="background:${n}"></span>`,t.addEventListener("click",i=>{i.stopPropagation(),window.__openBot?.(e.id)}),t}function mn(e,t,n,i=!0){let a=new Map;for(let u of e){let v=u.path||"";a.has(v)||a.set(v,[]),a.get(v).push(u)}let r=n?[]:window.__botsSnapshot||[],o=new Map;for(let u of r)a.has(u.projectPath)||a.set(u.projectPath,[]),o.has(u.projectPath)||o.set(u.projectPath,[]),o.get(u.projectPath).push(u);let l=[...a.keys()],p=pn();for(let[u,v]of a){let y=Si(u,l,t),D=p.has(u),x=document.createElement("div");if(x.className="session-group-header"+(D?" collapsed":""),x.title=u||"No working directory",x.innerHTML=`<span class="sg-folder">📁</span><span class="sg-label">${C(y)}</span>`,!n&&u){let g=document.createElement("button");g.className="sg-add-bot",g.textContent="+",g.title=`New bot in ${u}`,g.addEventListener("click",A=>{A.stopPropagation(),Tt(u)}),x.appendChild(g)}x.addEventListener("click",()=>{let g=pn(),A=x.nextElementSibling;g.has(u)?(g.delete(u),x.classList.remove("collapsed"),A?.classList.remove("collapsed")):(g.add(u),x.classList.add("collapsed"),A?.classList.add("collapsed")),Li(g)});let w=document.createElement("div");w.className="session-group-body"+(D?" collapsed":"");for(let g of v)w.appendChild(n?Bi(g,n,i):Ti(g));for(let g of o.get(u)||[])w.appendChild(Ii(g));k.appendChild(x),k.appendChild(w)}}function Bi(e,t,n){let i=document.createElement("div");i.className="session-item"+(e.name===M&&H===t?" active":"")+(n?"":" session-offline"),i.setAttribute("data-session",e.name),i.setAttribute("data-agent",t),i.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="${e.attached?"M19 4H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zm0 14H5V6h14v12z":"M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"}"></svg>
|
|
14
14
|
<span>${C(e.name)}</span>${n?"":'<span class="meta">offline</span>'}
|
|
15
|
-
<button class="session-edit-btn" data-session="${C(e.name)}" title="Edit session"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>`,n&&i.addEventListener("click",r=>{r.target.closest(".session-edit-btn")||
|
|
15
|
+
<button class="session-edit-btn" data-session="${C(e.name)}" title="Edit session"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>`,n&&i.addEventListener("click",r=>{r.target.closest(".session-edit-btn")||Fe(e.name,t)});let a=i.querySelector(".session-edit-btn");return a&&a.addEventListener("click",r=>{r.stopPropagation(),lt(e.name,a,{agentId:t})}),i}function Ti(e){let t=document.createElement("div");t.className="session-item"+(e.name===M&&!H?" active":""),t.setAttribute("data-session",e.name),t.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="${e.attached?"M19 4H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zm0 14H5V6h14v12z":"M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"}"></svg>
|
|
16
16
|
<span>${C(e.name)}</span>
|
|
17
17
|
<button class="session-edit-btn" data-session="${C(e.name)}" title="Edit session"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>
|
|
18
|
-
`,t.addEventListener("click",i=>{i.target.closest(".session-edit-btn")||
|
|
19
|
-
<span>${C(
|
|
20
|
-
<button class="session-edit-btn" data-session="${C(
|
|
18
|
+
`,t.addEventListener("click",i=>{i.target.closest(".session-edit-btn")||Fe(e.name)});let n=t.querySelector(".session-edit-btn");return n&&n.addEventListener("click",i=>{i.stopPropagation(),lt(e.name,n)}),t}function Mi(e){k.innerHTML='<button class="new-session-sidebar-btn" id="ns-btn">+ New Session</button>';let t=e.recent||[],n=document.createElement("div");n.className="sidebar-section-label"+(Te?" clickable":""),n.textContent=Te?"\u2190 \u8FD4\u56DE\u672C\u673A":"\u672C\u673A",Te&&(n.title="Back to hub",n.addEventListener("click",()=>{window.location.href="/"})),k.appendChild(n),mn(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,l=document.createElement("div");l.className="sidebar-section-label machine-label"+(r.online?"":" agent-offline-label")+(!o&&r.online?" clickable":""),l.textContent=r.agentName+(r.online?"":" (offline)"),!o&&r.online&&(l.title="\u6253\u5F00 "+r.agentName,l.addEventListener("click",()=>{window.location.href="/a/"+encodeURIComponent(r.agentId)+"/"})),k.appendChild(l),mn(r.sessions,e.home,r.agentId,r.online)}let a=e.tombstones||[];if(a.length>0){let r=document.createElement("div");r.className="sidebar-section-label tombstone-label",r.textContent="\u5931\u6548\u4F1A\u8BDD",k.appendChild(r);for(let o of a){let l=document.createElement("div");l.className="session-item session-tombstone",l.setAttribute("data-session",o.name),o.agentId&&l.setAttribute("data-agent",o.agentId);let p=o.agentId?o.agentOnline?" (agent)":" (agent \u79BB\u7EBF)":"";l.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"></svg>
|
|
19
|
+
<span>${C(o.name)}</span><span class="meta">\u5931\u6548${p}</span>
|
|
20
|
+
<button class="session-edit-btn" data-session="${C(o.name)}" title="\u6062\u590D\u4F1A\u8BDD"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>`,l.title="\u5931\u6548\u4F1A\u8BDD\uFF1A\u70B9\u51FB\u7BA1\u7406\uFF08\u91CD\u5EFA/\u91CD\u547D\u540D/\u5220\u9664\uFF09",l.addEventListener("click",()=>{lt(o.name,l,{tombstone:!0,agentId:o.agentId})});let u=l.querySelector(".session-edit-btn");u&&u.addEventListener("click",v=>{v.stopPropagation(),lt(o.name,u,{tombstone:!0,agentId:o.agentId})}),k.appendChild(l)}}}function C(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}async function Fe(e,t){if(M===e&&S&&H===(t||null))return;Me.style.display="none",pe.style.display="none",W.style.display="",W.classList.add("terminal-pending"),Ae(),S&&(ot(),S.destroy(),S=null),M=e,H=t||null,window.__tmuxWebScopeAgent=H,window.__tmuxWebCurrentSession=M,ta(e,t);let n=Ft(e,t);Bn.set(n,Date.now()+Gi);let i=we.get(n);if(i&&i.state==="working"){i.state="idle",i.doneUntil=void 0,i.unread=!1;let a=k.querySelector(t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])');a&&pt(a,n,i)}for(let a of k.querySelectorAll(".session-item"))a.classList.toggle("active",a.getAttribute("data-session")===e&&(a.getAttribute("data-agent")||null)===H);try{S=await si(W,e,{terminal:Be.terminal,scrollback:Be.scrollback,theme:Be.theme,wsBase:H?"/ws/a/"+encodeURIComponent(H):Be.wsBase||"/ws"}),Cn()}catch(a){console.error("[shell] terminal init failed:",a);let r=a&&typeof a=="object"&&"message"in a?a.message:String(a);W.textContent="Failed to open terminal for "+e+": "+r,W.classList.remove("terminal-pending")}}var Ze=[],F=null,fn=!1;function Di(e){if(!F||!F.files.length)return null;let t=F.repoRoot;if(!t||!e.startsWith(t))return null;let n=e.slice(t.length+1);for(let i of F.files)if(i.path===n)return i.status;return null}async function Ai(e){fn=!0;try{let t=await fetch(N("/api/git/status?path="+encodeURIComponent(e)));t.ok?F=await t.json():F=null}catch{F=null}finally{fn=!1}}function Fi(){if(!F||!F.branch)return"";let{branch:e,linesAdded:t,linesRemoved:n}=F,i=`<div class="sidebar-git"><div class="git-branch-badge">
|
|
21
21
|
<svg viewBox="0 0 16 16" fill="currentColor"><path d="M11.63 1.22a.75.75 0 00-1.06 0L5.99 5.8 4.12 3.93a.75.75 0 10-1.06 1.06L4.93 6.87A3.5 3.5 0 003 10.09v3.16a.75.75 0 001 0v-3.16a2.5 2.5 0 012.5-2.5h.27l-1.06 1.06a.75.75 0 001.06 1.06l2.37-2.38a.75.75 0 000-1.06L7.59 5.27l4.04-4.05a.75.75 0 000-1.06L11.63 1.22zM3.25 13.94a.75.75 0 01-.75-.75v-.69a.75.75 0 011.5 0v.69c0 .414-.336.75-.75.75z"/></svg>
|
|
22
|
-
${C(e)}</div>`;return(t>0||n>0)&&(i+=`<div class="git-diff-stats">+<span class="add">${t}</span> <span class="del">-${n}</span></div>`),i+"</div>"}k.addEventListener("click",e=>{e.target.closest(".sidebar-git")&&
|
|
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,
|
|
24
|
-
${
|
|
22
|
+
${C(e)}</div>`;return(t>0||n>0)&&(i+=`<div class="git-diff-stats">+<span class="add">${t}</span> <span class="del">-${n}</span></div>`),i+"</div>"}k.addEventListener("click",e=>{e.target.closest(".sidebar-git")&&ye&&F&&(e.stopPropagation(),bn())});var $e=document.getElementById("header-git"),hn=document.getElementById("git-diff-view"),vn=document.getElementById("gd-path"),Ge=document.getElementById("gd-status"),et=document.getElementById("gd-content"),$i=document.getElementById("gd-back"),ye=null;function Pe(e){if(!e||!e.branch){$e.style.display="none",ye=null;return}ye=e.repoRoot;let{branch:t,linesAdded:n,linesRemoved:i}=e,a=`<span class="branch">${C(t)}</span>`;(n>0||i>0)&&(a+=`<span class="sep">\xB7</span>+<span class="diff-add">${n}</span> <span class="diff-del">-${i}</span>`),$e.innerHTML=a,$e.style.display="block"}$e.addEventListener("click",e=>{ye&&F&&(e.stopPropagation(),bn())});var R=document.getElementById("git-popover"),tt=document.getElementById("git-popover-backdrop");function Bt(){let e=$e.getBoundingClientRect();R.style.top=e.bottom+4+"px",R.style.left=Math.max(8,Math.min(e.left,window.innerWidth-400))+"px"}function gn(){let e=ye,t=document.getElementById("git-popover-browse");t&&t.addEventListener("click",()=>{if(it(),e){Lt="files",document.querySelectorAll(".mode-btn").forEach(i=>i.classList.remove("active"));let n=document.getElementById("mode-files");n&&n.classList.add("active"),oe(e)}})}var yn="";function bn(){if(!F)return;let e=F.files||[];if(!e.length)R.innerHTML=`<div class="git-popover-header">No changes \u2014 clean working tree</div>
|
|
23
|
+
<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>`;else{let t=`<div class="git-popover-header">${e.length} file${e.length>1?"s":""} changed</div>`;for(let n=0;n<e.length;n++){let i=e[n],a=i.additions||0,r=i.deletions||0,o="";switch(i.status){case"M":o='<span class="git-file-status M">M</span>';break;case"A":o='<span class="git-file-status A">A</span>';break;case"D":o='<span class="git-file-status D">D</span>';break;case"?":o='<span class="git-file-status ?">?</span>';break;case"R":o='<span class="git-file-status R">R</span>';break}t+=`<div class="git-popover-item" data-idx="${n}">
|
|
24
|
+
${o}<span class="file-path">${C(i.path)}</span>
|
|
25
25
|
<span class="file-add">${a>0?"+"+a:""}</span>
|
|
26
26
|
<span class="file-del">${r>0?"-"+r:""}</span>
|
|
27
|
-
</div>`}t+='<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>',
|
|
27
|
+
</div>`}t+='<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>',yn=t,R.innerHTML=t,R.querySelectorAll(".git-popover-item").forEach(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",()=>En(a.path)))})}Bt(),R.classList.add("open"),tt.classList.add("open"),gn()}function Pi(){return window.innerWidth>=1024}function wn(e,t){let n=(e+(t&&e?`
|
|
28
28
|
`:"")+t).split(`
|
|
29
|
-
`),i="",a=0,r=0;for(let
|
|
29
|
+
`),i="",a=0,r=0;for(let o of n){let l=o;if(l.startsWith("@@")){let p=l.match(/@@\s+-(\d+)[^+]*\+(\d+)/);p&&(a=parseInt(p[1],10)-1,r=parseInt(p[2],10)-1),i+=`<div class="diff-line hunk"><span class="ln-body">${C(l)}</span></div>`;continue}if(l.startsWith("diff --git")||l.startsWith("index ")||l.startsWith("--- ")||l.startsWith("+++ ")||l.startsWith("new file")||l.startsWith("deleted file")){l.startsWith("diff --git")&&(i+=`<div class="diff-line header"><span class="ln-body">${C(l)}</span></div>`);continue}if(l.startsWith("+"))r++,i+=`<div class="diff-line add"><span class="ln-no">${r}</span><span class="ln-body">${C(l)}</span></div>`;else if(l.startsWith("-"))a++,i+=`<div class="diff-line del"><span class="ln-no">${a}</span><span class="ln-body">${C(l)}</span></div>`;else if(l.startsWith("\\"))i+=`<div class="diff-line"><span class="ln-body">${C(l)}</span></div>`;else{if(!l&&!a&&!r)continue;a++,r++,i+=`<div class="diff-line"><span class="ln-no">${a}</span><span class="ln-no" style="margin-right:12px">${r}</span><span class="ln-body">${C(l)}</span></div>`}}return{html:i,lineCount:n.length}}var nt=null;async function En(e){let t=ye;if(t)if(it(),Pi()){W.style.display="none",S&&(ot(),S.destroy(),S=null,nt=M,M=null),Pe(null),Me.style.display="none",pe.style.display="none",hn.style.display="flex",vn.textContent=e,Ge.textContent="Loading\u2026",et.innerHTML="";try{let n=await fetch(N("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!n.ok)throw new Error(await n.text());let i=await n.json();Oi(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: ${C(i)}</div>`}}else{R.innerHTML=`<div class="git-diff-view"><div class="diff-header">
|
|
30
30
|
<button class="diff-back">\u2190 Back</button>
|
|
31
31
|
<span class="diff-filename">${C(e)}</span>
|
|
32
32
|
<span class="diff-loading">Loading\u2026</span>
|
|
33
|
-
</div></div>`,
|
|
33
|
+
</div></div>`,Bt(),R.classList.add("open"),tt.classList.add("open");try{let n=await fetch(N("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!n.ok)throw new Error(await n.text());let i=await n.json();Ni(e,i.diff,i.stagedDiff)}catch(n){let i=n instanceof Error?n.message:String(n);R.innerHTML=`<div class="git-diff-view"><div class="diff-header">
|
|
34
34
|
<button class="diff-back">\u2190 Back</button>
|
|
35
35
|
<span class="diff-filename">${C(e)}</span>
|
|
36
|
-
</div><div class="diff-empty">Error loading diff: ${C(i)}</div></div>`}}}function
|
|
36
|
+
</div><div class="diff-empty">Error loading diff: ${C(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
38
|
<span class="diff-filename">${C(e)}</span>
|
|
39
|
-
</div><div class="diff-empty">No diff content available</div></div>`;return}let{html:i,lineCount:a}=
|
|
39
|
+
</div><div class="diff-empty">No diff content available</div></div>`;return}let{html:i,lineCount:a}=wn(t,n);R.innerHTML=`<div class="git-diff-view"><div class="diff-header">
|
|
40
40
|
<button class="diff-back">\u2190 Back</button>
|
|
41
41
|
<span class="diff-filename">${C(e)}</span>
|
|
42
42
|
<span class="diff-filesize">${a} lines</span>
|
|
43
|
-
</div><div class="diff-content">${i}</div></div>`,R.querySelector(".diff-back")?.addEventListener("click",()=>{R.innerHTML=
|
|
43
|
+
</div><div class="diff-content">${i}</div></div>`,R.querySelector(".diff-back")?.addEventListener("click",()=>{R.innerHTML=yn,Bt(),F&&R.querySelectorAll(".git-popover-item").forEach(r=>{let o=parseInt(r.dataset.idx||"0",10),l=F.files[o];!l||l.status==="D"||(r.style.cursor="pointer",r.addEventListener("click",()=>En(l.path)))}),gn()})}function Oi(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:a}=wn(t,n);vn.textContent=e,Ge.textContent=a+" lines",et.innerHTML=i}function ji(){hn.style.display="none",nt?(W.style.display="",W.classList.add("terminal-pending"),Fe(nt),nt=null):M?(W.style.display="",W.classList.add("terminal-pending"),Cn()):pe.style.display="flex"}$i.addEventListener("click",ji);function it(){R.classList.remove("open"),tt.classList.remove("open")}tt.addEventListener("click",it),document.addEventListener("keydown",e=>{e.key==="Escape"&&(it(),ut())});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();F=i,Pe(i);return}}}catch{}F=null,Pe(null)}var at=null;function Cn(){ot(),M&&(kn(M),at=setInterval(()=>{M&&kn(M)},3e4))}function ot(){at&&(clearInterval(at),at=null)}async function Tt(e){let t=e;if(t.startsWith("~"))try{let n=await(await fetch(N("/api/fs/list?path="+encodeURIComponent(t)))).json();typeof n.path=="string"&&n.path&&(t=n.path)}catch{}t=t.replace(/\/+$/,"")||"/",en(t)}function xn(e,t){let n=document.createElement("button");n.className="file-tree-bot-btn",n.textContent="+",n.title=`Create bot in ${t}`,n.setAttribute("aria-label",`Create bot in ${t}`),n.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),Tt(t)}),e.appendChild(n)}function Hi(){if(Ze=Be.fsRoots||[],Ze.length===0){if(M){Ri(M);return}oe("");return}k.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> ${C(e)}`,t.addEventListener("click",()=>oe(e)),xn(t,e),k.appendChild(t)}}async function Ri(e){k.innerHTML='<div class="file-tree-empty">Loading...</div>';try{let t=await(await fetch(N("/api/fs/session-path?session="+encodeURIComponent(e)))).json();t.path?oe(t.path):k.innerHTML='<div class="file-tree-info">Could not determine session directory.</div>'}catch{k.innerHTML='<div class="file-tree-error">Failed to get session directory</div>'}}async function oe(e){ie=e,k.innerHTML='<div class="file-tree-empty">Loading...</div>';let t=Ai(e);try{let n=await(await fetch(N("/api/fs/list?path="+encodeURIComponent(e)))).json(),i=typeof n.path=="string"&&n.path?n.path:e;if(i&&(ie=i),await t,k.innerHTML="",i){let o=document.createElement("div");o.className="file-tree-item file-tree-create-bot",o.innerHTML='<span class="file-tree-bot-plus">+</span> Create bot in this folder',o.title=`Create bot in ${i}`,o.addEventListener("click",()=>void Tt(i)),k.appendChild(o)}Pe(F),k.innerHTML+=Fi();let a=_i(i||e);if(a&&!Ze.some(o=>i===o)){let o=document.createElement("div");o.className="file-tree-item",o.innerHTML="..",o.addEventListener("click",()=>oe(a)),k.appendChild(o)}if(n.dirs)for(let o of n.dirs){let l=o.split("/").pop()||o.split("\\").pop(),p=document.createElement("div");p.className="file-tree-item",p.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor" class="file-icon"><path d="M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/></svg> ${C(l)}`,p.addEventListener("click",()=>oe(o)),xn(p,o),k.appendChild(p)}else k.innerHTML="";let r=n.files||[];for(let o of r){let l=o.split("/").pop()||o.split("\\").pop(),p=Di(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 y=document.createElement("div");y.className="file-tree-item file"+(u?" "+u:""),y.innerHTML=`<span class="file-icon">\u{1F4C4}</span> ${v}${C(l)}`,y.addEventListener("click",()=>zi(o)),k.appendChild(y)}}catch{k.innerHTML='<div class="file-tree-error">Failed to load directory</div>'}}function _i(e){let t=e.lastIndexOf("/");return t<=0?null:e.substring(0,t)}async function zi(e){Ke=e,W.style.display="none",S&&(ot(),S.destroy(),S=null,M=null),Pe(null),Ae(),pe.style.display="none",Me.style.display="flex",Ei.textContent=e,K.textContent="Loading...",me.style.display="none";try{let t=await fetch(N("/api/file?path="+encodeURIComponent(e)));if(!t.ok){let i=await t.json();K.textContent=i.error||"Failed to load",De.value="";return}let n=await t.json();De.value=n.content,Xe=n.content,tn=n.content,K.textContent=n.size+" bytes",me.style.display=""}catch{K.textContent="Failed to load",De.value=""}}De.addEventListener("input",()=>{Xe=De.value}),me.addEventListener("click",async()=>{me.textContent="Saving...",me.disabled=!0;try{let e=await fetch(N("/api/file"),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:Ke,content:Xe})});if(!e.ok){let t=await e.json();K.textContent=t.error||"Save failed";return}tn=Xe,K.textContent="Saved"}catch{K.textContent="Save failed"}finally{me.disabled=!1,me.textContent="Save"}}),ki.addEventListener("click",async()=>{if(confirm("Delete "+Ke+"?"))try{let e=await fetch(N("/api/file/delete"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:Ke})});if(!e.ok){let t=await e.json();K.textContent=t.error||"Delete failed";return}Me.style.display="none",pe.style.display="flex",ie&&oe(ie)}catch{K.textContent="Delete failed"}}),Ci.addEventListener("click",()=>{Me.style.display="none",pe.style.display="flex",ie&&oe(ie)}),xi.addEventListener("click",async()=>{let e=nn.value.trim();if(!e)return;let t=ie+"/"+e;try{let n=await fetch(N("/api/file/touch"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t})});if(!n.ok){let i=await n.json();K.textContent=i.error||"Create failed";return}nn.value="",ie&&oe(ie)}catch{K.textContent="Create failed"}});var st=document.getElementById("force-narrow-toggle");st&&(st.checked=Qe(),st.addEventListener("change",()=>{try{localStorage.setItem(sn,st.checked?"1":"0")}catch{}ln(),ae()})),ln(),document.getElementById("mode-settings").addEventListener("click",()=>{let e=an.classList.toggle("open");St.classList.toggle("open",e)}),St.addEventListener("click",()=>{an.classList.remove("open"),St.classList.remove("open")});var Y="",X=!1,Q,Ne=document.createElement("div");Ne.className="session-popover-backdrop",document.body.appendChild(Ne);var Z=document.createElement("div");Z.id="session-popover",Z.className="session-popover",Z.style.display="none",Z.innerHTML=`<div class="sp-field">
|
|
44
44
|
<label>Rename session</label>
|
|
45
45
|
<input type="text" id="sp-name" />
|
|
46
46
|
</div>
|
|
@@ -50,5 +50,5 @@ ${i.model.id}`);let W=c("select","bv-input");for(let h of["","off","minimal","lo
|
|
|
50
50
|
<button class="btn danger sp-delete" id="sp-delete">Delete</button>
|
|
51
51
|
</div>
|
|
52
52
|
<hr class="sp-divider" id="sp-divider" />
|
|
53
|
-
<button class="btn primary" id="sp-rebuild" style="display:none">\u91CD\u5EFA\u540C\u540D\u540C\u8DEF\u5F84 session</button>`,document.body.appendChild(
|
|
54
|
-
`).length;te.rows=Math.min(e,4)}),te.addEventListener("keydown",e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),
|
|
53
|
+
<button class="btn primary" id="sp-rebuild" style="display:none">\u91CD\u5EFA\u540C\u540D\u540C\u8DEF\u5F84 session</button>`,document.body.appendChild(Z);function Ui(e){let t=e.getBoundingClientRect(),n=window.innerHeight,i=Z.offsetHeight||240,a=t.bottom+4;a+i>n-8&&(a=Math.max(8,t.top-i-4)),Z.style.top=a+"px",Z.style.left=Math.max(8,Math.min(t.left,window.innerWidth-240))+"px"}function lt(e,t,n){Y=e,X=!!n?.tombstone,Q=n?.agentId;let i=document.getElementById("sp-name");i.value=e;let a=Z.querySelector(".sp-field label");a.textContent=X?"\u91CD\u547D\u540D (\u4EC5\u8BB0\u5F55\uFF0C\u4E0D\u91CD\u5EFA)":"Rename session";let r=document.getElementById("sp-rebuild");r.style.display=X?"":"none";let o=document.getElementById("sp-delete");o.textContent=X?"\u5220\u9664\u8BB0\u5F55":"Delete",o.title=X?"\u5220\u9664\u5931\u6548\u8BB0\u5F55\uFF08\u5893\u7891\u6D88\u5931\uFF09":"Delete session";let l=document.getElementById("sp-divider");l&&(l.style.display=X?"":"none");let p=document.getElementById("sp-save");p.textContent=X?"\u91CD\u547D\u540D":"Save",Ne.classList.add("open"),Z.style.display="block",Ui(t),setTimeout(()=>i.focus(),50)}function fe(){Ne.classList.remove("open"),Z.style.display="none"}Ne.addEventListener("click",fe),document.getElementById("sp-save").addEventListener("click",async()=>{let e=document.getElementById("sp-name").value.trim();if(!e||e===Y){fe();return}try{let t=X?{oldName:Y,newName:e,agentId:Q}:{oldName:Y,newName:e,...Q?{agentId:Q}:{}};if(!(await fetch(N(X?"/api/sessions/rename-tombstone":"/api/sessions/rename"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).ok)return;fe(),ae(),!X&&M===Y&&(Q??null)===H&&Fe(e,Q)}catch{}}),document.getElementById("sp-rebuild").addEventListener("click",async()=>{if(confirm('\u91CD\u5EFA\u4F1A\u8BDD "'+Y+'" (\u540C\u540D\u540C\u8DEF\u5F84\uFF0C\u5185\u5BB9\u4E3A\u7A7A)\uFF1F'))try{let e=await fetch(N("/api/sessions/rebuild"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:Y,agentId:Q})});if(!e.ok){let t=await e.json();alert(t.error||"\u91CD\u5EFA\u5931\u8D25");return}fe(),ae()}catch{}}),document.getElementById("sp-delete").addEventListener("click",async()=>{if(X){if(!confirm('\u5220\u9664\u5931\u6548\u8BB0\u5F55 "'+Y+'"\uFF1F'))return;try{if(!(await fetch(N("/api/sessions/dismiss"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:Y,agentId:Q})})).ok)return;fe(),ae()}catch{}return}if(confirm('Delete session "'+Y+'"?'))try{if(!(await fetch(N("/api/sessions/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:Y,...Q?{agentId:Q}:{}})})).ok)return;fe(),M===Y&&(Q??null)===H&&(S&&(S.destroy(),S=null),M=null,W.style.display="none",pe.style.display="flex"),ae()}catch{}}),document.getElementById("sp-cancel").addEventListener("click",fe);var Ln={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"),qi=new Set(["up","down","left","right","tab","s-tab","space"]),Ji=400,Wi=80,Oe=0,dt=0,ct=!1;function Yi(){Oe&&(clearTimeout(Oe),Oe=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;qi.has(n)&&(ct=!1,Oe=setTimeout(()=>{Oe=0,ct=!0,dt=setInterval(()=>{let i=Ln[n];i&&S&&S.sendInput(i)},Wi)},Ji))});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||!S)return;if(ct){ct=!1;return}let n=Ln[t.dataset.key];n&&(S.sendInput(n),S.focus())});var te=document.getElementById("mk-input"),Sn=document.getElementById("mk-send");function In(){if(!te||!S)return;let e=te.value;e&&(S.sendInput(e+"\r"),te.value="",te.rows=1,S.focus())}if(te&&(te.addEventListener("input",()=>{te.rows=1;let e=te.value.split(`
|
|
54
|
+
`).length;te.rows=Math.min(e,4)}),te.addEventListener("keydown",e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),In())})),Sn&&Sn.addEventListener("click",In),window.visualViewport){let e=document.querySelector(".app-layout"),t=()=>{e&&(e.style.height=window.visualViewport.height+"px"),window.scrollTo(0,0),document.documentElement.scrollTop=0,document.body.scrollTop=0};window.visualViewport.addEventListener("resize",t),window.addEventListener("orientationchange",()=>setTimeout(t,100)),document.addEventListener("touchstart",()=>{(window.scrollY>0||document.documentElement.scrollTop>0)&&window.scrollTo(0,0)},{passive:!0})}var Mt=document.getElementById("process-panel"),je=document.getElementById("proc-list"),Vi=document.getElementById("proc-close"),Dt=document.getElementById("proc-backdrop"),Ki=document.getElementById("header-ram");function Xi(){je.innerHTML='<div class="proc-empty">Loading\u2026</div>',fetch(N("/api/system/processes")).then(e=>e.json()).then(e=>{if(!Array.isArray(e)||!e.length){je.innerHTML='<div class="proc-empty">No processes</div>';return}let t="";for(let n of e){let i=n.rss,a=i<1048576?(i/1024).toFixed(0)+"K":(i/1048576).toFixed(1)+"M";t+='<div class="proc-row" data-pid="'+n.pid+'"><span class="proc-mem">'+n.mem+'%</span><span class="proc-rss">'+a+'</span><span class="proc-cmd" title="'+C(n.command)+'">'+C(n.command)+'</span><button class="proc-kill" title="Kill PID '+n.pid+'">×</button></div>'}je.innerHTML=t;for(let n of je.querySelectorAll(".proc-row")){let i=n.querySelector(".proc-kill");i&&i.addEventListener("click",a=>{let r=a.target.closest(".proc-row");!r||!confirm("Kill PID "+r.dataset.pid+"?")||fetch(N("/api/system/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:parseInt(r.dataset.pid,10)})}).then(o=>o.json()).then(o=>{o.ok?r.style.opacity="0.3":alert("Failed: "+(o.error||"unknown"))}).catch(()=>alert("Network error"))})}}).catch(()=>{je.innerHTML='<div class="proc-empty">Failed to load</div>'})}function Qi(){Mt.classList.add("open"),Dt.classList.add("open"),Xi()}function ut(){Mt.classList.remove("open"),Dt.classList.remove("open")}Ki.addEventListener("click",e=>{e.stopPropagation(),Mt.classList.contains("open")?ut():Qi()}),Vi.addEventListener("click",ut),Dt.addEventListener("click",ut);var Zi=2e3,He=null,At=null,be=new Map,we=new Map,Gi=5e3,Bn=new Map;function Ft(e,t){return(t?"a:"+t+":":"l:")+e}function ea(e,t,n){let i=Ft(e,t);if(n==="working"){let u=Bn.get(i);if(u&&Date.now()<u)return}let a=we.get(i),r=e===M&&(t??null)===H,o=n==="idle"&&a?.state==="working";we.set(i,{session:e,agentId:t,state:n,doneUntil:o?Date.now()+Zi:void 0,unread:o?!r:!1});let l=t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',p=k.querySelector(l);p&&pt(p,i,we.get(i))}function pt(e,t,n){let i=be.get(t);i&&(clearTimeout(i),be.delete(t)),e.classList.remove("working","just-done");let a=n.session===M&&(n.agentId??null)===H;n.state==="working"?e.classList.add("working"):a&&n.doneUntil&&Date.now()<n.doneUntil?(e.classList.add("just-done"),be.set(t,setTimeout(()=>{e.classList.remove("just-done"),be.delete(t)},Math.max(0,n.doneUntil-Date.now())))):!a&&n.unread&&e.classList.add("just-done")}function $t(){for(let[e,t]of we){let n=t.agentId?'.session-item[data-agent="'+CSS.escape(t.agentId)+'"][data-session="'+CSS.escape(t.session)+'"]':'.session-item[data-session="'+CSS.escape(t.session)+'"]:not([data-agent])',i=k.querySelector(n);i&&pt(i,e,t)}}function ta(e,t){let n=Ft(e,t),i=we.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])',o=k.querySelector(r);o&&pt(o,n,i)}function Tn(){if(He||At)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 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=()=>{He===n&&(He=null,At=setTimeout(()=>{At=null,Tn()},5e3))},n.onerror=()=>{try{n.close()}catch{}}}catch{He=null}}window.__openSession=Fe,window.__refreshSidebar=ae,ae(),Ae(),$t(),Tn(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&$t()}),setInterval(()=>{document.visibilityState==="visible"&&ae()},1e4),wi();
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
const d={catalog:null,templates:[],bots:[],approvals:[],activeId:null,items:new Map,ws:null,pollTimer:0,renderQueued:!1};function D(){try{return localStorage.getItem("tmux-web-token")||""}catch{return""}}async function f(t,e){const o=await fetch(t,{...e,headers:{"content-type":"application/json",Authorization:`Bearer ${D()}`,...e?.headers||{}}}),i=await o.text(),s=i?JSON.parse(i):null;if(!o.ok)throw new Error(s&&s.error||`HTTP ${o.status}`);return s}function n(t,e,o){const i=document.createElement(t);return e&&(i.className=e),o!==void 0&&(i.textContent=o),i}function tt(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 j(){const t=d.approvals.length,e=document.getElementById("bots-inbox-badge");e&&(e.style.display=t?"inline-block":"none",e.textContent=String(t));const o=document.getElementById("bv-inbox-count");o&&(o.textContent=t?`(${t})`:""),window.__botsSnapshot=d.bots,window.__refreshSidebar?.()}function et(){const t=document.getElementById("set-bot-templates"),e=document.getElementById("set-bot-new"),o=document.getElementById("set-bot-inbox"),i=()=>{document.getElementById("settings-popover")?.classList.remove("open"),document.getElementById("settings-backdrop")?.classList.remove("open")};t?.addEventListener("click",()=>{i(),A()}),e?.addEventListener("click",()=>{i(),ut()}),o?.addEventListener("click",()=>{i(),Q()})}function nt(){const t=n("div","bots-view");t.id="bots-view",t.hidden=!0;const e=n("div","bots-view-head"),o=n("div","bv-title"),i=n("span","bots-dot");i.id="bv-dot";const s=n("span","bv-title-text");s.id="bv-title";const l=n("span","bv-status");l.id="bv-status",o.append(i,s,l);const a=n("div","bv-actions"),p=n("div","bv-mode"),r=n("button","bv-mode-btn");r.id="bv-mode-btn",r.type="button",r.title="\u5BA1\u6279\u6A21\u5F0F\uFF08\u70B9\u5F00\u770B\u8BF4\u660E\uFF09";const u=n("div","bv-mode-menu");u.id="bv-mode-menu",u.hidden=!0;for(const[b,h,M]of[["supervised","\u9ED8\u8BA4","\u53EA\u8BFB\u5DE5\u5177\uFF08read/grep/find/ls\uFF09\u76F4\u63A5\u653E\u884C\uFF1Bbash\u3001edit\u3001write\u3001\u6269\u5C55/MCP \u5DE5\u5177\u4F1A\u95EE\u4F60"],["parent-supervised","\u76D1\u7BA1","\u5176\u4F59\u5DE5\u5177\u4EA4\u7ED9\u4E0A\u7EA7 bot \u51B3\u5B9A\uFF08\u5E26\u7406\u7531\uFF09\uFF1B\u4F60\u4ECD\u7136\u80FD\u770B\u5230\u5E76\u56DE\u7B54\uFF0C\u5148\u7B54\u5148\u5F97\uFF1B\u6CA1\u6709\u4E0A\u7EA7\u65F6\u56DE\u843D\u5230\u9ED8\u8BA4"],["full-access","\u5168\u653E\u884C","\u6240\u6709\u5DE5\u5177\u76F4\u63A5\u6267\u884C\uFF0C\u4E0D\u518D\u8BE2\u95EE\u3002\u6CE8\u610F\u8FD9\u4E0D\u662F\u6C99\u7BB1"]]){const c=n("button");c.dataset.mode=b,c.innerHTML=`<b>${h}</b><span>${M}</span>`,c.onclick=()=>{u.hidden=!0,ot(b)},u.appendChild(c)}r.onclick=b=>{b.stopPropagation(),u.hidden=!u.hidden},p.append(r,u),document.addEventListener("click",b=>{p.contains(b.target)||(u.hidden=!0)});const m=n("button","btn","Allow all");m.id="bv-allow-all",m.title="Approve every pending request for this bot",m.onclick=()=>{if(!d.activeId)return;const b=d.approvals.filter(h=>h.botId===d.activeId);Promise.all(b.map(h=>f(`/api/bots/${h.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:h.id,allow:!0})}))).finally(()=>void S(!0))};const v=n("button","btn","Needs you "),I=n("span");I.id="bv-inbox-count",v.appendChild(I),v.onclick=()=>void Q();const x=n("button","btn","Resume");x.onclick=()=>void z(b=>f(`/api/bots/${b}/resume`,{method:"POST"}).then(()=>S(!0)));const C=n("button","btn danger","Stop");C.onclick=()=>void z(b=>f(`/api/bots/${b}/stop`,{method:"POST"}).then(()=>S(!0)));const y=n("button","btn","Delete");y.onclick=()=>{d.activeId&&confirm("Delete this bot and its session?")&&f(`/api/bots/${d.activeId}`,{method:"DELETE"}).then(()=>{_(),S(!0)})};const E=n("button","btn","\u2715");E.onclick=()=>_(),a.append(p,m,v,x,C,y,E),e.append(o,a);const O=n("div","bots-messages");O.id="bots-messages";const $=n("div","bots-composer"),w=n("textarea");w.id="bots-input",w.rows=1,w.placeholder="Message the bot\u2026 (Enter to send, Shift+Enter for newline)",w.onkeydown=b=>{b.key==="Enter"&&!b.shiftKey&&(b.preventDefault(),F())};const P=n("button","btn primary","Send");P.onclick=()=>void F(),$.append(w,P),t.append(e,O,$),document.querySelector(".main-area")?.appendChild(t),document.getElementById("bots-modal")||ct()}async function F(){const t=document.getElementById("bots-input");if(!t||!d.activeId||!t.value.trim())return;const e=t.value;t.value="";try{await f(`/api/bots/${d.activeId}/input`,{method:"POST",body:JSON.stringify({text:e})})}catch(o){B({kind:"notice",level:"error",text:o instanceof Error?o.message:String(o)})}}function z(t){d.activeId&&t(d.activeId).catch(e=>B({kind:"notice",level:"error",text:e instanceof Error?e.message:String(e)}))}function _(){d.activeId=null;const t=document.getElementById("bots-view");t&&(t.hidden=!0);try{d.ws?.close()}catch{}d.ws=null,j();const e=document.getElementById("terminal-container"),o=document.getElementById("main-placeholder"),i=!!document.querySelector(".session-item.active:not(.bot-item)");e&&i?(e.style.display="",o&&(o.style.display="none")):o&&(o.style.display="")}async function G(t){d.activeId=t,d.items.set(t,[]);const e=document.getElementById("bots-view");e&&(e.hidden=!1);const o=document.getElementById("main-placeholder");o&&(o.style.display="none");const i=document.getElementById("terminal-container");i&&(i.style.display="none");const s=document.getElementById("file-editor");s&&(s.style.display="none"),j(),H();try{d.ws?.close()}catch{}const l=location.protocol==="https:"?"wss:":"ws:",a=new WebSocket(`${l}//${location.host}/ws/bots/${encodeURIComponent(t)}?token=${encodeURIComponent(D())}`);d.ws=a,a.onmessage=p=>{try{V(JSON.parse(String(p.data)))}catch{}},a.onclose=()=>{d.activeId===t&&setTimeout(()=>{d.activeId===t&&S(!0)},1500)},await S(!0)}function R(){return d.bots.find(t=>t.id===d.activeId)||null}function q(){const t=R();if(!t)return;const e=document.getElementById("bv-title"),o=document.getElementById("bv-status"),i=document.getElementById("bv-dot");e&&(e.textContent=t.title),o&&(o.textContent=`${t.status.replace(/_/g," ")} \xB7 ${t.templateId} \xB7 ${t.projectPath}`);const s=document.getElementById("bv-mode-btn");s&&t.runtimeMode&&(s.textContent=`${K[t.runtimeMode]||t.runtimeMode} \u25BE`);for(const p of document.querySelectorAll("#bv-mode-menu button"))p.classList.toggle("active",p.dataset.mode===t.runtimeMode);const l=document.getElementById("bv-allow-all"),a=d.approvals.filter(p=>p.botId===t.id).length;l&&(l.hidden=a===0,l.textContent=`Allow all (${a})`),i&&(i.style.background=tt(t.status))}const K={supervised:"\u9ED8\u8BA4","parent-supervised":"\u76D1\u7BA1","full-access":"\u5168\u653E\u884C"};async function ot(t){if(d.activeId)try{await f(`/api/bots/${d.activeId}/mode`,{method:"POST",body:JSON.stringify({mode:t})});const e=R();e&&(e.runtimeMode=t),q(),B({kind:"notice",level:"info",text:`\u5BA1\u6279\u6A21\u5F0F\uFF1A${K[t]||t}`})}catch(e){B({kind:"notice",level:"error",text:e instanceof Error?e.message:String(e)})}}function B(t,e=d.activeId){if(!e)return;const o=d.items.get(e)||[];o.push(t),d.items.set(e,o),e===d.activeId&&T()}function T(){d.renderQueued||(d.renderQueued=!0,requestAnimationFrame(()=>{d.renderQueued=!1,H()}))}function H(){const t=document.getElementById("bots-messages");if(!t||!d.activeId)return;const e=d.items.get(d.activeId)||[];t.textContent="";let o=null;for(const i of e)if(i.kind==="user"){const s=n("div","bv-msg bv-user");s.textContent=i.text,t.appendChild(s),o=null}else if(i.kind==="assistant"){const s=n("div","bv-msg bv-assistant");if(i.thinking){const a=n("details","bv-thinking");a.appendChild(n("summary",void 0,"thinking")),a.appendChild(n("div",void 0,i.thinking)),s.appendChild(a)}const l=n("div","bv-text");l.textContent=i.text,s.appendChild(l),t.appendChild(s),o=l}else if(i.kind==="tool")t.appendChild(it(i)),o=null;else if(i.kind==="approval")t.appendChild(st(i)),o=null;else if(i.kind==="notice"){const s=n("div",`bv-notice bv-notice-${i.level}`,i.text);t.appendChild(s)}o&&(o.scrollTop=o.scrollHeight),t.scrollTop=t.scrollHeight}function it(t){const e=n("details","bv-tool");e.open=t.phase!=="end"||!!t.isError;const o=n("summary"),i=n("span","bv-tool-name",t.name);if(o.appendChild(i),t.phase!=="end"&&o.appendChild(n("span","bv-tool-phase",t.phase)),t.isError&&o.appendChild(n("span","bv-tool-error","error")),typeof t.durationMs=="number"&&o.appendChild(n("span","bv-tool-meta",`${Math.round(t.durationMs)}ms`)),e.appendChild(o),t.args!==void 0){const s=n("pre","bv-pre");s.textContent=typeof t.args=="string"?t.args:JSON.stringify(t.args,null,2),e.appendChild(s)}if(t.output){const s=n("pre","bv-pre bv-output");s.textContent=t.output,e.appendChild(s)}return e}function st(t){const e=n("div","bv-approval"),o=t.approval;if(e.appendChild(n("div","bv-approval-title",o.title)),o.message&&e.appendChild(n("pre","bv-pre",o.message)),t.decided)return e.appendChild(n("div","bv-approval-decided",t.decided==="allowed"?"Allowed":"Denied")),e;const i=n("input","bv-reason");i.placeholder="reason (optional)";const s=n("div","bv-approval-actions"),l=n("button","btn primary","Allow"),a=n("button","btn",o.method==="confirm"&&/^Allow (.+?)\?$/.test(o.title)?`Always allow ${/^Allow (.+?)\?$/.exec(o.title)?.[1]}`:"Always allow");a.hidden=o.method!=="confirm";const p=n("button","btn danger","Deny"),r=async(u,m=!1)=>{try{await f(`/api/bots/${o.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:o.id,allow:u,always:m,reason:i.value||void 0})}),t.decided=u?"allowed":"denied",T(),S(!0)}catch(v){B({kind:"notice",level:"error",text:v instanceof Error?v.message:String(v)})}};return l.onclick=()=>void r(!0),a.onclick=()=>void r(!0,!0),p.onclick=()=>void r(!1),s.append(i,l,a,p),e.appendChild(s),e}function V(t){const e=String(t.type||""),o=d.activeId;if(!o)return;const i=d.items.get(o)||[];if(e==="snapshot")d.items.set(o,[]);else if(e==="user")B({kind:"user",text:String(t.text||"")});else if(e==="status"){const s=R();s&&(s.status=String(t.status||s.status)),q(),lt()}else if(e==="message"){const s=t.message;if(!s||String(s.role||"")!=="assistant")return;const a=at(s),p=dt(s),r=i[i.length-1];r&&r.kind==="assistant"?(r.text=a||r.text,r.thinking=p||r.thinking):i.push({kind:"assistant",text:a,thinking:p}),d.items.set(o,i),T()}else if(e==="delta"){const s=String(t.kind||""),l=String(t.delta||"");let a=i[i.length-1];(!a||a.kind!=="assistant")&&(i.push({kind:"assistant",text:"",thinking:""}),a=i[i.length-1]),a.kind==="assistant"&&(s==="text"?a.text+=l:s==="thinking"&&(a.thinking+=l)),d.items.set(o,i),T()}else if(e==="tool"){const s=String(t.callId||""),l=i.find(p=>p.kind==="tool"&&p.callId===s),a=String(t.phase||"start");l?(l.phase=a,a==="update"&&t.output&&(l.output=String(t.output)),a==="end"&&(t.output&&(l.output=String(t.output)),l.isError=t.isError===!0,typeof t.durationMs=="number"&&(l.durationMs=t.durationMs))):i.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}),d.items.set(o,i),T()}else if(e==="approval"){const s=t.approval;if(!s)return;const l=i;for(let a=l.length-1;a>=0;a--){const p=l[a];if(p.kind==="approval"&&p.approval.id===s.id){p.approval=s,s.state!=="pending"&&(p.decided=s.state==="allowed"?"allowed":"denied"),d.items.set(o,l),T();return}}l.push({kind:"approval",approval:s}),d.items.set(o,l),T()}else e==="notice"&&B({kind:"notice",level:String(t.level||"info"),text:String(t.text||"")})}function at(t){const e=t.content;return Array.isArray(e)?e.map(o=>o&&typeof o=="object"&&o.type==="text"?String(o.text||""):"").join(""):String(t.text||"")}function dt(t){const e=t.content;return Array.isArray(e)?e.map(o=>o&&typeof o=="object"&&o.type==="thinking"?String(o.thinking||""):"").join(""):""}async function S(t=!1){try{const[e,o]=await Promise.all([f("/api/bots"),f("/api/bots/approvals")]);if(d.bots=e,d.approvals=o,j(),q(),t&&d.activeId){const i=await f(`/api/bots/${d.activeId}/events?limit=300`);rt(i)}}catch{}}async function lt(){try{d.bots=await f("/api/bots"),j()}catch{}}function rt(t){if(d.activeId){d.items.set(d.activeId,[]);for(const e of t)V(e);H()}}function ct(){const t=n("div","bots-modal");t.id="bots-modal",t.hidden=!0;const e=n("div","bots-modal-card"),o=n("div","bots-modal-head"),i=n("span");i.id="bots-modal-title";const s=n("button","btn","\u2715");s.onclick=()=>J(),o.append(i,s);const l=n("div","bots-modal-body");l.id="bots-modal-body",e.append(o,l),t.appendChild(e),t.onclick=a=>{a.target===t&&J()},document.body.appendChild(t)}function W(t){const e=document.getElementById("bots-modal"),o=document.getElementById("bots-modal-title"),i=document.getElementById("bots-modal-body");if(!e||!i)throw new Error("modal missing");return o&&(o.textContent=t),i.textContent="",e.hidden=!1,i}function J(){const t=document.getElementById("bots-modal");t&&(t.hidden=!0)}async function pt(){return d.catalog||(d.catalog=await f("/api/bots/catalog")),d.catalog}async function Y(){return d.templates=await f("/api/bots/templates"),d.templates}async function A(){const t=W("Bot templates"),[e,o]=await Promise.all([pt(),Y()]),i=n("div","bv-template-list");for(const r of o){const u=n("div","bv-template-row");u.appendChild(n("span","bv-template-name",r.manifest.name)),u.appendChild(n("span","bv-template-desc",r.manifest.description||""));const m=n("button","btn","Edit");m.onclick=()=>X(t,e,r);const v=n("button","btn","Copy");v.title="Duplicate this template",v.onclick=()=>{const C=JSON.parse(JSON.stringify(r.manifest));C.name=`${r.manifest.name} copy`,f("/api/bots/templates",{method:"POST",body:JSON.stringify({manifest:C})}).then(()=>A()).catch(y=>alert(y instanceof Error?y.message:String(y)))};const I=n("button","btn danger","Delete");I.onclick=()=>{confirm(`Delete template ${r.manifest.name}?`)&&f(`/api/bots/templates/${r.id}`,{method:"DELETE"}).then(()=>A())};const x=n("span","bv-template-actions");x.append(m,v,I),u.appendChild(x),i.appendChild(u)}o.length===0&&i.appendChild(n("div","bots-empty","No templates yet")),t.appendChild(i);const s=n("div","bv-template-actions"),l=n("button","btn primary","New template");l.onclick=()=>X(t,e,null);const a=n("button","btn","Export");a.title="Download templates + library as JSON",a.onclick=()=>{(async()=>{try{const r=await fetch("/api/bots/export",{headers:{Authorization:`Bearer ${D()}`}});if(!r.ok)throw new Error(`HTTP ${r.status}`);const u=await r.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(r){alert(r instanceof Error?r.message:String(r))}})()};const p=n("button","btn","Import");p.title="Restore templates from a JSON bundle",p.onclick=()=>{const r=document.createElement("input");r.type="file",r.accept="application/json,.json",r.onchange=()=>{const u=r.files?.[0];u&&(async()=>{try{const m=JSON.parse(await u.text()),v=await f("/api/bots/import",{method:"POST",body:JSON.stringify(m)});alert(`Imported ${v.templates} templates, ${v.files} library files (${v.skipped} kept)`),await A()}catch(m){alert(m instanceof Error?m.message:String(m))}})()},r.click()},s.append(l,a,p),t.appendChild(s)}function U(t,e,o){const i=n("div","bv-field");i.appendChild(n("label","bv-label",t));const s=n("div","bv-check-grid"),l=[];for(const a of e){const p=n("label","bv-check"),r=document.createElement("input");r.type="checkbox",r.checked=o.includes(a.id),p.append(r,n("span",void 0,a.label)),a.hint&&(p.title=a.hint),s.appendChild(p),l.push({id:a.id,input:r})}return i.appendChild(s),{element:i,get:()=>l.filter(a=>a.input.checked).map(a=>a.id)}}function X(t,e,o){t.textContent="";const i=o?JSON.parse(JSON.stringify(o.manifest)):{name:"new-bot",description:""},s=n("input","bv-input");s.value=i.name,s.placeholder="Template name";const l=n("input","bv-input");l.value=i.description||"",l.placeholder="One line description";const a=n("textarea","bv-textarea");a.rows=6,a.value=i.system||"",a.placeholder="System prompt for this bot (written to SYSTEM.md)";const p=U("Skills",e.skills.map(c=>({id:c.id,label:c.name,hint:c.description})),i.skills||[]),r=U("Extensions (Pi builtins + library)",e.extensions.map(c=>({id:c.id,label:`${c.name}${c.kind==="builtin"?" (builtin)":""}`,hint:c.description})),(i.extensions||[]).map(c=>c.replace(/^.*\//,"").replace(/\.(js|ts)$/,""))),u=U("Prompt templates",e.prompts.map(c=>({id:c.id,label:c.name})),i.prompts||[]),m=n("select","bv-input");m.appendChild(new Option("none",""));for(const c of e.mcp)m.appendChild(new Option(c.name,c.id));i.mcp&&(m.value=e.mcp.find(c=>JSON.stringify(c.servers)===JSON.stringify(i.mcp?.mcpServers))?.id||"");const v=n("div","bv-field");v.appendChild(n("label","bv-label","Tools (allow list; deny always blocks)"));const I=n("div","bv-check-grid"),x=[];for(const c of e.tools){const N=n("label","bv-check"),k=document.createElement("input");k.type="checkbox",k.checked=(i.tools?.allow||[]).includes(c.name)||!i.tools?.allow?.length&&["read","grep","find","ls","edit","write","bash"].includes(c.name),N.append(k,n("span",void 0,c.name)),I.appendChild(N),x.push({name:c.name,input:k})}v.appendChild(I);const C=n("input","bv-input");C.value=(i.tools?.deny||[]).join(", "),C.placeholder="Always deny (comma separated), e.g. bash, write";const y=n("textarea","bv-textarea");y.rows=2,y.value=(i.packages||[]).join(`
|
|
2
|
-
`),y.placeholder="Pi packages, one per line (npm:@scope/pkg@1.2.3, git:..., ./path)";const E=
|
|
1
|
+
const a={catalog:null,templates:[],bots:[],approvals:[],activeId:null,items:new Map,ws:null,pollTimer:0,renderQueued:!1};function D(){try{return localStorage.getItem("tmux-web-token")||""}catch{return""}}async function f(t,e){const n=await fetch(t,{...e,headers:{"content-type":"application/json",Authorization:`Bearer ${D()}`,...e?.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 o(t,e,n){const i=document.createElement(t);return e&&(i.className=e),n!==void 0&&(i.textContent=n),i}function et(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 P(){const t=document.getElementById("bots-view");if(!t)return;const e=window.visualViewport,n=window.matchMedia("(max-width: 640px)").matches,i=!document.querySelector(".sidebar")?.classList.contains("collapsed");if(a.activeId&&e&&n&&!i){const s=document.querySelector(".fixed-header"),l=s?Math.round(s.getBoundingClientRect().height):0;t.style.position="fixed",t.style.top=`${Math.round(e.offsetTop)+l}px`,t.style.left=`${Math.round(e.offsetLeft)}px`,t.style.width=`${Math.round(e.width)}px`,t.style.height=`${Math.max(120,Math.round(e.height)-l)}px`,t.style.right="auto",t.style.bottom="auto"}else t.style.position="",t.style.top="",t.style.left="",t.style.width="",t.style.height="",t.style.right="",t.style.bottom=""}window.visualViewport?.addEventListener("resize",P),window.visualViewport?.addEventListener("scroll",P),window.addEventListener("resize",P),document.addEventListener("click",()=>setTimeout(P,0));function L(){const t=a.approvals.length,e=document.getElementById("bots-inbox-badge");e&&(e.style.display=t?"inline-block":"none",e.textContent=String(t));const n=document.getElementById("bv-inbox-count");n&&(n.textContent=t?`(${t})`:""),window.__botsSnapshot=a.bots,window.__refreshSidebar?.()}function nt(){const t=document.getElementById("set-bot-templates"),e=document.getElementById("set-bot-new"),n=document.getElementById("set-bot-inbox"),i=()=>{document.getElementById("settings-popover")?.classList.remove("open"),document.getElementById("settings-backdrop")?.classList.remove("open")};t?.addEventListener("click",()=>{i(),A()}),e?.addEventListener("click",()=>{i(),mt()}),n?.addEventListener("click",()=>{i(),z()})}function ot(){const t=o("div","bots-view");t.id="bots-view",t.hidden=!0;const e=o("div","bots-view-head"),n=o("div","bv-title"),i=o("span","bots-dot");i.id="bv-dot";const s=o("span","bv-title-text");s.id="bv-title";const l=o("span","bv-status");l.id="bv-status",n.append(i,s,l);const d=o("div","bv-actions"),p=o("div","bv-mode"),r=o("button","bv-mode-btn");r.id="bv-mode-btn",r.type="button",r.title="\u5BA1\u6279\u6A21\u5F0F\uFF08\u70B9\u5F00\u770B\u8BF4\u660E\uFF09";const u=o("div","bv-mode-menu");u.id="bv-mode-menu",u.hidden=!0;for(const[b,h,j]of[["supervised","\u9ED8\u8BA4","\u53EA\u8BFB\u5DE5\u5177\uFF08read/grep/find/ls\uFF09\u76F4\u63A5\u653E\u884C\uFF1Bbash\u3001edit\u3001write\u3001\u6269\u5C55/MCP \u5DE5\u5177\u4F1A\u95EE\u4F60"],["parent-supervised","\u76D1\u7BA1","\u5176\u4F59\u5DE5\u5177\u4EA4\u7ED9\u4E0A\u7EA7 bot \u51B3\u5B9A\uFF08\u5E26\u7406\u7531\uFF09\uFF1B\u4F60\u4ECD\u7136\u80FD\u770B\u5230\u5E76\u56DE\u7B54\uFF0C\u5148\u7B54\u5148\u5F97\uFF1B\u6CA1\u6709\u4E0A\u7EA7\u65F6\u56DE\u843D\u5230\u9ED8\u8BA4"],["full-access","\u5168\u653E\u884C","\u6240\u6709\u5DE5\u5177\u76F4\u63A5\u6267\u884C\uFF0C\u4E0D\u518D\u8BE2\u95EE\u3002\u6CE8\u610F\u8FD9\u4E0D\u662F\u6C99\u7BB1"]]){const c=o("button");c.dataset.mode=b,c.innerHTML=`<b>${h}</b><span>${j}</span>`,c.onclick=()=>{u.hidden=!0,it(b)},u.appendChild(c)}r.onclick=b=>{b.stopPropagation(),u.hidden=!u.hidden},p.append(r,u),document.addEventListener("click",b=>{p.contains(b.target)||(u.hidden=!0)});const m=o("button","btn","Allow all");m.id="bv-allow-all",m.title="Approve every pending request for this bot",m.onclick=()=>{if(!a.activeId)return;const b=a.approvals.filter(h=>h.botId===a.activeId);Promise.all(b.map(h=>f(`/api/bots/${h.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:h.id,allow:!0})}))).finally(()=>void S(!0))};const v=o("button","btn","Needs you "),C=o("span");C.id="bv-inbox-count",v.appendChild(C),v.onclick=()=>void z();const I=o("button","btn","Resume");I.onclick=()=>void F(b=>f(`/api/bots/${b}/resume`,{method:"POST"}).then(()=>S(!0)));const x=o("button","btn danger","Stop");x.onclick=()=>void F(b=>f(`/api/bots/${b}/stop`,{method:"POST"}).then(()=>S(!0)));const y=o("button","btn","Delete");y.onclick=()=>{a.activeId&&confirm("Delete this bot and its session?")&&f(`/api/bots/${a.activeId}`,{method:"DELETE"}).then(()=>{R(),S(!0)})};const E=o("button","btn","\u2715");E.onclick=()=>R(),d.append(p,m,v,I,x,y,E),e.append(n,d);const B=o("div","bots-messages");B.id="bots-messages";const O=o("div","bots-composer"),w=o("textarea");w.id="bots-input",w.rows=1,w.placeholder="Message the bot\u2026 (Enter to send, Shift+Enter for newline)",w.onkeydown=b=>{b.key==="Enter"&&!b.shiftKey&&(b.preventDefault(),Q())};const $=o("button","btn primary");$.title="Send",$.setAttribute("aria-label","Send"),$.innerHTML='<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19V5M5 12l7-7 7 7"/></svg>',$.onclick=()=>void Q(),O.append(w,$),t.append(e,B,O),document.querySelector(".main-area")?.appendChild(t),document.getElementById("bots-modal")||pt()}async function Q(){const t=document.getElementById("bots-input");if(!t||!a.activeId||!t.value.trim())return;const e=t.value;t.value="";try{await f(`/api/bots/${a.activeId}/input`,{method:"POST",body:JSON.stringify({text:e})})}catch(n){T({kind:"notice",level:"error",text:n instanceof Error?n.message:String(n)})}}function F(t){a.activeId&&t(a.activeId).catch(e=>T({kind:"notice",level:"error",text:e instanceof Error?e.message:String(e)}))}function R(){a.activeId=null,P();const t=document.getElementById("bots-view");t&&(t.hidden=!0);try{a.ws?.close()}catch{}a.ws=null,L();const e=document.getElementById("terminal-container"),n=document.getElementById("main-placeholder"),i=!!document.querySelector(".session-item.active:not(.bot-item)");e&&i?(e.style.display="",n&&(n.style.display="none")):n&&(n.style.display="")}async function G(t){a.activeId=t,window.__collapseSidebar?.(),P(),a.items.set(t,[]);const e=document.getElementById("bots-view");e&&(e.hidden=!1);const n=document.getElementById("main-placeholder");n&&(n.style.display="none");const i=document.getElementById("terminal-container");i&&(i.style.display="none");const s=document.getElementById("file-editor");s&&(s.style.display="none"),L(),W();try{a.ws?.close()}catch{}const l=location.protocol==="https:"?"wss:":"ws:",d=new WebSocket(`${l}//${location.host}/ws/bots/${encodeURIComponent(t)}?token=${encodeURIComponent(D())}`);a.ws=d,d.onmessage=p=>{try{Y(JSON.parse(String(p.data)))}catch{}},d.onclose=()=>{a.activeId===t&&setTimeout(()=>{a.activeId===t&&S(!0)},1500)},await S(!0)}function q(){return a.bots.find(t=>t.id===a.activeId)||null}function H(){const t=q();if(!t)return;const e=document.getElementById("bv-title"),n=document.getElementById("bv-status"),i=document.getElementById("bv-dot");e&&(e.textContent=t.title),n&&(n.textContent=`${t.status.replace(/_/g," ")} \xB7 ${t.templateId} \xB7 ${t.projectPath}`);const s=document.getElementById("bv-mode-btn");s&&t.runtimeMode&&(s.textContent=`${K[t.runtimeMode]||t.runtimeMode} \u25BE`);for(const p of document.querySelectorAll("#bv-mode-menu button"))p.classList.toggle("active",p.dataset.mode===t.runtimeMode);const l=document.getElementById("bv-allow-all"),d=a.approvals.filter(p=>p.botId===t.id).length;l&&(l.hidden=d===0,l.textContent=`Allow all (${d})`),i&&(i.style.background=et(t.status))}const K={supervised:"\u9ED8\u8BA4","parent-supervised":"\u76D1\u7BA1","full-access":"\u5168\u653E\u884C"};async function it(t){if(a.activeId)try{await f(`/api/bots/${a.activeId}/mode`,{method:"POST",body:JSON.stringify({mode:t})});const e=q();e&&(e.runtimeMode=t),H(),T({kind:"notice",level:"info",text:`\u5BA1\u6279\u6A21\u5F0F\uFF1A${K[t]||t}`})}catch(e){T({kind:"notice",level:"error",text:e instanceof Error?e.message:String(e)})}}function T(t,e=a.activeId){if(!e)return;const n=a.items.get(e)||[];n.push(t),a.items.set(e,n),e===a.activeId&&M()}function M(){a.renderQueued||(a.renderQueued=!0,requestAnimationFrame(()=>{a.renderQueued=!1,W()}))}function W(){const t=document.getElementById("bots-messages");if(!t||!a.activeId)return;const e=a.items.get(a.activeId)||[];t.textContent="";let n=null;for(const i of e)if(i.kind==="user"){const s=o("div","bv-msg bv-user");s.textContent=i.text,t.appendChild(s),n=null}else if(i.kind==="assistant"){const s=o("div","bv-msg bv-assistant");if(i.thinking){const d=o("details","bv-thinking");d.appendChild(o("summary",void 0,"thinking")),d.appendChild(o("div",void 0,i.thinking)),s.appendChild(d)}const l=o("div","bv-text");l.textContent=i.text,s.appendChild(l),t.appendChild(s),n=l}else if(i.kind==="tool")t.appendChild(st(i)),n=null;else if(i.kind==="approval")t.appendChild(at(i)),n=null;else if(i.kind==="notice"){const s=o("div",`bv-notice bv-notice-${i.level}`,i.text);t.appendChild(s)}n&&(n.scrollTop=n.scrollHeight),t.scrollTop=t.scrollHeight}function st(t){const e=o("details","bv-tool");e.open=t.phase!=="end"||!!t.isError;const n=o("summary"),i=o("span","bv-tool-name",t.name);if(n.appendChild(i),t.phase!=="end"&&n.appendChild(o("span","bv-tool-phase",t.phase)),t.isError&&n.appendChild(o("span","bv-tool-error","error")),typeof t.durationMs=="number"&&n.appendChild(o("span","bv-tool-meta",`${Math.round(t.durationMs)}ms`)),e.appendChild(n),t.args!==void 0){const s=o("pre","bv-pre");s.textContent=typeof t.args=="string"?t.args:JSON.stringify(t.args,null,2),e.appendChild(s)}if(t.output){const s=o("pre","bv-pre bv-output");s.textContent=t.output,e.appendChild(s)}return e}function at(t){const e=o("div","bv-approval"),n=t.approval;if(e.appendChild(o("div","bv-approval-title",n.title)),n.message&&e.appendChild(o("pre","bv-pre",n.message)),t.decided)return e.appendChild(o("div","bv-approval-decided",t.decided==="allowed"?"Allowed":"Denied")),e;const i=o("input","bv-reason");i.placeholder="reason (optional)";const s=o("div","bv-approval-actions"),l=o("button","btn primary","Allow"),d=o("button","btn",n.method==="confirm"&&/^Allow (.+?)\?$/.test(n.title)?`Always allow ${/^Allow (.+?)\?$/.exec(n.title)?.[1]}`:"Always allow");d.hidden=n.method!=="confirm";const p=o("button","btn danger","Deny"),r=async(u,m=!1)=>{try{await f(`/api/bots/${n.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:n.id,allow:u,always:m,reason:i.value||void 0})}),t.decided=u?"allowed":"denied",M(),S(!0)}catch(v){T({kind:"notice",level:"error",text:v instanceof Error?v.message:String(v)})}};return l.onclick=()=>void r(!0),d.onclick=()=>void r(!0,!0),p.onclick=()=>void r(!1),s.append(i,l,d,p),e.appendChild(s),e}function Y(t){const e=String(t.type||""),n=a.activeId;if(!n)return;const i=a.items.get(n)||[];if(e==="snapshot")a.items.set(n,[]);else if(e==="user")T({kind:"user",text:String(t.text||"")});else if(e==="status"){const s=q();s&&(s.status=String(t.status||s.status)),H(),rt()}else if(e==="message"){const s=t.message;if(!s||String(s.role||"")!=="assistant")return;const d=dt(s),p=lt(s),r=i[i.length-1];r&&r.kind==="assistant"?(r.text=d||r.text,r.thinking=p||r.thinking):i.push({kind:"assistant",text:d,thinking:p}),a.items.set(n,i),M()}else if(e==="delta"){const s=String(t.kind||""),l=String(t.delta||"");let d=i[i.length-1];(!d||d.kind!=="assistant")&&(i.push({kind:"assistant",text:"",thinking:""}),d=i[i.length-1]),d.kind==="assistant"&&(s==="text"?d.text+=l:s==="thinking"&&(d.thinking+=l)),a.items.set(n,i),M()}else if(e==="tool"){const s=String(t.callId||""),l=i.find(p=>p.kind==="tool"&&p.callId===s),d=String(t.phase||"start");l?(l.phase=d,d==="update"&&t.output&&(l.output=String(t.output)),d==="end"&&(t.output&&(l.output=String(t.output)),l.isError=t.isError===!0,typeof t.durationMs=="number"&&(l.durationMs=t.durationMs))):i.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:d}),a.items.set(n,i),M()}else if(e==="approval"){const s=t.approval;if(!s)return;const l=i;for(let d=l.length-1;d>=0;d--){const p=l[d];if(p.kind==="approval"&&p.approval.id===s.id){p.approval=s,s.state!=="pending"&&(p.decided=s.state==="allowed"?"allowed":"denied"),a.items.set(n,l),M();return}}l.push({kind:"approval",approval:s}),a.items.set(n,l),M()}else e==="notice"&&T({kind:"notice",level:String(t.level||"info"),text:String(t.text||"")})}function dt(t){const e=t.content;return Array.isArray(e)?e.map(n=>n&&typeof n=="object"&&n.type==="text"?String(n.text||""):"").join(""):String(t.text||"")}function lt(t){const e=t.content;return Array.isArray(e)?e.map(n=>n&&typeof n=="object"&&n.type==="thinking"?String(n.thinking||""):"").join(""):""}async function S(t=!1){try{const[e,n]=await Promise.all([f("/api/bots"),f("/api/bots/approvals")]);if(a.bots=e,a.approvals=n,L(),H(),t&&a.activeId){const i=await f(`/api/bots/${a.activeId}/events?limit=300`);ct(i)}}catch{}}async function rt(){try{a.bots=await f("/api/bots"),L()}catch{}}function ct(t){if(a.activeId){a.items.set(a.activeId,[]);for(const e of t)Y(e);W()}}function pt(){const t=o("div","bots-modal");t.id="bots-modal",t.hidden=!0;const e=o("div","bots-modal-card"),n=o("div","bots-modal-head"),i=o("span");i.id="bots-modal-title";const s=o("button","btn","\u2715");s.onclick=()=>J(),n.append(i,s);const l=o("div","bots-modal-body");l.id="bots-modal-body",e.append(n,l),t.appendChild(e),t.onclick=d=>{d.target===t&&J()},document.body.appendChild(t)}function U(t){const e=document.getElementById("bots-modal"),n=document.getElementById("bots-modal-title"),i=document.getElementById("bots-modal-body");if(!e||!i)throw new Error("modal missing");return n&&(n.textContent=t),i.textContent="",e.hidden=!1,i}function J(){const t=document.getElementById("bots-modal");t&&(t.hidden=!0)}async function ut(){return a.catalog||(a.catalog=await f("/api/bots/catalog")),a.catalog}async function X(){return a.templates=await f("/api/bots/templates"),a.templates}async function A(){const t=U("Bot templates"),[e,n]=await Promise.all([ut(),X()]),i=o("div","bv-template-list");for(const r of n){const u=o("div","bv-template-row");u.appendChild(o("span","bv-template-name",r.manifest.name)),u.appendChild(o("span","bv-template-desc",r.manifest.description||""));const m=o("button","btn","Edit");m.onclick=()=>Z(t,e,r);const v=o("button","btn","Copy");v.title="Duplicate this template",v.onclick=()=>{const x=JSON.parse(JSON.stringify(r.manifest));x.name=`${r.manifest.name} copy`,f("/api/bots/templates",{method:"POST",body:JSON.stringify({manifest:x})}).then(()=>A()).catch(y=>alert(y instanceof Error?y.message:String(y)))};const C=o("button","btn danger","Delete");C.onclick=()=>{confirm(`Delete template ${r.manifest.name}?`)&&f(`/api/bots/templates/${r.id}`,{method:"DELETE"}).then(()=>A())};const I=o("span","bv-template-actions");I.append(m,v,C),u.appendChild(I),i.appendChild(u)}n.length===0&&i.appendChild(o("div","bots-empty","No templates yet")),t.appendChild(i);const s=o("div","bv-template-actions"),l=o("button","btn primary","New template");l.onclick=()=>Z(t,e,null);const d=o("button","btn","Export");d.title="Download templates + library as JSON",d.onclick=()=>{(async()=>{try{const r=await fetch("/api/bots/export",{headers:{Authorization:`Bearer ${D()}`}});if(!r.ok)throw new Error(`HTTP ${r.status}`);const u=await r.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(r){alert(r instanceof Error?r.message:String(r))}})()};const p=o("button","btn","Import");p.title="Restore templates from a JSON bundle",p.onclick=()=>{const r=document.createElement("input");r.type="file",r.accept="application/json,.json",r.onchange=()=>{const u=r.files?.[0];u&&(async()=>{try{const m=JSON.parse(await u.text()),v=await f("/api/bots/import",{method:"POST",body:JSON.stringify(m)});alert(`Imported ${v.templates} templates, ${v.files} library files (${v.skipped} kept)`),await A()}catch(m){alert(m instanceof Error?m.message:String(m))}})()},r.click()},s.append(l,d,p),t.appendChild(s)}function V(t,e,n){const i=o("div","bv-field");i.appendChild(o("label","bv-label",t));const s=o("div","bv-check-grid"),l=[];for(const d of e){const p=o("label","bv-check"),r=document.createElement("input");r.type="checkbox",r.checked=n.includes(d.id),p.append(r,o("span",void 0,d.label)),d.hint&&(p.title=d.hint),s.appendChild(p),l.push({id:d.id,input:r})}return i.appendChild(s),{element:i,get:()=>l.filter(d=>d.input.checked).map(d=>d.id)}}function Z(t,e,n){t.textContent="";const i=n?JSON.parse(JSON.stringify(n.manifest)):{name:"new-bot",description:""},s=o("input","bv-input");s.value=i.name,s.placeholder="Template name";const l=o("input","bv-input");l.value=i.description||"",l.placeholder="One line description";const d=o("textarea","bv-textarea");d.rows=6,d.value=i.system||"",d.placeholder="System prompt for this bot (written to SYSTEM.md)";const p=V("Skills",e.skills.map(c=>({id:c.id,label:c.name,hint:c.description})),i.skills||[]),r=V("Extensions (Pi builtins + library)",e.extensions.map(c=>({id:c.id,label:`${c.name}${c.kind==="builtin"?" (builtin)":""}`,hint:c.description})),(i.extensions||[]).map(c=>c.replace(/^.*\//,"").replace(/\.(js|ts)$/,""))),u=V("Prompt templates",e.prompts.map(c=>({id:c.id,label:c.name})),i.prompts||[]),m=o("select","bv-input");m.appendChild(new Option("none",""));for(const c of e.mcp)m.appendChild(new Option(c.name,c.id));i.mcp&&(m.value=e.mcp.find(c=>JSON.stringify(c.servers)===JSON.stringify(i.mcp?.mcpServers))?.id||"");const v=o("div","bv-field");v.appendChild(o("label","bv-label","Tools (allow list; deny always blocks)"));const C=o("div","bv-check-grid"),I=[];for(const c of e.tools){const N=o("label","bv-check"),k=document.createElement("input");k.type="checkbox",k.checked=(i.tools?.allow||[]).includes(c.name)||!i.tools?.allow?.length&&["read","grep","find","ls","edit","write","bash"].includes(c.name),N.append(k,o("span",void 0,c.name)),C.appendChild(N),I.push({name:c.name,input:k})}v.appendChild(C);const x=o("input","bv-input");x.value=(i.tools?.deny||[]).join(", "),x.placeholder="Always deny (comma separated), e.g. bash, write";const y=o("textarea","bv-textarea");y.rows=2,y.value=(i.packages||[]).join(`
|
|
2
|
+
`),y.placeholder="Pi packages, one per line (npm:@scope/pkg@1.2.3, git:..., ./path)";const E=o("select","bv-input");E.appendChild(new Option("default (Pi settings)",""));for(const c of e.models)E.appendChild(new Option(`${c.provider}/${c.model}`,`${c.provider}
|
|
3
3
|
${c.model}`));i.model?.provider&&i.model?.id&&(E.value=`${i.model.provider}
|
|
4
|
-
${i.model.id}`);const
|
|
5
|
-
`),k=e.mcp.find(g=>g.id===m.value),
|
|
6
|
-
`).map(g=>g.trim()).filter(Boolean),mcp:k?{mcpServers:k.servers}:void 0,tools:{allow:
|
|
4
|
+
${i.model.id}`);const B=o("select","bv-input");for(const c of["","off","minimal","low","medium","high","xhigh","max"])B.appendChild(new Option(c||"default",c));i.model?.thinking&&(B.value=i.model.thinking);const O=o("select","bv-input");for(const c of["supervised","auto-accept-edits","full-access"])O.appendChild(new Option(c,c));O.value=i.permissions?.runtimeMode||"supervised";const w=o("select","bv-input");w.appendChild(new Option("ignore project .pi (recommended)","ignore")),w.appendChild(new Option("inherit project .pi (needs trust)","inherit")),w.value=i.projectResources||"ignore";const $=o("label","bv-check"),b=document.createElement("input");b.type="checkbox",b.checked=!!i.orchestrator,$.append(b,o("span",void 0,"Super bot: gets orchestration tools (create/stop/status child bots)"));const h=(c,N)=>{const k=o("div","bv-field");return k.appendChild(o("label","bv-label",c)),k.appendChild(N),k};t.append(h("Name",s),h("Description",l),h("System prompt",d),p.element,r.element,u.element,h("MCP preset",m),v,h("Always deny tools",x),h("Packages",y),h("Model",E),h("Thinking level",B),h("Approval mode",O),h("Project resources",w),$);const j=o("button","btn primary",n?"Save template":"Create template");j.onclick=async()=>{const[c,N]=E.value.split(`
|
|
5
|
+
`),k=e.mcp.find(g=>g.id===m.value),tt={name:s.value.trim()||"bot",description:l.value.trim()||void 0,system:d.value.trim()||void 0,skills:p.get(),extensions:r.get().map(g=>(g.startsWith("builtin:"),g)),prompts:u.get(),packages:y.value.split(`
|
|
6
|
+
`).map(g=>g.trim()).filter(Boolean),mcp:k?{mcpServers:k.servers}:void 0,tools:{allow:I.filter(g=>g.input.checked).map(g=>g.name),deny:x.value.split(",").map(g=>g.trim()).filter(Boolean)},model:c?{provider:c,id:N,thinking:B.value||void 0}:void 0,permissions:{runtimeMode:O.value},projectResources:w.value==="inherit"?"inherit":"ignore",orchestrator:b.checked||void 0};try{await f("/api/bots/templates",{method:"POST",body:JSON.stringify({id:n?.id,manifest:tt})}),J(),await A()}catch(g){alert(g instanceof Error?g.message:String(g))}},t.appendChild(j)}async function mt(){return bt("")}async function bt(t){const e=U("New bot"),n=await X();if(n.length===0){e.appendChild(o("div","bots-empty","Create a template first (\u2699)."));return}const i=o("select","bv-input");for(const u of n)i.appendChild(new Option(u.manifest.name,u.id));const s=o("input","bv-input");s.placeholder="Title (defaults to template name)";const l=o("input","bv-input");l.placeholder="/path/to/project";const d=t||a.bots[0]?.projectPath||"";l.value=d;const p=o("select","bv-input");p.appendChild(new Option("shared \u2014 run in the project folder","shared")),p.appendChild(new Option("worktree \u2014 isolated git worktree","worktree")),e.append(_("Template",i),_("Title",s),_("Project path",l),_("Workspace",p));const r=o("button","btn primary","Create bot");r.onclick=async()=>{try{const u=await f("/api/bots",{method:"POST",body:JSON.stringify({templateId:i.value,title:s.value.trim()||void 0,projectPath:l.value.trim()||void 0,isolation:p.value})});J(),await S(!0),await G(u.id)}catch(u){alert(u instanceof Error?u.message:String(u))}},e.appendChild(r)}function _(t,e){const n=o("div","bv-field");return n.appendChild(o("label","bv-label",t)),n.appendChild(e),n}async function z(){const t=U("Needs you");if(a.approvals=await f("/api/bots/approvals"),a.approvals.length===0){t.appendChild(o("div","bots-empty","Nothing waiting."));return}for(const e of a.approvals){const n=o("div","bv-approval");n.appendChild(o("div","bv-approval-title",`${e.botTitle}: ${e.title}`)),e.message&&n.appendChild(o("pre","bv-pre",e.message));const i=o("input","bv-reason");i.placeholder="reason (optional)";const s=o("div","bv-approval-actions"),l=o("button","btn primary","Allow"),d=o("button","btn danger","Deny"),p=async r=>{await f(`/api/bots/${e.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:e.id,allow:r,reason:i.value||void 0})}),await S(!0),await z()};l.onclick=()=>void p(!0),d.onclick=()=>void p(!1),s.append(i,l,d),n.appendChild(s),t.appendChild(n)}}function ft(){window.__botsInited||(window.__botsInited=!0,ot(),nt(),window.__openBot=G,document.addEventListener("click",t=>{const e=t.target;e&&(e.closest(".session-item.bot-item")||e.closest(".session-item")&&a.activeId&&setTimeout(()=>R(),0))},!0),S(!0),a.pollTimer=window.setInterval(()=>{document.hidden||S()},6e3),window.addEventListener("beforeunload",()=>window.clearInterval(a.pollTimer)))}export{ft as initBots,bt as openNewBotForPath};
|
|
@@ -1,20 +1,20 @@
|
|
|
1
|
-
import{initTerminal as tt}from"./terminal-core.js";import{initBots as nt,openNewBotForPath as st}from"./bots-client.js";const j=window.__TMUX_WEB_SHELL__;let f=null,u=null;const z=typeof window.__TMUX_WEB_SCOPE__?.agentId=="string"?window.__TMUX_WEB_SCOPE__.agentId:null;let h=z;window.__tmuxWebScopeAgent=z;let ye="sessions",x="",
|
|
1
|
+
import{initTerminal as tt}from"./terminal-core.js";import{initBots as nt,openNewBotForPath as st}from"./bots-client.js";const j=window.__TMUX_WEB_SHELL__;let f=null,u=null;const z=typeof window.__TMUX_WEB_SCOPE__?.agentId=="string"?window.__TMUX_WEB_SCOPE__.agentId:null;let h=z;window.__tmuxWebScopeAgent=z;let ye="sessions",x="",Q="",ee="",Ie="";function v(e){return h?"/a/"+encodeURIComponent(h)+e:e}const d=document.getElementById("sidebar-content"),R=document.getElementById("main-placeholder"),w=document.getElementById("terminal-container"),O=document.getElementById("file-editor"),it=document.getElementById("fe-path"),E=document.getElementById("fe-status"),U=document.getElementById("fe-content"),_=document.getElementById("fe-save"),ot=document.getElementById("fe-delete"),at=document.getElementById("fe-back"),xe=document.getElementById("fe-new-name"),lt=document.getElementById("fe-new-btn"),he=document.getElementById("settings-backdrop"),Te=document.getElementById("settings-popover"),Me=document.querySelector(".sidebar"),He="tmux-web-force-narrow";function te(){try{return localStorage.getItem(He)==="1"}catch{return!1}}function Ne(){document.documentElement.classList.toggle("force-narrow",te()),te()&&Re()&&W()}function Re(){return te()?!0:window.matchMedia("(max-width: 640px)").matches}function W(){Re()&&Me.classList.add("collapsed")}function _e(){Me.classList.remove("collapsed")}window.__collapseSidebar=W,document.getElementById("mode-sessions").addEventListener("click",()=>{_e(),$e("sessions")}),document.getElementById("mode-files").addEventListener("click",()=>{_e(),$e("files")});function $e(e){ye=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"?(be="",T()):Et()}let be="";async function T(){if(ye!=="sessions")return;try{const n=await(await fetch("/api/sidebar/sessions")).json(),s=(window.__botsSnapshot||[]).map(o=>[o.id,o.title,o.status,o.projectPath]),i=JSON.stringify({recent:n.recent,agents:n.agents,tombstones:n.tombstones,bots:s});if(i===be)return;be=i,ut(n)}catch{d.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")}),Be()}const Ae="tmux-web-sidebar-group-collapsed";function Pe(){try{return new Set(JSON.parse(localStorage.getItem(Ae)||"[]"))}catch{return new Set}}function ct(e){try{localStorage.setItem(Ae,JSON.stringify([...e]))}catch{}}function rt(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 a=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("/")===a))return a}return s}function dt(e){const t=document.createElement("div");t.className="session-item bot-item",t.setAttribute("data-bot-id",e.id),t.title=`Bot \xB7 ${e.projectPath}`;const n=e.status==="running"?"var(--panel-success)":e.status==="waiting_approval"||e.status==="waiting_input"?"#e0a23c":e.status==="failed"?"var(--panel-danger, #e5534b)":"var(--panel-muted)";return t.innerHTML=`<svg class="bot-icon" viewBox="0 0 24 24" fill="currentColor"><path d="M11 2h2v3h2a3 3 0 0 1 3 3v1h1a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2h-1v1a3 3 0 0 1-3 3H9a3 3 0 0 1-3-3v-1H5a2 2 0 0 1-2-2v-6a2 2 0 0 1 2-2h1V8a3 3 0 0 1 3-3h2V2zm-2 6v1h6V8H9zm-2 5a1.5 1.5 0 1 0 0 3 1.5 1.5 0 0 0 0-3zm10 0a1.5 1.5 0 1 0 0 3 1.5 1.5 0 0 0 0-3z"/></svg><span>${p(e.title)}</span><span class="bot-status-dot" style="background:${n}"></span>`,t.addEventListener("click",s=>{s.stopPropagation(),window.__openBot?.(e.id)}),t}function De(e,t,n,s=!0){const i=new Map;for(const r of e){const g=r.path||"";i.has(g)||i.set(g,[]),i.get(g).push(r)}const o=n?[]:window.__botsSnapshot||[],a=new Map;for(const r of o)i.has(r.projectPath)||i.set(r.projectPath,[]),a.has(r.projectPath)||a.set(r.projectPath,[]),a.get(r.projectPath).push(r);const l=[...i.keys()],c=Pe();for(const[r,g]of i){const H=rt(r,l,t),N=c.has(r),I=document.createElement("div");if(I.className="session-group-header"+(N?" collapsed":""),I.title=r||"No working directory",I.innerHTML=`<span class="sg-folder">📁</span><span class="sg-label">${p(H)}</span>`,!n&&r){const y=document.createElement("button");y.className="sg-add-bot",y.textContent="+",y.title=`New bot in ${r}`,y.addEventListener("click",Z=>{Z.stopPropagation(),Le(r)}),I.appendChild(y)}I.addEventListener("click",()=>{const y=Pe(),Z=I.nextElementSibling;y.has(r)?(y.delete(r),I.classList.remove("collapsed"),Z?.classList.remove("collapsed")):(y.add(r),I.classList.add("collapsed"),Z?.classList.add("collapsed")),ct(y)});const X=document.createElement("div");X.className="session-group-body"+(N?" collapsed":"");for(const y of g)X.appendChild(n?pt(y,n,s):ft(y));for(const y of a.get(r)||[])X.appendChild(dt(y));d.appendChild(I),d.appendChild(X)}}function pt(e,t,n){const s=document.createElement("div");s.className="session-item"+(e.name===u&&h===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
2
|
<span>${p(e.name)}</span>${n?"":'<span class="meta">offline</span>'}
|
|
3
|
-
<button class="session-edit-btn" data-session="${p(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")||
|
|
3
|
+
<button class="session-edit-btn" data-session="${p(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")||F(e.name,t)});const i=s.querySelector(".session-edit-btn");return i&&i.addEventListener("click",o=>{o.stopPropagation(),pe(e.name,i,{agentId:t})}),s}function ft(e){const t=document.createElement("div");t.className="session-item"+(e.name===u&&!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>
|
|
4
4
|
<span>${p(e.name)}</span>
|
|
5
5
|
<button class="session-edit-btn" data-session="${p(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")||
|
|
6
|
+
`,t.addEventListener("click",s=>{s.target.closest(".session-edit-btn")||F(e.name)});const n=t.querySelector(".session-edit-btn");return n&&n.addEventListener("click",s=>{s.stopPropagation(),pe(e.name,n)}),t}function ut(e){d.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"+(z?" clickable":""),n.textContent=z?"\u2190 \u8FD4\u56DE\u672C\u673A":"\u672C\u673A",z&&(n.title="Back to hub",n.addEventListener("click",()=>{window.location.href="/"})),d.appendChild(n),De(t,e.home);const s=e.agents||[];for(const o of s){if(!o.sessions||o.sessions.length===0)continue;const a=o.agentId===h,l=document.createElement("div");l.className="sidebar-section-label machine-label"+(o.online?"":" agent-offline-label")+(!a&&o.online?" clickable":""),l.textContent=o.agentName+(o.online?"":" (offline)"),!a&&o.online&&(l.title="\u6253\u5F00 "+o.agentName,l.addEventListener("click",()=>{window.location.href="/a/"+encodeURIComponent(o.agentId)+"/"})),d.appendChild(l),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",d.appendChild(o);for(const a of i){const l=document.createElement("div");l.className="session-item session-tombstone",l.setAttribute("data-session",a.name),a.agentId&&l.setAttribute("data-agent",a.agentId);const c=a.agentId?a.agentOnline?" (agent)":" (agent \u79BB\u7EBF)":"";l.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"></svg>
|
|
7
7
|
<span>${p(a.name)}</span><span class="meta">\u5931\u6548${c}</span>
|
|
8
|
-
<button class="session-edit-btn" data-session="${p(a.name)}" title="\u6062\u590D\u4F1A\u8BDD"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>`,l.title="\u5931\u6548\u4F1A\u8BDD\uFF1A\u70B9\u51FB\u7BA1\u7406\uFF08\u91CD\u5EFA/\u91CD\u547D\u540D/\u5220\u9664\uFF09",l.addEventListener("click",()=>{pe(a.name,l,{tombstone:!0,agentId:a.agentId})});const r=l.querySelector(".session-edit-btn");r&&r.addEventListener("click",g=>{g.stopPropagation(),pe(a.name,r,{tombstone:!0,agentId:a.agentId})}),d.appendChild(l)}}}function p(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}async function
|
|
8
|
+
<button class="session-edit-btn" data-session="${p(a.name)}" title="\u6062\u590D\u4F1A\u8BDD"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>`,l.title="\u5931\u6548\u4F1A\u8BDD\uFF1A\u70B9\u51FB\u7BA1\u7406\uFF08\u91CD\u5EFA/\u91CD\u547D\u540D/\u5220\u9664\uFF09",l.addEventListener("click",()=>{pe(a.name,l,{tombstone:!0,agentId:a.agentId})});const r=l.querySelector(".session-edit-btn");r&&r.addEventListener("click",g=>{g.stopPropagation(),pe(a.name,r,{tombstone:!0,agentId:a.agentId})}),d.appendChild(l)}}}function p(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}async function F(e,t){if(u===e&&f&&h===(t||null))return;O.style.display="none",R.style.display="none",w.style.display="",w.classList.add("terminal-pending"),W(),f&&(re(),f.destroy(),f=null),u=e,h=t||null,window.__tmuxWebScopeAgent=h,window.__tmuxWebCurrentSession=u,Dt(e,t);const n=Se(e,t);Qe.set(n,Date.now()+At);const s=D.get(n);if(s&&s.state==="working"){s.state="idle",s.doneUntil=void 0,s.unread=!1;const i=d.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&&ge(i,n,s)}for(const i of d.querySelectorAll(".session-item"))i.classList.toggle("active",i.getAttribute("data-session")===e&&(i.getAttribute("data-agent")||null)===h);try{f=await tt(w,e,{terminal:j.terminal,scrollback:j.scrollback,theme:j.theme,wsBase:h?"/ws/a/"+encodeURIComponent(h):j.wsBase||"/ws"}),Je()}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 ne=[],m=null,je=!1;function mt(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 vt(e){je=!0;try{const t=await fetch(v("/api/git/status?path="+encodeURIComponent(e)));t.ok?m=await t.json():m=null}catch{m=null}finally{je=!1}}function gt(){if(!m||!m.branch)return"";const{branch:e,linesAdded:t,linesRemoved:n}=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
|
-
${p(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>"}d.addEventListener("click",e=>{e.target.closest(".sidebar-git")&&A&&m&&(e.stopPropagation(),Fe())});const
|
|
10
|
+
${p(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>"}d.addEventListener("click",e=>{e.target.closest(".sidebar-git")&&A&&m&&(e.stopPropagation(),Fe())});const G=document.getElementById("header-git"),ze=document.getElementById("git-diff-view"),Oe=document.getElementById("gd-path"),se=document.getElementById("gd-status"),ie=document.getElementById("gd-content"),yt=document.getElementById("gd-back");let A=null;function V(e){if(!e||!e.branch){G.style.display="none",A=null;return}A=e.repoRoot;const{branch:t,linesAdded:n,linesRemoved:s}=e;let i=`<span class="branch">${p(t)}</span>`;(n>0||s>0)&&(i+=`<span class="sep">\xB7</span>+<span class="diff-add">${n}</span> <span class="diff-del">-${s}</span>`),G.innerHTML=i,G.style.display="block"}G.addEventListener("click",e=>{A&&m&&(e.stopPropagation(),Fe())});const b=document.getElementById("git-popover"),oe=document.getElementById("git-popover-backdrop");function we(){const e=G.getBoundingClientRect();b.style.top=e.bottom+4+"px",b.style.left=Math.max(8,Math.min(e.left,window.innerWidth-400))+"px"}function Ue(){const e=A,t=document.getElementById("git-popover-browse");t&&t.addEventListener("click",()=>{if(le(),e){ye="files",document.querySelectorAll(".mode-btn").forEach(s=>s.classList.remove("active"));const n=document.getElementById("mode-files");n&&n.classList.add("active"),M(e)}})}let We="";function Fe(){if(!m)return;const e=m.files||[];if(!e.length)b.innerHTML=`<div class="git-popover-header">No changes \u2014 clean working tree</div>
|
|
11
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 a="";switch(s.status){case"M":a='<span class="git-file-status M">M</span>';break;case"A":a='<span class="git-file-status A">A</span>';break;case"D":a='<span class="git-file-status D">D</span>';break;case"?":a='<span class="git-file-status ?">?</span>';break;case"R":a='<span class="git-file-status R">R</span>';break}t+=`<div class="git-popover-item" data-idx="${n}">
|
|
12
12
|
${a}<span class="file-path">${p(s.path)}</span>
|
|
13
13
|
<span class="file-add">${i>0?"+"+i:""}</span>
|
|
14
14
|
<span class="file-del">${o>0?"-"+o:""}</span>
|
|
15
15
|
</div>`}t+='<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>',We=t,b.innerHTML=t,b.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",()=>Ve(i.path)))})}we(),b.classList.add("open"),oe.classList.add("open"),Ue()}function ht(){return window.innerWidth>=1024}function Ge(e,t){const s=(e+(t&&e?`
|
|
16
16
|
`:"")+t).split(`
|
|
17
|
-
`);let i="",o=0,a=0;for(const l of s){const c=l;if(c.startsWith("@@")){const r=c.match(/@@\s+-(\d+)[^+]*\+(\d+)/);r&&(o=parseInt(r[1],10)-1,a=parseInt(r[2],10)-1),i+=`<div class="diff-line hunk"><span class="ln-body">${p(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">${p(c)}</span></div>`);continue}if(c.startsWith("+"))a++,i+=`<div class="diff-line add"><span class="ln-no">${a}</span><span class="ln-body">${p(c)}</span></div>`;else if(c.startsWith("-"))o++,i+=`<div class="diff-line del"><span class="ln-no">${o}</span><span class="ln-body">${p(c)}</span></div>`;else if(c.startsWith("\\"))i+=`<div class="diff-line"><span class="ln-body">${p(c)}</span></div>`;else{if(!c&&!o&&!a)continue;o++,a++,i+=`<div class="diff-line"><span class="ln-no">${o}</span><span class="ln-no" style="margin-right:12px">${a}</span><span class="ln-body">${p(c)}</span></div>`}}return{html:i,lineCount:s.length}}let ae=null;async function Ve(e){const t=A;if(t)if(le(),ht()){w.style.display="none",f&&(re(),f.destroy(),f=null,ae=u,u=null),
|
|
17
|
+
`);let i="",o=0,a=0;for(const l of s){const c=l;if(c.startsWith("@@")){const r=c.match(/@@\s+-(\d+)[^+]*\+(\d+)/);r&&(o=parseInt(r[1],10)-1,a=parseInt(r[2],10)-1),i+=`<div class="diff-line hunk"><span class="ln-body">${p(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">${p(c)}</span></div>`);continue}if(c.startsWith("+"))a++,i+=`<div class="diff-line add"><span class="ln-no">${a}</span><span class="ln-body">${p(c)}</span></div>`;else if(c.startsWith("-"))o++,i+=`<div class="diff-line del"><span class="ln-no">${o}</span><span class="ln-body">${p(c)}</span></div>`;else if(c.startsWith("\\"))i+=`<div class="diff-line"><span class="ln-body">${p(c)}</span></div>`;else{if(!c&&!o&&!a)continue;o++,a++,i+=`<div class="diff-line"><span class="ln-no">${o}</span><span class="ln-no" style="margin-right:12px">${a}</span><span class="ln-body">${p(c)}</span></div>`}}return{html:i,lineCount:s.length}}let ae=null;async function Ve(e){const t=A;if(t)if(le(),ht()){w.style.display="none",f&&(re(),f.destroy(),f=null,ae=u,u=null),V(null),O.style.display="none",R.style.display="none",ze.style.display="flex",Oe.textContent=e,se.textContent="Loading\u2026",ie.innerHTML="";try{const n=await fetch(v("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!n.ok)throw new Error(await n.text());const s=await n.json();wt(e,s.diff,s.stagedDiff)}catch(n){const s=n instanceof Error?n.message:String(n);se.textContent="Error",ie.innerHTML=`<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">Error: ${p(s)}</div>`}}else{b.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">${p(e)}</span>
|
|
20
20
|
<span class="diff-loading">Loading\u2026</span>
|
|
@@ -28,7 +28,7 @@ import{initTerminal as tt}from"./terminal-core.js";import{initBots as nt,openNew
|
|
|
28
28
|
<button class="diff-back">\u2190 Back</button>
|
|
29
29
|
<span class="diff-filename">${p(e)}</span>
|
|
30
30
|
<span class="diff-filesize">${i} lines</span>
|
|
31
|
-
</div><div class="diff-content">${s}</div></div>`,b.querySelector(".diff-back")?.addEventListener("click",()=>{b.innerHTML=We,we(),m&&b.querySelectorAll(".git-popover-item").forEach(o=>{const a=parseInt(o.dataset.idx||"0",10),l=m.files[a];!l||l.status==="D"||(o.style.cursor="pointer",o.addEventListener("click",()=>Ve(l.path)))}),Ue()})}function wt(e,t,n){if(!t&&!n){se.textContent="No diff",ie.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}=Ge(t,n);Oe.textContent=e,se.textContent=i+" lines",ie.innerHTML=s}function Lt(){ze.style.display="none",ae?(w.style.display="",w.classList.add("terminal-pending"),
|
|
31
|
+
</div><div class="diff-content">${s}</div></div>`,b.querySelector(".diff-back")?.addEventListener("click",()=>{b.innerHTML=We,we(),m&&b.querySelectorAll(".git-popover-item").forEach(o=>{const a=parseInt(o.dataset.idx||"0",10),l=m.files[a];!l||l.status==="D"||(o.style.cursor="pointer",o.addEventListener("click",()=>Ve(l.path)))}),Ue()})}function wt(e,t,n){if(!t&&!n){se.textContent="No diff",ie.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}=Ge(t,n);Oe.textContent=e,se.textContent=i+" lines",ie.innerHTML=s}function Lt(){ze.style.display="none",ae?(w.style.display="",w.classList.add("terminal-pending"),F(ae),ae=null):u?(w.style.display="",w.classList.add("terminal-pending"),Je()):R.style.display="flex"}yt.addEventListener("click",Lt);function le(){b.classList.remove("open"),oe.classList.remove("open")}oe.addEventListener("click",le),document.addEventListener("keydown",e=>{e.key==="Escape"&&(le(),ve())});async function qe(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,V(i);return}}}catch{}m=null,V(null)}let ce=null;function Je(){re(),u&&(qe(u),ce=setInterval(()=>{u&&qe(u)},3e4))}function re(){ce&&(clearInterval(ce),ce=null)}async function Le(e){let t=e;if(t.startsWith("~"))try{const s=await(await fetch(v("/api/fs/list?path="+encodeURIComponent(t)))).json();typeof s.path=="string"&&s.path&&(t=s.path)}catch{}t=t.replace(/\/+$/,"")||"/",st(t)}function Ke(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(),Le(t)}),e.appendChild(n)}function Et(){if(ne=j.fsRoots||[],ne.length===0){if(u){kt(u);return}M("");return}d.innerHTML="";for(const e of ne){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> ${p(e)}`,t.addEventListener("click",()=>M(e)),Ke(t,e),d.appendChild(t)}}async function kt(e){d.innerHTML='<div class="file-tree-empty">Loading...</div>';try{const n=await(await fetch(v("/api/fs/session-path?session="+encodeURIComponent(e)))).json();n.path?M(n.path):d.innerHTML='<div class="file-tree-info">Could not determine session directory.</div>'}catch{d.innerHTML='<div class="file-tree-error">Failed to get session directory</div>'}}async function M(e){x=e,d.innerHTML='<div class="file-tree-empty">Loading...</div>';const t=vt(e);try{const s=await(await fetch(v("/api/fs/list?path="+encodeURIComponent(e)))).json(),i=typeof s.path=="string"&&s.path?s.path:e;if(i&&(x=i),await t,d.innerHTML="",i){const 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 Le(i)),d.appendChild(l)}V(m),d.innerHTML+=gt();const o=Ct(i||e);if(o&&!ne.some(c=>i===c)){const c=document.createElement("div");c.className="file-tree-item",c.innerHTML="..",c.addEventListener("click",()=>M(o)),d.appendChild(c)}if(s.dirs)for(const l of s.dirs){const c=l.split("/").pop()||l.split("\\").pop(),r=document.createElement("div");r.className="file-tree-item",r.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> ${p(c)}`,r.addEventListener("click",()=>M(l)),Ke(r,l),d.appendChild(r)}else d.innerHTML="";const a=s.files||[];for(const l of a){const c=l.split("/").pop()||l.split("\\").pop(),r=mt(l);let g="",H="";if(r)switch(r){case"M":g="git-mod",H='<span class="git-file-status M">M</span>';break;case"A":g="git-add",H='<span class="git-file-status A">A</span>';break;case"D":g="git-del",H='<span class="git-file-status D">D</span>';break;case"?":g="git-untracked",H='<span class="git-file-status ?">?</span>';break;case"R":g="git-mod",H='<span class="git-file-status R">R</span>';break}const N=document.createElement("div");N.className="file-tree-item file"+(g?" "+g:""),N.innerHTML=`<span class="file-icon">\u{1F4C4}</span> ${H}${p(c)}`,N.addEventListener("click",()=>St(l)),d.appendChild(N)}}catch{d.innerHTML='<div class="file-tree-error">Failed to load directory</div>'}}function Ct(e){const t=e.lastIndexOf("/");return t<=0?null:e.substring(0,t)}async function St(e){Q=e,w.style.display="none",f&&(re(),f.destroy(),f=null,u=null),V(null),W(),R.style.display="none",O.style.display="flex",it.textContent=e,E.textContent="Loading...",_.style.display="none";try{const t=await fetch(v("/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,ee=n.content,Ie=n.content,E.textContent=n.size+" bytes",_.style.display=""}catch{E.textContent="Failed to load",U.value=""}}U.addEventListener("input",()=>{ee=U.value}),_.addEventListener("click",async()=>{_.textContent="Saving...",_.disabled=!0;try{const e=await fetch(v("/api/file"),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:Q,content:ee})});if(!e.ok){const t=await e.json();E.textContent=t.error||"Save failed";return}Ie=ee,E.textContent="Saved"}catch{E.textContent="Save failed"}finally{_.disabled=!1,_.textContent="Save"}}),ot.addEventListener("click",async()=>{if(confirm("Delete "+Q+"?"))try{const e=await fetch(v("/api/file/delete"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:Q})});if(!e.ok){const t=await e.json();E.textContent=t.error||"Delete failed";return}O.style.display="none",R.style.display="flex",x&&M(x)}catch{E.textContent="Delete failed"}}),at.addEventListener("click",()=>{O.style.display="none",R.style.display="flex",x&&M(x)}),lt.addEventListener("click",async()=>{const e=xe.value.trim();if(!e)return;const t=x+"/"+e;try{const n=await fetch(v("/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}xe.value="",x&&M(x)}catch{E.textContent="Create failed"}});const de=document.getElementById("force-narrow-toggle");de&&(de.checked=te(),de.addEventListener("change",()=>{try{localStorage.setItem(He,de.checked?"1":"0")}catch{}Ne(),T()})),Ne(),document.getElementById("mode-settings").addEventListener("click",()=>{const e=Te.classList.toggle("open");he.classList.toggle("open",e)}),he.addEventListener("click",()=>{Te.classList.remove("open"),he.classList.remove("open")});let L="",k=!1,C;const q=document.createElement("div");q.className="session-popover-backdrop",document.body.appendChild(q);const S=document.createElement("div");S.id="session-popover",S.className="session-popover",S.style.display="none",S.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,5 @@ import{initTerminal as tt}from"./terminal-core.js";import{initBots as nt,openNew
|
|
|
38
38
|
<button class="btn danger sp-delete" id="sp-delete">Delete</button>
|
|
39
39
|
</div>
|
|
40
40
|
<hr class="sp-divider" id="sp-divider" />
|
|
41
|
-
<button class="btn primary" id="sp-rebuild" style="display:none">\u91CD\u5EFA\u540C\u540D\u540C\u8DEF\u5F84 session</button>`,document.body.appendChild(S);function Bt(e){const t=e.getBoundingClientRect(),n=window.innerHeight,s=S.offsetHeight||240;let i=t.bottom+4;i+s>n-8&&(i=Math.max(8,t.top-s-4)),S.style.top=i+"px",S.style.left=Math.max(8,Math.min(t.left,window.innerWidth-240))+"px"}let Ot="";function pe(e,t,n){L=e,k=!!n?.tombstone,C=n?.agentId;const s=document.getElementById("sp-name");s.value=e;const i=S.querySelector(".sp-field label");i.textContent=k?"\u91CD\u547D\u540D (\u4EC5\u8BB0\u5F55\uFF0C\u4E0D\u91CD\u5EFA)":"Rename session";const o=document.getElementById("sp-rebuild");o.style.display=k?"":"none";const a=document.getElementById("sp-delete");a.textContent=k?"\u5220\u9664\u8BB0\u5F55":"Delete",a.title=k?"\u5220\u9664\u5931\u6548\u8BB0\u5F55\uFF08\u5893\u7891\u6D88\u5931\uFF09":"Delete session";const l=document.getElementById("sp-divider");l&&(l.style.display=k?"":"none");const c=document.getElementById("sp-save");c.textContent=k?"\u91CD\u547D\u540D":"Save",
|
|
42
|
-
`).length;B.rows=Math.min(e,4)}),B.addEventListener("keydown",e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),Ze())})),Xe&&Xe.addEventListener("click",Ze),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 Ee=document.getElementById("process-panel"),
|
|
41
|
+
<button class="btn primary" id="sp-rebuild" style="display:none">\u91CD\u5EFA\u540C\u540D\u540C\u8DEF\u5F84 session</button>`,document.body.appendChild(S);function Bt(e){const t=e.getBoundingClientRect(),n=window.innerHeight,s=S.offsetHeight||240;let i=t.bottom+4;i+s>n-8&&(i=Math.max(8,t.top-s-4)),S.style.top=i+"px",S.style.left=Math.max(8,Math.min(t.left,window.innerWidth-240))+"px"}let Ot="";function pe(e,t,n){L=e,k=!!n?.tombstone,C=n?.agentId;const s=document.getElementById("sp-name");s.value=e;const i=S.querySelector(".sp-field label");i.textContent=k?"\u91CD\u547D\u540D (\u4EC5\u8BB0\u5F55\uFF0C\u4E0D\u91CD\u5EFA)":"Rename session";const o=document.getElementById("sp-rebuild");o.style.display=k?"":"none";const a=document.getElementById("sp-delete");a.textContent=k?"\u5220\u9664\u8BB0\u5F55":"Delete",a.title=k?"\u5220\u9664\u5931\u6548\u8BB0\u5F55\uFF08\u5893\u7891\u6D88\u5931\uFF09":"Delete session";const l=document.getElementById("sp-divider");l&&(l.style.display=k?"":"none");const c=document.getElementById("sp-save");c.textContent=k?"\u91CD\u547D\u540D":"Save",q.classList.add("open"),S.style.display="block",Bt(t),setTimeout(()=>s.focus(),50)}function $(){q.classList.remove("open"),S.style.display="none"}q.addEventListener("click",$),document.getElementById("sp-save").addEventListener("click",async()=>{const e=document.getElementById("sp-name").value.trim();if(!e||e===L){$();return}try{const t=k?{oldName:L,newName:e,agentId:C}:{oldName:L,newName:e,...C?{agentId:C}:{}};if(!(await fetch(v(k?"/api/sessions/rename-tombstone":"/api/sessions/rename"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).ok)return;$(),T(),!k&&u===L&&(C??null)===h&&F(e,C)}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(v("/api/sessions/rebuild"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:L,agentId:C})});if(!e.ok){const t=await e.json();alert(t.error||"\u91CD\u5EFA\u5931\u8D25");return}$(),T()}catch{}}),document.getElementById("sp-delete").addEventListener("click",async()=>{if(k){if(!confirm('\u5220\u9664\u5931\u6548\u8BB0\u5F55 "'+L+'"\uFF1F'))return;try{if(!(await fetch(v("/api/sessions/dismiss"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:L,agentId:C})})).ok)return;$(),T()}catch{}return}if(confirm('Delete session "'+L+'"?'))try{if(!(await fetch(v("/api/sessions/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:L,...C?{agentId:C}:{}})})).ok)return;$(),u===L&&(C??null)===h&&(f&&(f.destroy(),f=null),u=null,w.style.display="none",R.style.display="flex"),T()}catch{}}),document.getElementById("sp-cancel").addEventListener("click",$);const Ye={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"},fe=document.getElementById("mobile-keys"),It=new Set(["up","down","left","right","tab","s-tab","space"]),xt=400,Tt=80;let J=0,ue=0,me=!1;function Mt(){J&&(clearTimeout(J),J=0),ue&&(clearInterval(ue),ue=0)}fe.addEventListener("mousedown",e=>{e.target.closest("button[data-key]")&&e.preventDefault()}),fe.addEventListener("pointerdown",e=>{const t=e.target.closest("button[data-key]");if(!t)return;const n=t.dataset.key;It.has(n)&&(me=!1,J=setTimeout(()=>{J=0,me=!0,ue=setInterval(()=>{const s=Ye[n];s&&f&&f.sendInput(s)},Tt)},xt))});for(const e of["pointerup","pointercancel","pointerleave"])fe.addEventListener(e,Mt);fe.addEventListener("click",e=>{const t=e.target.closest("button[data-key]");if(!t||!f)return;if(me){me=!1;return}const n=Ye[t.dataset.key];n&&(f.sendInput(n),f.focus())});const B=document.getElementById("mk-input"),Xe=document.getElementById("mk-send");function Ze(){if(!B||!f)return;const e=B.value;e&&(f.sendInput(e+"\r"),B.value="",B.rows=1,f.focus())}if(B&&(B.addEventListener("input",()=>{B.rows=1;const e=B.value.split(`
|
|
42
|
+
`).length;B.rows=Math.min(e,4)}),B.addEventListener("keydown",e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),Ze())})),Xe&&Xe.addEventListener("click",Ze),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 Ee=document.getElementById("process-panel"),K=document.getElementById("proc-list"),Ht=document.getElementById("proc-close"),ke=document.getElementById("proc-backdrop"),Nt=document.getElementById("header-ram");function Rt(){K.innerHTML='<div class="proc-empty">Loading\u2026</div>',fetch(v("/api/system/processes")).then(e=>e.json()).then(e=>{if(!Array.isArray(e)||!e.length){K.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="'+p(n.command)+'">'+p(n.command)+'</span><button class="proc-kill" title="Kill PID '+n.pid+'">×</button></div>'}K.innerHTML=t;for(const n of K.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(v("/api/system/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:parseInt(o.dataset.pid,10)})}).then(a=>a.json()).then(a=>{a.ok?o.style.opacity="0.3":alert("Failed: "+(a.error||"unknown"))}).catch(()=>alert("Network error"))})}}).catch(()=>{K.innerHTML='<div class="proc-empty">Failed to load</div>'})}function _t(){Ee.classList.add("open"),ke.classList.add("open"),Rt()}function ve(){Ee.classList.remove("open"),ke.classList.remove("open")}Nt.addEventListener("click",e=>{e.stopPropagation(),Ee.classList.contains("open")?ve():_t()}),Ht.addEventListener("click",ve),ke.addEventListener("click",ve);const $t=2e3;let Y=null,Ce=null;const P=new Map,D=new Map,At=5e3,Qe=new Map;function Se(e,t){return(t?"a:"+t+":":"l:")+e}function Pt(e,t,n){const s=Se(e,t);if(n==="working"){const r=Qe.get(s);if(r&&Date.now()<r)return}const i=D.get(s),o=e===u&&(t??null)===h,a=n==="idle"&&i?.state==="working";D.set(s,{session:e,agentId:t,state:n,doneUntil:a?Date.now()+$t:void 0,unread:a?!o:!1});const l=t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',c=d.querySelector(l);c&&ge(c,s,D.get(s))}function ge(e,t,n){const s=P.get(t);s&&(clearTimeout(s),P.delete(t)),e.classList.remove("working","just-done");const i=n.session===u&&(n.agentId??null)===h;n.state==="working"?e.classList.add("working"):i&&n.doneUntil&&Date.now()<n.doneUntil?(e.classList.add("just-done"),P.set(t,setTimeout(()=>{e.classList.remove("just-done"),P.delete(t)},Math.max(0,n.doneUntil-Date.now())))):!i&&n.unread&&e.classList.add("just-done")}function Be(){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=d.querySelector(n);s&&ge(s,e,t)}}function Dt(e,t){const n=Se(e,t),s=D.get(n);if(!s)return;const i=P.get(n);i&&(clearTimeout(i),P.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])',a=d.querySelector(o);a&&ge(a,n,s)}function et(){if(Y||Ce)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);Y=s,s.onmessage=i=>{try{const o=JSON.parse(String(i.data));o&&o.type==="session.activity"&&typeof o.session=="string"&&Pt(o.session,o.agentId||void 0,o.state==="working"?"working":"idle")}catch{}},s.onclose=()=>{Y===s&&(Y=null,Ce=setTimeout(()=>{Ce=null,et()},5e3))},s.onerror=()=>{try{s.close()}catch{}}}catch{Y=null}}window.__openSession=F,window.__refreshSidebar=T,T(),W(),Be(),et(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&Be()}),setInterval(()=>{document.visibilityState==="visible"&&T()},1e4),nt();
|
package/dist/lib/pages/shell.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{cssVarsStyle as c}from"../theme.js";import{newSessionModalCSS as b,newSessionModalHTML as x,newSessionModalScript as
|
|
1
|
+
import{cssVarsStyle as c}from"../theme.js";import{newSessionModalCSS as b,newSessionModalHTML as x,newSessionModalScript as g,reducedMotion as f}from"../shared-layout.js";import{icon as n}from"../icons.js";function m(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function o(e="var(--panel-accent)"){return`box-shadow: 0 0 0 2px ${e}; outline: none;`}function w(e){const{theme:t,fsRoots:r,terminalCfg:i,scrollback:p,wsBase:s}=e,a=e.version?m(e.version):"",l=`
|
|
2
2
|
*, *::before, *::after { box-sizing: border-box; }
|
|
3
3
|
html, body {
|
|
4
4
|
background: var(--page-bg); color: var(--page-fg);
|
|
@@ -765,9 +765,24 @@ import{cssVarsStyle as c}from"../theme.js";import{newSessionModalCSS as b,newSes
|
|
|
765
765
|
.bv-notice-warn { color: #e0a23c; }
|
|
766
766
|
.bv-notice-error { color: var(--panel-danger, #e5534b); }
|
|
767
767
|
|
|
768
|
-
|
|
769
|
-
.bots-composer
|
|
770
|
-
.bots-composer textarea
|
|
768
|
+
/* Same look and metrics as the terminal's mobile input row (.mk-input). */
|
|
769
|
+
.bots-composer { display: flex; gap: 4px; padding: 6px 8px; border-top: 1px solid var(--panel-border); background: var(--panel-bg); flex-shrink: 0; align-items: stretch; }
|
|
770
|
+
.bots-composer textarea {
|
|
771
|
+
flex: 1; resize: none; box-sizing: border-box;
|
|
772
|
+
min-height: 38px; max-height: 80px;
|
|
773
|
+
background: color-mix(in srgb, var(--page-bg), var(--panel-bg) 50%);
|
|
774
|
+
color: var(--page-fg); border: 1px solid var(--panel-border);
|
|
775
|
+
border-radius: 8px; padding: 6px 10px;
|
|
776
|
+
font-family: var(--font-mono); font-size: var(--text-base); line-height: 1.4; outline: none;
|
|
777
|
+
}
|
|
778
|
+
.bots-composer textarea:focus { border-color: var(--panel-accent); box-shadow: 0 0 0 2px color-mix(in srgb, var(--panel-accent) 15%, transparent); }
|
|
779
|
+
.bots-composer .btn.primary {
|
|
780
|
+
min-width: 44px; padding: 0 12px; border: none; color: white;
|
|
781
|
+
background: var(--panel-success); border-radius: 8px; cursor: pointer;
|
|
782
|
+
display: flex; align-items: center; justify-content: center;
|
|
783
|
+
}
|
|
784
|
+
.bots-composer .btn.primary:hover { filter: brightness(1.15); }
|
|
785
|
+
.bots-composer .btn.primary:active { filter: brightness(0.85); }
|
|
771
786
|
|
|
772
787
|
.bots-modal { position: fixed; inset: 0; background: rgba(0,0,0,0.45); display: flex; align-items: center; justify-content: center; z-index: 40; }
|
|
773
788
|
.bots-modal[hidden] { display: none; }
|
|
@@ -798,10 +813,23 @@ import{cssVarsStyle as c}from"../theme.js";import{newSessionModalCSS as b,newSes
|
|
|
798
813
|
.file-roots-list li:hover { border-color: var(--panel-accent); }
|
|
799
814
|
.file-roots-list li svg { width: 20px; height: 20px; flex-shrink: 0; fill: var(--panel-accent); }
|
|
800
815
|
|
|
801
|
-
${
|
|
816
|
+
${f()}
|
|
802
817
|
${b()}
|
|
803
818
|
@media (max-width: 640px) {
|
|
804
819
|
.app-layout { flex-direction: column; }
|
|
820
|
+
/* Bots chat on phones: two-row header, scrollable actions, modal-style mode
|
|
821
|
+
menu, and a 16px composer so iOS does not zoom the page on focus. */
|
|
822
|
+
.bots-view-head { flex-wrap: wrap; row-gap: 6px; padding: 6px 10px; }
|
|
823
|
+
.bv-title { flex: 1 1 100%; }
|
|
824
|
+
.bv-status { display: none; }
|
|
825
|
+
.bv-actions { flex: 1 1 100%; display: flex; gap: 6px; overflow-x: auto; padding-bottom: 2px; -webkit-overflow-scrolling: touch; }
|
|
826
|
+
.bv-actions .btn, .bv-actions .bv-mode-btn { flex: 0 0 auto; padding: 5px 9px; font-size: 11px; }
|
|
827
|
+
.bv-mode-menu { position: fixed; left: 10px; right: 10px; top: auto; bottom: 10px; width: auto; max-height: 60vh; overflow-y: auto; }
|
|
828
|
+
.bots-messages { padding: 10px; }
|
|
829
|
+
.bv-msg { max-width: 100%; }
|
|
830
|
+
.bots-composer { padding: 8px 10px; gap: 6px; }
|
|
831
|
+
.bv-approval-actions { flex-wrap: wrap; }
|
|
832
|
+
.bv-reason { flex: 1 1 100%; }
|
|
805
833
|
.sidebar { flex: 0 0 auto; border-right: none; border-bottom: 1px solid var(--panel-border); transition: max-height 0.2s; }
|
|
806
834
|
.sidebar.collapsed .sidebar-content { display: none; }
|
|
807
835
|
.sidebar.collapsed .sidebar-footer { display: none; }
|
|
@@ -831,12 +859,12 @@ import{cssVarsStyle as c}from"../theme.js";import{newSessionModalCSS as b,newSes
|
|
|
831
859
|
display: flex; flex-wrap: nowrap; gap: 4px;
|
|
832
860
|
overflow-x: auto; overscroll-behavior-x: contain;
|
|
833
861
|
}
|
|
834
|
-
`,v=JSON.stringify(t.terminal).replace(/</g,"\\u003c"),d=JSON.stringify({terminal:i,scrollback:p,theme:t.terminal,fsRoots:
|
|
862
|
+
`,v=JSON.stringify(t.terminal).replace(/</g,"\\u003c"),d=JSON.stringify({terminal:i,scrollback:p,theme:t.terminal,fsRoots:r,wsBase:s||""}).replace(/</g,"\\u003c");return`<!DOCTYPE html>
|
|
835
863
|
<html lang="en">
|
|
836
864
|
<head>
|
|
837
865
|
<meta charset="UTF-8" />
|
|
838
866
|
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
|
|
839
|
-
<meta name="tw-build" content="${
|
|
867
|
+
<meta name="tw-build" content="${a}" />
|
|
840
868
|
<meta name="apple-mobile-web-app-capable" content="yes" />
|
|
841
869
|
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
|
|
842
870
|
<meta name="apple-mobile-web-app-title" content="tmux-web" />
|
|
@@ -943,7 +971,7 @@ import{cssVarsStyle as c}from"../theme.js";import{newSessionModalCSS as b,newSes
|
|
|
943
971
|
<!-- Settings popover -->
|
|
944
972
|
<div class="popover-backdrop" id="settings-backdrop"></div>
|
|
945
973
|
<div class="settings-popover" id="settings-popover">
|
|
946
|
-
<div style="padding:1px 2px 6px;font-size:10px;color:var(--panel-muted);opacity:.8;font-family:var(--font-mono)">tmux-weblink v${
|
|
974
|
+
<div style="padding:1px 2px 6px;font-size:10px;color:var(--panel-muted);opacity:.8;font-family:var(--font-mono)">tmux-weblink v${a}</div>
|
|
947
975
|
<div style="padding:4px 0">
|
|
948
976
|
<button class="theme-option" data-theme="vscode" title="VS Code"><span class="theme-dot" style="background:#007acc"></span>VS Code${t.template==="vscode"?'<span class="theme-check">\u2713</span>':""}</button>
|
|
949
977
|
<button class="theme-option" data-theme="ghostty" title="Ghostty"><span class="theme-dot" style="background:#ff5f00"></span>Ghostty${t.template==="ghostty"?'<span class="theme-check">\u2713</span>':""}</button>
|
|
@@ -1018,7 +1046,7 @@ window.__onSessionCreated = async function(name, agentId) {
|
|
|
1018
1046
|
await window.__refreshSidebar();
|
|
1019
1047
|
window.__openSession(name, agentId || undefined);
|
|
1020
1048
|
};
|
|
1021
|
-
${
|
|
1049
|
+
${g("__onSessionCreated")}
|
|
1022
1050
|
</script>
|
|
1023
1051
|
<script>
|
|
1024
1052
|
// Sync app-layout height to visual viewport so mobile keyboard doesn't overlap
|