tmux-weblink 2.2.35 → 2.2.37

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 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
1
+ var kn=/\x1b\](?:10|11|110|111|104)(?:;[^\x07\x1b]*)?\x1b?(?:\\|\x07)/g;function st(e){return e.replace(/\x1b\[\?1049[hl]/g,"")}function me(e){return e.replace(kn,"")}var He;function Sn(){return He||(document.querySelector("link[data-tmux-web-xterm-css]")?He=Promise.resolve():(He=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)}),He))}var Tn=class Gt{terminal;fitAddon;container;webglActive=!1;repaintTimer=0;webglAddon=null;constructor(t,n,s){this.container=t,this.terminal=n,this.fitAddon=s,this.terminal.loadAddon(this.fitAddon),this.terminal.open(t),this.enableWebglRenderer(),document.addEventListener("visibilitychange",()=>{document.hidden||this.refreshPaintedRows()})}enableWebglRenderer(){if(Bn()==="webgl"){try{if(!document.createElement("canvas").getContext("webgl2",{failIfMajorPerformanceCaveat:!0}))return}catch{return}import("./addon-webgl-B45EJ6AW.js").then(({WebglAddon:t})=>{let n=new t;n.onContextLoss(()=>{this.webglActive=!1,this.webglAddon=null;try{n.dispose()}catch{}this.fit()});try{this.terminal.loadAddon(n)}catch{return}this.webglAddon=n,this.webglActive=!0,this.fit()}).catch(()=>{})}}refreshPaintedRows(){if(this.webglActive){try{this.webglAddon?.clearTextureAtlas?.()}catch{}try{this.terminal.refresh(0,Math.max(0,this.terminal.rows-1))}catch{}}}static async create(t,n,s){let[{Terminal:a},{FitAddon:r}]=await Promise.all([import("./xterm-BXEES47M.js"),import("./addon-fit-D5N335P2.js"),Sn()]),c="'JetBrains Mono', 'SF Mono', 'Menlo', monospace",o=new a({fontSize:In(14,c),fontFamily:c,cursorBlink:!0,cursorStyle:"bar",scrollback:n,convertEol:!1,smoothScrollDuration:120,theme:s});return new Gt(t,o,new r)}get cols(){return this.terminal.cols}get rows(){return this.terminal.rows}write(t){return new Promise(n=>this.terminal.write(t,n))}reset(){this.terminal.reset()}scrollToBottom(){this.terminal.scrollToBottom()}scrollToLine(t,n=!1){this.terminal.scrollToLine(Math.max(0,t),n),this.scheduleRepaintCheck()}scrollLines(t){this.terminal.scrollLines(t),this.scheduleRepaintCheck()}scheduleRepaintCheck(){this.webglActive&&(this.repaintTimer&&clearTimeout(this.repaintTimer),this.repaintTimer=setTimeout(()=>{this.repaintTimer=0,this.refreshPaintedRows()},150))}isNearScrollbackTop(){return this.terminal.buffer.active.viewportY<=1}viewportY(){return this.terminal.buffer.active.viewportY}baseY(){return this.terminal.buffer.active.baseY}cellHeight(){let t=this.terminal.element?.querySelector(".xterm-screen")?.getBoundingClientRect().height??0,n=this.terminal.rows;return t>0&&n>0?t/n:16}fit(){let t=Mn(this.container);if(t.width<=0||t.height<=0)return!1;let n=this.terminal.cols,s=this.terminal.rows,a=this.paintedCellWidth();a<=0&&(this.fitAddon.fit(),a=this.paintedCellWidth());let r=this.fitAddon.proposeDimensions?.();if(!r)return this.fitAddon.fit(),!0;let c=this.overlayScrollbarWidth(),o=c>0?c+2:0,u=a>0?Math.max(10,Math.min(r.cols,Math.floor((t.width-o)/a))):r.cols,p=r.rows;return(u!==this.terminal.cols||p!==this.terminal.rows)&&this.terminal.resize(u,p),this.webglActive&&(n!==this.terminal.cols||s!==this.terminal.rows)&&this.refreshPaintedRows(),!0}paintedCellWidth(){let t=this.terminal.element?.querySelector(".xterm-screen")?.getBoundingClientRect().width??0,n=this.terminal.cols;return t>0&&n>0?t/n:0}overlayScrollbarWidth(){let t=this.terminal.element?.querySelector(".vertical.scrollbar");if(!t)return 0;let n=t.getBoundingClientRect();return!(n.width>0)||!(n.height>0)?0:Math.round(n.width)}focus(){this.terminal.focus()}pasteText(t){this.terminal.paste(t)}input(t){this.terminal.input(t,!1)}onData(t){this.terminal.onData(t),this.terminal.onBinary(t)}onResize(t){this.terminal.onResize(t)}onScroll(t){this.terminal.onScroll(t)}attachCustomKeyEventHandler(t){this.terminal.attachCustomKeyEventHandler(t)}isFocused(){let t=document.activeElement;return t?t===this.container||t===this.terminal.textarea||this.container.contains(t)||!!t.closest?.(".xterm"):!1}getScreenText(){return this.getRowsText(0,this.terminal.rows-1)}getRowsText(t,n){let s=this.terminal.buffer.active,[a,r]=t<=n?[t,n]:[n,t],c=s.viewportY,o=[];for(let u=a;u<=r;u++){let p=s.getLine(c+u);o.push(p?p.translateToString(!0):"")}return o.join(`
2
+ `)}selectRows(t,n){let s=this.terminal.buffer.active,[a,r]=t<=n?[t,n]:[n,t];this.terminal.selectLines(s.viewportY+a,s.viewportY+r)}selectCells(t,n,s,a){let r=this.terminal.buffer.active,c=Math.min(n,a),o=Math.max(n,a);if(c===o){let u=Math.min(t,s),p=Math.max(t,s);this.terminal.select(u,r.viewportY+c,p-u+1)}else this.terminal.selectLines(r.viewportY+c,r.viewportY+o)}getCellsText(t,n,s,a){let r=this.terminal.buffer.active,c=Math.min(n,a),o=Math.max(n,a),u=n<a?t:n>a?s:Math.min(t,s),p=n<a?s:n>a?t:Math.max(t,s),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,O=A===o?p:this.terminal.cols-1,ae="";for(let ke=b;ke<=O;ke++){let K=B.getCell(ke);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 In(e,t){try{let n=document.createElement("canvas").getContext("2d");if(!n)return e;let s=100;n.font=`${s}px ${t}`;let a=n.measureText("M").width/s;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 Bn(){try{let e=new URLSearchParams(window.location.search).get("renderer");return e==="dom"||e==="webgl"?e:null}catch{return null}}function Mn(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 Dn(e,t,n){return e.innerHTML="",e.classList.add("terminal-pending"),(async()=>{let s=await Tn.create(e,n.scrollback,n.theme),a,r=0,c,o=null,u=0,p=0,E=.2,x=10,A=.95,B=.04,b=null,O=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",O&&clearTimeout(O),O=setTimeout(()=>{b&&(b.style.opacity="0")},900)}function ke(){O&&clearTimeout(O),b&&(b.style.opacity="0")}function K(){u&&(cancelAnimationFrame(u),u=0),p=0}function Qt(i){if(K(),Math.abs(i)<E)return;p=Math.max(-x,Math.min(x,i));let l=()=>{if(W){u=0;return}let d=s.cellHeight(),m=d>0?Math.round(p*16/d):p>0?1:-1;m===0&&(m=p>0?1:-1);let v=s.viewportY()-m,P=s.baseY(),_=Math.max(0,Math.min(v,P));if(s.scrollToLine(_,!0),p*=A,_!==v){u=0;return}if(Math.abs(p)<B){u=0;return}u=requestAnimationFrame(l)};u=requestAnimationFrame(l)}let Se=0,$="connecting",Te=0,oe=!1,Ie=[],Q="",W=!1,le=1e3,en=location.protocol==="https:"?"wss:":"ws:",mt=n.wsBase||"/ws",tn=en+"//"+location.host+mt+"/"+encodeURIComponent(t),nn=(mt.replace(/^\/ws/,"")||"")+"/api/session/"+encodeURIComponent(t)+"/upload",sn=/^((?!chrome|android|crios|fxios|edgios).)*safari/i.test(navigator.userAgent);function an(){return Ie.join("")+Q}async function on(i,l=0){let d=i?s.viewportY():0,m=me(an());if(s.reset(),!m){i||s.scrollToBottom();return}await s.write(m),i?s.scrollToLine(l+d):s.scrollToBottom()}function V(i){a?.readyState===WebSocket.OPEN&&a.send(JSON.stringify(i))}function ln(i){let l;try{l=JSON.parse(i)}catch{$==="live"&&(Q+=i,s.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"){Be=!0,$="dead",s.reset(),s.write(`\r
4
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
5
+ `).then(()=>{Me();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:s.cols,rows:s.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=st(me(l.data));Ie=[d],Q="",Te=typeof l.lines=="number"?l.lines:n.terminal.initialLines,$="live",s.reset(),X(),V({type:"resize",cols:s.cols,rows:s.rows}),s.write(d).then(()=>s.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?(Ie.unshift(st(l.data)),Te+=l.lines,on(!0,l.lines).finally(()=>{oe=!1})):oe=!1;return}if(l.type==="data"&&typeof l.data=="string"){let d=st(me(l.data));if($==="connecting"){$="live",Q=d,s.write(d);return}$==="live"&&(Q+=d,s.write(d))}}let Be=!1;function ft(){if(Be)return;let i=tn,l=localStorage.getItem("tmux-web-token");l&&(i+=(i.includes("?")?"&":"?")+"token="+encodeURIComponent(l)),i+=(i.includes("?")?"&":"?")+"cols="+s.cols+"&rows="+s.rows,a=new WebSocket(i),a.onopen=()=>{$="connecting",Te=0,oe=!1,Ie=[],Q="",s.reset(),le=1e3},a.onmessage=d=>{typeof d.data=="string"&&ln(d.data)},a.onclose=()=>{W||($="connecting",!Be&&setTimeout(()=>{le=Math.min(le*2,1e4),!W&&!Be&&ft()},le))},a.onerror=()=>a?.close()}function ee(i){V({type:"input",data:i})}function X(){return s.fit()}function Me(){e.classList.remove("terminal-pending")}function I(){r&&cancelAnimationFrame(r),c&&clearTimeout(c),X(),r=requestAnimationFrame(()=>{r=0,X()&&Me()}),c=setTimeout(()=>{X()&&Me()},120)}function rn(){I(),setTimeout(I,50),setTimeout(I,150),setTimeout(I,300)}function ht(i){return typeof i=="string"&&i.startsWith("image/")}function gt(i){return i?.files?.length?i.files[0]??null:null}function cn(i){if(!i?.items)return null;for(let l=0;l<i.items.length;l++){let d=i.items[l];if(d?.kind==="file"&&ht(d.type))return d.getAsFile()}return null}async function dn(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"),v={};m&&(v.Authorization="Bearer "+m);let P=await fetch(nn,{method:"POST",body:l,headers:v});if(!P.ok){let xt="upload failed";try{let Ct=await P.json();Ct.error&&(xt=Ct.error)}catch{}throw new Error(xt)}let _=await P.json();if(!_.path)throw new Error("no path in response");return _.path}async function et(i){try{let l=await dn(i);ee(l)}catch{}}s.onData(i=>ee(i)),s.onResize(({cols:i,rows:l})=>V({type:"resize",cols:i,rows:l})),s.onScroll(()=>{$!=="live"||oe||!s.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 vt(i,l){let d=e.querySelector(".xterm-screen, canvas"),m=(d&&d.getBoundingClientRect().width>0?d:e).getBoundingClientRect(),v=m.height>0&&s.rows>0?m.height/s.rows:18,P=m.width>0&&s.cols>0?m.width/s.cols:9;return{row:Math.max(0,Math.min(s.rows-1,Math.floor((l-m.top)/v))),col:Math.max(0,Math.min(s.cols-1,Math.floor((i-m.left)/P)))}}async function De(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 Ae(){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&&s.focus()}function yt(){te(!re)}function un(i){W||i.button!==0||ce||(re||i.shiftKey)&&(i.preventDefault(),i.stopPropagation(),ce=!0,L=vt(i.clientX,i.clientY),C=L,s.selectCells(L.col,L.row,C.col,C.row),document.addEventListener("mousemove",tt,!0),document.addEventListener("mouseup",nt,!0))}function tt(i){W||!ce||!L||(i.preventDefault(),i.stopPropagation(),C=vt(i.clientX,i.clientY),s.selectCells(L.col,L.row,C.col,C.row))}function nt(i){if(W||!ce||!L||!C)return;i.preventDefault(),i.stopPropagation(),document.removeEventListener("mousemove",tt,!0),document.removeEventListener("mouseup",nt,!0),ce=!1;let l=s.getCellsText(L.col,L.row,C.col,C.row);L=null,C=null,s.clearSelection(),te(!1),l&&(z.textContent="\u5DF2\u590D\u5236",De(l).then(Ae)),s.focus()}e.addEventListener("mousedown",un,!0),document.addEventListener("keydown",pn,!0);function pn(i){if(!(W||!s.isFocused()||i.defaultPrevented||i.isComposing)){if(re){if(i.key==="Escape"){i.preventDefault(),i.stopPropagation(),L=null,C=null,s.clearSelection(),te(!1);return}if(i.key==="Enter"||(i.ctrlKey||i.metaKey)&&i.code==="KeyC"){i.preventDefault(),i.stopPropagation(),De(s.getScreenText()).then(Ae),te(!1);return}}if(i.altKey&&i.code==="KeyC"&&!i.ctrlKey&&!i.metaKey){if(i.preventDefault(),i.stopPropagation(),L&&C){let l=s.getCellsText(L.col,L.row,C.col,C.row);L=null,C=null,s.clearSelection(),te(!1),l&&(z.textContent="Copied",De(l).then(Ae))}else{let l=s.getSelection();l?(s.clearSelection(),z.textContent="Copied",De(l).then(Ae)):yt()}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(ht(m)){let v=await d.getType(m);await et(v);return}}}catch{}try{let l=await navigator.clipboard?.readText();l&&s.pasteText(wt(l))}catch{}})();return}}}let Fe=0;function wt(i){return i.split(`\r
6
6
  `).join(`
7
7
  `).split(`
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">&#128193;</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
- <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 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>
8
+ `).join("\r")}async function mn(i){let l=cn(i.clipboardData);if(l){i.preventDefault(),i.stopPropagation();let v=Date.now();if(v-Fe<50)return;Fe=v,await et(l);return}let d=i.clipboardData?.getData("text/plain");if(!d)return;i.preventDefault(),i.stopPropagation();let m=Date.now();m-Fe<50||(Fe=m,s.pasteText(wt(d)))}let pe=0;function fn(i){i.preventDefault(),pe++,gt(i.dataTransfer)&&e.classList.add("terminal-drag-over")}function hn(i){i.preventDefault(),i.dataTransfer&&(i.dataTransfer.dropEffect="copy")}function gn(i){i.preventDefault(),pe--,pe<=0&&(pe=0,e.classList.remove("terminal-drag-over"))}async function vn(i){i.preventDefault(),pe=0,e.classList.remove("terminal-drag-over");let l=gt(i.dataTransfer);l&&await et(l)}function bt(i){!sn||i.key!=="Escape"||re||i.defaultPrevented||i.repeat||i.metaKey||i.ctrlKey||i.altKey||s.isFocused()&&(i.preventDefault(),i.stopPropagation(),ee("\x1B"))}e.addEventListener("paste",mn),e.addEventListener("dragenter",fn),e.addEventListener("dragover",hn),e.addEventListener("dragleave",gn),e.addEventListener("drop",vn),document.addEventListener("keydown",bt,!0);function yn(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",v=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:v,sent:!1},i.stopPropagation()}function wn(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,Se=Date.now()+500}i.preventDefault(),i.stopPropagation();let v=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=v;return}let _=v-o.lastT;_>0&&(o.velocity=P/_),xn(-P),o.lastX=l.clientX,o.lastY=l.clientY,o.lastT=v}function bn(i){if(!o)return;let l=o.scrolling,d=o.zone,m=o.tuiUp,v=o.velocity;if(o=null,i.stopPropagation(),d==="tui"){l||(ee(m?"\x1B[5~":"\x1B[6~"),ae(m),Se=Date.now()+500,i.preventDefault());return}if(!l){s.focus();return}Se=Date.now()+500,i.preventDefault(),v&&Qt(v)}function En(i){o=null,K(),i.stopPropagation()}function Ln(i){i.pointerType==="touch"&&Date.now()<Se&&(i.preventDefault(),i.stopPropagation())}function xn(i){let l=s.cellHeight(),d=l>0?Math.round(i/l):i>0?1:-1;d===0&&(d=i>0?1:-1),s.scrollLines(d)}e.addEventListener("touchstart",yn,{passive:!0,capture:!0}),e.addEventListener("touchmove",wn,{passive:!1,capture:!0}),e.addEventListener("touchend",bn,{passive:!1,capture:!0}),e.addEventListener("touchcancel",En,{passive:!0,capture:!0}),e.addEventListener("pointerup",Ln,!0);function Et(){I()}window.addEventListener("resize",Et),window.visualViewport?.addEventListener("resize",I),window.visualViewport?.addEventListener("scroll",I);let Lt=new ResizeObserver(()=>I());Lt.observe(e),document.fonts?.ready.then(()=>{I(),setTimeout(I,50),setTimeout(I,200)}),e.addEventListener("focusin",rn,!0);async function Cn(){if(document.fonts?.ready)try{await Promise.race([document.fonts.ready,new Promise(i=>setTimeout(i,1e3))])}catch{}}return requestAnimationFrame(()=>{X()&&Me(),(async()=>(await Cn(),X()&&V({type:"resize",cols:s.cols,rows:s.rows}),ft(),I()))()}),{destroy(){if(W=!0,K(),te(!1),ue&&clearTimeout(ue),document.removeEventListener("mousemove",tt,!0),document.removeEventListener("mouseup",nt,!0),a){try{a.close(1e3,"session switch")}catch{}a=void 0}e.innerHTML="",e.classList.remove("terminal-pending"),window.removeEventListener("resize",Et),Lt.disconnect(),document.removeEventListener("keydown",bt,!0)},focus(){s.focus()},sendInput(i){ee(i)},toggleCopyMode(){yt()}}})()}var fe=window.__TMUX_WEB_SHELL__,g=null,y=null,he=typeof window.__TMUX_WEB_SCOPE__?.agentId=="string"?window.__TMUX_WEB_SCOPE__.agentId:null,k=he;window.__tmuxWebScopeAgent=he;var it="sessions",Y="",Re="",Pe="",kt="";function S(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"),An=document.getElementById("fe-path"),F=document.getElementById("fe-status"),ve=document.getElementById("fe-content"),Z=document.getElementById("fe-save"),Fn=document.getElementById("fe-delete"),Hn=document.getElementById("fe-back"),St=document.getElementById("fe-new-name"),Rn=document.getElementById("fe-new-btn"),at=document.getElementById("settings-backdrop"),Tt=document.getElementById("settings-popover"),It=document.querySelector(".sidebar"),Bt="tmux-web-force-narrow";function Ne(){try{return localStorage.getItem(Bt)==="1"}catch{return!1}}function Mt(){document.documentElement.classList.toggle("force-narrow",Ne()),Ne()&&Dt()&&$e()}function Dt(){return Ne()?!0:window.matchMedia("(max-width: 640px)").matches}function $e(){Dt()&&It.classList.add("collapsed")}function At(){It.classList.remove("collapsed")}document.getElementById("mode-sessions").addEventListener("click",()=>{At(),Ft("sessions")}),document.getElementById("mode-files").addEventListener("click",()=>{At(),Ft("files")});function Ft(e){it=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"?(ot="",j()):Xn()}var ot="";async function j(){if(it!=="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===ot)return;ot=n,jn(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")}),pt()}var Ht="tmux-web-sidebar-group-collapsed";function Rt(){try{return new Set(JSON.parse(localStorage.getItem(Ht)||"[]"))}catch{return new Set}}function Pn(e){try{localStorage.setItem(Ht,JSON.stringify([...e]))}catch{}}function Nn(e,t,n){if(!e)return"\u2026";let s=n&&(e===n||e.startsWith(n+"/"))?"~"+e.slice(n.length):e,a=s.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:(n&&(o===n||o.startsWith(n+"/"))?"~"+o.slice(n.length):o).split("/").filter(Boolean).slice(-r).join("/")===c))return c}return s}function Pt(e,t,n,s=!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=Rt();for(let[o,u]of a){let p=Nn(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">&#128193;</span><span class="sg-label">${h(p)}</span>`,x.addEventListener("click",()=>{let B=Rt(),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")),Pn(B)});let A=document.createElement("div");A.className="session-group-body"+(E?" collapsed":"");for(let B of u)A.appendChild(n?$n(B,n,s):zn(B));f.appendChild(x),f.appendChild(A)}}function $n(e,t,n){let s=document.createElement("div");s.className="session-item"+(e.name===y&&k===t?" active":"")+(n?"":" session-offline"),s.setAttribute("data-session",e.name),s.setAttribute("data-agent",t),s.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="${e.attached?"M19 4H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zm0 14H5V6h14v12z":"M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"}"></svg>
9
+ <span>${h(e.name)}</span>${n?"":'<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>`,n&&s.addEventListener("click",r=>{r.target.closest(".session-edit-btn")||ye(e.name,t)});let a=s.querySelector(".session-edit-btn");return a&&a.addEventListener("click",r=>{r.stopPropagation(),Ve(e.name,a,{agentId:t})}),s}function zn(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 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>
13
+ `,t.addEventListener("click",s=>{s.target.closest(".session-edit-btn")||ye(e.name)});let n=t.querySelector(".session-edit-btn");return n&&n.addEventListener("click",s=>{s.stopPropagation(),Ve(e.name,n)}),t}function jn(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"+(he?" clickable":""),n.textContent=he?"\u2190 \u8FD4\u56DE\u672C\u673A":"\u672C\u673A",he&&(n.title="Back to hub",n.addEventListener("click",()=>{window.location.href="/"})),f.appendChild(n),Pt(t,e.home);let s=e.agents||[];for(let r of s){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),Pt(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",E=>{E.stopPropagation(),Ke(c.name,p,{tombstone:!0,agentId:c.agentId})}),f.appendChild(o)}}}function h(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}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">
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",()=>{Ve(c.name,o,{tombstone:!0,agentId:c.agentId})});let p=o.querySelector(".session-edit-btn");p&&p.addEventListener("click",E=>{E.stopPropagation(),Ve(c.name,p,{tombstone:!0,agentId:c.agentId})}),f.appendChild(o)}}}function h(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}async function ye(e,t){if(y===e&&g&&k===(t||null))return;ge.style.display="none",J.style.display="none",M.style.display="",M.classList.add("terminal-pending"),$e(),g&&(Oe(),g.destroy(),g=null),y=e,k=t||null,window.__tmuxWebScopeAgent=k,window.__tmuxWebCurrentSession=y,us(e,t);let n=ut(e,t);Jt.set(n,Date.now()+cs);let s=ie.get(n);if(s&&s.state==="working"){s.state="idle",s.doneUntil=void 0,s.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&&Qe(a,n,s)}for(let a of f.querySelectorAll(".session-item"))a.classList.toggle("active",a.getAttribute("data-session")===e&&(a.getAttribute("data-agent")||null)===k);try{g=await Dn(M,e,{terminal:fe.terminal,scrollback:fe.scrollback,theme:fe.theme,wsBase:k?"/ws/a/"+encodeURIComponent(k):fe.wsBase||"/ws"}),Ot()}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 ze=[],w=null,Nt=!1;function Un(e){if(!w||!w.files.length)return null;let t=w.repoRoot;if(!t||!e.startsWith(t))return null;let n=e.slice(t.length+1);for(let s of w.files)if(s.path===n)return s.status;return null}async function Wn(e){Nt=!0;try{let t=await fetch(S("/api/git/status?path="+encodeURIComponent(e)));t.ok?w=await t.json():w=null}catch{w=null}finally{Nt=!1}}function _n(){if(!w||!w.branch)return"";let{branch:e,linesAdded:t,linesRemoved:n}=w,s=`<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>"}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
- ${c}<span class="file-path">${h(n.path)}</span>
17
+ ${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")&&ne&&w&&(e.stopPropagation(),Wt())});var we=document.getElementById("header-git"),$t=document.getElementById("git-diff-view"),zt=document.getElementById("gd-path"),je=document.getElementById("gd-status"),Ue=document.getElementById("gd-content"),Yn=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:n,linesRemoved:s}=e,a=`<span class="branch">${h(t)}</span>`;(n>0||s>0)&&(a+=`<span class="sep">\xB7</span>+<span class="diff-add">${n}</span> <span class="diff-del">-${s}</span>`),we.innerHTML=a,we.style.display="block"}we.addEventListener("click",e=>{ne&&w&&(e.stopPropagation(),Wt())});var T=document.getElementById("git-popover"),We=document.getElementById("git-popover-backdrop");function lt(){let e=we.getBoundingClientRect();T.style.top=e.bottom+4+"px",T.style.left=Math.max(8,Math.min(e.left,window.innerWidth-400))+"px"}function jt(){let e=ne,t=document.getElementById("git-popover-browse");t&&t.addEventListener("click",()=>{if(Ye(),e){it="files",document.querySelectorAll(".mode-btn").forEach(s=>s.classList.remove("active"));let n=document.getElementById("mode-files");n&&n.classList.add("active"),q(e)}})}var Ut="";function Wt(){if(!w)return;let e=w.files||[];if(!e.length)T.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 n=0;n<e.length;n++){let s=e[n],a=s.additions||0,r=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}">
19
+ ${c}<span class="file-path">${h(s.path)}</span>
20
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>',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?`
22
+ </div>`}t+='<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>',Ut=t,T.innerHTML=t,T.querySelectorAll(".git-popover-item").forEach(n=>{let s=parseInt(n.dataset.idx||"0",10),a=e[s];!a||a.status==="D"||(n.classList.add("clickable"),n.style.cursor="pointer",n.addEventListener("click",()=>Yt(a.path)))})}lt(),T.classList.add("open"),We.classList.add("open"),jt()}function qn(){return window.innerWidth>=1024}function _t(e,t){let n=(e+(t&&e?`
23
23
  `:"")+t).split(`
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">
24
+ `),s="",a=0,r=0;for(let c of n){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),s+=`<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")&&(s+=`<div class="diff-line header"><span class="ln-body">${h(o)}</span></div>`);continue}if(o.startsWith("+"))r++,s+=`<div class="diff-line add"><span class="ln-no">${r}</span><span class="ln-body">${h(o)}</span></div>`;else if(o.startsWith("-"))a++,s+=`<div class="diff-line del"><span class="ln-no">${a}</span><span class="ln-body">${h(o)}</span></div>`;else if(o.startsWith("\\"))s+=`<div class="diff-line"><span class="ln-body">${h(o)}</span></div>`;else{if(!o&&!a&&!r)continue;a++,r++,s+=`<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:s,lineCount:n.length}}var _e=null;async function Yt(e){let t=ne;if(t)if(Ye(),qn()){M.style.display="none",g&&(Oe(),g.destroy(),g=null,_e=y,y=null),be(null),ge.style.display="none",J.style.display="none",$t.style.display="flex",zt.textContent=e,je.textContent="Loading\u2026",Ue.innerHTML="";try{let n=await fetch(S("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!n.ok)throw new Error(await n.text());let s=await n.json();Kn(e,s.diff,s.stagedDiff)}catch(n){let s=n instanceof Error?n.message:String(n);je.textContent="Error",Ue.innerHTML=`<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">Error: ${h(s)}</div>`}}else{T.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(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">
28
+ </div></div>`,lt(),T.classList.add("open"),We.classList.add("open");try{let n=await fetch(S("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!n.ok)throw new Error(await n.text());let s=await n.json();On(e,s.diff,s.stagedDiff)}catch(n){let s=n instanceof Error?n.message:String(n);T.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 Un(e,t,s){if(!t&&!s){S.innerHTML=`<div class="git-diff-view"><div class="diff-header">
31
+ </div><div class="diff-empty">Error loading diff: ${h(s)}</div></div>`}}}function On(e,t,n){if(!t&&!n){T.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:a}=zt(t,s);S.innerHTML=`<div class="git-diff-view"><div class="diff-header">
34
+ </div><div class="diff-empty">No diff content available</div></div>`;return}let{html:s,lineCount:a}=_t(t,n);T.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
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">
38
+ </div><div class="diff-content">${s}</div></div>`,T.querySelector(".diff-back")?.addEventListener("click",()=>{T.innerHTML=Ut,lt(),w&&T.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",()=>Yt(o.path)))}),jt()})}function Kn(e,t,n){if(!t&&!n){je.textContent="No diff",Ue.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:a}=_t(t,n);zt.textContent=e,je.textContent=a+" lines",Ue.innerHTML=s}function Vn(){$t.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"),Ot()):J.style.display="flex"}Yn.addEventListener("click",Vn);function Ye(){T.classList.remove("open"),We.classList.remove("open")}We.addEventListener("click",Ye),document.addEventListener("keydown",e=>{e.key==="Escape"&&(Ye(),Ge())});async function qt(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();w=s,be(s);return}}}catch{}w=null,be(null)}var qe=null;function Ot(){Oe(),y&&(qt(y),qe=setInterval(()=>{y&&qt(y)},3e4))}function Oe(){qe&&(clearInterval(qe),qe=null)}function Xn(){if(ze=fe.fsRoots||[],ze.length===0){if(y){Jn(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 ze){let t=document.createElement("div");t.className="file-tree-item",t.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor" class="file-icon"><path d="M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/></svg> ${h(e)}`,t.addEventListener("click",()=>q(e)),f.appendChild(t)}}async function Jn(e){f.innerHTML='<div class="file-tree-empty">Loading...</div>';try{let t=await(await fetch(S("/api/fs/session-path?session="+encodeURIComponent(e)))).json();t.path?q(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 q(e){Y=e,f.innerHTML='<div class="file-tree-empty">Loading...</div>';let t=Wn(e);try{let n=await(await fetch(S("/api/fs/list?path="+encodeURIComponent(e)))).json();await t,f.innerHTML="",be(w),f.innerHTML+=_n();let s=Zn(e);if(s&&!ze.some(r=>e===r)){let r=document.createElement("div");r.className="file-tree-item",r.innerHTML="..",r.addEventListener("click",()=>q(s)),f.appendChild(r)}if(n.dirs)for(let r of n.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",()=>q(r)),f.appendChild(o)}else f.innerHTML="";let a=n.files||[];for(let r of a){let c=r.split("/").pop()||r.split("\\").pop(),o=Un(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",()=>Gn(r)),f.appendChild(E)}}catch{f.innerHTML='<div class="file-tree-error">Failed to load directory</div>'}}function Zn(e){let t=e.lastIndexOf("/");return t<=0?null:e.substring(0,t)}async function Gn(e){Re=e,M.style.display="none",g&&(Oe(),g.destroy(),g=null,y=null),be(null),$e(),J.style.display="none",ge.style.display="flex",An.textContent=e,F.textContent="Loading...",Z.style.display="none";try{let t=await fetch(S("/api/file?path="+encodeURIComponent(e)));if(!t.ok){let s=await t.json();F.textContent=s.error||"Failed to load",ve.value="";return}let n=await t.json();ve.value=n.content,Pe=n.content,kt=n.content,F.textContent=n.size+" bytes",Z.style.display=""}catch{F.textContent="Failed to load",ve.value=""}}ve.addEventListener("input",()=>{Pe=ve.value}),Z.addEventListener("click",async()=>{Z.textContent="Saving...",Z.disabled=!0;try{let e=await fetch(S("/api/file"),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:Re,content:Pe})});if(!e.ok){let t=await e.json();F.textContent=t.error||"Save failed";return}kt=Pe,F.textContent="Saved"}catch{F.textContent="Save failed"}finally{Z.disabled=!1,Z.textContent="Save"}}),Fn.addEventListener("click",async()=>{if(confirm("Delete "+Re+"?"))try{let e=await fetch(S("/api/file/delete"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:Re})});if(!e.ok){let t=await e.json();F.textContent=t.error||"Delete failed";return}ge.style.display="none",J.style.display="flex",Y&&q(Y)}catch{F.textContent="Delete failed"}}),Hn.addEventListener("click",()=>{ge.style.display="none",J.style.display="flex",Y&&q(Y)}),Rn.addEventListener("click",async()=>{let e=St.value.trim();if(!e)return;let t=Y+"/"+e;try{let n=await fetch(S("/api/file/touch"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t})});if(!n.ok){let s=await n.json();F.textContent=s.error||"Create failed";return}St.value="",Y&&q(Y)}catch{F.textContent="Create failed"}});var Ke=document.getElementById("force-narrow-toggle");Ke&&(Ke.checked=Ne(),Ke.addEventListener("change",()=>{try{localStorage.setItem(Bt,Ke.checked?"1":"0")}catch{}Mt(),j()})),Mt(),document.getElementById("mode-settings").addEventListener("click",()=>{let e=Tt.classList.toggle("open");at.classList.toggle("open",e)}),at.addEventListener("click",()=>{Tt.classList.remove("open"),at.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 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+'">&times;</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);
48
+ <button class="btn danger" id="sp-delete">Delete session</button>`,document.body.appendChild(R);function Qn(e){let t=e.getBoundingClientRect(),n=window.innerHeight,s=R.offsetHeight||240,a=t.bottom+4;a+s>n-8&&(a=Math.max(8,t.top-s-4)),R.style.top=a+"px",R.style.left=Math.max(8,Math.min(t.left,window.innerWidth-240))+"px"}function Ve(e,t,n){D=e,U=!!n?.tombstone,H=n?.agentId;let s=document.getElementById("sp-name");s.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",Qn(t),setTimeout(()=>s.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(S(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(S("/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(S("/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(S("/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&&(g&&(g.destroy(),g=null),y=null,M.style.display="none",J.style.display="flex"),j()}catch{}}),document.getElementById("sp-cancel").addEventListener("click",G);var Kt={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"},Xe=document.getElementById("mobile-keys"),es=new Set(["up","down","left","right","tab","s-tab","space"]),ts=400,ns=80,Le=0,Je=0,Ze=!1;function ss(){Le&&(clearTimeout(Le),Le=0),Je&&(clearInterval(Je),Je=0)}Xe.addEventListener("mousedown",e=>{e.target.closest("button[data-key]")&&e.preventDefault()}),Xe.addEventListener("pointerdown",e=>{let t=e.target.closest("button[data-key]");if(!t)return;let n=t.dataset.key;es.has(n)&&(Ze=!1,Le=setTimeout(()=>{Le=0,Ze=!0,Je=setInterval(()=>{let s=Kt[n];s&&g&&g.sendInput(s)},ns)},ts))});for(let e of["pointerup","pointercancel","pointerleave"])Xe.addEventListener(e,ss);Xe.addEventListener("click",e=>{let t=e.target.closest("button[data-key]");if(!t||!g)return;if(Ze){Ze=!1;return}let n=Kt[t.dataset.key];n&&(g.sendInput(n),g.focus())});var N=document.getElementById("mk-input"),Vt=document.getElementById("mk-send");function Xt(){if(!N||!g)return;let e=N.value;e&&(g.sendInput(e+"\r"),N.value="",N.rows=1,g.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(),Xt())})),Vt&&Vt.addEventListener("click",Xt),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 rt=document.getElementById("process-panel"),xe=document.getElementById("proc-list"),is=document.getElementById("proc-close"),ct=document.getElementById("proc-backdrop"),as=document.getElementById("header-ram");function os(){xe.innerHTML='<div class="proc-empty">Loading\u2026</div>',fetch(S("/api/system/processes")).then(e=>e.json()).then(e=>{if(!Array.isArray(e)||!e.length){xe.innerHTML='<div class="proc-empty">No processes</div>';return}let t="";for(let n of e){let s=n.rss,a=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">'+a+'</span><span class="proc-cmd" title="'+h(n.command)+'">'+h(n.command)+'</span><button class="proc-kill" title="Kill PID '+n.pid+'">&times;</button></div>'}xe.innerHTML=t;for(let n of xe.querySelectorAll(".proc-row")){let s=n.querySelector(".proc-kill");s&&s.addEventListener("click",a=>{let r=a.target.closest(".proc-row");!r||!confirm("Kill PID "+r.dataset.pid+"?")||fetch(S("/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(()=>{xe.innerHTML='<div class="proc-empty">Failed to load</div>'})}function ls(){rt.classList.add("open"),ct.classList.add("open"),os()}function Ge(){rt.classList.remove("open"),ct.classList.remove("open")}as.addEventListener("click",e=>{e.stopPropagation(),rt.classList.contains("open")?Ge():ls()}),is.addEventListener("click",Ge),ct.addEventListener("click",Ge);var rs=2e3,Ce=null,dt=null,se=new Map,ie=new Map,cs=5e3,Jt=new Map;function ut(e,t){return(t?"a:"+t+":":"l:")+e}function ds(e,t,n){let s=ut(e,t);if(n==="working"){let p=Jt.get(s);if(p&&Date.now()<p)return}let a=ie.get(s),r=e===y&&(t??null)===k,c=n==="idle"&&a?.state==="working";ie.set(s,{session:e,agentId:t,state:n,doneUntil:c?Date.now()+rs: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&&Qe(u,s,ie.get(s))}function Qe(e,t,n){let s=se.get(t);s&&(clearTimeout(s),se.delete(t)),e.classList.remove("working","just-done");let a=n.session===y&&(n.agentId??null)===k;n.state==="working"?e.classList.add("working"):a&&n.doneUntil&&Date.now()<n.doneUntil?(e.classList.add("just-done"),se.set(t,setTimeout(()=>{e.classList.remove("just-done"),se.delete(t)},Math.max(0,n.doneUntil-Date.now())))):!a&&n.unread&&e.classList.add("just-done")}function pt(){for(let[e,t]of ie){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&&Qe(s,e,t)}}function us(e,t){let n=ut(e,t),s=ie.get(n);if(!s)return;let a=se.get(n);a&&(clearTimeout(a),se.delete(n)),s.doneUntil=void 0,s.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&&Qe(c,n,s)}function Zt(){if(Ce||dt)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);Ce=n,n.onmessage=s=>{try{let a=JSON.parse(String(s.data));a&&a.type==="session.activity"&&typeof a.session=="string"&&ds(a.session,a.agentId||void 0,a.state==="working"?"working":"idle")}catch{}},n.onclose=()=>{Ce===n&&(Ce=null,dt=setTimeout(()=>{dt=null,Zt()},5e3))},n.onerror=()=>{try{n.close()}catch{}}}catch{Ce=null}}window.__openSession=ye,window.__refreshSidebar=j,j(),$e(),pt(),Zt(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&pt()}),setInterval(()=>{document.visibilityState==="visible"&&j()},1e4);
@@ -1,34 +1,34 @@
1
- import{initTerminal as qe}from"./terminal-core.js";const D=window.__TMUX_WEB_SHELL__;let f=null,u=null;const P=typeof window.__TMUX_WEB_SCOPE__?.agentId=="string"?window.__TMUX_WEB_SCOPE__.agentId:null;let g=P;window.__tmuxWebScopeAgent=P;let de="sessions",x="",V="",J="",we="";function v(e){return g?"/a/"+encodeURIComponent(g)+e:e}const r=document.getElementById("sidebar-content"),H=document.getElementById("main-placeholder"),b=document.getElementById("terminal-container"),j=document.getElementById("file-editor"),Ve=document.getElementById("fe-path"),E=document.getElementById("fe-status"),O=document.getElementById("fe-content"),N=document.getElementById("fe-save"),Je=document.getElementById("fe-delete"),Ke=document.getElementById("fe-back"),Le=document.getElementById("fe-new-name"),Ye=document.getElementById("fe-new-btn"),pe=document.getElementById("settings-backdrop"),Ee=document.getElementById("settings-popover"),ke=document.querySelector(".sidebar"),Se="tmux-web-force-narrow";function K(){try{return localStorage.getItem(Se)==="1"}catch{return!1}}function Ce(){document.documentElement.classList.toggle("force-narrow",K()),K()&&Ie()&&Y()}function Ie(){return K()?!0:window.matchMedia("(max-width: 640px)").matches}function Y(){Ie()&&ke.classList.add("collapsed")}function Be(){ke.classList.remove("collapsed")}document.getElementById("mode-sessions").addEventListener("click",()=>{Be(),xe("sessions")}),document.getElementById("mode-files").addEventListener("click",()=>{Be(),xe("files")});function xe(e){de=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"?(fe="",I()):dt()}let fe="";async function I(){if(de!=="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===fe)return;fe=s,tt(t)}catch{r.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")}),he()}const Me="tmux-web-sidebar-group-collapsed";function Te(){try{return new Set(JSON.parse(localStorage.getItem(Me)||"[]"))}catch{return new Set}}function Xe(e){try{localStorage.setItem(Me,JSON.stringify([...e]))}catch{}}function Ze(e,n,t){if(!e)return"\u2026";const s=t&&(e===t||e.startsWith(t+"/"))?"~"+e.slice(t.length):e,i=s.split("/").filter(Boolean);if(i.length===0)return e;for(let o=1;o<=i.length;o++){const a=i.slice(-o).join("/");if(!n.some(c=>!c||c===e?!1:(t&&(c===t||c.startsWith(t+"/"))?"~"+c.slice(t.length):c).split("/").filter(Boolean).slice(-o).join("/")===a))return a}return s}function He(e,n,t,s=!0){const i=new Map;for(const l of e){const c=l.path||"";i.has(c)||i.set(c,[]),i.get(c).push(l)}const o=[...i.keys()],a=Te();for(const[l,c]of i){const p=Ze(l,o,n),L=a.has(l),h=document.createElement("div");h.className="session-group-header"+(L?" collapsed":""),h.title=l||"No working directory",h.innerHTML=`<span class="sg-folder">&#128193;</span><span class="sg-label">${d(p)}</span>`,h.addEventListener("click",()=>{const T=Te(),be=h.nextElementSibling;T.has(l)?(T.delete(l),h.classList.remove("collapsed"),be?.classList.remove("collapsed")):(T.add(l),h.classList.add("collapsed"),be?.classList.add("collapsed")),Xe(T)});const re=document.createElement("div");re.className="session-group-body"+(L?" collapsed":"");for(const T of c)re.appendChild(t?Qe(T,t,s):et(T));r.appendChild(h),r.appendChild(re)}}function Qe(e,n,t){const s=document.createElement("div");s.className="session-item"+(e.name===u&&g===n?" active":"")+(t?"":" session-offline"),s.setAttribute("data-session",e.name),s.setAttribute("data-agent",n),s.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="${e.attached?"M19 4H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zm0 14H5V6h14v12z":"M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"}"></svg>
1
+ import{initTerminal as Xe}from"./terminal-core.js";const D=window.__TMUX_WEB_SHELL__;let p=null,u=null;const P=typeof window.__TMUX_WEB_SCOPE__?.agentId=="string"?window.__TMUX_WEB_SCOPE__.agentId:null;let g=P;window.__tmuxWebScopeAgent=P;let me="sessions",x="",J="",K="",Se="";function v(e){return g?"/a/"+encodeURIComponent(g)+e:e}const r=document.getElementById("sidebar-content"),H=document.getElementById("main-placeholder"),b=document.getElementById("terminal-container"),j=document.getElementById("file-editor"),Ze=document.getElementById("fe-path"),E=document.getElementById("fe-status"),O=document.getElementById("fe-content"),R=document.getElementById("fe-save"),Qe=document.getElementById("fe-delete"),et=document.getElementById("fe-back"),Ce=document.getElementById("fe-new-name"),tt=document.getElementById("fe-new-btn"),ge=document.getElementById("settings-backdrop"),Ie=document.getElementById("settings-popover"),Be=document.querySelector(".sidebar"),xe="tmux-web-force-narrow";function Y(){try{return localStorage.getItem(xe)==="1"}catch{return!1}}function Te(){document.documentElement.classList.toggle("force-narrow",Y()),Y()&&Me()&&X()}function Me(){return Y()?!0:window.matchMedia("(max-width: 640px)").matches}function X(){Me()&&Be.classList.add("collapsed")}function He(){Be.classList.remove("collapsed")}document.getElementById("mode-sessions").addEventListener("click",()=>{He(),Re("sessions")}),document.getElementById("mode-files").addEventListener("click",()=>{He(),Re("files")});function Re(e){me=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"?(ve="",I()):gt()}let ve="";async function I(){if(me!=="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===ve)return;ve=s,at(t)}catch{r.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")}),Ee()}const Ne="tmux-web-sidebar-group-collapsed";function Ae(){try{return new Set(JSON.parse(localStorage.getItem(Ne)||"[]"))}catch{return new Set}}function nt(e){try{localStorage.setItem(Ne,JSON.stringify([...e]))}catch{}}function st(e,n,t){if(!e)return"\u2026";const s=t&&(e===t||e.startsWith(t+"/"))?"~"+e.slice(t.length):e,i=s.split("/").filter(Boolean);if(i.length===0)return e;for(let o=1;o<=i.length;o++){const a=i.slice(-o).join("/");if(!n.some(c=>!c||c===e?!1:(t&&(c===t||c.startsWith(t+"/"))?"~"+c.slice(t.length):c).split("/").filter(Boolean).slice(-o).join("/")===a))return a}return s}function _e(e,n,t,s=!0){const i=new Map;for(const l of e){const c=l.path||"";i.has(c)||i.set(c,[]),i.get(c).push(l)}const o=[...i.keys()],a=Ae();for(const[l,c]of i){const f=st(l,o,n),L=a.has(l),h=document.createElement("div");h.className="session-group-header"+(L?" collapsed":""),h.title=l||"No working directory",h.innerHTML=`<span class="sg-folder">&#128193;</span><span class="sg-label">${d(f)}</span>`,h.addEventListener("click",()=>{const M=Ae(),ke=h.nextElementSibling;M.has(l)?(M.delete(l),h.classList.remove("collapsed"),ke?.classList.remove("collapsed")):(M.add(l),h.classList.add("collapsed"),ke?.classList.add("collapsed")),nt(M)});const ue=document.createElement("div");ue.className="session-group-body"+(L?" collapsed":"");for(const M of c)ue.appendChild(t?it(M,t,s):ot(M));r.appendChild(h),r.appendChild(ue)}}function it(e,n,t){const s=document.createElement("div");s.className="session-item"+(e.name===u&&g===n?" active":"")+(t?"":" session-offline"),s.setAttribute("data-session",e.name),s.setAttribute("data-agent",n),s.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="${e.attached?"M19 4H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zm0 14H5V6h14v12z":"M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"}"></svg>
2
2
  <span>${d(e.name)}</span>${t?"":'<span class="meta">offline</span>'}
3
- <button class="session-edit-btn" data-session="${d(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>`,t&&s.addEventListener("click",o=>{o.target.closest(".session-edit-btn")||U(e.name,n)});const i=s.querySelector(".session-edit-btn");return i&&i.addEventListener("click",o=>{o.stopPropagation(),ae(e.name,i,{agentId:n})}),s}function et(e){const n=document.createElement("div");n.className="session-item"+(e.name===u&&!g?" 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>
3
+ <button class="session-edit-btn" data-session="${d(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>`,t&&s.addEventListener("click",o=>{o.target.closest(".session-edit-btn")||U(e.name,n)});const i=s.querySelector(".session-edit-btn");return i&&i.addEventListener("click",o=>{o.stopPropagation(),le(e.name,i,{agentId:n})}),s}function ot(e){const n=document.createElement("div");n.className="session-item"+(e.name===u&&!g?" 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>
4
4
  <span>${d(e.name)}</span>
5
5
  <button class="session-edit-btn" data-session="${d(e.name)}" title="Edit session"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>
6
- `,n.addEventListener("click",s=>{s.target.closest(".session-edit-btn")||U(e.name)});const t=n.querySelector(".session-edit-btn");return t&&t.addEventListener("click",s=>{s.stopPropagation(),ae(e.name,t)}),n}function tt(e){r.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"+(P?" clickable":""),t.textContent=P?"\u2190 \u8FD4\u56DE\u672C\u673A":"\u672C\u673A",P&&(t.title="Back to hub",t.addEventListener("click",()=>{window.location.href="/"})),r.appendChild(t),He(n,e.home);const s=e.agents||[];for(const o of s){if(!o.sessions||o.sessions.length===0)continue;const a=o.agentId===g,l=document.createElement("div");l.className="sidebar-section-label machine-label"+(o.online?"":" agent-offline-label")+(!a&&o.online?" clickable":""),l.textContent=o.agentName+(o.online?"":" (offline)"),!a&&o.online&&(l.title="\u6253\u5F00 "+o.agentName,l.addEventListener("click",()=>{window.location.href="/a/"+encodeURIComponent(o.agentId)+"/"})),r.appendChild(l),He(o.sessions,e.home,o.agentId,o.online)}const i=e.tombstones||[];if(i.length>0){const o=document.createElement("div");o.className="sidebar-section-label tombstone-label",o.textContent="\u5931\u6548\u4F1A\u8BDD",r.appendChild(o);for(const a of i){const l=document.createElement("div");l.className="session-item session-tombstone",l.setAttribute("data-session",a.name),a.agentId&&l.setAttribute("data-agent",a.agentId);const c=a.agentId?a.agentOnline?" (agent)":" (agent \u79BB\u7EBF)":"";l.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"></svg>
6
+ `,n.addEventListener("click",s=>{s.target.closest(".session-edit-btn")||U(e.name)});const t=n.querySelector(".session-edit-btn");return t&&t.addEventListener("click",s=>{s.stopPropagation(),le(e.name,t)}),n}function at(e){r.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"+(P?" clickable":""),t.textContent=P?"\u2190 \u8FD4\u56DE\u672C\u673A":"\u672C\u673A",P&&(t.title="Back to hub",t.addEventListener("click",()=>{window.location.href="/"})),r.appendChild(t),_e(n,e.home);const s=e.agents||[];for(const o of s){if(!o.sessions||o.sessions.length===0)continue;const a=o.agentId===g,l=document.createElement("div");l.className="sidebar-section-label machine-label"+(o.online?"":" agent-offline-label")+(!a&&o.online?" clickable":""),l.textContent=o.agentName+(o.online?"":" (offline)"),!a&&o.online&&(l.title="\u6253\u5F00 "+o.agentName,l.addEventListener("click",()=>{window.location.href="/a/"+encodeURIComponent(o.agentId)+"/"})),r.appendChild(l),_e(o.sessions,e.home,o.agentId,o.online)}const i=e.tombstones||[];if(i.length>0){const o=document.createElement("div");o.className="sidebar-section-label tombstone-label",o.textContent="\u5931\u6548\u4F1A\u8BDD",r.appendChild(o);for(const a of i){const l=document.createElement("div");l.className="session-item session-tombstone",l.setAttribute("data-session",a.name),a.agentId&&l.setAttribute("data-agent",a.agentId);const c=a.agentId?a.agentOnline?" (agent)":" (agent \u79BB\u7EBF)":"";l.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"></svg>
7
7
  <span>${d(a.name)}</span><span class="meta">\u5931\u6548${c}</span>
8
- <button class="session-edit-btn" data-session="${d(a.name)}" title="\u6062\u590D\u4F1A\u8BDD"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>`,l.title="\u5931\u6548\u4F1A\u8BDD\uFF1A\u70B9\u51FB\u7BA1\u7406\uFF08\u91CD\u5EFA/\u91CD\u547D\u540D/\u5220\u9664\uFF09",l.addEventListener("click",()=>{ae(a.name,l,{tombstone:!0,agentId:a.agentId})});const p=l.querySelector(".session-edit-btn");p&&p.addEventListener("click",L=>{L.stopPropagation(),ae(a.name,p,{tombstone:!0,agentId:a.agentId})}),r.appendChild(l)}}}function d(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}async function U(e,n){if(u===e&&f&&g===(n||null))return;j.style.display="none",H.style.display="none",b.style.display="",b.classList.add("terminal-pending"),Y(),f&&(ie(),f.destroy(),f=null),u=e,g=n||null,window.__tmuxWebScopeAgent=g,window.__tmuxWebCurrentSession=u,kt(e,n);const t=ye(e,n);Fe.set(t,Date.now()+Lt);const s=_.get(t);if(s&&s.state==="working"){s.state="idle",s.doneUntil=void 0,s.unread=!1;const i=r.querySelector(n?'.session-item[data-agent="'+CSS.escape(n)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])');i&&ce(i,t,s)}for(const i of r.querySelectorAll(".session-item"))i.classList.toggle("active",i.getAttribute("data-session")===e&&(i.getAttribute("data-agent")||null)===g);try{f=await qe(b,e,{terminal:D.terminal,scrollback:D.scrollback,theme:D.theme,wsBase:g?"/ws/a/"+encodeURIComponent(g):D.wsBase||"/ws"}),Ue()}catch(i){console.error("[shell] terminal init failed:",i);const o=i&&typeof i=="object"&&"message"in i?i.message:String(i);b.textContent="Failed to open terminal for "+e+": "+o,b.classList.remove("terminal-pending")}}let X=[],m=null,Ne=!1;function nt(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 st(e){Ne=!0;try{const n=await fetch(v("/api/git/status?path="+encodeURIComponent(e)));n.ok?m=await n.json():m=null}catch{m=null}finally{Ne=!1}}function it(){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
+ <button class="session-edit-btn" data-session="${d(a.name)}" title="\u6062\u590D\u4F1A\u8BDD"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>`,l.title="\u5931\u6548\u4F1A\u8BDD\uFF1A\u70B9\u51FB\u7BA1\u7406\uFF08\u91CD\u5EFA/\u91CD\u547D\u540D/\u5220\u9664\uFF09",l.addEventListener("click",()=>{le(a.name,l,{tombstone:!0,agentId:a.agentId})});const f=l.querySelector(".session-edit-btn");f&&f.addEventListener("click",L=>{L.stopPropagation(),le(a.name,f,{tombstone:!0,agentId:a.agentId})}),r.appendChild(l)}}}function d(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}async function U(e,n){if(u===e&&p&&g===(n||null))return;j.style.display="none",H.style.display="none",b.style.display="",b.classList.add("terminal-pending"),X(),p&&(oe(),p.destroy(),p=null),u=e,g=n||null,window.__tmuxWebScopeAgent=g,window.__tmuxWebCurrentSession=u,Ht(e,n);const t=Le(e,n);Ke.set(t,Date.now()+Tt);const s=$.get(t);if(s&&s.state==="working"){s.state="idle",s.doneUntil=void 0,s.unread=!1;const i=r.querySelector(n?'.session-item[data-agent="'+CSS.escape(n)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])');i&&fe(i,t,s)}for(const i of r.querySelectorAll(".session-item"))i.classList.toggle("active",i.getAttribute("data-session")===e&&(i.getAttribute("data-agent")||null)===g);try{p=await Xe(b,e,{terminal:D.terminal,scrollback:D.scrollback,theme:D.theme,wsBase:g?"/ws/a/"+encodeURIComponent(g):D.wsBase||"/ws"}),Ge()}catch(i){console.error("[shell] terminal init failed:",i);const o=i&&typeof i=="object"&&"message"in i?i.message:String(i);b.textContent="Failed to open terminal for "+e+": "+o,b.classList.remove("terminal-pending")}}let Z=[],m=null,$e=!1;function lt(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 ct(e){$e=!0;try{const n=await fetch(v("/api/git/status?path="+encodeURIComponent(e)));n.ok?m=await n.json():m=null}catch{m=null}finally{$e=!1}}function rt(){if(!m||!m.branch)return"";const{branch:e,linesAdded:n,linesRemoved:t}=m;let s=`<div class="sidebar-git"><div class="git-branch-badge">
9
9
  <svg viewBox="0 0 16 16" fill="currentColor"><path d="M11.63 1.22a.75.75 0 00-1.06 0L5.99 5.8 4.12 3.93a.75.75 0 10-1.06 1.06L4.93 6.87A3.5 3.5 0 003 10.09v3.16a.75.75 0 001 0v-3.16a2.5 2.5 0 012.5-2.5h.27l-1.06 1.06a.75.75 0 001.06 1.06l2.37-2.38a.75.75 0 000-1.06L7.59 5.27l4.04-4.05a.75.75 0 000-1.06L11.63 1.22zM3.25 13.94a.75.75 0 01-.75-.75v-.69a.75.75 0 011.5 0v.69c0 .414-.336.75-.75.75z"/></svg>
10
- ${d(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>"}r.addEventListener("click",e=>{e.target.closest(".sidebar-git")&&$&&m&&(e.stopPropagation(),De())});const W=document.getElementById("header-git"),Re=document.getElementById("git-diff-view"),$e=document.getElementById("gd-path"),Z=document.getElementById("gd-status"),Q=document.getElementById("gd-content"),ot=document.getElementById("gd-back");let $=null;function z(e){if(!e||!e.branch){W.style.display="none",$=null;return}$=e.repoRoot;const{branch:n,linesAdded:t,linesRemoved:s}=e;let i=`<span class="branch">${d(n)}</span>`;(t>0||s>0)&&(i+=`<span class="sep">\xB7</span>+<span class="diff-add">${t}</span> <span class="diff-del">-${s}</span>`),W.innerHTML=i,W.style.display="block"}W.addEventListener("click",e=>{$&&m&&(e.stopPropagation(),De())});const y=document.getElementById("git-popover"),ee=document.getElementById("git-popover-backdrop");function ue(){const e=W.getBoundingClientRect();y.style.top=e.bottom+4+"px",y.style.left=Math.max(8,Math.min(e.left,window.innerWidth-400))+"px"}function Ae(){const e=$,n=document.getElementById("git-popover-browse");n&&n.addEventListener("click",()=>{if(ne(),e){de="files",document.querySelectorAll(".mode-btn").forEach(s=>s.classList.remove("active"));const t=document.getElementById("mode-files");t&&t.classList.add("active"),M(e)}})}let _e="";function De(){if(!m)return;const e=m.files||[];if(!e.length)y.innerHTML=`<div class="git-popover-header">No changes \u2014 clean working tree</div>
10
+ ${d(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>"}r.addEventListener("click",e=>{e.target.closest(".sidebar-git")&&A&&m&&(e.stopPropagation(),Ue())});const W=document.getElementById("header-git"),De=document.getElementById("git-diff-view"),Pe=document.getElementById("gd-path"),Q=document.getElementById("gd-status"),ee=document.getElementById("gd-content"),dt=document.getElementById("gd-back");let A=null;function z(e){if(!e||!e.branch){W.style.display="none",A=null;return}A=e.repoRoot;const{branch:n,linesAdded:t,linesRemoved:s}=e;let i=`<span class="branch">${d(n)}</span>`;(t>0||s>0)&&(i+=`<span class="sep">\xB7</span>+<span class="diff-add">${t}</span> <span class="diff-del">-${s}</span>`),W.innerHTML=i,W.style.display="block"}W.addEventListener("click",e=>{A&&m&&(e.stopPropagation(),Ue())});const y=document.getElementById("git-popover"),te=document.getElementById("git-popover-backdrop");function ye(){const e=W.getBoundingClientRect();y.style.top=e.bottom+4+"px",y.style.left=Math.max(8,Math.min(e.left,window.innerWidth-400))+"px"}function je(){const e=A,n=document.getElementById("git-popover-browse");n&&n.addEventListener("click",()=>{if(se(),e){me="files",document.querySelectorAll(".mode-btn").forEach(s=>s.classList.remove("active"));const t=document.getElementById("mode-files");t&&t.classList.add("active"),T(e)}})}let Oe="";function Ue(){if(!m)return;const e=m.files||[];if(!e.length)y.innerHTML=`<div class="git-popover-header">No changes \u2014 clean working tree</div>
11
11
  <div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>`;else{let 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],i=s.additions||0,o=s.deletions||0;let a="";switch(s.status){case"M":a='<span class="git-file-status M">M</span>';break;case"A":a='<span class="git-file-status A">A</span>';break;case"D":a='<span class="git-file-status D">D</span>';break;case"?":a='<span class="git-file-status ?">?</span>';break;case"R":a='<span class="git-file-status R">R</span>';break}n+=`<div class="git-popover-item" data-idx="${t}">
12
12
  ${a}<span class="file-path">${d(s.path)}</span>
13
13
  <span class="file-add">${i>0?"+"+i:""}</span>
14
14
  <span class="file-del">${o>0?"-"+o:""}</span>
15
- </div>`}n+='<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>',_e=n,y.innerHTML=n,y.querySelectorAll(".git-popover-item").forEach(t=>{const s=parseInt(t.dataset.idx||"0",10),i=e[s];!i||i.status==="D"||(t.classList.add("clickable"),t.style.cursor="pointer",t.addEventListener("click",()=>je(i.path)))})}ue(),y.classList.add("open"),ee.classList.add("open"),Ae()}function at(){return window.innerWidth>=1024}function Pe(e,n){const s=(e+(n&&e?`
15
+ </div>`}n+='<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>',Oe=n,y.innerHTML=n,y.querySelectorAll(".git-popover-item").forEach(t=>{const s=parseInt(t.dataset.idx||"0",10),i=e[s];!i||i.status==="D"||(t.classList.add("clickable"),t.style.cursor="pointer",t.addEventListener("click",()=>ze(i.path)))})}ye(),y.classList.add("open"),te.classList.add("open"),je()}function pt(){return window.innerWidth>=1024}function We(e,n){const s=(e+(n&&e?`
16
16
  `:"")+n).split(`
17
- `);let i="",o=0,a=0;for(const l of s){const c=l;if(c.startsWith("@@")){const p=c.match(/@@\s+-(\d+)[^+]*\+(\d+)/);p&&(o=parseInt(p[1],10)-1,a=parseInt(p[2],10)-1),i+=`<div class="diff-line hunk"><span class="ln-body">${d(c)}</span></div>`;continue}if(c.startsWith("diff --git")||c.startsWith("index ")||c.startsWith("--- ")||c.startsWith("+++ ")||c.startsWith("new file")||c.startsWith("deleted file")){c.startsWith("diff --git")&&(i+=`<div class="diff-line header"><span class="ln-body">${d(c)}</span></div>`);continue}if(c.startsWith("+"))a++,i+=`<div class="diff-line add"><span class="ln-no">${a}</span><span class="ln-body">${d(c)}</span></div>`;else if(c.startsWith("-"))o++,i+=`<div class="diff-line del"><span class="ln-no">${o}</span><span class="ln-body">${d(c)}</span></div>`;else if(c.startsWith("\\"))i+=`<div class="diff-line"><span class="ln-body">${d(c)}</span></div>`;else{if(!c&&!o&&!a)continue;o++,a++,i+=`<div class="diff-line"><span class="ln-no">${o}</span><span class="ln-no" style="margin-right:12px">${a}</span><span class="ln-body">${d(c)}</span></div>`}}return{html:i,lineCount:s.length}}let te=null;async function je(e){const n=$;if(n)if(ne(),at()){b.style.display="none",f&&(ie(),f.destroy(),f=null,te=u,u=null),z(null),j.style.display="none",H.style.display="none",Re.style.display="flex",$e.textContent=e,Z.textContent="Loading\u2026",Q.innerHTML="";try{const t=await fetch(v("/api/git/diff?path="+encodeURIComponent(n)+"&file="+encodeURIComponent(e)));if(!t.ok)throw new Error(await t.text());const s=await t.json();ct(e,s.diff,s.stagedDiff)}catch(t){const s=t instanceof Error?t.message:String(t);Z.textContent="Error",Q.innerHTML=`<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">Error: ${d(s)}</div>`}}else{y.innerHTML=`<div class="git-diff-view"><div class="diff-header">
17
+ `);let i="",o=0,a=0;for(const l of s){const c=l;if(c.startsWith("@@")){const f=c.match(/@@\s+-(\d+)[^+]*\+(\d+)/);f&&(o=parseInt(f[1],10)-1,a=parseInt(f[2],10)-1),i+=`<div class="diff-line hunk"><span class="ln-body">${d(c)}</span></div>`;continue}if(c.startsWith("diff --git")||c.startsWith("index ")||c.startsWith("--- ")||c.startsWith("+++ ")||c.startsWith("new file")||c.startsWith("deleted file")){c.startsWith("diff --git")&&(i+=`<div class="diff-line header"><span class="ln-body">${d(c)}</span></div>`);continue}if(c.startsWith("+"))a++,i+=`<div class="diff-line add"><span class="ln-no">${a}</span><span class="ln-body">${d(c)}</span></div>`;else if(c.startsWith("-"))o++,i+=`<div class="diff-line del"><span class="ln-no">${o}</span><span class="ln-body">${d(c)}</span></div>`;else if(c.startsWith("\\"))i+=`<div class="diff-line"><span class="ln-body">${d(c)}</span></div>`;else{if(!c&&!o&&!a)continue;o++,a++,i+=`<div class="diff-line"><span class="ln-no">${o}</span><span class="ln-no" style="margin-right:12px">${a}</span><span class="ln-body">${d(c)}</span></div>`}}return{html:i,lineCount:s.length}}let ne=null;async function ze(e){const n=A;if(n)if(se(),pt()){b.style.display="none",p&&(oe(),p.destroy(),p=null,ne=u,u=null),z(null),j.style.display="none",H.style.display="none",De.style.display="flex",Pe.textContent=e,Q.textContent="Loading\u2026",ee.innerHTML="";try{const t=await fetch(v("/api/git/diff?path="+encodeURIComponent(n)+"&file="+encodeURIComponent(e)));if(!t.ok)throw new Error(await t.text());const s=await t.json();ut(e,s.diff,s.stagedDiff)}catch(t){const s=t instanceof Error?t.message:String(t);Q.textContent="Error",ee.innerHTML=`<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">Error: ${d(s)}</div>`}}else{y.innerHTML=`<div class="git-diff-view"><div class="diff-header">
18
18
  <button class="diff-back">\u2190 Back</button>
19
19
  <span class="diff-filename">${d(e)}</span>
20
20
  <span class="diff-loading">Loading\u2026</span>
21
- </div></div>`,ue(),y.classList.add("open"),ee.classList.add("open");try{const t=await fetch(v("/api/git/diff?path="+encodeURIComponent(n)+"&file="+encodeURIComponent(e)));if(!t.ok)throw new Error(await t.text());const s=await t.json();lt(e,s.diff,s.stagedDiff)}catch(t){const s=t instanceof Error?t.message:String(t);y.innerHTML=`<div class="git-diff-view"><div class="diff-header">
21
+ </div></div>`,ye(),y.classList.add("open"),te.classList.add("open");try{const t=await fetch(v("/api/git/diff?path="+encodeURIComponent(n)+"&file="+encodeURIComponent(e)));if(!t.ok)throw new Error(await t.text());const s=await t.json();ft(e,s.diff,s.stagedDiff)}catch(t){const s=t instanceof Error?t.message:String(t);y.innerHTML=`<div class="git-diff-view"><div class="diff-header">
22
22
  <button class="diff-back">\u2190 Back</button>
23
23
  <span class="diff-filename">${d(e)}</span>
24
- </div><div class="diff-empty">Error loading diff: ${d(s)}</div></div>`}}}function lt(e,n,t){if(!n&&!t){y.innerHTML=`<div class="git-diff-view"><div class="diff-header">
24
+ </div><div class="diff-empty">Error loading diff: ${d(s)}</div></div>`}}}function ft(e,n,t){if(!n&&!t){y.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">${d(e)}</span>
27
- </div><div class="diff-empty">No diff content available</div></div>`;return}const{html:s,lineCount:i}=Pe(n,t);y.innerHTML=`<div class="git-diff-view"><div class="diff-header">
27
+ </div><div class="diff-empty">No diff content available</div></div>`;return}const{html:s,lineCount:i}=We(n,t);y.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">${d(e)}</span>
30
30
  <span class="diff-filesize">${i} lines</span>
31
- </div><div class="diff-content">${s}</div></div>`,y.querySelector(".diff-back")?.addEventListener("click",()=>{y.innerHTML=_e,ue(),m&&y.querySelectorAll(".git-popover-item").forEach(o=>{const a=parseInt(o.dataset.idx||"0",10),l=m.files[a];!l||l.status==="D"||(o.style.cursor="pointer",o.addEventListener("click",()=>je(l.path)))}),Ae()})}function ct(e,n,t){if(!n&&!t){Z.textContent="No diff",Q.innerHTML='<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">No diff content available</div>';return}const{html:s,lineCount:i}=Pe(n,t);$e.textContent=e,Z.textContent=i+" lines",Q.innerHTML=s}function rt(){Re.style.display="none",te?(b.style.display="",b.classList.add("terminal-pending"),U(te),te=null):u?(b.style.display="",b.classList.add("terminal-pending"),Ue()):H.style.display="flex"}ot.addEventListener("click",rt);function ne(){y.classList.remove("open"),ee.classList.remove("open")}ee.addEventListener("click",ne),document.addEventListener("keydown",e=>{e.key==="Escape"&&(ne(),le())});async function Oe(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 i=await s.json();m=i,z(i);return}}}catch{}m=null,z(null)}let se=null;function Ue(){ie(),u&&(Oe(u),se=setInterval(()=>{u&&Oe(u)},3e4))}function ie(){se&&(clearInterval(se),se=null)}function dt(){if(X=D.fsRoots||[],X.length===0){if(u){pt(u);return}r.innerHTML='<div class="file-tree-info">Open a session first, then switch to Files to browse its directory.</div>';return}r.innerHTML="";for(const e of X){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> ${d(e)}`,n.addEventListener("click",()=>M(e)),r.appendChild(n)}}async function pt(e){r.innerHTML='<div class="file-tree-empty">Loading...</div>';try{const t=await(await fetch(v("/api/fs/session-path?session="+encodeURIComponent(e)))).json();t.path?M(t.path):r.innerHTML='<div class="file-tree-info">Could not determine session directory.</div>'}catch{r.innerHTML='<div class="file-tree-error">Failed to get session directory</div>'}}async function M(e){x=e,r.innerHTML='<div class="file-tree-empty">Loading...</div>';const n=st(e);try{const s=await(await fetch(v("/api/fs/list?path="+encodeURIComponent(e)))).json();await n,r.innerHTML="",z(m),r.innerHTML+=it();const i=ft(e);if(i&&!X.some(l=>e===l)){const l=document.createElement("div");l.className="file-tree-item",l.innerHTML="..",l.addEventListener("click",()=>M(i)),r.appendChild(l)}if(s.dirs)for(const a of s.dirs){const l=a.split("/").pop()||a.split("\\").pop(),c=document.createElement("div");c.className="file-tree-item",c.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> ${d(l)}`,c.addEventListener("click",()=>M(a)),r.appendChild(c)}else r.innerHTML="";const o=s.files||[];for(const a of o){const l=a.split("/").pop()||a.split("\\").pop(),c=nt(a);let p="",L="";if(c)switch(c){case"M":p="git-mod",L='<span class="git-file-status M">M</span>';break;case"A":p="git-add",L='<span class="git-file-status A">A</span>';break;case"D":p="git-del",L='<span class="git-file-status D">D</span>';break;case"?":p="git-untracked",L='<span class="git-file-status ?">?</span>';break;case"R":p="git-mod",L='<span class="git-file-status R">R</span>';break}const h=document.createElement("div");h.className="file-tree-item file"+(p?" "+p:""),h.innerHTML=`<span class="file-icon">\u{1F4C4}</span> ${L}${d(l)}`,h.addEventListener("click",()=>ut(a)),r.appendChild(h)}}catch{r.innerHTML='<div class="file-tree-error">Failed to load directory</div>'}}function ft(e){const n=e.lastIndexOf("/");return n<=0?null:e.substring(0,n)}async function ut(e){V=e,b.style.display="none",f&&(ie(),f.destroy(),f=null,u=null),z(null),Y(),H.style.display="none",j.style.display="flex",Ve.textContent=e,E.textContent="Loading...",N.style.display="none";try{const n=await fetch(v("/api/file?path="+encodeURIComponent(e)));if(!n.ok){const s=await n.json();E.textContent=s.error||"Failed to load",O.value="";return}const t=await n.json();O.value=t.content,J=t.content,we=t.content,E.textContent=t.size+" bytes",N.style.display=""}catch{E.textContent="Failed to load",O.value=""}}O.addEventListener("input",()=>{J=O.value}),N.addEventListener("click",async()=>{N.textContent="Saving...",N.disabled=!0;try{const e=await fetch(v("/api/file"),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:V,content:J})});if(!e.ok){const n=await e.json();E.textContent=n.error||"Save failed";return}we=J,E.textContent="Saved"}catch{E.textContent="Save failed"}finally{N.disabled=!1,N.textContent="Save"}}),Je.addEventListener("click",async()=>{if(confirm("Delete "+V+"?"))try{const e=await fetch(v("/api/file/delete"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:V})});if(!e.ok){const n=await e.json();E.textContent=n.error||"Delete failed";return}j.style.display="none",H.style.display="flex",x&&M(x)}catch{E.textContent="Delete failed"}}),Ke.addEventListener("click",()=>{j.style.display="none",H.style.display="flex",x&&M(x)}),Ye.addEventListener("click",async()=>{const e=Le.value.trim();if(!e)return;const n=x+"/"+e;try{const t=await fetch(v("/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}Le.value="",x&&M(x)}catch{E.textContent="Create failed"}});const oe=document.getElementById("force-narrow-toggle");oe&&(oe.checked=K(),oe.addEventListener("change",()=>{try{localStorage.setItem(Se,oe.checked?"1":"0")}catch{}Ce(),I()})),Ce(),document.getElementById("mode-settings").addEventListener("click",()=>{const e=Ee.classList.toggle("open");pe.classList.toggle("open",e)}),pe.addEventListener("click",()=>{Ee.classList.remove("open"),pe.classList.remove("open")});let w="",B=!1,k;const F=document.createElement("div");F.className="session-popover-backdrop",document.body.appendChild(F);const S=document.createElement("div");S.id="session-popover",S.className="session-popover",S.style.display="none",S.innerHTML=`<div class="sp-field">
31
+ </div><div class="diff-content">${s}</div></div>`,y.querySelector(".diff-back")?.addEventListener("click",()=>{y.innerHTML=Oe,ye(),m&&y.querySelectorAll(".git-popover-item").forEach(o=>{const a=parseInt(o.dataset.idx||"0",10),l=m.files[a];!l||l.status==="D"||(o.style.cursor="pointer",o.addEventListener("click",()=>ze(l.path)))}),je()})}function ut(e,n,t){if(!n&&!t){Q.textContent="No diff",ee.innerHTML='<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">No diff content available</div>';return}const{html:s,lineCount:i}=We(n,t);Pe.textContent=e,Q.textContent=i+" lines",ee.innerHTML=s}function mt(){De.style.display="none",ne?(b.style.display="",b.classList.add("terminal-pending"),U(ne),ne=null):u?(b.style.display="",b.classList.add("terminal-pending"),Ge()):H.style.display="flex"}dt.addEventListener("click",mt);function se(){y.classList.remove("open"),te.classList.remove("open")}te.addEventListener("click",se),document.addEventListener("keydown",e=>{e.key==="Escape"&&(se(),pe())});async function Fe(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 i=await s.json();m=i,z(i);return}}}catch{}m=null,z(null)}let ie=null;function Ge(){oe(),u&&(Fe(u),ie=setInterval(()=>{u&&Fe(u)},3e4))}function oe(){ie&&(clearInterval(ie),ie=null)}function gt(){if(Z=D.fsRoots||[],Z.length===0){if(u){vt(u);return}r.innerHTML='<div class="file-tree-info">Open a session first, then switch to Files to browse its directory.</div>';return}r.innerHTML="";for(const e of Z){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> ${d(e)}`,n.addEventListener("click",()=>T(e)),r.appendChild(n)}}async function vt(e){r.innerHTML='<div class="file-tree-empty">Loading...</div>';try{const t=await(await fetch(v("/api/fs/session-path?session="+encodeURIComponent(e)))).json();t.path?T(t.path):r.innerHTML='<div class="file-tree-info">Could not determine session directory.</div>'}catch{r.innerHTML='<div class="file-tree-error">Failed to get session directory</div>'}}async function T(e){x=e,r.innerHTML='<div class="file-tree-empty">Loading...</div>';const n=ct(e);try{const s=await(await fetch(v("/api/fs/list?path="+encodeURIComponent(e)))).json();await n,r.innerHTML="",z(m),r.innerHTML+=rt();const i=yt(e);if(i&&!Z.some(l=>e===l)){const l=document.createElement("div");l.className="file-tree-item",l.innerHTML="..",l.addEventListener("click",()=>T(i)),r.appendChild(l)}if(s.dirs)for(const a of s.dirs){const l=a.split("/").pop()||a.split("\\").pop(),c=document.createElement("div");c.className="file-tree-item",c.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> ${d(l)}`,c.addEventListener("click",()=>T(a)),r.appendChild(c)}else r.innerHTML="";const o=s.files||[];for(const a of o){const l=a.split("/").pop()||a.split("\\").pop(),c=lt(a);let f="",L="";if(c)switch(c){case"M":f="git-mod",L='<span class="git-file-status M">M</span>';break;case"A":f="git-add",L='<span class="git-file-status A">A</span>';break;case"D":f="git-del",L='<span class="git-file-status D">D</span>';break;case"?":f="git-untracked",L='<span class="git-file-status ?">?</span>';break;case"R":f="git-mod",L='<span class="git-file-status R">R</span>';break}const h=document.createElement("div");h.className="file-tree-item file"+(f?" "+f:""),h.innerHTML=`<span class="file-icon">\u{1F4C4}</span> ${L}${d(l)}`,h.addEventListener("click",()=>ht(a)),r.appendChild(h)}}catch{r.innerHTML='<div class="file-tree-error">Failed to load directory</div>'}}function yt(e){const n=e.lastIndexOf("/");return n<=0?null:e.substring(0,n)}async function ht(e){J=e,b.style.display="none",p&&(oe(),p.destroy(),p=null,u=null),z(null),X(),H.style.display="none",j.style.display="flex",Ze.textContent=e,E.textContent="Loading...",R.style.display="none";try{const n=await fetch(v("/api/file?path="+encodeURIComponent(e)));if(!n.ok){const s=await n.json();E.textContent=s.error||"Failed to load",O.value="";return}const t=await n.json();O.value=t.content,K=t.content,Se=t.content,E.textContent=t.size+" bytes",R.style.display=""}catch{E.textContent="Failed to load",O.value=""}}O.addEventListener("input",()=>{K=O.value}),R.addEventListener("click",async()=>{R.textContent="Saving...",R.disabled=!0;try{const e=await fetch(v("/api/file"),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:J,content:K})});if(!e.ok){const n=await e.json();E.textContent=n.error||"Save failed";return}Se=K,E.textContent="Saved"}catch{E.textContent="Save failed"}finally{R.disabled=!1,R.textContent="Save"}}),Qe.addEventListener("click",async()=>{if(confirm("Delete "+J+"?"))try{const e=await fetch(v("/api/file/delete"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:J})});if(!e.ok){const n=await e.json();E.textContent=n.error||"Delete failed";return}j.style.display="none",H.style.display="flex",x&&T(x)}catch{E.textContent="Delete failed"}}),et.addEventListener("click",()=>{j.style.display="none",H.style.display="flex",x&&T(x)}),tt.addEventListener("click",async()=>{const e=Ce.value.trim();if(!e)return;const n=x+"/"+e;try{const t=await fetch(v("/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}Ce.value="",x&&T(x)}catch{E.textContent="Create failed"}});const ae=document.getElementById("force-narrow-toggle");ae&&(ae.checked=Y(),ae.addEventListener("change",()=>{try{localStorage.setItem(xe,ae.checked?"1":"0")}catch{}Te(),I()})),Te(),document.getElementById("mode-settings").addEventListener("click",()=>{const e=Ie.classList.toggle("open");ge.classList.toggle("open",e)}),ge.addEventListener("click",()=>{Ie.classList.remove("open"),ge.classList.remove("open")});let w="",B=!1,k;const F=document.createElement("div");F.className="session-popover-backdrop",document.body.appendChild(F);const S=document.createElement("div");S.id="session-popover",S.className="session-popover",S.style.display="none",S.innerHTML=`<div class="sp-field">
32
32
  <label>Rename session</label>
33
33
  <input type="text" id="sp-name" />
34
34
  </div>
@@ -38,5 +38,5 @@ import{initTerminal as qe}from"./terminal-core.js";const D=window.__TMUX_WEB_SHE
38
38
  </div>
39
39
  <hr class="sp-divider" />
40
40
  <button class="btn primary" id="sp-rebuild" style="display:none">\u91CD\u5EFA\u540C\u540D\u540C\u8DEF\u5F84 session</button>
41
- <button class="btn danger" id="sp-delete">Delete session</button>`,document.body.appendChild(S);function mt(e){const n=e.getBoundingClientRect(),t=window.innerHeight,s=S.offsetHeight||240;let i=n.bottom+4;i+s>t-8&&(i=Math.max(8,n.top-s-4)),S.style.top=i+"px",S.style.left=Math.max(8,Math.min(n.left,window.innerWidth-240))+"px"}function ae(e,n,t){w=e,B=!!t?.tombstone,k=t?.agentId;const s=document.getElementById("sp-name");s.value=e;const i=S.querySelector(".sp-field label");i.textContent=B?"\u91CD\u547D\u540D (\u4EC5\u8BB0\u5F55\uFF0C\u4E0D\u91CD\u5EFA)":"Rename session";const o=document.getElementById("sp-rebuild");o.style.display=B?"":"none";const a=document.getElementById("sp-delete");a.textContent=B?"\u5220\u9664\u5931\u6548\u8BB0\u5F55 (\u5893\u7891\u6D88\u5931)":"Delete session";const l=document.getElementById("sp-save");l.textContent=B?"\u91CD\u547D\u540D":"Save",F.classList.add("open"),S.style.display="block",mt(n),setTimeout(()=>s.focus(),50)}function R(){F.classList.remove("open"),S.style.display="none"}F.addEventListener("click",R),document.getElementById("sp-save").addEventListener("click",async()=>{const e=document.getElementById("sp-name").value.trim();if(!e||e===w){R();return}try{const n=B?{oldName:w,newName:e,agentId:k}:{oldName:w,newName:e,...k?{agentId:k}:{}};if(!(await fetch(v(B?"/api/sessions/rename-tombstone":"/api/sessions/rename"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).ok)return;R(),I(),!B&&u===w&&(k??null)===g&&U(e,k)}catch{}}),document.getElementById("sp-rebuild").addEventListener("click",async()=>{if(confirm('\u91CD\u5EFA\u4F1A\u8BDD "'+w+'" (\u540C\u540D\u540C\u8DEF\u5F84\uFF0C\u5185\u5BB9\u4E3A\u7A7A)\uFF1F'))try{const e=await fetch(v("/api/sessions/rebuild"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:w,agentId:k})});if(!e.ok){const n=await e.json();alert(n.error||"\u91CD\u5EFA\u5931\u8D25");return}R(),I()}catch{}}),document.getElementById("sp-delete").addEventListener("click",async()=>{if(B){if(!confirm('\u5220\u9664\u5931\u6548\u8BB0\u5F55 "'+w+'"\uFF1F'))return;try{if(!(await fetch(v("/api/sessions/dismiss"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:w,agentId:k})})).ok)return;R(),I()}catch{}return}if(confirm('Delete session "'+w+'"?'))try{if(!(await fetch(v("/api/sessions/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:w,...k?{agentId:k}:{}})})).ok)return;R(),u===w&&(k??null)===g&&(f&&(f.destroy(),f=null),u=null,b.style.display="none",H.style.display="flex"),I()}catch{}}),document.getElementById("sp-cancel").addEventListener("click",R);const gt={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=gt[n.dataset.key];t&&(f.sendInput(t),f.focus())});const C=document.getElementById("mk-input"),We=document.getElementById("mk-send");function ze(){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(`
42
- `).length;C.rows=Math.min(e,4)}),C.addEventListener("keydown",e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),ze())})),We&&We.addEventListener("click",ze),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 me=document.getElementById("process-panel"),G=document.getElementById("proc-list"),vt=document.getElementById("proc-close"),ge=document.getElementById("proc-backdrop"),yt=document.getElementById("header-ram");function ht(){G.innerHTML='<div class="proc-empty">Loading\u2026</div>',fetch(v("/api/system/processes")).then(e=>e.json()).then(e=>{if(!Array.isArray(e)||!e.length){G.innerHTML='<div class="proc-empty">No processes</div>';return}let n="";for(const t of e){const s=t.rss,i=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">'+i+'</span><span class="proc-cmd" title="'+d(t.command)+'">'+d(t.command)+'</span><button class="proc-kill" title="Kill PID '+t.pid+'">&times;</button></div>'}G.innerHTML=n;for(const t of G.querySelectorAll(".proc-row")){const s=t.querySelector(".proc-kill");s&&s.addEventListener("click",i=>{const o=i.target.closest(".proc-row");!o||!confirm("Kill PID "+o.dataset.pid+"?")||fetch(v("/api/system/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:parseInt(o.dataset.pid,10)})}).then(a=>a.json()).then(a=>{a.ok?o.style.opacity="0.3":alert("Failed: "+(a.error||"unknown"))}).catch(()=>alert("Network error"))})}}).catch(()=>{G.innerHTML='<div class="proc-empty">Failed to load</div>'})}function bt(){me.classList.add("open"),ge.classList.add("open"),ht()}function le(){me.classList.remove("open"),ge.classList.remove("open")}yt.addEventListener("click",e=>{e.stopPropagation(),me.classList.contains("open")?le():bt()}),vt.addEventListener("click",le),ge.addEventListener("click",le);const wt=2e3;let q=null,ve=null;const A=new Map,_=new Map,Lt=5e3,Fe=new Map;function ye(e,n){return(n?"a:"+n+":":"l:")+e}function Et(e,n,t){const s=ye(e,n);if(t==="working"){const p=Fe.get(s);if(p&&Date.now()<p)return}const i=_.get(s),o=e===u&&(n??null)===g,a=t==="idle"&&i?.state==="working";_.set(s,{session:e,agentId:n,state:t,doneUntil:a?Date.now()+wt:void 0,unread:a?!o:!1});const l=n?'.session-item[data-agent="'+CSS.escape(n)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',c=r.querySelector(l);c&&ce(c,s,_.get(s))}function ce(e,n,t){const s=A.get(n);s&&(clearTimeout(s),A.delete(n)),e.classList.remove("working","just-done");const i=t.session===u&&(t.agentId??null)===g;t.state==="working"?e.classList.add("working"):i&&t.doneUntil&&Date.now()<t.doneUntil?(e.classList.add("just-done"),A.set(n,setTimeout(()=>{e.classList.remove("just-done"),A.delete(n)},Math.max(0,t.doneUntil-Date.now())))):!i&&t.unread&&e.classList.add("just-done")}function he(){for(const[e,n]of _){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=r.querySelector(t);s&&ce(s,e,n)}}function kt(e,n){const t=ye(e,n),s=_.get(t);if(!s)return;const i=A.get(t);i&&(clearTimeout(i),A.delete(t)),s.doneUntil=void 0,s.unread=!1;const o=n?'.session-item[data-agent="'+CSS.escape(n)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',a=r.querySelector(o);a&&ce(a,t,s)}function Ge(){if(q||ve)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);q=s,s.onmessage=i=>{try{const o=JSON.parse(String(i.data));o&&o.type==="session.activity"&&typeof o.session=="string"&&Et(o.session,o.agentId||void 0,o.state==="working"?"working":"idle")}catch{}},s.onclose=()=>{q===s&&(q=null,ve=setTimeout(()=>{ve=null,Ge()},5e3))},s.onerror=()=>{try{s.close()}catch{}}}catch{q=null}}window.__openSession=U,window.__refreshSidebar=I,I(),Y(),he(),Ge(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&he()}),setInterval(()=>{document.visibilityState==="visible"&&I()},1e4);
41
+ <button class="btn danger" id="sp-delete">Delete session</button>`,document.body.appendChild(S);function bt(e){const n=e.getBoundingClientRect(),t=window.innerHeight,s=S.offsetHeight||240;let i=n.bottom+4;i+s>t-8&&(i=Math.max(8,n.top-s-4)),S.style.top=i+"px",S.style.left=Math.max(8,Math.min(n.left,window.innerWidth-240))+"px"}function le(e,n,t){w=e,B=!!t?.tombstone,k=t?.agentId;const s=document.getElementById("sp-name");s.value=e;const i=S.querySelector(".sp-field label");i.textContent=B?"\u91CD\u547D\u540D (\u4EC5\u8BB0\u5F55\uFF0C\u4E0D\u91CD\u5EFA)":"Rename session";const o=document.getElementById("sp-rebuild");o.style.display=B?"":"none";const a=document.getElementById("sp-delete");a.textContent=B?"\u5220\u9664\u5931\u6548\u8BB0\u5F55 (\u5893\u7891\u6D88\u5931)":"Delete session";const l=document.getElementById("sp-save");l.textContent=B?"\u91CD\u547D\u540D":"Save",F.classList.add("open"),S.style.display="block",bt(n),setTimeout(()=>s.focus(),50)}function N(){F.classList.remove("open"),S.style.display="none"}F.addEventListener("click",N),document.getElementById("sp-save").addEventListener("click",async()=>{const e=document.getElementById("sp-name").value.trim();if(!e||e===w){N();return}try{const n=B?{oldName:w,newName:e,agentId:k}:{oldName:w,newName:e,...k?{agentId:k}:{}};if(!(await fetch(v(B?"/api/sessions/rename-tombstone":"/api/sessions/rename"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).ok)return;N(),I(),!B&&u===w&&(k??null)===g&&U(e,k)}catch{}}),document.getElementById("sp-rebuild").addEventListener("click",async()=>{if(confirm('\u91CD\u5EFA\u4F1A\u8BDD "'+w+'" (\u540C\u540D\u540C\u8DEF\u5F84\uFF0C\u5185\u5BB9\u4E3A\u7A7A)\uFF1F'))try{const e=await fetch(v("/api/sessions/rebuild"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:w,agentId:k})});if(!e.ok){const n=await e.json();alert(n.error||"\u91CD\u5EFA\u5931\u8D25");return}N(),I()}catch{}}),document.getElementById("sp-delete").addEventListener("click",async()=>{if(B){if(!confirm('\u5220\u9664\u5931\u6548\u8BB0\u5F55 "'+w+'"\uFF1F'))return;try{if(!(await fetch(v("/api/sessions/dismiss"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:w,agentId:k})})).ok)return;N(),I()}catch{}return}if(confirm('Delete session "'+w+'"?'))try{if(!(await fetch(v("/api/sessions/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:w,...k?{agentId:k}:{}})})).ok)return;N(),u===w&&(k??null)===g&&(p&&(p.destroy(),p=null),u=null,b.style.display="none",H.style.display="flex"),I()}catch{}}),document.getElementById("sp-cancel").addEventListener("click",N);const qe={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"},ce=document.getElementById("mobile-keys"),wt=new Set(["up","down","left","right","tab","s-tab","space"]),Lt=400,Et=80;let G=0,re=0,de=!1;function kt(){G&&(clearTimeout(G),G=0),re&&(clearInterval(re),re=0)}ce.addEventListener("mousedown",e=>{e.target.closest("button[data-key]")&&e.preventDefault()}),ce.addEventListener("pointerdown",e=>{const n=e.target.closest("button[data-key]");if(!n)return;const t=n.dataset.key;wt.has(t)&&(de=!1,G=setTimeout(()=>{G=0,de=!0,re=setInterval(()=>{const s=qe[t];s&&p&&p.sendInput(s)},Et)},Lt))});for(const e of["pointerup","pointercancel","pointerleave"])ce.addEventListener(e,kt);ce.addEventListener("click",e=>{const n=e.target.closest("button[data-key]");if(!n||!p)return;if(de){de=!1;return}const t=qe[n.dataset.key];t&&(p.sendInput(t),p.focus())});const C=document.getElementById("mk-input"),Ve=document.getElementById("mk-send");function Je(){if(!C||!p)return;const e=C.value;e&&(p.sendInput(e+"\r"),C.value="",C.rows=1,p.focus())}if(C&&(C.addEventListener("input",()=>{C.rows=1;const e=C.value.split(`
42
+ `).length;C.rows=Math.min(e,4)}),C.addEventListener("keydown",e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),Je())})),Ve&&Ve.addEventListener("click",Je),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 he=document.getElementById("process-panel"),q=document.getElementById("proc-list"),St=document.getElementById("proc-close"),be=document.getElementById("proc-backdrop"),Ct=document.getElementById("header-ram");function It(){q.innerHTML='<div class="proc-empty">Loading\u2026</div>',fetch(v("/api/system/processes")).then(e=>e.json()).then(e=>{if(!Array.isArray(e)||!e.length){q.innerHTML='<div class="proc-empty">No processes</div>';return}let n="";for(const t of e){const s=t.rss,i=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">'+i+'</span><span class="proc-cmd" title="'+d(t.command)+'">'+d(t.command)+'</span><button class="proc-kill" title="Kill PID '+t.pid+'">&times;</button></div>'}q.innerHTML=n;for(const t of q.querySelectorAll(".proc-row")){const s=t.querySelector(".proc-kill");s&&s.addEventListener("click",i=>{const o=i.target.closest(".proc-row");!o||!confirm("Kill PID "+o.dataset.pid+"?")||fetch(v("/api/system/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:parseInt(o.dataset.pid,10)})}).then(a=>a.json()).then(a=>{a.ok?o.style.opacity="0.3":alert("Failed: "+(a.error||"unknown"))}).catch(()=>alert("Network error"))})}}).catch(()=>{q.innerHTML='<div class="proc-empty">Failed to load</div>'})}function Bt(){he.classList.add("open"),be.classList.add("open"),It()}function pe(){he.classList.remove("open"),be.classList.remove("open")}Ct.addEventListener("click",e=>{e.stopPropagation(),he.classList.contains("open")?pe():Bt()}),St.addEventListener("click",pe),be.addEventListener("click",pe);const xt=2e3;let V=null,we=null;const _=new Map,$=new Map,Tt=5e3,Ke=new Map;function Le(e,n){return(n?"a:"+n+":":"l:")+e}function Mt(e,n,t){const s=Le(e,n);if(t==="working"){const f=Ke.get(s);if(f&&Date.now()<f)return}const i=$.get(s),o=e===u&&(n??null)===g,a=t==="idle"&&i?.state==="working";$.set(s,{session:e,agentId:n,state:t,doneUntil:a?Date.now()+xt:void 0,unread:a?!o:!1});const l=n?'.session-item[data-agent="'+CSS.escape(n)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',c=r.querySelector(l);c&&fe(c,s,$.get(s))}function fe(e,n,t){const s=_.get(n);s&&(clearTimeout(s),_.delete(n)),e.classList.remove("working","just-done");const i=t.session===u&&(t.agentId??null)===g;t.state==="working"?e.classList.add("working"):i&&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())))):!i&&t.unread&&e.classList.add("just-done")}function Ee(){for(const[e,n]of $){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=r.querySelector(t);s&&fe(s,e,n)}}function Ht(e,n){const t=Le(e,n),s=$.get(t);if(!s)return;const i=_.get(t);i&&(clearTimeout(i),_.delete(t)),s.doneUntil=void 0,s.unread=!1;const o=n?'.session-item[data-agent="'+CSS.escape(n)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',a=r.querySelector(o);a&&fe(a,t,s)}function Ye(){if(V||we)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);V=s,s.onmessage=i=>{try{const o=JSON.parse(String(i.data));o&&o.type==="session.activity"&&typeof o.session=="string"&&Mt(o.session,o.agentId||void 0,o.state==="working"?"working":"idle")}catch{}},s.onclose=()=>{V===s&&(V=null,we=setTimeout(()=>{we=null,Ye()},5e3))},s.onerror=()=>{try{s.close()}catch{}}}catch{V=null}}window.__openSession=U,window.__refreshSidebar=I,I(),X(),Ee(),Ye(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&Ee()}),setInterval(()=>{document.visibilityState==="visible"&&I()},1e4);
@@ -1,8 +1,8 @@
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
1
+ const Xt=/\x1b\](?:10|11|110|111|104)(?:;[^\x07\x1b]*)?\x1b?(?:\\|\x07)/g;function ot(s){return s.replace(/\x1b\[\?1049[hl]/g,"")}function H(s){return s.replace(Xt,"")}let W;function Ht(){return W||(document.querySelector("link[data-tmux-web-xterm-css]")?W=Promise.resolve():(W=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)}),W))}class rt{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(qt()==="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:c}]=await Promise.all([import("@xterm/xterm"),import("@xterm/addon-fit"),Ht()]),m="'JetBrains Mono', 'SF Mono', 'Menlo', monospace",a=new l({fontSize:Wt(14,m),fontFamily:m,cursorBlink:!0,cursorStyle:"bar",scrollback:o,convertEol:!1,smoothScrollDuration:120,theme:n});return new rt(i,a,new c)}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=_t(this.container);if(i.width<=0||i.height<=0)return!1;const o=this.terminal.cols,n=this.terminal.rows;let l=this.paintedCellWidth();l<=0&&(this.fitAddon.fit(),l=this.paintedCellWidth());const c=this.fitAddon.proposeDimensions?.();if(!c)return this.fitAddon.fit(),!0;const m=this.overlayScrollbarWidth(),a=m>0?m+2:0,u=l>0?Math.max(10,Math.min(c.cols,Math.floor((i.width-a)/l))):c.cols,h=c.rows;return(u!==this.terminal.cols||h!==this.terminal.rows)&&this.terminal.resize(u,h),this.webglActive&&(o!==this.terminal.cols||n!==this.terminal.rows)&&this.refreshPaintedRows(),!0}paintedCellWidth(){const o=this.terminal.element?.querySelector(".xterm-screen")?.getBoundingClientRect().width??0,n=this.terminal.cols;return o>0&&n>0?o/n:0}overlayScrollbarWidth(){const i=this.terminal.element?.querySelector(".vertical.scrollbar");if(!i)return 0;const o=i.getBoundingClientRect();return!(o.width>0)||!(o.height>0)?0:Math.round(o.width)}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,c]=i<=o?[i,o]:[o,i],m=n.viewportY,a=[];for(let u=l;u<=c;u++){const h=n.getLine(m+u);a.push(h?h.translateToString(!0):"")}return a.join(`
2
+ `)}selectRows(i,o){const n=this.terminal.buffer.active,[l,c]=i<=o?[i,o]:[o,i];this.terminal.selectLines(n.viewportY+l,n.viewportY+c)}selectCells(i,o,n,l){const c=this.terminal.buffer.active,m=Math.min(o,l),a=Math.max(o,l);if(m===a){const u=Math.min(i,n),h=Math.max(i,n);this.terminal.select(u,c.viewportY+m,h-u+1)}else this.terminal.selectLines(c.viewportY+m,c.viewportY+a)}getCellsText(i,o,n,l){const c=this.terminal.buffer.active,m=Math.min(o,l),a=Math.max(o,l),u=o<l?i:o>l?n:Math.min(i,n),h=o<l?n:o>l?i:Math.max(i,n),P=c.viewportY,A=[];for(let E=m;E<=a;E++){const q=c.getLine(P+E);if(!q){A.push("");continue}const g=E===m?u:0,M=E===a?h:this.terminal.cols-1;let F="";for(let _=g;_<=M;_++){const L=q.getCell(_);L&&(F+=L.getChars())}A.push(F.replace(/\s+$/,""))}return A.join(`
3
+ `)}getSelection(){return this.terminal.getSelection()}clearSelection(){this.terminal.clearSelection()}hasSelectionSupport(){return!0}}function Wt(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 c=window.devicePixelRatio||1;let m=s,a=Number.POSITIVE_INFINITY;for(let u=4;u<=40;u++){const h=u/(l*c);if(h<s-1.5||h>s+1.5)continue;const P=Math.abs(h-s);P<a&&(a=P,m=h)}return Math.round(m*100)/100}catch{return s}}function qt(){try{const s=new URLSearchParams(window.location.search).get("renderer");return s==="dom"||s==="webgl"?s:null}catch{return null}}function _t(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 Vt(s,i,o){return s.innerHTML="",s.classList.add("terminal-pending"),(async()=>{const n=await rt.create(s,o.scrollback,o.theme);let l,c=0,m,a=null,u=0,h=0;const P=.2,A=10,E=.95,q=.04;let g=null,M=null;function F(t){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=t?"\u2191 \u4E0A\u7FFB\u4E00\u9875 (PgUp)":"\u2193 \u4E0B\u7FFB\u4E00\u9875 (PgDn)",g.style.top=t?"10%":"auto",g.style.bottom=t?"auto":"10%",g.style.opacity="1",M&&clearTimeout(M),M=setTimeout(()=>{g&&(g.style.opacity="0")},900)}function _(){M&&clearTimeout(M),g&&(g.style.opacity="0")}function L(){u&&(cancelAnimationFrame(u),u=0),h=0}function gt(t){if(L(),Math.abs(t)<P)return;h=Math.max(-A,Math.min(A,t));const e=()=>{if(C){u=0;return}const r=n.cellHeight();let f=r>0?Math.round(h*16/r):h>0?1:-1;f===0&&(f=h>0?1:-1);const v=n.viewportY()-f,x=n.baseY(),X=Math.max(0,Math.min(v,x));if(n.scrollToLine(X,!0),h*=E,X!==v){u=0;return}if(Math.abs(h)<q){u=0;return}u=requestAnimationFrame(e)};u=requestAnimationFrame(e)}let j=0,b="connecting",V=0,R=!1,J=[],I="",C=!1,z=1e3;const yt=location.protocol==="https:"?"wss:":"ws:",st=o.wsBase||"/ws",vt=yt+"//"+location.host+st+"/"+encodeURIComponent(i),bt=(st.replace(/^\/ws/,"")||"")+"/api/session/"+encodeURIComponent(i)+"/upload",Tt=/^((?!chrome|android|crios|fxios|edgios).)*safari/i.test(navigator.userAgent);function xt(){return J.join("")+I}async function Ct(t,e=0){const r=t?n.viewportY():0,f=H(xt());if(n.reset(),!f){t||n.scrollToBottom();return}await n.write(f),t?n.scrollToLine(e+r):n.scrollToBottom()}function S(t){l?.readyState===WebSocket.OPEN&&l.send(JSON.stringify(t))}function Et(t){let e;try{e=JSON.parse(t)}catch{b==="live"&&(I+=t,n.write(H(t)));return}if(e.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(e.type==="attach_failed"&&typeof e.message=="string"){$=!0,b="dead",n.reset(),n.write(`\r
4
+ \x1B[31m`+H(e.message)+`\x1B[0m\r
5
+ `).then(()=>{G();try{l?.close()}catch{}});return}if(e.type==="auth.ok"){e.token&&localStorage.setItem("tmux-web-token",e.token),z=1e3,D(),S({type:"resize",cols:n.cols,rows:n.rows}),y();return}if(e.type==="auth.failed"){if(e.permanentLock||e.retryAfterMs&&e.retryAfterMs>6e4){localStorage.removeItem("tmux-web-token"),location.href="/login?error="+encodeURIComponent(e.message);return}return}if(e.type==="snapshot"&&typeof e.data=="string"){const r=ot(H(e.data));J=[r],I="",V=typeof e.lines=="number"?e.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(e.type==="window_changed"&&typeof e.activeIndex=="number"){const r=new URL(location.href);r.searchParams.get("window")!==String(e.activeIndex)&&(r.searchParams.set("window",String(e.activeIndex)),history.replaceState(history.state,"",r)),window.dispatchEvent(new CustomEvent("tmux:windows",{detail:e.windows}));return}if(e.type==="history"&&typeof e.data=="string"){e.lines>0&&e.data?(J.unshift(ot(e.data)),V+=e.lines,Ct(!0,e.lines).finally(()=>{R=!1})):R=!1;return}if(e.type==="data"&&typeof e.data=="string"){const r=ot(H(e.data));if(b==="connecting"){b="live",I=r,n.write(r);return}b==="live"&&(I+=r,n.write(r))}}let $=!1;function at(){if($)return;let t=vt;const e=localStorage.getItem("tmux-web-token");e&&(t+=(t.includes("?")?"&":"?")+"token="+encodeURIComponent(e)),t+=(t.includes("?")?"&":"?")+"cols="+n.cols+"&rows="+n.rows,l=new WebSocket(t),l.onopen=()=>{b="connecting",V=0,R=!1,J=[],I="",n.reset(),z=1e3},l.onmessage=r=>{typeof r.data=="string"&&Et(r.data)},l.onclose=()=>{C||(b="connecting",!$&&setTimeout(()=>{z=Math.min(z*2,1e4),!C&&!$&&at()},z))},l.onerror=()=>l?.close()}function k(t){S({type:"input",data:t})}function D(){return n.fit()}function G(){s.classList.remove("terminal-pending")}function y(){c&&cancelAnimationFrame(c),m&&clearTimeout(m),D(),c=requestAnimationFrame(()=>{c=0,D()&&G()}),m=setTimeout(()=>{D()&&G()},120)}function Mt(){y(),setTimeout(y,50),setTimeout(y,150),setTimeout(y,300)}function lt(t){return typeof t=="string"&&t.startsWith("image/")}function ct(t){return t?.files?.length?t.files[0]??null:null}function Lt(t){if(!t?.items)return null;for(let e=0;e<t.items.length;e++){const r=t.items[e];if(r?.kind==="file"&&lt(r.type))return r.getAsFile()}return null}async function St(t){const e=new FormData,r=t instanceof File&&t.name?t.name:"upload";e.append("file",t,r);const f=localStorage.getItem("tmux-web-token"),d={};f&&(d.Authorization="Bearer "+f);const v=await fetch(bt,{method:"POST",body:e,headers:d});if(!v.ok){let X="upload failed";try{const wt=await v.json();wt.error&&(X=wt.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 et(t){try{const e=await St(t);k(e)}catch{}}n.onData(t=>k(t)),n.onResize(({cols:t,rows:e})=>S({type:"resize",cols:t,rows:e})),n.onScroll(()=>{b!=="live"||R||!n.isNearScrollbackTop()||(R=!0,S({type:"load_history",before:V}))});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 ut(t,e){const r=s.querySelector(".xterm-screen, canvas"),d=(r&&r.getBoundingClientRect().width>0?r:s).getBoundingClientRect(),v=d.height>0&&n.rows>0?d.height/n.rows:18,x=d.width>0&&n.cols>0?d.width/n.cols:9;return{row:Math.max(0,Math.min(n.rows-1,Math.floor((e-d.top)/v))),col:Math.max(0,Math.min(n.cols-1,Math.floor((t-d.left)/x)))}}async function Q(t){if(!t)return;try{if(navigator.clipboard?.writeText){await navigator.clipboard.writeText(t);return}}catch{}const e=document.createElement("textarea");e.value=t,e.style.position="fixed",e.style.opacity="0",e.style.pointerEvents="none",document.body.appendChild(e),e.focus(),e.select();try{document.execCommand("copy")}catch{}e.remove()}let N;function Z(){T.hidden=!1,N&&clearTimeout(N),N=setTimeout(()=>{T.hidden=!0},1e3)}function Y(t){B=t,U.hidden=!t,s.classList.toggle("terminal-copy-mode-active",t),t&&n.focus()}function dt(){Y(!B)}function Dt(t){C||t.button!==0||K||(B||t.shiftKey)&&(t.preventDefault(),t.stopPropagation(),K=!0,p=ut(t.clientX,t.clientY),w=p,n.selectCells(p.col,p.row,w.col,w.row),document.addEventListener("mousemove",nt,!0),document.addEventListener("mouseup",it,!0))}function nt(t){C||!K||!p||(t.preventDefault(),t.stopPropagation(),w=ut(t.clientX,t.clientY),n.selectCells(p.col,p.row,w.col,w.row))}function it(t){if(C||!K||!p||!w)return;t.preventDefault(),t.stopPropagation(),document.removeEventListener("mousemove",nt,!0),document.removeEventListener("mouseup",it,!0),K=!1;const e=n.getCellsText(p.col,p.row,w.col,w.row);p=null,w=null,n.clearSelection(),Y(!1),e&&(T.textContent="\u5DF2\u590D\u5236",Q(e).then(Z)),n.focus()}s.addEventListener("mousedown",Dt,!0),document.addEventListener("keydown",Pt,!0);function Pt(t){if(!(C||!n.isFocused()||t.defaultPrevented||t.isComposing)){if(B){if(t.key==="Escape"){t.preventDefault(),t.stopPropagation(),p=null,w=null,n.clearSelection(),Y(!1);return}if(t.key==="Enter"||(t.ctrlKey||t.metaKey)&&t.code==="KeyC"){t.preventDefault(),t.stopPropagation(),Q(n.getScreenText()).then(Z),Y(!1);return}}if(t.altKey&&t.code==="KeyC"&&!t.ctrlKey&&!t.metaKey){if(t.preventDefault(),t.stopPropagation(),p&&w){const e=n.getCellsText(p.col,p.row,w.col,w.row);p=null,w=null,n.clearSelection(),Y(!1),e&&(T.textContent="Copied",Q(e).then(Z))}else{const e=n.getSelection();e?(n.clearSelection(),T.textContent="Copied",Q(e).then(Z)):dt()}return}if((t.ctrlKey||t.metaKey)&&t.code==="KeyV"){t.preventDefault(),t.stopPropagation(),(async()=>{try{if(navigator.clipboard?.read){const e=await navigator.clipboard.read();for(const r of e)for(const f of r.types)if(lt(f)){const d=await r.getType(f);await et(d);return}}}catch{}try{const e=await navigator.clipboard?.readText();e&&n.pasteText(ft(e))}catch{}})();return}}}let tt=0;function ft(t){return t.split(`\r
6
6
  `).join(`
7
7
  `).split(`
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};
8
+ `).join("\r")}async function At(t){const e=Lt(t.clipboardData);if(e){t.preventDefault(),t.stopPropagation();const d=Date.now();if(d-tt<50)return;tt=d,await et(e);return}const r=t.clipboardData?.getData("text/plain");if(!r)return;t.preventDefault(),t.stopPropagation();const f=Date.now();f-tt<50||(tt=f,n.pasteText(ft(r)))}let O=0;function It(t){t.preventDefault(),O++,ct(t.dataTransfer)&&s.classList.add("terminal-drag-over")}function kt(t){t.preventDefault(),t.dataTransfer&&(t.dataTransfer.dropEffect="copy")}function Yt(t){t.preventDefault(),O--,O<=0&&(O=0,s.classList.remove("terminal-drag-over"))}async function Ft(t){t.preventDefault(),O=0,s.classList.remove("terminal-drag-over");const e=ct(t.dataTransfer);e&&await et(e)}function ht(t){!Tt||t.key!=="Escape"||B||t.defaultPrevented||t.repeat||t.metaKey||t.ctrlKey||t.altKey||n.isFocused()&&(t.preventDefault(),t.stopPropagation(),k("\x1B"))}s.addEventListener("paste",At),s.addEventListener("dragenter",It),s.addEventListener("dragover",kt),s.addEventListener("dragleave",Yt),s.addEventListener("drop",Ft),document.addEventListener("keydown",ht,!0);function Rt(t){if(t.touches.length!==1){a=null;return}const e=t.touches[0];if(!e)return;L();const r=s.getBoundingClientRect(),f=e.clientX-r.left<r.width*.4?"tui":"history",d=e.clientY-r.top<r.height*.5;a={startX:e.clientX,startY:e.clientY,lastX:e.clientX,lastY:e.clientY,lastT:performance.now(),velocity:0,scrolling:!1,zone:f,tuiUp:d,sent:!1},t.stopPropagation()}function zt(t){if(!a||t.touches.length!==1)return;const e=t.touches[0];if(!e)return;const r=e.clientY-a.startY,f=e.clientX-a.startX;if(!a.scrolling){if(Math.abs(r)<8||Math.abs(r)<Math.abs(f))return;a.scrolling=!0,j=Date.now()+500}t.preventDefault(),t.stopPropagation();const d=performance.now(),v=e.clientY-a.lastY;if(a.zone==="tui"){a.sent||(a.sent=!0,k(a.tuiUp?"\x1B[5~":"\x1B[6~"),F(a.tuiUp)),a.lastX=e.clientX,a.lastY=e.clientY,a.lastT=d;return}const x=d-a.lastT;x>0&&(a.velocity=v/x),Nt(-v),a.lastX=e.clientX,a.lastY=e.clientY,a.lastT=d}function Bt(t){if(!a)return;const e=a.scrolling,r=a.zone,f=a.tuiUp,d=a.velocity;if(a=null,t.stopPropagation(),r==="tui"){e||(k(f?"\x1B[5~":"\x1B[6~"),F(f),j=Date.now()+500,t.preventDefault());return}if(!e){n.focus();return}j=Date.now()+500,t.preventDefault(),d&&gt(d)}function Kt(t){a=null,L(),t.stopPropagation()}function Ut(t){t.pointerType==="touch"&&Date.now()<j&&(t.preventDefault(),t.stopPropagation())}function Nt(t){const e=n.cellHeight();let r=e>0?Math.round(t/e):t>0?1:-1;r===0&&(r=t>0?1:-1),n.scrollLines(r)}s.addEventListener("touchstart",Rt,{passive:!0,capture:!0}),s.addEventListener("touchmove",zt,{passive:!1,capture:!0}),s.addEventListener("touchend",Bt,{passive:!1,capture:!0}),s.addEventListener("touchcancel",Kt,{passive:!0,capture:!0}),s.addEventListener("pointerup",Ut,!0);function mt(){y()}window.addEventListener("resize",mt),window.visualViewport?.addEventListener("resize",y),window.visualViewport?.addEventListener("scroll",y);const pt=new ResizeObserver(()=>y());pt.observe(s),document.fonts?.ready.then(()=>{y(),setTimeout(y,50),setTimeout(y,200)}),s.addEventListener("focusin",Mt,!0);async function Ot(){if(document.fonts?.ready)try{await Promise.race([document.fonts.ready,new Promise(t=>setTimeout(t,1e3))])}catch{}}return requestAnimationFrame(()=>{D()&&G(),(async()=>(await Ot(),D()&&S({type:"resize",cols:n.cols,rows:n.rows}),at(),y()))()}),{destroy(){if(C=!0,L(),Y(!1),N&&clearTimeout(N),document.removeEventListener("mousemove",nt,!0),document.removeEventListener("mouseup",it,!0),l){try{l.close(1e3,"session switch")}catch{}l=void 0}s.innerHTML="",s.classList.remove("terminal-pending"),window.removeEventListener("resize",mt),pt.disconnect(),document.removeEventListener("keydown",ht,!0)},focus(){n.focus()},sendInput(t){k(t)},toggleCopyMode(){dt()}}})()}export{Vt as initTerminal,ot as stripAltScreenSequences};
@@ -1,4 +1,4 @@
1
- import{cssVarsStyle as d}from"../theme.js";import{newSessionModalCSS as c,newSessionModalHTML as f,newSessionModalScript as g,reducedMotion as b}from"../shared-layout.js";import{icon as i}from"../icons.js";function v(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function o(t="var(--panel-accent)"){return`box-shadow: 0 0 0 2px ${t}; outline: none;`}function y(t){const{theme:e,fsRoots:n,terminalCfg:r,scrollback:a,wsBase:s}=t,l=`
1
+ import{cssVarsStyle as d}from"../theme.js";import{newSessionModalCSS as c,newSessionModalHTML as f,newSessionModalScript as g,reducedMotion as b}from"../shared-layout.js";import{icon as n}from"../icons.js";function v(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function o(t="var(--panel-accent)"){return`box-shadow: 0 0 0 2px ${t}; outline: none;`}function y(t){const{theme:e,fsRoots:i,terminalCfg:r,scrollback:a,wsBase:s}=t,l=`
2
2
  *, *::before, *::after { box-sizing: border-box; }
3
3
  html, body {
4
4
  background: var(--page-bg); color: var(--page-fg);
@@ -575,6 +575,16 @@ import{cssVarsStyle as d}from"../theme.js";import{newSessionModalCSS as c,newSes
575
575
  touch-action: manipulation; user-select: none;
576
576
  }
577
577
  .mobile-keys button:active { opacity: 0.55; }
578
+ /* Slim tappable strip under the input: the "empty space" that expands the keys. */
579
+ .mobile-keys .mk-handle {
580
+ display: flex; align-items: center; justify-content: center;
581
+ height: 16px; margin-top: 2px; border-radius: 6px;
582
+ color: var(--panel-muted); opacity: 0.65;
583
+ cursor: pointer; touch-action: manipulation; -webkit-tap-highlight-color: transparent;
584
+ }
585
+ .mobile-keys .mk-handle:active { opacity: 1; }
586
+ .mobile-keys .mk-handle svg { transition: transform 0.15s; }
587
+ .mobile-keys.mk-open .mk-handle svg { transform: rotate(180deg); }
578
588
  .mobile-keys .mk-input {
579
589
  display: flex; gap: 4px; flex: 1 1 100%;
580
590
  }
@@ -630,7 +640,14 @@ import{cssVarsStyle as d}from"../theme.js";import{newSessionModalCSS as c,newSes
630
640
  .sidebar.collapsed { max-height: 48px; overflow: hidden; }
631
641
  .mobile-keys { display: flex; }
632
642
  .mobile-keys .mk-buttons { display: none; }
633
- .mobile-keys.mk-focused .mk-buttons { display: flex; flex-wrap: wrap; gap: 4px; }
643
+ /* Expanded state is explicit (remembered per browser) rather than tied to
644
+ input focus: tapping a key moves focus, which used to collapse the strip
645
+ after every press. */
646
+ .mobile-keys.mk-open .mk-buttons {
647
+ display: flex; flex-wrap: nowrap; gap: 4px;
648
+ overflow-x: auto; overscroll-behavior-x: contain;
649
+ -webkit-overflow-scrolling: touch;
650
+ }
634
651
  }
635
652
 
636
653
  /* Forced narrow layout (settings toggle): same rules as the 640px
@@ -642,8 +659,11 @@ import{cssVarsStyle as d}from"../theme.js";import{newSessionModalCSS as c,newSes
642
659
  html.force-narrow .sidebar.collapsed { max-height: 48px; overflow: hidden; }
643
660
  html.force-narrow .mobile-keys { display: flex; }
644
661
  html.force-narrow .mobile-keys .mk-buttons { display: none; }
645
- html.force-narrow .mobile-keys.mk-focused .mk-buttons { display: flex; flex-wrap: wrap; gap: 4px; }
646
- `,x=JSON.stringify(e.terminal).replace(/</g,"\\u003c"),p=JSON.stringify({terminal:r,scrollback:a,theme:e.terminal,fsRoots:n,wsBase:s||""}).replace(/</g,"\\u003c");return`<!DOCTYPE html>
662
+ html.force-narrow .mobile-keys.mk-open .mk-buttons {
663
+ display: flex; flex-wrap: nowrap; gap: 4px;
664
+ overflow-x: auto; overscroll-behavior-x: contain;
665
+ }
666
+ `,x=JSON.stringify(e.terminal).replace(/</g,"\\u003c"),p=JSON.stringify({terminal:r,scrollback:a,theme:e.terminal,fsRoots:i,wsBase:s||""}).replace(/</g,"\\u003c");return`<!DOCTYPE html>
647
667
  <html lang="en">
648
668
  <head>
649
669
  <meta charset="UTF-8" />
@@ -691,9 +711,9 @@ import{cssVarsStyle as d}from"../theme.js";import{newSessionModalCSS as c,newSes
691
711
  <aside class="sidebar">
692
712
  <div class="sidebar-content" id="sidebar-content"></div>
693
713
  <div class="sidebar-footer">
694
- <button class="mode-btn active" id="mode-sessions" title="Sessions">${i("sessions",'width="20" height="20"')}</button>
695
- <button class="mode-btn" id="mode-files" title="Files">${i("folder",'width="20" height="20"')}</button>
696
- <button class="mode-btn" id="mode-settings" title="Settings">${i("settings",'width="20" height="20"')}</button>
714
+ <button class="mode-btn active" id="mode-sessions" title="Sessions">${n("sessions",'width="20" height="20"')}</button>
715
+ <button class="mode-btn" id="mode-files" title="Files">${n("folder",'width="20" height="20"')}</button>
716
+ <button class="mode-btn" id="mode-settings" title="Settings">${n("settings",'width="20" height="20"')}</button>
697
717
  </div>
698
718
  </aside>
699
719
 
@@ -731,6 +751,7 @@ import{cssVarsStyle as d}from"../theme.js";import{newSessionModalCSS as c,newSes
731
751
  <textarea id="mk-input" placeholder="Type or voice input\u2026" autocapitalize="off" autocomplete="off" autocorrect="off" spellcheck="false" rows="1"></textarea>
732
752
  <button id="mk-send" type="button" title="Send (Enter)"><svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19V5M5 12l7-7 7 7"/></svg></button>
733
753
  </div>
754
+ <div class="mk-handle" id="mk-handle" role="button" tabindex="0" aria-pressed="false" title="Show/hide extra keys" aria-label="Show or hide extra keys"><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M6 15l6-6 6 6"/></svg></div>
734
755
  <div class="mk-buttons" id="mk-buttons">
735
756
  <button data-key="esc">ESC</button>
736
757
  <button data-key="tab">Tab</button>
@@ -855,24 +876,33 @@ ${g("__onSessionCreated")}
855
876
  });
856
877
  }
857
878
 
858
- /* Mobile keys: show buttons on input focus, hide on blur */
859
- var mkInput = document.getElementById('mk-input');
860
- var mobileKeys = document.getElementById('mobile-keys');
861
- var hideTimer = null;
862
- if (mkInput && mobileKeys) {
863
- mkInput.addEventListener('focus', function() {
864
- clearTimeout(hideTimer);
865
- mobileKeys.classList.add('mk-focused');
866
- });
867
- mkInput.addEventListener('blur', function() {
868
- hideTimer = setTimeout(function() {
869
- mobileKeys.classList.remove('mk-focused');
870
- }, 200);
871
- });
872
- mobileKeys.addEventListener('mousedown', function() {
873
- clearTimeout(hideTimer);
879
+ /* Mobile keys: collapsible strip, expanded by tapping the space under the
880
+ input. The expanded state is remembered per browser and does not depend on
881
+ input focus, so keys stay pressable without re-activating the text field. */
882
+ (function() {
883
+ var mobileKeys = document.getElementById('mobile-keys');
884
+ var mkHandle = document.getElementById('mk-handle');
885
+ if (!mobileKeys || !mkHandle) return;
886
+ var MK_OPEN_KEY = 'tmux-web-mk-open';
887
+ function stored() {
888
+ try { return localStorage.getItem(MK_OPEN_KEY) === '1'; } catch (e) { return false; }
889
+ }
890
+ function apply(open) {
891
+ mobileKeys.classList.toggle('mk-open', open);
892
+ mkHandle.setAttribute('aria-pressed', open ? 'true' : 'false');
893
+ }
894
+ apply(stored());
895
+ function toggle(e) {
896
+ if (e) { e.preventDefault(); e.stopPropagation(); }
897
+ var open = !mobileKeys.classList.contains('mk-open');
898
+ apply(open);
899
+ try { localStorage.setItem(MK_OPEN_KEY, open ? '1' : '0'); } catch (err) {}
900
+ }
901
+ mkHandle.addEventListener('click', toggle);
902
+ mkHandle.addEventListener('keydown', function(e) {
903
+ if (e.key === 'Enter' || e.key === ' ') toggle(e);
874
904
  });
875
- }
905
+ })();
876
906
  })();
877
907
  </script>
878
908
  <script>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tmux-weblink",
3
- "version": "2.2.35",
3
+ "version": "2.2.37",
4
4
  "description": "Access your tmux sessions from the browser. A continuation of tmux-web and persalink.",
5
5
  "type": "module",
6
6
  "bin": {