tmux-weblink 3.2.0 → 3.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/apple-touch-icon-180.png +0 -0
- package/dist/assets/icon-192.png +0 -0
- package/dist/assets/icon-512.png +0 -0
- package/dist/assets/icon-maskable-192.png +0 -0
- package/dist/assets/icon-maskable-512.png +0 -0
- package/dist/assets/shell-client.js +13 -13
- package/dist/browser/shell-client.js +12 -12
- package/dist/lib/build-app.js +26 -10
- package/dist/lib/pages/shell.js +41 -12
- package/package.json +3 -3
- package/scripts/generate-icons.mjs +136 -145
|
@@ -1,34 +1,34 @@
|
|
|
1
|
-
import{initTerminal as it}from"./terminal-core.js";import{initBots as ot,openNewBotForPath as at}from"./bots-client.js";import{icon as Q}from"../lib/icons.js";import{toggleOverlayMenu as lt}from"./menu.js";const
|
|
1
|
+
import{initTerminal as it}from"./terminal-core.js";import{initBots as ot,openNewBotForPath as at}from"./bots-client.js";import{icon as Q}from"../lib/icons.js";import{toggleOverlayMenu as lt}from"./menu.js";const U=window.__TMUX_WEB_SHELL__;let f=null,u=null;const W=typeof window.__TMUX_WEB_SCOPE__?.agentId=="string"?window.__TMUX_WEB_SCOPE__.agentId:null;let h=W;window.__tmuxWebScopeAgent=W;let he="sessions",T="",ee="",te="",xe="";function v(e){return h?"/a/"+encodeURIComponent(h)+e:e}const d=document.getElementById("sidebar-content"),$=document.getElementById("main-placeholder"),w=document.getElementById("terminal-container"),z=document.getElementById("file-editor"),ct=document.getElementById("fe-path"),E=document.getElementById("fe-status"),F=document.getElementById("fe-content"),R=document.getElementById("fe-save"),rt=document.getElementById("fe-delete"),dt=document.getElementById("fe-back"),Me=document.getElementById("fe-new-name"),pt=document.getElementById("fe-new-btn"),be=document.getElementById("settings-backdrop"),He=document.getElementById("settings-popover"),Ne=document.querySelector(".sidebar"),_e="tmux-web-force-narrow";function ne(){try{return localStorage.getItem(_e)==="1"}catch{return!1}}function $e(){document.documentElement.classList.toggle("force-narrow",ne()),ne()&&we()&&A()}function we(){return ne()?!0:window.matchMedia("(max-width: 640px)").matches}function Re(e){Ne.classList.toggle("open",e),document.getElementById("sidebar-backdrop")?.classList.toggle("open",e)}function A(){we()&&Re(!1)}function Ae(){Re(!0)}document.getElementById("sidebar-backdrop")?.addEventListener("click",()=>A()),window.addEventListener("keydown",e=>{e.key==="Escape"&&we()&&Ne.classList.contains("open")&&(e.stopPropagation(),A())}),window.__collapseSidebar=A,document.getElementById("mode-sessions").addEventListener("click",()=>{Ae(),Pe("sessions")}),document.getElementById("mode-files").addEventListener("click",()=>{Ae(),Pe("files")});function Pe(e){he=e,document.querySelectorAll(".mode-btn").forEach(n=>n.classList.remove("active"));const t=document.getElementById(e==="sessions"?"mode-sessions":"mode-files");t&&t.classList.add("active"),e==="sessions"?(Le="",x()):It()}let Le="";async function x(){if(he!=="sessions")return;try{const n=await(await fetch("/api/sidebar/sessions")).json(),s=(window.__botsSnapshot||[]).map(o=>[o.id,o.title,o.status,o.projectPath]),i=JSON.stringify({recent:n.recent,agents:n.agents,tombstones:n.tombstones,bots:s});if(i===Le)return;Le=i,ht(n)}catch{d.innerHTML+='<div class="file-tree-empty">Failed to load sessions</div>'}const e=document.getElementById("ns-btn");e&&e.addEventListener("click",()=>{const t=window.__openNewSessionModal;typeof t=="function"?t():document.getElementById("new-session-modal")?.classList.add("open")}),Te()}const De="tmux-web-sidebar-group-collapsed";function je(){try{return new Set(JSON.parse(localStorage.getItem(De)||"[]"))}catch{return new Set}}function ft(e){try{localStorage.setItem(De,JSON.stringify([...e]))}catch{}}function ut(e,t,n){if(!e)return"\u2026";const s=n&&(e===n||e.startsWith(n+"/"))?"~"+e.slice(n.length):e,i=s.split("/").filter(Boolean);if(i.length===0)return e;for(let o=1;o<=i.length;o++){const a=i.slice(-o).join("/");if(!t.some(c=>!c||c===e?!1:(n&&(c===n||c.startsWith(n+"/"))?"~"+c.slice(n.length):c).split("/").filter(Boolean).slice(-o).join("/")===a))return a}return s}const mt={running:"var(--panel-success)",waiting_approval:"#e0a23c",waiting_input:"#e0a23c",queued:"var(--panel-accent)",starting:"var(--panel-accent)",failed:"var(--panel-danger, #e5534b)"};function gt(e){const t=document.createElement("div");return t.className="session-item bot-item",t.setAttribute("data-bot-id",e.id),t.dataset.status=e.status,t.title=`Bot \xB7 ${e.status.replace(/_/g," ")} \xB7 ${e.projectPath}`,t.style.setProperty("--bot-status",mt[e.status]??"var(--panel-muted)"),t.innerHTML=`${Q("bot",'class="bot-icon"')}<span>${p(e.title)}</span>`,t.addEventListener("click",n=>{n.stopPropagation(),window.__openBot?.(e.id)}),t}function Oe(e,t,n,s=!0){const i=new Map;for(const r of e){const y=r.path||"";i.has(y)||i.set(y,[]),i.get(y).push(r)}const o=n?[]:window.__botsSnapshot||[],a=new Map;for(const r of o)i.has(r.projectPath)||i.set(r.projectPath,[]),a.has(r.projectPath)||a.set(r.projectPath,[]),a.get(r.projectPath).push(r);const l=[...i.keys()],c=je();for(const[r,y]of i){const H=ut(r,l,t),_=c.has(r),I=document.createElement("div");if(I.className="session-group-header"+(_?" collapsed":""),I.title=r||"No working directory",I.innerHTML=`<span class="sg-folder">📁</span><span class="sg-label">${p(H)}</span>`,r){const m=document.createElement("button");m.className="sg-add-btn",m.innerHTML=Q("add",'width="14" height="14"');const N=t&&r.startsWith(t)?`~${r.slice(t.length)}`:r;m.title=`New session or bot in ${N}`,m.setAttribute("aria-label",`New session or bot in ${N}`),m.setAttribute("aria-haspopup","menu"),m.setAttribute("aria-expanded","false"),m.addEventListener("click",st=>{st.stopPropagation(),lt({anchor:m,label:`Add to ${N}`,items:[{icon:"terminal",label:"New tmux session",detail:`in ${N}`,onSelect:()=>window.__openNewSessionModal?.(r)},{icon:"agents",label:"New bot",detail:n?"only for folders on this host":`in ${N}`,disabled:!!n,onSelect:()=>void ke(r)}]})}),I.appendChild(m)}I.addEventListener("click",()=>{const m=je(),N=I.nextElementSibling;m.has(r)?(m.delete(r),I.classList.remove("collapsed"),N?.classList.remove("collapsed")):(m.add(r),I.classList.add("collapsed"),N?.classList.add("collapsed")),ft(m)});const Z=document.createElement("div");Z.className="session-group-body"+(_?" collapsed":"");for(const m of y)Z.appendChild(n?vt(m,n,s):yt(m));for(const m of a.get(r)||[])Z.appendChild(gt(m));d.appendChild(I),d.appendChild(Z)}}function vt(e,t,n){const s=document.createElement("div");s.className="session-item"+(e.name===u&&h===t?" active":"")+(n?"":" session-offline"),s.setAttribute("data-session",e.name),s.setAttribute("data-agent",t),s.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="${e.attached?"M19 4H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zm0 14H5V6h14v12z":"M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"}"></svg>
|
|
2
2
|
<span>${p(e.name)}</span>${n?"":'<span class="meta">offline</span>'}
|
|
3
|
-
<button class="session-edit-btn" data-session="${p(e.name)}" title="Edit session"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>`,n&&s.addEventListener("click",o=>{o.target.closest(".session-edit-btn")||G(e.name,t)});const i=s.querySelector(".session-edit-btn");return i&&i.addEventListener("click",o=>{o.stopPropagation(),fe(e.name,i,{agentId:t})}),s}function
|
|
3
|
+
<button class="session-edit-btn" data-session="${p(e.name)}" title="Edit session"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>`,n&&s.addEventListener("click",o=>{o.target.closest(".session-edit-btn")||G(e.name,t)});const i=s.querySelector(".session-edit-btn");return i&&i.addEventListener("click",o=>{o.stopPropagation(),fe(e.name,i,{agentId:t})}),s}function yt(e){const t=document.createElement("div");t.className="session-item"+(e.name===u&&!h?" active":""),t.setAttribute("data-session",e.name),t.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="${e.attached?"M19 4H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zm0 14H5V6h14v12z":"M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"}"></svg>
|
|
4
4
|
<span>${p(e.name)}</span>
|
|
5
5
|
<button class="session-edit-btn" data-session="${p(e.name)}" title="Edit session"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>
|
|
6
|
-
`,t.addEventListener("click",s=>{s.target.closest(".session-edit-btn")||G(e.name)});const n=t.querySelector(".session-edit-btn");return n&&n.addEventListener("click",s=>{s.stopPropagation(),fe(e.name,n)}),t}function
|
|
6
|
+
`,t.addEventListener("click",s=>{s.target.closest(".session-edit-btn")||G(e.name)});const n=t.querySelector(".session-edit-btn");return n&&n.addEventListener("click",s=>{s.stopPropagation(),fe(e.name,n)}),t}function ht(e){d.innerHTML='<button class="new-session-sidebar-btn" id="ns-btn">+ New Session</button>';const t=e.recent||[],n=document.createElement("div");n.className="sidebar-section-label"+(W?" clickable":""),n.textContent=W?"\u2190 \u8FD4\u56DE\u672C\u673A":"\u672C\u673A",W&&(n.title="Back to hub",n.addEventListener("click",()=>{window.location.href="/"})),d.appendChild(n),Oe(t,e.home);const s=e.agents||[];for(const o of s){if(!o.sessions||o.sessions.length===0)continue;const a=o.agentId===h,l=document.createElement("div");l.className="sidebar-section-label machine-label"+(o.online?"":" agent-offline-label")+(!a&&o.online?" clickable":""),l.textContent=o.agentName+(o.online?"":" (offline)"),!a&&o.online&&(l.title="\u6253\u5F00 "+o.agentName,l.addEventListener("click",()=>{window.location.href="/a/"+encodeURIComponent(o.agentId)+"/"})),d.appendChild(l),Oe(o.sessions,e.home,o.agentId,o.online)}const i=e.tombstones||[];if(i.length>0){const o=document.createElement("div");o.className="sidebar-section-label tombstone-label",o.textContent="\u5931\u6548\u4F1A\u8BDD",d.appendChild(o);for(const a of i){const l=document.createElement("div");l.className="session-item session-tombstone",l.setAttribute("data-session",a.name),a.agentId&&l.setAttribute("data-agent",a.agentId);const c=a.agentId?a.agentOnline?" (agent)":" (agent \u79BB\u7EBF)":"";l.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor"><path d="M4 6h16v2H4V6zm0 5h16v2H4v-2zm0 5h16v2H4v-2z"></svg>
|
|
7
7
|
<span>${p(a.name)}</span><span class="meta">\u5931\u6548${c}</span>
|
|
8
|
-
<button class="session-edit-btn" data-session="${p(a.name)}" title="\u6062\u590D\u4F1A\u8BDD"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>`,l.title="\u5931\u6548\u4F1A\u8BDD\uFF1A\u70B9\u51FB\u7BA1\u7406\uFF08\u91CD\u5EFA/\u91CD\u547D\u540D/\u5220\u9664\uFF09",l.addEventListener("click",()=>{fe(a.name,l,{tombstone:!0,agentId:a.agentId})});const r=l.querySelector(".session-edit-btn");r&&r.addEventListener("click",y=>{y.stopPropagation(),fe(a.name,r,{tombstone:!0,agentId:a.agentId})}),d.appendChild(l)}}}function p(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}async function G(e,t){if(u===e&&f&&h===(t||null))return;z.style.display="none"
|
|
8
|
+
<button class="session-edit-btn" data-session="${p(a.name)}" title="\u6062\u590D\u4F1A\u8BDD"><svg viewBox="0 0 24 24" fill="currentColor" width="14" height="14"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 000-1.41l-2.34-2.34a1 1 0 00-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/></svg></button>`,l.title="\u5931\u6548\u4F1A\u8BDD\uFF1A\u70B9\u51FB\u7BA1\u7406\uFF08\u91CD\u5EFA/\u91CD\u547D\u540D/\u5220\u9664\uFF09",l.addEventListener("click",()=>{fe(a.name,l,{tombstone:!0,agentId:a.agentId})});const r=l.querySelector(".session-edit-btn");r&&r.addEventListener("click",y=>{y.stopPropagation(),fe(a.name,r,{tombstone:!0,agentId:a.agentId})}),d.appendChild(l)}}}function p(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}async function G(e,t){if(u===e&&f&&h===(t||null))return;z.style.display="none",$.style.display="none",w.style.display="",w.classList.add("terminal-pending"),A(),f&&(de(),f.destroy(),f=null),u=e,h=t||null,window.__tmuxWebScopeAgent=h,window.__tmuxWebCurrentSession=u,zt(e,t);const n=Ie(e,t);tt.set(n,Date.now()+Ut);const s=O.get(n);if(s&&s.state==="working"){s.state="idle",s.doneUntil=void 0,s.unread=!1;const i=d.querySelector(t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])');i&&ye(i,n,s)}for(const i of d.querySelectorAll(".session-item"))i.classList.toggle("active",i.getAttribute("data-session")===e&&(i.getAttribute("data-agent")||null)===h);try{f=await it(w,e,{terminal:U.terminal,scrollback:U.scrollback,theme:U.theme,wsBase:h?"/ws/a/"+encodeURIComponent(h):U.wsBase||"/ws"}),Ye()}catch(i){console.error("[shell] terminal init failed:",i);const o=i&&typeof i=="object"&&"message"in i?i.message:String(i);w.textContent="Failed to open terminal for "+e+": "+o,w.classList.remove("terminal-pending")}}let se=[],g=null,Ue=!1;function bt(e){if(!g||!g.files.length)return null;const t=g.repoRoot;if(!t||!e.startsWith(t))return null;const n=e.slice(t.length+1);for(const s of g.files)if(s.path===n)return s.status;return null}async function wt(e){Ue=!0;try{const t=await fetch(v("/api/git/status?path="+encodeURIComponent(e)));t.ok?g=await t.json():g=null}catch{g=null}finally{Ue=!1}}function Lt(){if(!g||!g.branch)return"";const{branch:e,linesAdded:t,linesRemoved:n}=g;let s=`<div class="sidebar-git"><div class="git-branch-badge">
|
|
9
9
|
<svg viewBox="0 0 16 16" fill="currentColor"><path d="M11.63 1.22a.75.75 0 00-1.06 0L5.99 5.8 4.12 3.93a.75.75 0 10-1.06 1.06L4.93 6.87A3.5 3.5 0 003 10.09v3.16a.75.75 0 001 0v-3.16a2.5 2.5 0 012.5-2.5h.27l-1.06 1.06a.75.75 0 001.06 1.06l2.37-2.38a.75.75 0 000-1.06L7.59 5.27l4.04-4.05a.75.75 0 000-1.06L11.63 1.22zM3.25 13.94a.75.75 0 01-.75-.75v-.69a.75.75 0 011.5 0v.69c0 .414-.336.75-.75.75z"/></svg>
|
|
10
|
-
${p(e)}</div>`;return(t>0||n>0)&&(s+=`<div class="git-diff-stats">+<span class="add">${t}</span> <span class="del">-${n}</span></div>`),s+"</div>"}d.addEventListener("click",e=>{e.target.closest(".sidebar-git")&&D&&g&&(e.stopPropagation(),qe())});const q=document.getElementById("header-git"),
|
|
10
|
+
${p(e)}</div>`;return(t>0||n>0)&&(s+=`<div class="git-diff-stats">+<span class="add">${t}</span> <span class="del">-${n}</span></div>`),s+"</div>"}d.addEventListener("click",e=>{e.target.closest(".sidebar-git")&&D&&g&&(e.stopPropagation(),qe())});const q=document.getElementById("header-git"),We=document.getElementById("git-diff-view"),ze=document.getElementById("gd-path"),ie=document.getElementById("gd-status"),oe=document.getElementById("gd-content"),Et=document.getElementById("gd-back");let D=null;function V(e){if(!e||!e.branch){q.style.display="none",D=null;return}D=e.repoRoot;const{branch:t,linesAdded:n,linesRemoved:s}=e;let i=`<span class="branch">${p(t)}</span>`;(n>0||s>0)&&(i+=`<span class="sep">\xB7</span>+<span class="diff-add">${n}</span> <span class="diff-del">-${s}</span>`),q.innerHTML=i,q.style.display="block"}q.addEventListener("click",e=>{D&&g&&(e.stopPropagation(),qe())});const b=document.getElementById("git-popover"),ae=document.getElementById("git-popover-backdrop");function Ee(){const e=q.getBoundingClientRect();b.style.top=e.bottom+4+"px",b.style.left=Math.max(8,Math.min(e.left,window.innerWidth-400))+"px"}function Fe(){const e=D,t=document.getElementById("git-popover-browse");t&&t.addEventListener("click",()=>{if(ce(),e){he="files",document.querySelectorAll(".mode-btn").forEach(s=>s.classList.remove("active"));const n=document.getElementById("mode-files");n&&n.classList.add("active"),M(e)}})}let Ge="";function qe(){if(!g)return;const e=g.files||[];if(!e.length)b.innerHTML=`<div class="git-popover-header">No changes \u2014 clean working tree</div>
|
|
11
11
|
<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>`;else{let t=`<div class="git-popover-header">${e.length} file${e.length>1?"s":""} changed</div>`;for(let n=0;n<e.length;n++){const s=e[n],i=s.additions||0,o=s.deletions||0;let a="";switch(s.status){case"M":a='<span class="git-file-status M">M</span>';break;case"A":a='<span class="git-file-status A">A</span>';break;case"D":a='<span class="git-file-status D">D</span>';break;case"?":a='<span class="git-file-status ?">?</span>';break;case"R":a='<span class="git-file-status R">R</span>';break}t+=`<div class="git-popover-item" data-idx="${n}">
|
|
12
12
|
${a}<span class="file-path">${p(s.path)}</span>
|
|
13
13
|
<span class="file-add">${i>0?"+"+i:""}</span>
|
|
14
14
|
<span class="file-del">${o>0?"-"+o:""}</span>
|
|
15
|
-
</div>`}t+='<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>',Ge=t,b.innerHTML=t,b.querySelectorAll(".git-popover-item").forEach(n=>{const s=parseInt(n.dataset.idx||"0",10),i=e[s];!i||i.status==="D"||(n.classList.add("clickable"),n.style.cursor="pointer",n.addEventListener("click",()=>Je(i.path)))})}Ee(),b.classList.add("open"),ae.classList.add("open"),Fe()}function
|
|
15
|
+
</div>`}t+='<div class="git-popover-footer"><button id="git-popover-browse">Browse repository \u2192</button></div>',Ge=t,b.innerHTML=t,b.querySelectorAll(".git-popover-item").forEach(n=>{const s=parseInt(n.dataset.idx||"0",10),i=e[s];!i||i.status==="D"||(n.classList.add("clickable"),n.style.cursor="pointer",n.addEventListener("click",()=>Je(i.path)))})}Ee(),b.classList.add("open"),ae.classList.add("open"),Fe()}function kt(){return window.innerWidth>=1024}function Ve(e,t){const s=(e+(t&&e?`
|
|
16
16
|
`:"")+t).split(`
|
|
17
|
-
`);let i="",o=0,a=0;for(const l of s){const c=l;if(c.startsWith("@@")){const r=c.match(/@@\s+-(\d+)[^+]*\+(\d+)/);r&&(o=parseInt(r[1],10)-1,a=parseInt(r[2],10)-1),i+=`<div class="diff-line hunk"><span class="ln-body">${p(c)}</span></div>`;continue}if(c.startsWith("diff --git")||c.startsWith("index ")||c.startsWith("--- ")||c.startsWith("+++ ")||c.startsWith("new file")||c.startsWith("deleted file")){c.startsWith("diff --git")&&(i+=`<div class="diff-line header"><span class="ln-body">${p(c)}</span></div>`);continue}if(c.startsWith("+"))a++,i+=`<div class="diff-line add"><span class="ln-no">${a}</span><span class="ln-body">${p(c)}</span></div>`;else if(c.startsWith("-"))o++,i+=`<div class="diff-line del"><span class="ln-no">${o}</span><span class="ln-body">${p(c)}</span></div>`;else if(c.startsWith("\\"))i+=`<div class="diff-line"><span class="ln-body">${p(c)}</span></div>`;else{if(!c&&!o&&!a)continue;o++,a++,i+=`<div class="diff-line"><span class="ln-no">${o}</span><span class="ln-no" style="margin-right:12px">${a}</span><span class="ln-body">${p(c)}</span></div>`}}return{html:i,lineCount:s.length}}let le=null;async function Je(e){const t=D;if(t)if(ce(),
|
|
17
|
+
`);let i="",o=0,a=0;for(const l of s){const c=l;if(c.startsWith("@@")){const r=c.match(/@@\s+-(\d+)[^+]*\+(\d+)/);r&&(o=parseInt(r[1],10)-1,a=parseInt(r[2],10)-1),i+=`<div class="diff-line hunk"><span class="ln-body">${p(c)}</span></div>`;continue}if(c.startsWith("diff --git")||c.startsWith("index ")||c.startsWith("--- ")||c.startsWith("+++ ")||c.startsWith("new file")||c.startsWith("deleted file")){c.startsWith("diff --git")&&(i+=`<div class="diff-line header"><span class="ln-body">${p(c)}</span></div>`);continue}if(c.startsWith("+"))a++,i+=`<div class="diff-line add"><span class="ln-no">${a}</span><span class="ln-body">${p(c)}</span></div>`;else if(c.startsWith("-"))o++,i+=`<div class="diff-line del"><span class="ln-no">${o}</span><span class="ln-body">${p(c)}</span></div>`;else if(c.startsWith("\\"))i+=`<div class="diff-line"><span class="ln-body">${p(c)}</span></div>`;else{if(!c&&!o&&!a)continue;o++,a++,i+=`<div class="diff-line"><span class="ln-no">${o}</span><span class="ln-no" style="margin-right:12px">${a}</span><span class="ln-body">${p(c)}</span></div>`}}return{html:i,lineCount:s.length}}let le=null;async function Je(e){const t=D;if(t)if(ce(),kt()){w.style.display="none",f&&(de(),f.destroy(),f=null,le=u,u=null),V(null),z.style.display="none",$.style.display="none",We.style.display="flex",ze.textContent=e,ie.textContent="Loading\u2026",oe.innerHTML="";try{const n=await fetch(v("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!n.ok)throw new Error(await n.text());const s=await n.json();Ct(e,s.diff,s.stagedDiff)}catch(n){const s=n instanceof Error?n.message:String(n);ie.textContent="Error",oe.innerHTML=`<div class="diff-empty" style="padding:24px;text-align:center;color:var(--panel-muted)">Error: ${p(s)}</div>`}}else{b.innerHTML=`<div class="git-diff-view"><div class="diff-header">
|
|
18
18
|
<button class="diff-back">\u2190 Back</button>
|
|
19
19
|
<span class="diff-filename">${p(e)}</span>
|
|
20
20
|
<span class="diff-loading">Loading\u2026</span>
|
|
21
|
-
</div></div>`,Ee(),b.classList.add("open"),ae.classList.add("open");try{const n=await fetch(v("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!n.ok)throw new Error(await n.text());const s=await n.json();
|
|
21
|
+
</div></div>`,Ee(),b.classList.add("open"),ae.classList.add("open");try{const n=await fetch(v("/api/git/diff?path="+encodeURIComponent(t)+"&file="+encodeURIComponent(e)));if(!n.ok)throw new Error(await n.text());const s=await n.json();St(e,s.diff,s.stagedDiff)}catch(n){const s=n instanceof Error?n.message:String(n);b.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">${p(e)}</span>
|
|
24
|
-
</div><div class="diff-empty">Error loading diff: ${p(s)}</div></div>`}}}function
|
|
24
|
+
</div><div class="diff-empty">Error loading diff: ${p(s)}</div></div>`}}}function St(e,t,n){if(!t&&!n){b.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">${p(e)}</span>
|
|
27
27
|
</div><div class="diff-empty">No diff content available</div></div>`;return}const{html:s,lineCount:i}=Ve(t,n);b.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">${p(e)}</span>
|
|
30
30
|
<span class="diff-filesize">${i} lines</span>
|
|
31
|
-
</div><div class="diff-content">${s}</div></div>`,b.querySelector(".diff-back")?.addEventListener("click",()=>{b.innerHTML=Ge,Ee(),g&&b.querySelectorAll(".git-popover-item").forEach(o=>{const a=parseInt(o.dataset.idx||"0",10),l=g.files[a];!l||l.status==="D"||(o.style.cursor="pointer",o.addEventListener("click",()=>Je(l.path)))}),Fe()})}function
|
|
31
|
+
</div><div class="diff-content">${s}</div></div>`,b.querySelector(".diff-back")?.addEventListener("click",()=>{b.innerHTML=Ge,Ee(),g&&b.querySelectorAll(".git-popover-item").forEach(o=>{const a=parseInt(o.dataset.idx||"0",10),l=g.files[a];!l||l.status==="D"||(o.style.cursor="pointer",o.addEventListener("click",()=>Je(l.path)))}),Fe()})}function Ct(e,t,n){if(!t&&!n){ie.textContent="No diff",oe.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}=Ve(t,n);ze.textContent=e,ie.textContent=i+" lines",oe.innerHTML=s}function Bt(){We.style.display="none",le?(w.style.display="",w.classList.add("terminal-pending"),G(le),le=null):u?(w.style.display="",w.classList.add("terminal-pending"),Ye()):$.style.display="flex"}Et.addEventListener("click",Bt);function ce(){b.classList.remove("open"),ae.classList.remove("open")}ae.addEventListener("click",ce),document.addEventListener("keydown",e=>{e.key==="Escape"&&(ce(),ve())});async function Ke(e){try{const n=await(await fetch("/api/fs/session-path?session="+encodeURIComponent(e))).json();if(n.path){const s=await fetch("/api/git/status?path="+encodeURIComponent(n.path));if(s.ok){const i=await s.json();g=i,V(i);return}}}catch{}g=null,V(null)}let re=null;function Ye(){de(),u&&(Ke(u),re=setInterval(()=>{u&&Ke(u)},3e4))}function de(){re&&(clearInterval(re),re=null)}async function ke(e){let t=e;if(t.startsWith("~"))try{const s=await(await fetch(v("/api/fs/list?path="+encodeURIComponent(t)))).json();typeof s.path=="string"&&s.path&&(t=s.path)}catch{}t=t.replace(/\/+$/,"")||"/",at(t)}function Xe(e,t){const n=document.createElement("button");n.className="file-tree-bot-btn",n.innerHTML=Q("add",'width="12" height="12"'),n.title=`Create bot in ${t}`,n.setAttribute("aria-label",`Create bot in ${t}`),n.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),ke(t)}),e.appendChild(n)}function It(){if(se=U.fsRoots||[],se.length===0){if(u){Tt(u);return}M("");return}d.innerHTML="";for(const e of se){const t=document.createElement("div");t.className="file-tree-item",t.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor" class="file-icon"><path d="M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/></svg> ${p(e)}`,t.addEventListener("click",()=>M(e)),Xe(t,e),d.appendChild(t)}}async function Tt(e){d.innerHTML='<div class="file-tree-empty">Loading...</div>';try{const n=await(await fetch(v("/api/fs/session-path?session="+encodeURIComponent(e)))).json();n.path?M(n.path):d.innerHTML='<div class="file-tree-info">Could not determine session directory.</div>'}catch{d.innerHTML='<div class="file-tree-error">Failed to get session directory</div>'}}async function M(e){T=e,d.innerHTML='<div class="file-tree-empty">Loading...</div>';const t=wt(e);try{const s=await(await fetch(v("/api/fs/list?path="+encodeURIComponent(e)))).json(),i=typeof s.path=="string"&&s.path?s.path:e;if(i&&(T=i),await t,d.innerHTML="",i){const l=document.createElement("div");l.className="file-tree-item file-tree-create-bot",l.innerHTML=`<span class="file-tree-bot-plus">${Q("add",'width="11" height="11"')}</span> Create bot in this folder`,l.title=`Create bot in ${i}`,l.addEventListener("click",()=>void ke(i)),d.appendChild(l)}V(g),d.innerHTML+=Lt();const o=xt(i||e);if(o&&!se.some(c=>i===c)){const c=document.createElement("div");c.className="file-tree-item",c.innerHTML="..",c.addEventListener("click",()=>M(o)),d.appendChild(c)}if(s.dirs)for(const l of s.dirs){const c=l.split("/").pop()||l.split("\\").pop(),r=document.createElement("div");r.className="file-tree-item",r.innerHTML=`<svg viewBox="0 0 24 24" fill="currentColor" class="file-icon"><path d="M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/></svg> ${p(c)}`,r.addEventListener("click",()=>M(l)),Xe(r,l),d.appendChild(r)}else d.innerHTML="";const a=s.files||[];for(const l of a){const c=l.split("/").pop()||l.split("\\").pop(),r=bt(l);let y="",H="";if(r)switch(r){case"M":y="git-mod",H='<span class="git-file-status M">M</span>';break;case"A":y="git-add",H='<span class="git-file-status A">A</span>';break;case"D":y="git-del",H='<span class="git-file-status D">D</span>';break;case"?":y="git-untracked",H='<span class="git-file-status ?">?</span>';break;case"R":y="git-mod",H='<span class="git-file-status R">R</span>';break}const _=document.createElement("div");_.className="file-tree-item file"+(y?" "+y:""),_.innerHTML=`<span class="file-icon">\u{1F4C4}</span> ${H}${p(c)}`,_.addEventListener("click",()=>Mt(l)),d.appendChild(_)}}catch{d.innerHTML='<div class="file-tree-error">Failed to load directory</div>'}}function xt(e){const t=e.lastIndexOf("/");return t<=0?null:e.substring(0,t)}async function Mt(e){ee=e,w.style.display="none",f&&(de(),f.destroy(),f=null,u=null),V(null),A(),$.style.display="none",z.style.display="flex",ct.textContent=e,E.textContent="Loading...",R.style.display="none";try{const t=await fetch(v("/api/file?path="+encodeURIComponent(e)));if(!t.ok){const s=await t.json();E.textContent=s.error||"Failed to load",F.value="";return}const n=await t.json();F.value=n.content,te=n.content,xe=n.content,E.textContent=n.size+" bytes",R.style.display=""}catch{E.textContent="Failed to load",F.value=""}}F.addEventListener("input",()=>{te=F.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:ee,content:te})});if(!e.ok){const t=await e.json();E.textContent=t.error||"Save failed";return}xe=te,E.textContent="Saved"}catch{E.textContent="Save failed"}finally{R.disabled=!1,R.textContent="Save"}}),rt.addEventListener("click",async()=>{if(confirm("Delete "+ee+"?"))try{const e=await fetch(v("/api/file/delete"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:ee})});if(!e.ok){const t=await e.json();E.textContent=t.error||"Delete failed";return}z.style.display="none",$.style.display="flex",T&&M(T)}catch{E.textContent="Delete failed"}}),dt.addEventListener("click",()=>{z.style.display="none",$.style.display="flex",T&&M(T)}),pt.addEventListener("click",async()=>{const e=Me.value.trim();if(!e)return;const t=T+"/"+e;try{const n=await fetch(v("/api/file/touch"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t})});if(!n.ok){const s=await n.json();E.textContent=s.error||"Create failed";return}Me.value="",T&&M(T)}catch{E.textContent="Create failed"}});const pe=document.getElementById("force-narrow-toggle");pe&&(pe.checked=ne(),pe.addEventListener("change",()=>{try{localStorage.setItem(_e,pe.checked?"1":"0")}catch{}$e(),x()})),$e(),document.getElementById("mode-settings").addEventListener("click",()=>{const e=He.classList.toggle("open");be.classList.toggle("open",e)}),be.addEventListener("click",()=>{He.classList.remove("open"),be.classList.remove("open")});let L="",k=!1,S;const J=document.createElement("div");J.className="session-popover-backdrop",document.body.appendChild(J);const C=document.createElement("div");C.id="session-popover",C.className="session-popover",C.style.display="none",C.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 it}from"./terminal-core.js";import{initBots as ot,openNew
|
|
|
38
38
|
<button class="btn danger sp-delete" id="sp-delete">Delete</button>
|
|
39
39
|
</div>
|
|
40
40
|
<hr class="sp-divider" id="sp-divider" />
|
|
41
|
-
<button class="btn primary" id="sp-rebuild" style="display:none">\u91CD\u5EFA\u540C\u540D\u540C\u8DEF\u5F84 session</button>`,document.body.appendChild(C);function
|
|
42
|
-
`).length;B.rows=Math.min(e,4)}),B.addEventListener("keydown",e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),et())})),Qe&&Qe.addEventListener("click",et),window.visualViewport){const e=document.querySelector(".app-layout"),t=()=>{e&&(e.style.height=window.visualViewport.height+"px"),window.scrollTo(0,0),document.documentElement.scrollTop=0,document.body.scrollTop=0};window.visualViewport.addEventListener("resize",t),window.addEventListener("orientationchange",()=>setTimeout(t,100)),document.addEventListener("touchstart",()=>{(window.scrollY>0||document.documentElement.scrollTop>0)&&window.scrollTo(0,0)},{passive:!0})}const Se=document.getElementById("process-panel"),Y=document.getElementById("proc-list"),
|
|
41
|
+
<button class="btn primary" id="sp-rebuild" style="display:none">\u91CD\u5EFA\u540C\u540D\u540C\u8DEF\u5F84 session</button>`,document.body.appendChild(C);function Ht(e){const t=e.getBoundingClientRect(),n=window.innerHeight,s=C.offsetHeight||240;let i=t.bottom+4;i+s>n-8&&(i=Math.max(8,t.top-s-4)),C.style.top=i+"px",C.style.left=Math.max(8,Math.min(t.left,window.innerWidth-240))+"px"}let Jt="";function fe(e,t,n){L=e,k=!!n?.tombstone,S=n?.agentId;const s=document.getElementById("sp-name");s.value=e;const i=C.querySelector(".sp-field label");i.textContent=k?"\u91CD\u547D\u540D (\u4EC5\u8BB0\u5F55\uFF0C\u4E0D\u91CD\u5EFA)":"Rename session";const o=document.getElementById("sp-rebuild");o.style.display=k?"":"none";const a=document.getElementById("sp-delete");a.textContent=k?"\u5220\u9664\u8BB0\u5F55":"Delete",a.title=k?"\u5220\u9664\u5931\u6548\u8BB0\u5F55\uFF08\u5893\u7891\u6D88\u5931\uFF09":"Delete session";const l=document.getElementById("sp-divider");l&&(l.style.display=k?"":"none");const c=document.getElementById("sp-save");c.textContent=k?"\u91CD\u547D\u540D":"Save",J.classList.add("open"),C.style.display="block",Ht(t),setTimeout(()=>s.focus(),50)}function P(){J.classList.remove("open"),C.style.display="none"}J.addEventListener("click",P),document.getElementById("sp-save").addEventListener("click",async()=>{const e=document.getElementById("sp-name").value.trim();if(!e||e===L){P();return}try{const t=k?{oldName:L,newName:e,agentId:S}:{oldName:L,newName:e,...S?{agentId:S}:{}};if(!(await fetch(v(k?"/api/sessions/rename-tombstone":"/api/sessions/rename"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).ok)return;P(),x(),!k&&u===L&&(S??null)===h&&G(e,S)}catch{}}),document.getElementById("sp-rebuild").addEventListener("click",async()=>{if(confirm('\u91CD\u5EFA\u4F1A\u8BDD "'+L+'" (\u540C\u540D\u540C\u8DEF\u5F84\uFF0C\u5185\u5BB9\u4E3A\u7A7A)\uFF1F'))try{const e=await fetch(v("/api/sessions/rebuild"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:L,agentId:S})});if(!e.ok){const t=await e.json();alert(t.error||"\u91CD\u5EFA\u5931\u8D25");return}P(),x()}catch{}}),document.getElementById("sp-delete").addEventListener("click",async()=>{if(k){if(!confirm('\u5220\u9664\u5931\u6548\u8BB0\u5F55 "'+L+'"\uFF1F'))return;try{if(!(await fetch(v("/api/sessions/dismiss"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:L,agentId:S})})).ok)return;P(),x()}catch{}return}if(confirm('Delete session "'+L+'"?'))try{if(!(await fetch(v("/api/sessions/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:L,...S?{agentId:S}:{}})})).ok)return;P(),u===L&&(S??null)===h&&(f&&(f.destroy(),f=null),u=null,w.style.display="none",$.style.display="flex"),x()}catch{}}),document.getElementById("sp-cancel").addEventListener("click",P);const Ze={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"},ue=document.getElementById("mobile-keys"),Nt=new Set(["up","down","left","right","tab","s-tab","space"]),_t=400,$t=80;let K=0,me=0,ge=!1;function Rt(){K&&(clearTimeout(K),K=0),me&&(clearInterval(me),me=0)}ue.addEventListener("mousedown",e=>{e.target.closest("button[data-key]")&&e.preventDefault()}),ue.addEventListener("pointerdown",e=>{const t=e.target.closest("button[data-key]");if(!t)return;const n=t.dataset.key;Nt.has(n)&&(ge=!1,K=setTimeout(()=>{K=0,ge=!0,me=setInterval(()=>{const s=Ze[n];s&&f&&f.sendInput(s)},$t)},_t))});for(const e of["pointerup","pointercancel","pointerleave"])ue.addEventListener(e,Rt);ue.addEventListener("click",e=>{const t=e.target.closest("button[data-key]");if(!t||!f)return;if(ge){ge=!1;return}const n=Ze[t.dataset.key];n&&(f.sendInput(n),f.focus())});const B=document.getElementById("mk-input"),Qe=document.getElementById("mk-send");function et(){if(!B||!f)return;const e=B.value;e&&(f.sendInput(e+"\r"),B.value="",B.rows=1,f.focus())}if(B&&(B.addEventListener("input",()=>{B.rows=1;const e=B.value.split(`
|
|
42
|
+
`).length;B.rows=Math.min(e,4)}),B.addEventListener("keydown",e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),et())})),Qe&&Qe.addEventListener("click",et),window.visualViewport){const e=document.querySelector(".app-layout"),t=()=>{e&&(e.style.height=window.visualViewport.height+"px"),window.scrollTo(0,0),document.documentElement.scrollTop=0,document.body.scrollTop=0};window.visualViewport.addEventListener("resize",t),window.addEventListener("orientationchange",()=>setTimeout(t,100)),document.addEventListener("touchstart",()=>{(window.scrollY>0||document.documentElement.scrollTop>0)&&window.scrollTo(0,0)},{passive:!0})}const Se=document.getElementById("process-panel"),Y=document.getElementById("proc-list"),At=document.getElementById("proc-close"),Ce=document.getElementById("proc-backdrop"),Pt=document.getElementById("header-ram");function Dt(){Y.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){Y.innerHTML='<div class="proc-empty">No processes</div>';return}let t="";for(const n of e){const s=n.rss,i=s<1048576?(s/1024).toFixed(0)+"K":(s/1048576).toFixed(1)+"M";t+='<div class="proc-row" data-pid="'+n.pid+'"><span class="proc-mem">'+n.mem+'%</span><span class="proc-rss">'+i+'</span><span class="proc-cmd" title="'+p(n.command)+'">'+p(n.command)+'</span><button class="proc-kill" title="Kill PID '+n.pid+'">×</button></div>'}Y.innerHTML=t;for(const n of Y.querySelectorAll(".proc-row")){const s=n.querySelector(".proc-kill");s&&s.addEventListener("click",i=>{const o=i.target.closest(".proc-row");!o||!confirm("Kill PID "+o.dataset.pid+"?")||fetch(v("/api/system/kill"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pid:parseInt(o.dataset.pid,10)})}).then(a=>a.json()).then(a=>{a.ok?o.style.opacity="0.3":alert("Failed: "+(a.error||"unknown"))}).catch(()=>alert("Network error"))})}}).catch(()=>{Y.innerHTML='<div class="proc-empty">Failed to load</div>'})}function jt(){Se.classList.add("open"),Ce.classList.add("open"),Dt()}function ve(){Se.classList.remove("open"),Ce.classList.remove("open")}Pt.addEventListener("click",e=>{e.stopPropagation(),Se.classList.contains("open")?ve():jt()}),At.addEventListener("click",ve),Ce.addEventListener("click",ve);const Ot=2e3;let X=null,Be=null;const j=new Map,O=new Map,Ut=5e3,tt=new Map;function Ie(e,t){return(t?"a:"+t+":":"l:")+e}function Wt(e,t,n){const s=Ie(e,t);if(n==="working"){const r=tt.get(s);if(r&&Date.now()<r)return}const i=O.get(s),o=e===u&&(t??null)===h,a=n==="idle"&&i?.state==="working";O.set(s,{session:e,agentId:t,state:n,doneUntil:a?Date.now()+Ot:void 0,unread:a?!o:!1});const l=t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',c=d.querySelector(l);c&&ye(c,s,O.get(s))}function ye(e,t,n){const s=j.get(t);s&&(clearTimeout(s),j.delete(t)),e.classList.remove("working","just-done");const i=n.session===u&&(n.agentId??null)===h;n.state==="working"?e.classList.add("working"):i&&n.doneUntil&&Date.now()<n.doneUntil?(e.classList.add("just-done"),j.set(t,setTimeout(()=>{e.classList.remove("just-done"),j.delete(t)},Math.max(0,n.doneUntil-Date.now())))):!i&&n.unread&&e.classList.add("just-done")}function Te(){for(const[e,t]of O){const n=t.agentId?'.session-item[data-agent="'+CSS.escape(t.agentId)+'"][data-session="'+CSS.escape(t.session)+'"]':'.session-item[data-session="'+CSS.escape(t.session)+'"]:not([data-agent])',s=d.querySelector(n);s&&ye(s,e,t)}}function zt(e,t){const n=Ie(e,t),s=O.get(n);if(!s)return;const i=j.get(n);i&&(clearTimeout(i),j.delete(n)),s.doneUntil=void 0,s.unread=!1;const o=t?'.session-item[data-agent="'+CSS.escape(t)+'"][data-session="'+CSS.escape(e)+'"]':'.session-item[data-session="'+CSS.escape(e)+'"]:not([data-agent])',a=d.querySelector(o);a&&ye(a,n,s)}function nt(){if(X||Be)return;const e=localStorage.getItem("tmux-web-token");let n=(location.protocol==="https:"?"wss:":"ws:")+"//"+location.host+"/ws/activity";e&&(n+="?token="+encodeURIComponent(e));try{const s=new WebSocket(n);X=s,s.onmessage=i=>{try{const o=JSON.parse(String(i.data));o&&o.type==="session.activity"&&typeof o.session=="string"&&Wt(o.session,o.agentId||void 0,o.state==="working"?"working":"idle")}catch{}},s.onclose=()=>{X===s&&(X=null,Be=setTimeout(()=>{Be=null,nt()},5e3))},s.onerror=()=>{try{s.close()}catch{}}}catch{X=null}}window.__openSession=G,window.__refreshSidebar=x,x(),A(),Te(),nt(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&Te()}),setInterval(()=>{document.visibilityState==="visible"&&x()},1e4),ot();
|
package/dist/lib/build-app.js
CHANGED
|
@@ -1,10 +1,26 @@
|
|
|
1
|
-
import{existsSync as P,readdirSync as
|
|
2
|
-
<
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
1
|
+
import{existsSync as P,readdirSync as le,statSync as T,unlinkSync as me,writeFileSync as pe,mkdirSync as fe,readFileSync as z}from"node:fs";import{readFile as ge}from"node:fs/promises";import{execSync as C,execFileSync as L}from"node:child_process";import{tmuxEnv as he}from"./tmux-env.js";import h from"node:path";import{fileURLToPath as ye}from"node:url";import{Hono as je}from"hono";import{listSessions as D}from"../sessions.js";import{createRequire as we}from"node:module";import{getBotManager as ve}from"./bots/manager.js";import{registerBotRoutes as ke}from"./bots/routes.js";import{renderLoginPage as qe,renderNotesIndex as be,renderNotesPage as Se,renderSettings as Te,renderThemeSettings as Ae,renderHistoryIndex as xe,renderQuickCommandsPage as Ce,renderFilesIndex as Ie,renderShell as _e}from"../frontend.js";import{renderFederationPage as Ee}from"./pages/federation.js";import{createAgentToken as Oe,removeAgentToken as Ne,listAgentTokens as V}from"./agent-tokens.js";import{hashPassword as Re,verifyPassword as Pe,validatePassword as Le}from"./auth.js";import{atomicWriteFileSync as De}from"./atomicWrite.js";import{resolveFsPath as A,resolveFsRoots as Q,MAX_FILE_BYTES as K,walkRecursive as Fe,fsEntryCmp as X}from"./fs-access.js";import{captureSessionWindowsWithPath as He}from"./tmux-windows.js";import{audit as k}from"./auditLog.js";import{db as b}from"./db.js";import{getSessionAccessMap as Me}from"./session-access.js";import{listWindowHistory as Ue,clearWindowHistory as We}from"./window-history.js";import{saveSecurityConfig as Be}from"./security-config.js";import{ImageUploadError as Ge,saveUploadedImage as $e}from"./image-upload.js";import{readSettings as Z,writeSettings as ze}from"./settings.js";import{readActiveTheme as Ve,setActiveThemeTemplate as Y}from"./theme-store.js";import{isThemeTemplateId as J,THEME_TEMPLATE_IDS as Qe}from"./themes/index.js";import{pinView as Ke,unpinView as Xe,listPinnedViews as Ze}from"./pinned-views.js";import{getStoredWindows as Ye}from"./session-windows.js";import{buildSidebarSessions as Je}from"./sessions-sidebar.js";import{upsertSessionState as ee,removeSessionState as F,renameSessionState as H,computeTombstones as et,getSessionState as tt}from"./session-state.js";import{createQuickCommand as rt,deleteQuickCommand as nt,listQuickCommands as te,updateQuickCommand as st}from"./quick-commands.js";import{getSystemStatus as ot,getTopProcesses as it,killProcess as at}from"./system-monitor.js";import{newTmuxSession as re,renameSession as dt,killSession as ut,sessionExists as ct,TmuxWindowsError as ne}from"./tmux-windows.js";import{registerAgentTunnel as lt}from"./agent-tunnel.js";import{injectScopeScript as mt}from"./scope-script.js";const M="tmux-web-token",pt=365;function ft(x){return x==="127.0.0.1"||x==="::1"||x==="::ffff:127.0.0.1"}const gt=we(import.meta.url),{version:ht}=gt("../../package.json");function tr(x){const{mode:se,securityConfig:y,tokenStore:w,rateLimiter:_,settings:yt,terminalBufferConfig:E,getAgentId:U,state:l,federation:q,hub:f}=x,v=se==="agent";function I(e){if(y.security.trustProxy){const t=(e.req.header("x-forwarded-for")||"").split(",")[0].trim();if(t)return t}return e.env?.incoming?.socket?.remoteAddress||"unknown"}function O(e){const t=e.req.header("authorization");if(t?.startsWith("Bearer "))return t.slice(7);const r=e.req.header("cookie");if(!r)return null;const n=r.match(new RegExp(`(?:^|;\\s*)${M}=([^;]+)`));return n?decodeURIComponent(n[1]):null}function jt(e){const t=O(e);return t?w.validateToken(t):null}function W(e,t){const r=e.req.header("x-forwarded-proto")==="https"||e.req.url.startsWith("https:");e.header("Set-Cookie",`${M}=${encodeURIComponent(t)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${pt*86400}${r?"; Secure":""}`)}function oe(e){e.header("Set-Cookie",`${M}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`)}const i=()=>v?async(e,t)=>t():async(e,t)=>{const r=O(e);return!r||!w.validateToken(r)?(k("http_unauthorized",{ip:I(e)}),e.json({error:"unauthorized"},401)):t()},j=()=>v?async(e,t)=>t():async(e,t)=>{const r=O(e);if(!r||!w.validateToken(r)){const n=encodeURIComponent(e.req.url);return e.redirect(`/login?returnTo=${n}`,302)}return t()};function N(e){const t=D(),r=new Set(t.map(c=>c.name)),n=Je(t,Me(),Ze()),o=[],a=new Map,u=new Map;if(f)for(const c of f.agents.list()){const d=f.agents.get(c.agentId);a.set(c.agentId,new Set((d?d.sessions:[]).map(m=>m.name))),u.set(c.agentId,c.online),o.push({agentId:c.agentId,agentName:c.name,online:c.online,sessions:d?d.sessions:[]})}const g=et(r,a,u);return{...n,currentSession:e??null,agents:o,tombstones:g}}function B(e){const t=typeof e.sessionName=="string"?e.sessionName.trim():"";if(!t)return{error:"sessionName is required"};if(e.windowIndex===void 0)return{sessionName:t};const r=e.windowIndex;return typeof r!="number"||!Number.isInteger(r)||r<0?{error:"windowIndex must be a non-negative integer"}:{sessionName:t,windowIndex:r}}const s=new je;s.use("*",async(e,t)=>{await t(),(e.res.headers.get("content-type")||"").includes("text/html")&&e.header("Cache-Control","no-store"),e.header("X-Content-Type-Options","nosniff"),e.header("X-Frame-Options","DENY"),e.header("Content-Security-Policy",["default-src 'self'","script-src 'self' 'unsafe-inline'","style-src 'self' 'unsafe-inline' https://fonts.googleapis.com","connect-src 'self' ws: wss: http: https:","img-src 'self' data:","font-src 'self' https://fonts.gstatic.com","worker-src 'self' blob:"].join("; ")),e.header("Referrer-Policy","strict-origin-when-cross-origin")}),s.use("*",async(e,t)=>{const r=e.req.method;if(r==="GET"||r==="HEAD"||r==="OPTIONS")return t();const n=e.req.header("sec-fetch-site");return n&&n!=="same-origin"&&n!=="none"?e.text("cross-site request blocked",403):t()}),v||s.use("*",async(e,t)=>{if(await t(),e.req.method!=="GET"||e.req.path==="/login"||!(e.res.headers.get("content-type")??"").includes("text/html"))return;const n=await e.res.text();e.res=new Response(mt(n,{prefix:"",agentId:null}),e.res)});const G=h.dirname(ye(import.meta.url)),ie=[h.join(G,"..","assets"),h.join(G,"assets"),h.join(process.cwd(),"dist","assets")];s.get("/assets/:file",async e=>{const t=e.req.param("file");if(!/^[a-zA-Z0-9._-]+$/.test(t))return e.notFound();for(const r of ie){const n=h.join(r,t);if(!P(n))continue;const o=await ge(n),a=h.extname(t),u={".css":"text/css; charset=utf-8",".js":"application/javascript; charset=utf-8",".map":"application/json; charset=utf-8",".png":"image/png",".svg":"image/svg+xml",".webp":"image/webp",".ico":"image/x-icon"};return e.body(o,200,{"Content-Type":u[a]??"application/octet-stream","Cache-Control":a===".js"||a===".css"?"no-cache":"public, max-age=3600"})}return e.notFound()});const ae=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
|
|
2
|
+
<defs>
|
|
3
|
+
<linearGradient id="bg" x1="0" y1="0" x2="0" y2="1">
|
|
4
|
+
<stop offset="0" stop-color="#101620"/>
|
|
5
|
+
<stop offset="1" stop-color="#090c11"/>
|
|
6
|
+
</linearGradient>
|
|
7
|
+
<radialGradient id="glow" cx="46%" cy="50%" r="62%">
|
|
8
|
+
<stop offset="0" stop-color="#7dd3fc" stop-opacity="0.16"/>
|
|
9
|
+
<stop offset="1" stop-color="#7dd3fc" stop-opacity="0"/>
|
|
10
|
+
</radialGradient>
|
|
11
|
+
</defs>
|
|
12
|
+
<rect width="64" height="64" rx="14" fill="url(#bg)"/>
|
|
13
|
+
<rect width="64" height="64" rx="14" fill="url(#glow)"/>
|
|
14
|
+
<path d="M19 24.3 29 32 19 39.7" fill="none" stroke="#7dd3fc" stroke-width="4.6" stroke-linecap="round" stroke-linejoin="round"/>
|
|
15
|
+
<line x1="35" y1="39.7" x2="45" y2="39.7" stroke="#7dd3fc" stroke-width="4.6" stroke-linecap="round"/>
|
|
16
|
+
</svg>`,$=e=>e.body(ae,200,{"Content-Type":"image/svg+xml; charset=utf-8","Cache-Control":"public, max-age=86400"});s.get("/favicon.svg",$),s.get("/favicon.ico",$),s.get("/manifest.json",async e=>{const t=await Ve();return e.json({id:"/",name:"tmux-weblink",short_name:"tmux-web",description:"Access your tmux sessions from the browser",start_url:"/",scope:"/",display:"standalone",display_override:["standalone","minimal-ui"],orientation:"any",background_color:t.shell.pageBg,theme_color:t.shell.panelBg,categories:["developer","productivity","utilities"],icons:[{src:"/assets/icon-192.png",sizes:"192x192",type:"image/png",purpose:"any"},{src:"/assets/icon-512.png",sizes:"512x512",type:"image/png",purpose:"any"},{src:"/assets/icon-maskable-192.png",sizes:"192x192",type:"image/png",purpose:"maskable"},{src:"/assets/icon-maskable-512.png",sizes:"512x512",type:"image/png",purpose:"maskable"}]},200,{"Cache-Control":"public, max-age=300"})});const de=`// tmux-weblink Service Worker
|
|
6
17
|
const CACHE = "tmux-weblink-v2";
|
|
7
|
-
const ASSETS = [
|
|
18
|
+
const ASSETS = [
|
|
19
|
+
"/", "/manifest.json", "/favicon.svg",
|
|
20
|
+
"/assets/icon-192.png", "/assets/icon-512.png",
|
|
21
|
+
"/assets/icon-maskable-192.png", "/assets/icon-maskable-512.png",
|
|
22
|
+
"/assets/apple-touch-icon-180.png",
|
|
23
|
+
];
|
|
8
24
|
self.addEventListener("install", (e) => {
|
|
9
25
|
e.waitUntil(caches.open(CACHE).then((c) => c.addAll(ASSETS)));
|
|
10
26
|
self.skipWaiting();
|
|
@@ -18,7 +34,7 @@ self.addEventListener("activate", (e) => {
|
|
|
18
34
|
self.addEventListener("fetch", (e) => {
|
|
19
35
|
e.respondWith(fetch(e.request).catch(() => caches.match(e.request)));
|
|
20
36
|
});
|
|
21
|
-
`;o.get("/sw.js",e=>e.body(ue,200,{"Content-Type":"application/javascript; charset=utf-8"})),o.get("/login",e=>{const r=e.req.query("setup")==="1"?!0:!y.passwordHash,n=e.req.query("error");return e.html(Se({setupMode:r,error:n?decodeURIComponent(n):void 0,theme:l.activeTheme}))}),o.get("/",j(),e=>{const t=Q();return e.html(Ee({theme:l.activeTheme,version:gt,fsRoots:t,terminalCfg:E,scrollback:E.initialLines+2*E.historyChunk,wsBase:k&&U?.()?`/ws/a/${U()}`:void 0}))}),o.get("/notes",j(),e=>e.html(be(S.data.notes,l.activeTheme))),o.get("/notes/:session",j(),e=>{const t=decodeURIComponent(e.req.param("session"));return e.html(Te(t,l.activeTheme))}),o.get("/history",j(),e=>{const t=F(),r=new Set(t.map(n=>n.name));return e.html(Ce(We(),l.activeTheme,r))}),o.get("/quick-commands",j(),e=>e.html(Ie(te(),l.activeTheme))),o.get("/files",j(),e=>{const t=Q();return e.html(_e(l.activeTheme,t))}),o.post("/api/history/clear",i(),async e=>(await Be(),e.json({ok:!0}))),o.get("/api/quick-commands",i(),e=>e.json(te())),o.post("/api/quick-commands",i(),async e=>{let t;try{t=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const r=await rt(t);return"error"in r?e.json({error:r.error},400):e.json(r,201)}),o.patch("/api/quick-commands/:id",i(),async e=>{let t;try{t=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const r=await ot(e.req.param("id"),t);return"error"in r?e.json({error:r.error},r.status):e.json(r)}),o.delete("/api/quick-commands/:id",i(),e=>nt(e.req.param("id"))?e.json({ok:!0}):e.json({error:"not found"},404)),o.post("/api/auth/password",async e=>{if(k)return e.json({error:"hub only"},403);const t=I(e),r=_.check(t);if(!r.allowed)return v("rate_limited",{ip:t,retryAfterMs:r.retryAfterMs,permanentLock:r.permanentLock}),r.permanentLock?e.json({error:"Server locked after too many failed attempts",permanentLock:!0},403):e.json({error:"Too many attempts",retryAfterMs:r.retryAfterMs},429);let n;try{n=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const s=typeof n.password=="string"?n.password:"";if(!y.passwordHash){if(!y.security.allowRemoteSetup&&!pt(t))return v("setup_rejected_remote",{ip:t}),e.json({error:"First-run setup must be performed from localhost"},403);if(l.settingUpPassword)return e.json({error:"Password setup in progress"},409);const c=Fe(s);if(c)return e.json({error:c},400);l.settingUpPassword=!0;try{y.passwordHash=await Pe(s),$e(y),v("password_set",{ip:t})}finally{l.settingUpPassword=!1}const{plaintext:d}=w.createAccessToken("setup",y.security.tokenTtlDays);return W(e,d),e.json({ok:!0,token:d,setupMode:!0})}if(!await Le(s,y.passwordHash)){const c=_.recordFailure(t);return v("auth_failed",{ip:t,method:"password",failures:c.failures,permanentLock:c.permanentLock}),c.permanentLock?(w.revokeAll(),v("permanent_lock",{ip:t,failures:c.failures}),e.json({error:"Server locked after too many failed attempts",permanentLock:!0},403)):c.allowed?e.json({error:"Incorrect password"},401):e.json({error:"Too many attempts",retryAfterMs:c.retryAfterMs},429)}_.recordSuccess(t);const u=`browser-${t}`,{plaintext:h}=w.createAccessToken(u,y.security.tokenTtlDays);return W(e,h),v("auth_success",{ip:t,method:"password",tokenName:u}),e.json({ok:!0,token:h})}),o.post("/api/auth/token",i(),async e=>{if(k)return e.json({error:"hub only"},403);const t=I(e);let r;try{r=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const n=typeof r.name=="string"?r.name:`api-${t}`,s=typeof r.ttlDays=="number"?r.ttlDays:y.security.tokenTtlDays,{stored:a,plaintext:u}=w.createAccessToken(n,s);return v("token_created",{ip:t,name:a.name,tokenId:a.id}),e.json({id:a.id,name:a.name,token:u,expiresAt:a.expiresAt})}),o.get("/api/auth/tokens",i(),e=>k?e.json({error:"hub only"},403):e.json(w.list().map(t=>({id:t.id,name:t.name,createdAt:t.createdAt,lastUsedAt:t.lastUsedAt,expiresAt:t.expiresAt})))),o.delete("/api/auth/tokens/:id",i(),e=>k?e.json({error:"hub only"},403):w.revoke(e.req.param("id"))?(v("token_revoked",{ip:I(e),tokenId:e.req.param("id")}),e.json({ok:!0})):e.json({error:"not found"},404)),o.post("/api/auth/logout",i(),e=>(se(e),e.json({ok:!0}))),o.get("/settings",j(),async e=>{const t=await Z();return e.html(Ae({settings:t,theme:l.activeTheme,saved:e.req.query("saved")==="1",error:e.req.query("error")?decodeURIComponent(e.req.query("error")):void 0}))}),o.post("/settings",i(),async e=>{let t;try{t=await e.req.parseBody()}catch{return e.redirect("/settings?error="+encodeURIComponent("invalid form body"),303)}const r=await Z(),n=t.defaultView==="recent"?"recent":"default";return await Ve({...r,defaultView:n}),e.redirect("/settings?saved=1",303)}),o.get("/settings/theme",j(),e=>e.html(xe({theme:l.activeTheme,saved:e.req.query("saved")==="1"}))),o.post("/settings/theme",i(),async e=>{let t;try{t=await e.req.parseBody()}catch{return e.redirect("/settings/theme?error=1",303)}const r=t.template;return typeof r!="string"||!J(r)?e.redirect("/settings/theme",303):(l.activeTheme=await Y(r),e.redirect("/settings/theme?saved=1",303))});const ce={vscode:"VS Code",ghostty:"Ghostty","warm-clay":"Warm Clay","dark-cove":"Dark Cove"};o.get("/api/theme",i(),e=>e.json({active:l.activeTheme.template,templates:Qe.map(t=>({id:t,name:ce[t]}))})),o.post("/api/theme",i(),async e=>{let t;try{t=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const r=t.template;return typeof r!="string"||!J(r)?e.json({error:"invalid theme template"},400):(l.activeTheme=await Y(r),e.json({ok:!0,active:l.activeTheme.template}))}),o.get("/api/system/status",i(),e=>e.json(st())),o.get("/api/system/processes",i(),e=>e.json(it())),q&&(o.get("/settings/federation",j(),e=>e.redirect("/settings/machines",301)),o.get("/settings/machines",j(),async e=>e.html(Oe({config:q.getConfig(),status:q.status(),tokens:V().map(t=>({id:t.id,name:t.name,createdAt:t.createdAt})),hostname:q.hostname},l.activeTheme))),o.get("/api/machines",i(),e=>e.json({config:q.getConfig(),status:q.status()})),o.post("/api/machines",i(),async e=>{let t;try{t=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const r=typeof t.hub=="string"?t.hub.trim():"",n=typeof t.token=="string"?t.token.trim():"",s=typeof t.name=="string"?t.name.trim().slice(0,64):"",a=t.enabled===!0;if(a){if(!r)return e.json({error:"hub URL is required"},400);if(!/^wss?:\/\//i.test(r))return e.json({error:"hub URL must start with ws:// or wss://"},400);if(!n)return e.json({error:"registration token is required"},400)}const u={hub:r||void 0,token:n||void 0,name:s||void 0,enabled:a};return await q.setConfig(u),e.json({ok:!0,status:q.status()})}),o.get("/api/agent-tokens",i(),e=>e.json(V().map(t=>({id:t.id,name:t.name,createdAt:t.createdAt})))),o.post("/api/agent-tokens",i(),async e=>{let t;try{t=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const r=typeof t.name=="string"?t.name.trim().slice(0,64):"";if(!r)return e.json({error:"name is required"},400);const{id:n,token:s}=Ne(r);return e.json({ok:!0,id:n,name:r,token:s})}),o.delete("/api/agent-tokens/:id",i(),e=>{const t=e.req.param("id");return Re(t)?e.json({ok:!0}):e.json({error:"no such token"},404)})),o.post("/api/system/kill",i(),async e=>{const{pid:t}=await e.req.json();if(typeof t!="number"||!Number.isInteger(t)||t<=0)return e.json({error:"invalid pid"},400);const r=at(t);return r.ok?e.json({ok:!0}):e.json({error:r.error},500)}),o.get("/api/agents",i(),e=>p?e.json(p.agents.list()):e.json([])),o.post("/api/sessions/new",i(),async e=>{let t;try{t=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const r=typeof t.name=="string"?t.name.trim():"";if(!r)return e.json({error:"name is required"},400);if(!/^[a-zA-Z0-9_\-. ]+$/.test(r))return e.json({error:"name contains invalid characters"},400);const n=typeof t.dir=="string"&&t.dir.trim()?t.dir.trim():void 0;if(F().some(a=>a.name===r))return e.json({error:"session already exists"},409);try{return re(r,n),ee(r,{path:n}),e.json({ok:!0})}catch(a){const u=a instanceof ne?a.message:"failed to create session";return e.json({error:u},500)}}),o.post("/api/sessions/rename",i(),async e=>{try{const t=await e.req.json(),{oldName:r,newName:n}=t,s=typeof t.agentId=="string"?t.agentId:void 0;if(!r||!n)return e.json({error:"oldName and newName required"},400);if(!/^[a-zA-Z0-9_\-. ]+$/.test(n))return e.json({error:"invalid characters in name"},400);if(s){if(!p)return e.json({error:"not a hub"},400);const a=p.getChannel(s);return!a||!a.renameSession(r,n)?e.json({error:"agent offline"},409):(H(r,n,s),e.json({ok:!0,async:!0}))}return dt(r,n),H(r,n),e.json({ok:!0})}catch{return e.json({error:"rename failed"},500)}}),o.post("/api/sessions/kill",i(),async e=>{try{const t=await e.req.json(),{name:r}=t,n=typeof t.agentId=="string"?t.agentId:void 0;if(!r)return e.json({error:"name required"},400);if(n){if(!p)return e.json({error:"not a hub"},400);const s=p.getChannel(n);return!s||!s.killSession(r)?e.json({error:"agent offline"},409):(D(r,n),e.json({ok:!0,async:!0}))}return ut(r),D(r),e.json({ok:!0})}catch{return e.json({error:"kill failed"},500)}}),o.post("/api/sessions/rebuild",i(),async e=>{try{const t=await e.req.json(),r=typeof t.name=="string"?t.name.trim():"";if(!r)return e.json({error:"name required"},400);const n=typeof t.agentId=="string"?t.agentId:void 0,a=tt().find(u=>u.name===r&&(u.agentId??null)===(n??null))?.path;if(n){if(!p)return e.json({error:"not a hub"},400);const u=p.getChannel(n);return u?u.rebuildSession(r,a)?e.json({ok:!0,async:!0}):e.json({error:"agent offline"},409):e.json({error:"agent offline"},409)}if(ct(r))return e.json({error:"session already exists"},409);try{re(r,a)}catch(u){const h=u instanceof ne?u.message:"rebuild failed";return e.json({error:h},500)}return ee(r,{path:a}),e.json({ok:!0})}catch{return e.json({error:"rebuild failed"},500)}}),o.post("/api/sessions/dismiss",i(),async e=>{try{const t=await e.req.json(),r=typeof t.name=="string"?t.name.trim():"";if(!r)return e.json({error:"name required"},400);const n=typeof t.agentId=="string"?t.agentId:void 0;return D(r,n),e.json({ok:!0})}catch{return e.json({error:"dismiss failed"},500)}}),o.post("/api/sessions/rename-tombstone",i(),async e=>{try{const t=await e.req.json(),r=typeof t.oldName=="string"?t.oldName.trim():"",n=typeof t.newName=="string"?t.newName.trim():"";if(!r||!n)return e.json({error:"oldName and newName required"},400);if(!/^[a-zA-Z0-9_\-. ]+$/.test(n))return e.json({error:"invalid characters in name"},400);const s=typeof t.agentId=="string"?t.agentId:void 0;return H(r,n,s),e.json({ok:!0})}catch{return e.json({error:"rename failed"},500)}}),o.get("/api/session-program",i(),e=>{const t=e.req.query("session");if(!t)return e.json({program:null});try{const n=L("tmux",["display-message","-p","-t",t,"#{pane_current_command}"],{encoding:"utf-8",timeout:3e3,env:ye()}).trim()||null;return e.json({program:n})}catch{return e.json({program:null})}}),o.post("/api/session/:name/upload",i(),async e=>{try{const r=(await e.req.parseBody()).file;if(!(r instanceof File))return e.json({error:'expected a file field named "file"'},400);const n=Buffer.from(await r.arrayBuffer()),{path:s}=await ze(n,r.type,r.name);return e.json({path:s})}catch(t){return t instanceof Ge?e.json({error:t.message},t.status):e.json({error:"upload failed"},500)}}),o.get("/api/fs/session-path",i(),e=>{const t=e.req.query("session");if(!t)return e.json({path:process.env.HOME??"/"});try{const r=Me(t),s=r.find(a=>a.active)?.path??r[0]?.path??process.env.HOME??"/";return e.json({path:s})}catch{return e.json({path:process.env.HOME??"/"})}}),o.get("/api/fs/list",i(),e=>{const t=process.env.HOME??"/";let r=e.req.query("path")??t;r.startsWith("~")&&(r=t+r.slice(1)),r.startsWith("/")||(r=g.join(t,r));const n=e.req.query("recursive")==="true";let s=r,a="",u=r.endsWith("/");if(!u)try{u=T(r).isDirectory()}catch{}u||(s=g.dirname(r),a=g.basename(r).toLowerCase());try{const h=me(s),c=[],d=[];for(const m of h)if(!(a&&!m.toLowerCase().startsWith(a))){try{const f=g.join(s,m);T(f).isDirectory()?(c.push(f),n&&He(f,c,d,0)):d.push(f)}catch{}if(c.length+d.length>=5e3)break}return c.sort(X),d.sort(X),e.json({dirs:c,files:d,path:s})}catch{return e.json({dirs:[],files:[]})}});function le(e){const t={repoRoot:null,branch:null,files:[],linesAdded:0,linesRemoved:0};try{const r=C("git rev-parse --show-toplevel 2>/dev/null",{cwd:e,encoding:"utf-8",timeout:3e3}).trim();if(!r)return t;let n;try{n=C("git branch --show-current 2>/dev/null",{cwd:r,encoding:"utf-8",timeout:3e3}).trim()}catch{n=C("git rev-parse --short HEAD 2>/dev/null",{cwd:r,encoding:"utf-8",timeout:3e3}).trim()}n||(n="HEAD");let s="";try{s=C("git status --porcelain 2>/dev/null",{cwd:r,encoding:"utf-8",timeout:3e3})}catch{}const a=[];for(const d of s.split(`
|
|
22
|
-
`)){if(!d.trim())continue;const m=d[0],
|
|
23
|
-
`)){if(!m.trim())continue;const
|
|
24
|
-
`).length;d.additions=
|
|
37
|
+
`;s.get("/sw.js",e=>e.body(de,200,{"Content-Type":"application/javascript; charset=utf-8"})),s.get("/login",e=>{const r=e.req.query("setup")==="1"?!0:!y.passwordHash,n=e.req.query("error");return e.html(qe({setupMode:r,error:n?decodeURIComponent(n):void 0,theme:l.activeTheme}))}),s.get("/",j(),e=>{const t=Q();return e.html(_e({theme:l.activeTheme,version:ht,fsRoots:t,terminalCfg:E,scrollback:E.initialLines+2*E.historyChunk,wsBase:v&&U?.()?`/ws/a/${U()}`:void 0}))}),s.get("/notes",j(),e=>e.html(be(b.data.notes,l.activeTheme))),s.get("/notes/:session",j(),e=>{const t=decodeURIComponent(e.req.param("session"));return e.html(Se(t,l.activeTheme))}),s.get("/history",j(),e=>{const t=D(),r=new Set(t.map(n=>n.name));return e.html(xe(Ue(),l.activeTheme,r))}),s.get("/quick-commands",j(),e=>e.html(Ce(te(),l.activeTheme))),s.get("/files",j(),e=>{const t=Q();return e.html(Ie(l.activeTheme,t))}),s.post("/api/history/clear",i(),async e=>(await We(),e.json({ok:!0}))),s.get("/api/quick-commands",i(),e=>e.json(te())),s.post("/api/quick-commands",i(),async e=>{let t;try{t=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const r=await rt(t);return"error"in r?e.json({error:r.error},400):e.json(r,201)}),s.patch("/api/quick-commands/:id",i(),async e=>{let t;try{t=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const r=await st(e.req.param("id"),t);return"error"in r?e.json({error:r.error},r.status):e.json(r)}),s.delete("/api/quick-commands/:id",i(),e=>nt(e.req.param("id"))?e.json({ok:!0}):e.json({error:"not found"},404)),s.post("/api/auth/password",async e=>{if(v)return e.json({error:"hub only"},403);const t=I(e),r=_.check(t);if(!r.allowed)return k("rate_limited",{ip:t,retryAfterMs:r.retryAfterMs,permanentLock:r.permanentLock}),r.permanentLock?e.json({error:"Server locked after too many failed attempts",permanentLock:!0},403):e.json({error:"Too many attempts",retryAfterMs:r.retryAfterMs},429);let n;try{n=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const o=typeof n.password=="string"?n.password:"";if(!y.passwordHash){if(!y.security.allowRemoteSetup&&!ft(t))return k("setup_rejected_remote",{ip:t}),e.json({error:"First-run setup must be performed from localhost"},403);if(l.settingUpPassword)return e.json({error:"Password setup in progress"},409);const c=Le(o);if(c)return e.json({error:c},400);l.settingUpPassword=!0;try{y.passwordHash=await Re(o),Be(y),k("password_set",{ip:t})}finally{l.settingUpPassword=!1}const{plaintext:d}=w.createAccessToken("setup",y.security.tokenTtlDays);return W(e,d),e.json({ok:!0,token:d,setupMode:!0})}if(!await Pe(o,y.passwordHash)){const c=_.recordFailure(t);return k("auth_failed",{ip:t,method:"password",failures:c.failures,permanentLock:c.permanentLock}),c.permanentLock?(w.revokeAll(),k("permanent_lock",{ip:t,failures:c.failures}),e.json({error:"Server locked after too many failed attempts",permanentLock:!0},403)):c.allowed?e.json({error:"Incorrect password"},401):e.json({error:"Too many attempts",retryAfterMs:c.retryAfterMs},429)}_.recordSuccess(t);const u=`browser-${t}`,{plaintext:g}=w.createAccessToken(u,y.security.tokenTtlDays);return W(e,g),k("auth_success",{ip:t,method:"password",tokenName:u}),e.json({ok:!0,token:g})}),s.post("/api/auth/token",i(),async e=>{if(v)return e.json({error:"hub only"},403);const t=I(e);let r;try{r=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const n=typeof r.name=="string"?r.name:`api-${t}`,o=typeof r.ttlDays=="number"?r.ttlDays:y.security.tokenTtlDays,{stored:a,plaintext:u}=w.createAccessToken(n,o);return k("token_created",{ip:t,name:a.name,tokenId:a.id}),e.json({id:a.id,name:a.name,token:u,expiresAt:a.expiresAt})}),s.get("/api/auth/tokens",i(),e=>v?e.json({error:"hub only"},403):e.json(w.list().map(t=>({id:t.id,name:t.name,createdAt:t.createdAt,lastUsedAt:t.lastUsedAt,expiresAt:t.expiresAt})))),s.delete("/api/auth/tokens/:id",i(),e=>v?e.json({error:"hub only"},403):w.revoke(e.req.param("id"))?(k("token_revoked",{ip:I(e),tokenId:e.req.param("id")}),e.json({ok:!0})):e.json({error:"not found"},404)),s.post("/api/auth/logout",i(),e=>(oe(e),e.json({ok:!0}))),s.get("/settings",j(),async e=>{const t=await Z();return e.html(Te({settings:t,theme:l.activeTheme,saved:e.req.query("saved")==="1",error:e.req.query("error")?decodeURIComponent(e.req.query("error")):void 0}))}),s.post("/settings",i(),async e=>{let t;try{t=await e.req.parseBody()}catch{return e.redirect("/settings?error="+encodeURIComponent("invalid form body"),303)}const r=await Z(),n=t.defaultView==="recent"?"recent":"default";return await ze({...r,defaultView:n}),e.redirect("/settings?saved=1",303)}),s.get("/settings/theme",j(),e=>e.html(Ae({theme:l.activeTheme,saved:e.req.query("saved")==="1"}))),s.post("/settings/theme",i(),async e=>{let t;try{t=await e.req.parseBody()}catch{return e.redirect("/settings/theme?error=1",303)}const r=t.template;return typeof r!="string"||!J(r)?e.redirect("/settings/theme",303):(l.activeTheme=await Y(r),e.redirect("/settings/theme?saved=1",303))});const ue={vscode:"VS Code",ghostty:"Ghostty","warm-clay":"Warm Clay","dark-cove":"Dark Cove"};s.get("/api/theme",i(),e=>e.json({active:l.activeTheme.template,templates:Qe.map(t=>({id:t,name:ue[t]}))})),s.post("/api/theme",i(),async e=>{let t;try{t=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const r=t.template;return typeof r!="string"||!J(r)?e.json({error:"invalid theme template"},400):(l.activeTheme=await Y(r),e.json({ok:!0,active:l.activeTheme.template}))}),s.get("/api/system/status",i(),e=>e.json(ot())),s.get("/api/system/processes",i(),e=>e.json(it())),q&&(s.get("/settings/federation",j(),e=>e.redirect("/settings/machines",301)),s.get("/settings/machines",j(),async e=>e.html(Ee({config:q.getConfig(),status:q.status(),tokens:V().map(t=>({id:t.id,name:t.name,createdAt:t.createdAt})),hostname:q.hostname},l.activeTheme))),s.get("/api/machines",i(),e=>e.json({config:q.getConfig(),status:q.status()})),s.post("/api/machines",i(),async e=>{let t;try{t=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const r=typeof t.hub=="string"?t.hub.trim():"",n=typeof t.token=="string"?t.token.trim():"",o=typeof t.name=="string"?t.name.trim().slice(0,64):"",a=t.enabled===!0;if(a){if(!r)return e.json({error:"hub URL is required"},400);if(!/^wss?:\/\//i.test(r))return e.json({error:"hub URL must start with ws:// or wss://"},400);if(!n)return e.json({error:"registration token is required"},400)}const u={hub:r||void 0,token:n||void 0,name:o||void 0,enabled:a};return await q.setConfig(u),e.json({ok:!0,status:q.status()})}),s.get("/api/agent-tokens",i(),e=>e.json(V().map(t=>({id:t.id,name:t.name,createdAt:t.createdAt})))),s.post("/api/agent-tokens",i(),async e=>{let t;try{t=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const r=typeof t.name=="string"?t.name.trim().slice(0,64):"";if(!r)return e.json({error:"name is required"},400);const{id:n,token:o}=Oe(r);return e.json({ok:!0,id:n,name:r,token:o})}),s.delete("/api/agent-tokens/:id",i(),e=>{const t=e.req.param("id");return Ne(t)?e.json({ok:!0}):e.json({error:"no such token"},404)})),s.post("/api/system/kill",i(),async e=>{const{pid:t}=await e.req.json();if(typeof t!="number"||!Number.isInteger(t)||t<=0)return e.json({error:"invalid pid"},400);const r=at(t);return r.ok?e.json({ok:!0}):e.json({error:r.error},500)}),s.get("/api/agents",i(),e=>f?e.json(f.agents.list()):e.json([])),s.post("/api/sessions/new",i(),async e=>{let t;try{t=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const r=typeof t.name=="string"?t.name.trim():"";if(!r)return e.json({error:"name is required"},400);if(!/^[a-zA-Z0-9_\-. ]+$/.test(r))return e.json({error:"name contains invalid characters"},400);const n=typeof t.dir=="string"&&t.dir.trim()?t.dir.trim():void 0;if(D().some(a=>a.name===r))return e.json({error:"session already exists"},409);try{return re(r,n),ee(r,{path:n}),e.json({ok:!0})}catch(a){const u=a instanceof ne?a.message:"failed to create session";return e.json({error:u},500)}}),s.post("/api/sessions/rename",i(),async e=>{try{const t=await e.req.json(),{oldName:r,newName:n}=t,o=typeof t.agentId=="string"?t.agentId:void 0;if(!r||!n)return e.json({error:"oldName and newName required"},400);if(!/^[a-zA-Z0-9_\-. ]+$/.test(n))return e.json({error:"invalid characters in name"},400);if(o){if(!f)return e.json({error:"not a hub"},400);const a=f.getChannel(o);return!a||!a.renameSession(r,n)?e.json({error:"agent offline"},409):(H(r,n,o),e.json({ok:!0,async:!0}))}return dt(r,n),H(r,n),e.json({ok:!0})}catch{return e.json({error:"rename failed"},500)}}),s.post("/api/sessions/kill",i(),async e=>{try{const t=await e.req.json(),{name:r}=t,n=typeof t.agentId=="string"?t.agentId:void 0;if(!r)return e.json({error:"name required"},400);if(n){if(!f)return e.json({error:"not a hub"},400);const o=f.getChannel(n);return!o||!o.killSession(r)?e.json({error:"agent offline"},409):(F(r,n),e.json({ok:!0,async:!0}))}return ut(r),F(r),e.json({ok:!0})}catch{return e.json({error:"kill failed"},500)}}),s.post("/api/sessions/rebuild",i(),async e=>{try{const t=await e.req.json(),r=typeof t.name=="string"?t.name.trim():"";if(!r)return e.json({error:"name required"},400);const n=typeof t.agentId=="string"?t.agentId:void 0,a=tt().find(u=>u.name===r&&(u.agentId??null)===(n??null))?.path;if(n){if(!f)return e.json({error:"not a hub"},400);const u=f.getChannel(n);return u?u.rebuildSession(r,a)?e.json({ok:!0,async:!0}):e.json({error:"agent offline"},409):e.json({error:"agent offline"},409)}if(ct(r))return e.json({error:"session already exists"},409);try{re(r,a)}catch(u){const g=u instanceof ne?u.message:"rebuild failed";return e.json({error:g},500)}return ee(r,{path:a}),e.json({ok:!0})}catch{return e.json({error:"rebuild failed"},500)}}),s.post("/api/sessions/dismiss",i(),async e=>{try{const t=await e.req.json(),r=typeof t.name=="string"?t.name.trim():"";if(!r)return e.json({error:"name required"},400);const n=typeof t.agentId=="string"?t.agentId:void 0;return F(r,n),e.json({ok:!0})}catch{return e.json({error:"dismiss failed"},500)}}),s.post("/api/sessions/rename-tombstone",i(),async e=>{try{const t=await e.req.json(),r=typeof t.oldName=="string"?t.oldName.trim():"",n=typeof t.newName=="string"?t.newName.trim():"";if(!r||!n)return e.json({error:"oldName and newName required"},400);if(!/^[a-zA-Z0-9_\-. ]+$/.test(n))return e.json({error:"invalid characters in name"},400);const o=typeof t.agentId=="string"?t.agentId:void 0;return H(r,n,o),e.json({ok:!0})}catch{return e.json({error:"rename failed"},500)}}),s.get("/api/session-program",i(),e=>{const t=e.req.query("session");if(!t)return e.json({program:null});try{const n=L("tmux",["display-message","-p","-t",t,"#{pane_current_command}"],{encoding:"utf-8",timeout:3e3,env:he()}).trim()||null;return e.json({program:n})}catch{return e.json({program:null})}}),s.post("/api/session/:name/upload",i(),async e=>{try{const r=(await e.req.parseBody()).file;if(!(r instanceof File))return e.json({error:'expected a file field named "file"'},400);const n=Buffer.from(await r.arrayBuffer()),{path:o}=await $e(n,r.type,r.name);return e.json({path:o})}catch(t){return t instanceof Ge?e.json({error:t.message},t.status):e.json({error:"upload failed"},500)}}),s.get("/api/fs/session-path",i(),e=>{const t=e.req.query("session");if(!t)return e.json({path:process.env.HOME??"/"});try{const r=He(t),o=r.find(a=>a.active)?.path??r[0]?.path??process.env.HOME??"/";return e.json({path:o})}catch{return e.json({path:process.env.HOME??"/"})}}),s.get("/api/fs/list",i(),e=>{const t=process.env.HOME??"/";let r=e.req.query("path")??t;r.startsWith("~")&&(r=t+r.slice(1)),r.startsWith("/")||(r=h.join(t,r));const n=e.req.query("recursive")==="true";let o=r,a="",u=r.endsWith("/");if(!u)try{u=T(r).isDirectory()}catch{}u||(o=h.dirname(r),a=h.basename(r).toLowerCase());try{const g=le(o),c=[],d=[];for(const m of g)if(!(a&&!m.toLowerCase().startsWith(a))){try{const p=h.join(o,m);T(p).isDirectory()?(c.push(p),n&&Fe(p,c,d,0)):d.push(p)}catch{}if(c.length+d.length>=5e3)break}return c.sort(X),d.sort(X),e.json({dirs:c,files:d,path:o})}catch{return e.json({dirs:[],files:[]})}});function ce(e){const t={repoRoot:null,branch:null,files:[],linesAdded:0,linesRemoved:0};try{const r=C("git rev-parse --show-toplevel 2>/dev/null",{cwd:e,encoding:"utf-8",timeout:3e3}).trim();if(!r)return t;let n;try{n=C("git branch --show-current 2>/dev/null",{cwd:r,encoding:"utf-8",timeout:3e3}).trim()}catch{n=C("git rev-parse --short HEAD 2>/dev/null",{cwd:r,encoding:"utf-8",timeout:3e3}).trim()}n||(n="HEAD");let o="";try{o=C("git status --porcelain 2>/dev/null",{cwd:r,encoding:"utf-8",timeout:3e3})}catch{}const a=[];for(const d of o.split(`
|
|
38
|
+
`)){if(!d.trim())continue;const m=d[0],p=d[1],S=d.substring(3).trim(),R=p!==" "?p:m;a.push({path:S,status:R,staged:m,unstaged:p,additions:0,deletions:0})}const u=new Map;try{const d=C("git diff --numstat HEAD 2>/dev/null",{cwd:r,encoding:"utf-8",timeout:3e3});for(const m of d.split(`
|
|
39
|
+
`)){if(!m.trim())continue;const p=m.split(" ");if(p.length>=3){const S=parseInt(p[0],10)||0,R=parseInt(p[1],10)||0;u.set(p[2],{added:S,deleted:R})}}}catch{}for(const d of a){const m=u.get(d.path);m&&(d.additions=m.added,d.deletions=m.deleted)}let g=0,c=0;for(const d of a)g+=d.additions,c+=d.deletions;for(const d of a)if(d.status==="?"&&d.additions===0)try{const m=h.join(r,d.path),S=z(m,"utf-8").split(`
|
|
40
|
+
`).length;d.additions=S,g+=S}catch{}return{repoRoot:r,branch:n,files:a,linesAdded:g,linesRemoved:c}}catch{return t}}if(s.get("/api/git/status",i(),e=>{const t=e.req.query("path");if(!t)return e.json({error:"path is required"},400);try{const r=A(t),n=ce(r);return e.json(n)}catch(r){return r.message==="FS_ROOTS_NOT_CONFIGURED"?e.json({error:"file access not configured"},403):r.message==="PATH_NOT_ALLOWED"?e.json({error:"path not allowed"},403):e.json({repoRoot:null,branch:null,files:[],linesAdded:0,linesRemoved:0})}}),s.get("/api/git/diff",i(),e=>{const t=e.req.query("path"),r=e.req.query("file");if(!t||!r)return e.json({error:"path and file are required"},400);try{const n=A(t);if(!P(n)||!T(n).isDirectory())return e.json({error:"invalid repository path: "+n},400);try{const o=L("/usr/bin/git",["diff","HEAD","--",r],{cwd:n,encoding:"utf-8",timeout:5e3}),a=L("/usr/bin/git",["diff","--cached","--",r],{cwd:n,encoding:"utf-8",timeout:5e3});return e.json({diff:o,stagedDiff:a})}catch(o){throw console.error("[git/diff] execFileSync failed:",o?.code,o.message),o}}catch(n){return n.message==="FS_ROOTS_NOT_CONFIGURED"?e.json({error:"file access not configured"},403):n.message==="PATH_NOT_ALLOWED"?e.json({error:"path not allowed"},403):(console.error("[git/diff] exception:",n),e.json({error:String(n)},500))}}),s.get("/api/file",i(),e=>{try{const t=e.req.query("path");if(!t)return e.json({error:"path is required"},400);const r=A(t);if(!T(r).isFile())return e.json({error:"not a file"},400);const n=T(r).size;if(n>K)return e.json({error:"file too large",size:n,maxBytes:K},413);const o=z(r,"utf-8");return e.json({path:r,content:o,size:n})}catch(t){return t.message==="FS_ROOTS_NOT_CONFIGURED"?e.json({error:"file access not configured"},403):t.message==="PATH_NOT_ALLOWED"?e.json({error:"path not allowed"},403):t.code==="ENOENT"?e.json({error:"not found"},404):e.json({error:"internal error"},500)}}),s.put("/api/file",i(),async e=>{try{const t=await e.req.json();if(!t.path||typeof t.content!="string")return e.json({error:"path and content are required"},400);const r=A(t.path);return De(r,t.content),e.json({ok:!0})}catch(t){return t.message==="FS_ROOTS_NOT_CONFIGURED"?e.json({error:"file access not configured"},403):t.message==="PATH_NOT_ALLOWED"?e.json({error:"path not allowed"},403):e.json({error:"write failed"},500)}}),s.post("/api/file/delete",i(),async e=>{try{const t=await e.req.json();if(!t.path)return e.json({error:"path is required"},400);const r=A(t.path);return T(r).isFile()?(me(r),e.json({ok:!0})):e.json({error:"not a file"},400)}catch(t){return t.message==="FS_ROOTS_NOT_CONFIGURED"?e.json({error:"file access not configured"},403):t.message==="PATH_NOT_ALLOWED"?e.json({error:"path not allowed"},403):e.json({error:"delete failed"},500)}}),s.post("/api/file/touch",i(),async e=>{try{const t=await e.req.json();if(!t.path)return e.json({error:"path is required"},400);const r=A(t.path);return P(r)?e.json({error:"file already exists"},409):(fe(h.dirname(r),{recursive:!0}),pe(r,"","utf-8"),e.json({ok:!0,path:r}))}catch(t){return t.message==="FS_ROOTS_NOT_CONFIGURED"?e.json({error:"file access not configured"},403):t.message==="PATH_NOT_ALLOWED"?e.json({error:"path not allowed"},403):e.json({error:"touch failed"},500)}}),s.get("/api/sidebar/sessions",i(),e=>{const t=e.req.query("currentSession");return e.json(N(typeof t=="string"&&t?t:void 0))}),s.get("/api/sidebar/session-windows/:session",i(),e=>{const t=decodeURIComponent(e.req.param("session"));return e.json(Ye(t))}),s.post("/api/pinned-views",i(),async e=>{let t;try{t=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const r=B(t);return"error"in r?e.json({error:r.error},400):(await Ke(r.sessionName,r.windowIndex),e.json(N()))}),s.delete("/api/pinned-views",i(),async e=>{let t;try{t=await e.req.json()}catch{return e.json({error:"invalid json"},400)}const r=B(t);return"error"in r?e.json({error:r.error},400):(await Xe(r.sessionName,r.windowIndex),e.json(N()))}),s.get("/api/notes",i(),e=>{const t=[...b.data.notes].sort((r,n)=>(n.updatedAt??0)-(r.updatedAt??0));return e.json(t)}),s.get("/api/notes/:scope",i(),e=>{const t=decodeURIComponent(e.req.param("scope")),r=b.data.notes.find(n=>n.scope===t);return r?e.json(r):e.json(null,404)}),s.put("/api/notes/:scope",i(),async e=>{const t=decodeURIComponent(e.req.param("scope"));let r;try{r=await e.req.json()}catch{return e.json({error:"invalid json"},400)}if(typeof r.content!="string")return e.json({error:"content must be string"},400);const n={scope:t,content:r.content,updatedAt:Date.now()},o=b.data.notes.findIndex(a=>a.scope===t);return o>=0?b.data.notes[o]=n:b.data.notes.push(n),await b.write(),e.json({ok:!0})}),f&&(s.use("/a/:agentId/*",i()),lt(s,{getChannel:f.getChannel})),!v)try{ke(s,{manager:ve(),userAuth:i})}catch(e){console.error("[bots] failed to register routes:",e)}return s}export{tr as buildApp};
|
package/dist/lib/pages/shell.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{cssVarsStyle as c}from"../theme.js";import{newSessionModalCSS as b,newSessionModalHTML as x,newSessionModalScript as g,reducedMotion as f}from"../shared-layout.js";import{icon as o}from"../icons.js";function m(
|
|
1
|
+
import{cssVarsStyle as c}from"../theme.js";import{newSessionModalCSS as b,newSessionModalHTML as x,newSessionModalScript as g,reducedMotion as f}from"../shared-layout.js";import{icon as o}from"../icons.js";function m(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function a(t="var(--panel-accent)"){return`box-shadow: 0 0 0 2px ${t}; outline: none;`}function y(t){const{theme:e,fsRoots:r,terminalCfg:i,scrollback:p,wsBase:s}=t,n=t.version?m(t.version):"",l=`
|
|
2
2
|
*, *::before, *::after { box-sizing: border-box; }
|
|
3
3
|
html, body {
|
|
4
4
|
background: var(--page-bg); color: var(--page-fg);
|
|
@@ -209,9 +209,35 @@ import{cssVarsStyle as c}from"../theme.js";import{newSessionModalCSS as b,newSes
|
|
|
209
209
|
.file-tree-bot-plus svg { width: 11px; height: 11px; }
|
|
210
210
|
|
|
211
211
|
/* Bots merged into session groups */
|
|
212
|
-
.session-item.bot-item
|
|
213
|
-
|
|
214
|
-
.session-item.bot-item .bot-
|
|
212
|
+
.session-item.bot-item { border-left: 2px solid color-mix(in srgb, var(--bot-status, var(--panel-accent)) 45%, transparent); }
|
|
213
|
+
/* The bot glyph carries the run state (colour set per row in shell-client). */
|
|
214
|
+
.session-item.bot-item .bot-icon {
|
|
215
|
+
width: 17px; height: 17px; flex-shrink: 0;
|
|
216
|
+
fill: var(--bot-status, var(--panel-accent));
|
|
217
|
+
transition: fill 0.2s;
|
|
218
|
+
}
|
|
219
|
+
/* A live or blocked bot also tints its row, so the state reads at a glance
|
|
220
|
+
rather than from a 17px glyph alone. */
|
|
221
|
+
.session-item.bot-item[data-status="running"],
|
|
222
|
+
.session-item.bot-item[data-status="waiting_approval"],
|
|
223
|
+
.session-item.bot-item[data-status="waiting_input"],
|
|
224
|
+
.session-item.bot-item[data-status="failed"] {
|
|
225
|
+
background: color-mix(in srgb, var(--bot-status) 9%, transparent);
|
|
226
|
+
}
|
|
227
|
+
.session-item.bot-item[data-status="running"]:hover,
|
|
228
|
+
.session-item.bot-item[data-status="waiting_approval"]:hover,
|
|
229
|
+
.session-item.bot-item[data-status="waiting_input"]:hover,
|
|
230
|
+
.session-item.bot-item[data-status="failed"]:hover {
|
|
231
|
+
background: color-mix(in srgb, var(--bot-status) 15%, transparent);
|
|
232
|
+
}
|
|
233
|
+
/* Waiting on you: breathe, so a running conversation is noticed without a badge. */
|
|
234
|
+
@media (prefers-reduced-motion: no-preference) {
|
|
235
|
+
.session-item.bot-item[data-status="waiting_approval"] .bot-icon,
|
|
236
|
+
.session-item.bot-item[data-status="waiting_input"] .bot-icon {
|
|
237
|
+
animation: bot-wait 1.8s ease-in-out infinite;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
@keyframes bot-wait { 0%, 100% { opacity: 1; } 50% { opacity: 0.4; } }
|
|
215
241
|
.settings-item { display: flex; align-items: center; gap: 8px; width: 100%; text-align: left; background: none; border: none; color: inherit; font: inherit; cursor: pointer; }
|
|
216
242
|
.settings-item-icon { display: inline-flex; color: var(--panel-muted); flex: 0 0 auto; }
|
|
217
243
|
.settings-item #bots-inbox-badge { margin-left: auto; }
|
|
@@ -1166,7 +1192,7 @@ import{cssVarsStyle as c}from"../theme.js";import{newSessionModalCSS as b,newSes
|
|
|
1166
1192
|
display: flex; flex-wrap: nowrap; gap: 4px;
|
|
1167
1193
|
overflow-x: auto; overscroll-behavior-x: contain;
|
|
1168
1194
|
}
|
|
1169
|
-
`,v=JSON.stringify(
|
|
1195
|
+
`,v=JSON.stringify(e.terminal).replace(/</g,"\\u003c"),d=JSON.stringify({terminal:i,scrollback:p,theme:e.terminal,fsRoots:r,wsBase:s||""}).replace(/</g,"\\u003c");return`<!DOCTYPE html>
|
|
1170
1196
|
<html lang="en">
|
|
1171
1197
|
<head>
|
|
1172
1198
|
<meta charset="UTF-8" />
|
|
@@ -1175,12 +1201,15 @@ import{cssVarsStyle as c}from"../theme.js";import{newSessionModalCSS as b,newSes
|
|
|
1175
1201
|
<meta name="apple-mobile-web-app-capable" content="yes" />
|
|
1176
1202
|
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
|
|
1177
1203
|
<meta name="apple-mobile-web-app-title" content="tmux-web" />
|
|
1178
|
-
|
|
1179
|
-
<link rel="
|
|
1204
|
+
<!-- iOS reads the apple-touch-icon (opaque, square); everything else uses the manifest. -->
|
|
1205
|
+
<link rel="apple-touch-icon" sizes="180x180" href="/assets/apple-touch-icon-180.png" />
|
|
1180
1206
|
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
|
1207
|
+
<link rel="icon" type="image/png" sizes="192x192" href="/assets/icon-192.png" />
|
|
1208
|
+
<link rel="manifest" href="/manifest.json" />
|
|
1209
|
+
<meta name="theme-color" content="${e.shell.pageBg}" />
|
|
1181
1210
|
<title>tmux-weblink</title>
|
|
1182
1211
|
<style>
|
|
1183
|
-
${c(
|
|
1212
|
+
${c(e.shell)}
|
|
1184
1213
|
${l}
|
|
1185
1214
|
</style>
|
|
1186
1215
|
</head>
|
|
@@ -1282,10 +1311,10 @@ import{cssVarsStyle as c}from"../theme.js";import{newSessionModalCSS as b,newSes
|
|
|
1282
1311
|
<div class="settings-popover" id="settings-popover">
|
|
1283
1312
|
<div style="padding:1px 2px 6px;font-size:10px;color:var(--panel-muted);opacity:.8;font-family:var(--font-mono)">tmux-weblink v${n}</div>
|
|
1284
1313
|
<div style="padding:4px 0">
|
|
1285
|
-
<button class="theme-option" data-theme="vscode" title="VS Code"><span class="theme-dot" style="background:#007acc"></span>VS Code${
|
|
1286
|
-
<button class="theme-option" data-theme="ghostty" title="Ghostty"><span class="theme-dot" style="background:#ff5f00"></span>Ghostty${
|
|
1287
|
-
<button class="theme-option" data-theme="warm-clay" title="Warm Clay"><span class="theme-dot" style="background:#b86b52"></span>Warm Clay${
|
|
1288
|
-
<button class="theme-option" data-theme="dark-cove" title="Dark Cove"><span class="theme-dot" style="background:#7aa2f7"></span>Dark Cove${
|
|
1314
|
+
<button class="theme-option" data-theme="vscode" title="VS Code"><span class="theme-dot" style="background:#007acc"></span>VS Code${e.template==="vscode"?'<span class="theme-check">\u2713</span>':""}</button>
|
|
1315
|
+
<button class="theme-option" data-theme="ghostty" title="Ghostty"><span class="theme-dot" style="background:#ff5f00"></span>Ghostty${e.template==="ghostty"?'<span class="theme-check">\u2713</span>':""}</button>
|
|
1316
|
+
<button class="theme-option" data-theme="warm-clay" title="Warm Clay"><span class="theme-dot" style="background:#b86b52"></span>Warm Clay${e.template==="warm-clay"?'<span class="theme-check">\u2713</span>':""}</button>
|
|
1317
|
+
<button class="theme-option" data-theme="dark-cove" title="Dark Cove"><span class="theme-dot" style="background:#7aa2f7"></span>Dark Cove${e.template==="dark-cove"?'<span class="theme-check">\u2713</span>':""}</button>
|
|
1289
1318
|
</div>
|
|
1290
1319
|
<label class="force-narrow-row" title="\u7A84\u5C4F\u65F6\u4FA7\u8FB9\u680F\u6298\u53E0\u4E3A\u9876\u680F\u3001\u7EC8\u7AEF\u5360\u6EE1\u3001\u5E95\u90E8\u663E\u793A\u865A\u62DF\u952E\u76D8\u5DE5\u5177\u680F\uFF08\u4EC5\u5F71\u54CD\u672C\u6D4F\u89C8\u5668\uFF09">
|
|
1291
1320
|
<span>\u5F3A\u5236\u7A84\u5C4F\uFF08\u79FB\u52A8\u5E03\u5C40\uFF09</span>
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tmux-weblink",
|
|
3
|
-
"version": "3.2.
|
|
3
|
+
"version": "3.2.2",
|
|
4
4
|
"description": "Access your tmux sessions from the browser. A continuation of tmux-web and persalink.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
"scripts": {
|
|
16
16
|
"postinstall": "node scripts/fix-pty-perms.mjs",
|
|
17
17
|
"prepublishOnly": "npm run build",
|
|
18
|
-
"build": "tsc && npm run check:drawer-scripts && npm run
|
|
18
|
+
"build": "tsc && npm run check:drawer-scripts && npm run build:client && npm run generate-icons && npm run build:exts && npm run minify:dist",
|
|
19
19
|
"generate-icons": "node scripts/generate-icons.mjs",
|
|
20
20
|
"check:drawer-scripts": "tsx scripts/check-drawer-scripts.ts",
|
|
21
21
|
"build:client": "node scripts/build-client.mjs",
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
"build:exts": "node scripts/build-exts.mjs --force",
|
|
27
27
|
"minify:dist": "node scripts/minify-dist.mjs",
|
|
28
28
|
"start": "node dist/index.js",
|
|
29
|
-
"predev": "node scripts/build-client.mjs && node scripts/build-exts.mjs",
|
|
29
|
+
"predev": "node scripts/build-client.mjs && node scripts/generate-icons.mjs && node scripts/build-exts.mjs --force",
|
|
30
30
|
"dev": "TMUX_WEB_DEV=1 npx tsx src/index.ts"
|
|
31
31
|
},
|
|
32
32
|
"keywords": [
|