tmux-weblink 2.2.6 → 2.2.7
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 +16 -16
- package/dist/browser/shell-client.js +13 -13
- package/dist/index.js +3 -3
- package/package.json +1 -1
|
@@ -1,40 +1,40 @@
|
|
|
1
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,
|
|
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,
|
|
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,x=[];for(let A=c;A<=l;A++){let be=o.getLine(w+A);if(!be){x.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())}x.push(X.replace(/\s+$/,""))}return x.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,x=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(-x,Math.min(x,a));let i=()=>{if(P){d=0;return}let u=e.querySelector(".xterm-rows > div"),m=u?u.getBoundingClientRect().height:16,L=m>0?Math.round(p*16/m):p>0?1:-1;L===0&&(L=p>0?1:-1);let D=s.viewportY()-L,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,Le=[],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 Le.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"){Ee=!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 u=Ye(ce(i.data));
|
|
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));Le=[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?(Le.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 Ee=!1;function nt(){if(Ee)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,Le=[],G="",s.reset(),ne=1e3},r.onmessage=u=>{typeof u.data=="string"&&Ut(u.data)},r.onclose=()=>{P||(T="connecting",!Ee&&setTimeout(()=>{ne=Math.min(ne*2,1e4),!P&&!Ee&&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"),L={};m&&(L.Authorization="Bearer "+m);let D=await fetch(zt,{method:"POST",body:i,headers:L});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,C=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(),L=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)/L))),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),C=b,s.selectCells(b.col,b.row,C.col,C.row),document.addEventListener("mousemove",Oe,!0),document.addEventListener("mouseup",Ue,!0))}function Oe(a){P||!ae||!b||(a.preventDefault(),a.stopPropagation(),C=it(a.clientX,a.clientY),s.selectCells(b.col,b.row,C.col,C.row))}function Ue(a){if(P||!ae||!b||!C)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,C.col,C.row);b=null,C=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,C=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&&C){let i=s.getCellsText(b.col,b.row,C.col,C.row);b=null,C=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 L=await u.getType(m);await We(L);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
|
|
8
|
+
`).join("\r")}async function Xt(a){let i=qt(a.clipboardData);if(i){a.preventDefault(),a.stopPropagation();let L=Date.now();if(L-Te<50)return;Te=L,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 L=performance.now(),D=i.clientY-l.lastY,Y=L-l.lastT;Y>0&&(l.velocity=D/Y),ln(-D),l.lastX=i.clientX,l.lastY=i.clientY,l.lastT=L}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,E=pt;window.__tmuxWebScopeAgent=pt;var qe="sessions",j="",Be="",Ie="",ft="";function k(e){return E?"/a/"+encodeURIComponent(E)+e:e}var f=document.getElementById("sidebar-content"),q=document.getElementById("main-placeholder"),B=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 Ln(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 x=bt(),A=p.nextElementSibling;x.has(o)?(x.delete(o),p.classList.remove("collapsed"),A?.classList.remove("collapsed")):(x.add(o),p.classList.add("collapsed"),A?.classList.add("collapsed")),wn(x)});let w=document.createElement("div");w.className="session-group-body"+(d?" collapsed":"");for(let x of c)w.appendChild(En(x));f.appendChild(p),f.appendChild(w)}}function En(e){let t=document.createElement("div");t.className="session-item"+(e.name===g&&!E?" 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"+(
|
|
12
|
-
<span>${h(d.name)}</span><span class="meta">${o.online?"":"offline"}</span>`,o.online&&p.addEventListener("click",
|
|
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"+(E?" clickable":""),n.textContent=E?"\u2190 \u8FD4\u56DE\u672C\u673A":"\u672C\u673A",E&&(n.title="Back to hub",n.addEventListener("click",()=>{window.location.href="/"})),f.appendChild(n),Ln(t,e.home);let s=e.agents||[];for(let o of s){if(!o.sessions||o.sessions.length===0)continue;let c=o.agentId===E,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&&E===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);let w=d.path?d.path.split("/").filter(Boolean).slice(-2).join("/"):"";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">${w?h(w)+" ":""}${o.online?"":"offline"}</span>`,o.online&&p.addEventListener("click",x=>{x.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
13
|
<span>${h(c.name)}</span><span class="meta">\u5931\u6548${d}</span>
|
|
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&&
|
|
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&&E===(t||null))){ue.style.display="none",q.style.display="none",B.style.display="",B.classList.add("terminal-pending"),Ve(),v&&(Pe(),v.destroy(),v=null),g=e,E=t||null,window.__tmuxWebScopeAgent=E,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)===E);try{v=await fn(B,e,{terminal:de.terminal,scrollback:de.scrollback,theme:de.theme,wsBase:E?"/ws/a/"+encodeURIComponent(E):de.wsBase||"/ws"}),It()}catch(n){console.error("[shell] terminal init failed:",n);let s=n&&typeof n=="object"&&"message"in n?n.message:String(n);B.textContent="Failed to open terminal for "+e+": "+s,B.classList.remove("terminal-pending")}}}var De=[],y=null,Lt=!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){Lt=!0;try{let t=await fetch(k("/api/git/status?path="+encodeURIComponent(e)));t.ok?y=await t.json():y=null}catch{y=null}finally{Lt=!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
|
-
${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"),
|
|
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"),Et=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 S=document.getElementById("git-popover"),Fe=document.getElementById("git-popover-backdrop");function Xe(){let e=me.getBoundingClientRect();S.style.top=e.bottom+4+"px",S.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)S.innerHTML=`<div class="git-popover-header">No changes \u2014 clean working tree</div>
|
|
17
17
|
<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>`;else{let t=`<div class="git-popover-header">${e.length} file${e.length>1?"s":""} changed</div>`;for(let n=0;n<e.length;n++){let s=e[n],r=s.additions||0,o=s.deletions||0,c="";switch(s.status){case"M":c='<span class="git-file-status M">M</span>';break;case"A":c='<span class="git-file-status A">A</span>';break;case"D":c='<span class="git-file-status D">D</span>';break;case"?":c='<span class="git-file-status ?">?</span>';break;case"R":c='<span class="git-file-status R">R</span>';break}t+=`<div class="git-popover-item" data-idx="${n}">
|
|
18
18
|
${c}<span class="file-path">${h(s.path)}</span>
|
|
19
19
|
<span class="file-add">${r>0?"+"+r:""}</span>
|
|
20
20
|
<span class="file-del">${o>0?"-"+o:""}</span>
|
|
21
|
-
</div>`}t+='<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>',kt=t,
|
|
21
|
+
</div>`}t+='<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>',kt=t,S.innerHTML=t,S.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(),S.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 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()){
|
|
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()){B.style.display="none",v&&(Pe(),v.destroy(),v=null,Re=g,g=null),he(null),ue.style.display="none",q.style.display="none",Et.style.display="flex",xt.textContent=e,He.textContent="Loading\u2026",Ae.innerHTML="";try{let n=await fetch(k("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!n.ok)throw new Error(await n.text());let s=await n.json();In(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{S.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>
|
|
27
|
-
</div></div>`,Xe(),
|
|
27
|
+
</div></div>`,Xe(),S.classList.add("open"),Fe.classList.add("open");try{let n=await fetch(k("/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);S.innerHTML=`<div class="git-diff-view"><div class="diff-header">
|
|
28
28
|
<button class="diff-back">\u2190 Back</button>
|
|
29
29
|
<span class="diff-filename">${h(e)}</span>
|
|
30
|
-
</div><div class="diff-empty">Error loading diff: ${h(s)}</div></div>`}}}function
|
|
30
|
+
</div><div class="diff-empty">Error loading diff: ${h(s)}</div></div>`}}}function Bn(e,t,n){if(!t&&!n){S.innerHTML=`<div class="git-diff-view"><div class="diff-header">
|
|
31
31
|
<button class="diff-back">\u2190 Back</button>
|
|
32
32
|
<span class="diff-filename">${h(e)}</span>
|
|
33
|
-
</div><div class="diff-empty">No diff content available</div></div>`;return}let{html:s,lineCount:r}=Tt(t,n);
|
|
33
|
+
</div><div class="diff-empty">No diff content available</div></div>`;return}let{html:s,lineCount:r}=Tt(t,n);S.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">${h(e)}</span>
|
|
36
36
|
<span class="diff-filesize">${r} lines</span>
|
|
37
|
-
</div><div class="diff-content">${s}</div></div>`,
|
|
37
|
+
</div><div class="diff-content">${s}</div></div>`,S.querySelector(".diff-back")?.addEventListener("click",()=>{S.innerHTML=kt,Xe(),y&&S.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 In(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(){Et.style.display="none",Re?(B.style.display="",B.classList.add("terminal-pending"),fe(Re),Re=null):g?(B.style.display="",B.classList.add("terminal-pending"),It()):q.style.display="flex"}Tn.addEventListener("click",Dn);function Ne(){S.classList.remove("open"),Fe.classList.remove("open")}Fe.addEventListener("click",Ne),document.addEventListener("keydown",e=>{e.key==="Escape"&&(Ne(),ze())});async function Bt(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 It(){Pe(),g&&(Bt(g),$e=setInterval(()=>{g&&Bt(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(k("/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(k("/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){Be=e,B.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(k("/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,Ie=n.content,ft=n.content,H.textContent=n.size+" bytes",K.style.display=""}catch{H.textContent="Failed to load",pe.value=""}}pe.addEventListener("input",()=>{Ie=pe.value}),K.addEventListener("click",async()=>{K.textContent="Saving...",K.disabled=!0;try{let e=await fetch(k("/api/file"),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:Be,content:Ie})});if(!e.ok){let t=await e.json();H.textContent=t.error||"Save failed";return}ft=Ie,H.textContent="Saved"}catch{H.textContent="Save failed"}finally{K.disabled=!1,K.textContent="Save"}}),hn.addEventListener("click",async()=>{if(confirm("Delete "+Be+"?"))try{let e=await fetch(k("/api/file/delete"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:Be})});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(k("/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 I="",$=!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>
|
|
@@ -44,5 +44,5 @@ var cn=/\x1b\](?:10|11|110|111|104)(?:;[^\x07\x1b]*)?\x1b?(?:\\|\x07)/g;function
|
|
|
44
44
|
</div>
|
|
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
|
-
<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){
|
|
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(
|
|
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){I=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===I){V();return}try{let t=$?{oldName:I,newName:e,agentId:je}:{oldName:I,newName:e};if(!(await fetch(k($?"/api/sessions/rename-tombstone":"/api/sessions/rename"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).ok)return;V(),z(),!$&&g===I&&fe(e)}catch{}}),document.getElementById("sp-rebuild").addEventListener("click",async()=>{if(confirm('\u91CD\u5EFA\u4F1A\u8BDD "'+I+'" (\u540C\u540D\u540C\u8DEF\u5F84\uFF0C\u5185\u5BB9\u4E3A\u7A7A)\uFF1F'))try{let e=await fetch(k("/api/sessions/rebuild"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:I,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 "'+I+'"\uFF1F'))return;try{if(!(await fetch(k("/api/sessions/dismiss"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:I,agentId:je})})).ok)return;V(),z()}catch{}return}if(confirm('Delete session "'+I+'"?'))try{if(!(await fetch(k("/api/sessions/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:I})})).ok)return;V(),g===I&&(v&&(v.destroy(),v=null),g=null,B.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(k("/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(k("/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)===E,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)===E;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,33 +1,33 @@
|
|
|
1
|
-
import{initTerminal as De}from"./terminal-core.js";const
|
|
1
|
+
import{initTerminal as De}from"./terminal-core.js";const R=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 y(e){return v?"/a/"+encodeURIComponent(v)+e:e}const d=document.getElementById("sidebar-content"),T=document.getElementById("main-placeholder"),w=document.getElementById("terminal-container"),A=document.getElementById("file-editor"),Pe=document.getElementById("fe-path"),E=document.getElementById("fe-status"),_=document.getElementById("fe-content"),M=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 b=Le(),fe=r.nextElementSibling;b.has(i)?(b.delete(i),r.classList.remove("collapsed"),fe?.classList.remove("collapsed")):(b.add(i),r.classList.add("collapsed"),fe?.classList.add("collapsed")),ze(b)});const g=document.createElement("div");g.className="session-group-body"+(l?" collapsed":"");for(const b of o)g.appendChild(qe(b));d.appendChild(r),d.appendChild(g)}}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),l.path&&(r.title=l.path)
|
|
5
|
-
<span>${p(l.name)}</span><span class="meta">${i.online?"":"offline"}</span>`,i.online&&r.addEventListener("click",
|
|
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);const g=l.path?l.path.split("/").filter(Boolean).slice(-2).join("/"):"";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
|
+
<span>${p(l.name)}</span><span class="meta">${g?p(g)+" ":""}${i.online?"":"offline"}</span>`,i.online&&r.addEventListener("click",b=>{b.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
|
-
<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",
|
|
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",g=>{g.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",T.style.display="none",w.style.display="",w.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(w,e,{terminal:R.terminal,scrollback:R.scrollback,theme:R.theme,wsBase:v?"/ws/a/"+encodeURIComponent(v):R.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);w.textContent="Failed to open terminal for "+e+": "+s,w.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(y("/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">
|
|
8
8
|
<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>
|
|
9
|
-
${p(e)}</div>`;return(n>0||t>0)&&(s+=`<div class="git-diff-stats">+<span class="add">${n}</span> <span class="del">-${t}</span></div>`),s+"</div>"}d.addEventListener("click",e=>{e.target.closest(".sidebar-git")&&N&&m&&(e.stopPropagation(),Be())});const P=document.getElementById("header-git"),ke=document.getElementById("git-diff-view"),Ce=document.getElementById("gd-path"),V=document.getElementById("gd-status"),J=document.getElementById("gd-content"),Ye=document.getElementById("gd-back");let N=null;function j(e){if(!e||!e.branch){P.style.display="none",N=null;return}N=e.repoRoot;const{branch:n,linesAdded:t,linesRemoved:s}=e;let a=`<span class="branch">${p(n)}</span>`;(t>0||s>0)&&(a+=`<span class="sep">\xB7</span>+<span class="diff-add">${t}</span> <span class="diff-del">-${s}</span>`),P.innerHTML=a,P.style.display="block"}P.addEventListener("click",e=>{N&&m&&(e.stopPropagation(),Be())});const
|
|
9
|
+
${p(e)}</div>`;return(n>0||t>0)&&(s+=`<div class="git-diff-stats">+<span class="add">${n}</span> <span class="del">-${t}</span></div>`),s+"</div>"}d.addEventListener("click",e=>{e.target.closest(".sidebar-git")&&N&&m&&(e.stopPropagation(),Be())});const P=document.getElementById("header-git"),ke=document.getElementById("git-diff-view"),Ce=document.getElementById("gd-path"),V=document.getElementById("gd-status"),J=document.getElementById("gd-content"),Ye=document.getElementById("gd-back");let N=null;function j(e){if(!e||!e.branch){P.style.display="none",N=null;return}N=e.repoRoot;const{branch:n,linesAdded:t,linesRemoved:s}=e;let a=`<span class="branch">${p(n)}</span>`;(t>0||s>0)&&(a+=`<span class="sep">\xB7</span>+<span class="diff-add">${t}</span> <span class="diff-del">-${s}</span>`),P.innerHTML=a,P.style.display="block"}P.addEventListener("click",e=>{N&&m&&(e.stopPropagation(),Be())});const h=document.getElementById("git-popover"),K=document.getElementById("git-popover-backdrop");function ae(){const e=P.getBoundingClientRect();h.style.top=e.bottom+4+"px",h.style.left=Math.max(8,Math.min(e.left,window.innerWidth-400))+"px"}function Se(){const e=N,n=document.getElementById("git-popover-browse");n&&n.addEventListener("click",()=>{if(Y(),e){ne="files",document.querySelectorAll(".mode-btn").forEach(s=>s.classList.remove("active"));const t=document.getElementById("mode-files");t&&t.classList.add("active"),x(e)}})}let Ie="";function Be(){if(!m)return;const e=m.files||[];if(!e.length)h.innerHTML=`<div class="git-popover-header">No changes \u2014 clean working tree</div>
|
|
10
10
|
<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>`;else{let n=`<div class="git-popover-header">${e.length} file${e.length>1?"s":""} changed</div>`;for(let t=0;t<e.length;t++){const s=e[t],a=s.additions||0,i=s.deletions||0;let o="";switch(s.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}n+=`<div class="git-popover-item" data-idx="${t}">
|
|
11
11
|
${o}<span class="file-path">${p(s.path)}</span>
|
|
12
12
|
<span class="file-add">${a>0?"+"+a:""}</span>
|
|
13
13
|
<span class="file-del">${i>0?"-"+i:""}</span>
|
|
14
|
-
</div>`}n+='<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>',Ie=n,
|
|
14
|
+
</div>`}n+='<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>',Ie=n,h.innerHTML=n,h.querySelectorAll(".git-popover-item").forEach(t=>{const s=parseInt(t.dataset.idx||"0",10),a=e[s];!a||a.status==="D"||(t.classList.add("clickable"),t.style.cursor="pointer",t.addEventListener("click",()=>Te(a.path)))})}ae(),h.classList.add("open"),K.classList.add("open"),Se()}function Ze(){return window.innerWidth>=1024}function xe(e,n){const s=(e+(n&&e?`
|
|
15
15
|
`:"")+n).split(`
|
|
16
|
-
`);let a="",i=0,o=0;for(const c of s){const l=c;if(l.startsWith("@@")){const r=l.match(/@@\s+-(\d+)[^+]*\+(\d+)/);r&&(i=parseInt(r[1],10)-1,o=parseInt(r[2],10)-1),a+=`<div class="diff-line hunk"><span class="ln-body">${p(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")&&(a+=`<div class="diff-line header"><span class="ln-body">${p(l)}</span></div>`);continue}if(l.startsWith("+"))o++,a+=`<div class="diff-line add"><span class="ln-no">${o}</span><span class="ln-body">${p(l)}</span></div>`;else if(l.startsWith("-"))i++,a+=`<div class="diff-line del"><span class="ln-no">${i}</span><span class="ln-body">${p(l)}</span></div>`;else if(l.startsWith("\\"))a+=`<div class="diff-line"><span class="ln-body">${p(l)}</span></div>`;else{if(!l&&!i&&!o)continue;i++,o++,a+=`<div class="diff-line"><span class="ln-no">${i}</span><span class="ln-no" style="margin-right:12px">${o}</span><span class="ln-body">${p(l)}</span></div>`}}return{html:a,lineCount:s.length}}let X=null;async function
|
|
16
|
+
`);let a="",i=0,o=0;for(const c of s){const l=c;if(l.startsWith("@@")){const r=l.match(/@@\s+-(\d+)[^+]*\+(\d+)/);r&&(i=parseInt(r[1],10)-1,o=parseInt(r[2],10)-1),a+=`<div class="diff-line hunk"><span class="ln-body">${p(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")&&(a+=`<div class="diff-line header"><span class="ln-body">${p(l)}</span></div>`);continue}if(l.startsWith("+"))o++,a+=`<div class="diff-line add"><span class="ln-no">${o}</span><span class="ln-body">${p(l)}</span></div>`;else if(l.startsWith("-"))i++,a+=`<div class="diff-line del"><span class="ln-no">${i}</span><span class="ln-body">${p(l)}</span></div>`;else if(l.startsWith("\\"))a+=`<div class="diff-line"><span class="ln-body">${p(l)}</span></div>`;else{if(!l&&!i&&!o)continue;i++,o++,a+=`<div class="diff-line"><span class="ln-no">${i}</span><span class="ln-no" style="margin-right:12px">${o}</span><span class="ln-body">${p(l)}</span></div>`}}return{html:a,lineCount:s.length}}let X=null;async function Te(e){const n=N;if(n)if(Y(),Ze()){w.style.display="none",f&&(Q(),f.destroy(),f=null,X=u,u=null),j(null),A.style.display="none",T.style.display="none",ke.style.display="flex",Ce.textContent=e,V.textContent="Loading\u2026",J.innerHTML="";try{const t=await fetch(y("/api/git/diff?path="+encodeURIComponent(n)+"&file="+encodeURIComponent(e)));if(!t.ok)throw new Error(await t.text());const s=await t.json();et(e,s.diff,s.stagedDiff)}catch(t){const s=t instanceof Error?t.message:String(t);V.textContent="Error",J.innerHTML=`<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">Error: ${p(s)}</div>`}}else{h.innerHTML=`<div class="git-diff-view"><div class="diff-header">
|
|
17
17
|
<button class="diff-back">\u2190 Back</button>
|
|
18
18
|
<span class="diff-filename">${p(e)}</span>
|
|
19
19
|
<span class="diff-loading">Loading\u2026</span>
|
|
20
|
-
</div></div>`,ae(),
|
|
20
|
+
</div></div>`,ae(),h.classList.add("open"),K.classList.add("open");try{const t=await fetch(y("/api/git/diff?path="+encodeURIComponent(n)+"&file="+encodeURIComponent(e)));if(!t.ok)throw new Error(await t.text());const s=await t.json();Qe(e,s.diff,s.stagedDiff)}catch(t){const s=t instanceof Error?t.message:String(t);h.innerHTML=`<div class="git-diff-view"><div class="diff-header">
|
|
21
21
|
<button class="diff-back">\u2190 Back</button>
|
|
22
22
|
<span class="diff-filename">${p(e)}</span>
|
|
23
|
-
</div><div class="diff-empty">Error loading diff: ${p(s)}</div></div>`}}}function Qe(e,n,t){if(!n&&!t){
|
|
23
|
+
</div><div class="diff-empty">Error loading diff: ${p(s)}</div></div>`}}}function Qe(e,n,t){if(!n&&!t){h.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">${p(e)}</span>
|
|
26
|
-
</div><div class="diff-empty">No diff content available</div></div>`;return}const{html:s,lineCount:a}=xe(n,t);
|
|
26
|
+
</div><div class="diff-empty">No diff content available</div></div>`;return}const{html:s,lineCount:a}=xe(n,t);h.innerHTML=`<div class="git-diff-view"><div class="diff-header">
|
|
27
27
|
<button class="diff-back">\u2190 Back</button>
|
|
28
28
|
<span class="diff-filename">${p(e)}</span>
|
|
29
29
|
<span class="diff-filesize">${a} lines</span>
|
|
30
|
-
</div><div class="diff-content">${s}</div></div>`,
|
|
30
|
+
</div><div class="diff-content">${s}</div></div>`,h.querySelector(".diff-back")?.addEventListener("click",()=>{h.innerHTML=Ie,ae(),m&&h.querySelectorAll(".git-popover-item").forEach(i=>{const o=parseInt(i.dataset.idx||"0",10),c=m.files[o];!c||c.status==="D"||(i.style.cursor="pointer",i.addEventListener("click",()=>Te(c.path)))}),Se()})}function et(e,n,t){if(!n&&!t){V.textContent="No diff",J.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:a}=xe(n,t);Ce.textContent=e,V.textContent=a+" lines",J.innerHTML=s}function tt(){ke.style.display="none",X?(w.style.display="",w.classList.add("terminal-pending"),D(X),X=null):u?(w.style.display="",w.classList.add("terminal-pending"),He()):T.style.display="flex"}Ye.addEventListener("click",tt);function Y(){h.classList.remove("open"),K.classList.remove("open")}K.addEventListener("click",Y),document.addEventListener("keydown",e=>{e.key==="Escape"&&(Y(),te())});async function Me(e){try{const t=await(await fetch("/api/fs/session-path?session="+encodeURIComponent(e))).json();if(t.path){const s=await fetch("/api/git/status?path="+encodeURIComponent(t.path));if(s.ok){const a=await s.json();m=a,j(a);return}}}catch{}m=null,j(null)}let Z=null;function He(){Q(),u&&(Me(u),Z=setInterval(()=>{u&&Me(u)},3e4))}function Q(){Z&&(clearInterval(Z),Z=null)}function nt(){if(q=R.fsRoots||[],q.length===0){if(u){st(u);return}d.innerHTML='<div class="file-tree-info">Open a session first, then switch to Files to browse its directory.</div>';return}d.innerHTML="";for(const e of q){const n=document.createElement("div");n.className="file-tree-item",n.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor" class="file-icon"><path d="M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/></svg> ${p(e)}`,n.addEventListener("click",()=>x(e)),d.appendChild(n)}}async function st(e){d.innerHTML='<div class="file-tree-empty">Loading...</div>';try{const t=await(await fetch(y("/api/fs/session-path?session="+encodeURIComponent(e)))).json();t.path?x(t.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 x(e){I=e,d.innerHTML='<div class="file-tree-empty">Loading...</div>';const n=Ke(e);try{const s=await(await fetch(y("/api/fs/list?path="+encodeURIComponent(e)))).json();await n,d.innerHTML="",j(m),d.innerHTML+=Xe();const a=it(e);if(a&&!q.some(c=>e===c)){const c=document.createElement("div");c.className="file-tree-item",c.innerHTML="..",c.addEventListener("click",()=>x(a)),d.appendChild(c)}if(s.dirs)for(const o of s.dirs){const 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> ${p(c)}`,l.addEventListener("click",()=>x(o)),d.appendChild(l)}else d.innerHTML="";const i=s.files||[];for(const o of i){const c=o.split("/").pop()||o.split("\\").pop(),l=Je(o);let r="",g="";if(l)switch(l){case"M":r="git-mod",g='<span class="git-file-status M">M</span>';break;case"A":r="git-add",g='<span class="git-file-status A">A</span>';break;case"D":r="git-del",g='<span class="git-file-status D">D</span>';break;case"?":r="git-untracked",g='<span class="git-file-status ?">?</span>';break;case"R":r="git-mod",g='<span class="git-file-status R">R</span>';break}const b=document.createElement("div");b.className="file-tree-item file"+(r?" "+r:""),b.innerHTML=`<span class="file-icon">\u{1F4C4}</span> ${g}${p(c)}`,b.addEventListener("click",()=>ot(o)),d.appendChild(b)}}catch{d.innerHTML='<div class="file-tree-error">Failed to load directory</div>'}}function it(e){const n=e.lastIndexOf("/");return n<=0?null:e.substring(0,n)}async function ot(e){F=e,w.style.display="none",f&&(Q(),f.destroy(),f=null,u=null),j(null),ie(),T.style.display="none",A.style.display="flex",Pe.textContent=e,E.textContent="Loading...",M.style.display="none";try{const n=await fetch(y("/api/file?path="+encodeURIComponent(e)));if(!n.ok){const s=await n.json();E.textContent=s.error||"Failed to load",_.value="";return}const t=await n.json();_.value=t.content,G=t.content,me=t.content,E.textContent=t.size+" bytes",M.style.display=""}catch{E.textContent="Failed to load",_.value=""}}_.addEventListener("input",()=>{G=_.value}),M.addEventListener("click",async()=>{M.textContent="Saving...",M.disabled=!0;try{const e=await fetch(y("/api/file"),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:F,content:G})});if(!e.ok){const n=await e.json();E.textContent=n.error||"Save failed";return}me=G,E.textContent="Saved"}catch{E.textContent="Save failed"}finally{M.disabled=!1,M.textContent="Save"}}),je.addEventListener("click",async()=>{if(confirm("Delete "+F+"?"))try{const e=await fetch(y("/api/file/delete"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:F})});if(!e.ok){const n=await e.json();E.textContent=n.error||"Delete failed";return}A.style.display="none",T.style.display="flex",I&&x(I)}catch{E.textContent="Delete failed"}}),Oe.addEventListener("click",()=>{A.style.display="none",T.style.display="flex",I&&x(I)}),We.addEventListener("click",async()=>{const e=ve.value.trim();if(!e)return;const n=I+"/"+e;try{const t=await fetch(y("/api/file/touch"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:n})});if(!t.ok){const s=await t.json();E.textContent=s.error||"Create failed";return}ve.value="",I&&x(I)}catch{E.textContent="Create failed"}}),document.getElementById("mode-settings").addEventListener("click",()=>{const e=ge.classList.toggle("open");se.classList.toggle("open",e)}),se.addEventListener("click",()=>{ge.classList.remove("open"),se.classList.remove("open")});let L="",S=!1,ee;const O=document.createElement("div");O.className="session-popover-backdrop",document.body.appendChild(O);const k=document.createElement("div");k.id="session-popover",k.className="session-popover",k.style.display="none",k.innerHTML=`<div class="sp-field">
|
|
31
31
|
<label>Rename session</label>
|
|
32
32
|
<input type="text" id="sp-name" />
|
|
33
33
|
</div>
|
|
@@ -37,5 +37,5 @@ import{initTerminal as De}from"./terminal-core.js";const $=window.__TMUX_WEB_SHE
|
|
|
37
37
|
</div>
|
|
38
38
|
<hr class="sp-divider" />
|
|
39
39
|
<button class="btn primary" id="sp-rebuild" style="display:none">\u91CD\u5EFA\u540C\u540D\u540C\u8DEF\u5F84 session</button>
|
|
40
|
-
<button class="btn danger" id="sp-delete">Delete session</button>`,document.body.appendChild(k);function at(e){const n=e.getBoundingClientRect();k.style.top=n.bottom+4+"px",k.style.left=Math.max(8,Math.min(n.left,window.innerWidth-240))+"px"}function Ne(e,n,t){
|
|
41
|
-
`).length;C.rows=Math.min(e,4)}),C.addEventListener("keydown",e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault()
|
|
40
|
+
<button class="btn danger" id="sp-delete">Delete session</button>`,document.body.appendChild(k);function at(e){const n=e.getBoundingClientRect();k.style.top=n.bottom+4+"px",k.style.left=Math.max(8,Math.min(n.left,window.innerWidth-240))+"px"}function Ne(e,n,t){L=e,S=!!t?.tombstone,ee=t?.agentId;const s=document.getElementById("sp-name");s.value=e;const a=k.querySelector(".sp-field label");a.textContent=S?"\u91CD\u547D\u540D (\u4EC5\u8BB0\u5F55\uFF0C\u4E0D\u91CD\u5EFA)":"Rename session";const i=document.getElementById("sp-rebuild");i.style.display=S?"":"none";const o=document.getElementById("sp-delete");o.textContent=S?"\u5220\u9664\u5931\u6548\u8BB0\u5F55 (\u5893\u7891\u6D88\u5931)":"Delete session";const c=document.getElementById("sp-save");c.textContent=S?"\u91CD\u547D\u540D":"Save",O.classList.add("open"),k.style.display="block",at(n),setTimeout(()=>s.focus(),50)}function H(){O.classList.remove("open"),k.style.display="none"}O.addEventListener("click",H),document.getElementById("sp-save").addEventListener("click",async()=>{const e=document.getElementById("sp-name").value.trim();if(!e||e===L){H();return}try{const n=S?{oldName:L,newName:e,agentId:ee}:{oldName:L,newName:e};if(!(await fetch(y(S?"/api/sessions/rename-tombstone":"/api/sessions/rename"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).ok)return;H(),B(),!S&&u===L&&D(e)}catch{}}),document.getElementById("sp-rebuild").addEventListener("click",async()=>{if(confirm('\u91CD\u5EFA\u4F1A\u8BDD "'+L+'" (\u540C\u540D\u540C\u8DEF\u5F84\uFF0C\u5185\u5BB9\u4E3A\u7A7A)\uFF1F'))try{const e=await fetch(y("/api/sessions/rebuild"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:L,agentId:ee})});if(!e.ok){const n=await e.json();alert(n.error||"\u91CD\u5EFA\u5931\u8D25");return}H(),B()}catch{}}),document.getElementById("sp-delete").addEventListener("click",async()=>{if(S){if(!confirm('\u5220\u9664\u5931\u6548\u8BB0\u5F55 "'+L+'"\uFF1F'))return;try{if(!(await fetch(y("/api/sessions/dismiss"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:L,agentId:ee})})).ok)return;H(),B()}catch{}return}if(confirm('Delete session "'+L+'"?'))try{if(!(await fetch(y("/api/sessions/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:L})})).ok)return;H(),u===L&&(f&&(f.destroy(),f=null),u=null,w.style.display="none",T.style.display="flex"),B()}catch{}}),document.getElementById("sp-cancel").addEventListener("click",H);const lt={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=>{const n=e.target.closest("button[data-key]");if(!n||!f)return;const t=lt[n.dataset.key];t&&(f.sendInput(t),f.focus())});const C=document.getElementById("mk-input"),$e=document.getElementById("mk-send");function Re(){if(!C||!f)return;const e=C.value;e&&(f.sendInput(e+"\r"),C.value="",C.rows=1,f.focus())}if(C&&(C.addEventListener("input",()=>{C.rows=1;const e=C.value.split(`
|
|
41
|
+
`).length;C.rows=Math.min(e,4)}),C.addEventListener("keydown",e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),Re())})),$e&&$e.addEventListener("click",Re),window.visualViewport){const e=document.querySelector(".app-layout"),n=()=>{e&&(e.style.height=window.visualViewport.height+"px"),window.scrollTo(0,0),document.documentElement.scrollTop=0,document.body.scrollTop=0};window.visualViewport.addEventListener("resize",n),window.addEventListener("orientationchange",()=>setTimeout(n,100)),document.addEventListener("touchstart",()=>{(window.scrollY>0||document.documentElement.scrollTop>0)&&window.scrollTo(0,0)},{passive:!0})}const le=document.getElementById("process-panel"),W=document.getElementById("proc-list"),ct=document.getElementById("proc-close"),ce=document.getElementById("proc-backdrop"),rt=document.getElementById("header-ram");function dt(){W.innerHTML='<div class="proc-empty">Loading\u2026</div>',fetch(y("/api/system/processes")).then(e=>e.json()).then(e=>{if(!Array.isArray(e)||!e.length){W.innerHTML='<div class="proc-empty">No processes</div>';return}let n="";for(const t of e){const s=t.rss,a=s<1048576?(s/1024).toFixed(0)+"K":(s/1048576).toFixed(1)+"M";n+='<div class="proc-row" data-pid="'+t.pid+'"><span class="proc-mem">'+t.mem+'%</span><span class="proc-rss">'+a+'</span><span class="proc-cmd" title="'+p(t.command)+'">'+p(t.command)+'</span><button class="proc-kill" title="Kill PID '+t.pid+'">×</button></div>'}W.innerHTML=n;for(const t of W.querySelectorAll(".proc-row")){const s=t.querySelector(".proc-kill");s&&s.addEventListener("click",a=>{const i=a.target.closest(".proc-row");!i||!confirm("Kill PID "+i.dataset.pid+"?")||fetch(y("/api/system/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:parseInt(i.dataset.pid,10)})}).then(o=>o.json()).then(o=>{o.ok?i.style.opacity="0.3":alert("Failed: "+(o.error||"unknown"))}).catch(()=>alert("Network error"))})}}).catch(()=>{W.innerHTML='<div class="proc-empty">Failed to load</div>'})}function pt(){le.classList.add("open"),ce.classList.add("open"),dt()}function te(){le.classList.remove("open"),ce.classList.remove("open")}rt.addEventListener("click",e=>{e.stopPropagation(),le.classList.contains("open")?te():pt()}),ct.addEventListener("click",te),ce.addEventListener("click",te);const ft=2e3;let U=null,re=null;const $=new Map,z=new Map;function Ae(e,n){return(n?"a:"+n+":":"l:")+e}function ut(e,n,t){const s=Ae(e,n),a=z.get(s),i=e===u&&(n??null)===v,o=t==="idle"&&a?.state==="working";z.set(s,{session:e,agentId:n,state:t,doneUntil:o?Date.now()+ft:void 0,unread:o?!i:!1});const c=n?'.session-item[data-agent="'+CSS.escape(n)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',l=d.querySelector(c);l&&de(l,s,z.get(s))}function de(e,n,t){const s=$.get(n);s&&(clearTimeout(s),$.delete(n)),e.classList.remove("working","just-done");const a=t.session===u&&(t.agentId??null)===v;t.state==="working"?e.classList.add("working"):a&&t.doneUntil&&Date.now()<t.doneUntil?(e.classList.add("just-done"),$.set(n,setTimeout(()=>{e.classList.remove("just-done"),$.delete(n)},Math.max(0,t.doneUntil-Date.now())))):!a&&t.unread&&e.classList.add("just-done")}function pe(){for(const[e,n]of z){const t=n.agentId?'.session-item[data-agent="'+CSS.escape(n.agentId)+'"][data-session="'+CSS.escape(n.session)+'"]':'.session-item[data-session="'+CSS.escape(n.session)+'"]:not([data-agent])',s=d.querySelector(t);s&&de(s,e,n)}}function mt(e,n){const t=Ae(e,n),s=z.get(t);if(!s)return;const a=$.get(t);a&&(clearTimeout(a),$.delete(t)),s.doneUntil=void 0,s.unread=!1;const i=n?'.session-item[data-agent="'+CSS.escape(n)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',o=d.querySelector(i);o&&de(o,t,s)}function _e(){if(U||re)return;const e=localStorage.getItem("tmux-web-token");let t=(location.protocol==="https:"?"wss:":"ws:")+"//"+location.host+"/ws/activity";e&&(t+="?token="+encodeURIComponent(e));try{const s=new WebSocket(t);U=s,s.onmessage=a=>{try{const i=JSON.parse(String(a.data));i&&i.type==="session.activity"&&typeof i.session=="string"&&ut(i.session,i.agentId||void 0,i.state==="working"?"working":"idle")}catch{}},s.onclose=()=>{U===s&&(U=null,re=setTimeout(()=>{re=null,_e()},5e3))},s.onerror=()=>{try{s.close()}catch{}}}catch{U=null}}window.__openSession=D,window.__refreshSidebar=B,B(),ie(),pe(),_e(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&pe()}),setInterval(()=>{document.visibilityState==="visible"&&B()},1e4);
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{chmodSync as he,existsSync as
|
|
2
|
+
import{chmodSync as he,existsSync as G,readdirSync as ge,statSync as ye}from"node:fs";import{createRequire as V}from"node:module";import{hostname as E,networkInterfaces as ke}from"node:os";const ve=V(import.meta.url),{version:Te}=ve("../package.json");import M from"node:path";import{fileURLToPath as _e}from"node:url";import{serve as we}from"@hono/node-server";import{WebSocketServer as Se,WebSocket as F}from"ws";try{const e=M.dirname(V(import.meta.url).resolve("node-pty/package.json")),t=M.join(e,"prebuilds");if(G(t))for(const o of ge(t)){const n=M.join(t,o,"spawn-helper");G(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 X}from"./lib/ws-message.js";import{loadDotEnv as Re}from"./lib/load-env.js";import{listSessions as $e,resolveTmuxSocketPath as Oe}from"./sessions.js";import{cmdSetup as Me,cmdTheme as Ne,printUsage as Y,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 K}from"./lib/build-app.js";import{attachTerminal as Fe,killAllAttachedPtys as je}from"./lib/attach-terminal.js";import{acquireControlClient as Q,killAllControlClients as He}from"./lib/tmux-control.js";import{getSessionPaneTarget as Z,capturePaneTail as q,capturePaneHistoryChunk as ee,toCrlf as te}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 ne}from"./lib/session-state.js";import{sessionWorkingPath as Ze}from"./lib/sessions-sidebar.js";Re();const j=Be(),g=Ae(),v=new Ce,A=new Pe;let D=!1;const qe="tmux-web-token";function H(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 B(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=B(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 oe(e,t){e.readyState===F.OPEN&&e.send(JSON.stringify(t))}const re=process.argv.slice(2),L=re;if(L.length>0){const[e,t]=L;switch(e){case"setup":await Me(L),process.exit(0);case"theme":await Ne(L.slice(1)),process.exit(0);case"agent":{const o=M.join(M.dirname(_e(import.meta.url)),"agent.js"),{spawn:n}=await import("node:child_process"),f=n(process.execPath,[o,...re],{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":Y(),process.exit(0);case"-V":case"--version":case"-v":Le(),process.exit(0);default:console.error(`unknown argument: ${e}`),Y(),process.exit(1)}}function P(e,t){e.readyState===F.OPEN&&e.send(JSON.stringify(t))}const se=new Set;await N.read(),N.data.sessionAccess??=[],N.data.pinnedViews??=[],N.data.watchedPanes??=[],N.data.quickCommands??=[];const ae=await Ue();let tt=await Ee();const k=new We({onChange:()=>{}}),w=new Map;function ie(e){return k.get(e)?w.get(e)??null:null}const ce={activeTheme:tt,settingUpPassword:!1},nt=K({mode:"hub",securityConfig:g,tokenStore:v,rateLimiter:A,settings:ae,terminalBufferConfig:j,state:ce,federation:{getConfig:()=>x,setConfig:async e=>{x=e,await Ye(e),ue(e)},status:rt,hostname:E()},hub:{agents:k,getChannel:ie}}),ot=K({mode:"agent",securityConfig:g,tokenStore:v,rateLimiter:A,settings:ae,terminalBufferConfig:j,state:ce});let x=await Xe(),$=null;function le(){$&&($.stop(),$=null)}function ue(e){le(),!(!e.enabled||!e.hub||!e.token)&&($=Ke({hub:e.hub,token:e.token,name:e.name?.trim()||E(),version:Te,app:ot,listSessions:$e,terminalBufferConfig:j,getSessionPaneTarget:Z,capturePaneTail:q,capturePaneHistoryChunk:ee,toCrlf:te,handleClientMessage:X,acquireControlClient:Q}))}function rt(){return x.enabled?$?$.status():{state:"idle",agentId:null,hub:x.hub??"",name:x.name??E()}:{state:"idle",agentId:null,hub:x.hub??"",name:x.name??E()}}ue(x);const de=new Qe,W=new Map;setInterval(()=>{(async()=>{try{const e=await de.scan(),t=[];for(const[o,n]of e)W.get(o)!==n&&t.push({session:o,state:n});for(const o of W.keys())e.has(o)||t.push({session:o,state:"idle"});W.clear();for(const[o,n]of e)W.set(o,n);for(const o of t)fe({type:"session.activity",session:o.session,state:o.state})}catch{}})()},de.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}),z=new Set;function fe(e){const t=JSON.stringify(e);for(const o of z)o.readyState===F.OPEN&&o.send(t)}function I(e,t,o){e.write(`HTTP/1.1 ${t} ${o}\r
|
|
3
3
|
\r
|
|
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
|
|
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 S=H(e),a=B(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",()=>z.delete(c)),z.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=H(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=B(e)||n.searchParams.get("token")||"",_=y?v.validateToken(y):null;O.handleUpgrade(e,t,o,S=>{O.emit("connection",S,e,decodeURIComponent(i[1]),l,_)})}),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||(ne(o,{path:Ze(o)}),l=Fe(o,{send:a=>P(e,a),onMessage:a=>{u=a},onClose:a=>{_=a}},{terminalBufferConfig:j,getSessionPaneTarget:Z,capturePaneTail:q,capturePaneHistoryChunk:ee,toCrlf:te,handleClientMessage:X,acquireControlClient:Q,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 _=null;async function S(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(D)return m("Password setup in progress"),!0;const C=Ie(r.password);if(C)return m(C),!0;D=!0;try{g.passwordHash=await be(r.password),Ve(g),d("password_set",{ip:n})}finally{D=!1}const{stored:J,plaintext:pe}=v.createAccessToken("setup",g.security.tokenTtlDays);return P(e,{type:"auth.ok",setupMode:!0,token:pe}),d("token_created",{ip:n,name:J.name,tokenId:J.id}),d("auth_success",{ip:n,method:"password",tokenName:J.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 T=`ws-${n}`,{plaintext:U}=v.createAccessToken(T,g.security.tokenTtlDays);return p("password",T),P(e,{type:"auth.ok",setupMode:!1,token:U}),!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 S(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}),_?.(),l&&(l.dispose(),l=null)}),e.on("error",()=>{s.authTimeout&&clearTimeout(s.authTimeout),R.delete(e),_?.(),l&&(l.dispose(),l=null)})});function ct(e,t,o,n,f){const s=H(e),i=new URL(e.url||"/",`http://${e.headers.host}`),l=B(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=ie(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 _=ut(),S=(()=>{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(_,f,a),k.bumpRelayConns(n,1),ne(f,{agentId:n}),!p.attach(_,f,S)){a.send(JSON.stringify({type:"data",data:`\r
|
|
5
5
|
\x1B[31magent offline\x1B[0m\r
|
|
6
|
-
`})),a.close(1011,"agent offline"),p.relayClosed(
|
|
6
|
+
`})),a.close(1011,"agent offline"),p.relayClosed(_),k.bumpRelayConns(n,-1);return}a.on("message",c=>{const h=typeof c=="string"?c:c.toString("utf-8");let T;try{T=JSON.parse(h)}catch{return}(T.type==="input"||T.type==="resize"||T.type==="load_history")&&p.sendToAgent(_,T)});const r=()=>{p.relayClosed(_),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=H(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 S=ze(y.token);if(!S){A.recordFailure(n),d("agent_bad_token",{ip:n}),oe(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=S.id;if(!k.register(r,a,s,S.tokenHash)){d("agent_cap_reached",{ip:n}),oe(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);const T=h.slice(0,3).map(U=>({name:U.name,path:U.path}));console.log(`[sessions] agent ${r}: ${JSON.stringify(T)}`)},onActivity:h=>{for(const T of h)fe({type:"session.activity",agentId:r,session:T.session,state:T.state})},onRebuildResult:h=>{console.log(`[agent ${r}] rebuild ${h.session}: ${h.ok?"ok":h.message}`)},onClose:h=>{w.get(r)===h&&w.delete(r)}}),w.set(r,i),k.touch(r),s.send(JSON.stringify({type:"hello_ok",agentId:r})),i.sendSessionsReq()}),s.on("close",()=>{i&&(i.dispose(),w.delete(i.agentId),k.unregister(i.agentId),d("agent_disconnected",{ip:n,agentId:i.agentId})),clearTimeout(l)}),s.on("error",()=>{i&&(i.dispose(),w.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===F.CLOSED&&(k.unregister(o),w.get(o)?.dispose(),w.delete(o))}const t=new Set(Ge().map(o=>o.tokenHash));for(const[o,n]of w){const f=k.peek(o);if(!(!f||t.has(f.tokenHash))){d("agent_token_revoked",{agentId:o}),n.dispose(),w.delete(o),k.unregister(o);try{f.ws.close(4003,"token revoked")}catch{}}}v.purgeExpired()},10*1e3).unref();function me(){le(),He(),je();for(const e of w.values())e.dispose();w.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 se)try{e.kill()}catch{}se.clear(),A.dispose(),process.exit(0)}process.on("SIGINT",me),process.on("SIGTERM",me);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
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)}}
|