tmux-weblink 3.1.1 → 3.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/shell-client.js +98 -94
- package/dist/browser/bots-client.js +6 -6
- package/dist/browser/highlight.js +3 -0
- package/dist/browser/markdown.js +4 -2
- package/dist/browser/menu.js +1 -0
- package/dist/browser/shell-client.js +13 -13
- package/dist/lib/bots/manager.js +4 -4
- package/dist/lib/bots/routes.js +1 -1
- package/dist/lib/icons.js +1 -1
- package/dist/lib/pages/shell.js +160 -37
- package/dist/lib/shared-layout.js +44 -11
- package/package.json +1 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{icon as P}from"../lib/icons.js";import{createMarkdownRenderer as St}from"./markdown.js";const G=St(document),l={catalog:null,templates:[],bots:[],approvals:[],activeId:null,items:new Map,ws:null,pollTimer:0,renderQueued:!1};let A=[],M=!0,Ct=!1,ct=0;function Y(){try{return localStorage.getItem("tmux-web-token")||""}catch{return""}}async function k(t,e){const o=await fetch(t,{...e,headers:{"content-type":"application/json",Authorization:`Bearer ${Y()}`,...e?.headers||{}}}),i=await o.text(),s=i?JSON.parse(i):null;if(!o.ok)throw new Error(s&&s.error||`HTTP ${o.status}`);return s}function n(t,e,o){const i=document.createElement(t);return e&&(i.className=e),o!==void 0&&(i.textContent=o),i}function pt(t){return t==="running"?"var(--panel-success)":t==="waiting_approval"||t==="waiting_input"?"#e0a23c":t==="failed"?"var(--panel-danger, #e5534b)":t==="completed"?"var(--panel-accent)":"var(--panel-muted)"}function L(){X||(X=requestAnimationFrame(()=>{X=0,It()}))}let X=0,U="";function It(){const t=document.getElementById("bots-view");if(!t)return;const e=window.visualViewport,o=window.matchMedia("(max-width: 640px)").matches,i=!document.querySelector(".sidebar")?.classList.contains("collapsed");if(l.activeId&&e&&o&&!i){const s=document.querySelector(".fixed-header"),a=s?Math.round(s.getBoundingClientRect().height):0,r=Math.round(e.offsetTop)+a,c=Math.round(e.offsetLeft),d=Math.round(e.width),p=Math.max(120,Math.round(e.height)-a),m=`fixed|${r}|${c}|${d}|${p}`;if(m===U)return;U=m,t.style.position="fixed",t.style.top=`${r}px`,t.style.left=`${c}px`,t.style.width=`${d}px`,t.style.height=`${p}px`,t.style.right="auto",t.style.bottom="auto"}else{if(U==="")return;U="",t.style.position="",t.style.top="",t.style.left="",t.style.width="",t.style.height="",t.style.right="",t.style.bottom=""}}window.visualViewport?.addEventListener("resize",L),window.visualViewport?.addEventListener("scroll",L),window.addEventListener("resize",L),document.addEventListener("click",L);const ut=document.querySelector(".sidebar");ut&&new MutationObserver(L).observe(ut,{attributes:!0,attributeFilter:["class"]}),window.__syncBotsViewport=L;function F(){const t=l.approvals.length,e=document.getElementById("bots-inbox-badge");e&&(e.style.display=t?"inline-block":"none",e.textContent=String(t));const o=document.getElementById("bv-inbox-count");o&&(o.textContent=t?`(${t})`:""),window.__botsSnapshot=l.bots,window.__refreshSidebar?.()}function Et(){const t=document.getElementById("set-bot-templates"),e=document.getElementById("set-bot-new"),o=document.getElementById("set-bot-inbox"),i=()=>{document.getElementById("settings-popover")?.classList.remove("open"),document.getElementById("settings-backdrop")?.classList.remove("open")};t?.addEventListener("click",()=>{i(),V()}),e?.addEventListener("click",()=>{i(),Rt()}),o?.addEventListener("click",()=>{i(),dt()})}function $t(){const t=n("div","bots-view");t.id="bots-view",t.hidden=!0;const e=n("div","bots-view-head"),o=n("div","bv-title"),i=n("span","bots-dot");i.id="bv-dot";const s=n("span","bv-title-text");s.id="bv-title";const a=n("span","bv-status");a.id="bv-status",o.append(i,s,a);const r=n("div","bv-actions"),c=n("div","bv-mode"),d=n("button","bv-mode-btn");d.id="bv-mode-btn",d.type="button",d.setAttribute("aria-haspopup","menu"),d.setAttribute("aria-expanded","false"),yt(d,"supervised");const p=n("div","bv-menu bv-mode-menu");p.id="bv-mode-menu",p.setAttribute("role","menu"),p.hidden=!0;for(const[b,C,K]of[["supervised","\u9ED8\u8BA4","\u53EA\u8BFB\u5DE5\u5177\uFF08read/grep/find/ls\uFF09\u76F4\u63A5\u653E\u884C\uFF1Bbash\u3001edit\u3001write\u3001\u6269\u5C55/MCP \u5DE5\u5177\u4F1A\u95EE\u4F60"],["parent-supervised","\u76D1\u7BA1","\u5176\u4F59\u5DE5\u5177\u4EA4\u7ED9\u4E0A\u7EA7 bot \u51B3\u5B9A\uFF08\u5E26\u7406\u7531\uFF09\uFF1B\u4F60\u4ECD\u7136\u80FD\u770B\u5230\u5E76\u56DE\u7B54\uFF0C\u5148\u7B54\u5148\u5F97\uFF1B\u6CA1\u6709\u4E0A\u7EA7\u65F6\u56DE\u843D\u5230\u9ED8\u8BA4"],["full-access","\u5168\u653E\u884C","\u6240\u6709\u5DE5\u5177\u76F4\u63A5\u6267\u884C\uFF0C\u4E0D\u518D\u8BE2\u95EE\u3002\u6CE8\u610F\u8FD9\u4E0D\u662F\u6C99\u7BB1"]]){const j=n("button","bv-menu-item");j.dataset.mode=b,j.setAttribute("role","menuitemradio"),j.innerHTML=`<span class="bv-menu-icon">${P(gt[b],'width="15" height="15"')}</span><span class="bv-menu-text"><b>${C}</b><span>${K}</span></span><span class="bv-menu-check">${P("check",'width="13" height="13"')}</span>`,j.onclick=()=>{m(!1),Mt(b)},p.appendChild(j)}const m=b=>{b&&O(!1),p.hidden=!b,d.setAttribute("aria-expanded",b?"true":"false")};d.onclick=b=>{b.stopPropagation(),m(p.hidden)},c.append(d);const f=n("button","btn bv-inbox");f.id="bv-inbox",f.title="Requests waiting for you";const y=n("span",void 0,"Needs you"),E=n("span","bv-inbox-count");E.id="bv-inbox-count",f.append(y,E),f.onclick=()=>void dt();const v=n("button","bv-icon-btn");v.id="bv-more-btn",v.type="button",v.title="More actions",v.setAttribute("aria-label","More actions"),v.setAttribute("aria-haspopup","menu"),v.setAttribute("aria-expanded","false"),v.innerHTML=P("dots",'width="16" height="16"');const w=n("div","bv-menu");w.id="bv-more-menu",w.setAttribute("role","menu"),w.hidden=!0;const x=(b,C,K,j)=>{const D=n("button",`bv-menu-item${b?` ${b}`:""}`);return D.type="button",D.setAttribute("role","menuitem"),D.innerHTML=`<span class="bv-menu-icon">${P(C,'width="15" height="15"')}</span><span class="bv-menu-text"><b>${K}</b></span>`,D.onclick=()=>{O(!1),j()},D},B=x("","check","Allow all",()=>{if(!l.activeId)return;const b=l.approvals.filter(C=>C.botId===l.activeId);Promise.all(b.map(C=>k(`/api/bots/${C.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:C.id,allow:!0})}))).finally(()=>void $(!0))});B.id="bv-allow-all",B.title="Approve every pending request for this bot";const H=x("","refresh","Resume bot",()=>ht(b=>k(`/api/bots/${b}/resume`,{method:"POST"}).then(()=>$(!0)))),N=x("","stop","Stop run",()=>ht(b=>k(`/api/bots/${b}/stop`,{method:"POST"}).then(()=>$(!0)))),W=x("danger","delete","Delete bot",()=>{l.activeId&&confirm("Delete this bot and its session?")&&k(`/api/bots/${l.activeId}`,{method:"DELETE"}).then(()=>{tt(),$(!0)})});w.append(B,H,N,n("div","bv-menu-sep"),W);const O=b=>{b&&m(!1),w.hidden=!b,v.setAttribute("aria-expanded",b?"true":"false")};v.onclick=b=>{b.stopPropagation(),O(w.hidden)},document.addEventListener("click",b=>{const C=b.target;C&&(!c.contains(C)&&!p.contains(C)&&m(!1),!v.contains(C)&&!w.contains(C)&&O(!1))}),r.append(c,f,v),e.append(o,r);const g=n("div","bots-messages");g.id="bots-messages";const I=n("button","bv-jump");I.type="button",I.id="bv-jump",I.innerHTML=`${P("chevron-down",'width="14" height="14"')}<span>Latest</span>`,I.title="Jump to the latest message",I.hidden=!0,I.onclick=()=>{M=!0,g.scrollTop=g.scrollHeight,I.hidden=!0};const u=()=>{M=g.scrollHeight-g.scrollTop-g.clientHeight<48,I.hidden=M};g.addEventListener("scroll",u,{passive:!0}),g.addEventListener("touchmove",()=>{M=!1,I.hidden=g.scrollHeight-g.clientHeight<1},{passive:!0}),g.addEventListener("wheel",()=>{M=!1},{passive:!0});const T=n("div","bots-composer-wrap"),S=n("div","bv-composer-error");S.id="bv-composer-error",S.hidden=!0;const q=n("div","bots-composer"),h=n("textarea");h.id="bots-input",h.rows=1,h.placeholder="Message the bot\u2026",h.spellcheck=!1;const lt=window.matchMedia("(pointer: coarse)").matches;lt||(h.enterKeyHint="send"),h.onkeydown=b=>{b.key!=="Enter"||b.shiftKey||b.isComposing||lt||b.keyCode===229||(b.preventDefault(),bt())},h.oninput=()=>Z(null);const R=n("button","btn primary");R.id="bv-send",R.title="Send",R.setAttribute("aria-label","Send"),R.innerHTML='<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>',R.onclick=()=>void bt(),q.append(h,R),q.addEventListener("click",b=>{b.target?.closest("button")||document.activeElement!==h&&h.focus()}),T.append(S,q),t.append(e,g,I,T,p,w),document.querySelector(".main-area")?.appendChild(t),document.getElementById("bots-modal")||Jt()}function Z(t){const e=document.getElementById("bv-composer-error");e&&(e.textContent=t??"",e.hidden=!t)}function mt(t){const e=document.getElementById("bv-send");e&&(e.disabled=t,e.setAttribute("aria-busy",t?"true":"false"),e.title=t?"Sending\u2026":"Send")}async function bt(){const t=document.getElementById("bots-input");if(!t||!l.activeId||Ct||!t.value.trim())return;const e=l.activeId,o=t.value;Z(null),mt(!0);try{await k(`/api/bots/${e}/input`,{method:"POST",body:JSON.stringify({text:o})}),t.value===o&&(t.value=""),M=!0}catch(i){Z(i instanceof Error?i.message:String(i))}finally{mt(!1)}}function ht(t){l.activeId&&t(l.activeId).catch(e=>_({kind:"notice",level:"error",text:e instanceof Error?e.message:String(e)}))}function tt(){l.activeId=null,A=[],M=!0,L();const t=document.getElementById("bots-view");t&&(t.hidden=!0);try{l.ws?.close()}catch{}l.ws=null,F();const e=document.getElementById("terminal-container"),o=document.getElementById("main-placeholder"),i=!!document.querySelector(".session-item.active:not(.bot-item)");e&&i?(e.style.display="",o&&(o.style.display="none")):o&&(o.style.display="")}async function ft(t){l.activeId=t,A=[],M=!0;const e=document.getElementById("bv-jump");e&&(e.hidden=!0),window.__collapseSidebar?.(),L(),l.items.set(t,[]);const o=document.getElementById("bots-view");o&&(o.hidden=!1);const i=document.getElementById("main-placeholder");i&&(i.style.display="none");const s=document.getElementById("terminal-container");s&&(s.style.display="none");const a=document.getElementById("file-editor");a&&(a.style.display="none"),F(),st();try{l.ws?.close()}catch{}const r=location.protocol==="https:"?"wss:":"ws:",c=new WebSocket(`${r}//${location.host}/ws/bots/${encodeURIComponent(t)}?token=${encodeURIComponent(Y())}`);l.ws=c,c.onmessage=d=>{try{wt(JSON.parse(String(d.data)))}catch{}},c.onclose=()=>{l.activeId===t&&setTimeout(()=>{l.activeId===t&&$(!0)},1500)},await $(!0)}function et(){return l.bots.find(t=>t.id===l.activeId)||null}function nt(){const t=et();if(!t)return;const e=document.getElementById("bv-title"),o=document.getElementById("bv-status"),i=document.getElementById("bv-dot");e&&(e.textContent=t.title),o&&(o.textContent=Bt[t.status]??t.status.replace(/_/g," "),o.dataset.status=t.status,o.style.color=pt(t.status),o.title=`${t.status.replace(/_/g," ")} \xB7 ${t.templateId} \xB7 ${t.projectPath}`);const s=document.getElementById("bv-mode-btn");s&&yt(s,t.runtimeMode||"supervised");for(const c of document.querySelectorAll("#bv-mode-menu button")){const d=c.dataset.mode===t.runtimeMode;c.classList.toggle("active",d),c.setAttribute("aria-checked",d?"true":"false")}const a=document.getElementById("bv-allow-all"),r=l.approvals.filter(c=>c.botId===t.id).length;if(a){a.hidden=r===0;const c=a.querySelector(".bv-menu-text b");c&&(c.textContent=`Allow all (${r})`)}i&&(i.style.background=pt(t.status))}const Bt={queued:"queued",starting:"starting",running:"running",waiting_input:"waiting",waiting_approval:"approval",completed:"done",failed:"failed",cancelled:"stopped",stale:"stale"},vt={supervised:"\u9ED8\u8BA4","parent-supervised":"\u76D1\u7BA1","full-access":"\u5168\u653E\u884C"},gt={supervised:"shield","parent-supervised":"shield-up","full-access":"shield-alert"};function yt(t,e){const o=gt[e]??"shield";t.dataset.mode=e,t.innerHTML=P(o,'width="15" height="15"');const i=`\u5BA1\u6279\u6A21\u5F0F\uFF1A${vt[e]??e}`;t.title=`${i}\uFF08\u70B9\u5F00\u53EF\u5207\u6362\uFF09`,t.setAttribute("aria-label",i)}async function Mt(t){if(l.activeId)try{await k(`/api/bots/${l.activeId}/mode`,{method:"POST",body:JSON.stringify({mode:t})});const e=et();e&&(e.runtimeMode=t),nt(),_({kind:"notice",level:"info",text:`\u5BA1\u6279\u6A21\u5F0F\uFF1A${vt[t]||t}`})}catch(e){_({kind:"notice",level:"error",text:e instanceof Error?e.message:String(e)})}}function _(t,e=l.activeId){if(!e)return;const o=l.items.get(e)||[];o.push(t),l.items.set(e,o),e===l.activeId&&J()}function J(){if(l.renderQueued)return;l.renderQueued=!0;const t=Math.max(0,60-(performance.now()-ct));window.setTimeout(()=>{l.renderQueued=!1,ct=performance.now(),st()},t)}function ot(t){switch(t.kind){case"assistant":return{text:t.text,thinking:t.thinking};case"tool":return{phase:t.phase,output:t.output,error:t.isError,durationMs:t.durationMs};case"approval":return{decided:t.decided,approvalState:t.approval.state};default:return{}}}function Ot(t,e){return t.text!==e.text||t.thinking!==e.thinking||t.phase!==e.phase||t.output!==e.output||t.error!==e.error||t.durationMs!==e.durationMs||t.decided!==e.decided||t.approvalState!==e.approvalState}function it(t){if(t.kind==="user"){const e=n("div","bv-msg bv-user");return e.appendChild(G(t.text)),e}if(t.kind==="assistant"){const e=n("div","bv-msg bv-assistant");if(t.thinking){const i=n("details","bv-thinking");i.appendChild(n("summary",void 0,"thinking")),i.appendChild(n("div",void 0,t.thinking)),e.appendChild(i)}const o=n("div","bv-text");return o.appendChild(G(t.text)),e.appendChild(o),e}return t.kind==="tool"?At(t):t.kind==="approval"?Lt(t):n("div",`bv-notice bv-notice-${t.level}`,t.text)}function Tt(t,e){const o=t.querySelector("details.bv-thinking");if(e.thinking)if(o){const s=o.querySelector("div");s&&s.textContent!==e.thinking&&(s.textContent=e.thinking)}else{const s=n("details","bv-thinking");s.appendChild(n("summary",void 0,"thinking")),s.appendChild(n("div",void 0,e.thinking)),t.prepend(s)}else o&&o.remove();const i=t.querySelector(".bv-text");i&&i.replaceChildren(G(e.text))}function st(){const t=document.getElementById("bots-messages");if(!t||!l.activeId||document.getElementById("bots-view")?.hidden)return;const e=l.items.get(l.activeId)||[],o=M;if(e.length<A.length||e.some((s,a)=>A[a]?.item!==s))t.textContent="",A=e.map(s=>{const a=it(s);return t.appendChild(a),{item:s,snapshot:ot(s),node:a}});else{for(let s=A.length;s<e.length;s++){const a=e[s],r=it(a);t.appendChild(r),A.push({item:a,snapshot:ot(a),node:r})}for(let s=0;s<e.length;s++){const a=e[s],r=A[s],c=ot(a);if(Ot(r.snapshot,c)){if(a.kind==="assistant")Tt(r.node,a);else{const d=it(a);r.node.replaceWith(d),r.node=d}r.snapshot=c}}}o&&(t.scrollTop=t.scrollHeight)}function At(t){const e=n("details","bv-tool");e.open=t.phase!=="end"||!!t.isError;const o=n("summary"),i=n("span","bv-tool-name",t.name);if(o.appendChild(i),t.phase!=="end"&&o.appendChild(n("span","bv-tool-phase",t.phase)),t.isError&&o.appendChild(n("span","bv-tool-error","error")),typeof t.durationMs=="number"&&o.appendChild(n("span","bv-tool-meta",`${Math.round(t.durationMs)}ms`)),e.appendChild(o),t.args!==void 0){const s=n("pre","bv-pre");s.textContent=typeof t.args=="string"?t.args:JSON.stringify(t.args,null,2),e.appendChild(s)}if(t.output){const s=n("pre","bv-pre bv-output");s.textContent=t.output,e.appendChild(s)}return e}function Lt(t){const e=n("div","bv-approval"),o=t.approval;if(e.appendChild(n("div","bv-approval-tag","Needs approval")),e.appendChild(n("div","bv-approval-title",o.title)),o.message){const y=n("pre","bv-pre bv-approval-detail");y.textContent=o.message,e.appendChild(y)}if(t.decided)return e.appendChild(n("div","bv-approval-decided",t.decided==="allowed"?"Allowed":"Denied")),e;const i=n("input","bv-reason");i.placeholder="reason (optional)",i.setAttribute("aria-label","Reason (optional)");const s=n("div","bv-approval-actions"),a=n("button","btn primary","Allow once"),r=/^Allow (.+?)\?$/.exec(o.title)?.[1],c=o.method==="confirm"?r&&r.length<=24?`Always allow ${r}`:"Always allow this tool":"Allow for this session",d=n("button","btn",c);d.hidden=o.method!=="confirm";const p=n("button","btn danger","Deny"),m=[a,d,p],f=async(y,E,v)=>{const w=v.textContent??"";for(const x of m)x.disabled=!0;v.textContent=y?"Allowing\u2026":"Denying\u2026";try{await k(`/api/bots/${o.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:o.id,allow:y,always:E,reason:i.value||void 0})}),t.decided=y?"allowed":"denied",J(),$(!0)}catch(x){for(const B of m)B.disabled=!1;v.textContent=w,_({kind:"notice",level:"error",text:x instanceof Error?x.message:String(x)})}};return a.onclick=()=>void f(!0,!1,a),d.onclick=()=>void f(!0,!0,d),p.onclick=()=>void f(!1,!1,p),s.append(i,a,d,p),e.appendChild(s),e}function wt(t){const e=String(t.type||""),o=l.activeId;if(!o)return;const i=l.items.get(o)||[];if(e==="snapshot")l.items.set(o,[]);else if(e==="user")M=!0,_({kind:"user",text:String(t.text||"")});else if(e==="status"){const s=et();s&&(s.status=String(t.status||s.status)),nt(),Pt()}else if(e==="message"){const s=t.message;if(!s||String(s.role||"")!=="assistant")return;const r=Nt(s),c=jt(s),d=i[i.length-1];d&&d.kind==="assistant"?(d.text=r||d.text,d.thinking=c||d.thinking):i.push({kind:"assistant",text:r,thinking:c}),l.items.set(o,i),J()}else if(e==="delta"){const s=String(t.kind||""),a=String(t.delta||"");let r=i[i.length-1];(!r||r.kind!=="assistant")&&(i.push({kind:"assistant",text:"",thinking:""}),r=i[i.length-1]),r.kind==="assistant"&&(s==="text"?r.text+=a:s==="thinking"&&(r.thinking+=a)),l.items.set(o,i),J()}else if(e==="tool"){const s=String(t.callId||""),a=i.find(c=>c.kind==="tool"&&c.callId===s),r=String(t.phase||"start");a?(a.phase=r,r==="update"&&t.output&&(a.output=String(t.output)),r==="end"&&(t.output&&(a.output=String(t.output)),a.isError=t.isError===!0,typeof t.durationMs=="number"&&(a.durationMs=t.durationMs))):i.push({kind:"tool",callId:s,name:String(t.name||"tool"),args:t.args,output:t.output?String(t.output):void 0,isError:t.isError===!0,durationMs:typeof t.durationMs=="number"?t.durationMs:void 0,phase:r}),l.items.set(o,i),J()}else if(e==="approval"){const s=t.approval;if(!s)return;const a=i;for(let r=a.length-1;r>=0;r--){const c=a[r];if(c.kind==="approval"&&c.approval.id===s.id){c.approval=s,s.state!=="pending"&&(c.decided=s.state==="allowed"?"allowed":"denied"),l.items.set(o,a),J();return}}a.push({kind:"approval",approval:s}),l.items.set(o,a),J()}else e==="notice"&&_({kind:"notice",level:String(t.level||"info"),text:String(t.text||"")})}function Nt(t){const e=t.content;return Array.isArray(e)?e.map(o=>o&&typeof o=="object"&&o.type==="text"?String(o.text||""):"").join(""):String(t.text||"")}function jt(t){const e=t.content;return Array.isArray(e)?e.map(o=>o&&typeof o=="object"&&o.type==="thinking"?String(o.thinking||""):"").join(""):""}async function $(t=!1){try{const[e,o]=await Promise.all([k("/api/bots"),k("/api/bots/approvals")]);if(l.bots=e,l.approvals=o,F(),nt(),t&&l.activeId){const i=await k(`/api/bots/${l.activeId}/events?limit=300`);_t(i)}}catch{}}async function Pt(){try{l.bots=await k("/api/bots"),F()}catch{}}function _t(t){if(l.activeId){l.items.set(l.activeId,[]);for(const e of t)wt(e);st()}}function Jt(){const t=n("div","bots-modal");t.id="bots-modal",t.hidden=!0;const e=n("div","bots-modal-card"),o=n("div","bots-modal-head"),i=n("span");i.id="bots-modal-title";const s=n("button","btn");s.innerHTML=P("close",'width="14" height="14"'),s.title="Close",s.onclick=()=>z(),o.append(i,s);const a=n("div","bots-modal-body");a.id="bots-modal-body",e.append(o,a),t.appendChild(e),t.onclick=r=>{r.target===t&&z()},document.body.appendChild(t)}function at(t){const e=document.getElementById("bots-modal"),o=document.getElementById("bots-modal-title"),i=document.getElementById("bots-modal-body");if(!e||!i)throw new Error("modal missing");return o&&(o.textContent=t),i.textContent="",e.hidden=!1,i}function z(){const t=document.getElementById("bots-modal");t&&(t.hidden=!0)}async function Ht(){return l.catalog||(l.catalog=await k("/api/bots/catalog")),l.catalog}async function kt(){return l.templates=await k("/api/bots/templates"),l.templates}async function V(){const t=at("Bot templates"),[e,o]=await Promise.all([Ht(),kt()]),i=n("div","bv-template-list");for(const d of o){const p=n("div","bv-template-row");p.appendChild(n("span","bv-template-name",d.manifest.name)),p.appendChild(n("span","bv-template-desc",d.manifest.description||""));const m=n("button","btn","Edit");m.onclick=()=>xt(t,e,d);const f=n("button","btn","Copy");f.title="Duplicate this template",f.onclick=()=>{const v=JSON.parse(JSON.stringify(d.manifest));v.name=`${d.manifest.name} copy`,k("/api/bots/templates",{method:"POST",body:JSON.stringify({manifest:v})}).then(()=>V()).catch(w=>alert(w instanceof Error?w.message:String(w)))};const y=n("button","btn danger","Delete");y.onclick=()=>{confirm(`Delete template ${d.manifest.name}?`)&&k(`/api/bots/templates/${d.id}`,{method:"DELETE"}).then(()=>V())};const E=n("span","bv-template-actions");E.append(m,f,y),p.appendChild(E),i.appendChild(p)}o.length===0&&i.appendChild(n("div","bots-empty","No templates yet")),t.appendChild(i);const s=n("div","bv-template-actions"),a=n("button","btn primary","New template");a.onclick=()=>xt(t,e,null);const r=n("button","btn","Export");r.title="Download templates + library as JSON",r.onclick=()=>{(async()=>{try{const d=await fetch("/api/bots/export",{headers:{Authorization:`Bearer ${Y()}`}});if(!d.ok)throw new Error(`HTTP ${d.status}`);const p=await d.blob(),m=document.createElement("a");m.href=URL.createObjectURL(p),m.download=`tmux-weblink-bots-${new Date().toISOString().slice(0,10)}.json`,m.click(),setTimeout(()=>URL.revokeObjectURL(m.href),2e3)}catch(d){alert(d instanceof Error?d.message:String(d))}})()};const c=n("button","btn","Import");c.title="Restore templates from a JSON bundle",c.onclick=()=>{const d=document.createElement("input");d.type="file",d.accept="application/json,.json",d.onchange=()=>{const p=d.files?.[0];p&&(async()=>{try{const m=JSON.parse(await p.text()),f=await k("/api/bots/import",{method:"POST",body:JSON.stringify(m)});alert(`Imported ${f.templates} templates, ${f.files} library files (${f.skipped} kept)`),await V()}catch(m){alert(m instanceof Error?m.message:String(m))}})()},d.click()},s.append(a,r,c),t.appendChild(s)}function rt(t,e,o){const i=n("div","bv-field");i.appendChild(n("label","bv-label",t));const s=n("div","bv-check-grid"),a=[];for(const r of e){const c=n("label","bv-check"),d=document.createElement("input");d.type="checkbox",d.checked=o.includes(r.id),c.append(d,n("span",void 0,r.label)),r.hint&&(c.title=r.hint),s.appendChild(c),a.push({id:r.id,input:d})}return i.appendChild(s),{element:i,get:()=>a.filter(r=>r.input.checked).map(r=>r.id)}}function xt(t,e,o){t.textContent="";const i=o?JSON.parse(JSON.stringify(o.manifest)):{name:"new-bot",description:""},s=n("input","bv-input");s.value=i.name,s.placeholder="Template name";const a=n("input","bv-input");a.value=i.description||"",a.placeholder="One line description";const r=n("textarea","bv-textarea");r.rows=6,r.value=i.system||"",r.placeholder="System prompt for this bot (written to SYSTEM.md)";const c=rt("Skills",e.skills.map(u=>({id:u.id,label:u.name,hint:u.description})),i.skills||[]),d=rt("Extensions (Pi builtins + library)",e.extensions.map(u=>({id:u.id,label:`${u.name}${u.kind==="builtin"?" (builtin)":""}`,hint:u.description})),(i.extensions||[]).map(u=>u.replace(/^.*\//,"").replace(/\.(js|ts)$/,""))),p=rt("Prompt templates",e.prompts.map(u=>({id:u.id,label:u.name})),i.prompts||[]),m=n("select","bv-input");m.appendChild(new Option("none",""));for(const u of e.mcp)m.appendChild(new Option(u.name,u.id));i.mcp&&(m.value=e.mcp.find(u=>JSON.stringify(u.servers)===JSON.stringify(i.mcp?.mcpServers))?.id||"");const f=n("div","bv-field");f.appendChild(n("label","bv-label","Tools (allow list; deny always blocks)"));const y=n("div","bv-check-grid"),E=[];for(const u of e.tools){const T=n("label","bv-check"),S=document.createElement("input");S.type="checkbox",S.checked=(i.tools?.allow||[]).includes(u.name)||!i.tools?.allow?.length&&["read","grep","find","ls","edit","write","bash"].includes(u.name),T.append(S,n("span",void 0,u.name)),y.appendChild(T),E.push({name:u.name,input:S})}f.appendChild(y);const v=n("input","bv-input");v.value=(i.tools?.deny||[]).join(", "),v.placeholder="Always deny (comma separated), e.g. bash, write";const w=n("textarea","bv-textarea");w.rows=2,w.value=(i.packages||[]).join(`
|
|
2
|
-
`),
|
|
3
|
-
${
|
|
4
|
-
${
|
|
5
|
-
`),
|
|
6
|
-
`).map(
|
|
1
|
+
import{icon as H}from"../lib/icons.js";import{createMarkdownRenderer as Ft}from"./markdown.js";const mt=Ft(document),d={catalog:null,templates:[],bots:[],approvals:[],activeId:null,items:new Map,queues:new Map,ws:null,pollTimer:0,renderQueued:!1};let q=[],O=!0;const $t=200;let At=$t,Qt=!1,Bt=0;function ft(){try{return localStorage.getItem("tmux-web-token")||""}catch{return""}}async function x(t,e){const n=await fetch(t,{...e,headers:{"content-type":"application/json",Authorization:`Bearer ${ft()}`,...e?.headers||{}}}),o=await n.text(),s=o?JSON.parse(o):null;if(!n.ok)throw new Error(s&&s.error||`HTTP ${n.status}`);return s}function i(t,e,n){const o=document.createElement(t);return e&&(o.className=e),n!==void 0&&(o.textContent=n),o}function Tt(t){return t==="running"?"var(--panel-success)":t==="waiting_approval"||t==="waiting_input"?"#e0a23c":t==="failed"?"var(--panel-danger, #e5534b)":t==="completed"?"var(--panel-accent)":"var(--panel-muted)"}function R(){ht||(ht=requestAnimationFrame(()=>{ht=0,zt()}))}let ht=0,Z="";function zt(){const t=document.getElementById("bots-view");if(!t)return;const e=window.visualViewport,n=window.matchMedia("(max-width: 640px)").matches,o=document.querySelector(".sidebar")?.classList.contains("open")===!0;if(d.activeId&&e&&n&&!o){const s=document.querySelector(".fixed-header"),a=s?Math.round(s.getBoundingClientRect().height):0,l=Math.round(e.offsetTop)+a,c=Math.round(e.offsetLeft),r=Math.round(e.width),p=Math.max(120,Math.round(e.height)-a),f=`fixed|${l}|${c}|${r}|${p}`;if(f===Z)return;Z=f,t.style.position="fixed",t.style.top=`${l}px`,t.style.left=`${c}px`,t.style.width=`${r}px`,t.style.height=`${p}px`,t.style.right="auto",t.style.bottom="auto"}else{if(Z==="")return;Z="",t.style.position="",t.style.top="",t.style.left="",t.style.width="",t.style.height="",t.style.right="",t.style.bottom=""}}window.visualViewport?.addEventListener("resize",R),window.visualViewport?.addEventListener("scroll",R),window.addEventListener("resize",R),document.addEventListener("click",R);const Mt=document.querySelector(".sidebar");Mt&&new MutationObserver(R).observe(Mt,{attributes:!0,attributeFilter:["class"]}),window.__syncBotsViewport=R;function tt(){const t=d.approvals.length,e=document.getElementById("bots-inbox-badge");e&&(e.style.display=t?"inline-block":"none",e.textContent=String(t));const n=document.getElementById("bv-inbox-count");n&&(n.textContent=t?`(${t})`:""),window.__botsSnapshot=d.bots,window.__refreshSidebar?.()}function Kt(){const t=document.getElementById("set-bot-templates"),e=document.getElementById("set-bot-new"),n=document.getElementById("set-bot-inbox"),o=()=>{document.getElementById("settings-popover")?.classList.remove("open"),document.getElementById("settings-backdrop")?.classList.remove("open")};t?.addEventListener("click",()=>{o(),X()}),e?.addEventListener("click",()=>{o(),ue()}),n?.addEventListener("click",()=>{o(),Et()})}function Gt(){const t=i("div","bots-view");t.id="bots-view",t.hidden=!0;const e=i("div","bots-view-head"),n=i("div","bv-title"),o=i("span","bots-dot");o.id="bv-dot";const s=i("span","bv-title-text");s.id="bv-title";const a=i("span","bv-status");a.id="bv-status",n.append(o,s,a);const l=i("div","bv-actions"),c=i("div","bv-mode"),r=i("button","bv-mode-btn");r.id="bv-mode-btn",r.type="button",r.setAttribute("aria-haspopup","menu"),r.setAttribute("aria-expanded","false"),Jt(r,"supervised");const p=i("div","bv-menu bv-mode-menu");p.id="bv-mode-menu",p.setAttribute("role","menu"),p.hidden=!0;for(const[u,k,B]of[["supervised","\u9ED8\u8BA4","\u53EA\u8BFB\u5DE5\u5177\uFF08read/grep/find/ls\uFF09\u76F4\u63A5\u653E\u884C\uFF1Bbash\u3001edit\u3001write\u3001\u6269\u5C55/MCP \u5DE5\u5177\u4F1A\u95EE\u4F60"],["parent-supervised","\u76D1\u7BA1","\u5176\u4F59\u5DE5\u5177\u4EA4\u7ED9\u4E0A\u7EA7 bot \u51B3\u5B9A\uFF08\u5E26\u7406\u7531\uFF09\uFF1B\u4F60\u4ECD\u7136\u80FD\u770B\u5230\u5E76\u56DE\u7B54\uFF0C\u5148\u7B54\u5148\u5F97\uFF1B\u6CA1\u6709\u4E0A\u7EA7\u65F6\u56DE\u843D\u5230\u9ED8\u8BA4"],["full-access","\u5168\u653E\u884C","\u6240\u6709\u5DE5\u5177\u76F4\u63A5\u6267\u884C\uFF0C\u4E0D\u518D\u8BE2\u95EE\u3002\u6CE8\u610F\u8FD9\u4E0D\u662F\u6C99\u7BB1"]]){const W=i("button","bv-menu-item");W.dataset.mode=u,W.setAttribute("role","menuitemradio"),W.innerHTML=`<span class="bv-menu-icon">${H(_t[u],'width="15" height="15"')}</span><span class="bv-menu-text"><b>${k}</b><span>${B}</span></span><span class="bv-menu-check">${H("check",'width="13" height="13"')}</span>`,W.onclick=()=>{f(!1),te(u)},p.appendChild(W)}const f=u=>{u&&L(!1),p.hidden=!u,r.setAttribute("aria-expanded",u?"true":"false")};r.onclick=u=>{u.stopPropagation(),f(p.hidden)},c.append(r);const b=i("button","btn bv-inbox");b.id="bv-inbox",b.title="Requests waiting for you";const v=i("span",void 0,"Needs you"),y=i("span","bv-inbox-count");y.id="bv-inbox-count",b.append(v,y),b.onclick=()=>void Et();const h=i("button","bv-icon-btn");h.id="bv-more-btn",h.type="button",h.title="More actions",h.setAttribute("aria-label","More actions"),h.setAttribute("aria-haspopup","menu"),h.setAttribute("aria-expanded","false"),h.innerHTML=H("dots",'width="16" height="16"');const S=i("div","bv-menu");S.id="bv-more-menu",S.setAttribute("role","menu"),S.hidden=!0;const C=(u,k,B,W)=>{const G=i("button",`bv-menu-item${u?` ${u}`:""}`);return G.type="button",G.setAttribute("role","menuitem"),G.innerHTML=`<span class="bv-menu-icon">${H(k,'width="15" height="15"')}</span><span class="bv-menu-text"><b>${B}</b></span>`,G.onclick=()=>{L(!1),W()},G},M=C("","check","Allow all",()=>{if(!d.activeId)return;const u=d.approvals.filter(k=>k.botId===d.activeId);Promise.all(u.map(k=>x(`/api/bots/${k.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:k.id,allow:!0})}))).finally(()=>void T(!0))});M.id="bv-allow-all",M.title="Approve every pending request for this bot";const Q=C("","refresh","Resume bot",()=>Dt(u=>x(`/api/bots/${u}/resume`,{method:"POST"}).then(()=>T(!0)))),J=C("","stop","Stop run",()=>Dt(u=>x(`/api/bots/${u}/stop`,{method:"POST"}).then(()=>T(!0)))),Y=C("danger","delete","Delete bot",()=>{d.activeId&&confirm("Delete this bot and its session?")&&x(`/api/bots/${d.activeId}`,{method:"DELETE"}).then(()=>{yt(),T(!0)})});S.append(M,Q,J,i("div","bv-menu-sep"),Y);const L=u=>{u&&f(!1),S.hidden=!u,h.setAttribute("aria-expanded",u?"true":"false")};h.onclick=u=>{u.stopPropagation(),L(S.hidden)},document.addEventListener("click",u=>{const k=u.target;k&&(!c.contains(k)&&!p.contains(k)&&f(!1),!h.contains(k)&&!S.contains(k)&&L(!1))}),l.append(c,b,h),e.append(n,l);const g=i("div","bots-messages");g.id="bots-messages";const $=i("button","bv-jump");$.type="button",$.id="bv-jump",$.innerHTML=`${H("chevron-down",'width="14" height="14"')}<span>Latest</span>`,$.title="Jump to the latest message",$.hidden=!0,$.onclick=()=>{O=!0,g.scrollTop=g.scrollHeight,$.hidden=!0};const m=()=>{O=g.scrollHeight-g.scrollTop-g.clientHeight<48,$.hidden=O};g.addEventListener("scroll",m,{passive:!0}),g.addEventListener("touchmove",()=>{O=!1,$.hidden=g.scrollHeight-g.clientHeight<1},{passive:!0}),g.addEventListener("wheel",()=>{O=!1},{passive:!0});const I=i("div","bots-composer-wrap"),E=i("div","bv-queue");E.id="bv-queue",E.hidden=!0;const lt=i("span","bv-queue-text"),w=i("button","bv-queue-clear","Clear");w.type="button",w.title="Drop the queued messages",w.onclick=()=>{d.activeId&&x(`/api/bots/${d.activeId}/queue/clear`,{method:"POST"}).then(()=>vt(),u=>P(u instanceof Error?u.message:String(u)))},E.append(lt,w);const dt=i("div","bv-attach-strip");dt.id="bv-attach-strip",dt.hidden=!0;const ct=i("div","bv-composer-error");ct.id="bv-composer-error",ct.hidden=!0;const pt=i("div","bv-suggest");pt.id="bv-suggest",pt.hidden=!0;const ut=i("div","bots-composer"),U=i("button","bv-attach-btn");U.type="button",U.id="bv-attach",U.title="Attach an image",U.setAttribute("aria-label","Attach an image"),U.innerHTML=H("attach",'width="18" height="18"');const N=i("input");N.type="file",N.accept="image/*",N.multiple=!0,N.hidden=!0,U.onclick=()=>N.click(),N.onchange=()=>{for(const u of Array.from(N.files??[]))bt(u);N.value=""};const A=i("textarea");A.id="bots-input",A.rows=1,A.placeholder="Message the bot\u2026",A.spellcheck=!1;const It=window.matchMedia("(pointer: coarse)").matches;It||(A.enterKeyHint="send"),A.onkeydown=u=>{Yt(u)||u.key!=="Enter"||u.shiftKey||u.isComposing||It||u.keyCode===229||(u.preventDefault(),jt())},A.oninput=()=>{P(null),et(A),qt()},A.onclick=()=>qt(),A.addEventListener("paste",u=>{const k=Array.from(u.clipboardData?.files??[]).filter(B=>B.type.startsWith("image/"));if(k.length!==0){u.preventDefault();for(const B of k)bt(B)}});const z=i("button","btn primary");z.id="bv-send",z.title="Send",z.setAttribute("aria-label","Send"),z.innerHTML='<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>',z.onclick=()=>void jt(),ut.append(U,A,z),ut.addEventListener("click",u=>{const k=u.target;k?.closest("button")&&_(),!k?.closest("button")&&document.activeElement!==A&&A.focus()}),I.addEventListener("dragover",u=>{u.dataTransfer&&(u.preventDefault(),I.classList.add("drop-target"))}),I.addEventListener("dragleave",()=>I.classList.remove("drop-target")),I.addEventListener("drop",u=>{u.preventDefault(),I.classList.remove("drop-target");const k=Array.from(u.dataTransfer?.files??[]).filter(B=>B.type.startsWith("image/"));for(const B of k)bt(B)}),I.append(E,dt,pt,ct,N,ut),t.append(e,g,$,I,p,S),document.querySelector(".main-area")?.appendChild(t),document.getElementById("bots-modal")||ce()}function P(t){const e=document.getElementById("bv-composer-error");e&&(e.textContent=t??"",e.hidden=!t)}function Ot(t){const e=document.getElementById("bv-send");e&&(e.disabled=t,e.setAttribute("aria-busy",t?"true":"false"),e.title=t?"Sending\u2026":"Send")}const j=[],Lt=4,Xt=4*1024*1024;function et(t){t.style.height="auto";const e=window.matchMedia("(max-width: 640px)").matches?132:160;t.style.height=`${Math.min(e,t.scrollHeight)}px`}function nt(){const t=document.getElementById("bv-attach-strip");t&&(t.textContent="",t.hidden=j.length===0,j.forEach((e,n)=>{const o=i("span","bv-attach-chip"),s=i("img");s.src=e.preview,s.alt=e.name;const a=i("button","bv-attach-remove","\xD7");a.type="button",a.title=`Remove ${e.name}`,a.setAttribute("aria-label",`Remove ${e.name}`),a.onclick=()=>{j.splice(n,1),nt()},o.append(s,a),t.appendChild(o)}))}async function bt(t){if(!t.type.startsWith("image/")){P("Only image attachments are supported.");return}if(j.length>=Lt){P(`At most ${Lt} images per message.`);return}if(t.size>Xt){P("Images must be smaller than 4 MB.");return}const e=await new Promise((o,s)=>{const a=new FileReader;a.onload=()=>o(String(a.result??"")),a.onerror=()=>s(new Error("could not read the image")),a.readAsDataURL(t)}),n=e.indexOf(",");j.push({data:e.slice(n+1),mimeType:t.type,name:t.name||"image",preview:e}),P(null),nt()}function vt(){const t=document.getElementById("bv-queue");if(!t)return;const e=d.activeId?d.queues.get(d.activeId):void 0,n=e?.steering.length??0,o=e?.followUp.length??0;if(n+o===0){t.hidden=!0;return}const s=[];n&&s.push(`${n} steering`),o&&s.push(`${o} follow-up`),t.hidden=!1;const a=t.querySelector(".bv-queue-text");a&&(a.textContent=`Queued \xB7 ${s.join(" \xB7 ")}`)}let D=[],K=0,ot=null,be=null;function _(){const t=document.getElementById("bv-suggest");t&&(t.hidden=!0),D=[],ot=null}function gt(){const t=document.getElementById("bv-suggest");if(t){if(t.textContent="",D.length===0){t.hidden=!0;return}t.hidden=!1,D.forEach((e,n)=>{const o=i("button",`bv-suggest-item${n===K?" active":""}`);o.type="button",o.innerHTML=`<span class="bv-suggest-kind">${e.kind==="file"?"@":"/"}</span><span class="bv-suggest-label">${Nt(e.label)}</span><span class="bv-suggest-detail">${Nt(e.detail)}</span>`,o.onmousedown=s=>s.preventDefault(),o.onclick=()=>Pt(n),t.appendChild(o)})}}function Nt(t){return t.replace(/[&<>"]/g,e=>({"&":"&","<":"<",">":">",'"':"""})[e])}async function qt(){const t=document.getElementById("bots-input");if(!t)return;const e=t.selectionStart??t.value.length,n=t.value.slice(0,e),o=/(^|\s)([/@])([^\s]*)$/.exec(n);if(!o){_();return}const s=o[2],a=o[3];if(ot={start:e-a.length-1,end:e},s==="/"){const b=d.catalog,v=(b?.prompts??[]).map(h=>({kind:"prompt",label:`/${h.name}`,detail:"prompt template",value:`/${h.name} `})),y=(b?.skills??[]).map(h=>({kind:"skill",label:`/skill:${h.name}`,detail:h.description||"skill",value:`/skill:${h.name} `}));D=[...v,...y].filter(h=>h.label.toLowerCase().includes(a.toLowerCase())||h.detail.toLowerCase().includes(a.toLowerCase())).slice(0,8),K=0,gt();return}const c=it();if(!c){_();return}const r=a.lastIndexOf("/"),p=r>=0?`${c.projectPath}/${a.slice(0,r)}`:c.projectPath,f=r>=0?a.slice(r+1):a;try{D=((await x(`/api/fs/list?path=${encodeURIComponent(p)}`)).entries??[]).filter(y=>y.name.toLowerCase().startsWith(f.toLowerCase())).slice(0,8).map(y=>{const h=r>=0?a.slice(0,r+1):"";return{kind:"file",label:`@${h}${y.name}${y.type==="dir"?"/":""}`,detail:y.type==="dir"?"directory":"file",value:`@${h}${y.name}${y.type==="dir"?"/":" "}`}}),K=0,gt()}catch{_()}}function Pt(t){const e=document.getElementById("bots-input"),n=D[t];if(!e||!n||!ot)return;const{start:o,end:s}=ot;e.value=`${e.value.slice(0,o)}${n.value}${e.value.slice(s)}`;const a=o+n.value.length;_(),e.focus(),e.setSelectionRange(a,a),et(e)}function Yt(t){const e=document.getElementById("bv-suggest");if(!e||e.hidden||D.length===0)return!1;if(t.key==="ArrowDown"||t.key==="ArrowUp"){t.preventDefault();const n=t.key==="ArrowDown"?1:-1;return K=(K+n+D.length)%D.length,gt(),!0}return t.key==="Enter"||t.key==="Tab"?(t.preventDefault(),Pt(K),!0):t.key==="Escape"?(t.preventDefault(),_(),!0):!1}async function jt(){const t=document.getElementById("bots-input");if(!t||!d.activeId||Qt||!t.value.trim()&&j.length===0)return;const e=d.activeId,n=t.value.trim()?t.value:"See the attached image",o=j.map(({data:s,mimeType:a})=>({data:s,mimeType:a}));P(null),Ot(!0);try{await x(`/api/bots/${e}/input`,{method:"POST",body:JSON.stringify({text:n,images:o.length?o:void 0})}),t.value===n&&(t.value="",et(t)),_(),j.length=0,nt(),O=!0}catch(s){P(s instanceof Error?s.message:String(s))}finally{Ot(!1)}}function Dt(t){d.activeId&&t(d.activeId).catch(e=>V({kind:"notice",level:"error",text:e instanceof Error?e.message:String(e)}))}function yt(){d.activeId=null,q=[],O=!0,R();const t=document.getElementById("bots-view");t&&(t.hidden=!0);try{d.ws?.close()}catch{}d.ws=null,tt();const e=document.getElementById("terminal-container"),n=document.getElementById("main-placeholder"),o=!!document.querySelector(".session-item.active:not(.bot-item)");e&&o?(e.style.display="",n&&(n.style.display="none")):n&&(n.style.display="")}async function Ht(t){d.activeId=t,q=[],O=!0,j.length=0,nt(),vt(),_();const e=document.getElementById("bots-input");e&&(e.value="",et(e)),P(null);const n=document.getElementById("bv-jump");n&&(n.hidden=!0),window.__collapseSidebar?.(),R(),d.items.set(t,[]);const o=document.getElementById("bots-view");o&&(o.hidden=!1);const s=document.getElementById("main-placeholder");s&&(s.style.display="none");const a=document.getElementById("terminal-container");a&&(a.style.display="none");const l=document.getElementById("file-editor");l&&(l.style.display="none"),tt(),st();try{d.ws?.close()}catch{}const c=location.protocol==="https:"?"wss:":"ws:",r=new WebSocket(`${c}//${location.host}/ws/bots/${encodeURIComponent(t)}?token=${encodeURIComponent(ft())}`);d.ws=r,r.onmessage=p=>{try{Ut(JSON.parse(String(p.data)))}catch{}},r.onclose=()=>{d.activeId===t&&setTimeout(()=>{d.activeId===t&&T(!0)},1500)},await T(!0)}function it(){return d.bots.find(t=>t.id===d.activeId)||null}function wt(){const t=it();if(!t)return;const e=document.getElementById("bv-title"),n=document.getElementById("bv-status"),o=document.getElementById("bv-dot");e&&(e.textContent=t.title),n&&(n.textContent=Zt[t.status]??t.status.replace(/_/g," "),n.dataset.status=t.status,n.style.color=Tt(t.status),n.title=`${t.status.replace(/_/g," ")} \xB7 ${t.templateId} \xB7 ${t.projectPath}`);const s=document.getElementById("bv-mode-btn");s&&Jt(s,t.runtimeMode||"supervised");for(const c of document.querySelectorAll("#bv-mode-menu button")){const r=c.dataset.mode===t.runtimeMode;c.classList.toggle("active",r),c.setAttribute("aria-checked",r?"true":"false")}const a=document.getElementById("bv-allow-all"),l=d.approvals.filter(c=>c.botId===t.id).length;if(a){a.hidden=l===0;const c=a.querySelector(".bv-menu-text b");c&&(c.textContent=`Allow all (${l})`)}o&&(o.style.background=Tt(t.status))}const Zt={queued:"queued",starting:"starting",running:"running",waiting_input:"waiting",waiting_approval:"approval",completed:"done",failed:"failed",cancelled:"stopped",stale:"stale"},Rt={supervised:"\u9ED8\u8BA4","parent-supervised":"\u76D1\u7BA1","full-access":"\u5168\u653E\u884C"},_t={supervised:"shield","parent-supervised":"shield-up","full-access":"shield-alert"};function Jt(t,e){const n=_t[e]??"shield";t.dataset.mode=e,t.innerHTML=H(n,'width="15" height="15"');const o=`\u5BA1\u6279\u6A21\u5F0F\uFF1A${Rt[e]??e}`;t.title=`${o}\uFF08\u70B9\u5F00\u53EF\u5207\u6362\uFF09`,t.setAttribute("aria-label",o)}async function te(t){if(d.activeId)try{await x(`/api/bots/${d.activeId}/mode`,{method:"POST",body:JSON.stringify({mode:t})});const e=it();e&&(e.runtimeMode=t),wt(),V({kind:"notice",level:"info",text:`\u5BA1\u6279\u6A21\u5F0F\uFF1A${Rt[t]||t}`})}catch(e){V({kind:"notice",level:"error",text:e instanceof Error?e.message:String(e)})}}function V(t,e=d.activeId){if(!e)return;const n=d.items.get(e)||[];n.push(t),d.items.set(e,n),e===d.activeId&&F()}function F(){if(d.renderQueued)return;d.renderQueued=!0;const t=Math.max(0,60-(performance.now()-Bt));window.setTimeout(()=>{d.renderQueued=!1,Bt=performance.now(),st()},t)}function kt(t){switch(t.kind){case"assistant":return{text:t.text,thinking:t.thinking};case"tool":return{phase:t.phase,output:t.output,error:t.isError,durationMs:t.durationMs};case"approval":return{decided:t.decided,approvalState:t.approval.state};default:return{}}}function ee(t,e){return t.text!==e.text||t.thinking!==e.thinking||t.phase!==e.phase||t.output!==e.output||t.error!==e.error||t.durationMs!==e.durationMs||t.decided!==e.decided||t.approvalState!==e.approvalState}function xt(t){if(t.kind==="user"){const e=i("div","bv-msg bv-user");return e.appendChild(mt(t.text)),e}if(t.kind==="assistant"){const e=i("div","bv-msg bv-assistant");if(t.thinking){const o=i("details","bv-thinking");o.appendChild(i("summary",void 0,"thinking")),o.appendChild(i("div",void 0,t.thinking)),e.appendChild(o)}const n=i("div","bv-text");return n.appendChild(mt(t.text)),e.appendChild(n),e}return t.kind==="tool"?ie(t):t.kind==="approval"?se(t):i("div",`bv-notice bv-notice-${t.level}`,t.text)}function ne(t,e){const n=t.querySelector("details.bv-thinking");if(e.thinking)if(n){const s=n.querySelector("div");s&&s.textContent!==e.thinking&&(s.textContent=e.thinking)}else{const s=i("details","bv-thinking");s.appendChild(i("summary",void 0,"thinking")),s.appendChild(i("div",void 0,e.thinking)),t.prepend(s)}else n&&n.remove();const o=t.querySelector(".bv-text");o&&o.replaceChildren(mt(e.text))}function st(){const t=document.getElementById("bots-messages");if(!t||!d.activeId||document.getElementById("bots-view")?.hidden)return;const e=d.items.get(d.activeId)||[],n=Math.max(0,e.length-At),o=n?e.slice(n):e,s=O;if(o.length<q.length||o.some((l,c)=>q[c]?.item!==l))t.textContent="",q=o.map(l=>{const c=xt(l);return t.appendChild(c),{item:l,snapshot:kt(l),node:c}});else{for(let l=q.length;l<o.length;l++){const c=o[l],r=xt(c);t.appendChild(r),q.push({item:c,snapshot:kt(c),node:r})}for(let l=0;l<o.length;l++){const c=o[l],r=q[l],p=kt(c);if(ee(r.snapshot,p)){if(c.kind==="assistant")ne(r.node,c);else{const f=xt(c);r.node.replaceWith(f),r.node=f}r.snapshot=p}}}oe(t,n),s&&(t.scrollTop=t.scrollHeight)}function oe(t,e){const n=t.querySelector(":scope > .bv-earlier");if(e===0){n?.remove();return}const o=`Show earlier messages (${e})`;if(n){n.textContent!==o&&(n.textContent=o);return}const s=i("button","bv-earlier",o);s.type="button",s.onclick=()=>{const a=t.scrollHeight,l=t.scrollTop;At+=$t,q=[],st(),t.scrollTop=l+(t.scrollHeight-a)},t.prepend(s)}function ie(t){const e=i("details","bv-tool");e.open=t.phase!=="end"||!!t.isError;const n=i("summary"),o=i("span","bv-tool-name",t.name);if(n.appendChild(o),t.phase!=="end"&&n.appendChild(i("span","bv-tool-phase",t.phase)),t.isError&&n.appendChild(i("span","bv-tool-error","error")),typeof t.durationMs=="number"&&n.appendChild(i("span","bv-tool-meta",`${Math.round(t.durationMs)}ms`)),e.appendChild(n),t.args!==void 0){const s=i("pre","bv-pre");s.textContent=typeof t.args=="string"?t.args:JSON.stringify(t.args,null,2),e.appendChild(s)}if(t.output){const s=i("pre","bv-pre bv-output");s.textContent=t.output,e.appendChild(s)}return e}function se(t){const e=i("div","bv-approval"),n=t.approval;if(e.appendChild(i("div","bv-approval-tag","Needs approval")),e.appendChild(i("div","bv-approval-title",n.title)),n.message){const v=i("pre","bv-pre bv-approval-detail");v.textContent=n.message,e.appendChild(v)}if(t.decided)return e.appendChild(i("div","bv-approval-decided",t.decided==="allowed"?"Allowed":"Denied")),e;const o=i("input","bv-reason");o.placeholder="reason (optional)",o.setAttribute("aria-label","Reason (optional)");const s=i("div","bv-approval-actions"),a=i("button","btn primary","Allow once"),l=/^Allow (.+?)\?$/.exec(n.title)?.[1],c=n.method==="confirm"?l&&l.length<=24?`Always allow ${l}`:"Always allow this tool":"Allow for this session",r=i("button","btn",c);r.hidden=n.method!=="confirm";const p=i("button","btn danger","Deny"),f=[a,r,p],b=async(v,y,h)=>{const S=h.textContent??"";for(const C of f)C.disabled=!0;h.textContent=v?"Allowing\u2026":"Denying\u2026";try{await x(`/api/bots/${n.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:n.id,allow:v,always:y,reason:o.value||void 0})}),t.decided=v?"allowed":"denied",F(),T(!0)}catch(C){for(const M of f)M.disabled=!1;h.textContent=S,V({kind:"notice",level:"error",text:C instanceof Error?C.message:String(C)})}};return a.onclick=()=>void b(!0,!1,a),r.onclick=()=>void b(!0,!0,r),p.onclick=()=>void b(!1,!1,p),s.append(o,a,r,p),e.appendChild(s),e}function Ut(t){const e=String(t.type||""),n=d.activeId;if(!n)return;const o=d.items.get(n)||[];if(e==="snapshot")d.items.set(n,[]);else if(e==="queue")d.queues.set(n,{steering:Array.isArray(t.steering)?t.steering:[],followUp:Array.isArray(t.followUp)?t.followUp:[]}),vt();else if(e==="user")O=!0,V({kind:"user",text:String(t.text||"")});else if(e==="status"){const s=it();s&&(s.status=String(t.status||s.status)),wt(),le()}else if(e==="message"){const s=t.message;if(!s||String(s.role||"")!=="assistant")return;const l=ae(s),c=re(s),r=o[o.length-1];r&&r.kind==="assistant"?(r.text=l||r.text,r.thinking=c||r.thinking):o.push({kind:"assistant",text:l,thinking:c}),d.items.set(n,o),F()}else if(e==="delta"){const s=String(t.kind||""),a=String(t.delta||"");let l=o[o.length-1];(!l||l.kind!=="assistant")&&(o.push({kind:"assistant",text:"",thinking:""}),l=o[o.length-1]),l.kind==="assistant"&&(s==="text"?l.text+=a:s==="thinking"&&(l.thinking+=a)),d.items.set(n,o),F()}else if(e==="tool"){const s=String(t.callId||""),a=o.find(c=>c.kind==="tool"&&c.callId===s),l=String(t.phase||"start");a?(a.phase=l,l==="update"&&t.output&&(a.output=String(t.output)),l==="end"&&(t.output&&(a.output=String(t.output)),a.isError=t.isError===!0,typeof t.durationMs=="number"&&(a.durationMs=t.durationMs))):o.push({kind:"tool",callId:s,name:String(t.name||"tool"),args:t.args,output:t.output?String(t.output):void 0,isError:t.isError===!0,durationMs:typeof t.durationMs=="number"?t.durationMs:void 0,phase:l}),d.items.set(n,o),F()}else if(e==="approval"){const s=t.approval;if(!s)return;const a=o;for(let l=a.length-1;l>=0;l--){const c=a[l];if(c.kind==="approval"&&c.approval.id===s.id){c.approval=s,s.state!=="pending"&&(c.decided=s.state==="allowed"?"allowed":"denied"),d.items.set(n,a),F();return}}a.push({kind:"approval",approval:s}),d.items.set(n,a),F()}else e==="notice"&&V({kind:"notice",level:String(t.level||"info"),text:String(t.text||"")})}function ae(t){const e=t.content;return Array.isArray(e)?e.map(n=>n&&typeof n=="object"&&n.type==="text"?String(n.text||""):"").join(""):String(t.text||"")}function re(t){const e=t.content;return Array.isArray(e)?e.map(n=>n&&typeof n=="object"&&n.type==="thinking"?String(n.thinking||""):"").join(""):""}async function T(t=!1){try{const[e,n]=await Promise.all([x("/api/bots"),x("/api/bots/approvals")]);if(d.bots=e,d.approvals=n,tt(),wt(),t&&d.activeId){const o=await x(`/api/bots/${d.activeId}/events?limit=300`);de(o)}}catch{}}async function le(){try{d.bots=await x("/api/bots"),tt()}catch{}}function de(t){if(d.activeId){d.items.set(d.activeId,[]);for(const e of t)Ut(e);st()}}function ce(){const t=i("div","bots-modal");t.id="bots-modal",t.hidden=!0;const e=i("div","bots-modal-card"),n=i("div","bots-modal-head"),o=i("span");o.id="bots-modal-title";const s=i("button","btn");s.innerHTML=H("close",'width="14" height="14"'),s.title="Close",s.onclick=()=>at(),n.append(o,s);const a=i("div","bots-modal-body");a.id="bots-modal-body",e.append(n,a),t.appendChild(e),t.onclick=l=>{l.target===t&&at()},document.body.appendChild(t)}function St(t){const e=document.getElementById("bots-modal"),n=document.getElementById("bots-modal-title"),o=document.getElementById("bots-modal-body");if(!e||!o)throw new Error("modal missing");return n&&(n.textContent=t),o.textContent="",e.hidden=!1,o}function at(){const t=document.getElementById("bots-modal");t&&(t.hidden=!0)}async function pe(){return d.catalog||(d.catalog=await x("/api/bots/catalog")),d.catalog}async function Wt(){return d.templates=await x("/api/bots/templates"),d.templates}async function X(){const t=St("Bot templates"),[e,n]=await Promise.all([pe(),Wt()]),o=i("div","bv-template-list");for(const r of n){const p=i("div","bv-template-row");p.appendChild(i("span","bv-template-name",r.manifest.name)),p.appendChild(i("span","bv-template-desc",r.manifest.description||""));const f=i("button","btn","Edit");f.onclick=()=>Vt(t,e,r);const b=i("button","btn","Copy");b.title="Duplicate this template",b.onclick=()=>{const h=JSON.parse(JSON.stringify(r.manifest));h.name=`${r.manifest.name} copy`,x("/api/bots/templates",{method:"POST",body:JSON.stringify({manifest:h})}).then(()=>X()).catch(S=>alert(S instanceof Error?S.message:String(S)))};const v=i("button","btn danger","Delete");v.onclick=()=>{confirm(`Delete template ${r.manifest.name}?`)&&x(`/api/bots/templates/${r.id}`,{method:"DELETE"}).then(()=>X())};const y=i("span","bv-template-actions");y.append(f,b,v),p.appendChild(y),o.appendChild(p)}n.length===0&&o.appendChild(i("div","bots-empty","No templates yet")),t.appendChild(o);const s=i("div","bv-template-actions"),a=i("button","btn primary","New template");a.onclick=()=>Vt(t,e,null);const l=i("button","btn","Export");l.title="Download templates + library as JSON",l.onclick=()=>{(async()=>{try{const r=await fetch("/api/bots/export",{headers:{Authorization:`Bearer ${ft()}`}});if(!r.ok)throw new Error(`HTTP ${r.status}`);const p=await r.blob(),f=document.createElement("a");f.href=URL.createObjectURL(p),f.download=`tmux-weblink-bots-${new Date().toISOString().slice(0,10)}.json`,f.click(),setTimeout(()=>URL.revokeObjectURL(f.href),2e3)}catch(r){alert(r instanceof Error?r.message:String(r))}})()};const c=i("button","btn","Import");c.title="Restore templates from a JSON bundle",c.onclick=()=>{const r=document.createElement("input");r.type="file",r.accept="application/json,.json",r.onchange=()=>{const p=r.files?.[0];p&&(async()=>{try{const f=JSON.parse(await p.text()),b=await x("/api/bots/import",{method:"POST",body:JSON.stringify(f)});alert(`Imported ${b.templates} templates, ${b.files} library files (${b.skipped} kept)`),await X()}catch(f){alert(f instanceof Error?f.message:String(f))}})()},r.click()},s.append(a,l,c),t.appendChild(s)}function Ct(t,e,n){const o=i("div","bv-field");o.appendChild(i("label","bv-label",t));const s=i("div","bv-check-grid"),a=[];for(const l of e){const c=i("label","bv-check"),r=document.createElement("input");r.type="checkbox",r.checked=n.includes(l.id),c.append(r,i("span",void 0,l.label)),l.hint&&(c.title=l.hint),s.appendChild(c),a.push({id:l.id,input:r})}return o.appendChild(s),{element:o,get:()=>a.filter(l=>l.input.checked).map(l=>l.id)}}function Vt(t,e,n){t.textContent="";const o=n?JSON.parse(JSON.stringify(n.manifest)):{name:"new-bot",description:""},s=i("input","bv-input");s.value=o.name,s.placeholder="Template name";const a=i("input","bv-input");a.value=o.description||"",a.placeholder="One line description";const l=i("textarea","bv-textarea");l.rows=6,l.value=o.system||"",l.placeholder="System prompt for this bot (written to SYSTEM.md)";const c=Ct("Skills",e.skills.map(m=>({id:m.id,label:m.name,hint:m.description})),o.skills||[]),r=Ct("Extensions (Pi builtins + library)",e.extensions.map(m=>({id:m.id,label:`${m.name}${m.kind==="builtin"?" (builtin)":""}`,hint:m.description})),(o.extensions||[]).map(m=>m.replace(/^.*\//,"").replace(/\.(js|ts)$/,""))),p=Ct("Prompt templates",e.prompts.map(m=>({id:m.id,label:m.name})),o.prompts||[]),f=i("select","bv-input");f.appendChild(new Option("none",""));for(const m of e.mcp)f.appendChild(new Option(m.name,m.id));o.mcp&&(f.value=e.mcp.find(m=>JSON.stringify(m.servers)===JSON.stringify(o.mcp?.mcpServers))?.id||"");const b=i("div","bv-field");b.appendChild(i("label","bv-label","Tools (allow list; deny always blocks)"));const v=i("div","bv-check-grid"),y=[];for(const m of e.tools){const I=i("label","bv-check"),E=document.createElement("input");E.type="checkbox",E.checked=(o.tools?.allow||[]).includes(m.name)||!o.tools?.allow?.length&&["read","grep","find","ls","edit","write","bash"].includes(m.name),I.append(E,i("span",void 0,m.name)),v.appendChild(I),y.push({name:m.name,input:E})}b.appendChild(v);const h=i("input","bv-input");h.value=(o.tools?.deny||[]).join(", "),h.placeholder="Always deny (comma separated), e.g. bash, write";const S=i("textarea","bv-textarea");S.rows=2,S.value=(o.packages||[]).join(`
|
|
2
|
+
`),S.placeholder="Pi packages, one per line (npm:@scope/pkg@1.2.3, git:..., ./path)";const C=i("select","bv-input");C.appendChild(new Option("default (Pi settings)",""));for(const m of e.models)C.appendChild(new Option(`${m.provider}/${m.model}`,`${m.provider}
|
|
3
|
+
${m.model}`));o.model?.provider&&o.model?.id&&(C.value=`${o.model.provider}
|
|
4
|
+
${o.model.id}`);const M=i("select","bv-input");for(const m of["","off","minimal","low","medium","high","xhigh","max"])M.appendChild(new Option(m||"default",m));o.model?.thinking&&(M.value=o.model.thinking);const Q=i("select","bv-input");for(const m of["supervised","auto-accept-edits","full-access"])Q.appendChild(new Option(m,m));Q.value=o.permissions?.runtimeMode||"supervised";const J=i("select","bv-input");J.appendChild(new Option("ignore project .pi (recommended)","ignore")),J.appendChild(new Option("inherit project .pi (needs trust)","inherit")),J.value=o.projectResources||"ignore";const Y=i("label","bv-check"),L=document.createElement("input");L.type="checkbox",L.checked=!!o.orchestrator,Y.append(L,i("span",void 0,"Super bot: gets orchestration tools (create/stop/status child bots)"));const g=(m,I)=>{const E=i("div","bv-field");return E.appendChild(i("label","bv-label",m)),E.appendChild(I),E};t.append(g("Name",s),g("Description",a),g("System prompt",l),c.element,r.element,p.element,g("MCP preset",f),b,g("Always deny tools",h),g("Packages",S),g("Model",C),g("Thinking level",M),g("Approval mode",Q),g("Project resources",J),Y);const $=i("button","btn primary",n?"Save template":"Create template");$.onclick=async()=>{const[m,I]=C.value.split(`
|
|
5
|
+
`),E=e.mcp.find(w=>w.id===f.value),lt={name:s.value.trim()||"bot",description:a.value.trim()||void 0,system:l.value.trim()||void 0,skills:c.get(),extensions:r.get().map(w=>(w.startsWith("builtin:"),w)),prompts:p.get(),packages:S.value.split(`
|
|
6
|
+
`).map(w=>w.trim()).filter(Boolean),mcp:E?{mcpServers:E.servers}:void 0,tools:{allow:y.filter(w=>w.input.checked).map(w=>w.name),deny:h.value.split(",").map(w=>w.trim()).filter(Boolean)},model:m?{provider:m,id:I,thinking:M.value||void 0}:void 0,permissions:{runtimeMode:Q.value},projectResources:J.value==="inherit"?"inherit":"ignore",orchestrator:L.checked||void 0};try{await x("/api/bots/templates",{method:"POST",body:JSON.stringify({id:n?.id,manifest:lt})}),at(),await X()}catch(w){alert(w instanceof Error?w.message:String(w))}},t.appendChild($)}async function ue(){return me("")}async function me(t){const e=St("New bot"),n=await Wt();if(n.length===0){e.appendChild(i("div","bots-empty","No templates yet \u2014 create one with \u201CNew template\u201D."));return}const o=i("select","bv-input");for(const p of n)o.appendChild(new Option(p.manifest.name,p.id));const s=i("input","bv-input");s.placeholder="Title (defaults to template name)";const a=i("input","bv-input");a.placeholder="/path/to/project";const l=t||d.bots[0]?.projectPath||"";a.value=l;const c=i("select","bv-input");c.appendChild(new Option("shared \u2014 run in the project folder","shared")),c.appendChild(new Option("worktree \u2014 isolated git worktree","worktree")),e.append(rt("Template",o),rt("Title",s),rt("Project path",a),rt("Workspace",c));const r=i("button","btn primary","Create bot");r.onclick=async()=>{try{const p=await x("/api/bots",{method:"POST",body:JSON.stringify({templateId:o.value,title:s.value.trim()||void 0,projectPath:a.value.trim()||void 0,isolation:c.value})});at(),await T(!0),await Ht(p.id)}catch(p){alert(p instanceof Error?p.message:String(p))}},e.appendChild(r)}function rt(t,e){const n=i("div","bv-field");return n.appendChild(i("label","bv-label",t)),n.appendChild(e),n}async function Et(){const t=St("Needs you");if(d.approvals=await x("/api/bots/approvals"),d.approvals.length===0){t.appendChild(i("div","bots-empty","Nothing waiting."));return}for(const e of d.approvals){const n=i("div","bv-approval");if(n.appendChild(i("div","bv-approval-tag",e.botTitle)),n.appendChild(i("div","bv-approval-title",e.title)),e.message){const p=i("pre","bv-pre bv-approval-detail");p.textContent=e.message,n.appendChild(p)}const o=i("input","bv-reason");o.placeholder="reason (optional)",o.setAttribute("aria-label","Reason (optional)");const s=i("div","bv-approval-actions"),a=i("button","btn primary","Allow once"),l=i("button","btn danger","Deny"),c=[a,l],r=async(p,f)=>{const b=f.textContent??"";for(const v of c)v.disabled=!0;f.textContent=p?"Allowing\u2026":"Denying\u2026";try{await x(`/api/bots/${e.botId}/approve`,{method:"POST",body:JSON.stringify({requestId:e.id,allow:p,reason:o.value||void 0})}),await T(!0),await Et()}catch(v){for(const y of c)y.disabled=!1;f.textContent=b,V({kind:"notice",level:"error",text:v instanceof Error?v.message:String(v)})}};a.onclick=()=>void r(!0,a),l.onclick=()=>void r(!1,l),s.append(o,a,l),n.appendChild(s),t.appendChild(n)}}function ve(){window.__botsInited||(window.__botsInited=!0,Gt(),Kt(),window.__openBot=Ht,document.addEventListener("click",t=>{const e=t.target;e&&(e.closest(".session-item.bot-item")||e.closest(".session-item")&&d.activeId&&setTimeout(()=>yt(),0))},!0),document.addEventListener("click",t=>{const e=t.target;!e||!d.activeId||(e.closest("#mode-files")||e.closest(".file-tree-item")||e.closest(".file-roots-list li"))&&yt()}),T(!0),d.pollTimer=window.setInterval(()=>{document.hidden||T()},6e3),window.addEventListener("beforeunload",()=>window.clearInterval(d.pollTimer)))}export{ve as initBots,me as openNewBotForPath};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
const y=["const","let","var","function","return","if","else","for","while","do","switch","case","default","break","continue","class","extends","implements","interface","type","enum","import","export","from","as","async","await","try","catch","finally","throw","new","this","super","typeof","instanceof","in","of","void","null","undefined","true","false","public","private","protected","readonly","static","yield","delete","declare","namespace","satisfies","infer","keyof","is"],g=["def","class","return","if","elif","else","for","while","try","except","finally","with","as","import","from","pass","raise","lambda","yield","assert","del","global","nonlocal","and","or","not","in","is","None","True","False","async","await","match","case"],S=["if","then","else","elif","fi","for","while","do","done","case","esac","function","return","export","local","set","unset","source","echo","cd","exit","in"],C={js:"js",jsx:"js",ts:"js",tsx:"js",javascript:"js",typescript:"js",node:"js",mjs:"js",cjs:"js",py:"py",python:"py",sh:"sh",bash:"sh",shell:"sh",zsh:"sh",console:"sh",json:"json",jsonc:"json",css:"css",scss:"css",diff:"diff",patch:"diff"},k={js:y,py:g,sh:S,json:[],css:[],diff:[],plain:[]},N={js:[{cls:"com",source:"\\/\\/[^\\n]*|\\/\\*[\\s\\S]*?\\*\\/"},{cls:"str",source:"\"(?:\\\\.|[^\"\\\\])*\"|'(?:\\\\.|[^'\\\\])*'|`(?:\\\\.|[^`\\\\])*`"},{cls:"num",source:"\\b\\d[\\d_]*(?:\\.\\d+)?\\b"},{cls:"word",source:"\\b[A-Za-z_$][\\w$]*\\b"}],py:[{cls:"com",source:"#[^\\n]*"},{cls:"str",source:`"""[\\s\\S]*?"""|'''[\\s\\S]*?'''|"(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*'`},{cls:"num",source:"\\b\\d[\\d_]*(?:\\.\\d+)?\\b"},{cls:"word",source:"\\b[A-Za-z_][\\w]*\\b"}],sh:[{cls:"com",source:"#[^\\n]*"},{cls:"str",source:`"(?:\\\\.|[^"\\\\])*"|'[^']*'`},{cls:"num",source:"\\b\\d+\\b"},{cls:"word",source:"\\b[A-Za-z_][\\w-]*\\b"}],json:[{cls:"str",source:'"(?:\\\\.|[^"\\\\])*"'},{cls:"num",source:"-?\\b\\d+(?:\\.\\d+)?\\b"},{cls:"word",source:"\\b(?:true|false|null)\\b"}],css:[{cls:"com",source:"\\/\\*[\\s\\S]*?\\*\\/"},{cls:"str",source:`"(?:\\\\.|[^"\\\\])*"|'[^']*'`},{cls:"num",source:"#[0-9a-fA-F]{3,8}\\b|-?\\b\\d+(?:\\.\\d+)?(?:px|em|rem|%|vh|vw|s|ms)?\\b"},{cls:"word",source:"[.#][\\w-]+|@[\\w-]+|\\b[a-z-]+(?=\\s*:)"}],diff:[],plain:[]};function _(e,t,p){const n=C[p.trim().toLowerCase()]??"plain",s=e.createDocumentFragment();if(n==="diff")return E(e,s,t),s;const c=N[n];if(c.length===0)return s.appendChild(e.createTextNode(t)),s;const i=new Set(k[n]),l=c.map((o,r)=>`g${r}`).join(""),w=new RegExp(c.map((o,r)=>`(?<g${r}>${o.source})`).join("|"),"g");let a=0;for(const o of t.matchAll(w)){const r=o.index??0;r>a&&s.appendChild(e.createTextNode(t.slice(a,r))),a=r+o[0].length;const b=o.groups??{},m=c.findIndex((j,x)=>b[`g${x}`]!==void 0),d=o[0];if(m<0){s.appendChild(e.createTextNode(d));continue}const f=c[m].cls;let u=f==="word"?i.has(d)?"tok-kw":null:`tok-${f}`;if(n==="json"&&f==="str"&&t.slice(a).trimStart().startsWith(":")&&(u="tok-key"),u===null){s.appendChild(e.createTextNode(d));continue}const h=e.createElement("span");h.className=u,h.textContent=d,s.appendChild(h)}return a<t.length&&s.appendChild(e.createTextNode(t.slice(a))),s}function E(e,t,p){const n=p.split(`
|
|
2
|
+
`);n.forEach((s,c)=>{const i=s.startsWith("+")?"tok-add":s.startsWith("-")?"tok-del":s.startsWith("@@")?"tok-meta":null;if(i){const l=e.createElement("span");l.className=i,l.textContent=s,t.appendChild(l)}else t.appendChild(e.createTextNode(s));c<n.length-1&&t.appendChild(e.createTextNode(`
|
|
3
|
+
`))})}export{_ as highlightCode};
|
package/dist/browser/markdown.js
CHANGED
|
@@ -1,2 +1,4 @@
|
|
|
1
|
-
import{marked as
|
|
2
|
-
`)
|
|
1
|
+
import{marked as M}from"marked";import{highlightCode as R}from"./highlight.js";const $=new Set(["http:","https:","mailto:"]);function T(c){const l=(c??"").trim();if(!l||l.startsWith("//"))return null;if(!/^[a-z][a-z0-9+.-]*:/i.test(l))return l;try{return $.has(new URL(l).protocol)?l:null}catch{return null}}const _=c=>/^[a-z][a-z0-9+.-]*:/i.test(c)&&!c.startsWith("mailto:"),S=4e5,H=200,z=900;function q(c){if(c.length<z||/^ {0,3}(?:<|:::|\$\$|\\\[|\[\^)/m.test(c)||/^[ \t]*\[[^\]]+\]:/m.test(c))return null;const l=c.split(`
|
|
2
|
+
`),p=[];let f=[],m=null;const i=()=>{const d=f.join(`
|
|
3
|
+
`);d.trim()&&p.push(d),f=[]};for(let d=0;d<l.length;d++){const h=l[d],C=/^ {0,3}(`{3,}|~{3,})/.exec(h);if(m){f.push(h),C&&h.trimStart().startsWith(m)&&(m=null);continue}if(C){m=C[1],f.push(h);continue}if(f.push(h),h.trim()!=="")continue;let o=d+1;for(;o<l.length&&l[o].trim()==="";)o++;if(o>=l.length)break;const b=l[o];if(/^[ \t]/.test(b)||/^(?:[-*+](?:[ \t]|$)|\d{1,9}[.)](?:[ \t]|$)|>|\||:::|```|~~~)/.test(b))continue;const N=[...f].reverse().find(e=>e.trim()!=="")??"";if(/^[ \t]*(?:\||>)/.test(N))continue;const t=N.trim();/^[-*+]$/.test(t)||/^\d{1,9}[.)]$/.test(t)||i()}return i(),p.length>1?p:null}function I(c){const l=new Map;let p=0;function f(t,e){const n=t.length+H;if(!(n>S/4)){l.set(t,{fragment:e,chars:n}),p+=n;for(const r of l.keys()){if(p<=S)break;const s=l.get(r);s&&(l.delete(r),p-=s.chars)}}}function m(t,e){e.split(`
|
|
4
|
+
`).forEach((r,s)=>{s>0&&t.appendChild(c.createElement("br")),r&&t.appendChild(c.createTextNode(r))})}function i(t,e){switch(e.type){case"text":{if(e.tokens?.length){for(const n of e.tokens)i(t,n);return}m(t,e.text??e.raw??"");return}case"escape":t.appendChild(c.createTextNode(e.text??""));return;case"strong":case"em":case"del":{const n=c.createElement(e.type==="strong"?"strong":e.type==="em"?"em":"del");for(const r of e.tokens??[])i(n,r);t.appendChild(n);return}case"codespan":{const n=c.createElement("code");n.textContent=e.text??"",t.appendChild(n);return}case"br":t.appendChild(c.createElement("br"));return;case"link":{const n=e.tokens??[],r=T(e.href);if(!r){for(const a of n)i(t,a);return}const s=c.createElement("a");s.href=r,s.rel="noreferrer noopener",e.title&&(s.title=e.title),_(r)&&(s.target="_blank");for(const a of n)i(s,a);t.appendChild(s);return}case"image":{const n=T(e.href),r=e.text?.trim()||e.href||"image";if(!n){t.appendChild(c.createTextNode(r));return}const s=c.createElement("a");s.href=n,s.textContent=r,s.rel="noreferrer noopener",_(n)&&(s.target="_blank"),t.appendChild(s);return}case"html":t.appendChild(c.createTextNode(e.raw??e.text??""));return;default:if(e.tokens?.length){for(const n of e.tokens)i(t,n);return}m(t,e.text??e.raw??"")}}function d(t){const e=c.createElement("div");e.className="bv-code";const n=c.createElement("div");n.className="bv-code-head";const r=(t.lang??"").trim().split(/\s+/)[0]??"",s=c.createElement("span");s.className="bv-code-lang",s.textContent=r||"text";const a=c.createElement("button");a.type="button",a.className="bv-code-copy",a.textContent="Copy";const x=t.text??"";a.addEventListener("click",()=>{const u=navigator.clipboard?.writeText(x);u&&u.then(()=>{a.textContent="Copied",window.setTimeout(()=>{a.textContent="Copy"},1200)},()=>{})}),n.append(s,a);const y=c.createElement("pre"),g=c.createElement("code");return r&&(g.className=`language-${r}`),g.appendChild(R(c,x,r)),y.appendChild(g),e.append(n,y),e}function h(t,e){const n=c.createElement("div");n.className="bv-table";const r=c.createElement("table"),s=c.createElement("thead"),a=c.createElement("tr"),x=e.align??[],y=(u,E,v)=>{const w=c.createElement(u);x[v]&&(w.style.textAlign=x[v]);for(const A of E.tokens??[])i(w,A);return w};(e.header??[]).forEach((u,E)=>a.appendChild(y("th",u,E))),s.appendChild(a);const g=c.createElement("tbody");for(const u of e.rows??[]){const E=c.createElement("tr");u.forEach((v,w)=>E.appendChild(y("td",v,w))),g.appendChild(E)}r.append(s,g),n.appendChild(r),t.appendChild(n)}function C(t,e){const n=c.createElement("li");if(e.task){const r=c.createElement("input");r.type="checkbox",r.disabled=!0,r.checked=e.checked===!0,n.appendChild(r)}for(const r of e.tokens??[])if(r.type==="text")i(n,r);else if(r.type==="paragraph")for(const s of r.tokens??[])i(n,s);else o(n,r);t.appendChild(n)}function o(t,e){switch(e.type){case"space":return;case"heading":{const n=Math.min(Math.max(e.depth??1,1),6),r=c.createElement(`h${n}`);for(const s of e.tokens??[])i(r,s);t.appendChild(r);return}case"paragraph":{const n=c.createElement("p");for(const r of e.tokens??[])i(n,r);t.appendChild(n);return}case"text":i(t,e);return;case"code":t.appendChild(d(e));return;case"blockquote":{const n=c.createElement("blockquote");for(const r of e.tokens??[])o(n,r);t.appendChild(n);return}case"list":{const n=e.items??e.tokens??[];if(e.ordered){const r=c.createElement("ol");typeof e.start=="number"&&e.start!==1&&(r.start=e.start);for(const s of n)C(r,s);t.appendChild(r)}else{const r=c.createElement("ul");for(const s of n)C(r,s);t.appendChild(r)}return}case"table":h(t,e);return;case"hr":t.appendChild(c.createElement("hr"));return;case"html":case"escape":t.appendChild(c.createTextNode(e.raw??e.text??""));return;default:if(e.tokens?.length){for(const n of e.tokens)o(t,n);return}e.text&&t.appendChild(c.createTextNode(e.text))}}function b(t){const e=c.createDocumentFragment();try{const n=M.lexer(t);for(const r of n)o(e,r)}catch{e.replaceChildren(c.createTextNode(t))}return e}function N(t){const e=l.get(t);if(e)return l.delete(t),l.set(t,e),e.fragment.cloneNode(!0);const n=b(t);return f(t,n),n.cloneNode(!0)}return t=>{const e=l.get(t);if(e)return l.delete(t),l.set(t,e),e.fragment.cloneNode(!0);const n=q(t);if(n){const s=c.createDocumentFragment();for(const a of n)s.appendChild(N(a));return s}const r=b(t);return f(t,r),r.cloneNode(!0)}}export{I as createMarkdownRenderer,T as safeHref};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{icon as b}from"../lib/icons.js";let s=null;function u(r){return r.replace(/[&<>"]/g,o=>({"&":"&","<":"<",">":">",'"':"""})[o])}function c(){s?.dispose(),s=null}function v(r){const o=s?.anchor===r.anchor;c(),!o&&w(r)}function w(r){const{anchor:o,items:m}=r,n=document.createElement("div");n.className="bv-menu overlay-menu",n.setAttribute("role","menu"),r.label&&n.setAttribute("aria-label",r.label);const a=[];for(const e of m){const t=document.createElement("button");t.type="button",t.className=`bv-menu-item${e.danger?" danger":""}`,t.setAttribute("role","menuitem"),t.disabled=e.disabled===!0,t.innerHTML=`<span class="bv-menu-icon">${b(e.icon,'width="15" height="15"')}</span><span class="bv-menu-text"><b>${u(e.label)}</b>${e.detail?`<span>${u(e.detail)}</span>`:""}</span>`,t.addEventListener("click",()=>{t.disabled||(c(),e.onSelect?.())}),n.appendChild(t),t.disabled||a.push(t)}const p=window.matchMedia("(max-width: 640px)").matches;if(document.body.appendChild(n),!p){n.classList.add("anchored");const e=o.getBoundingClientRect(),t=n.offsetWidth||260,i=n.offsetHeight||0,h=Math.min(Math.max(8,e.left),window.innerWidth-t-8),f=window.innerHeight-e.bottom>i+24?e.bottom+6:Math.max(8,e.top-i-6);n.style.left=`${Math.round(h)}px`,n.style.top=`${Math.round(f)}px`}o.setAttribute("aria-expanded","true"),a[0]?.focus();const d=e=>{if(e.key==="Escape"){e.stopPropagation(),c(),o.focus();return}if(e.key!=="ArrowDown"&&e.key!=="ArrowUp")return;e.preventDefault();const t=a.indexOf(document.activeElement),i=e.key==="ArrowDown"?1:-1;a[(t+i+a.length)%a.length]?.focus()},l=e=>{const t=e.target;t&&(n.contains(t)||o.contains(t))||c()};document.addEventListener("keydown",d,!0),document.addEventListener("pointerdown",l,!0),s={anchor:o,dispose:()=>{document.removeEventListener("keydown",d,!0),document.removeEventListener("pointerdown",l,!0),n.remove(),o.setAttribute("aria-expanded","false")}}}export{c as closeOverlayMenu,w as showOverlayMenu,v as toggleOverlayMenu};
|
|
@@ -1,34 +1,34 @@
|
|
|
1
|
-
import{initTerminal as
|
|
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 W=window.__TMUX_WEB_SHELL__;let f=null,u=null;const U=typeof window.__TMUX_WEB_SCOPE__?.agentId=="string"?window.__TMUX_WEB_SCOPE__.agentId:null;let h=U;window.__tmuxWebScopeAgent=U;let he="sessions",x="",ee="",te="",Te="";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="",T()):Bt()}let Le="";async function T(){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,yt(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")}),xe()}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}function mt(e){const t=document.createElement("div");t.className="session-item bot-item",t.setAttribute("data-bot-id",e.id),t.title=`Bot \xB7 ${e.projectPath}`;const n=e.status==="running"?"var(--panel-success)":e.status==="waiting_approval"||e.status==="waiting_input"?"#e0a23c":e.status==="failed"?"var(--panel-danger, #e5534b)":"var(--panel-muted)";return t.innerHTML=`${Q("bot",'class="bot-icon"')}<span>${p(e.title)}</span><span class="bot-status-dot" style="background:${n}"></span>`,t.addEventListener("click",s=>{s.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?gt(m,n,s):vt(m));for(const m of a.get(r)||[])Z.appendChild(mt(m));d.appendChild(I),d.appendChild(Z)}}function gt(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")||
|
|
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 vt(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")||
|
|
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 yt(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"+(U?" clickable":""),n.textContent=U?"\u2190 \u8FD4\u56DE\u672C\u673A":"\u672C\u673A",U&&(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",
|
|
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,Ut(e,t);const n=Ie(e,t);tt.set(n,Date.now()+Ot);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:W.terminal,scrollback:W.scrollback,theme:W.theme,wsBase:h?"/ws/a/"+encodeURIComponent(h):W.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,We=!1;function ht(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 bt(e){We=!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{We=!1}}function wt(){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")&&
|
|
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"),Ue=document.getElementById("git-diff-view"),ze=document.getElementById("gd-path"),ie=document.getElementById("gd-status"),oe=document.getElementById("gd-content"),Lt=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>',
|
|
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 Et(){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
|
|
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(),Et()){w.style.display="none",f&&(de(),f.destroy(),f=null,le=u,u=null),V(null),z.style.display="none",_.style.display="none",Ue.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();St(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>`,
|
|
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();kt(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 kt(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
|
-
</div><div class="diff-empty">No diff content available</div></div>`;return}const{html:s,lineCount:i}=
|
|
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=
|
|
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 St(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 Ct(){Ue.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"}Lt.addEventListener("click",Ct);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 Bt(){if(se=W.fsRoots||[],se.length===0){if(u){It(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 It(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){x=e,d.innerHTML='<div class="file-tree-empty">Loading...</div>';const t=bt(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&&(x=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+=wt();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=ht(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",()=>Tt(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 Tt(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,Te=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}Te=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",x&&M(x)}catch{E.textContent="Delete failed"}}),dt.addEventListener("click",()=>{z.style.display="none",_.style.display="flex",x&&M(x)}),pt.addEventListener("click",async()=>{const e=Me.value.trim();if(!e)return;const t=x+"/"+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="",x&&M(x)}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(),T()})),_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 nt}from"./terminal-core.js";import{initBots as st,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(),
|
|
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 Mt(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 Vt="";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",Mt(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(),T(),!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(),T()}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(),T()}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"),T()}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"),Ht=new Set(["up","down","left","right","tab","s-tab","space"]),Nt=400,$t=80;let K=0,me=0,ge=!1;function _t(){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;Ht.has(n)&&(ge=!1,K=setTimeout(()=>{K=0,ge=!0,me=setInterval(()=>{const s=Ze[n];s&&f&&f.sendInput(s)},$t)},Nt))});for(const e of["pointerup","pointercancel","pointerleave"])ue.addEventListener(e,_t);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"),Rt=document.getElementById("proc-close"),Ce=document.getElementById("proc-backdrop"),At=document.getElementById("header-ram");function Pt(){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 Dt(){Se.classList.add("open"),Ce.classList.add("open"),Pt()}function ve(){Se.classList.remove("open"),Ce.classList.remove("open")}At.addEventListener("click",e=>{e.stopPropagation(),Se.classList.contains("open")?ve():Dt()}),Rt.addEventListener("click",ve),Ce.addEventListener("click",ve);const jt=2e3;let X=null,Be=null;const j=new Map,O=new Map,Ot=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()+jt: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 xe(){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 Ut(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=T,T(),A(),xe(),nt(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&xe()}),setInterval(()=>{document.visibilityState==="visible"&&T()},1e4),ot();
|