tmux-weblink 2.2.3 → 2.2.5
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.
- package/dist/assets/shell-client.js +11 -11
- package/dist/browser/shell-client.js +1 -1
- package/dist/index.js +4 -4
- package/dist/lib/agent-client.js +1 -1
- package/package.json +1 -1
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
var cn=/\x1b\](?:10|11|110|111|104)(?:;[^\x07\x1b]*)?\x1b?(?:\\|\x07)/g;function Ye(e){return e.replace(/\x1b\[\?1049[hl]/g,"")}function ce(e){return e.replace(cn,"")}var Me;function dn(){return Me||(document.querySelector("link[data-tmux-web-xterm-css]")?Me=Promise.resolve():(Me=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)}),Me))}var un=class Nt{terminal;fitAddon;container;constructor(t,n,s){this.container=t,this.terminal=n,this.fitAddon=s,this.terminal.loadAddon(this.fitAddon),this.terminal.open(t)}static async create(t,n,s){let[{Terminal:r},{FitAddon:o}]=await Promise.all([import("./xterm-BXEES47M.js"),import("./addon-fit-D5N335P2.js"),dn()]),c=new r({fontSize:14,fontFamily:"'JetBrains Mono', 'SF Mono', 'Menlo', monospace",cursorBlink:!0,cursorStyle:"bar",scrollback:n,convertEol:!1,smoothScrollDuration:120,theme:s});return new Nt(t,c,new o)}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)}scrollLines(t){let n=this.terminal.buffer?.active;this.terminal.scrollLines(t)}isNearScrollbackTop(){return this.terminal.buffer.active.viewportY<=1}viewportY(){return this.terminal.buffer.active.viewportY}baseY(){return this.terminal.buffer.active.baseY}fit(){let t=pn(this.container);if(t.width<=0||t.height<=0)return!1;let n=this.terminal._core?._renderService?.dimensions?.css?.cell;if(!n?.width||!n?.height)return this.fitAddon.fit(),!0;let s=n.width,r=n.height,o=this.terminal.element?.querySelector(".xterm-viewport"),c=o?Math.max(0,o.offsetWidth-o.clientWidth):0,l=Math.max(2,Math.floor((t.width-c)/s)),
|
|
2
|
-
`)}selectRows(t,n){let s=this.terminal.buffer.active,[r,o]=t<=n?[t,n]:[n,t];this.terminal.selectLines(s.viewportY+r,s.viewportY+o)}selectCells(t,n,s,r){let o=this.terminal.buffer.active,c=Math.min(n,r),l=Math.max(n,r);if(c===l){let
|
|
3
|
-
`)}getSelection(){return this.terminal.getSelection()}clearSelection(){this.terminal.clearSelection()}hasSelectionSupport(){return!0}};function pn(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 fn(e,t,n){return e.innerHTML="",e.classList.add("terminal-pending"),(async()=>{let s=await un.create(e,n.scrollback,n.theme),r,o=0,c,l=null,
|
|
1
|
+
var cn=/\x1b\](?:10|11|110|111|104)(?:;[^\x07\x1b]*)?\x1b?(?:\\|\x07)/g;function Ye(e){return e.replace(/\x1b\[\?1049[hl]/g,"")}function ce(e){return e.replace(cn,"")}var Me;function dn(){return Me||(document.querySelector("link[data-tmux-web-xterm-css]")?Me=Promise.resolve():(Me=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)}),Me))}var un=class Nt{terminal;fitAddon;container;constructor(t,n,s){this.container=t,this.terminal=n,this.fitAddon=s,this.terminal.loadAddon(this.fitAddon),this.terminal.open(t)}static async create(t,n,s){let[{Terminal:r},{FitAddon:o}]=await Promise.all([import("./xterm-BXEES47M.js"),import("./addon-fit-D5N335P2.js"),dn()]),c=new r({fontSize:14,fontFamily:"'JetBrains Mono', 'SF Mono', 'Menlo', monospace",cursorBlink:!0,cursorStyle:"bar",scrollback:n,convertEol:!1,smoothScrollDuration:120,theme:s});return new Nt(t,c,new o)}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)}scrollLines(t){let n=this.terminal.buffer?.active;this.terminal.scrollLines(t)}isNearScrollbackTop(){return this.terminal.buffer.active.viewportY<=1}viewportY(){return this.terminal.buffer.active.viewportY}baseY(){return this.terminal.buffer.active.baseY}fit(){let t=pn(this.container);if(t.width<=0||t.height<=0)return!1;let n=this.terminal._core?._renderService?.dimensions?.css?.cell;if(!n?.width||!n?.height)return this.fitAddon.fit(),!0;let s=n.width,r=n.height,o=this.terminal.element?.querySelector(".xterm-viewport"),c=o?Math.max(0,o.offsetWidth-o.clientWidth):0,l=Math.max(2,Math.floor((t.width-c)/s)),d=Math.max(2,Math.floor(t.height/r));return(l!==this.terminal.cols||d!==this.terminal.rows)&&this.terminal.resize(l,d),!0}focus(){this.terminal.focus()}pasteText(t){this.terminal.paste(t)}input(t){this.terminal.input(t,!1)}onData(t){this.terminal.onData(t),this.terminal.onBinary(t)}onResize(t){this.terminal.onResize(t)}onScroll(t){this.terminal.onScroll(t)}attachCustomKeyEventHandler(t){this.terminal.attachCustomKeyEventHandler(t)}isFocused(){let t=document.activeElement;return t?t===this.container||t===this.terminal.textarea||this.container.contains(t)||!!t.closest?.(".xterm"):!1}getScreenText(){return this.getRowsText(0,this.terminal.rows-1)}getRowsText(t,n){let s=this.terminal.buffer.active,[r,o]=t<=n?[t,n]:[n,t],c=s.viewportY,l=[];for(let d=r;d<=o;d++){let p=s.getLine(c+d);l.push(p?p.translateToString(!0):"")}return l.join(`
|
|
2
|
+
`)}selectRows(t,n){let s=this.terminal.buffer.active,[r,o]=t<=n?[t,n]:[n,t];this.terminal.selectLines(s.viewportY+r,s.viewportY+o)}selectCells(t,n,s,r){let o=this.terminal.buffer.active,c=Math.min(n,r),l=Math.max(n,r);if(c===l){let d=Math.min(t,s),p=Math.max(t,s);this.terminal.select(d,o.viewportY+c,p-d+1)}else this.terminal.selectLines(o.viewportY+c,o.viewportY+l)}getCellsText(t,n,s,r){let o=this.terminal.buffer.active,c=Math.min(n,r),l=Math.max(n,r),d=n<r?t:n>r?s:Math.min(t,s),p=n<r?s:n>r?t:Math.max(t,s),w=o.viewportY,S=[];for(let A=c;A<=l;A++){let be=o.getLine(w+A);if(!be){S.push("");continue}let J=A===c?d:0,_e=A===l?p:this.terminal.cols-1,X="";for(let T=J;T<=_e;T++){let W=be.getCell(T);W&&(X+=W.getChars())}S.push(X.replace(/\s+$/,""))}return S.join(`
|
|
3
|
+
`)}getSelection(){return this.terminal.getSelection()}clearSelection(){this.terminal.clearSelection()}hasSelectionSupport(){return!0}};function pn(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 fn(e,t,n){return e.innerHTML="",e.classList.add("terminal-pending"),(async()=>{let s=await un.create(e,n.scrollback,n.theme),r,o=0,c,l=null,d=0,p=0,w=.2,S=10,A=.95,be=.04;function J(){d&&(cancelAnimationFrame(d),d=0),p=0}function _e(a){if(J(),Math.abs(a)<w)return;p=Math.max(-S,Math.min(S,a));let i=()=>{if(P){d=0;return}let u=e.querySelector(".xterm-rows > div"),m=u?u.getBoundingClientRect().height:16,E=m>0?Math.round(p*16/m):p>0?1:-1;E===0&&(E=p>0?1:-1);let D=s.viewportY()-E,Y=s.baseY(),re=Math.max(0,Math.min(D,Y));if(s.scrollToLine(re,!0),p*=A,re!==D){d=0;return}if(Math.abs(p)<be){d=0;return}d=requestAnimationFrame(i)};d=requestAnimationFrame(i)}let X=0,T="connecting",W=0,te=!1,Ee=[],G="",P=!1,ne=1e3,$t=location.protocol==="https:"?"wss:":"ws:",Pt=n.wsBase||"/ws",jt=$t+"//"+location.host+Pt+"/"+encodeURIComponent(t),zt="/api/session/"+encodeURIComponent(t)+"/upload",_t=/^((?!chrome|android|crios|fxios|edgios).)*safari/i.test(navigator.userAgent);function Wt(){return Ee.join("")+G}async function Ot(a,i=0){let u=a?s.viewportY():0,m=ce(Wt());if(s.reset(),!m){a||s.scrollToBottom();return}await s.write(m),a?s.scrollToLine(i+u):s.scrollToBottom()}function O(a){r?.readyState===WebSocket.OPEN&&r.send(JSON.stringify(a))}function Ut(a){let i;try{i=JSON.parse(a)}catch{T==="live"&&(G+=a,s.write(ce(a)));return}if(i.type==="auth.required"){let u=localStorage.getItem("tmux-web-token");u?O({type:"auth.token",token:u}):location.href="/login?returnTo="+encodeURIComponent(location.pathname+location.search);return}if(i.type==="attach_failed"&&typeof i.message=="string"){Le=!0,T="dead",s.reset(),s.write(`\r
|
|
4
4
|
\x1B[31m`+ce(i.message)+`\x1B[0m\r
|
|
5
|
-
`).then(()=>{Ce();try{r?.close()}catch{}});return}if(i.type==="auth.ok"){i.token&&localStorage.setItem("tmux-web-token",i.token),ne=1e3,U(),O({type:"resize",cols:s.cols,rows:s.rows}),M();return}if(i.type==="auth.failed"){if(i.permanentLock||i.retryAfterMs&&i.retryAfterMs>6e4){localStorage.removeItem("tmux-web-token"),location.href="/login?error="+encodeURIComponent(i.message);return}return}if(i.type==="snapshot"&&typeof i.data=="string"){let
|
|
5
|
+
`).then(()=>{Ce();try{r?.close()}catch{}});return}if(i.type==="auth.ok"){i.token&&localStorage.setItem("tmux-web-token",i.token),ne=1e3,U(),O({type:"resize",cols:s.cols,rows:s.rows}),M();return}if(i.type==="auth.failed"){if(i.permanentLock||i.retryAfterMs&&i.retryAfterMs>6e4){localStorage.removeItem("tmux-web-token"),location.href="/login?error="+encodeURIComponent(i.message);return}return}if(i.type==="snapshot"&&typeof i.data=="string"){let u=Ye(ce(i.data));Ee=[u],G="",W=typeof i.lines=="number"?i.lines:n.terminal.initialLines,T="live",s.reset(),U(),O({type:"resize",cols:s.cols,rows:s.rows}),s.write(u).then(()=>s.scrollToBottom());return}if(i.type==="window_changed"&&typeof i.activeIndex=="number"){let u=new URL(location.href);u.searchParams.get("window")!==String(i.activeIndex)&&(u.searchParams.set("window",String(i.activeIndex)),history.replaceState(history.state,"",u)),window.dispatchEvent(new CustomEvent("tmux:windows",{detail:i.windows}));return}if(i.type==="history"&&typeof i.data=="string"){i.lines>0&&i.data?(Ee.unshift(Ye(i.data)),W+=i.lines,Ot(!0,i.lines).finally(()=>{te=!1})):te=!1;return}if(i.type==="data"&&typeof i.data=="string"){let u=Ye(ce(i.data));if(T==="connecting"){T="live",G=u,s.write(u);return}T==="live"&&(G+=u,s.write(u))}}let Le=!1;function nt(){if(Le)return;let a=jt,i=localStorage.getItem("tmux-web-token");i&&(a+=(a.includes("?")?"&":"?")+"token="+encodeURIComponent(i)),a+=(a.includes("?")?"&":"?")+"cols="+s.cols+"&rows="+s.rows,r=new WebSocket(a),r.onopen=()=>{T="connecting",W=0,te=!1,Ee=[],G="",s.reset(),ne=1e3},r.onmessage=u=>{typeof u.data=="string"&&Ut(u.data)},r.onclose=()=>{P||(T="connecting",!Le&&setTimeout(()=>{ne=Math.min(ne*2,1e4),!P&&!Le&&nt()},ne))},r.onerror=()=>r?.close()}function xe(a){O({type:"input",data:a})}function U(){return s.fit()}function Ce(){e.classList.remove("terminal-pending")}function M(){o&&cancelAnimationFrame(o),c&&clearTimeout(c),U(),o=requestAnimationFrame(()=>{o=0,U()&&Ce()}),c=setTimeout(()=>{U()&&Ce()},120)}function Yt(){M(),setTimeout(M,50),setTimeout(M,150),setTimeout(M,300)}function st(a){return typeof a=="string"&&a.startsWith("image/")}function at(a){return a?.files?.length?a.files[0]??null:null}function qt(a){if(!a?.items)return null;for(let i=0;i<a.items.length;i++){let u=a.items[i];if(u?.kind==="file"&&st(u.type))return u.getAsFile()}return null}async function Kt(a){let i=new FormData,u=a instanceof File&&a.name?a.name:"upload";i.append("file",a,u);let m=localStorage.getItem("tmux-web-token"),E={};m&&(E.Authorization="Bearer "+m);let D=await fetch(zt,{method:"POST",body:i,headers:E});if(!D.ok){let re="upload failed";try{let ut=await D.json();ut.error&&(re=ut.error)}catch{}throw new Error(re)}let Y=await D.json();if(!Y.path)throw new Error("no path in response");return Y.path}async function We(a){try{let i=await Kt(a);xe(i)}catch{}}s.onData(a=>xe(a)),s.onResize(({cols:a,rows:i})=>O({type:"resize",cols:a,rows:i})),s.onScroll(()=>{T!=="live"||te||!s.isNearScrollbackTop()||(te=!0,O({type:"load_history",before:W}))});let se=!1,ae=!1,b=null,x=null,ie=document.createElement("div");ie.className="terminal-copy-banner",ie.innerHTML='<strong>Copy mode</strong><span class="hint">drag to copy \xB7 Esc exits</span>',ie.hidden=!0,e.appendChild(ie);let N=document.createElement("div");N.className="terminal-copy-banner terminal-copy-toast",N.textContent="Copied",N.hidden=!0,e.appendChild(N);function it(a,i){let u=e.querySelector(".xterm-screen, canvas"),m=(u&&u.getBoundingClientRect().width>0?u:e).getBoundingClientRect(),E=m.height>0&&s.rows>0?m.height/s.rows:18,D=m.width>0&&s.cols>0?m.width/s.cols:9;return{row:Math.max(0,Math.min(s.rows-1,Math.floor((i-m.top)/E))),col:Math.max(0,Math.min(s.cols-1,Math.floor((a-m.left)/D)))}}async function ke(a){if(!a)return;try{if(navigator.clipboard?.writeText){await navigator.clipboard.writeText(a);return}}catch{}let i=document.createElement("textarea");i.value=a,i.style.position="fixed",i.style.opacity="0",i.style.pointerEvents="none",document.body.appendChild(i),i.focus(),i.select();try{document.execCommand("copy")}catch{}i.remove()}let oe;function Se(){N.hidden=!1,oe&&clearTimeout(oe),oe=setTimeout(()=>{N.hidden=!0},1e3)}function Z(a){se=a,ie.hidden=!a,e.classList.toggle("terminal-copy-mode-active",a),a&&s.focus()}function ot(){Z(!se)}function Vt(a){P||a.button!==0||ae||(se||a.shiftKey)&&(a.preventDefault(),a.stopPropagation(),ae=!0,b=it(a.clientX,a.clientY),x=b,s.selectCells(b.col,b.row,x.col,x.row),document.addEventListener("mousemove",Oe,!0),document.addEventListener("mouseup",Ue,!0))}function Oe(a){P||!ae||!b||(a.preventDefault(),a.stopPropagation(),x=it(a.clientX,a.clientY),s.selectCells(b.col,b.row,x.col,x.row))}function Ue(a){if(P||!ae||!b||!x)return;a.preventDefault(),a.stopPropagation(),document.removeEventListener("mousemove",Oe,!0),document.removeEventListener("mouseup",Ue,!0),ae=!1;let i=s.getCellsText(b.col,b.row,x.col,x.row);b=null,x=null,s.clearSelection(),Z(!1),i&&(N.textContent="\u5DF2\u590D\u5236",ke(i).then(Se)),s.focus()}e.addEventListener("mousedown",Vt,!0),document.addEventListener("keydown",Jt,!0);function Jt(a){if(!(P||!s.isFocused()||a.defaultPrevented||a.isComposing)){if(se){if(a.key==="Escape"){a.preventDefault(),a.stopPropagation(),b=null,x=null,s.clearSelection(),Z(!1);return}if(a.key==="Enter"||(a.ctrlKey||a.metaKey)&&a.code==="KeyC"){a.preventDefault(),a.stopPropagation(),ke(s.getScreenText()).then(Se),Z(!1);return}}if(a.altKey&&a.code==="KeyC"&&!a.ctrlKey&&!a.metaKey){if(a.preventDefault(),a.stopPropagation(),b&&x){let i=s.getCellsText(b.col,b.row,x.col,x.row);b=null,x=null,s.clearSelection(),Z(!1),i&&(N.textContent="Copied",ke(i).then(Se))}else{let i=s.getSelection();i?(s.clearSelection(),N.textContent="Copied",ke(i).then(Se)):ot()}return}if((a.ctrlKey||a.metaKey)&&a.code==="KeyV"){a.preventDefault(),a.stopPropagation(),(async()=>{try{if(navigator.clipboard?.read){let i=await navigator.clipboard.read();for(let u of i)for(let m of u.types)if(st(m)){let E=await u.getType(m);await We(E);return}}}catch{}try{let i=await navigator.clipboard?.readText();i&&s.pasteText(lt(i))}catch{}})();return}}}let Te=0;function lt(a){return a.split(`\r
|
|
6
6
|
`).join(`
|
|
7
7
|
`).split(`
|
|
8
|
-
`).join("\r")}async function Xt(a){let i=qt(a.clipboardData);if(i){a.preventDefault(),a.stopPropagation();let E=Date.now();if(E-Te<50)return;Te=E,await We(i);return}let
|
|
8
|
+
`).join("\r")}async function Xt(a){let i=qt(a.clipboardData);if(i){a.preventDefault(),a.stopPropagation();let E=Date.now();if(E-Te<50)return;Te=E,await We(i);return}let u=a.clipboardData?.getData("text/plain");if(!u)return;a.preventDefault(),a.stopPropagation();let m=Date.now();m-Te<50||(Te=m,s.pasteText(lt(u)))}let le=0;function Gt(a){a.preventDefault(),le++,at(a.dataTransfer)&&e.classList.add("terminal-drag-over")}function Zt(a){a.preventDefault(),a.dataTransfer&&(a.dataTransfer.dropEffect="copy")}function Qt(a){a.preventDefault(),le--,le<=0&&(le=0,e.classList.remove("terminal-drag-over"))}async function en(a){a.preventDefault(),le=0,e.classList.remove("terminal-drag-over");let i=at(a.dataTransfer);i&&await We(i)}function rt(a){!_t||a.key!=="Escape"||se||a.defaultPrevented||a.repeat||a.metaKey||a.ctrlKey||a.altKey||s.isFocused()&&(a.preventDefault(),a.stopPropagation(),xe("\x1B"))}e.addEventListener("paste",Xt),e.addEventListener("dragenter",Gt),e.addEventListener("dragover",Zt),e.addEventListener("dragleave",Qt),e.addEventListener("drop",en),document.addEventListener("keydown",rt,!0);function tn(a){if(a.touches.length!==1){l=null;return}let i=a.touches[0];i&&(J(),l={startX:i.clientX,startY:i.clientY,lastX:i.clientX,lastY:i.clientY,lastT:performance.now(),velocity:0,scrolling:!1},a.stopPropagation())}function nn(a){if(!l||a.touches.length!==1)return;let i=a.touches[0];if(!i)return;let u=i.clientY-l.startY,m=i.clientX-l.startX;if(!l.scrolling){if(Math.abs(u)<8||Math.abs(u)<Math.abs(m))return;l.scrolling=!0,X=Date.now()+500}a.preventDefault(),a.stopPropagation();let E=performance.now(),D=i.clientY-l.lastY,Y=E-l.lastT;Y>0&&(l.velocity=D/Y),ln(-D),l.lastX=i.clientX,l.lastY=i.clientY,l.lastT=E}function sn(a){if(!l)return;let i=l.scrolling,u=l.velocity;if(l=null,a.stopPropagation(),!i){s.focus();return}X=Date.now()+500,a.preventDefault(),u&&_e(u)}function an(a){l=null,J(),a.stopPropagation()}function on(a){a.pointerType==="touch"&&Date.now()<X&&(a.preventDefault(),a.stopPropagation())}function ln(a){let i=e.querySelector(".xterm-rows > div"),u=i?i.getBoundingClientRect().height:16,m=u>0?Math.round(a/u):a>0?1:-1;m===0&&(m=a>0?1:-1),s.scrollLines(m)}e.addEventListener("touchstart",tn,{passive:!0,capture:!0}),e.addEventListener("touchmove",nn,{passive:!1,capture:!0}),e.addEventListener("touchend",sn,{passive:!1,capture:!0}),e.addEventListener("touchcancel",an,{passive:!0,capture:!0}),e.addEventListener("pointerup",on,!0);function ct(){M()}window.addEventListener("resize",ct),window.visualViewport?.addEventListener("resize",M),window.visualViewport?.addEventListener("scroll",M);let dt=new ResizeObserver(()=>M());dt.observe(e),document.fonts?.ready.then(()=>{M(),setTimeout(M,50),setTimeout(M,200)}),e.addEventListener("focusin",Yt,!0);async function rn(){if(document.fonts?.ready)try{await Promise.race([document.fonts.ready,new Promise(a=>setTimeout(a,1e3))])}catch{}}return requestAnimationFrame(()=>{U()&&Ce(),(async()=>(await rn(),U()&&O({type:"resize",cols:s.cols,rows:s.rows}),nt(),M()))()}),{destroy(){if(P=!0,J(),Z(!1),oe&&clearTimeout(oe),document.removeEventListener("mousemove",Oe,!0),document.removeEventListener("mouseup",Ue,!0),r){try{r.close(1e3,"session switch")}catch{}r=void 0}e.innerHTML="",e.classList.remove("terminal-pending"),window.removeEventListener("resize",ct),dt.disconnect(),document.removeEventListener("keydown",rt,!0)},focus(){s.focus()},sendInput(a){xe(a)},toggleCopyMode(){ot()}}})()}var de=window.__TMUX_WEB_SHELL__,v=null,g=null,pt=typeof window.__TMUX_WEB_SCOPE__?.agentId=="string"?window.__TMUX_WEB_SCOPE__.agentId:null,L=pt;window.__tmuxWebScopeAgent=pt;var qe="sessions",j="",Ie="",Be="",ft="";function C(e){return L?"/a/"+encodeURIComponent(L)+e:e}var f=document.getElementById("sidebar-content"),q=document.getElementById("main-placeholder"),I=document.getElementById("terminal-container"),ue=document.getElementById("file-editor"),mn=document.getElementById("fe-path"),H=document.getElementById("fe-status"),pe=document.getElementById("fe-content"),K=document.getElementById("fe-save"),hn=document.getElementById("fe-delete"),vn=document.getElementById("fe-back"),mt=document.getElementById("fe-new-name"),gn=document.getElementById("fe-new-btn"),Ke=document.getElementById("settings-backdrop"),ht=document.getElementById("settings-popover"),vt=document.querySelector(".sidebar");function yn(){return window.matchMedia("(max-width: 640px)").matches}function Ve(){yn()&&vt.classList.add("collapsed")}function gt(){vt.classList.remove("collapsed")}document.getElementById("mode-sessions").addEventListener("click",()=>{gt(),yt("sessions")}),document.getElementById("mode-files").addEventListener("click",()=>{gt(),yt("files")});function yt(e){qe=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"?(Je="",z()):Hn()}var Je="";async function z(){if(qe!=="sessions")return;try{let t=await(await fetch("/api/sidebar/sessions")).json(),n=JSON.stringify({recent:t.recent,agents:t.agents,tombstones:t.tombstones});if(n===Je)return;Je=n,xn(t)}catch{f.innerHTML+='<div class="file-tree-empty">Failed to load sessions</div>'}let e=document.getElementById("ns-btn");e&&e.addEventListener("click",()=>{let t=window.__openNewSessionModal;typeof t=="function"?t():document.getElementById("new-session-modal")?.classList.add("open")}),tt()}var wt="tmux-web-sidebar-group-collapsed";function bt(){try{return new Set(JSON.parse(localStorage.getItem(wt)||"[]"))}catch{return new Set}}function wn(e){try{localStorage.setItem(wt,JSON.stringify([...e]))}catch{}}function bn(e,t,n){if(!e)return"\u2026";let s=n&&(e===n||e.startsWith(n+"/"))?"~"+e.slice(n.length):e,r=s.split("/").filter(Boolean);if(r.length===0)return e;for(let o=1;o<=r.length;o++){let c=r.slice(-o).join("/");if(!t.some(l=>!l||l===e?!1:(n&&(l===n||l.startsWith(n+"/"))?"~"+l.slice(n.length):l).split("/").filter(Boolean).slice(-o).join("/")===c))return c}return s}function En(e,t){let n=new Map;for(let o of e){let c=o.path||"";n.has(c)||n.set(c,[]),n.get(c).push(o)}let s=[...n.keys()],r=bt();for(let[o,c]of n){let l=bn(o,s,t),d=r.has(o),p=document.createElement("div");p.className="session-group-header"+(d?" collapsed":""),p.title=o||"No working directory",p.innerHTML=`<span class="sg-folder">📁</span><span class="sg-label">${h(l)}</span>`,p.addEventListener("click",()=>{let S=bt(),A=p.nextElementSibling;S.has(o)?(S.delete(o),p.classList.remove("collapsed"),A?.classList.remove("collapsed")):(S.add(o),p.classList.add("collapsed"),A?.classList.add("collapsed")),wn(S)});let w=document.createElement("div");w.className="session-group-body"+(d?" collapsed":"");for(let S of c)w.appendChild(Ln(S));f.appendChild(p),f.appendChild(w)}}function Ln(e){let t=document.createElement("div");t.className="session-item"+(e.name===g&&!L?" 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>
|
|
9
9
|
<span>${h(e.name)}</span>
|
|
10
10
|
<button class="session-edit-btn" data-session="${h(e.name)}" title="Edit session"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>
|
|
11
|
-
`,t.addEventListener("click",s=>{s.target.closest(".session-edit-btn")||fe(e.name)});let n=t.querySelector(".session-edit-btn");return n&&n.addEventListener("click",s=>{s.stopPropagation(),Dt(e.name,n)}),t}function xn(e){f.innerHTML='<button class="new-session-sidebar-btn" id="ns-btn">+ New Session</button>';let t=e.recent||[],n=document.createElement("div");n.className="sidebar-section-label"+(L?" clickable":""),n.textContent=L?"\u2190 \u8FD4\u56DE\u672C\u673A":"\u672C\u673A",L&&(n.title="Back to hub",n.addEventListener("click",()=>{window.location.href="/"})),f.appendChild(n),En(t,e.home);let s=e.agents||[];for(let o of s){if(!o.sessions||o.sessions.length===0)continue;let c=o.agentId===L,l=document.createElement("div");l.className="sidebar-section-label machine-label"+(o.online?"":" agent-offline-label")+(!c&&o.online?" clickable":""),l.textContent=o.agentName+(o.online?"":" (offline)"),!c&&o.online&&(l.title="\u6253\u5F00 "+o.agentName,l.addEventListener("click",()=>{window.location.href="/a/"+encodeURIComponent(o.agentId)+"/"})),f.appendChild(l);for(let
|
|
12
|
-
<span>${h(
|
|
13
|
-
<span>${h(c.name)}</span><span class="meta">\u5931\u6548${
|
|
11
|
+
`,t.addEventListener("click",s=>{s.target.closest(".session-edit-btn")||fe(e.name)});let n=t.querySelector(".session-edit-btn");return n&&n.addEventListener("click",s=>{s.stopPropagation(),Dt(e.name,n)}),t}function xn(e){f.innerHTML='<button class="new-session-sidebar-btn" id="ns-btn">+ New Session</button>';let t=e.recent||[],n=document.createElement("div");n.className="sidebar-section-label"+(L?" clickable":""),n.textContent=L?"\u2190 \u8FD4\u56DE\u672C\u673A":"\u672C\u673A",L&&(n.title="Back to hub",n.addEventListener("click",()=>{window.location.href="/"})),f.appendChild(n),En(t,e.home);let s=e.agents||[];for(let o of s){if(!o.sessions||o.sessions.length===0)continue;let c=o.agentId===L,l=document.createElement("div");l.className="sidebar-section-label machine-label"+(o.online?"":" agent-offline-label")+(!c&&o.online?" clickable":""),l.textContent=o.agentName+(o.online?"":" (offline)"),!c&&o.online&&(l.title="\u6253\u5F00 "+o.agentName,l.addEventListener("click",()=>{window.location.href="/a/"+encodeURIComponent(o.agentId)+"/"})),f.appendChild(l);for(let d of o.sessions){let p=document.createElement("div");p.className="session-item"+(d.name===g&&L===o.agentId?" active":"")+(o.online?"":" session-offline"),p.setAttribute("data-session",d.name),p.setAttribute("data-agent",o.agentId),d.path&&(p.title=d.path),p.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="${d.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>
|
|
12
|
+
<span>${h(d.name)}</span><span class="meta">${o.online?"":"offline"}</span>`,o.online&&p.addEventListener("click",w=>{w.target.closest(".session-edit-btn")||fe(d.name,o.agentId)}),f.appendChild(p)}}let r=e.tombstones||[];if(r.length>0){let o=document.createElement("div");o.className="sidebar-section-label tombstone-label",o.textContent="\u5931\u6548\u4F1A\u8BDD",f.appendChild(o);for(let c of r){let l=document.createElement("div");l.className="session-item session-tombstone",l.setAttribute("data-session",c.name),c.agentId&&l.setAttribute("data-agent",c.agentId);let d=c.agentId?c.agentOnline?" (agent)":" (agent \u79BB\u7EBF)":"";l.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"></svg>
|
|
13
|
+
<span>${h(c.name)}</span><span class="meta">\u5931\u6548${d}</span>
|
|
14
14
|
<button class="session-edit-btn" data-session="${h(c.name)}" title="\u6062\u590D\u4F1A\u8BDD"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>`;let p=l.querySelector(".session-edit-btn");p&&p.addEventListener("click",w=>{w.stopPropagation(),Dt(c.name,p,{tombstone:!0,agentId:c.agentId})}),f.appendChild(l)}}}function h(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}async function fe(e,t){if(!(g===e&&v&&L===(t||null))){ue.style.display="none",q.style.display="none",I.style.display="",I.classList.add("terminal-pending"),Ve(),v&&(Pe(),v.destroy(),v=null),g=e,L=t||null,window.__tmuxWebScopeAgent=L,window.__tmuxWebCurrentSession=g,Un(e,t);for(let n of f.querySelectorAll(".session-item"))n.classList.toggle("active",n.getAttribute("data-session")===e&&(n.getAttribute("data-agent")||null)===L);try{v=await fn(I,e,{terminal:de.terminal,scrollback:de.scrollback,theme:de.theme,wsBase:L?"/ws/a/"+encodeURIComponent(L):de.wsBase||"/ws"}),Bt()}catch(n){console.error("[shell] terminal init failed:",n);let s=n&&typeof n=="object"&&"message"in n?n.message:String(n);I.textContent="Failed to open terminal for "+e+": "+s,I.classList.remove("terminal-pending")}}}var De=[],y=null,Et=!1;function Cn(e){if(!y||!y.files.length)return null;let t=y.repoRoot;if(!t||!e.startsWith(t))return null;let n=e.slice(t.length+1);for(let s of y.files)if(s.path===n)return s.status;return null}async function kn(e){Et=!0;try{let t=await fetch(C("/api/git/status?path="+encodeURIComponent(e)));t.ok?y=await t.json():y=null}catch{y=null}finally{Et=!1}}function Sn(){if(!y||!y.branch)return"";let{branch:e,linesAdded:t,linesRemoved:n}=y,s=`<div class="sidebar-git"><div class="git-branch-badge">
|
|
15
15
|
<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>
|
|
16
16
|
${h(e)}</div>`;return(t>0||n>0)&&(s+=`<div class="git-diff-stats">+<span class="add">${t}</span> <span class="del">-${n}</span></div>`),s+"</div>"}f.addEventListener("click",e=>{e.target.closest(".sidebar-git")&&Q&&y&&(e.stopPropagation(),St())});var me=document.getElementById("header-git"),Lt=document.getElementById("git-diff-view"),xt=document.getElementById("gd-path"),He=document.getElementById("gd-status"),Ae=document.getElementById("gd-content"),Tn=document.getElementById("gd-back"),Q=null;function he(e){if(!e||!e.branch){me.style.display="none",Q=null;return}Q=e.repoRoot;let{branch:t,linesAdded:n,linesRemoved:s}=e,r=`<span class="branch">${h(t)}</span>`;(n>0||s>0)&&(r+=`<span class="sep">\xB7</span>+<span class="diff-add">${n}</span> <span class="diff-del">-${s}</span>`),me.innerHTML=r,me.style.display="block"}me.addEventListener("click",e=>{Q&&y&&(e.stopPropagation(),St())});var k=document.getElementById("git-popover"),Fe=document.getElementById("git-popover-backdrop");function Xe(){let e=me.getBoundingClientRect();k.style.top=e.bottom+4+"px",k.style.left=Math.max(8,Math.min(e.left,window.innerWidth-400))+"px"}function Ct(){let e=Q,t=document.getElementById("git-popover-browse");t&&t.addEventListener("click",()=>{if(Ne(),e){qe="files",document.querySelectorAll(".mode-btn").forEach(s=>s.classList.remove("active"));let n=document.getElementById("mode-files");n&&n.classList.add("active"),_(e)}})}var kt="";function St(){if(!y)return;let e=y.files||[];if(!e.length)k.innerHTML=`<div class="git-popover-header">No changes \u2014 clean working tree</div>
|
|
@@ -20,7 +20,7 @@ var cn=/\x1b\](?:10|11|110|111|104)(?:;[^\x07\x1b]*)?\x1b?(?:\\|\x07)/g;function
|
|
|
20
20
|
<span class="file-del">${o>0?"-"+o:""}</span>
|
|
21
21
|
</div>`}t+='<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>',kt=t,k.innerHTML=t,k.querySelectorAll(".git-popover-item").forEach(n=>{let s=parseInt(n.dataset.idx||"0",10),r=e[s];!r||r.status==="D"||(n.classList.add("clickable"),n.style.cursor="pointer",n.addEventListener("click",()=>Mt(r.path)))})}Xe(),k.classList.add("open"),Fe.classList.add("open"),Ct()}function Mn(){return window.innerWidth>=1024}function Tt(e,t){let n=(e+(t&&e?`
|
|
22
22
|
`:"")+t).split(`
|
|
23
|
-
`),s="",r=0,o=0;for(let c of n){let l=c;if(l.startsWith("@@")){let
|
|
23
|
+
`),s="",r=0,o=0;for(let c of n){let l=c;if(l.startsWith("@@")){let d=l.match(/@@\s+-(\d+)[^+]*\+(\d+)/);d&&(r=parseInt(d[1],10)-1,o=parseInt(d[2],10)-1),s+=`<div class="diff-line hunk"><span class="ln-body">${h(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")&&(s+=`<div class="diff-line header"><span class="ln-body">${h(l)}</span></div>`);continue}if(l.startsWith("+"))o++,s+=`<div class="diff-line add"><span class="ln-no">${o}</span><span class="ln-body">${h(l)}</span></div>`;else if(l.startsWith("-"))r++,s+=`<div class="diff-line del"><span class="ln-no">${r}</span><span class="ln-body">${h(l)}</span></div>`;else if(l.startsWith("\\"))s+=`<div class="diff-line"><span class="ln-body">${h(l)}</span></div>`;else{if(!l&&!r&&!o)continue;r++,o++,s+=`<div class="diff-line"><span class="ln-no">${r}</span><span class="ln-no" style="margin-right:12px">${o}</span><span class="ln-body">${h(l)}</span></div>`}}return{html:s,lineCount:n.length}}var Re=null;async function Mt(e){let t=Q;if(t)if(Ne(),Mn()){I.style.display="none",v&&(Pe(),v.destroy(),v=null,Re=g,g=null),he(null),ue.style.display="none",q.style.display="none",Lt.style.display="flex",xt.textContent=e,He.textContent="Loading\u2026",Ae.innerHTML="";try{let n=await fetch(C("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!n.ok)throw new Error(await n.text());let s=await n.json();Bn(e,s.diff,s.stagedDiff)}catch(n){let s=n instanceof Error?n.message:String(n);He.textContent="Error",Ae.innerHTML=`<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">Error: ${h(s)}</div>`}}else{k.innerHTML=`<div class="git-diff-view"><div class="diff-header">
|
|
24
24
|
<button class="diff-back">\u2190 Back</button>
|
|
25
25
|
<span class="diff-filename">${h(e)}</span>
|
|
26
26
|
<span class="diff-loading">Loading\u2026</span>
|
|
@@ -34,7 +34,7 @@ var cn=/\x1b\](?:10|11|110|111|104)(?:;[^\x07\x1b]*)?\x1b?(?:\\|\x07)/g;function
|
|
|
34
34
|
<button class="diff-back">\u2190 Back</button>
|
|
35
35
|
<span class="diff-filename">${h(e)}</span>
|
|
36
36
|
<span class="diff-filesize">${r} lines</span>
|
|
37
|
-
</div><div class="diff-content">${s}</div></div>`,k.querySelector(".diff-back")?.addEventListener("click",()=>{k.innerHTML=kt,Xe(),y&&k.querySelectorAll(".git-popover-item").forEach(o=>{let c=parseInt(o.dataset.idx||"0",10),l=y.files[c];!l||l.status==="D"||(o.style.cursor="pointer",o.addEventListener("click",()=>Mt(l.path)))}),Ct()})}function Bn(e,t,n){if(!t&&!n){He.textContent="No diff",Ae.innerHTML='<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">No diff content available</div>';return}let{html:s,lineCount:r}=Tt(t,n);xt.textContent=e,He.textContent=r+" lines",Ae.innerHTML=s}function Dn(){Lt.style.display="none",Re?(I.style.display="",I.classList.add("terminal-pending"),fe(Re),Re=null):g?(I.style.display="",I.classList.add("terminal-pending"),Bt()):q.style.display="flex"}Tn.addEventListener("click",Dn);function Ne(){k.classList.remove("open"),Fe.classList.remove("open")}Fe.addEventListener("click",Ne),document.addEventListener("keydown",e=>{e.key==="Escape"&&(Ne(),ze())});async function It(e){try{let t=await(await fetch("/api/fs/session-path?session="+encodeURIComponent(e))).json();if(t.path){let n=await fetch("/api/git/status?path="+encodeURIComponent(t.path));if(n.ok){let s=await n.json();y=s,he(s);return}}}catch{}y=null,he(null)}var $e=null;function Bt(){Pe(),g&&(It(g),$e=setInterval(()=>{g&&It(g)},3e4))}function Pe(){$e&&(clearInterval($e),$e=null)}function Hn(){if(De=de.fsRoots||[],De.length===0){if(g){An(g);return}f.innerHTML='<div class="file-tree-info">Open a session first, then switch to Files to browse its directory.</div>';return}f.innerHTML="";for(let e of De){let t=document.createElement("div");t.className="file-tree-item",t.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor" class="file-icon"><path d="M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/></svg> ${h(e)}`,t.addEventListener("click",()=>_(e)),f.appendChild(t)}}async function An(e){f.innerHTML='<div class="file-tree-empty">Loading...</div>';try{let t=await(await fetch(C("/api/fs/session-path?session="+encodeURIComponent(e)))).json();t.path?_(t.path):f.innerHTML='<div class="file-tree-info">Could not determine session directory.</div>'}catch{f.innerHTML='<div class="file-tree-error">Failed to get session directory</div>'}}async function _(e){j=e,f.innerHTML='<div class="file-tree-empty">Loading...</div>';let t=kn(e);try{let n=await(await fetch(C("/api/fs/list?path="+encodeURIComponent(e)))).json();await t,f.innerHTML="",he(y),f.innerHTML+=Sn();let s=Fn(e);if(s&&!De.some(o=>e===o)){let o=document.createElement("div");o.className="file-tree-item",o.innerHTML="..",o.addEventListener("click",()=>_(s)),f.appendChild(o)}if(n.dirs)for(let o of n.dirs){let c=o.split("/").pop()||o.split("\\").pop(),l=document.createElement("div");l.className="file-tree-item",l.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor" class="file-icon"><path d="M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/></svg> ${h(c)}`,l.addEventListener("click",()=>_(o)),f.appendChild(l)}else f.innerHTML="";let r=n.files||[];for(let o of r){let c=o.split("/").pop()||o.split("\\").pop(),l=Cn(o),
|
|
37
|
+
</div><div class="diff-content">${s}</div></div>`,k.querySelector(".diff-back")?.addEventListener("click",()=>{k.innerHTML=kt,Xe(),y&&k.querySelectorAll(".git-popover-item").forEach(o=>{let c=parseInt(o.dataset.idx||"0",10),l=y.files[c];!l||l.status==="D"||(o.style.cursor="pointer",o.addEventListener("click",()=>Mt(l.path)))}),Ct()})}function Bn(e,t,n){if(!t&&!n){He.textContent="No diff",Ae.innerHTML='<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">No diff content available</div>';return}let{html:s,lineCount:r}=Tt(t,n);xt.textContent=e,He.textContent=r+" lines",Ae.innerHTML=s}function Dn(){Lt.style.display="none",Re?(I.style.display="",I.classList.add("terminal-pending"),fe(Re),Re=null):g?(I.style.display="",I.classList.add("terminal-pending"),Bt()):q.style.display="flex"}Tn.addEventListener("click",Dn);function Ne(){k.classList.remove("open"),Fe.classList.remove("open")}Fe.addEventListener("click",Ne),document.addEventListener("keydown",e=>{e.key==="Escape"&&(Ne(),ze())});async function It(e){try{let t=await(await fetch("/api/fs/session-path?session="+encodeURIComponent(e))).json();if(t.path){let n=await fetch("/api/git/status?path="+encodeURIComponent(t.path));if(n.ok){let s=await n.json();y=s,he(s);return}}}catch{}y=null,he(null)}var $e=null;function Bt(){Pe(),g&&(It(g),$e=setInterval(()=>{g&&It(g)},3e4))}function Pe(){$e&&(clearInterval($e),$e=null)}function Hn(){if(De=de.fsRoots||[],De.length===0){if(g){An(g);return}f.innerHTML='<div class="file-tree-info">Open a session first, then switch to Files to browse its directory.</div>';return}f.innerHTML="";for(let e of De){let t=document.createElement("div");t.className="file-tree-item",t.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor" class="file-icon"><path d="M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/></svg> ${h(e)}`,t.addEventListener("click",()=>_(e)),f.appendChild(t)}}async function An(e){f.innerHTML='<div class="file-tree-empty">Loading...</div>';try{let t=await(await fetch(C("/api/fs/session-path?session="+encodeURIComponent(e)))).json();t.path?_(t.path):f.innerHTML='<div class="file-tree-info">Could not determine session directory.</div>'}catch{f.innerHTML='<div class="file-tree-error">Failed to get session directory</div>'}}async function _(e){j=e,f.innerHTML='<div class="file-tree-empty">Loading...</div>';let t=kn(e);try{let n=await(await fetch(C("/api/fs/list?path="+encodeURIComponent(e)))).json();await t,f.innerHTML="",he(y),f.innerHTML+=Sn();let s=Fn(e);if(s&&!De.some(o=>e===o)){let o=document.createElement("div");o.className="file-tree-item",o.innerHTML="..",o.addEventListener("click",()=>_(s)),f.appendChild(o)}if(n.dirs)for(let o of n.dirs){let c=o.split("/").pop()||o.split("\\").pop(),l=document.createElement("div");l.className="file-tree-item",l.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor" class="file-icon"><path d="M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/></svg> ${h(c)}`,l.addEventListener("click",()=>_(o)),f.appendChild(l)}else f.innerHTML="";let r=n.files||[];for(let o of r){let c=o.split("/").pop()||o.split("\\").pop(),l=Cn(o),d="",p="";if(l)switch(l){case"M":d="git-mod",p='<span class="git-file-status M">M</span>';break;case"A":d="git-add",p='<span class="git-file-status A">A</span>';break;case"D":d="git-del",p='<span class="git-file-status D">D</span>';break;case"?":d="git-untracked",p='<span class="git-file-status ?">?</span>';break;case"R":d="git-mod",p='<span class="git-file-status R">R</span>';break}let w=document.createElement("div");w.className="file-tree-item file"+(d?" "+d:""),w.innerHTML=`<span class="file-icon">\u{1F4C4}</span> ${p}${h(c)}`,w.addEventListener("click",()=>Rn(o)),f.appendChild(w)}}catch{f.innerHTML='<div class="file-tree-error">Failed to load directory</div>'}}function Fn(e){let t=e.lastIndexOf("/");return t<=0?null:e.substring(0,t)}async function Rn(e){Ie=e,I.style.display="none",v&&(Pe(),v.destroy(),v=null,g=null),he(null),Ve(),q.style.display="none",ue.style.display="flex",mn.textContent=e,H.textContent="Loading...",K.style.display="none";try{let t=await fetch(C("/api/file?path="+encodeURIComponent(e)));if(!t.ok){let s=await t.json();H.textContent=s.error||"Failed to load",pe.value="";return}let n=await t.json();pe.value=n.content,Be=n.content,ft=n.content,H.textContent=n.size+" bytes",K.style.display=""}catch{H.textContent="Failed to load",pe.value=""}}pe.addEventListener("input",()=>{Be=pe.value}),K.addEventListener("click",async()=>{K.textContent="Saving...",K.disabled=!0;try{let e=await fetch(C("/api/file"),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:Ie,content:Be})});if(!e.ok){let t=await e.json();H.textContent=t.error||"Save failed";return}ft=Be,H.textContent="Saved"}catch{H.textContent="Save failed"}finally{K.disabled=!1,K.textContent="Save"}}),hn.addEventListener("click",async()=>{if(confirm("Delete "+Ie+"?"))try{let e=await fetch(C("/api/file/delete"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:Ie})});if(!e.ok){let t=await e.json();H.textContent=t.error||"Delete failed";return}ue.style.display="none",q.style.display="flex",j&&_(j)}catch{H.textContent="Delete failed"}}),vn.addEventListener("click",()=>{ue.style.display="none",q.style.display="flex",j&&_(j)}),gn.addEventListener("click",async()=>{let e=mt.value.trim();if(!e)return;let t=j+"/"+e;try{let n=await fetch(C("/api/file/touch"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t})});if(!n.ok){let s=await n.json();H.textContent=s.error||"Create failed";return}mt.value="",j&&_(j)}catch{H.textContent="Create failed"}}),document.getElementById("mode-settings").addEventListener("click",()=>{let e=ht.classList.toggle("open");Ke.classList.toggle("open",e)}),Ke.addEventListener("click",()=>{ht.classList.remove("open"),Ke.classList.remove("open")});var B="",$=!1,je,ve=document.createElement("div");ve.className="session-popover-backdrop",document.body.appendChild(ve);var F=document.createElement("div");F.id="session-popover",F.className="session-popover",F.style.display="none",F.innerHTML=`<div class="sp-field">
|
|
38
38
|
<label>Rename session</label>
|
|
39
39
|
<input type="text" id="sp-name" />
|
|
40
40
|
</div>
|
|
@@ -45,4 +45,4 @@ var cn=/\x1b\](?:10|11|110|111|104)(?:;[^\x07\x1b]*)?\x1b?(?:\\|\x07)/g;function
|
|
|
45
45
|
<hr class="sp-divider" />
|
|
46
46
|
<button class="btn primary" id="sp-rebuild" style="display:none">\u91CD\u5EFA\u540C\u540D\u540C\u8DEF\u5F84 session</button>
|
|
47
47
|
<button class="btn danger" id="sp-delete">Delete session</button>`,document.body.appendChild(F);function Nn(e){let t=e.getBoundingClientRect();F.style.top=t.bottom+4+"px",F.style.left=Math.max(8,Math.min(t.left,window.innerWidth-240))+"px"}function Dt(e,t,n){B=e,$=!!n?.tombstone,je=n?.agentId;let s=document.getElementById("sp-name");s.value=e;let r=F.querySelector(".sp-field label");r.textContent=$?"\u91CD\u547D\u540D (\u4EC5\u8BB0\u5F55\uFF0C\u4E0D\u91CD\u5EFA)":"Rename session";let o=document.getElementById("sp-rebuild");o.style.display=$?"":"none";let c=document.getElementById("sp-delete");c.textContent=$?"\u5220\u9664\u5931\u6548\u8BB0\u5F55 (\u5893\u7891\u6D88\u5931)":"Delete session";let l=document.getElementById("sp-save");l.textContent=$?"\u91CD\u547D\u540D":"Save",ve.classList.add("open"),F.style.display="block",Nn(t),setTimeout(()=>s.focus(),50)}function V(){ve.classList.remove("open"),F.style.display="none"}ve.addEventListener("click",V),document.getElementById("sp-save").addEventListener("click",async()=>{let e=document.getElementById("sp-name").value.trim();if(!e||e===B){V();return}try{let t=$?{oldName:B,newName:e,agentId:je}:{oldName:B,newName:e};if(!(await fetch(C($?"/api/sessions/rename-tombstone":"/api/sessions/rename"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).ok)return;V(),z(),!$&&g===B&&fe(e)}catch{}}),document.getElementById("sp-rebuild").addEventListener("click",async()=>{if(confirm('\u91CD\u5EFA\u4F1A\u8BDD "'+B+'" (\u540C\u540D\u540C\u8DEF\u5F84\uFF0C\u5185\u5BB9\u4E3A\u7A7A)\uFF1F'))try{let e=await fetch(C("/api/sessions/rebuild"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:B,agentId:je})});if(!e.ok){let t=await e.json();alert(t.error||"\u91CD\u5EFA\u5931\u8D25");return}V(),z()}catch{}}),document.getElementById("sp-delete").addEventListener("click",async()=>{if($){if(!confirm('\u5220\u9664\u5931\u6548\u8BB0\u5F55 "'+B+'"\uFF1F'))return;try{if(!(await fetch(C("/api/sessions/dismiss"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:B,agentId:je})})).ok)return;V(),z()}catch{}return}if(confirm('Delete session "'+B+'"?'))try{if(!(await fetch(C("/api/sessions/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:B})})).ok)return;V(),g===B&&(v&&(v.destroy(),v=null),g=null,I.style.display="none",q.style.display="flex"),z()}catch{}}),document.getElementById("sp-cancel").addEventListener("click",V);var $n={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"};document.getElementById("mobile-keys").addEventListener("click",e=>{let t=e.target.closest("button[data-key]");if(!t||!v)return;let n=$n[t.dataset.key];n&&(v.sendInput(n),v.focus())});var R=document.getElementById("mk-input"),Ht=document.getElementById("mk-send");function At(){if(!R||!v)return;let e=R.value;e&&(v.sendInput(e+"\r"),R.value="",R.rows=1,v.focus())}if(R&&(R.addEventListener("input",()=>{R.rows=1;let e=R.value.split(`
|
|
48
|
-
`).length;R.rows=Math.min(e,4)}),R.addEventListener("keydown",e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),At())})),Ht&&Ht.addEventListener("click",At),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 Ge=document.getElementById("process-panel"),ge=document.getElementById("proc-list"),Pn=document.getElementById("proc-close"),Ze=document.getElementById("proc-backdrop"),jn=document.getElementById("header-ram");function zn(){ge.innerHTML='<div class="proc-empty">Loading\u2026</div>',fetch(C("/api/system/processes")).then(e=>e.json()).then(e=>{if(!Array.isArray(e)||!e.length){ge.innerHTML='<div class="proc-empty">No processes</div>';return}let t="";for(let n of e){let s=n.rss,r=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">'+r+'</span><span class="proc-cmd" title="'+h(n.command)+'">'+h(n.command)+'</span><button class="proc-kill" title="Kill PID '+n.pid+'">×</button></div>'}ge.innerHTML=t;for(let n of ge.querySelectorAll(".proc-row")){let s=n.querySelector(".proc-kill");s&&s.addEventListener("click",r=>{let o=r.target.closest(".proc-row");!o||!confirm("Kill PID "+o.dataset.pid+"?")||fetch(C("/api/system/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:parseInt(o.dataset.pid,10)})}).then(c=>c.json()).then(c=>{c.ok?o.style.opacity="0.3":alert("Failed: "+(c.error||"unknown"))}).catch(()=>alert("Network error"))})}}).catch(()=>{ge.innerHTML='<div class="proc-empty">Failed to load</div>'})}function _n(){Ge.classList.add("open"),Ze.classList.add("open"),zn()}function ze(){Ge.classList.remove("open"),Ze.classList.remove("open")}jn.addEventListener("click",e=>{e.stopPropagation(),Ge.classList.contains("open")?ze():_n()}),Pn.addEventListener("click",ze),Ze.addEventListener("click",ze);var Wn=2e3,ye=null,Qe=null,ee=new Map,we=new Map;function Ft(e,t){return(t?"a:"+t+":":"l:")+e}function On(e,t,n){let s=Ft(e,t),r=we.get(s),o=e===g&&(t??null)===L,c=n==="idle"&&r?.state==="working";we.set(s,{session:e,agentId:t,state:n,doneUntil:c?Date.now()+Wn:void 0,unread:c?!o:!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])',
|
|
48
|
+
`).length;R.rows=Math.min(e,4)}),R.addEventListener("keydown",e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),At())})),Ht&&Ht.addEventListener("click",At),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 Ge=document.getElementById("process-panel"),ge=document.getElementById("proc-list"),Pn=document.getElementById("proc-close"),Ze=document.getElementById("proc-backdrop"),jn=document.getElementById("header-ram");function zn(){ge.innerHTML='<div class="proc-empty">Loading\u2026</div>',fetch(C("/api/system/processes")).then(e=>e.json()).then(e=>{if(!Array.isArray(e)||!e.length){ge.innerHTML='<div class="proc-empty">No processes</div>';return}let t="";for(let n of e){let s=n.rss,r=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">'+r+'</span><span class="proc-cmd" title="'+h(n.command)+'">'+h(n.command)+'</span><button class="proc-kill" title="Kill PID '+n.pid+'">×</button></div>'}ge.innerHTML=t;for(let n of ge.querySelectorAll(".proc-row")){let s=n.querySelector(".proc-kill");s&&s.addEventListener("click",r=>{let o=r.target.closest(".proc-row");!o||!confirm("Kill PID "+o.dataset.pid+"?")||fetch(C("/api/system/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:parseInt(o.dataset.pid,10)})}).then(c=>c.json()).then(c=>{c.ok?o.style.opacity="0.3":alert("Failed: "+(c.error||"unknown"))}).catch(()=>alert("Network error"))})}}).catch(()=>{ge.innerHTML='<div class="proc-empty">Failed to load</div>'})}function _n(){Ge.classList.add("open"),Ze.classList.add("open"),zn()}function ze(){Ge.classList.remove("open"),Ze.classList.remove("open")}jn.addEventListener("click",e=>{e.stopPropagation(),Ge.classList.contains("open")?ze():_n()}),Pn.addEventListener("click",ze),Ze.addEventListener("click",ze);var Wn=2e3,ye=null,Qe=null,ee=new Map,we=new Map;function Ft(e,t){return(t?"a:"+t+":":"l:")+e}function On(e,t,n){let s=Ft(e,t),r=we.get(s),o=e===g&&(t??null)===L,c=n==="idle"&&r?.state==="working";we.set(s,{session:e,agentId:t,state:n,doneUntil:c?Date.now()+Wn:void 0,unread:c?!o:!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])',d=f.querySelector(l);d&&et(d,s,we.get(s))}function et(e,t,n){let s=ee.get(t);s&&(clearTimeout(s),ee.delete(t)),e.classList.remove("working","just-done");let r=n.session===g&&(n.agentId??null)===L;n.state==="working"?e.classList.add("working"):r&&n.doneUntil&&Date.now()<n.doneUntil?(e.classList.add("just-done"),ee.set(t,setTimeout(()=>{e.classList.remove("just-done"),ee.delete(t)},Math.max(0,n.doneUntil-Date.now())))):!r&&n.unread&&e.classList.add("just-done")}function tt(){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])',s=f.querySelector(n);s&&et(s,e,t)}}function Un(e,t){let n=Ft(e,t),s=we.get(n);if(!s)return;let r=ee.get(n);r&&(clearTimeout(r),ee.delete(n)),s.doneUntil=void 0,s.unread=!1;let o=t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',c=f.querySelector(o);c&&et(c,n,s)}function Rt(){if(ye||Qe)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);ye=n,n.onmessage=s=>{try{let r=JSON.parse(String(s.data));r&&r.type==="session.activity"&&typeof r.session=="string"&&On(r.session,r.agentId||void 0,r.state==="working"?"working":"idle")}catch{}},n.onclose=()=>{ye===n&&(ye=null,Qe=setTimeout(()=>{Qe=null,Rt()},5e3))},n.onerror=()=>{try{n.close()}catch{}}}catch{ye=null}}window.__openSession=fe,window.__refreshSidebar=z,z(),Ve(),tt(),Rt(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&tt()}),setInterval(()=>{document.visibilityState==="visible"&&z()},1e4);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import{initTerminal as De}from"./terminal-core.js";const $=window.__TMUX_WEB_SHELL__;let f=null,u=null;const ue=typeof window.__TMUX_WEB_SCOPE__?.agentId=="string"?window.__TMUX_WEB_SCOPE__.agentId:null;let v=ue;window.__tmuxWebScopeAgent=ue;let ne="sessions",I="",F="",G="",me="";function g(e){return v?"/a/"+encodeURIComponent(v)+e:e}const d=document.getElementById("sidebar-content"),M=document.getElementById("main-placeholder"),b=document.getElementById("terminal-container"),A=document.getElementById("file-editor"),Pe=document.getElementById("fe-path"),E=document.getElementById("fe-status"),_=document.getElementById("fe-content"),T=document.getElementById("fe-save"),je=document.getElementById("fe-delete"),Oe=document.getElementById("fe-back"),ve=document.getElementById("fe-new-name"),We=document.getElementById("fe-new-btn"),se=document.getElementById("settings-backdrop"),ge=document.getElementById("settings-popover"),ye=document.querySelector(".sidebar");function Ue(){return window.matchMedia("(max-width: 640px)").matches}function ie(){Ue()&&ye.classList.add("collapsed")}function he(){ye.classList.remove("collapsed")}document.getElementById("mode-sessions").addEventListener("click",()=>{he(),be("sessions")}),document.getElementById("mode-files").addEventListener("click",()=>{he(),be("files")});function be(e){ne=e,document.querySelectorAll(".mode-btn").forEach(t=>t.classList.remove("active"));const n=document.getElementById(e==="sessions"?"mode-sessions":"mode-files");n&&n.classList.add("active"),e==="sessions"?(oe="",B()):nt()}let oe="";async function B(){if(ne!=="sessions")return;try{const t=await(await fetch("/api/sidebar/sessions")).json(),s=JSON.stringify({recent:t.recent,agents:t.agents,tombstones:t.tombstones});if(s===oe)return;oe=s,Ve(t)}catch{d.innerHTML+='<div class="file-tree-empty">Failed to load sessions</div>'}const e=document.getElementById("ns-btn");e&&e.addEventListener("click",()=>{const n=window.__openNewSessionModal;typeof n=="function"?n():document.getElementById("new-session-modal")?.classList.add("open")}),pe()}const we="tmux-web-sidebar-group-collapsed";function Le(){try{return new Set(JSON.parse(localStorage.getItem(we)||"[]"))}catch{return new Set}}function ze(e){try{localStorage.setItem(we,JSON.stringify([...e]))}catch{}}function Fe(e,n,t){if(!e)return"\u2026";const s=t&&(e===t||e.startsWith(t+"/"))?"~"+e.slice(t.length):e,a=s.split("/").filter(Boolean);if(a.length===0)return e;for(let i=1;i<=a.length;i++){const o=a.slice(-i).join("/");if(!n.some(l=>!l||l===e?!1:(t&&(l===t||l.startsWith(t+"/"))?"~"+l.slice(t.length):l).split("/").filter(Boolean).slice(-i).join("/")===o))return o}return s}function Ge(e,n){const t=new Map;for(const i of e){const o=i.path||"";t.has(o)||t.set(o,[]),t.get(o).push(i)}const s=[...t.keys()],a=Le();for(const[i,o]of t){const c=Fe(i,s,n),l=a.has(i),r=document.createElement("div");r.className="session-group-header"+(l?" collapsed":""),r.title=i||"No working directory",r.innerHTML=`<span class="sg-folder">📁</span><span class="sg-label">${p(c)}</span>`,r.addEventListener("click",()=>{const L=Le(),fe=r.nextElementSibling;L.has(i)?(L.delete(i),r.classList.remove("collapsed"),fe?.classList.remove("collapsed")):(L.add(i),r.classList.add("collapsed"),fe?.classList.add("collapsed")),ze(L)});const h=document.createElement("div");h.className="session-group-body"+(l?" collapsed":"");for(const L of o)h.appendChild(qe(L));d.appendChild(r),d.appendChild(h)}}function qe(e){const n=document.createElement("div");n.className="session-item"+(e.name===u&&!v?" active":""),n.setAttribute("data-session",e.name),n.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="${e.attached?"M19 4H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zm0 14H5V6h14v12z":"M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"}"></svg>
|
|
2
2
|
<span>${p(e.name)}</span>
|
|
3
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>
|
|
4
|
-
`,n.addEventListener("click",s=>{s.target.closest(".session-edit-btn")||D(e.name)});const t=n.querySelector(".session-edit-btn");return t&&t.addEventListener("click",s=>{s.stopPropagation(),Ne(e.name,t)}),n}function Ve(e){d.innerHTML='<button class="new-session-sidebar-btn" id="ns-btn">+ New Session</button>';const n=e.recent||[],t=document.createElement("div");t.className="sidebar-section-label"+(v?" clickable":""),t.textContent=v?"\u2190 \u8FD4\u56DE\u672C\u673A":"\u672C\u673A",v&&(t.title="Back to hub",t.addEventListener("click",()=>{window.location.href="/"})),d.appendChild(t),Ge(n,e.home);const s=e.agents||[];for(const i of s){if(!i.sessions||i.sessions.length===0)continue;const o=i.agentId===v,c=document.createElement("div");c.className="sidebar-section-label machine-label"+(i.online?"":" agent-offline-label")+(!o&&i.online?" clickable":""),c.textContent=i.agentName+(i.online?"":" (offline)"),!o&&i.online&&(c.title="\u6253\u5F00 "+i.agentName,c.addEventListener("click",()=>{window.location.href="/a/"+encodeURIComponent(i.agentId)+"/"})),d.appendChild(c);for(const l of i.sessions){const r=document.createElement("div");r.className="session-item"+(l.name===u&&v===i.agentId?" active":"")+(i.online?"":" session-offline"),r.setAttribute("data-session",l.name),r.setAttribute("data-agent",i.agentId),r.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="${l.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
|
+
`,n.addEventListener("click",s=>{s.target.closest(".session-edit-btn")||D(e.name)});const t=n.querySelector(".session-edit-btn");return t&&t.addEventListener("click",s=>{s.stopPropagation(),Ne(e.name,t)}),n}function Ve(e){d.innerHTML='<button class="new-session-sidebar-btn" id="ns-btn">+ New Session</button>';const n=e.recent||[],t=document.createElement("div");t.className="sidebar-section-label"+(v?" clickable":""),t.textContent=v?"\u2190 \u8FD4\u56DE\u672C\u673A":"\u672C\u673A",v&&(t.title="Back to hub",t.addEventListener("click",()=>{window.location.href="/"})),d.appendChild(t),Ge(n,e.home);const s=e.agents||[];for(const i of s){if(!i.sessions||i.sessions.length===0)continue;const o=i.agentId===v,c=document.createElement("div");c.className="sidebar-section-label machine-label"+(i.online?"":" agent-offline-label")+(!o&&i.online?" clickable":""),c.textContent=i.agentName+(i.online?"":" (offline)"),!o&&i.online&&(c.title="\u6253\u5F00 "+i.agentName,c.addEventListener("click",()=>{window.location.href="/a/"+encodeURIComponent(i.agentId)+"/"})),d.appendChild(c);for(const l of i.sessions){const r=document.createElement("div");r.className="session-item"+(l.name===u&&v===i.agentId?" active":"")+(i.online?"":" session-offline"),r.setAttribute("data-session",l.name),r.setAttribute("data-agent",i.agentId),l.path&&(r.title=l.path),r.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="${l.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>
|
|
5
5
|
<span>${p(l.name)}</span><span class="meta">${i.online?"":"offline"}</span>`,i.online&&r.addEventListener("click",h=>{h.target.closest(".session-edit-btn")||D(l.name,i.agentId)}),d.appendChild(r)}}const a=e.tombstones||[];if(a.length>0){const i=document.createElement("div");i.className="sidebar-section-label tombstone-label",i.textContent="\u5931\u6548\u4F1A\u8BDD",d.appendChild(i);for(const o of a){const c=document.createElement("div");c.className="session-item session-tombstone",c.setAttribute("data-session",o.name),o.agentId&&c.setAttribute("data-agent",o.agentId);const l=o.agentId?o.agentOnline?" (agent)":" (agent \u79BB\u7EBF)":"";c.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"></svg>
|
|
6
6
|
<span>${p(o.name)}</span><span class="meta">\u5931\u6548${l}</span>
|
|
7
7
|
<button class="session-edit-btn" data-session="${p(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>`;const r=c.querySelector(".session-edit-btn");r&&r.addEventListener("click",h=>{h.stopPropagation(),Ne(o.name,r,{tombstone:!0,agentId:o.agentId})}),d.appendChild(c)}}}function p(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}async function D(e,n){if(!(u===e&&f&&v===(n||null))){A.style.display="none",M.style.display="none",b.style.display="",b.classList.add("terminal-pending"),ie(),f&&(Q(),f.destroy(),f=null),u=e,v=n||null,window.__tmuxWebScopeAgent=v,window.__tmuxWebCurrentSession=u,mt(e,n);for(const t of d.querySelectorAll(".session-item"))t.classList.toggle("active",t.getAttribute("data-session")===e&&(t.getAttribute("data-agent")||null)===v);try{f=await De(b,e,{terminal:$.terminal,scrollback:$.scrollback,theme:$.theme,wsBase:v?"/ws/a/"+encodeURIComponent(v):$.wsBase||"/ws"}),He()}catch(t){console.error("[shell] terminal init failed:",t);const s=t&&typeof t=="object"&&"message"in t?t.message:String(t);b.textContent="Failed to open terminal for "+e+": "+s,b.classList.remove("terminal-pending")}}}let q=[],m=null,Ee=!1;function Je(e){if(!m||!m.files.length)return null;const n=m.repoRoot;if(!n||!e.startsWith(n))return null;const t=e.slice(n.length+1);for(const s of m.files)if(s.path===t)return s.status;return null}async function Ke(e){Ee=!0;try{const n=await fetch(g("/api/git/status?path="+encodeURIComponent(e)));n.ok?m=await n.json():m=null}catch{m=null}finally{Ee=!1}}function Xe(){if(!m||!m.branch)return"";const{branch:e,linesAdded:n,linesRemoved:t}=m;let s=`<div class="sidebar-git"><div class="git-branch-badge">
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{chmodSync as he,existsSync as z,readdirSync as ge,statSync as ye}from"node:fs";import{createRequire as G}from"node:module";import{hostname as U}from"node:os";const
|
|
2
|
+
import{chmodSync as he,existsSync as z,readdirSync as ge,statSync as ye}from"node:fs";import{createRequire as G}from"node:module";import{hostname as U,networkInterfaces as ke}from"node:os";const ve=G(import.meta.url),{version:Te}=ve("../package.json");import $ from"node:path";import{fileURLToPath as _e}from"node:url";import{serve as we}from"@hono/node-server";import{WebSocketServer as Se,WebSocket as E}from"ws";try{const e=$.dirname(G(import.meta.url).resolve("node-pty/package.json")),t=$.join(e,"prebuilds");if(z(t))for(const o of ge(t)){const n=$.join(t,o,"spawn-helper");z(n)&&!(ye(n).mode&73)&&he(n,493)}}catch{}import{loadSecurityConfig as Ae}from"./lib/security-config.js";import{TokenStore as Ce,hashPassword as be,verifyPassword as xe,validatePassword as Ie}from"./lib/auth.js";import{RateLimiter as Pe}from"./lib/rateLimiter.js";import{audit as d}from"./lib/auditLog.js";import{db as N}from"./lib/db.js";import{handleClientMessage as V}from"./lib/ws-message.js";import{loadDotEnv as Re}from"./lib/load-env.js";import{listSessions as Me,resolveTmuxSocketPath as Oe}from"./sessions.js";import{cmdSetup as $e,cmdTheme as Ne,printUsage as X,printVersion as Le}from"./lib/cli.js";import{readSettings as Ue}from"./lib/settings.js";import{readActiveTheme as Ee}from"./lib/theme-store.js";import{buildApp as Y}from"./lib/build-app.js";import{attachTerminal as Fe,killAllAttachedPtys as je}from"./lib/attach-terminal.js";import{acquireControlClient as K,killAllControlClients as He}from"./lib/tmux-control.js";import{getSessionPaneTarget as Q,capturePaneTail as Z,capturePaneHistoryChunk as q,toCrlf as ee}from"./lib/tmux-capture.js";import{readTerminalBufferConfig as Be}from"./lib/terminal-config.js";import{AgentRegistry as We}from"./lib/agent-registry.js";import{AgentChannel as Je,MAX_RELAY_CONNS_PER_AGENT as De}from"./lib/agent-relay.js";import{findAgentTokenByPlaintext as ze,listAgentTokens as Ge}from"./lib/agent-tokens.js";import{saveSecurityConfig as Ve}from"./lib/security-config.js";import{readFederationConfig as Xe,writeFederationConfig as Ye}from"./lib/federation-config.js";import{startAgentClient as Ke}from"./lib/agent-client.js";import{ActivityProbe as Qe}from"./lib/activity-probe.js";import{upsertSessionState as te}from"./lib/session-state.js";import{sessionWorkingPath as Ze}from"./lib/sessions-sidebar.js";Re();const F=Be(),g=Ae(),v=new Ce,A=new Pe;let J=!1;const qe="tmux-web-token";function j(e){if(g.security.trustProxy){const t=(e.headers["x-forwarded-for"]||"").split(",")[0].trim();if(t)return t}return e.socket.remoteAddress||"unknown"}function H(e){const t=e.headers.authorization;if(typeof t=="string"&&t.startsWith("Bearer "))return t.slice(7);const o=e.headers.cookie;if(typeof o!="string")return null;const n=o.match(new RegExp(`(?:^|;\\s*)${qe}=([^;]+)`));return n?decodeURIComponent(n[1]):null}function Vt(e){const t=H(e);return t?v.validateToken(t):null}const R=new Map;function et(e){let t=0;for(const o of R.values())o.ip===e&&t++;return t}function b(e,t,o){try{e.close(t,o)}catch{}}function ne(e,t){e.readyState===E.OPEN&&e.send(JSON.stringify(t))}const oe=process.argv.slice(2),L=oe;if(L.length>0){const[e,t]=L;switch(e){case"setup":await $e(L),process.exit(0);case"theme":await Ne(L.slice(1)),process.exit(0);case"agent":{const o=$.join($.dirname(_e(import.meta.url)),"agent.js"),{spawn:n}=await import("node:child_process"),f=n(process.execPath,[o,...oe],{stdio:"inherit"});f.on("error",s=>{console.error(s),process.exit(1)}),f.on("exit",s=>process.exit(s??0)),await new Promise(()=>{})}case"agent-token":await pt(L.slice(1)),process.exit(0);case"help":case"--help":case"-h":X(),process.exit(0);case"-V":case"--version":case"-v":Le(),process.exit(0);default:console.error(`unknown argument: ${e}`),X(),process.exit(1)}}function P(e,t){e.readyState===E.OPEN&&e.send(JSON.stringify(t))}const re=new Set;await N.read(),N.data.sessionAccess??=[],N.data.pinnedViews??=[],N.data.watchedPanes??=[],N.data.quickCommands??=[];const se=await Ue();let tt=await Ee();const k=new We({onChange:()=>{}}),_=new Map;function ae(e){return k.get(e)?_.get(e)??null:null}const ie={activeTheme:tt,settingUpPassword:!1},nt=Y({mode:"hub",securityConfig:g,tokenStore:v,rateLimiter:A,settings:se,terminalBufferConfig:F,state:ie,federation:{getConfig:()=>x,setConfig:async e=>{x=e,await Ye(e),le(e)},status:rt,hostname:U()},hub:{agents:k,getChannel:ae}}),ot=Y({mode:"agent",securityConfig:g,tokenStore:v,rateLimiter:A,settings:se,terminalBufferConfig:F,state:ie});let x=await Xe(),M=null;function ce(){M&&(M.stop(),M=null)}function le(e){ce(),!(!e.enabled||!e.hub||!e.token)&&(M=Ke({hub:e.hub,token:e.token,name:e.name?.trim()||U(),version:Te,app:ot,listSessions:Me,terminalBufferConfig:F,getSessionPaneTarget:Q,capturePaneTail:Z,capturePaneHistoryChunk:q,toCrlf:ee,handleClientMessage:V,acquireControlClient:K}))}function rt(){return x.enabled?M?M.status():{state:"idle",agentId:null,hub:x.hub??"",name:x.name??U()}:{state:"idle",agentId:null,hub:x.hub??"",name:x.name??U()}}le(x);const ue=new Qe,B=new Map;setInterval(()=>{(async()=>{try{const e=await ue.scan(),t=[];for(const[o,n]of e)B.get(o)!==n&&t.push({session:o,state:n});for(const o of B.keys())e.has(o)||t.push({session:o,state:"idle"});B.clear();for(const[o,n]of e)B.set(o,n);for(const o of t)de({type:"session.activity",session:o.session,state:o.state})}catch{}})()},ue.scanMs);const st=parseInt(process.env.PORT||"21000",10);function at(){const e=[];try{for(const t of Object.values(ke()))for(const o of t??[])o.family==="IPv4"&&!o.internal&&e.push(o.address)}catch{}return e}const it=we({fetch:nt.fetch,port:st,hostname:"0.0.0.0"},e=>{console.log(`tmux-web running at http://localhost:${e.port}`);for(const t of at())console.log(` also on http://${t}:${e.port}`)}),O=new Se({noServer:!0}),D=new Set;function de(e){const t=JSON.stringify(e);for(const o of D)o.readyState===E.OPEN&&o.send(t)}function I(e,t,o){e.write(`HTTP/1.1 ${t} ${o}\r
|
|
3
3
|
\r
|
|
4
|
-
`),e.destroy()}
|
|
4
|
+
`),e.destroy()}it.on("upgrade",(e,t,o)=>{const n=new URL(e.url||"/",`http://${e.headers.host}`),f=n.pathname;if(f==="/ws/activity"){const w=j(e),a=H(e)||n.searchParams.get("token")||"";if(!(a?v.validateToken(a):null)){I(t,401,"Unauthorized");return}O.handleUpgrade(e,t,o,c=>{c.on("close",()=>D.delete(c)),D.add(c)});return}if(f==="/agent/ws"){dt(e,t,o);return}const s=f.match(/^\/ws\/a\/([^/]+)\/(.+)$/);if(s){ct(e,t,o,decodeURIComponent(s[1]),decodeURIComponent(s[2]));return}const i=f.match(/^\/ws\/(.+)$/);if(!i){t.destroy();return}const l=j(e),u=e.headers.origin,p=g.security.allowedOrigins;if(u&&!(u===`http://${e.headers.host}`||u===`https://${e.headers.host}`)&&(p.length===0||!p.includes(u))){d("ws_rejected_origin",{ip:l,origin:u}),I(t,403,"Origin not allowed");return}const m=et(l);if(m>=g.security.maxConnectionsPerIp){d("ws_rejected_per_ip_cap",{ip:l,liveFromIp:m}),I(t,429,"Too many connections");return}const y=H(e)||n.searchParams.get("token")||"",T=y?v.validateToken(y):null;O.handleUpgrade(e,t,o,w=>{O.emit("connection",w,e,decodeURIComponent(i[1]),l,T)})}),O.on("connection",(e,t,o,n,f)=>{const s={ws:e,ip:n,authenticated:!1,authTimeout:null},i=(()=>{try{const a=new URL(t.url||"/",`http://${t.headers.host}`).searchParams,r=Number(a.get("cols")),c=Number(a.get("rows"));if(Number.isInteger(r)&&Number.isInteger(c)&&r>0&&c>0&&r<=1e3&&c<=1e3)return{cols:r,rows:c}}catch{}})();R.set(e,s),d("ws_connected",{ip:n});let l=null,u=null;function p(a,r){s.authenticated=!0,s.authTimeout&&(clearTimeout(s.authTimeout),s.authTimeout=null),d("auth_success",{ip:n,method:a,tokenName:r}),P(e,{type:"auth.ok",setupMode:!g.passwordHash}),y()}function m(a,r={}){P(e,{type:"auth.failed",message:a,...r})}function y(){l||(te(o,{path:Ze(o)}),l=Fe(o,{send:a=>P(e,a),onMessage:a=>{u=a},onClose:a=>{T=a}},{terminalBufferConfig:F,getSessionPaneTarget:Q,capturePaneTail:Z,capturePaneHistoryChunk:q,toCrlf:ee,handleClientMessage:V,acquireControlClient:K,initialCols:i?.cols,initialRows:i?.rows,tmuxSocketPath:Oe()??void 0,onPtyExit:(a,r)=>b(e,1e3,"pty exited"),onSpawnError:(a,r)=>b(e,1011,"pty spawn failed")}))}let T=null;async function w(a){let r;try{r=JSON.parse(a)}catch{return!1}if(r.type==="auth.token"&&typeof r.token=="string"){const c=v.validateToken(r.token);if(!c){d("token_auth_failed",{ip:n});const h=A.recordFailure(n);return h.permanentLock&&(v.revokeAll(),d("permanent_lock",{ip:n,failures:h.failures})),m("Invalid or expired token",{permanentLock:h.permanentLock,retryAfterMs:h.retryAfterMs}),!0}return v.touch(c.tokenHash),p("token",c.name),!0}if(r.type==="auth"&&typeof r.password=="string"){const c=A.check(n);if(!c.allowed)return d("rate_limited",{ip:n,retryAfterMs:c.retryAfterMs,permanentLock:c.permanentLock}),m("Too many attempts",{permanentLock:c.permanentLock,retryAfterMs:c.retryAfterMs}),!0;if(!g.passwordHash){if(!g.security.allowRemoteSetup&&!mt(n))return d("setup_rejected_remote",{ip:n}),m("First-run setup must be performed from localhost"),!0;if(J)return m("Password setup in progress"),!0;const C=Ie(r.password);if(C)return m(C),!0;J=!0;try{g.passwordHash=await be(r.password),Ve(g),d("password_set",{ip:n})}finally{J=!1}const{stored:W,plaintext:pe}=v.createAccessToken("setup",g.security.tokenTtlDays);return P(e,{type:"auth.ok",setupMode:!0,token:pe}),d("token_created",{ip:n,name:W.name,tokenId:W.id}),d("auth_success",{ip:n,method:"password",tokenName:W.name}),y(),!0}if(!g.passwordHash)return m("Server not configured"),!0;if(!await xe(r.password,g.passwordHash)){const C=A.recordFailure(n);return d("auth_failed",{ip:n,method:"password",failures:C.failures,permanentLock:C.permanentLock}),C.permanentLock&&(v.revokeAll(),d("permanent_lock",{ip:n,failures:C.failures})),m("Incorrect password",{permanentLock:C.permanentLock,retryAfterMs:C.retryAfterMs}),!0}A.recordSuccess(n);const S=`ws-${n}`,{plaintext:me}=v.createAccessToken(S,g.security.tokenTtlDays);return p("password",S),P(e,{type:"auth.ok",setupMode:!1,token:me}),!0}return!1}f?(v.touch(f.tokenHash),p("token",f.name)):(P(e,{type:"auth.required",setupMode:!g.passwordHash}),s.authTimeout=setTimeout(()=>{s.authenticated||(d("auth_timeout",{ip:n}),m("Authentication timeout"),b(e,4e3,"Auth timeout"))},g.security.authTimeoutMs)),e.on("message",async a=>{const r=typeof a=="string"?a:a.toString("utf-8");if(!s.authenticated){if(r.length>1e6){P(e,{type:"auth.failed",message:"Message too large"});return}await w(r)||m("Authentication required");return}if(u)try{u(r)}catch{}}),e.on("close",()=>{s.authTimeout&&clearTimeout(s.authTimeout),R.delete(e),d("ws_disconnected",{ip:n}),T?.(),l&&(l.dispose(),l=null)}),e.on("error",()=>{s.authTimeout&&clearTimeout(s.authTimeout),R.delete(e),T?.(),l&&(l.dispose(),l=null)})});function ct(e,t,o,n,f){const s=j(e),i=new URL(e.url||"/",`http://${e.headers.host}`),l=H(e)||i.searchParams.get("token")||"";if(!(l?v.validateToken(l):null)){d("ws_rejected_remote_auth",{ip:s,agentId:n}),I(t,401,"Unauthorized");return}const p=ae(n);if(!p){d("ws_rejected_remote_offline",{ip:s,agentId:n}),I(t,503,"Agent offline");return}if(p.relayCount>=De){I(t,429,"Too many connections to agent");return}const m=e.headers.origin,y=g.security.allowedOrigins;if(m&&!(m===`http://${e.headers.host}`||m===`https://${e.headers.host}`)&&(y.length===0||!y.includes(m))){I(t,403,"Origin not allowed");return}const T=ut(),w=(()=>{try{const a=new URL(e.url||"/",`http://${e.headers.host}`).searchParams,r=Number(a.get("cols")),c=Number(a.get("rows"));if(Number.isInteger(r)&&Number.isInteger(c)&&r>0&&c>0&&r<=1e3&&c<=1e3)return{cols:r,rows:c}}catch{}})();O.handleUpgrade(e,t,o,a=>{if(p.registerRelay(T,f,a),k.bumpRelayConns(n,1),te(f,{agentId:n}),!p.attach(T,f,w)){a.send(JSON.stringify({type:"data",data:`\r
|
|
5
5
|
\x1B[31magent offline\x1B[0m\r
|
|
6
|
-
`})),a.close(1011,"agent offline"),p.relayClosed(
|
|
7
|
-
Run on the remote machine:`),console.log(` tmux-web agent --hub wss://YOUR_HUB --token ${u} --name "${i}"`);return}case"list":{const i=o();if(!i.length){console.log("No agent tokens. Create one with: tmux-web agent-token add --name <name>");return}console.log("Agent tokens:");for(const l of i)console.log(` ${l.id} ${l.name} (created ${new Date(l.createdAt).toISOString()})`);return}case"remove":{const i=s.find(u=>!u.startsWith("-"));i||(console.error("usage: tmux-web agent-token remove <id>"),process.exit(1)),
|
|
6
|
+
`})),a.close(1011,"agent offline"),p.relayClosed(T),k.bumpRelayConns(n,-1);return}a.on("message",c=>{const h=typeof c=="string"?c:c.toString("utf-8");let S;try{S=JSON.parse(h)}catch{return}(S.type==="input"||S.type==="resize"||S.type==="load_history")&&p.sendToAgent(T,S)});const r=()=>{p.relayClosed(T),k.bumpRelayConns(n,-1)};a.on("close",r),a.on("error",r)})}let lt=1;function ut(){return lt++}function dt(e,t,o){const n=j(e),f=e.headers.origin;if(f){d("agent_rejected_origin",{ip:n,origin:f}),I(t,403,"Origin not allowed");return}O.handleUpgrade(e,t,o,s=>{let i=null,l=setTimeout(()=>{d("agent_hello_timeout",{ip:n}),b(s,4e3,"hello timeout")},1e4);s.on("message",(u,p)=>{if(i){k.touch(i.agentId),p?i.handleData(Array.isArray(u)?Buffer.concat(u):Buffer.from(u)):i.handleMessage(typeof u=="string"?u:Buffer.from(u).toString("utf-8"));return}const m=typeof u=="string"?u:u.toString("utf-8");let y;try{y=JSON.parse(m)}catch{b(s,1008,"bad hello");return}if(y.type!=="hello"||typeof y.token!="string"){b(s,1008,"expected hello");return}if(!A.check(n).allowed){d("agent_rate_limited",{ip:n}),b(s,429,"Too many attempts");return}const w=ze(y.token);if(!w){A.recordFailure(n),d("agent_bad_token",{ip:n}),ne(s,{type:"hello_err",reason:"invalid token"}),b(s,4003,"invalid token");return}const a=typeof y.name=="string"&&y.name.trim()?y.name.trim().slice(0,64):"agent",r=w.id;if(!k.register(r,a,s,w.tokenHash)){d("agent_cap_reached",{ip:n}),ne(s,{type:"hello_err",reason:"too many agents"}),b(s,4004,"too many agents");return}clearTimeout(l),A.recordSuccess(n),d("agent_connected",{ip:n,agentId:r,name:a}),i=new Je(s,r,{onSessions:h=>k.setSessions(r,h),onActivity:h=>{for(const S of h)de({type:"session.activity",agentId:r,session:S.session,state:S.state})},onRebuildResult:h=>{console.log(`[agent ${r}] rebuild ${h.session}: ${h.ok?"ok":h.message}`)},onClose:h=>{_.get(r)===h&&_.delete(r)}}),_.set(r,i),k.touch(r),s.send(JSON.stringify({type:"hello_ok",agentId:r})),i.sendSessionsReq()}),s.on("close",()=>{i&&(i.dispose(),_.delete(i.agentId),k.unregister(i.agentId),d("agent_disconnected",{ip:n,agentId:i.agentId})),clearTimeout(l)}),s.on("error",()=>{i&&(i.dispose(),_.delete(i.agentId),k.unregister(i.agentId)),clearTimeout(l)})})}const ft=parseInt(process.env.TMUX_WEB_AGENT_OFFLINE_MS||"45000",10);setInterval(()=>{const e=k.pruneOffline(ft);for(const o of e){const n=k.peek(o);n&&n.ws.readyState===E.CLOSED&&(k.unregister(o),_.get(o)?.dispose(),_.delete(o))}const t=new Set(Ge().map(o=>o.tokenHash));for(const[o,n]of _){const f=k.peek(o);if(!(!f||t.has(f.tokenHash))){d("agent_token_revoked",{agentId:o}),n.dispose(),_.delete(o),k.unregister(o);try{f.ws.close(4003,"token revoked")}catch{}}}v.purgeExpired()},10*1e3).unref();function fe(){ce(),He(),je();for(const e of _.values())e.dispose();_.clear();for(const[e,t]of R){try{e.close(1001,"Server shutting down")}catch{}t.authTimeout&&clearTimeout(t.authTimeout)}R.clear();for(const e of re)try{e.kill()}catch{}re.clear(),A.dispose(),process.exit(0)}process.on("SIGINT",fe),process.on("SIGTERM",fe);function mt(e){return e==="127.0.0.1"||e==="::1"||e==="::ffff:127.0.0.1"}async function pt(e){const{createAgentToken:t,listAgentTokens:o,removeAgentToken:n}=await import("./lib/agent-tokens.js"),[f,...s]=e;switch(f){case"add":{const i=s.find(p=>!p.startsWith("-"))||"agent",{id:l,token:u}=t(i);console.log("\u2713 agent token created"),console.log(` id: ${l}`),console.log(` name: ${i}`),console.log(` token: ${u}`),console.log(`
|
|
7
|
+
Run on the remote machine:`),console.log(` tmux-web agent --hub wss://YOUR_HUB --token ${u} --name "${i}"`);return}case"list":{const i=o();if(!i.length){console.log("No agent tokens. Create one with: tmux-web agent-token add --name <name>");return}console.log("Agent tokens:");for(const l of i)console.log(` ${l.id} ${l.name} (created ${new Date(l.createdAt).toISOString()})`);return}case"remove":{const i=s.find(u=>!u.startsWith("-"));i||(console.error("usage: tmux-web agent-token remove <id>"),process.exit(1)),n(i)||(console.error(`no token with id ${i}`),process.exit(1)),console.log(`\u2713 token ${i} removed`);return}default:console.error("usage: tmux-web agent-token <add|list|remove>"),process.exit(1)}}
|
package/dist/lib/agent-client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{WebSocket as w}from"ws";import{attachTerminal as F}from"./attach-terminal.js";import{encodeBinaryFrame as G,decodeBinaryFrame as X,BIN_KIND_HTTP_BODY as O}from"./agent-channel.js";import{ActivityProbe as Y}from"./activity-probe.js";import{
|
|
1
|
+
import{WebSocket as w}from"ws";import{attachTerminal as F}from"./attach-terminal.js";import{encodeBinaryFrame as G,decodeBinaryFrame as X,BIN_KIND_HTTP_BODY as O}from"./agent-channel.js";import{ActivityProbe as Y}from"./activity-probe.js";import{sessionWorkingPath as z}from"./sessions-sidebar.js";import{newTmuxSession as Q}from"./tmux-windows.js";const V=parseInt(process.env.TMUX_WEB_AGENT_HEARTBEAT_MS||"15000",10),Z=parseInt(process.env.TMUX_WEB_AGENT_SESSIONS_POLL_MS||"10000",10),ee=new Set(["content-type","content-disposition","location","cache-control","etag"]);function ce(o){const B=o.log??(e=>console.log(`[agent] ${e}`)),h=e=>console.error(`[agent] ${e}`);let s=null,I=1e3,v=null,T=!1;const u=new Map,y=new Map,p=new Map,E=new Set;function H(e){return E.has(e)?Promise.resolve():new Promise(t=>{p.set(e,t),setTimeout(()=>{p.delete(e)&&t()},3e4)})}let _=null,m=null,S=null,g=null,M=new Map,C="",P=null;const b={state:"idle",agentId:null,hub:o.hub,name:o.name};function f(e,t){t!==void 0&&(b.lastError=t),b.state=e,b.agentId=P,o.onStatus?.({...b})}function c(e){s&&s.readyState===w.OPEN&&s.send(JSON.stringify(e))}function k(){let e;try{e=o.listSessions()}catch{return}const t=e.map(r=>({...r,path:z(r.name)})),n=JSON.stringify(t);n!==C&&(C=n,c({type:"sessions",sessions:t}))}function R(){_||(_=setInterval(k,Z)),m||(m=setInterval(()=>c({type:"ping",ts:Date.now()}),V)),S||(g=new Y,S=setInterval(()=>void q(),g.scanMs))}function L(){_&&(clearInterval(_),_=null),m&&(clearInterval(m),m=null),S&&(clearInterval(S),S=null),g=null}async function q(){if(!(!s||s.readyState!==w.OPEN||!g))try{const e=await g.scan(),t=[];for(const[n,r]of e)M.get(n)!==r&&t.push({session:n,state:r});M=e,t.length&&c({type:"activity",activities:t})}catch{}}async function U(e){let t;if(e.hasBody){await H(e.id),E.delete(e.id);const a=y.get(e.id);y.delete(e.id),t=a&&a.length?Buffer.concat(a):Buffer.alloc(0)}const n=new URL(e.path,"http://agent.invalid");let r;try{const a={method:e.method,headers:e.headers};t&&t.length&&(a.body=t),r=await Promise.race([o.app.request(new Request(n,a)),new Promise((te,K)=>setTimeout(()=>K(new Error("app.request timed out")),3e4))])}catch(a){h(`tunnel request failed: ${e.method} ${e.path} ${a.message}`),c({type:"http_resp",id:e.id,status:500,headers:{"content-type":"application/json"},hasBody:!1});return}const d={};r.headers.forEach((a,l)=>{ee.has(l.toLowerCase())&&(d[l]=a)});const i=Buffer.from(await r.arrayBuffer());if(c({type:"http_resp",id:e.id,status:r.status,headers:d,hasBody:i.length>0}),i.length>0){for(let l=0;l<i.length;l+=65536){if(!s||s.readyState!==w.OPEN)return;s.send(G(O,e.id,i.subarray(l,l+65536)))}c({type:"http_body_end",id:e.id})}}function x(e,t){let n=!1,r="";try{Q(e,t),n=!0}catch(d){r=d instanceof Error?d.message:"rebuild failed"}s&&s.readyState===w.OPEN&&s.send(JSON.stringify({type:"rebuild_session_result",session:e,ok:n,message:r})),k()}function J(e){const t=e.session;let n=!1;try{n=o.listSessions().some(i=>i.name===t)}catch{n=!1}if(!n){c({type:"attach_err",connId:e.connId,session:t,message:"no such session"});return}let r=null;const d=F(t,{send:i=>c({type:"ws_to_hub",connId:e.connId,msg:i}),onMessage:i=>{r=i},onClose:()=>{}},{terminalBufferConfig:o.terminalBufferConfig,getSessionPaneTarget:o.getSessionPaneTarget,capturePaneTail:o.capturePaneTail,capturePaneHistoryChunk:o.capturePaneHistoryChunk,toCrlf:o.toCrlf,handleClientMessage:o.handleClientMessage,acquireControlClient:o.acquireControlClient,initialCols:e.cols,initialRows:e.rows,tmuxSocketPath:o.tmuxSocketPath,onPtyExit:(i,a)=>{c({type:"ws_close",connId:e.connId,code:1e3,reason:`tmux exited (${a})`})},onSpawnError:(i,a)=>{h(`attach failed for session "${e.session}": ${a}`),c({type:"attach_err",connId:e.connId,session:t,message:a})},onAttached:i=>{c({type:"attach_ok",connId:e.connId,session:t})}});u.set(e.connId,{onMessage:i=>r?.(i),dispose:()=>{u.delete(e.connId),d.dispose()}})}function D(e){let t;try{t=JSON.parse(e)}catch{return}switch(t.type){case"hello_ok":P=t.agentId,I=1e3,B(`connected to hub as "${P}"`),f("connected"),k(),R();break;case"hello_err":if(h(`hub rejected us: ${t.reason}`),f("error",t.reason),s)try{s.close(4003,"hello rejected")}catch{}break;case"sessions_req":k();break;case"http_req":U(t);break;case"http_body_end":{E.add(t.id);const n=p.get(t.id);n&&(p.delete(t.id),n());break}case"attach":J(t);break;case"rebuild_session":x(t.session,t.dir);break;case"ws_to_agent":{const n=u.get(t.connId);if(n)try{n.onMessage(JSON.stringify(t.msg))}catch{}break}case"detach":{const n=u.get(t.connId);n&&n.dispose();break}case"pong":break;default:break}}function W(e){const t=X(e);if(t&&t.kind===O){const n=y.get(t.id)??[];n.push(t.payload),y.set(t.id,n)}}function N(){L();for(const e of u.values())try{e.dispose()}catch{}u.clear(),y.clear(),p.clear(),E.clear(),C=""}function A(){if(s){try{s.removeAllListeners()}catch{}s=null}if(N(),T)return;f("connecting");const e=I+Math.random()*500;B(`reconnecting in ${Math.round(e)}ms\u2026`),v=setTimeout($,e),I=Math.min(I*2,6e4)}function $(){if(T||s)return;const e=o.hub.replace(/\/+$/,"").replace(/^http:/,"ws:").replace(/^https:/,"wss:")+"/agent/ws";let t;try{t=new w(e)}catch(n){h(`bad hub URL: ${n.message} (${e})`),f("error",`bad hub URL: ${n.message}`);return}s=t,f("connecting"),t.on("open",()=>{B(`connecting to ${e}\u2026`),c({type:"hello",token:o.token,name:o.name,version:o.version})}),t.on("message",(n,r)=>{r?W(Array.isArray(n)?Buffer.concat(n):Buffer.isBuffer(n)?n:Buffer.from(n)):D(typeof n=="string"?n:Buffer.from(n).toString("utf-8"))}),t.on("close",()=>{s===t&&A()}),t.on("error",n=>{h(`connection error: ${n.message}`),s===t&&A()})}function j(){if(!T){if(T=!0,v&&clearTimeout(v),N(),s){try{s.removeAllListeners(),s.close(1e3,"shutdown")}catch{}s=null}P=null,f("idle")}}return $(),{stop:j,status:()=>({...b})}}export{ce as startAgentClient};
|