tmux-weblink 2.2.33 → 2.2.35
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1,41 +1,41 @@
|
|
|
1
|
-
var bn=/\x1b\](?:10|11|110|111|104)(?:;[^\x07\x1b]*)?\x1b?(?:\\|\x07)/g;function Qe(e){return e.replace(/\x1b\[\?1049[hl]/g,"")}function
|
|
2
|
-
`)}selectRows(t,s){let n=this.terminal.buffer.active,[
|
|
3
|
-
`)}getSelection(){return this.terminal.getSelection()}clearSelection(){this.terminal.clearSelection()}hasSelectionSupport(){return!0}};function xn(e){let t=e.getBoundingClientRect(),s=window.visualViewport;return s?{width:Math.min(t.width,s.width),height:Math.max(0,Math.min(t.height,s.height-Math.max(0,t.top)))}:t}function
|
|
4
|
-
\x1B[31m`+
|
|
5
|
-
`).then(()=>{
|
|
1
|
+
var bn=/\x1b\](?:10|11|110|111|104)(?:;[^\x07\x1b]*)?\x1b?(?:\\|\x07)/g;function Qe(e){return e.replace(/\x1b\[\?1049[hl]/g,"")}function me(e){return e.replace(bn,"")}var Fe;function En(){return Fe||(document.querySelector("link[data-tmux-web-xterm-css]")?Fe=Promise.resolve():(Fe=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)}),Fe))}var Ln=class Kt{terminal;fitAddon;container;webglActive=!1;repaintTimer=0;webglAddon=null;constructor(t,s,n){this.container=t,this.terminal=s,this.fitAddon=n,this.terminal.loadAddon(this.fitAddon),this.terminal.open(t),this.enableWebglRenderer(),document.addEventListener("visibilitychange",()=>{document.hidden||this.refreshPaintedRows()})}enableWebglRenderer(){if(Cn()==="webgl"){try{if(!document.createElement("canvas").getContext("webgl2",{failIfMajorPerformanceCaveat:!0}))return}catch{return}import("./addon-webgl-B45EJ6AW.js").then(({WebglAddon:t})=>{let s=new t;s.onContextLoss(()=>{this.webglActive=!1,this.webglAddon=null;try{s.dispose()}catch{}this.fit()});try{this.terminal.loadAddon(s)}catch{return}this.webglAddon=s,this.webglActive=!0,this.fit()}).catch(()=>{})}}refreshPaintedRows(){if(this.webglActive){try{this.webglAddon?.clearTextureAtlas?.()}catch{}try{this.terminal.refresh(0,Math.max(0,this.terminal.rows-1))}catch{}}}static async create(t,s,n){let[{Terminal:a},{FitAddon:r}]=await Promise.all([import("./xterm-BXEES47M.js"),import("./addon-fit-D5N335P2.js"),En()]),c="'JetBrains Mono', 'SF Mono', 'Menlo', monospace",o=new a({fontSize:xn(14,c),fontFamily:c,cursorBlink:!0,cursorStyle:"bar",scrollback:s,convertEol:!1,smoothScrollDuration:120,theme:n});return new Kt(t,o,new r)}get cols(){return this.terminal.cols}get rows(){return this.terminal.rows}write(t){return new Promise(s=>this.terminal.write(t,s))}reset(){this.terminal.reset()}scrollToBottom(){this.terminal.scrollToBottom()}scrollToLine(t,s=!1){this.terminal.scrollToLine(Math.max(0,t),s),this.scheduleRepaintCheck()}scrollLines(t){this.terminal.scrollLines(t),this.scheduleRepaintCheck()}scheduleRepaintCheck(){this.webglActive&&(this.repaintTimer&&clearTimeout(this.repaintTimer),this.repaintTimer=setTimeout(()=>{this.repaintTimer=0,this.refreshPaintedRows()},150))}isNearScrollbackTop(){return this.terminal.buffer.active.viewportY<=1}viewportY(){return this.terminal.buffer.active.viewportY}baseY(){return this.terminal.buffer.active.baseY}cellHeight(){let t=this.terminal.element?.querySelector(".xterm-screen")?.getBoundingClientRect().height??0,s=this.terminal.rows;return t>0&&s>0?t/s:16}fit(){let t=kn(this.container);if(t.width<=0||t.height<=0)return!1;let s=this.terminal.cols,n=this.terminal.rows;return this.fitAddon.fit(),this.webglActive&&(s!==this.terminal.cols||n!==this.terminal.rows)&&this.refreshPaintedRows(),!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,s){let n=this.terminal.buffer.active,[a,r]=t<=s?[t,s]:[s,t],c=n.viewportY,o=[];for(let u=a;u<=r;u++){let p=n.getLine(c+u);o.push(p?p.translateToString(!0):"")}return o.join(`
|
|
2
|
+
`)}selectRows(t,s){let n=this.terminal.buffer.active,[a,r]=t<=s?[t,s]:[s,t];this.terminal.selectLines(n.viewportY+a,n.viewportY+r)}selectCells(t,s,n,a){let r=this.terminal.buffer.active,c=Math.min(s,a),o=Math.max(s,a);if(c===o){let u=Math.min(t,n),p=Math.max(t,n);this.terminal.select(u,r.viewportY+c,p-u+1)}else this.terminal.selectLines(r.viewportY+c,r.viewportY+o)}getCellsText(t,s,n,a){let r=this.terminal.buffer.active,c=Math.min(s,a),o=Math.max(s,a),u=s<a?t:s>a?n:Math.min(t,n),p=s<a?n:s>a?t:Math.max(t,n),E=r.viewportY,x=[];for(let A=c;A<=o;A++){let B=r.getLine(E+A);if(!B){x.push("");continue}let b=A===c?u:0,q=A===o?p:this.terminal.cols-1,ae="";for(let Ce=b;Ce<=q;Ce++){let K=B.getCell(Ce);K&&(ae+=K.getChars())}x.push(ae.replace(/\s+$/,""))}return x.join(`
|
|
3
|
+
`)}getSelection(){return this.terminal.getSelection()}clearSelection(){this.terminal.clearSelection()}hasSelectionSupport(){return!0}};function xn(e,t){try{let s=document.createElement("canvas").getContext("2d");if(!s)return e;let n=100;s.font=`${n}px ${t}`;let a=s.measureText("M").width/n;if(!Number.isFinite(a)||a<=0)return e;let r=window.devicePixelRatio||1,c=e,o=Number.POSITIVE_INFINITY;for(let u=4;u<=40;u++){let p=u/(a*r);if(p<e-1.5||p>e+1.5)continue;let E=Math.abs(p-e);E<o&&(o=E,c=p)}return Math.round(c*100)/100}catch{return e}}function Cn(){try{let e=new URLSearchParams(window.location.search).get("renderer");return e==="dom"||e==="webgl"?e:null}catch{return null}}function kn(e){let t=e.getBoundingClientRect(),s=window.visualViewport;return s?{width:Math.min(t.width,s.width),height:Math.max(0,Math.min(t.height,s.height-Math.max(0,t.top)))}:t}function Tn(e,t,s){return e.innerHTML="",e.classList.add("terminal-pending"),(async()=>{let n=await Ln.create(e,s.scrollback,s.theme),a,r=0,c,o=null,u=0,p=0,E=.2,x=10,A=.95,B=.04,b=null,q=null;function ae(i){b||(b=document.createElement("div"),b.style.cssText=["position:absolute","left:0","width:40%","padding:10px 0","text-align:center","font:600 14px/1.4 system-ui, -apple-system, sans-serif","color:rgba(255,255,255,0.95)","background:rgba(20,30,50,0.55)","border:1px solid rgba(255,255,255,0.25)","border-radius:10px","pointer-events:none","opacity:0","transition:opacity 0.15s ease","z-index:6"].join(";"),e.appendChild(b)),b.textContent=i?"\u2191 \u4E0A\u7FFB\u4E00\u9875 (PgUp)":"\u2193 \u4E0B\u7FFB\u4E00\u9875 (PgDn)",b.style.top=i?"10%":"auto",b.style.bottom=i?"auto":"10%",b.style.opacity="1",q&&clearTimeout(q),q=setTimeout(()=>{b&&(b.style.opacity="0")},900)}function Ce(){q&&clearTimeout(q),b&&(b.style.opacity="0")}function K(){u&&(cancelAnimationFrame(u),u=0),p=0}function Vt(i){if(K(),Math.abs(i)<E)return;p=Math.max(-x,Math.min(x,i));let l=()=>{if(_){u=0;return}let d=n.cellHeight(),m=d>0?Math.round(p*16/d):p>0?1:-1;m===0&&(m=p>0?1:-1);let g=n.viewportY()-m,P=n.baseY(),Y=Math.max(0,Math.min(g,P));if(n.scrollToLine(Y,!0),p*=A,Y!==g){u=0;return}if(Math.abs(p)<B){u=0;return}u=requestAnimationFrame(l)};u=requestAnimationFrame(l)}let ke=0,$="connecting",Te=0,oe=!1,Se=[],Q="",_=!1,le=1e3,Xt=location.protocol==="https:"?"wss:":"ws:",ct=s.wsBase||"/ws",Jt=Xt+"//"+location.host+ct+"/"+encodeURIComponent(t),Zt=(ct.replace(/^\/ws/,"")||"")+"/api/session/"+encodeURIComponent(t)+"/upload",Gt=/^((?!chrome|android|crios|fxios|edgios).)*safari/i.test(navigator.userAgent);function Qt(){return Se.join("")+Q}async function en(i,l=0){let d=i?n.viewportY():0,m=me(Qt());if(n.reset(),!m){i||n.scrollToBottom();return}await n.write(m),i?n.scrollToLine(l+d):n.scrollToBottom()}function V(i){a?.readyState===WebSocket.OPEN&&a.send(JSON.stringify(i))}function tn(i){let l;try{l=JSON.parse(i)}catch{$==="live"&&(Q+=i,n.write(me(i)));return}if(l.type==="auth.required"){let d=localStorage.getItem("tmux-web-token");d?V({type:"auth.token",token:d}):location.href="/login?returnTo="+encodeURIComponent(location.pathname+location.search);return}if(l.type==="attach_failed"&&typeof l.message=="string"){Ie=!0,$="dead",n.reset(),n.write(`\r
|
|
4
|
+
\x1B[31m`+me(l.message)+`\x1B[0m\r
|
|
5
|
+
`).then(()=>{Be();try{a?.close()}catch{}});return}if(l.type==="auth.ok"){l.token&&localStorage.setItem("tmux-web-token",l.token),le=1e3,X(),V({type:"resize",cols:n.cols,rows:n.rows}),I();return}if(l.type==="auth.failed"){if(l.permanentLock||l.retryAfterMs&&l.retryAfterMs>6e4){localStorage.removeItem("tmux-web-token"),location.href="/login?error="+encodeURIComponent(l.message);return}return}if(l.type==="snapshot"&&typeof l.data=="string"){let d=Qe(me(l.data));Se=[d],Q="",Te=typeof l.lines=="number"?l.lines:s.terminal.initialLines,$="live",n.reset(),X(),V({type:"resize",cols:n.cols,rows:n.rows}),n.write(d).then(()=>n.scrollToBottom());return}if(l.type==="window_changed"&&typeof l.activeIndex=="number"){let d=new URL(location.href);d.searchParams.get("window")!==String(l.activeIndex)&&(d.searchParams.set("window",String(l.activeIndex)),history.replaceState(history.state,"",d)),window.dispatchEvent(new CustomEvent("tmux:windows",{detail:l.windows}));return}if(l.type==="history"&&typeof l.data=="string"){l.lines>0&&l.data?(Se.unshift(Qe(l.data)),Te+=l.lines,en(!0,l.lines).finally(()=>{oe=!1})):oe=!1;return}if(l.type==="data"&&typeof l.data=="string"){let d=Qe(me(l.data));if($==="connecting"){$="live",Q=d,n.write(d);return}$==="live"&&(Q+=d,n.write(d))}}let Ie=!1;function dt(){if(Ie)return;let i=Jt,l=localStorage.getItem("tmux-web-token");l&&(i+=(i.includes("?")?"&":"?")+"token="+encodeURIComponent(l)),i+=(i.includes("?")?"&":"?")+"cols="+n.cols+"&rows="+n.rows,a=new WebSocket(i),a.onopen=()=>{$="connecting",Te=0,oe=!1,Se=[],Q="",n.reset(),le=1e3},a.onmessage=d=>{typeof d.data=="string"&&tn(d.data)},a.onclose=()=>{_||($="connecting",!Ie&&setTimeout(()=>{le=Math.min(le*2,1e4),!_&&!Ie&&dt()},le))},a.onerror=()=>a?.close()}function ee(i){V({type:"input",data:i})}function X(){return n.fit()}function Be(){e.classList.remove("terminal-pending")}function I(){r&&cancelAnimationFrame(r),c&&clearTimeout(c),X(),r=requestAnimationFrame(()=>{r=0,X()&&Be()}),c=setTimeout(()=>{X()&&Be()},120)}function nn(){I(),setTimeout(I,50),setTimeout(I,150),setTimeout(I,300)}function ut(i){return typeof i=="string"&&i.startsWith("image/")}function pt(i){return i?.files?.length?i.files[0]??null:null}function sn(i){if(!i?.items)return null;for(let l=0;l<i.items.length;l++){let d=i.items[l];if(d?.kind==="file"&&ut(d.type))return d.getAsFile()}return null}async function an(i){let l=new FormData,d=i instanceof File&&i.name?i.name:"upload";l.append("file",i,d);let m=localStorage.getItem("tmux-web-token"),g={};m&&(g.Authorization="Bearer "+m);let P=await fetch(Zt,{method:"POST",body:l,headers:g});if(!P.ok){let wt="upload failed";try{let bt=await P.json();bt.error&&(wt=bt.error)}catch{}throw new Error(wt)}let Y=await P.json();if(!Y.path)throw new Error("no path in response");return Y.path}async function Je(i){try{let l=await an(i);ee(l)}catch{}}n.onData(i=>ee(i)),n.onResize(({cols:i,rows:l})=>V({type:"resize",cols:i,rows:l})),n.onScroll(()=>{$!=="live"||oe||!n.isNearScrollbackTop()||(oe=!0,V({type:"load_history",before:Te}))});let re=!1,ce=!1,L=null,C=null,de=document.createElement("div");de.className="terminal-copy-banner",de.innerHTML='<strong>Copy mode</strong><span class="hint">drag to copy \xB7 Esc exits</span>',de.hidden=!0,e.appendChild(de);let z=document.createElement("div");z.className="terminal-copy-banner terminal-copy-toast",z.textContent="Copied",z.hidden=!0,e.appendChild(z);function mt(i,l){let d=e.querySelector(".xterm-screen, canvas"),m=(d&&d.getBoundingClientRect().width>0?d:e).getBoundingClientRect(),g=m.height>0&&n.rows>0?m.height/n.rows:18,P=m.width>0&&n.cols>0?m.width/n.cols:9;return{row:Math.max(0,Math.min(n.rows-1,Math.floor((l-m.top)/g))),col:Math.max(0,Math.min(n.cols-1,Math.floor((i-m.left)/P)))}}async function Me(i){if(!i)return;try{if(navigator.clipboard?.writeText){await navigator.clipboard.writeText(i);return}}catch{}let l=document.createElement("textarea");l.value=i,l.style.position="fixed",l.style.opacity="0",l.style.pointerEvents="none",document.body.appendChild(l),l.focus(),l.select();try{document.execCommand("copy")}catch{}l.remove()}let ue;function De(){z.hidden=!1,ue&&clearTimeout(ue),ue=setTimeout(()=>{z.hidden=!0},1e3)}function te(i){re=i,de.hidden=!i,e.classList.toggle("terminal-copy-mode-active",i),i&&n.focus()}function ft(){te(!re)}function on(i){_||i.button!==0||ce||(re||i.shiftKey)&&(i.preventDefault(),i.stopPropagation(),ce=!0,L=mt(i.clientX,i.clientY),C=L,n.selectCells(L.col,L.row,C.col,C.row),document.addEventListener("mousemove",Ze,!0),document.addEventListener("mouseup",Ge,!0))}function Ze(i){_||!ce||!L||(i.preventDefault(),i.stopPropagation(),C=mt(i.clientX,i.clientY),n.selectCells(L.col,L.row,C.col,C.row))}function Ge(i){if(_||!ce||!L||!C)return;i.preventDefault(),i.stopPropagation(),document.removeEventListener("mousemove",Ze,!0),document.removeEventListener("mouseup",Ge,!0),ce=!1;let l=n.getCellsText(L.col,L.row,C.col,C.row);L=null,C=null,n.clearSelection(),te(!1),l&&(z.textContent="\u5DF2\u590D\u5236",Me(l).then(De)),n.focus()}e.addEventListener("mousedown",on,!0),document.addEventListener("keydown",ln,!0);function ln(i){if(!(_||!n.isFocused()||i.defaultPrevented||i.isComposing)){if(re){if(i.key==="Escape"){i.preventDefault(),i.stopPropagation(),L=null,C=null,n.clearSelection(),te(!1);return}if(i.key==="Enter"||(i.ctrlKey||i.metaKey)&&i.code==="KeyC"){i.preventDefault(),i.stopPropagation(),Me(n.getScreenText()).then(De),te(!1);return}}if(i.altKey&&i.code==="KeyC"&&!i.ctrlKey&&!i.metaKey){if(i.preventDefault(),i.stopPropagation(),L&&C){let l=n.getCellsText(L.col,L.row,C.col,C.row);L=null,C=null,n.clearSelection(),te(!1),l&&(z.textContent="Copied",Me(l).then(De))}else{let l=n.getSelection();l?(n.clearSelection(),z.textContent="Copied",Me(l).then(De)):ft()}return}if((i.ctrlKey||i.metaKey)&&i.code==="KeyV"){i.preventDefault(),i.stopPropagation(),(async()=>{try{if(navigator.clipboard?.read){let l=await navigator.clipboard.read();for(let d of l)for(let m of d.types)if(ut(m)){let g=await d.getType(m);await Je(g);return}}}catch{}try{let l=await navigator.clipboard?.readText();l&&n.pasteText(ht(l))}catch{}})();return}}}let Ae=0;function ht(i){return i.split(`\r
|
|
6
6
|
`).join(`
|
|
7
7
|
`).split(`
|
|
8
|
-
`).join("\r")}async function rn(
|
|
8
|
+
`).join("\r")}async function rn(i){let l=sn(i.clipboardData);if(l){i.preventDefault(),i.stopPropagation();let g=Date.now();if(g-Ae<50)return;Ae=g,await Je(l);return}let d=i.clipboardData?.getData("text/plain");if(!d)return;i.preventDefault(),i.stopPropagation();let m=Date.now();m-Ae<50||(Ae=m,n.pasteText(ht(d)))}let pe=0;function cn(i){i.preventDefault(),pe++,pt(i.dataTransfer)&&e.classList.add("terminal-drag-over")}function dn(i){i.preventDefault(),i.dataTransfer&&(i.dataTransfer.dropEffect="copy")}function un(i){i.preventDefault(),pe--,pe<=0&&(pe=0,e.classList.remove("terminal-drag-over"))}async function pn(i){i.preventDefault(),pe=0,e.classList.remove("terminal-drag-over");let l=pt(i.dataTransfer);l&&await Je(l)}function gt(i){!Gt||i.key!=="Escape"||re||i.defaultPrevented||i.repeat||i.metaKey||i.ctrlKey||i.altKey||n.isFocused()&&(i.preventDefault(),i.stopPropagation(),ee("\x1B"))}e.addEventListener("paste",rn),e.addEventListener("dragenter",cn),e.addEventListener("dragover",dn),e.addEventListener("dragleave",un),e.addEventListener("drop",pn),document.addEventListener("keydown",gt,!0);function mn(i){if(i.touches.length!==1){o=null;return}let l=i.touches[0];if(!l)return;K();let d=e.getBoundingClientRect(),m=l.clientX-d.left<d.width*.4?"tui":"history",g=l.clientY-d.top<d.height*.5;o={startX:l.clientX,startY:l.clientY,lastX:l.clientX,lastY:l.clientY,lastT:performance.now(),velocity:0,scrolling:!1,zone:m,tuiUp:g,sent:!1},i.stopPropagation()}function fn(i){if(!o||i.touches.length!==1)return;let l=i.touches[0];if(!l)return;let d=l.clientY-o.startY,m=l.clientX-o.startX;if(!o.scrolling){if(Math.abs(d)<8||Math.abs(d)<Math.abs(m))return;o.scrolling=!0,ke=Date.now()+500}i.preventDefault(),i.stopPropagation();let g=performance.now(),P=l.clientY-o.lastY;if(o.zone==="tui"){o.sent||(o.sent=!0,ee(o.tuiUp?"\x1B[5~":"\x1B[6~"),ae(o.tuiUp)),o.lastX=l.clientX,o.lastY=l.clientY,o.lastT=g;return}let Y=g-o.lastT;Y>0&&(o.velocity=P/Y),yn(-P),o.lastX=l.clientX,o.lastY=l.clientY,o.lastT=g}function hn(i){if(!o)return;let l=o.scrolling,d=o.zone,m=o.tuiUp,g=o.velocity;if(o=null,i.stopPropagation(),d==="tui"){l||(ee(m?"\x1B[5~":"\x1B[6~"),ae(m),ke=Date.now()+500,i.preventDefault());return}if(!l){n.focus();return}ke=Date.now()+500,i.preventDefault(),g&&Vt(g)}function gn(i){o=null,K(),i.stopPropagation()}function vn(i){i.pointerType==="touch"&&Date.now()<ke&&(i.preventDefault(),i.stopPropagation())}function yn(i){let l=n.cellHeight(),d=l>0?Math.round(i/l):i>0?1:-1;d===0&&(d=i>0?1:-1),n.scrollLines(d)}e.addEventListener("touchstart",mn,{passive:!0,capture:!0}),e.addEventListener("touchmove",fn,{passive:!1,capture:!0}),e.addEventListener("touchend",hn,{passive:!1,capture:!0}),e.addEventListener("touchcancel",gn,{passive:!0,capture:!0}),e.addEventListener("pointerup",vn,!0);function vt(){I()}window.addEventListener("resize",vt),window.visualViewport?.addEventListener("resize",I),window.visualViewport?.addEventListener("scroll",I);let yt=new ResizeObserver(()=>I());yt.observe(e),document.fonts?.ready.then(()=>{I(),setTimeout(I,50),setTimeout(I,200)}),e.addEventListener("focusin",nn,!0);async function wn(){if(document.fonts?.ready)try{await Promise.race([document.fonts.ready,new Promise(i=>setTimeout(i,1e3))])}catch{}}return requestAnimationFrame(()=>{X()&&Be(),(async()=>(await wn(),X()&&V({type:"resize",cols:n.cols,rows:n.rows}),dt(),I()))()}),{destroy(){if(_=!0,K(),te(!1),ue&&clearTimeout(ue),document.removeEventListener("mousemove",Ze,!0),document.removeEventListener("mouseup",Ge,!0),a){try{a.close(1e3,"session switch")}catch{}a=void 0}e.innerHTML="",e.classList.remove("terminal-pending"),window.removeEventListener("resize",vt),yt.disconnect(),document.removeEventListener("keydown",gt,!0)},focus(){n.focus()},sendInput(i){ee(i)},toggleCopyMode(){ft()}}})()}var fe=window.__TMUX_WEB_SHELL__,v=null,y=null,he=typeof window.__TMUX_WEB_SCOPE__?.agentId=="string"?window.__TMUX_WEB_SCOPE__.agentId:null,k=he;window.__tmuxWebScopeAgent=he;var et="sessions",O="",He="",Re="",Et="";function T(e){return k?"/a/"+encodeURIComponent(k)+e:e}var f=document.getElementById("sidebar-content"),J=document.getElementById("main-placeholder"),M=document.getElementById("terminal-container"),ge=document.getElementById("file-editor"),Sn=document.getElementById("fe-path"),F=document.getElementById("fe-status"),ve=document.getElementById("fe-content"),Z=document.getElementById("fe-save"),In=document.getElementById("fe-delete"),Bn=document.getElementById("fe-back"),Lt=document.getElementById("fe-new-name"),Mn=document.getElementById("fe-new-btn"),tt=document.getElementById("settings-backdrop"),xt=document.getElementById("settings-popover"),Ct=document.querySelector(".sidebar"),kt="tmux-web-force-narrow";function Pe(){try{return localStorage.getItem(kt)==="1"}catch{return!1}}function Tt(){document.documentElement.classList.toggle("force-narrow",Pe()),Pe()&&St()&&Ne()}function St(){return Pe()?!0:window.matchMedia("(max-width: 640px)").matches}function Ne(){St()&&Ct.classList.add("collapsed")}function It(){Ct.classList.remove("collapsed")}document.getElementById("mode-sessions").addEventListener("click",()=>{It(),Bt("sessions")}),document.getElementById("mode-files").addEventListener("click",()=>{It(),Bt("files")});function Bt(e){et=e,document.querySelectorAll(".mode-btn").forEach(s=>s.classList.remove("active"));let t=document.getElementById(e==="sessions"?"mode-sessions":"mode-files");t&&t.classList.add("active"),e==="sessions"?(nt="",j()):On()}var nt="";async function j(){if(et!=="sessions")return;try{let t=await(await fetch("/api/sidebar/sessions")).json(),s=JSON.stringify({recent:t.recent,agents:t.agents,tombstones:t.tombstones});if(s===nt)return;nt=s,Rn(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")}),rt()}var Mt="tmux-web-sidebar-group-collapsed";function Dt(){try{return new Set(JSON.parse(localStorage.getItem(Mt)||"[]"))}catch{return new Set}}function Dn(e){try{localStorage.setItem(Mt,JSON.stringify([...e]))}catch{}}function An(e,t,s){if(!e)return"\u2026";let n=s&&(e===s||e.startsWith(s+"/"))?"~"+e.slice(s.length):e,a=n.split("/").filter(Boolean);if(a.length===0)return e;for(let r=1;r<=a.length;r++){let c=a.slice(-r).join("/");if(!t.some(o=>!o||o===e?!1:(s&&(o===s||o.startsWith(s+"/"))?"~"+o.slice(s.length):o).split("/").filter(Boolean).slice(-r).join("/")===c))return c}return n}function At(e,t,s,n=!0){let a=new Map;for(let o of e){let u=o.path||"";a.has(u)||a.set(u,[]),a.get(u).push(o)}let r=[...a.keys()],c=Dt();for(let[o,u]of a){let p=An(o,r,t),E=c.has(o),x=document.createElement("div");x.className="session-group-header"+(E?" collapsed":""),x.title=o||"No working directory",x.innerHTML=`<span class="sg-folder">📁</span><span class="sg-label">${h(p)}</span>`,x.addEventListener("click",()=>{let B=Dt(),b=x.nextElementSibling;B.has(o)?(B.delete(o),x.classList.remove("collapsed"),b?.classList.remove("collapsed")):(B.add(o),x.classList.add("collapsed"),b?.classList.add("collapsed")),Dn(B)});let A=document.createElement("div");A.className="session-group-body"+(E?" collapsed":"");for(let B of u)A.appendChild(s?Fn(B,s,n):Hn(B));f.appendChild(x),f.appendChild(A)}}function Fn(e,t,s){let n=document.createElement("div");n.className="session-item"+(e.name===y&&k===t?" active":"")+(s?"":" session-offline"),n.setAttribute("data-session",e.name),n.setAttribute("data-agent",t),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>
|
|
9
9
|
<span>${h(e.name)}</span>${s?"":'<span class="meta">offline</span>'}
|
|
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>`,s&&n.addEventListener("click",r=>{r.target.closest(".session-edit-btn")||ye(e.name,t)});let
|
|
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>`,s&&n.addEventListener("click",r=>{r.target.closest(".session-edit-btn")||ye(e.name,t)});let a=n.querySelector(".session-edit-btn");return a&&a.addEventListener("click",r=>{r.stopPropagation(),Ke(e.name,a,{agentId:t})}),n}function Hn(e){let t=document.createElement("div");t.className="session-item"+(e.name===y&&!k?" 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>
|
|
11
11
|
<span>${h(e.name)}</span>
|
|
12
12
|
<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>
|
|
13
|
-
`,t.addEventListener("click",n=>{n.target.closest(".session-edit-btn")||ye(e.name)});let s=t.querySelector(".session-edit-btn");return s&&s.addEventListener("click",n=>{n.stopPropagation(),Ke(e.name,s)}),t}function
|
|
13
|
+
`,t.addEventListener("click",n=>{n.target.closest(".session-edit-btn")||ye(e.name)});let s=t.querySelector(".session-edit-btn");return s&&s.addEventListener("click",n=>{n.stopPropagation(),Ke(e.name,s)}),t}function Rn(e){f.innerHTML='<button class="new-session-sidebar-btn" id="ns-btn">+ New Session</button>';let t=e.recent||[],s=document.createElement("div");s.className="sidebar-section-label"+(he?" clickable":""),s.textContent=he?"\u2190 \u8FD4\u56DE\u672C\u673A":"\u672C\u673A",he&&(s.title="Back to hub",s.addEventListener("click",()=>{window.location.href="/"})),f.appendChild(s),At(t,e.home);let n=e.agents||[];for(let r of n){if(!r.sessions||r.sessions.length===0)continue;let c=r.agentId===k,o=document.createElement("div");o.className="sidebar-section-label machine-label"+(r.online?"":" agent-offline-label")+(!c&&r.online?" clickable":""),o.textContent=r.agentName+(r.online?"":" (offline)"),!c&&r.online&&(o.title="\u6253\u5F00 "+r.agentName,o.addEventListener("click",()=>{window.location.href="/a/"+encodeURIComponent(r.agentId)+"/"})),f.appendChild(o),At(r.sessions,e.home,r.agentId,r.online)}let a=e.tombstones||[];if(a.length>0){let r=document.createElement("div");r.className="sidebar-section-label tombstone-label",r.textContent="\u5931\u6548\u4F1A\u8BDD",f.appendChild(r);for(let c of a){let o=document.createElement("div");o.className="session-item session-tombstone",o.setAttribute("data-session",c.name),c.agentId&&o.setAttribute("data-agent",c.agentId);let u=c.agentId?c.agentOnline?" (agent)":" (agent \u79BB\u7EBF)":"";o.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"></svg>
|
|
14
14
|
<span>${h(c.name)}</span><span class="meta">\u5931\u6548${u}</span>
|
|
15
|
-
<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>`,o.title="\u5931\u6548\u4F1A\u8BDD\uFF1A\u70B9\u51FB\u7BA1\u7406\uFF08\u91CD\u5EFA/\u91CD\u547D\u540D/\u5220\u9664\uFF09",o.addEventListener("click",()=>{Ke(c.name,o,{tombstone:!0,agentId:c.agentId})});let p=o.querySelector(".session-edit-btn");p&&p.addEventListener("click",
|
|
15
|
+
<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>`,o.title="\u5931\u6548\u4F1A\u8BDD\uFF1A\u70B9\u51FB\u7BA1\u7406\uFF08\u91CD\u5EFA/\u91CD\u547D\u540D/\u5220\u9664\uFF09",o.addEventListener("click",()=>{Ke(c.name,o,{tombstone:!0,agentId:c.agentId})});let p=o.querySelector(".session-edit-btn");p&&p.addEventListener("click",E=>{E.stopPropagation(),Ke(c.name,p,{tombstone:!0,agentId:c.agentId})}),f.appendChild(o)}}}function h(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}async function ye(e,t){if(y===e&&v&&k===(t||null))return;ge.style.display="none",J.style.display="none",M.style.display="",M.classList.add("terminal-pending"),Ne(),v&&(We(),v.destroy(),v=null),y=e,k=t||null,window.__tmuxWebScopeAgent=k,window.__tmuxWebCurrentSession=y,ss(e,t);let s=lt(e,t);Wt.set(s,Date.now()+ts);let n=ie.get(s);if(n&&n.state==="working"){n.state="idle",n.doneUntil=void 0,n.unread=!1;let a=f.querySelector(t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])');a&&Xe(a,s,n)}for(let a of f.querySelectorAll(".session-item"))a.classList.toggle("active",a.getAttribute("data-session")===e&&(a.getAttribute("data-agent")||null)===k);try{v=await Tn(M,e,{terminal:fe.terminal,scrollback:fe.scrollback,theme:fe.theme,wsBase:k?"/ws/a/"+encodeURIComponent(k):fe.wsBase||"/ws"}),_t()}catch(a){console.error("[shell] terminal init failed:",a);let r=a&&typeof a=="object"&&"message"in a?a.message:String(a);M.textContent="Failed to open terminal for "+e+": "+r,M.classList.remove("terminal-pending")}}var $e=[],w=null,Ft=!1;function Pn(e){if(!w||!w.files.length)return null;let t=w.repoRoot;if(!t||!e.startsWith(t))return null;let s=e.slice(t.length+1);for(let n of w.files)if(n.path===s)return n.status;return null}async function Nn(e){Ft=!0;try{let t=await fetch(T("/api/git/status?path="+encodeURIComponent(e)));t.ok?w=await t.json():w=null}catch{w=null}finally{Ft=!1}}function $n(){if(!w||!w.branch)return"";let{branch:e,linesAdded:t,linesRemoved:s}=w,n=`<div class="sidebar-git"><div class="git-branch-badge">
|
|
16
16
|
<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>
|
|
17
|
-
${h(e)}</div>`;return(t>0||s>0)&&(n+=`<div class="git-diff-stats">+<span class="add">${t}</span> <span class="del">-${s}</span></div>`),n+"</div>"}
|
|
18
|
-
<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 s=0;s<e.length;s++){let n=e[s],
|
|
17
|
+
${h(e)}</div>`;return(t>0||s>0)&&(n+=`<div class="git-diff-stats">+<span class="add">${t}</span> <span class="del">-${s}</span></div>`),n+"</div>"}f.addEventListener("click",e=>{e.target.closest(".sidebar-git")&&ne&&w&&(e.stopPropagation(),$t())});var we=document.getElementById("header-git"),Ht=document.getElementById("git-diff-view"),Rt=document.getElementById("gd-path"),ze=document.getElementById("gd-status"),je=document.getElementById("gd-content"),zn=document.getElementById("gd-back"),ne=null;function be(e){if(!e||!e.branch){we.style.display="none",ne=null;return}ne=e.repoRoot;let{branch:t,linesAdded:s,linesRemoved:n}=e,a=`<span class="branch">${h(t)}</span>`;(s>0||n>0)&&(a+=`<span class="sep">\xB7</span>+<span class="diff-add">${s}</span> <span class="diff-del">-${n}</span>`),we.innerHTML=a,we.style.display="block"}we.addEventListener("click",e=>{ne&&w&&(e.stopPropagation(),$t())});var S=document.getElementById("git-popover"),Ue=document.getElementById("git-popover-backdrop");function st(){let e=we.getBoundingClientRect();S.style.top=e.bottom+4+"px",S.style.left=Math.max(8,Math.min(e.left,window.innerWidth-400))+"px"}function Pt(){let e=ne,t=document.getElementById("git-popover-browse");t&&t.addEventListener("click",()=>{if(Ye(),e){et="files",document.querySelectorAll(".mode-btn").forEach(n=>n.classList.remove("active"));let s=document.getElementById("mode-files");s&&s.classList.add("active"),W(e)}})}var Nt="";function $t(){if(!w)return;let e=w.files||[];if(!e.length)S.innerHTML=`<div class="git-popover-header">No changes \u2014 clean working tree</div>
|
|
18
|
+
<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 s=0;s<e.length;s++){let n=e[s],a=n.additions||0,r=n.deletions||0,c="";switch(n.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="${s}">
|
|
19
19
|
${c}<span class="file-path">${h(n.path)}</span>
|
|
20
|
-
<span class="file-add">${
|
|
20
|
+
<span class="file-add">${a>0?"+"+a:""}</span>
|
|
21
21
|
<span class="file-del">${r>0?"-"+r:""}</span>
|
|
22
|
-
</div>`}t+='<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>',
|
|
22
|
+
</div>`}t+='<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>',Nt=t,S.innerHTML=t,S.querySelectorAll(".git-popover-item").forEach(s=>{let n=parseInt(s.dataset.idx||"0",10),a=e[n];!a||a.status==="D"||(s.classList.add("clickable"),s.style.cursor="pointer",s.addEventListener("click",()=>jt(a.path)))})}st(),S.classList.add("open"),Ue.classList.add("open"),Pt()}function jn(){return window.innerWidth>=1024}function zt(e,t){let s=(e+(t&&e?`
|
|
23
23
|
`:"")+t).split(`
|
|
24
|
-
`),n="",
|
|
24
|
+
`),n="",a=0,r=0;for(let c of s){let o=c;if(o.startsWith("@@")){let u=o.match(/@@\s+-(\d+)[^+]*\+(\d+)/);u&&(a=parseInt(u[1],10)-1,r=parseInt(u[2],10)-1),n+=`<div class="diff-line hunk"><span class="ln-body">${h(o)}</span></div>`;continue}if(o.startsWith("diff --git")||o.startsWith("index ")||o.startsWith("--- ")||o.startsWith("+++ ")||o.startsWith("new file")||o.startsWith("deleted file")){o.startsWith("diff --git")&&(n+=`<div class="diff-line header"><span class="ln-body">${h(o)}</span></div>`);continue}if(o.startsWith("+"))r++,n+=`<div class="diff-line add"><span class="ln-no">${r}</span><span class="ln-body">${h(o)}</span></div>`;else if(o.startsWith("-"))a++,n+=`<div class="diff-line del"><span class="ln-no">${a}</span><span class="ln-body">${h(o)}</span></div>`;else if(o.startsWith("\\"))n+=`<div class="diff-line"><span class="ln-body">${h(o)}</span></div>`;else{if(!o&&!a&&!r)continue;a++,r++,n+=`<div class="diff-line"><span class="ln-no">${a}</span><span class="ln-no" style="margin-right:12px">${r}</span><span class="ln-body">${h(o)}</span></div>`}}return{html:n,lineCount:s.length}}var _e=null;async function jt(e){let t=ne;if(t)if(Ye(),jn()){M.style.display="none",v&&(We(),v.destroy(),v=null,_e=y,y=null),be(null),ge.style.display="none",J.style.display="none",Ht.style.display="flex",Rt.textContent=e,ze.textContent="Loading\u2026",je.innerHTML="";try{let s=await fetch(T("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!s.ok)throw new Error(await s.text());let n=await s.json();_n(e,n.diff,n.stagedDiff)}catch(s){let n=s instanceof Error?s.message:String(s);ze.textContent="Error",je.innerHTML=`<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">Error: ${h(n)}</div>`}}else{S.innerHTML=`<div class="git-diff-view"><div class="diff-header">
|
|
25
25
|
<button class="diff-back">\u2190 Back</button>
|
|
26
26
|
<span class="diff-filename">${h(e)}</span>
|
|
27
27
|
<span class="diff-loading">Loading\u2026</span>
|
|
28
|
-
</div></div>`,st(),S.classList.add("open"),Ue.classList.add("open");try{let s=await fetch(
|
|
28
|
+
</div></div>`,st(),S.classList.add("open"),Ue.classList.add("open");try{let s=await fetch(T("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!s.ok)throw new Error(await s.text());let n=await s.json();Un(e,n.diff,n.stagedDiff)}catch(s){let n=s instanceof Error?s.message:String(s);S.innerHTML=`<div class="git-diff-view"><div class="diff-header">
|
|
29
29
|
<button class="diff-back">\u2190 Back</button>
|
|
30
30
|
<span class="diff-filename">${h(e)}</span>
|
|
31
|
-
</div><div class="diff-empty">Error loading diff: ${h(n)}</div></div>`}}}function
|
|
31
|
+
</div><div class="diff-empty">Error loading diff: ${h(n)}</div></div>`}}}function Un(e,t,s){if(!t&&!s){S.innerHTML=`<div class="git-diff-view"><div class="diff-header">
|
|
32
32
|
<button class="diff-back">\u2190 Back</button>
|
|
33
33
|
<span class="diff-filename">${h(e)}</span>
|
|
34
|
-
</div><div class="diff-empty">No diff content available</div></div>`;return}let{html:n,lineCount:
|
|
34
|
+
</div><div class="diff-empty">No diff content available</div></div>`;return}let{html:n,lineCount:a}=zt(t,s);S.innerHTML=`<div class="git-diff-view"><div class="diff-header">
|
|
35
35
|
<button class="diff-back">\u2190 Back</button>
|
|
36
36
|
<span class="diff-filename">${h(e)}</span>
|
|
37
|
-
<span class="diff-filesize">${
|
|
38
|
-
</div><div class="diff-content">${n}</div></div>`,S.querySelector(".diff-back")?.addEventListener("click",()=>{S.innerHTML=
|
|
37
|
+
<span class="diff-filesize">${a} lines</span>
|
|
38
|
+
</div><div class="diff-content">${n}</div></div>`,S.querySelector(".diff-back")?.addEventListener("click",()=>{S.innerHTML=Nt,st(),w&&S.querySelectorAll(".git-popover-item").forEach(r=>{let c=parseInt(r.dataset.idx||"0",10),o=w.files[c];!o||o.status==="D"||(r.style.cursor="pointer",r.addEventListener("click",()=>jt(o.path)))}),Pt()})}function _n(e,t,s){if(!t&&!s){ze.textContent="No diff",je.innerHTML='<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">No diff content available</div>';return}let{html:n,lineCount:a}=zt(t,s);Rt.textContent=e,ze.textContent=a+" lines",je.innerHTML=n}function Yn(){Ht.style.display="none",_e?(M.style.display="",M.classList.add("terminal-pending"),ye(_e),_e=null):y?(M.style.display="",M.classList.add("terminal-pending"),_t()):J.style.display="flex"}zn.addEventListener("click",Yn);function Ye(){S.classList.remove("open"),Ue.classList.remove("open")}Ue.addEventListener("click",Ye),document.addEventListener("keydown",e=>{e.key==="Escape"&&(Ye(),Ve())});async function Ut(e){try{let t=await(await fetch("/api/fs/session-path?session="+encodeURIComponent(e))).json();if(t.path){let s=await fetch("/api/git/status?path="+encodeURIComponent(t.path));if(s.ok){let n=await s.json();w=n,be(n);return}}}catch{}w=null,be(null)}var Oe=null;function _t(){We(),y&&(Ut(y),Oe=setInterval(()=>{y&&Ut(y)},3e4))}function We(){Oe&&(clearInterval(Oe),Oe=null)}function On(){if($e=fe.fsRoots||[],$e.length===0){if(y){Wn(y);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 $e){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",()=>W(e)),f.appendChild(t)}}async function Wn(e){f.innerHTML='<div class="file-tree-empty">Loading...</div>';try{let t=await(await fetch(T("/api/fs/session-path?session="+encodeURIComponent(e)))).json();t.path?W(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 W(e){O=e,f.innerHTML='<div class="file-tree-empty">Loading...</div>';let t=Nn(e);try{let s=await(await fetch(T("/api/fs/list?path="+encodeURIComponent(e)))).json();await t,f.innerHTML="",be(w),f.innerHTML+=$n();let n=qn(e);if(n&&!$e.some(r=>e===r)){let r=document.createElement("div");r.className="file-tree-item",r.innerHTML="..",r.addEventListener("click",()=>W(n)),f.appendChild(r)}if(s.dirs)for(let r of s.dirs){let c=r.split("/").pop()||r.split("\\").pop(),o=document.createElement("div");o.className="file-tree-item",o.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)}`,o.addEventListener("click",()=>W(r)),f.appendChild(o)}else f.innerHTML="";let a=s.files||[];for(let r of a){let c=r.split("/").pop()||r.split("\\").pop(),o=Pn(r),u="",p="";if(o)switch(o){case"M":u="git-mod",p='<span class="git-file-status M">M</span>';break;case"A":u="git-add",p='<span class="git-file-status A">A</span>';break;case"D":u="git-del",p='<span class="git-file-status D">D</span>';break;case"?":u="git-untracked",p='<span class="git-file-status ?">?</span>';break;case"R":u="git-mod",p='<span class="git-file-status R">R</span>';break}let E=document.createElement("div");E.className="file-tree-item file"+(u?" "+u:""),E.innerHTML=`<span class="file-icon">\u{1F4C4}</span> ${p}${h(c)}`,E.addEventListener("click",()=>Kn(r)),f.appendChild(E)}}catch{f.innerHTML='<div class="file-tree-error">Failed to load directory</div>'}}function qn(e){let t=e.lastIndexOf("/");return t<=0?null:e.substring(0,t)}async function Kn(e){He=e,M.style.display="none",v&&(We(),v.destroy(),v=null,y=null),be(null),Ne(),J.style.display="none",ge.style.display="flex",Sn.textContent=e,F.textContent="Loading...",Z.style.display="none";try{let t=await fetch(T("/api/file?path="+encodeURIComponent(e)));if(!t.ok){let n=await t.json();F.textContent=n.error||"Failed to load",ve.value="";return}let s=await t.json();ve.value=s.content,Re=s.content,Et=s.content,F.textContent=s.size+" bytes",Z.style.display=""}catch{F.textContent="Failed to load",ve.value=""}}ve.addEventListener("input",()=>{Re=ve.value}),Z.addEventListener("click",async()=>{Z.textContent="Saving...",Z.disabled=!0;try{let e=await fetch(T("/api/file"),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:He,content:Re})});if(!e.ok){let t=await e.json();F.textContent=t.error||"Save failed";return}Et=Re,F.textContent="Saved"}catch{F.textContent="Save failed"}finally{Z.disabled=!1,Z.textContent="Save"}}),In.addEventListener("click",async()=>{if(confirm("Delete "+He+"?"))try{let e=await fetch(T("/api/file/delete"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:He})});if(!e.ok){let t=await e.json();F.textContent=t.error||"Delete failed";return}ge.style.display="none",J.style.display="flex",O&&W(O)}catch{F.textContent="Delete failed"}}),Bn.addEventListener("click",()=>{ge.style.display="none",J.style.display="flex",O&&W(O)}),Mn.addEventListener("click",async()=>{let e=Lt.value.trim();if(!e)return;let t=O+"/"+e;try{let s=await fetch(T("/api/file/touch"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t})});if(!s.ok){let n=await s.json();F.textContent=n.error||"Create failed";return}Lt.value="",O&&W(O)}catch{F.textContent="Create failed"}});var qe=document.getElementById("force-narrow-toggle");qe&&(qe.checked=Pe(),qe.addEventListener("change",()=>{try{localStorage.setItem(kt,qe.checked?"1":"0")}catch{}Tt(),j()})),Tt(),document.getElementById("mode-settings").addEventListener("click",()=>{let e=xt.classList.toggle("open");tt.classList.toggle("open",e)}),tt.addEventListener("click",()=>{xt.classList.remove("open"),tt.classList.remove("open")});var D="",U=!1,H,Ee=document.createElement("div");Ee.className="session-popover-backdrop",document.body.appendChild(Ee);var R=document.createElement("div");R.id="session-popover",R.className="session-popover",R.style.display="none",R.innerHTML=`<div class="sp-field">
|
|
39
39
|
<label>Rename session</label>
|
|
40
40
|
<input type="text" id="sp-name" />
|
|
41
41
|
</div>
|
|
@@ -45,5 +45,5 @@ var bn=/\x1b\](?:10|11|110|111|104)(?:;[^\x07\x1b]*)?\x1b?(?:\\|\x07)/g;function
|
|
|
45
45
|
</div>
|
|
46
46
|
<hr class="sp-divider" />
|
|
47
47
|
<button class="btn primary" id="sp-rebuild" style="display:none">\u91CD\u5EFA\u540C\u540D\u540C\u8DEF\u5F84 session</button>
|
|
48
|
-
<button class="btn danger" id="sp-delete">Delete session</button>`,document.body.appendChild(R);function
|
|
49
|
-
`).length;
|
|
48
|
+
<button class="btn danger" id="sp-delete">Delete session</button>`,document.body.appendChild(R);function Vn(e){let t=e.getBoundingClientRect(),s=window.innerHeight,n=R.offsetHeight||240,a=t.bottom+4;a+n>s-8&&(a=Math.max(8,t.top-n-4)),R.style.top=a+"px",R.style.left=Math.max(8,Math.min(t.left,window.innerWidth-240))+"px"}function Ke(e,t,s){D=e,U=!!s?.tombstone,H=s?.agentId;let n=document.getElementById("sp-name");n.value=e;let a=R.querySelector(".sp-field label");a.textContent=U?"\u91CD\u547D\u540D (\u4EC5\u8BB0\u5F55\uFF0C\u4E0D\u91CD\u5EFA)":"Rename session";let r=document.getElementById("sp-rebuild");r.style.display=U?"":"none";let c=document.getElementById("sp-delete");c.textContent=U?"\u5220\u9664\u5931\u6548\u8BB0\u5F55 (\u5893\u7891\u6D88\u5931)":"Delete session";let o=document.getElementById("sp-save");o.textContent=U?"\u91CD\u547D\u540D":"Save",Ee.classList.add("open"),R.style.display="block",Vn(t),setTimeout(()=>n.focus(),50)}function G(){Ee.classList.remove("open"),R.style.display="none"}Ee.addEventListener("click",G),document.getElementById("sp-save").addEventListener("click",async()=>{let e=document.getElementById("sp-name").value.trim();if(!e||e===D){G();return}try{let t=U?{oldName:D,newName:e,agentId:H}:{oldName:D,newName:e,...H?{agentId:H}:{}};if(!(await fetch(T(U?"/api/sessions/rename-tombstone":"/api/sessions/rename"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).ok)return;G(),j(),!U&&y===D&&(H??null)===k&&ye(e,H)}catch{}}),document.getElementById("sp-rebuild").addEventListener("click",async()=>{if(confirm('\u91CD\u5EFA\u4F1A\u8BDD "'+D+'" (\u540C\u540D\u540C\u8DEF\u5F84\uFF0C\u5185\u5BB9\u4E3A\u7A7A)\uFF1F'))try{let e=await fetch(T("/api/sessions/rebuild"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:D,agentId:H})});if(!e.ok){let t=await e.json();alert(t.error||"\u91CD\u5EFA\u5931\u8D25");return}G(),j()}catch{}}),document.getElementById("sp-delete").addEventListener("click",async()=>{if(U){if(!confirm('\u5220\u9664\u5931\u6548\u8BB0\u5F55 "'+D+'"\uFF1F'))return;try{if(!(await fetch(T("/api/sessions/dismiss"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:D,agentId:H})})).ok)return;G(),j()}catch{}return}if(confirm('Delete session "'+D+'"?'))try{if(!(await fetch(T("/api/sessions/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:D,...H?{agentId:H}:{}})})).ok)return;G(),y===D&&(H??null)===k&&(v&&(v.destroy(),v=null),y=null,M.style.display="none",J.style.display="flex"),j()}catch{}}),document.getElementById("sp-cancel").addEventListener("click",G);var Xn={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 s=Xn[t.dataset.key];s&&(v.sendInput(s),v.focus())});var N=document.getElementById("mk-input"),Yt=document.getElementById("mk-send");function Ot(){if(!N||!v)return;let e=N.value;e&&(v.sendInput(e+"\r"),N.value="",N.rows=1,v.focus())}if(N&&(N.addEventListener("input",()=>{N.rows=1;let e=N.value.split(`
|
|
49
|
+
`).length;N.rows=Math.min(e,4)}),N.addEventListener("keydown",e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),Ot())})),Yt&&Yt.addEventListener("click",Ot),window.visualViewport){let e=document.querySelector(".app-layout"),t=()=>{e&&(e.style.height=window.visualViewport.height+"px"),window.scrollTo(0,0),document.documentElement.scrollTop=0,document.body.scrollTop=0};window.visualViewport.addEventListener("resize",t),window.addEventListener("orientationchange",()=>setTimeout(t,100)),document.addEventListener("touchstart",()=>{(window.scrollY>0||document.documentElement.scrollTop>0)&&window.scrollTo(0,0)},{passive:!0})}var it=document.getElementById("process-panel"),Le=document.getElementById("proc-list"),Jn=document.getElementById("proc-close"),at=document.getElementById("proc-backdrop"),Zn=document.getElementById("header-ram");function Gn(){Le.innerHTML='<div class="proc-empty">Loading\u2026</div>',fetch(T("/api/system/processes")).then(e=>e.json()).then(e=>{if(!Array.isArray(e)||!e.length){Le.innerHTML='<div class="proc-empty">No processes</div>';return}let t="";for(let s of e){let n=s.rss,a=n<1048576?(n/1024).toFixed(0)+"K":(n/1048576).toFixed(1)+"M";t+='<div class="proc-row" data-pid="'+s.pid+'"><span class="proc-mem">'+s.mem+'%</span><span class="proc-rss">'+a+'</span><span class="proc-cmd" title="'+h(s.command)+'">'+h(s.command)+'</span><button class="proc-kill" title="Kill PID '+s.pid+'">×</button></div>'}Le.innerHTML=t;for(let s of Le.querySelectorAll(".proc-row")){let n=s.querySelector(".proc-kill");n&&n.addEventListener("click",a=>{let r=a.target.closest(".proc-row");!r||!confirm("Kill PID "+r.dataset.pid+"?")||fetch(T("/api/system/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:parseInt(r.dataset.pid,10)})}).then(c=>c.json()).then(c=>{c.ok?r.style.opacity="0.3":alert("Failed: "+(c.error||"unknown"))}).catch(()=>alert("Network error"))})}}).catch(()=>{Le.innerHTML='<div class="proc-empty">Failed to load</div>'})}function Qn(){it.classList.add("open"),at.classList.add("open"),Gn()}function Ve(){it.classList.remove("open"),at.classList.remove("open")}Zn.addEventListener("click",e=>{e.stopPropagation(),it.classList.contains("open")?Ve():Qn()}),Jn.addEventListener("click",Ve),at.addEventListener("click",Ve);var es=2e3,xe=null,ot=null,se=new Map,ie=new Map,ts=5e3,Wt=new Map;function lt(e,t){return(t?"a:"+t+":":"l:")+e}function ns(e,t,s){let n=lt(e,t);if(s==="working"){let p=Wt.get(n);if(p&&Date.now()<p)return}let a=ie.get(n),r=e===y&&(t??null)===k,c=s==="idle"&&a?.state==="working";ie.set(n,{session:e,agentId:t,state:s,doneUntil:c?Date.now()+es:void 0,unread:c?!r:!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])',u=f.querySelector(o);u&&Xe(u,n,ie.get(n))}function Xe(e,t,s){let n=se.get(t);n&&(clearTimeout(n),se.delete(t)),e.classList.remove("working","just-done");let a=s.session===y&&(s.agentId??null)===k;s.state==="working"?e.classList.add("working"):a&&s.doneUntil&&Date.now()<s.doneUntil?(e.classList.add("just-done"),se.set(t,setTimeout(()=>{e.classList.remove("just-done"),se.delete(t)},Math.max(0,s.doneUntil-Date.now())))):!a&&s.unread&&e.classList.add("just-done")}function rt(){for(let[e,t]of ie){let s=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])',n=f.querySelector(s);n&&Xe(n,e,t)}}function ss(e,t){let s=lt(e,t),n=ie.get(s);if(!n)return;let a=se.get(s);a&&(clearTimeout(a),se.delete(s)),n.doneUntil=void 0,n.unread=!1;let r=t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',c=f.querySelector(r);c&&Xe(c,s,n)}function qt(){if(xe||ot)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 s=new WebSocket(t);xe=s,s.onmessage=n=>{try{let a=JSON.parse(String(n.data));a&&a.type==="session.activity"&&typeof a.session=="string"&&ns(a.session,a.agentId||void 0,a.state==="working"?"working":"idle")}catch{}},s.onclose=()=>{xe===s&&(xe=null,ot=setTimeout(()=>{ot=null,qt()},5e3))},s.onerror=()=>{try{s.close()}catch{}}}catch{xe=null}}window.__openSession=ye,window.__refreshSidebar=j,j(),Ne(),rt(),qt(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&rt()}),setInterval(()=>{document.visibilityState==="visible"&&j()},1e4);
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
const
|
|
2
|
-
`)}selectRows(o
|
|
3
|
-
`)}getSelection(){return this.terminal.getSelection()}clearSelection(){this.terminal.clearSelection()}hasSelectionSupport(){return!0}}function _e(
|
|
4
|
-
\x1B[31m`+
|
|
5
|
-
`).then(()=>{G();try{l?.close()}catch{}});return}if(t.type==="auth.ok"){t.token&&localStorage.setItem("tmux-web-token",t.token),z=1e3,D(),S({type:"resize",cols:n.cols,rows:n.rows}),y();return}if(t.type==="auth.failed"){if(t.permanentLock||t.retryAfterMs&&t.retryAfterMs>6e4){localStorage.removeItem("tmux-web-token"),location.href="/login?error="+encodeURIComponent(t.message);return}return}if(t.type==="snapshot"&&typeof t.data=="string"){const
|
|
1
|
+
const Xe=/\x1b\](?:10|11|110|111|104)(?:;[^\x07\x1b]*)?\x1b?(?:\\|\x07)/g;function oe(s){return s.replace(/\x1b\[\?1049[hl]/g,"")}function H(s){return s.replace(Xe,"")}let _;function He(){return _||(document.querySelector("link[data-tmux-web-xterm-css]")?_=Promise.resolve():(_=new Promise(i=>{const o=document.createElement("link");o.rel="stylesheet",o.href="/assets/xterm.css",o.setAttribute("data-tmux-web-xterm-css",""),o.addEventListener("load",()=>i(),{once:!0}),o.addEventListener("error",()=>i(),{once:!0}),document.head.appendChild(o)}),_))}class re{terminal;fitAddon;container;webglActive=!1;repaintTimer=0;webglAddon=null;constructor(i,o,n){this.container=i,this.terminal=o,this.fitAddon=n,this.terminal.loadAddon(this.fitAddon),this.terminal.open(i),this.enableWebglRenderer(),document.addEventListener("visibilitychange",()=>{document.hidden||this.refreshPaintedRows()})}enableWebglRenderer(){if(je()==="webgl"){try{if(!document.createElement("canvas").getContext("webgl2",{failIfMajorPerformanceCaveat:!0}))return}catch{return}import("@xterm/addon-webgl").then(({WebglAddon:i})=>{const o=new i;o.onContextLoss(()=>{this.webglActive=!1,this.webglAddon=null;try{o.dispose()}catch{}this.fit()});try{this.terminal.loadAddon(o)}catch{return}this.webglAddon=o,this.webglActive=!0,this.fit()}).catch(()=>{})}}refreshPaintedRows(){if(this.webglActive){try{this.webglAddon?.clearTextureAtlas?.()}catch{}try{this.terminal.refresh(0,Math.max(0,this.terminal.rows-1))}catch{}}}static async create(i,o,n){const[{Terminal:l},{FitAddon:d}]=await Promise.all([import("@xterm/xterm"),import("@xterm/addon-fit"),He()]),h="'JetBrains Mono', 'SF Mono', 'Menlo', monospace",a=new l({fontSize:_e(14,h),fontFamily:h,cursorBlink:!0,cursorStyle:"bar",scrollback:o,convertEol:!1,smoothScrollDuration:120,theme:n});return new re(i,a,new d)}get cols(){return this.terminal.cols}get rows(){return this.terminal.rows}write(i){return new Promise(o=>this.terminal.write(i,o))}reset(){this.terminal.reset()}scrollToBottom(){this.terminal.scrollToBottom()}scrollToLine(i,o=!1){this.terminal.scrollToLine(Math.max(0,i),o),this.scheduleRepaintCheck()}scrollLines(i){this.terminal.scrollLines(i),this.scheduleRepaintCheck()}scheduleRepaintCheck(){this.webglActive&&(this.repaintTimer&&clearTimeout(this.repaintTimer),this.repaintTimer=setTimeout(()=>{this.repaintTimer=0,this.refreshPaintedRows()},150))}isNearScrollbackTop(){return this.terminal.buffer.active.viewportY<=1}viewportY(){return this.terminal.buffer.active.viewportY}baseY(){return this.terminal.buffer.active.baseY}cellHeight(){const o=this.terminal.element?.querySelector(".xterm-screen")?.getBoundingClientRect().height??0,n=this.terminal.rows;return o>0&&n>0?o/n:16}fit(){const i=qe(this.container);if(i.width<=0||i.height<=0)return!1;const o=this.terminal.cols,n=this.terminal.rows;return this.fitAddon.fit(),this.webglActive&&(o!==this.terminal.cols||n!==this.terminal.rows)&&this.refreshPaintedRows(),!0}focus(){this.terminal.focus()}pasteText(i){this.terminal.paste(i)}input(i){this.terminal.input(i,!1)}onData(i){this.terminal.onData(i),this.terminal.onBinary(i)}onResize(i){this.terminal.onResize(i)}onScroll(i){this.terminal.onScroll(i)}attachCustomKeyEventHandler(i){this.terminal.attachCustomKeyEventHandler(i)}isFocused(){const i=document.activeElement;return i?i===this.container||i===this.terminal.textarea||this.container.contains(i)||!!i.closest?.(".xterm"):!1}getScreenText(){return this.getRowsText(0,this.terminal.rows-1)}getRowsText(i,o){const n=this.terminal.buffer.active,[l,d]=i<=o?[i,o]:[o,i],h=n.viewportY,a=[];for(let f=l;f<=d;f++){const m=n.getLine(h+f);a.push(m?m.translateToString(!0):"")}return a.join(`
|
|
2
|
+
`)}selectRows(i,o){const n=this.terminal.buffer.active,[l,d]=i<=o?[i,o]:[o,i];this.terminal.selectLines(n.viewportY+l,n.viewportY+d)}selectCells(i,o,n,l){const d=this.terminal.buffer.active,h=Math.min(o,l),a=Math.max(o,l);if(h===a){const f=Math.min(i,n),m=Math.max(i,n);this.terminal.select(f,d.viewportY+h,m-f+1)}else this.terminal.selectLines(d.viewportY+h,d.viewportY+a)}getCellsText(i,o,n,l){const d=this.terminal.buffer.active,h=Math.min(o,l),a=Math.max(o,l),f=o<l?i:o>l?n:Math.min(i,n),m=o<l?n:o>l?i:Math.max(i,n),P=d.viewportY,I=[];for(let C=h;C<=a;C++){const j=d.getLine(P+C);if(!j){I.push("");continue}const g=C===h?f:0,L=C===a?m:this.terminal.cols-1;let F="";for(let q=g;q<=L;q++){const M=j.getCell(q);M&&(F+=M.getChars())}I.push(F.replace(/\s+$/,""))}return I.join(`
|
|
3
|
+
`)}getSelection(){return this.terminal.getSelection()}clearSelection(){this.terminal.clearSelection()}hasSelectionSupport(){return!0}}function _e(s,i){try{const o=document.createElement("canvas").getContext("2d");if(!o)return s;const n=100;o.font=`${n}px ${i}`;const l=o.measureText("M").width/n;if(!Number.isFinite(l)||l<=0)return s;const d=window.devicePixelRatio||1;let h=s,a=Number.POSITIVE_INFINITY;for(let f=4;f<=40;f++){const m=f/(l*d);if(m<s-1.5||m>s+1.5)continue;const P=Math.abs(m-s);P<a&&(a=P,h=m)}return Math.round(h*100)/100}catch{return s}}function je(){try{const s=new URLSearchParams(window.location.search).get("renderer");return s==="dom"||s==="webgl"?s:null}catch{return null}}function qe(s){const i=s.getBoundingClientRect(),o=window.visualViewport;return o?{width:Math.min(i.width,o.width),height:Math.max(0,Math.min(i.height,o.height-Math.max(0,i.top)))}:i}function We(s,i,o){return s.innerHTML="",s.classList.add("terminal-pending"),(async()=>{const n=await re.create(s,o.scrollback,o.theme);let l,d=0,h,a=null,f=0,m=0;const P=.2,I=10,C=.95,j=.04;let g=null,L=null;function F(e){g||(g=document.createElement("div"),g.style.cssText=["position:absolute","left:0","width:40%","padding:10px 0","text-align:center","font:600 14px/1.4 system-ui, -apple-system, sans-serif","color:rgba(255,255,255,0.95)","background:rgba(20,30,50,0.55)","border:1px solid rgba(255,255,255,0.25)","border-radius:10px","pointer-events:none","opacity:0","transition:opacity 0.15s ease","z-index:6"].join(";"),s.appendChild(g)),g.textContent=e?"\u2191 \u4E0A\u7FFB\u4E00\u9875 (PgUp)":"\u2193 \u4E0B\u7FFB\u4E00\u9875 (PgDn)",g.style.top=e?"10%":"auto",g.style.bottom=e?"auto":"10%",g.style.opacity="1",L&&clearTimeout(L),L=setTimeout(()=>{g&&(g.style.opacity="0")},900)}function q(){L&&clearTimeout(L),g&&(g.style.opacity="0")}function M(){f&&(cancelAnimationFrame(f),f=0),m=0}function ge(e){if(M(),Math.abs(e)<P)return;m=Math.max(-I,Math.min(I,e));const t=()=>{if(E){f=0;return}const r=n.cellHeight();let u=r>0?Math.round(m*16/r):m>0?1:-1;u===0&&(u=m>0?1:-1);const v=n.viewportY()-u,x=n.baseY(),X=Math.max(0,Math.min(v,x));if(n.scrollToLine(X,!0),m*=C,X!==v){f=0;return}if(Math.abs(m)<j){f=0;return}f=requestAnimationFrame(t)};f=requestAnimationFrame(t)}let V=0,b="connecting",W=0,R=!1,J=[],A="",E=!1,z=1e3;const ye=location.protocol==="https:"?"wss:":"ws:",se=o.wsBase||"/ws",ve=ye+"//"+location.host+se+"/"+encodeURIComponent(i),be=(se.replace(/^\/ws/,"")||"")+"/api/session/"+encodeURIComponent(i)+"/upload",Te=/^((?!chrome|android|crios|fxios|edgios).)*safari/i.test(navigator.userAgent);function xe(){return J.join("")+A}async function Ee(e,t=0){const r=e?n.viewportY():0,u=H(xe());if(n.reset(),!u){e||n.scrollToBottom();return}await n.write(u),e?n.scrollToLine(t+r):n.scrollToBottom()}function S(e){l?.readyState===WebSocket.OPEN&&l.send(JSON.stringify(e))}function Ce(e){let t;try{t=JSON.parse(e)}catch{b==="live"&&(A+=e,n.write(H(e)));return}if(t.type==="auth.required"){const r=localStorage.getItem("tmux-web-token");r?S({type:"auth.token",token:r}):location.href="/login?returnTo="+encodeURIComponent(location.pathname+location.search);return}if(t.type==="attach_failed"&&typeof t.message=="string"){$=!0,b="dead",n.reset(),n.write(`\r
|
|
4
|
+
\x1B[31m`+H(t.message)+`\x1B[0m\r
|
|
5
|
+
`).then(()=>{G();try{l?.close()}catch{}});return}if(t.type==="auth.ok"){t.token&&localStorage.setItem("tmux-web-token",t.token),z=1e3,D(),S({type:"resize",cols:n.cols,rows:n.rows}),y();return}if(t.type==="auth.failed"){if(t.permanentLock||t.retryAfterMs&&t.retryAfterMs>6e4){localStorage.removeItem("tmux-web-token"),location.href="/login?error="+encodeURIComponent(t.message);return}return}if(t.type==="snapshot"&&typeof t.data=="string"){const r=oe(H(t.data));J=[r],A="",W=typeof t.lines=="number"?t.lines:o.terminal.initialLines,b="live",n.reset(),D(),S({type:"resize",cols:n.cols,rows:n.rows}),n.write(r).then(()=>n.scrollToBottom());return}if(t.type==="window_changed"&&typeof t.activeIndex=="number"){const r=new URL(location.href);r.searchParams.get("window")!==String(t.activeIndex)&&(r.searchParams.set("window",String(t.activeIndex)),history.replaceState(history.state,"",r)),window.dispatchEvent(new CustomEvent("tmux:windows",{detail:t.windows}));return}if(t.type==="history"&&typeof t.data=="string"){t.lines>0&&t.data?(J.unshift(oe(t.data)),W+=t.lines,Ee(!0,t.lines).finally(()=>{R=!1})):R=!1;return}if(t.type==="data"&&typeof t.data=="string"){const r=oe(H(t.data));if(b==="connecting"){b="live",A=r,n.write(r);return}b==="live"&&(A+=r,n.write(r))}}let $=!1;function ae(){if($)return;let e=ve;const t=localStorage.getItem("tmux-web-token");t&&(e+=(e.includes("?")?"&":"?")+"token="+encodeURIComponent(t)),e+=(e.includes("?")?"&":"?")+"cols="+n.cols+"&rows="+n.rows,l=new WebSocket(e),l.onopen=()=>{b="connecting",W=0,R=!1,J=[],A="",n.reset(),z=1e3},l.onmessage=r=>{typeof r.data=="string"&&Ce(r.data)},l.onclose=()=>{E||(b="connecting",!$&&setTimeout(()=>{z=Math.min(z*2,1e4),!E&&!$&&ae()},z))},l.onerror=()=>l?.close()}function k(e){S({type:"input",data:e})}function D(){return n.fit()}function G(){s.classList.remove("terminal-pending")}function y(){d&&cancelAnimationFrame(d),h&&clearTimeout(h),D(),d=requestAnimationFrame(()=>{d=0,D()&&G()}),h=setTimeout(()=>{D()&&G()},120)}function Le(){y(),setTimeout(y,50),setTimeout(y,150),setTimeout(y,300)}function le(e){return typeof e=="string"&&e.startsWith("image/")}function ce(e){return e?.files?.length?e.files[0]??null:null}function Me(e){if(!e?.items)return null;for(let t=0;t<e.items.length;t++){const r=e.items[t];if(r?.kind==="file"&&le(r.type))return r.getAsFile()}return null}async function Se(e){const t=new FormData,r=e instanceof File&&e.name?e.name:"upload";t.append("file",e,r);const u=localStorage.getItem("tmux-web-token"),c={};u&&(c.Authorization="Bearer "+u);const v=await fetch(be,{method:"POST",body:t,headers:c});if(!v.ok){let X="upload failed";try{const we=await v.json();we.error&&(X=we.error)}catch{}throw new Error(X)}const x=await v.json();if(!x.path)throw new Error("no path in response");return x.path}async function te(e){try{const t=await Se(e);k(t)}catch{}}n.onData(e=>k(e)),n.onResize(({cols:e,rows:t})=>S({type:"resize",cols:e,rows:t})),n.onScroll(()=>{b!=="live"||R||!n.isNearScrollbackTop()||(R=!0,S({type:"load_history",before:W}))});let B=!1,K=!1,p=null,w=null;const U=document.createElement("div");U.className="terminal-copy-banner",U.innerHTML='<strong>Copy mode</strong><span class="hint">drag to copy \xB7 Esc exits</span>',U.hidden=!0,s.appendChild(U);const T=document.createElement("div");T.className="terminal-copy-banner terminal-copy-toast",T.textContent="Copied",T.hidden=!0,s.appendChild(T);function ue(e,t){const r=s.querySelector(".xterm-screen, canvas"),c=(r&&r.getBoundingClientRect().width>0?r:s).getBoundingClientRect(),v=c.height>0&&n.rows>0?c.height/n.rows:18,x=c.width>0&&n.cols>0?c.width/n.cols:9;return{row:Math.max(0,Math.min(n.rows-1,Math.floor((t-c.top)/v))),col:Math.max(0,Math.min(n.cols-1,Math.floor((e-c.left)/x)))}}async function Q(e){if(!e)return;try{if(navigator.clipboard?.writeText){await navigator.clipboard.writeText(e);return}}catch{}const t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.opacity="0",t.style.pointerEvents="none",document.body.appendChild(t),t.focus(),t.select();try{document.execCommand("copy")}catch{}t.remove()}let N;function Z(){T.hidden=!1,N&&clearTimeout(N),N=setTimeout(()=>{T.hidden=!0},1e3)}function Y(e){B=e,U.hidden=!e,s.classList.toggle("terminal-copy-mode-active",e),e&&n.focus()}function fe(){Y(!B)}function De(e){E||e.button!==0||K||(B||e.shiftKey)&&(e.preventDefault(),e.stopPropagation(),K=!0,p=ue(e.clientX,e.clientY),w=p,n.selectCells(p.col,p.row,w.col,w.row),document.addEventListener("mousemove",ne,!0),document.addEventListener("mouseup",ie,!0))}function ne(e){E||!K||!p||(e.preventDefault(),e.stopPropagation(),w=ue(e.clientX,e.clientY),n.selectCells(p.col,p.row,w.col,w.row))}function ie(e){if(E||!K||!p||!w)return;e.preventDefault(),e.stopPropagation(),document.removeEventListener("mousemove",ne,!0),document.removeEventListener("mouseup",ie,!0),K=!1;const t=n.getCellsText(p.col,p.row,w.col,w.row);p=null,w=null,n.clearSelection(),Y(!1),t&&(T.textContent="\u5DF2\u590D\u5236",Q(t).then(Z)),n.focus()}s.addEventListener("mousedown",De,!0),document.addEventListener("keydown",Pe,!0);function Pe(e){if(!(E||!n.isFocused()||e.defaultPrevented||e.isComposing)){if(B){if(e.key==="Escape"){e.preventDefault(),e.stopPropagation(),p=null,w=null,n.clearSelection(),Y(!1);return}if(e.key==="Enter"||(e.ctrlKey||e.metaKey)&&e.code==="KeyC"){e.preventDefault(),e.stopPropagation(),Q(n.getScreenText()).then(Z),Y(!1);return}}if(e.altKey&&e.code==="KeyC"&&!e.ctrlKey&&!e.metaKey){if(e.preventDefault(),e.stopPropagation(),p&&w){const t=n.getCellsText(p.col,p.row,w.col,w.row);p=null,w=null,n.clearSelection(),Y(!1),t&&(T.textContent="Copied",Q(t).then(Z))}else{const t=n.getSelection();t?(n.clearSelection(),T.textContent="Copied",Q(t).then(Z)):fe()}return}if((e.ctrlKey||e.metaKey)&&e.code==="KeyV"){e.preventDefault(),e.stopPropagation(),(async()=>{try{if(navigator.clipboard?.read){const t=await navigator.clipboard.read();for(const r of t)for(const u of r.types)if(le(u)){const c=await r.getType(u);await te(c);return}}}catch{}try{const t=await navigator.clipboard?.readText();t&&n.pasteText(de(t))}catch{}})();return}}}let ee=0;function de(e){return e.split(`\r
|
|
6
6
|
`).join(`
|
|
7
7
|
`).split(`
|
|
8
|
-
`).join("\r")}async function
|
|
8
|
+
`).join("\r")}async function Ie(e){const t=Me(e.clipboardData);if(t){e.preventDefault(),e.stopPropagation();const c=Date.now();if(c-ee<50)return;ee=c,await te(t);return}const r=e.clipboardData?.getData("text/plain");if(!r)return;e.preventDefault(),e.stopPropagation();const u=Date.now();u-ee<50||(ee=u,n.pasteText(de(r)))}let O=0;function Ae(e){e.preventDefault(),O++,ce(e.dataTransfer)&&s.classList.add("terminal-drag-over")}function ke(e){e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect="copy")}function Ye(e){e.preventDefault(),O--,O<=0&&(O=0,s.classList.remove("terminal-drag-over"))}async function Fe(e){e.preventDefault(),O=0,s.classList.remove("terminal-drag-over");const t=ce(e.dataTransfer);t&&await te(t)}function me(e){!Te||e.key!=="Escape"||B||e.defaultPrevented||e.repeat||e.metaKey||e.ctrlKey||e.altKey||n.isFocused()&&(e.preventDefault(),e.stopPropagation(),k("\x1B"))}s.addEventListener("paste",Ie),s.addEventListener("dragenter",Ae),s.addEventListener("dragover",ke),s.addEventListener("dragleave",Ye),s.addEventListener("drop",Fe),document.addEventListener("keydown",me,!0);function Re(e){if(e.touches.length!==1){a=null;return}const t=e.touches[0];if(!t)return;M();const r=s.getBoundingClientRect(),u=t.clientX-r.left<r.width*.4?"tui":"history",c=t.clientY-r.top<r.height*.5;a={startX:t.clientX,startY:t.clientY,lastX:t.clientX,lastY:t.clientY,lastT:performance.now(),velocity:0,scrolling:!1,zone:u,tuiUp:c,sent:!1},e.stopPropagation()}function ze(e){if(!a||e.touches.length!==1)return;const t=e.touches[0];if(!t)return;const r=t.clientY-a.startY,u=t.clientX-a.startX;if(!a.scrolling){if(Math.abs(r)<8||Math.abs(r)<Math.abs(u))return;a.scrolling=!0,V=Date.now()+500}e.preventDefault(),e.stopPropagation();const c=performance.now(),v=t.clientY-a.lastY;if(a.zone==="tui"){a.sent||(a.sent=!0,k(a.tuiUp?"\x1B[5~":"\x1B[6~"),F(a.tuiUp)),a.lastX=t.clientX,a.lastY=t.clientY,a.lastT=c;return}const x=c-a.lastT;x>0&&(a.velocity=v/x),Ne(-v),a.lastX=t.clientX,a.lastY=t.clientY,a.lastT=c}function Be(e){if(!a)return;const t=a.scrolling,r=a.zone,u=a.tuiUp,c=a.velocity;if(a=null,e.stopPropagation(),r==="tui"){t||(k(u?"\x1B[5~":"\x1B[6~"),F(u),V=Date.now()+500,e.preventDefault());return}if(!t){n.focus();return}V=Date.now()+500,e.preventDefault(),c&&ge(c)}function Ke(e){a=null,M(),e.stopPropagation()}function Ue(e){e.pointerType==="touch"&&Date.now()<V&&(e.preventDefault(),e.stopPropagation())}function Ne(e){const t=n.cellHeight();let r=t>0?Math.round(e/t):e>0?1:-1;r===0&&(r=e>0?1:-1),n.scrollLines(r)}s.addEventListener("touchstart",Re,{passive:!0,capture:!0}),s.addEventListener("touchmove",ze,{passive:!1,capture:!0}),s.addEventListener("touchend",Be,{passive:!1,capture:!0}),s.addEventListener("touchcancel",Ke,{passive:!0,capture:!0}),s.addEventListener("pointerup",Ue,!0);function he(){y()}window.addEventListener("resize",he),window.visualViewport?.addEventListener("resize",y),window.visualViewport?.addEventListener("scroll",y);const pe=new ResizeObserver(()=>y());pe.observe(s),document.fonts?.ready.then(()=>{y(),setTimeout(y,50),setTimeout(y,200)}),s.addEventListener("focusin",Le,!0);async function Oe(){if(document.fonts?.ready)try{await Promise.race([document.fonts.ready,new Promise(e=>setTimeout(e,1e3))])}catch{}}return requestAnimationFrame(()=>{D()&&G(),(async()=>(await Oe(),D()&&S({type:"resize",cols:n.cols,rows:n.rows}),ae(),y()))()}),{destroy(){if(E=!0,M(),Y(!1),N&&clearTimeout(N),document.removeEventListener("mousemove",ne,!0),document.removeEventListener("mouseup",ie,!0),l){try{l.close(1e3,"session switch")}catch{}l=void 0}s.innerHTML="",s.classList.remove("terminal-pending"),window.removeEventListener("resize",he),pe.disconnect(),document.removeEventListener("keydown",me,!0)},focus(){n.focus()},sendInput(e){k(e)},toggleCopyMode(){fe()}}})()}export{We as initTerminal,oe as stripAltScreenSequences};
|