baxian 1.2.15 → 1.2.17
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/agent/manager.d.ts +7 -0
- package/dist/agent/manager.d.ts.map +1 -1
- package/dist/agent/manager.js +291 -34
- package/dist/agent/manager.js.map +1 -1
- package/dist/agent/pane-streamer.d.ts.map +1 -1
- package/dist/agent/pane-streamer.js +1 -3
- package/dist/agent/pane-streamer.js.map +1 -1
- package/dist/agent/tmux.d.ts +1 -0
- package/dist/agent/tmux.d.ts.map +1 -1
- package/dist/agent/tmux.js +12 -5
- package/dist/agent/tmux.js.map +1 -1
- package/dist/web/assets/index-BgUL3TNI.css +1 -0
- package/dist/web/assets/index-CMT0Apmv.js +4 -0
- package/dist/web/index.html +2 -2
- package/package.json +3 -2
- package/dist/web/assets/index-BffCQxGl.js +0 -4
- package/dist/web/assets/index-C-2iqzvs.css +0 -1
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
var js=Object.defineProperty;var Ns=(t,s,n)=>s in t?js(t,s,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[s]=n;var ne=(t,s,n)=>Ns(t,typeof s!="symbol"?s+"":s,n);import{r as a,j as e,a as ks,c as Ss}from"./react-BFCkCmbU.js";import{x as Es,a as Cs}from"./xterm-D5X2JljJ.js";import{L as Me,u as ts,a as Rs,B as As,b as Ts,R as Is,c as et}from"./router-D24GsdXZ.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))o(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const l of i.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&o(l)}).observe(document,{childList:!0,subtree:!0});function n(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function o(r){if(r.ep)return;r.ep=!0;const i=n(r);fetch(r.href,i)}})();const Ps={"claude-code":"Claude Code",codex:"Codex"};function pt(t){return t?Ps[t]:null}function gt(t,s){const n=pt(s);return n?`${t} (${n})`:t}const ss=new Set(["merged","done","failed","cancelled"]),ns=new Set(["in_progress","review","fixing","approved","merge-ready","ready","max_rounds"]),tt=20,Ye=5*1024*1024,Fe=4,rs=600*1e3,$s=1536,Ds=1872,os=192,as=208,Re="/api",bt="baxian.token",Qe="baxian:unauthorized";function vt(){try{return typeof localStorage<"u"?localStorage.getItem(bt):null}catch{return null}}function Os(t){try{localStorage.setItem(bt,t)}catch(s){console.error("Failed to save auth token to localStorage",s)}}function Ms(){try{localStorage.removeItem(bt)}catch(t){console.error("Failed to clear auth token from localStorage",t)}}function ye(t){const s=vt();return{...t??{},...s?{Authorization:`Bearer ${s}`}:{}}}class Ce extends Error{constructor(s,n,o){super(n),this.status=s,this.details=o,this.name="ApiError"}}async function je(t){const s=await t.text();let n=s||`HTTP ${t.status}`,o;try{const r=JSON.parse(s);typeof r.error=="string"&&(n=r.error),Array.isArray(r.details)&&(o=r.details)}catch{}throw t.status===401&&typeof window<"u"&&window.dispatchEvent(new CustomEvent(Qe)),new Ce(t.status,n,o)}async function fe(t){const s=await fetch(`${Re}${t}`,{headers:ye()});return s.ok||await je(s),s.json()}async function Ls(){const t=await fetch("/health");return t.ok||await je(t),t.json()}async function ae(t,s,n){const o=s!==void 0,r=await fetch(`${Re}${t}`,{method:"POST",headers:o?ye({"Content-Type":"application/json"}):ye(),body:o?JSON.stringify(s):void 0,signal:n==null?void 0:n.signal});return r.ok||await je(r),r.json()}async function $t(t,s,n){const o=await fetch(`${Re}${t}`,{method:"PATCH",headers:ye({"Content-Type":"application/json"}),body:s?JSON.stringify(s):void 0,signal:n==null?void 0:n.signal});if(o.ok||await je(o),o.status===204)return;const r=await o.text();if(r)return JSON.parse(r)}async function _s(t,s){const n=await fetch(`${Re}${t}`,{method:"PUT",headers:ye({"Content-Type":"application/json"}),body:JSON.stringify(s??null)});if(n.ok||await je(n),n.status===204)return;const o=await n.text();if(o)return JSON.parse(o)}async function Te(t){const s=await fetch(`${Re}${t}`,{method:"DELETE",headers:ye()});if(s.ok||await je(s),s.status===204)return;const n=await s.text();if(n)return JSON.parse(n)}const X=encodeURIComponent;function ut(t){return new Promise((s,n)=>{const o=new FileReader;o.onerror=()=>n(o.error??new Error("file read failed")),o.onload=()=>{const r=o.result;if(typeof r!="string"){n(new Error("unexpected FileReader result"));return}const i=r.indexOf(",");s(i>=0?r.slice(i+1):r)},o.readAsDataURL(t)})}const $={agents:{list:()=>fe("/agents"),get:t=>fe(`/agents/${X(t)}`),stop:t=>Te(`/agents/${X(t)}/session`),compact:t=>ae(`/agents/${X(t)}/compact`),clear:t=>ae(`/agents/${X(t)}/clear`),probe:(t,s={},n)=>ae("/agents/probe",{mode:t,host:s.host,hostId:s.hostId},n),uploadImage:async(t,s)=>ae(`/agents/${X(t)}/images`,{dataBase64:await ut(s)}),setPet:(t,s)=>_s(`/agents/${X(t)}/pet`,{petId:s})},pets:{list:()=>fe("/pets"),create:async(t,s)=>ae("/pets",{petJson:t,spritesheetBase64:await ut(s)}),remove:t=>Te(`/pets/${X(t)}`),fetchSpritesheet:async t=>{const s=await fetch(`${Re}/pets/${X(t)}/spritesheet`,{headers:ye()});return s.ok||await je(s),s.blob()}},tasks:{list:async t=>{const s=new Map;for(const n of["active","pending"]){let o=0;for(;;){const r=await $.tasks.page(t,{category:n,offset:o});for(const i of r.tasks)s.set(i.id,i);if(!r.hasMore||r.tasks.length===0)break;o=r.nextOffset}}return[...s.values()]},page:(t,s={})=>{const n=[`projectId=${X(t)}`];return s.category&&n.push(`category=${s.category}`),n.push(`offset=${s.offset??0}`),fe(`/tasks?${n.join("&")}`)},get:t=>fe(`/tasks/${X(t)}`),create:t=>ae("/tasks",t),update:(t,s)=>$t(`/tasks/${X(t)}`,s),retry:t=>ae(`/tasks/${X(t)}/retry`),review:t=>ae(`/tasks/${X(t)}/review`),complete:t=>ae(`/tasks/${X(t)}/complete`),continue:t=>ae(`/tasks/${X(t)}/continue`),reviews:t=>fe(`/tasks/${X(t)}/reviews`),dispatch:(t,s)=>ae(`/tasks/${X(t)}/dispatch`,s)},projects:{list:()=>fe("/projects"),get:t=>fe(`/projects/${X(t)}`),create:t=>ae("/projects",t),delete:t=>Te(`/projects/${X(t)}`),addAgent:(t,s)=>ae(`/projects/${X(t)}/agents`,s),deleteAgent:(t,s)=>Te(`/projects/${X(t)}/agents/${X(s)}`),resumeAgent:(t,s)=>ae(`/projects/${X(t)}/agents/${X(s)}/resume`),bootstrap:t=>ae(`/projects/${X(t)}/bootstrap`)},hosts:{list:()=>fe("/hosts"),create:t=>ae("/hosts",t),update:(t,s)=>$t(`/hosts/${X(t)}`,s),delete:t=>Te(`/hosts/${X(t)}`),check:t=>ae("/hosts/check",t)},config:{get:()=>fe("/config")},health:{get:Ls},server:{restart:()=>ae("/restart")}},is=a.createContext(null),Fs={success:"border-[#bbf7d0] bg-[#f0fdf4] text-success",warn:"border-[#fde68a] bg-[#fef3c7] text-warn",error:"border-[#fecaca] bg-[#fef2f2] text-danger"},Bs={success:"✅",warn:"⚠️",error:"❌"};let Hs=1;function zs({children:t}){const[s,n]=a.useState([]),o=a.useCallback(i=>{n(l=>l.filter(u=>u.id!==i))},[]),r=a.useCallback(i=>{const l=Hs++,u=i.durationMs??3e3;n(h=>[...h,{...i,id:l}]),setTimeout(()=>o(l),u)},[o]);return e.jsxs(is.Provider,{value:{show:r},children:[t,e.jsx("div",{className:"pointer-events-none fixed inset-x-4 top-4 z-[60] flex flex-col items-end gap-2",children:s.map(i=>e.jsx("div",{className:`pointer-events-auto w-full max-w-xs rounded-lg border px-4 py-3 shadow-toast ${Fs[i.kind]}`,role:"status",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{"aria-hidden":!0,className:"text-[14px]",children:Bs[i.kind]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-[13px] font-semibold",children:i.title}),i.body&&e.jsx("div",{className:"mt-1 whitespace-pre-line text-[12px] text-og-700",children:i.body})]}),e.jsx("button",{type:"button",onClick:()=>o(i.id),className:"text-current opacity-50 transition-opacity hover:opacity-100","aria-label":"Dismiss",children:"✕"})]})},i.id))})]})}function he(){const t=a.useContext(is);if(!t)throw new Error("useToast must be inside <ToastProvider>");return t}const qe="baxian.pendingRestart",Us=500,Ws=3e4,cs=a.createContext(null);function Gs(){try{const t=localStorage.getItem(qe);if(!t)return{count:0,baselineStartedAt:null};const s=JSON.parse(t);return{count:typeof s.count=="number"?s.count:0,baselineStartedAt:typeof s.baselineStartedAt=="string"?s.baselineStartedAt:null}}catch{return{count:0,baselineStartedAt:null}}}function Qs(t){try{t.count<=0?localStorage.removeItem(qe):localStorage.setItem(qe,JSON.stringify(t))}catch{}}function qs({children:t}){const s=Gs(),[n,o]=a.useState(s.count),[r,i]=a.useState(s.baselineStartedAt),[l,u]=a.useState(s.count>0?"pending":"idle"),[h,x]=a.useState(),v=a.useRef(s.count),p=a.useRef(s.count>0?"pending":"idle"),d=a.useRef(0),y=a.useCallback(f=>{v.current=f,o(f)},[]),A=a.useCallback(f=>{o(N=>{const w=f(N);return v.current=w,w})},[]),m=a.useCallback(f=>{p.current=f,u(f)},[]);a.useEffect(()=>{Qs({count:n,baselineStartedAt:r})},[n,r]),a.useEffect(()=>{let f=!1;(async()=>{try{const w=await $.health.get();if(f)return;i(c=>c!==null&&w.startedAt!==c?(y(0),m("idle"),null):c)}catch{}})();const N=w=>{if(w.key===qe){if(w.newValue===null){if(p.current==="restarting"&&d.current>0){y(d.current),i(null);return}y(0),i(null),p.current!=="restarting"&&m("idle");return}try{const c=JSON.parse(w.newValue);typeof c.count=="number"&&(p.current==="restarting"&&c.count>v.current&&(d.current+=c.count-v.current),y(c.count),p.current!=="restarting"&&m(c.count>0?"pending":"idle")),typeof c.baselineStartedAt=="string"?i(c.baselineStartedAt):c.baselineStartedAt===null&&i(null)}catch{}}};return window.addEventListener("storage",N),()=>{f=!0,window.removeEventListener("storage",N)}},[y,m]);const b=a.useRef(!1),S=a.useCallback(()=>{A(f=>f+1),p.current==="restarting"?d.current+=1:m("pending"),i(f=>(f!==null||b.current||(b.current=!0,(async()=>{try{const N=await $.health.get();i(w=>w??N.startedAt)}catch{}finally{b.current=!1}})()),f))},[m,A]),M=a.useCallback(async()=>{d.current=0,x(void 0),m("restarting");let f;try{f=(await $.health.get()).startedAt}catch(w){m("failed"),x(`获取重启前 startedAt 失败: ${w instanceof Error?w.message:String(w)}`);return}try{await $.server.restart()}catch(w){if(!(w instanceof Ce&&w.status===409)){m("failed"),x(`触发重启失败: ${w instanceof Error?w.message:String(w)}`);return}}const N=Date.now();for(;Date.now()-N<Ws;){await new Promise(w=>setTimeout(w,Us));try{const w=await $.health.get();if(w.startedAt!==f){const c=d.current;d.current=0,i(c>0?w.startedAt:null),y(c),m(c>0?"pending":"idle");return}}catch{}}m("failed"),x("重启超时(30s 未恢复)。请检查日志或手动 baxian start -c <path>")},[y,m]);return e.jsx(cs.Provider,{value:{phase:l,count:n,error:h,flagDirty:S,triggerRestart:M},children:t})}function Xe(){const t=a.useContext(cs);if(!t)throw new Error("usePendingRestart must be used inside PendingRestartProvider");return t}const Ks=[500,1e3,2e3,4e3,8e3,15e3,3e4];class ls{constructor(s){ne(this,"attempts",0);ne(this,"timer",null);ne(this,"delaysMs");this.opts=s,this.delaysMs=s.delaysMs??Ks}schedule(){if(this.timer||!this.shouldReconnect())return;const s=this.delaysMs[Math.min(this.attempts,this.delaysMs.length-1)];this.attempts+=1,this.timer=setTimeout(()=>{this.timer=null,this.shouldReconnect()&&this.opts.reconnect()},s)}cancel(){this.timer&&(clearTimeout(this.timer),this.timer=null)}reset(){this.attempts=0}shouldReconnect(){return this.opts.shouldReconnect?this.opts.shouldReconnect():!0}}let Dt=0;function Vs(){Dt++;const t=Math.random().toString(36).slice(2,8);return`sub-${Date.now().toString(36)}-${Dt}-${t}`}function Js(t){return Array.from(new TextEncoder().encode(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}function Ys(){return`${location.protocol==="https:"?"wss":"ws"}://${location.host}/api/stream`}const Xs=(t,s)=>s&&s.length>0?new WebSocket(t,s):new WebSocket(t);class Zs{constructor(s={}){ne(this,"wsUrl");ne(this,"wsFactory");ne(this,"tokenProvider");ne(this,"ws",null);ne(this,"subs",new Map);ne(this,"snapshotPending",new Set);ne(this,"preSubscribeQueue",new Map);ne(this,"outbox",[]);ne(this,"reconnectScheduler");ne(this,"explicitlyClosed",!1);this.wsUrl=s.wsUrl??Ys(),this.wsFactory=s.wsFactory??Xs,this.tokenProvider=s.tokenProvider??vt,this.reconnectScheduler=new ls({reconnect:()=>this.openSocket(),shouldReconnect:()=>!this.explicitlyClosed&&this.subs.size>0})}subscribe(s){const n=Vs(),o={subscriberId:n,agentId:s.agentId,mode:s.mode,onSnapshot:s.onSnapshot,onData:s.onData,onError:s.onError,onSessionGone:s.onSessionGone};return this.subs.set(n,o),this.snapshotPending.add(n),this.preSubscribeQueue.set(n,[]),this.ensureSocket(),this.wsSendOrQueue({op:"subscribe",subscriberId:n,agentId:s.agentId,mode:s.mode}),{subscriberId:n,unsubscribe:()=>this.unsubscribe(n)}}send(s,n){if(this.subs.has(s)){if(this.snapshotPending.has(s)){this.outbox.push({op:"input",subscriberId:s,data:n});return}this.wsSendOrQueue({op:"input",subscriberId:s,data:n})}}resize(s,n,o){const r=this.subs.get(s);r&&(r.lastSize={cols:n,rows:o},!this.snapshotPending.has(s)&&this.wsSendOrQueue({op:"resize",subscriberId:s,cols:n,rows:o}))}ping(){this.wsSendOrQueue({op:"ping"})}close(){if(this.explicitlyClosed=!0,this.reconnectScheduler.cancel(),this.reconnectScheduler.reset(),this.ws){try{this.ws.close()}catch{}this.ws=null}this.subs.clear(),this.snapshotPending.clear(),this.preSubscribeQueue.clear(),this.outbox=[]}unsubscribe(s){this.subs.has(s)&&(this.subs.delete(s),this.snapshotPending.delete(s),this.preSubscribeQueue.delete(s),this.wsSendOrQueue({op:"unsubscribe",subscriberId:s}),this.subs.size===0&&this.teardownSocket())}teardownSocket(){if(this.reconnectScheduler.cancel(),this.reconnectScheduler.reset(),this.outbox=[],this.ws){try{this.ws.close()}catch{}this.ws=null}}ensureSocket(){this.explicitlyClosed||this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING)||this.openSocket()}openSocket(){if(this.explicitlyClosed)return;this.reconnectScheduler.cancel();const s=this.tokenProvider(),n=s?[`baxian.token.${Js(s)}`]:void 0;let o;try{o=this.wsFactory(this.wsUrl,n)}catch(r){console.warn("[pane-stream] WebSocket constructor threw:",r),this.scheduleReconnect();return}this.ws=o,o.onopen=()=>{if(o!==this.ws)return;this.reconnectScheduler.reset();for(const i of this.subs.values()){this.snapshotPending.add(i.subscriberId),this.preSubscribeQueue.set(i.subscriberId,[]),i.snapshotSeq=void 0;try{o.send(JSON.stringify({op:"subscribe",subscriberId:i.subscriberId,agentId:i.agentId,mode:i.mode}))}catch(l){console.warn("[pane-stream] resubscribe send failed:",l)}}const r=this.outbox;this.outbox=[];for(const i of r)if(i.op!=="subscribe"){if("subscriberId"in i&&i.subscriberId){if(!this.subs.has(i.subscriberId))continue;if(this.snapshotPending.has(i.subscriberId)&&i.op!=="unsubscribe"){this.outbox.push(i);continue}}try{o.send(JSON.stringify(i))}catch(l){console.warn("[pane-stream] outbox flush failed:",l)}}},o.onmessage=r=>{if(o!==this.ws)return;let i;try{const l=typeof r.data=="string"?r.data:String(r.data);i=JSON.parse(l)}catch{return}this.handleMessage(i)},o.onclose=()=>{o===this.ws&&(this.ws=null,!this.explicitlyClosed&&this.subs.size!==0&&this.scheduleReconnect())},o.onerror=()=>{}}scheduleReconnect(){this.reconnectScheduler.schedule()}wsSendOrQueue(s){if(this.ws&&this.ws.readyState===WebSocket.OPEN)try{this.ws.send(JSON.stringify(s));return}catch(n){console.warn("[pane-stream] send failed, will queue:",n)}this.outbox.push(s)}handleMessage(s){var n,o;switch(s.type){case"snapshot":this.handleSnapshot(s);break;case"subscribed":this.handleSubscribed(s);break;case"data":this.dispatch(s);break;case"session_gone":for(const r of[...this.subs.values()])r.agentId===s.agentId&&((n=r.onSessionGone)==null||n.call(r));break;case"error":{if(s.subscriberId){const r=this.subs.get(s.subscriberId);(o=r==null?void 0:r.onError)==null||o.call(r,{code:s.code,message:s.message})}else console.warn("[pane-stream] connection-level error:",s.code,s.message);break}}}handleSnapshot(s){const n=this.subs.get(s.subscriberId);n&&n.onSnapshot({cols:s.cols,rows:s.rows,data:s.data})}handleSubscribed(s){const n=this.subs.get(s.subscriberId);if(!n)return;n.snapshotSeq=s.snapshotSeq,n.lastSize||(n.lastSize={cols:s.cols,rows:s.rows}),this.snapshotPending.delete(s.subscriberId);const o=this.preSubscribeQueue.get(s.subscriberId);if(this.preSubscribeQueue.delete(s.subscriberId),o)for(const r of o)r.seq>s.snapshotSeq&&n.onData(r.data);n.mode==="full"&&n.lastSize&&this.wsSendOrQueue({op:"resize",subscriberId:n.subscriberId,cols:n.lastSize.cols,rows:n.lastSize.rows}),this.flushOutboxForSub(s.subscriberId)}flushOutboxForSub(s){if(this.outbox.length===0||!this.ws||this.ws.readyState!==WebSocket.OPEN)return;const n=[];for(const o of this.outbox)if("subscriberId"in o&&o.subscriberId===s&&o.op!=="subscribe")try{this.ws.send(JSON.stringify(o))}catch(r){console.warn("[pane-stream] flushOutboxForSub send failed:",r)}else n.push(o);this.outbox=n}dispatch(s){for(const n of this.subs.values())if(n.agentId===s.agentId)if(this.snapshotPending.has(n.subscriberId)){const o=this.preSubscribeQueue.get(n.subscriberId);o&&o.push({seq:s.seq,data:s.data})}else n.onData(s.data)}}let st=null;function nt(){return st||(st=new Zs),st}function en(t){const{agentId:s,mode:n}=t,o=a.useRef(null),r=a.useRef({onSnapshot:t.onSnapshot,onData:t.onData,onError:t.onError,onSessionGone:t.onSessionGone});r.current={onSnapshot:t.onSnapshot,onData:t.onData,onError:t.onError,onSessionGone:t.onSessionGone},a.useEffect(()=>{const h=nt().subscribe({agentId:s,mode:n,onSnapshot:x=>r.current.onSnapshot(x),onData:x=>r.current.onData(x),onError:x=>{var v,p;return(p=(v=r.current).onError)==null?void 0:p.call(v,x)},onSessionGone:()=>{var x,v;return(v=(x=r.current).onSessionGone)==null?void 0:v.call(x)}});return o.current=h.subscriberId,()=>{o.current=null,h.unsubscribe()}},[s,n]);const i=a.useCallback(u=>{const h=o.current;h&&nt().send(h,u)},[]),l=a.useCallback((u,h)=>{const x=o.current;x&&nt().resize(x,u,h)},[]);return{send:i,resize:l}}const tn=[{key:"up",label:"上",path:"M12 5l-6 6m6-6l6 6m-6-6v14"},{key:"down",label:"下",path:"M12 19l6-6m-6 6l-6-6m6 6V5"},{key:"left",label:"左",path:"M5 12l6-6m-6 6l6 6m-6-6h14"},{key:"right",label:"右",path:"M19 12l-6-6m6 6l-6 6m6-6H5"}],Be=Object.fromEntries(tn.map(t=>[t.key,t]));function He({arrow:t,onPress:s}){return e.jsx("button",{type:"button","aria-label":`方向键 ${t.label}`,"data-arrow":t.key,onMouseDown:n=>n.preventDefault(),onClick:()=>s(t.key),className:"flex h-8 w-8 items-center justify-center rounded border border-hairline bg-surface text-og-700 transition-colors hover:bg-og-100 hover:text-og-1000 active:bg-og-200",children:e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:e.jsx("path",{d:t.path})})})}function sn({onKey:t,className:s}){return e.jsxs("div",{role:"group","aria-label":"终端方向键",className:s??"flex flex-none items-center justify-center gap-1 border-t border-hairline bg-page px-3 py-2",children:[e.jsx(He,{arrow:Be.left,onPress:t}),e.jsx(He,{arrow:Be.up,onPress:t}),e.jsx(He,{arrow:Be.down,onPress:t}),e.jsx(He,{arrow:Be.right,onPress:t})]})}const nn=Math.floor(Ye/1024/1024);function rn({agentId:t,className:s}){const n=a.useRef(null),[o,r]=a.useState(!1),{show:i}=he(),l=async u=>{var x;const h=(x=u.target.files)==null?void 0:x[0];if(u.target.value="",!!h){if(h.size>Ye){i({kind:"error",title:"图片过大",body:`单张图片不能超过 ${nn} MiB`});return}r(!0);try{await $.agents.uploadImage(t,h),i({kind:"success",title:"图片已插入",body:"路径已粘贴到终端输入,补充说明后回车"})}catch(v){const p=v instanceof Ce||v instanceof Error?v.message:String(v);i({kind:"error",title:"图片上传失败",body:p})}finally{r(!1)}}};return e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button","aria-label":"上传图片",disabled:o,onMouseDown:u=>u.preventDefault(),onClick:()=>{var u;return(u=n.current)==null?void 0:u.click()},className:s??"flex h-8 w-8 items-center justify-center rounded border border-hairline bg-surface text-og-700 transition-colors hover:bg-og-100 hover:text-og-1000 active:bg-og-200 disabled:cursor-not-allowed disabled:opacity-50",children:e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),e.jsx("circle",{cx:"9",cy:"9",r:"2"}),e.jsx("path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"})]})}),e.jsx("input",{ref:n,type:"file",accept:"image/*",className:"hidden",onChange:l})]})}const on={up:"A",down:"B",right:"C",left:"D"};function an(t,s){return(s?"\x1BO":"\x1B[")+on[t]}const Ot=18,cn=250,ln=256*1024,Mt="#fdfdfd",dn='ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',un={background:Mt,foreground:"#474c55",cursor:"#1348dc",cursorAccent:Mt,selectionBackground:"#eaf0ff",black:"#0d0d0f",red:"#b91c1c",green:"#15803d",yellow:"#b45309",blue:"#1348dc",magenta:"#9333ea",cyan:"#0e7490",white:"#474c55",brightBlack:"#878e9b",brightRed:"#dc2626",brightGreen:"#16a34a",brightYellow:"#d97706",brightBlue:"#3080ff",brightMagenta:"#a855f7",brightCyan:"#0891b2",brightWhite:"#0d0d0f"},fn=/\x1b\[(?:\?[\d;]*c|>[\d;]*c|\??\d+;\d+R|\d+n)/g;function hn(t){return t.replace(fn,"")}const mn=1024*1024;function xn(t){const s=t.indexOf(";");if(s===-1)return null;const n=t.slice(s+1);if(n.length===0||n==="?"||n.length>mn)return null;try{const o=atob(n),r=new Uint8Array(o.length);for(let i=0;i<o.length;i++)r[i]=o.charCodeAt(i);return new TextDecoder().decode(r)}catch{return null}}function De({agentId:t,mode:s,interactive:n=!1,maxLines:o,className:r,autoFocus:i=!0,deferFullUntilFocus:l=!1,arrowKeys:u=!1}){const h=a.useRef(null),x=a.useRef(null),v=a.useRef(null),p=a.useRef(null),d=a.useRef(!1),y=a.useRef(""),A=a.useRef([]),m=a.useRef(0),b=a.useRef(null),S=a.useRef(null),M=a.useRef(null),f=a.useRef(Promise.resolve()),N=a.useRef(0),[w,c]=a.useState(null),[W,K]=a.useState(!1),P=`${t}\0${s}\0${l?"1":"0"}`,[L,E]=a.useState({key:P,active:!1}),I=L.key===P&&L.active,z=s==="full"&&l,U=z&&!I?"preview":s,_=n&&U==="full",F=(k,B)=>B.length===0?Promise.resolve():new Promise(D=>{try{k.write(B,()=>D())}catch(ie){console.warn("[pane-terminal] write failed:",ie),D()}}),G=U==="preview",oe=()=>{if(!G)return;const k=h.current,B=x.current;if(!k||!B||k.clientHeight<=0)return;const ie=(B.buffer.active.cursorY+1)*Ot;k.scrollTop=Math.max(0,ie-k.clientHeight)},j=()=>{if(!G||M.current!==null)return;let k=!1;const B=requestAnimationFrame(()=>{k=!0,M.current=null,oe()});k||(M.current=B)},g=(k,B)=>{f.current=f.current.then(async()=>{const D=x.current;if(!(!D||B!==N.current))try{await k(D),_&&D.scrollToBottom(),j()}catch(ie){console.warn("[pane-terminal] terminal task failed:",ie)}}).catch(D=>{console.warn("[pane-terminal] write chain failed:",D)})},q=(k,B)=>{g(D=>F(D,k),B)},J=()=>{b.current!==null&&(cancelAnimationFrame(b.current),b.current=null),S.current!==null&&(clearTimeout(S.current),S.current=null)},V=()=>{J(),A.current=[],m.current=0},ee=()=>{J();const k=A.current;k.length!==0&&(A.current=[],m.current=0,q(k.join(""),N.current))},R=k=>{if(k.length!==0){if(A.current.push(k),m.current+=k.length,m.current>=ln){ee();return}b.current===null&&(b.current=requestAnimationFrame(ee)),S.current===null&&(S.current=setTimeout(ee,cn))}},{send:Q,resize:Y}=en({agentId:t,mode:U,onSnapshot:({cols:k,rows:B,data:D})=>{if(x.current)try{const le=N.current+1;N.current=le,V(),g(async de=>{var C;de.reset(),_?((C=p.current)==null||C.call(p),await F(de,D)):(k>0&&B>0&&de.resize(k,B),await F(de,D))},le)}catch(le){console.warn("[pane-terminal] snapshot write failed:",le)}},onData:k=>{R(k)},onError:k=>c(`${k.code}: ${k.message}`),onSessionGone:()=>K(!0)});a.useEffect(()=>{c(null),K(!1)},[t,U]),a.useEffect(()=>{y.current=""},[P]),a.useEffect(()=>{if(U!=="full")return;const k=y.current;k.length!==0&&(y.current="",Q(k))},[Q,U]);const ce=a.useCallback(()=>{!n||!z||I||(d.current=!0,E({key:P,active:!0}))},[P,I,n,z]),O=a.useCallback(k=>{const B=hn(k);if(B.length!==0){if(z&&(!I||y.current.length>0)){y.current+=B,ce();return}Q(B)}},[ce,I,Q,z]);a.useEffect(()=>{const k=h.current;if(!k)return;let B=!1;const D=new Es.Terminal({cursorBlink:n,disableStdin:!n,theme:un,fontFamily:dn,fontSize:13,lineHeight:1.4,scrollback:U==="full"?5e3:1e3}),ie=new Cs.FitAddon;D.loadAddon(ie),D.open(k),x.current=D,v.current=ie;const le=G?D.onRender(()=>j()):null;if(n&&(i||d.current)){d.current=!1;try{D.focus()}catch{}}n&&(D.onData(O),U==="full"&&D.parser.registerOscHandler(52,we=>{var ke;const Ne=xn(we);return Ne!==null&&((ke=navigator.clipboard)==null||ke.writeText(Ne).catch(()=>{})),!0}));const de=()=>k.clientWidth>0&&k.clientHeight>0,C=(we=!1)=>{if(!de())return!1;const Ne=D.cols,ke=D.rows;try{ie.fit()}catch{return!1}return _&&D.scrollToBottom(),D.cols>0&&D.rows>0&&(we||D.cols!==Ne||D.rows!==ke)&&Y(D.cols,D.rows),!0};p.current=_?()=>C(!0):null;let H=null,re=null,Z=null,ue=0;const me=()=>{H||(H=new ResizeObserver(()=>{re&&clearTimeout(re),re=setTimeout(()=>{re=null,_?C():G&&j()},100)}),H.observe(k))},_e=()=>{Z=requestAnimationFrame(()=>{if(Z=null,!B){if(!_){G&&(me(),j());return}if(C(!0)){me();return}if(ue++<5){_e();return}me()}})};return _e(),()=>{B=!0,Z!==null&&cancelAnimationFrame(Z),b.current!==null&&(cancelAnimationFrame(b.current),b.current=null),S.current!==null&&(clearTimeout(S.current),S.current=null),M.current!==null&&(cancelAnimationFrame(M.current),M.current=null),N.current++,A.current=[],m.current=0,f.current=Promise.resolve(),re&&clearTimeout(re),H==null||H.disconnect(),le==null||le.dispose(),x.current=null,v.current=null,p.current=null;try{D.dispose()}catch(we){console.warn("[pane-terminal] dispose failed:",we)}}},[t,i,_,O,n,U,Y]);const te=()=>{var k;if(n){ce();try{(k=x.current)==null||k.focus()}catch{}}};a.useEffect(()=>{if(n)return;const k=h.current;if(!k)return;const B=D=>{D.stopPropagation()};return k.addEventListener("wheel",B,{capture:!0,passive:!0}),()=>k.removeEventListener("wheel",B,{capture:!0})},[n]);const se=o&&o>0?{maxHeight:`${o*Ot}px`}:void 0;return e.jsxs("div",{className:r??"flex flex-col h-full w-full min-h-0 bg-[#fdfdfd]",children:[(w||W)&&e.jsx("div",{className:"border-b border-[#fecaca] bg-[#fef2f2] px-3 py-1 font-mono text-[11px] text-danger",children:W?"session ended":w}),e.jsx("div",{className:"flex flex-1 min-h-0 px-2 py-1.5",style:se,children:e.jsx("div",{ref:h,className:"flex-1 min-h-0 overflow-hidden",onMouseDown:te})}),n&&u&&e.jsxs("div",{className:"grid grid-cols-[1fr_auto_1fr] gap-2 flex-none items-center border-t border-hairline bg-page px-3 py-2",children:[e.jsx("div",{className:"flex items-center",children:e.jsx(rn,{agentId:t})}),e.jsx(sn,{className:"flex items-center justify-center gap-1",onKey:k=>{var D,ie;const B=!!((ie=(D=x.current)==null?void 0:D.modes)!=null&&ie.applicationCursorKeysMode);O(an(k,B))}})]})]})}function pn(){const[t,s]=a.useState([]),[n,o]=a.useState(!0),[r,i]=a.useState(null),l=a.useCallback(async()=>{o(!0);try{s(await $.pets.list()),i(null)}catch(u){i(u instanceof Error?u.message:String(u))}finally{o(!1)}},[]);return a.useEffect(()=>{l()},[l]),{pets:t,loading:n,error:r,refresh:l}}const rt=new Map,ot=new Map;function gn(t){const[s,n]=a.useState(()=>t?ot.get(t)??null:null);return a.useEffect(()=>{if(!t){n(null);return}const o=ot.get(t);if(n(o??null),o)return;let r=!1,i=rt.get(t);return i||(i=$.pets.fetchSpritesheet(t).then(l=>{const u=URL.createObjectURL(l);return ot.set(t,u),u}),rt.set(t,i)),i.then(l=>{r||n(l)},()=>{r||n(null),rt.delete(t)}),()=>{r=!0}},[t]),s}const bn=[{state:"idle",row:0,durations:[280,110,110,140,140,320]},{state:"running-right",row:1,durations:[120,120,120,120,120,120,120,220]},{state:"running-left",row:2,durations:[120,120,120,120,120,120,120,220]},{state:"waving",row:3,durations:[140,140,140,280]},{state:"jumping",row:4,durations:[140,140,140,140,280]},{state:"failed",row:5,durations:[140,140,140,140,140,140,140,240]},{state:"waiting",row:6,durations:[150,150,150,150,150,260]},{state:"running",row:7,durations:[120,120,120,120,120,220]},{state:"review",row:8,durations:[150,150,150,150,150,280]}];function vn(t,s){if(s)return 3;switch(t){case"working":return 7;case"waiting":return 6;case"pending":return 6;case"error":return 5;case"idle":return 0;case"unknown":return 0;default:return 0}}const wt=36,wn=wt/as,yn=os*wn;function jn(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function ds({petId:t,status:s,bootstrapping:n=!1,label:o,displayHeight:r=wt,className:i}){const l=gn(t),u=vn(s,n),h=bn[u],x=h.durations.length,[v,p]=a.useState(0),d=r/as,y=os*d;return a.useEffect(()=>{if(p(0),!l||x<=1||jn())return;let A,m=0;const b=()=>{m=(m+1)%x,p(m),A=setTimeout(b,h.durations[m])};return A=setTimeout(b,h.durations[0]),()=>clearTimeout(A)},[l,u,x,h]),l?e.jsx("span",{role:"img","aria-label":o,title:o,"data-pet-row":u,"data-pet-col":v,className:["inline-block shrink-0",i].filter(Boolean).join(" "),style:{width:`${y}px`,height:`${r}px`,backgroundImage:`url(${l})`,backgroundRepeat:"no-repeat",backgroundSize:`${$s*d}px ${Ds*d}px`,backgroundPositionX:`${-(v*y)}px`,backgroundPositionY:`${-(u*r)}px`,imageRendering:"pixelated"}}):e.jsx("span",{className:"pill pill-idle",title:o,children:o})}const Nn={sm:"max-w-md",md:"max-w-lg",lg:"max-w-2xl"},Lt='input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), [href], [tabindex]:not([tabindex="-1"])';function ve({open:t,onClose:s,title:n,titleContent:o,children:r,footer:i,size:l="md",dismissOnBackdrop:u=!0}){const h=a.useRef(null),x=a.useRef(null),v=a.useRef(!1),p=a.useRef(s);return a.useEffect(()=>{p.current=s},[s]),a.useEffect(()=>{if(!t)return;x.current=document.activeElement;const d=m=>{if(m.key==="Escape"){p.current();return}if(m.key!=="Tab")return;const b=h.current;if(!b)return;const S=Array.from(b.querySelectorAll(Lt)).filter(w=>w.offsetParent!==null||w===document.activeElement);if(S.length===0){m.preventDefault();return}const M=S[0],f=S[S.length-1],N=document.activeElement;m.shiftKey&&(N===M||!b.contains(N))?(m.preventDefault(),f.focus()):!m.shiftKey&&(N===f||!b.contains(N))&&(m.preventDefault(),M.focus())};document.addEventListener("keydown",d);const y=document.body.style.overflow;document.body.style.overflow="hidden";const A=h.current;if(A){const m=A.querySelector(Lt);m==null||m.focus()}return()=>{var m,b;document.removeEventListener("keydown",d),document.body.style.overflow=y,(b=(m=x.current)==null?void 0:m.focus)==null||b.call(m)}},[t]),t?e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-og-1000/45 px-3 sm:px-4",onMouseDown:u?d=>{v.current=d.target===d.currentTarget}:void 0,onClick:u?d=>{d.target===d.currentTarget&&v.current&&p.current()}:void 0,role:"presentation",children:e.jsxs("div",{ref:h,className:`flex w-full ${Nn[l]} max-h-[90dvh] flex-col overflow-hidden rounded-lg border border-og-100 bg-surface shadow-modal`,onClick:d=>d.stopPropagation(),role:"dialog","aria-modal":"true","aria-label":n,children:[e.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-hairline px-5 py-3",children:[e.jsx("h2",{title:n,className:"min-w-0 truncate font-display text-[15px] font-semibold tracking-tight text-og-1000",children:o??n}),e.jsx("button",{type:"button",onClick:()=>p.current(),className:"-mr-1 flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-og-400 transition-colors hover:bg-og-50 hover:text-og-800","aria-label":"Close",children:"✕"})]}),e.jsx("div",{className:"min-h-0 flex-1 overflow-auto px-5 py-4",children:r}),i&&e.jsx("div",{className:"flex shrink-0 flex-wrap items-center justify-end gap-2 border-t border-hairline px-5 py-3",children:i})]})}):null}class Ge extends Error{constructor(s){super(s),this.name="PetPackageError"}}const ze=t=>t.split("/").pop()??t;function kn(t){return typeof t.text=="function"?t.text():new Promise((s,n)=>{const o=new FileReader;o.onerror=()=>n(o.error??new Error("file read failed")),o.onload=()=>s(typeof o.result=="string"?o.result:""),o.readAsText(t)})}async function Sn(t){const s=t.find(l=>ze(l.name)==="pet.json"||ze(l.webkitRelativePath||"")==="pet.json");if(!s)throw new Ge("文件包中未找到 pet.json");let n;try{n=JSON.parse(await kn(s))}catch{throw new Ge("pet.json 解析失败")}const o=n&&typeof n=="object"&&typeof n.spritesheetPath=="string"?n.spritesheetPath:"",r=o?ze(o):"",i=(r?t.find(l=>ze(l.name)===r):void 0)??t.find(l=>/\.(png|webp)$/i.test(l.name));if(!i)throw new Ge("文件包中未找到精灵图(png/webp)");return{manifest:n,spritesheet:i}}function En({children:t,style:s}){const n=a.useRef(null),[o,r]=a.useState(typeof IntersectionObserver>"u");return a.useEffect(()=>{if(o||typeof IntersectionObserver>"u")return;const i=n.current;if(!i)return;const l=new IntersectionObserver(u=>{u.some(h=>h.isIntersecting)&&(r(!0),l.disconnect())});return l.observe(i),()=>l.disconnect()},[o]),e.jsx("span",{ref:n,className:"inline-block shrink-0",style:s,children:o?t:null})}function Cn({agentId:t,currentPetId:s,onClose:n}){const{show:o}=he(),{pets:r,loading:i,refresh:l}=pn(),[u,h]=a.useState(!!s),[x,v]=a.useState(s),[p,d]=a.useState(!1),y=a.useRef(null);a.useEffect(()=>{v(s)},[s]),a.useEffect(()=>{const f=y.current;f&&(f.setAttribute("webkitdirectory",""),f.setAttribute("directory",""))},[u]);const A=f=>f instanceof Ce||f instanceof Error?f.message:String(f),m=async f=>{if(h(f),!f&&x){d(!0);try{await $.agents.setPet(t,null),v(null),o({kind:"success",title:"已关闭 Agent Pet"})}catch(N){o({kind:"error",title:"关闭失败",body:A(N)}),h(!0)}finally{d(!1)}}},b=async f=>{d(!0);try{await $.agents.setPet(t,f),v(f),o({kind:"success",title:"已选择 Pet"})}catch(N){o({kind:"error",title:"选择失败",body:A(N)})}finally{d(!1)}},S=async(f,N)=>{if(window.confirm(`确认删除 Pet「${N}」?使用它的 Agent 会回到默认状态显示。`)){d(!0);try{await $.pets.remove(f),await l(),o({kind:"success",title:`Pet「${N}」已删除`})}catch(w){o({kind:"error",title:"删除失败",body:A(w)})}finally{d(!1)}}},M=async f=>{const N=f.target.files?Array.from(f.target.files):[];if(f.target.value="",!!N.length){d(!0);try{const{manifest:w,spritesheet:c}=await Sn(N);await $.pets.create(w,c),await l(),o({kind:"success",title:"Pet 上传成功"})}catch(w){const c=w instanceof Ge?w.message:A(w);o({kind:"error",title:"Pet 上传失败",body:c})}finally{d(!1)}}};return e.jsx(ve,{open:!0,onClose:n,title:"Agent Pet",size:"md",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("label",{className:"flex items-center gap-2 text-[13px] text-og-1000",children:[e.jsx("input",{type:"checkbox",checked:u,disabled:p,onChange:f=>void m(f.target.checked)}),"启用 Agent Pet"]}),u?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("button",{type:"button",onClick:()=>{var f;return(f=y.current)==null?void 0:f.click()},disabled:p,className:"btn-secondary",children:"上传 Pet 文件包"}),e.jsx("input",{ref:y,type:"file","aria-label":"上传 Codex Pet 文件包",className:"hidden",onChange:f=>void M(f)}),e.jsx("p",{className:"mt-1 text-[12px] text-og-400",children:"选择 Codex Pet 目录(含 pet.json 与精灵图)。"})]}),i?e.jsx("p",{className:"text-[13px] text-og-500",children:"加载中…"}):r.length===0?e.jsx("p",{className:"text-[13px] text-og-500",children:"还没有上传过 Pet,点击上方按钮上传。"}):e.jsx("ul",{className:"grid grid-cols-2 gap-2",children:r.map(f=>{const N=f.id===x;return e.jsxs("li",{className:`flex items-center gap-2 rounded-md border p-2 ${N?"border-accent bg-accent-soft/40":"border-hairline"}`,children:[e.jsx(En,{style:{width:`${yn}px`,height:`${wt}px`},children:e.jsx(ds,{petId:f.id,status:"idle",label:f.displayName})}),e.jsxs("button",{type:"button",onClick:()=>void b(f.id),disabled:p||N,title:f.description||f.displayName,className:"min-w-0 flex-1 truncate text-left text-[13px] text-og-1000 hover:text-accent-hover disabled:cursor-default",children:[f.displayName,N&&e.jsx("span",{className:"ml-1 text-[11px] text-accent",children:"(当前)"})]}),e.jsx("button",{type:"button","aria-label":`删除 ${f.displayName}`,onClick:()=>void S(f.id,f.displayName),disabled:p,className:"shrink-0 text-[12px] text-danger hover:underline disabled:opacity-50",children:"删除"})]},f.id)})})]}):e.jsx("p",{className:"text-[12px] text-og-500",children:"开启后可上传 Codex Pet 文件包,或选择已上传过的 Pet 替换 Agent 卡片上的状态显示。"})]})})}const Rn={unknown:{label:"Unknown",cls:"pill pill-idle"},idle:{label:"Idle",cls:"pill pill-idle"},pending:{label:"Pending user",cls:"pill pill-warn"},working:{label:"Working",cls:"pill pill-live"},waiting:{label:"Waiting",cls:"pill pill-review"},error:{label:"Error",cls:"pill pill-warn"}},An=72,Tn={absent:{label:"No session",modifier:"status-dot--warn"},unreachable:{label:"Host unreachable",modifier:"status-dot--danger"},unknown:{label:"Session unknown",modifier:"status-dot--warn"},starting:{label:"Starting session",modifier:"status-dot--info"}};function In({state:t}){if(t==="present")return null;const{label:s,modifier:n}=Tn[t];return e.jsx("span",{role:"img","aria-label":s,title:s,className:`status-dot ml-2 ${n}`})}function Pn({agent:t,projectId:s,role:n,runtime:o,onDeleted:r,pendingRestart:i=!1,terminalLoading:l=!1,showTaskBinding:u=!0,terminalMode:h="activity-preview",active:x,onActivate:v}){var kt,St,Et,Ct,Rt,At,Tt;const[p,d]=a.useState(!1),[y,A]=a.useState(null),{show:m}=he(),{flagDirty:b}=Xe(),[S,M]=a.useState(!1),[f,N]=a.useState(null),[w,c]=a.useState(!1),[W,K]=a.useState(!1),[P,L]=a.useState(!1),[E,I]=a.useState(!1),[z,U]=a.useState(!1),[_,F]=a.useState(!1),[G,oe]=a.useState(!1),j=a.useRef(null),g=a.useRef(null),q=a.useId(),J=a.useId();a.useEffect(()=>{if(!_)return;const T=Ae=>{var It,Pt;const pe=Ae.target;pe&&((It=g.current)!=null&&It.contains(pe)||(Pt=j.current)!=null&&Pt.contains(pe)||F(!1))},xe=Ae=>{var pe;Ae.key==="Escape"&&(F(!1),(pe=j.current)==null||pe.focus())};return document.addEventListener("mousedown",T),document.addEventListener("keydown",xe),()=>{document.removeEventListener("mousedown",T),document.removeEventListener("keydown",xe)}},[_]),a.useEffect(()=>{var xe;if(!_)return;const T=(xe=g.current)==null?void 0:xe.querySelector('[role="menuitem"]:not([disabled])');T==null||T.focus()},[_]);const V=(kt=t.binding)==null?void 0:kt.taskId,ee=((St=t.binding)==null?void 0:St.status)==="awaiting_human",R=!!((Et=t.binding)!=null&&Et.creationToken)&&!((Ct=t.binding)!=null&&Ct.paneId)&&!ee&&t.reason!=="PENDING_HUMAN",Q=R?{label:"Starting",cls:"pill pill-review"}:Rn[t.runtimeStatus],Y=R?"starting":t.tmuxSessionStatus,ce=h==="activity-preview"&&!R&&(t.runtimeStatus==="working"||t.runtimeStatus==="pending"),O=h==="embedded-full",te=O&&typeof v=="function",se=te&&x===!0,k=l||i||R,B=l?"Agent 状态加载中":i?"重启 baxian server 后可用":"Agent 正在启动",D=pt(o),ie=async()=>{d(!0),A(null);try{await $.agents.stop(t.id)}catch(T){A(T instanceof Error?T.message:String(T))}finally{d(!1)}},le=async()=>{if(V&&window.confirm(`请 QA 对 task ${V} 重审?这会让 QA agent 立即开始新一轮 review(reviewRound +1)。`)){L(!0);try{const T=await $.tasks.review(V);m({kind:"success",title:`已派 QA 重审 (round ${T.reviewRound})`})}catch(T){m({kind:"error",title:"Review 派发失败",body:T instanceof Error?T.message:String(T)})}finally{L(!1)}}},de=async()=>{U(!0);try{(await $.projects.bootstrap(s)).ok?m({kind:"success",title:"Bootstrap retry 完成",body:"agent 状态将在下一次刷新生效。"}):m({kind:"warn",title:"Bootstrap retry 仍失败",body:"看一下红色错误卡的最新原因,按提示修复后再试。"})}catch(T){m({kind:"error",title:"Bootstrap retry 失败",body:T instanceof Error?T.message:String(T)})}finally{U(!1)}},C=async()=>{if(window.confirm(`确认 Resume Agent ${t.id}?baxian 会清除 awaiting_human 状态,agent 重新可派遣。`)){I(!0);try{const T=await $.projects.resumeAgent(s,t.id);m({kind:"success",title:`Agent ${t.id} 已 Resume`,body:T.releasedBinding?"原任务已释放,agent 可接新任务。":"保留绑定(原任务仍 active)。"})}catch(T){m({kind:"error",title:"Resume 失败",body:T instanceof Error?T.message:String(T)})}finally{I(!1)}}},H=async()=>{c(!0);try{await $.agents.compact(t.id),m({kind:"success",title:`已向 Agent ${t.id} 发送 /compact`})}catch(T){m({kind:"error",title:"Compact 失败",body:T instanceof Error?T.message:String(T)})}finally{c(!1)}},re=async()=>{if(window.confirm(`确认向 Agent ${t.id} 发送 /clear?这会清空整个会话上下文,不可恢复。`)){K(!0);try{await $.agents.clear(t.id),m({kind:"success",title:`已向 Agent ${t.id} 发送 /clear`})}catch(T){m({kind:"error",title:"Clear 失败",body:T instanceof Error?T.message:String(T)})}finally{K(!1)}}},Z=async()=>{if(window.confirm(`确认删除 Agent ${t.id}?此操作不可撤销`)){M(!0),N(null);try{const T=await $.projects.deleteAgent(s,t.id);T!=null&&T.restartRequired&&b();const xe=(T==null?void 0:T.removed)??[t.id];if(xe.length>1){const Ae=xe.filter(pe=>pe!==t.id).join(", ");m({kind:"warn",title:`已删除 Agent ${t.id}`,body:`配对的 QA Agent ${Ae} 也被一并移除。`})}else m({kind:"success",title:`Agent ${t.id} 已删除`});r==null||r()}catch(T){N(T instanceof Error?T.message:String(T))}finally{M(!1)}}},ue=te&&!k&&!se,me=["card relative flex h-full min-w-0 flex-col overflow-visible p-4",se?"ring-2 ring-accent":""].filter(Boolean).join(" "),_e=["mb-3 flex items-start justify-between gap-2",t.petId?"pr-28":""].filter(Boolean).join(" "),we=["mb-2 mt-3 h-80 min-h-0 overflow-hidden border border-hairline bg-surface",ue?"cursor-pointer":""].filter(Boolean).join(" "),Ne=ue?()=>v==null?void 0:v():void 0,ke=ue?T=>{(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),v==null||v())}:void 0;return e.jsxs("div",{className:me,"data-agent-card":te?t.id:void 0,children:[t.petId&&e.jsx("div",{className:"absolute -top-4 right-7 z-10",children:e.jsx(ds,{petId:t.petId,status:t.runtimeStatus,bootstrapping:R,label:Q.label,displayHeight:An})}),e.jsxs("div",{className:_e,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:"shrink-0 font-mono text-[11px] font-medium uppercase tracking-[0.05em] text-og-500",children:n}),e.jsx("span",{className:"min-w-0 truncate whitespace-nowrap font-display text-[14px] font-semibold text-og-1000",title:gt(t.id,o),children:t.id}),D&&e.jsxs("span",{className:"hidden shrink-0 whitespace-nowrap text-[12px] text-og-400 sm:inline",title:D,children:["(",D,")"]})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-1",children:[ee&&e.jsx("span",{className:"pill pill-warn",title:((Rt=t.binding)==null?void 0:Rt.awaitingReason)??"需人工处理",children:"Held"}),!t.petId&&e.jsx("span",{className:Q.cls,children:Q.label}),t.stale&&e.jsx("span",{className:"pill pill-warn",title:t.observedAt?`Last observed at ${t.observedAt}`:void 0,children:"Stale"}),e.jsx(In,{state:Y})]})]}),R&&e.jsx("div",{className:"mb-2 rounded-md border border-accent-soft bg-accent-soft/40 px-2.5 py-2 text-[12px] text-accent",children:"Agent 正在启动,终端可用后会自动刷新。"}),ee&&e.jsxs("div",{className:"mb-2 rounded-md border border-[#fde68a] bg-[#fef3c7]/60 px-2.5 py-2 text-[12px] text-warn",children:[e.jsx("span",{className:"font-mono",children:(At=t.binding)==null?void 0:At.awaitingPhase}),((Tt=t.binding)==null?void 0:Tt.awaitingReason)&&e.jsxs("span",{children:[" · ",t.binding.awaitingReason]})]}),!R&&t.runtimeStatus==="pending"&&e.jsxs("div",{className:"mb-2 space-y-1 rounded-md border border-[#fde68a] bg-[#fef3c7]/60 px-2.5 py-2 text-[12px] text-warn",children:[e.jsx("div",{className:"font-medium",children:"等待人工介入"}),e.jsxs("div",{children:["Agent 正在等待人工输入。请打开 ",e.jsx(Me,{to:`/terminal/${t.id}`,className:"text-accent hover:text-accent-hover underline",children:"Terminal"})," 处理; 处理完后状态会随下一次观测刷新。"]})]}),t.latestError&&e.jsxs("div",{className:"mb-2 space-y-1 rounded-md border border-[#fecaca] bg-[#fef2f2] px-2.5 py-2 text-[12px] text-danger",children:[e.jsx("div",{className:"break-words font-medium",children:t.latestError.message}),e.jsxs("div",{className:"font-mono text-[11px] opacity-80",children:[t.latestError.reason," · ",t.latestError.occurredAt]})]}),t.latestBootstrapError&&e.jsxs("div",{className:"mb-2 space-y-1 rounded-md border border-[#fecaca] bg-[#fef2f2] px-2.5 py-2 text-[12px] text-danger",children:[e.jsx("div",{className:"break-words font-medium",children:t.latestBootstrapError.message}),t.latestBootstrapError.recommendation&&e.jsx("div",{className:"break-words",children:t.latestBootstrapError.recommendation}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"truncate font-mono text-[11px] opacity-80",children:[t.latestBootstrapError.reason," · ",t.latestBootstrapError.occurredAt]}),e.jsx("button",{type:"button",onClick:de,disabled:z,className:"btn-secondary shrink-0 !border-[#fecaca] !text-danger hover:!bg-[#fef2f2] hover:!border-danger hover:!text-danger",children:z?"Retrying…":"Retry bootstrap"})]})]}),u&&V&&e.jsxs("div",{className:"mb-2 text-[12px] text-og-500",children:["Task: ",e.jsx("span",{className:"font-mono text-og-700",children:V})]}),ce&&e.jsx("div",{className:"mb-2 overflow-hidden border border-hairline bg-surface",children:e.jsx(De,{agentId:t.id,mode:"preview",maxLines:6,interactive:!1})}),O&&e.jsx("div",{className:we,role:ue?"button":void 0,tabIndex:ue?0:void 0,"aria-label":ue?`激活 ${t.id} 终端`:void 0,onClick:Ne,onKeyDown:ke,children:k?e.jsx("div",{className:"flex h-full items-center justify-center px-3 text-[13px] text-og-500",children:B}):te?se?e.jsx(De,{agentId:t.id,mode:"full",interactive:!0,autoFocus:!0}):e.jsx(De,{agentId:t.id,mode:"preview",interactive:!1}):e.jsx(De,{agentId:t.id,mode:"full",interactive:!0,autoFocus:!1,deferFullUntilFocus:!0})}),i&&e.jsx("div",{className:"mb-2 rounded-md border border-[#fde68a] bg-[#fef3c7]/60 px-2.5 py-1.5 text-[12px] text-warn",children:"⚠️ 重启 baxian server 后生效"}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2 overflow-x-auto scrollbar-none",children:[k?e.jsx("span",{className:"shrink-0 cursor-not-allowed text-[13px] text-og-400",title:B,children:"Terminal"}):e.jsx(Me,{to:`/terminal/${t.id}`,className:"btn-secondary shrink-0",children:"Terminal"}),!i&&t.runtimeStatus==="working"&&e.jsx("button",{onClick:ie,disabled:p,className:"btn-ghost shrink-0 !text-danger hover:!bg-[#fef2f2]",children:p?"Stopping…":"Stop"}),ee&&e.jsx("button",{type:"button",onClick:C,disabled:E,title:"清除 awaiting_human 状态,让 agent 重新可派遣",className:"btn-ghost shrink-0 !text-warn hover:!bg-[#fef3c7]/60",children:E?"Resuming…":"Resume"})]}),e.jsxs("div",{className:"relative shrink-0",children:[e.jsx("button",{ref:j,id:J,type:"button",onClick:()=>F(T=>!T),disabled:S,"aria-haspopup":"menu","aria-expanded":_,"aria-controls":q,"aria-label":`Agent ${t.id} 操作菜单`,className:"flex h-8 w-8 items-center justify-center rounded text-og-500 transition-colors hover:bg-og-100 hover:text-og-1000 disabled:cursor-not-allowed disabled:opacity-50",children:e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("circle",{cx:"12",cy:"12",r:"1"}),e.jsx("circle",{cx:"12",cy:"5",r:"1"}),e.jsx("circle",{cx:"12",cy:"19",r:"1"})]})}),_&&e.jsxs("div",{ref:g,id:q,role:"menu","aria-labelledby":J,className:"absolute right-0 bottom-full z-10 mb-1 min-w-[140px] rounded-md border border-hairline bg-surface py-1 shadow-md",children:[e.jsx("button",{type:"button",role:"menuitem",onClick:()=>{F(!1),H()},disabled:w||W||S,title:"向 agent runtime 发送 /compact 压缩上下文",className:"block w-full px-3 py-1.5 text-left text-[13px] text-og-1000 hover:bg-og-100 disabled:opacity-50 disabled:cursor-not-allowed",children:w?"Compacting…":"Compact"}),e.jsx("button",{type:"button",role:"menuitem",onClick:()=>{F(!1),re()},disabled:W||w||S,title:"向 agent runtime 发送 /clear 清空上下文",className:"block w-full px-3 py-1.5 text-left text-[13px] text-og-1000 hover:bg-og-100 disabled:opacity-50 disabled:cursor-not-allowed",children:W?"Clearing…":"Clear"}),e.jsx("button",{type:"button",role:"menuitem",onClick:()=>{F(!1),oe(!0)},disabled:w||W||S,title:"配置 Agent Pet(在状态位置显示动画宠物)",className:"block w-full px-3 py-1.5 text-left text-[13px] text-og-1000 hover:bg-og-100 disabled:opacity-50 disabled:cursor-not-allowed",children:"Agent Pet"}),!i&&V&&n==="dev"&&e.jsx("button",{type:"button",role:"menuitem",onClick:()=>{F(!1),le()},disabled:P||S,title:`让 QA 立即对 task ${V} 跑一轮 review(需要该 task 已有 PR)`,className:"block w-full px-3 py-1.5 text-left text-[13px] text-og-1000 hover:bg-og-100 disabled:opacity-50 disabled:cursor-not-allowed",children:P?"Dispatching…":"Call review"}),e.jsx("button",{type:"button",role:"menuitem",onClick:()=>{F(!1),Z()},disabled:S||w||W,className:"block w-full px-3 py-1.5 text-left text-[13px] text-danger hover:bg-[#fef2f2] disabled:opacity-50 disabled:cursor-not-allowed",children:S?"Deleting…":"Delete"})]})]})]}),y&&e.jsx("div",{className:"mt-1.5 break-words text-[12px] text-danger",children:y}),f&&e.jsx("div",{className:"mt-1.5 break-words text-[12px] text-danger",children:f}),G&&e.jsx(Cn,{agentId:t.id,currentPetId:t.petId??null,onClose:()=>oe(!1)})]})}const _t=200,Ft=16e3,$n="baxian.draft.createTask:";function ft(t){return`${$n}${t??"*"}`}function Bt(t){try{const s=localStorage.getItem(t);if(!s)return null;const n=JSON.parse(s);if(!n||typeof n!="object")return null;const o=n,r=typeof o.title=="string"?o.title:"",i=typeof o.description=="string"?o.description:"",l=typeof o.projectId=="string"?o.projectId:"",u=typeof o.preferredAgentId=="string"?o.preferredAgentId:"",h=typeof o.updatedAt=="number"?o.updatedAt:void 0;return!r.trim()&&!i.trim()?null:{title:r,description:i,projectId:l,preferredAgentId:u,updatedAt:h}}catch{return null}}function Dn(t,s){const n=!s.title.trim()&&!s.description.trim();try{n?localStorage.removeItem(t):localStorage.setItem(t,JSON.stringify({...s,updatedAt:Date.now()}))}catch{}}function Ht(t){try{localStorage.removeItem(t)}catch{}}function On(t){const s=ft(t),n=Bt(s);if(!t)return n;const o=ft(void 0),r=Bt(o);if(!r||r.projectId!==t)return n;const i=!n||(r.updatedAt??0)>(n.updatedAt??0);if(i)try{localStorage.setItem(s,JSON.stringify(r))}catch{return r}try{localStorage.removeItem(o)}catch{}return i?r:n}const Ue="w-full rounded-md border border-og-100 bg-surface px-2.5 py-1.5 text-[13px] text-og-800 placeholder:text-og-400 focus:border-accent focus:outline-none focus:ring-[3px] focus:ring-accent-soft disabled:cursor-not-allowed disabled:opacity-50",Ie="mb-1.5 block text-[12px] font-medium text-og-700",zt="mt-1 text-right text-[12px] text-og-400",Mn=Math.floor(Ye/1024/1024);function yt(t){const s=t.mode==="edit",{show:n}=he(),o=s?t.task.projectId:t.projectId,r=s?t.task.title:"",i=s?t.task.description:"",l=s?t.task.preferredAgentId:"",[u,h]=a.useState([]),[x,v]=a.useState([]),[p,d]=a.useState(o??""),[y,A]=a.useState(l),[m,b]=a.useState(r),[S,M]=a.useState(i),[f,N]=a.useState([]),w=a.useRef(null),[c,W]=a.useState(!1),[K,P]=a.useState(null),[L,E]=a.useState(!1),I=a.useRef(0),z=a.useRef(0),U=a.useRef(0),_=a.useRef(new Set),F=s?null:ft(o);a.useEffect(()=>{if(!t.open)return;I.current+=1,z.current+=1;const C=I.current;h([]),v([]),_.current=new Set;const H=F?On(o):null;H&&_.current.add(H.projectId),d(o??(H==null?void 0:H.projectId)??""),A((H==null?void 0:H.preferredAgentId)||l),b((H==null?void 0:H.title)||r),M((H==null?void 0:H.description)||i),E(H!==null),P(null),W(!1),N([]),Promise.all([$.projects.list(),$.agents.list()]).then(([re,Z])=>{C===I.current&&(h(re),v(Z))}).catch(re=>{C===I.current&&P(re instanceof Error?re.message:String(re))})},[t.open,o,r,i,l,F]),a.useEffect(()=>{if(!(!t.open||!F)){if(U.current!==z.current){U.current=z.current;return}Dn(F,{title:m,description:S,projectId:p,preferredAgentId:y})}},[t.open,F,m,S,p,y]);const G=a.useMemo(()=>u.find(C=>C.id===p)??null,[u,p]),oe=a.useMemo(()=>G?G.agent.flat().filter(C=>C.role==="dev"):[],[G]),j=a.useMemo(()=>new Set(x.map(C=>C.id)),[x]),g=a.useMemo(()=>oe.filter(C=>j.has(C.id)),[oe,j]),q=a.useMemo(()=>oe.filter(C=>!j.has(C.id)),[oe,j]);a.useEffect(()=>{s||G!==null&&y!==""&&!g.find(C=>C.id===y)&&A("")},[G,g,y,s]),a.useEffect(()=>{s||G&&g.length!==0&&(_.current.has(G.id)||(_.current.add(G.id),A(C=>C===""?g[0].id:C)))},[s,G,g]);const J=!s||g.find(C=>C.id===y),V=s&&!J&&!!y,ee=V&&q.some(C=>C.id===y),R=ee?`当前 dev "${y}" 在 baxian.json 中存在但 runtime 未加载,可能是手动编辑过配置文件;重启 server 可拉起`:V?`当前 dev "${y}" 不在 runtime(可能已从 project 配置移除);保存可能失败,请确认或选择新 dev`:!p||g.length>0?null:q.length>0?"baxian.json 里有 dev agent 但 runtime 未加载(可能是手动编辑过配置);重启 server 后生效":null,Q=m.trim(),Y=S.trim(),O=!!p&&Q.length>0&&!c,te=()=>{c||t.onClose()},se=()=>{F&&(Ht(F),d(o??""),A(l),b(r),M(i),P(null),E(!1))},k=async C=>{var H,re;if(C.preventDefault(),!!O){W(!0),P(null);try{if(t.mode==="edit"){const Z=await $.tasks.update(t.task.id,{title:Q,description:Y,preferredAgentId:y});n({kind:"success",title:"任务已更新"}),(H=t.onUpdated)==null||H.call(t,Z),t.onClose()}else{const Z=f.length?await Promise.all(f.map(async me=>({dataBase64:await ut(me),filename:me.name}))):void 0,ue=await $.tasks.create({projectId:p,title:Q,description:Y,preferredAgentId:y,...Z?{images:Z}:{}});F&&Ht(F),n({kind:"success",title:"任务已创建"}),(re=t.onCreated)==null||re.call(t,ue),t.onClose()}}catch(Z){P(Z instanceof Error?Z.message:String(Z))}finally{W(!1)}}},B=C=>{const H=Array.from(C.target.files??[]);if(C.target.value="",H.length===0)return;const re=H.filter(Z=>Z.size>Ye?(n({kind:"error",title:"图片过大",body:`${Z.name} 超过 ${Mn} MiB`}),!1):!0);N(Z=>(Z.length+re.length>Fe&&n({kind:"warn",title:`最多 ${Fe} 张图片`}),[...Z,...re].slice(0,Fe)))},D=C=>N(H=>H.filter((re,Z)=>Z!==C)),ie=s?"编辑 Task":"新建 Task",le=s?c?"保存中…":"保存":c?"创建中…":"创建",de=!s&&!o;return e.jsx(ve,{open:t.open,onClose:te,title:ie,size:"md",dismissOnBackdrop:!1,footer:e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:te,disabled:c,className:"btn-secondary",children:"取消"}),e.jsx("button",{type:"submit",form:"create-task-form",disabled:!O,className:"btn-primary",children:le})]}),children:e.jsxs("form",{id:"create-task-form",onSubmit:k,className:"space-y-3",children:[!s&&L&&e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-md border border-accent-soft bg-accent-soft/30 px-3 py-2 text-[12px] text-accent",children:[e.jsx("span",{children:"已恢复上次未提交的草稿"}),e.jsx("button",{type:"button",onClick:se,className:"shrink-0 underline hover:text-accent-hover",children:"丢弃"})]}),K&&e.jsx("div",{className:"rounded-md border border-[#fecaca] bg-[#fef2f2] px-3 py-2 text-[13px] text-danger",children:K}),de&&e.jsxs("div",{children:[e.jsx("label",{className:Ie,htmlFor:"task-project",children:"Project"}),e.jsxs("select",{id:"task-project",value:p,onChange:C=>d(C.target.value),className:Ue,disabled:c,required:!0,children:[e.jsx("option",{value:"",disabled:!0,children:"选择项目"}),u.map(C=>e.jsx("option",{value:C.id,children:C.id},C.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ie,htmlFor:"task-dev",children:"Dev Agent"}),e.jsxs("select",{id:"task-dev",value:y,onChange:C=>A(C.target.value),className:Ue,disabled:c,children:[e.jsx("option",{value:"",children:"暂不指定"}),V&&e.jsxs("option",{value:y,children:[y," ",ee?"(待重启)":"(不在 runtime)"]}),g.map(C=>e.jsx("option",{value:C.id,children:C.id},C.id))]}),R&&e.jsx("div",{className:"mt-1 text-[12px] text-warn",children:R})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ie,htmlFor:"task-title",children:"Title"}),e.jsx("input",{id:"task-title",type:"text",value:m,onChange:C=>b(C.target.value),maxLength:_t,className:Ue,placeholder:"一句话描述要做什么",disabled:c,required:!0}),e.jsxs("div",{className:zt,children:[m.length," / ",_t]})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ie,htmlFor:"task-description",children:"Description(可选)"}),e.jsx("textarea",{id:"task-description",value:S,onChange:C=>M(C.target.value),maxLength:Ft,rows:8,className:`${Ue} font-mono text-[12px]`,placeholder:"详细描述任务,支持 markdown;简单任务可不填",disabled:c}),e.jsxs("div",{className:zt,children:[S.length," / ",Ft]})]}),!s&&e.jsxs("div",{children:[e.jsx("label",{className:Ie,children:"图片(可选)"}),e.jsx("button",{type:"button",onClick:()=>{var C;return(C=w.current)==null?void 0:C.click()},disabled:c||f.length>=Fe,className:"btn-secondary",children:"添加图片"}),e.jsx("input",{ref:w,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:B}),f.length>0&&e.jsx("ul",{className:"mt-2 space-y-1",children:f.map((C,H)=>e.jsxs("li",{className:"flex items-center justify-between rounded-md border border-og-100 bg-surface px-2.5 py-1.5",children:[e.jsx("span",{title:C.name,className:"truncate text-[12px] text-og-700",children:C.name}),e.jsx("button",{type:"button","aria-label":`移除图片 ${C.name}`,onClick:()=>D(H),disabled:c,className:"ml-2 shrink-0 text-og-400 transition-colors hover:text-danger",children:"✕"})]},`${C.name}-${H}`))})]})]})})}function Ln(t){return Array.from(new TextEncoder().encode(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}function _n(){return`${location.protocol==="https:"?"wss":"ws"}://${location.host}/api/realtime`}const Fn=(t,s)=>s&&s.length>0?new WebSocket(t,s):new WebSocket(t);class Bn{constructor(s={}){ne(this,"wsUrl");ne(this,"wsFactory");ne(this,"tokenProvider");ne(this,"ws",null);ne(this,"topics",new Map);ne(this,"cache",new Map);ne(this,"outbox",[]);ne(this,"reconnectScheduler");ne(this,"explicitlyClosed",!1);this.wsUrl=s.wsUrl??_n(),this.wsFactory=s.wsFactory??Fn,this.tokenProvider=s.tokenProvider??vt,this.reconnectScheduler=new ls({reconnect:()=>this.openSocket(),shouldReconnect:()=>!this.explicitlyClosed&&this.topics.size>0})}subscribe(s,n,o){let r=this.topics.get(s);const i=!r;return r||(r={data:new Set,error:new Set},this.topics.set(s,r)),r.data.add(n),o&&r.error.add(o),i?(this.ensureSocket(),this.wsSendOrQueue({op:"subscribe",topic:s})):this.cache.has(s)&&queueMicrotask(()=>{var l;(l=this.topics.get(s))!=null&&l.data.has(n)&&this.cache.has(s)&&n(this.cache.get(s))}),()=>this.unsubscribe(s,n,o)}close(){if(this.explicitlyClosed=!0,this.reconnectScheduler.cancel(),this.reconnectScheduler.reset(),this.ws){try{this.ws.close()}catch{}this.ws=null}this.topics.clear(),this.cache.clear(),this.outbox=[]}unsubscribe(s,n,o){const r=this.topics.get(s);r&&(r.data.delete(n),o&&r.error.delete(o),r.data.size===0&&r.error.size===0&&(this.topics.delete(s),this.cache.delete(s),this.wsSendOrQueue({op:"unsubscribe",topic:s}),this.topics.size===0&&this.teardownSocket()))}teardownSocket(){if(this.reconnectScheduler.cancel(),this.reconnectScheduler.reset(),this.outbox=[],this.ws){try{this.ws.close()}catch{}this.ws=null}}ensureSocket(){this.explicitlyClosed||this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING)||this.openSocket()}openSocket(){if(this.explicitlyClosed)return;this.reconnectScheduler.cancel();const s=this.tokenProvider(),n=s?[`baxian.token.${Ln(s)}`]:void 0;let o;try{o=this.wsFactory(this.wsUrl,n)}catch(i){console.warn("[events-client] WebSocket constructor threw:",i),this.broadcastConnectionError({code:"connection_failed",message:i instanceof Error?i.message:"WebSocket constructor threw"}),this.scheduleReconnect();return}this.ws=o;let r=!1;o.onopen=()=>{if(o!==this.ws)return;r=!0,this.reconnectScheduler.reset();for(const l of this.topics.keys())try{o.send(JSON.stringify({op:"subscribe",topic:l}))}catch(u){console.warn("[events-client] resubscribe send failed:",u)}const i=this.outbox;this.outbox=[];for(const l of i)if(!(l.op==="subscribe"||l.op==="unsubscribe"))try{o.send(JSON.stringify(l))}catch(u){console.warn("[events-client] outbox flush failed:",u)}},o.onmessage=i=>{if(o!==this.ws)return;let l;try{const u=typeof i.data=="string"?i.data:String(i.data);l=JSON.parse(u)}catch{return}this.handleMessage(l)},o.onclose=()=>{o===this.ws&&(this.ws=null,!this.explicitlyClosed&&(r||this.broadcastConnectionError({code:"connection_failed",message:"WebSocket failed to connect (auth, network, or proxy issue)"}),this.topics.size!==0&&this.scheduleReconnect()))},o.onerror=()=>{}}scheduleReconnect(){this.reconnectScheduler.schedule()}broadcastConnectionError(s){for(const n of this.topics.values())for(const o of[...n.error])try{o(s)}catch(r){console.error("[events-client] error handler threw on connection error:",r)}}wsSendOrQueue(s){if(this.ws&&this.ws.readyState===WebSocket.OPEN)try{this.ws.send(JSON.stringify(s));return}catch(n){console.warn("[events-client] send failed, will queue:",n)}this.outbox.push(s)}handleMessage(s){switch(s.type){case"data":{const n=this.topics.get(s.topic);if(this.cache.set(s.topic,s.data),!n)return;for(const o of[...n.data])try{o(s.data)}catch(r){console.error(`[events-client] handler threw on ${s.topic}:`,r)}break}case"error":{const n={code:s.code,message:s.message};if(s.topic){const o=this.topics.get(s.topic);if(o)for(const r of[...o.error])try{r(n)}catch(i){console.error(`[events-client] error handler threw on ${s.topic}:`,i)}}else console.warn("[events-client] connection-level error:",s.code,s.message);break}}}}let at=null;function jt(){return at||(at=new Bn),at}function us(){const[t,s]=a.useState(null),[n,o]=a.useState(!1),[r,i]=a.useState(null);return a.useEffect(()=>jt().subscribe("agents",u=>{i(null),s(u),o(!0)},u=>i(u)),[]),{data:t,loaded:n,error:r}}function Hn(t){const[s,n]=a.useState(null),[o,r]=a.useState(!1),[i,l]=a.useState(null);return a.useEffect(()=>(n(null),r(!1),l(null),jt().subscribe(`task:${t}`,h=>{l(null),n(h),r(!0)},h=>l(h))),[t]),{data:s,loaded:o,error:i}}function fs(t){const[s,n]=a.useState(null),[o,r]=a.useState(!1),[i,l]=a.useState(null);return a.useEffect(()=>{if(!t){n(null),r(!1),l(null);return}n(null),r(!1),l(null);let u=!1,h=!1,x=!1;const v=jt().subscribe(`project-tasks:${t}`,p=>{u||(h=!0,l(null),n(p),r(!0))},p=>{u||(l(p),!(h||x)&&(x=!0,$.tasks.list(t).then(d=>{u||h||(n(d),r(!0))},d=>{console.warn(`[useProjectTasks] REST fallback failed for ${t}:`,d)})))});return()=>{u=!0,v()}},[t]),{data:s,loaded:o,error:i}}let Ke=null,be=null,Ve=null,Oe=0;const ht=new Set;function hs(){ht.forEach(t=>t())}async function zn(){const t=Oe;try{const s=await $.projects.list();if(t!==Oe)return;Ke=s,Ve=null}catch(s){if(t!==Oe)return;Ve=s instanceof Error?s.message:String(s)}finally{t===Oe&&(be=null,hs())}}function mt(){return be||(be=zn(),be)}function Un(){Oe+=1,Ke=null,be=null,Ve=null,hs()}typeof window<"u"&&window.addEventListener(Qe,Un);async function Wn(){const t=be!==null;await mt(),t&&await mt()}function Ze(){const[,t]=a.useState(0);return a.useEffect(()=>{const s=()=>t(n=>n+1);return ht.add(s),Ke===null&&!be&&mt(),()=>{ht.delete(s)}},[]),{projects:Ke,error:Ve,refresh:Wn}}function Gn(t){const[s,n]=a.useState(!1);return a.useEffect(()=>{function o(){if(!t||t.status!=="review"||!t.reviewDispatchedAt||!t.qaAgentId){n(!1);return}const i=Date.now()-Date.parse(t.reviewDispatchedAt);n(i>=rs)}o();const r=setInterval(o,3e4);return()=>clearInterval(r)},[t==null?void 0:t.status,t==null?void 0:t.reviewDispatchedAt,t==null?void 0:t.qaAgentId]),s}const ms=a.createContext(null);function Qn({children:t}){const[s,n]=a.useState(null),o=a.useCallback(i=>n(i),[]),r=a.useCallback(()=>n(null),[]);return e.jsxs(ms.Provider,{value:{openTask:o},children:[t,s!==null&&e.jsx(Vn,{taskId:s,onClose:r,onOpenTask:n},s)]})}function Le(){const t=a.useContext(ms);if(!t)throw new Error("useTaskDetail must be inside <TaskDetailProvider>");return t}const Ut=ss,xs={pending:"pill",in_progress:"pill pill-live",review:"pill pill-review",fixing:"pill pill-warn",approved:"pill pill-live","merge-ready":"pill pill-live",ready:"pill pill-live",merged:"pill pill-live",done:"pill pill-live",failed:"pill pill-warn",max_rounds:"pill pill-warn",cancelled:"pill"},qn={pending:"bg-og-300",in_progress:"bg-success",review:"bg-accent",fixing:"bg-warn",approved:"bg-success","merge-ready":"bg-success",ready:"bg-success",merged:"bg-success",done:"bg-success",failed:"bg-warn",max_rounds:"bg-warn",cancelled:"bg-og-300"};function Kn({status:t}){return e.jsx("span",{role:"img","aria-label":t,title:t,className:`inline-block h-2 w-2 shrink-0 rounded-full ${qn[t]??"bg-og-300"}`})}function Nt(t){if(!t)return"";const s=t.match(/^task-(\d+)$/);return s?s[1]:t}function Wt({id:t,runtime:s}){const n=pt(s);return t?e.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-baseline gap-1 align-baseline",title:gt(t,s),children:[e.jsx("span",{className:"min-w-0 truncate font-mono text-og-800",children:t}),n&&e.jsxs("span",{className:"hidden shrink-0 whitespace-nowrap text-[12px] text-og-400 sm:inline",children:["(",n,")"]})]}):e.jsx("span",{className:"font-mono text-og-800",children:"—"})}function it(t){if(t==null)return"";const s=String(t).trim();if(!s)return"";const n=s.match(/^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2})(?::(\d{2}))?/);if(n)return`${n[1]} ${n[2]}:${n[3]??"00"}`;const o=new Date(s);return Number.isNaN(o.getTime())?s:o.toISOString().slice(0,19).replace("T"," ")}function Vn({taskId:t,onClose:s,onOpenTask:n}){const{show:o}=he(),[r,i]=a.useState(!1),[l,u]=a.useState(!1),[h,x]=a.useState(!1),[v,p]=a.useState(!1),[d,y]=a.useState(!1),[A,m]=a.useState(!1),[b,S]=a.useState(null),{data:M,loaded:f,error:N}=Hn(t),{projects:w}=Ze(),c=b??M,W=Gn(c),K=(N==null?void 0:N.message)??null,P=a.useMemo(()=>{const g=new Map;for(const q of w??[])for(const J of q.agent)for(const V of J)g.set(V.id,V.runtime);return g},[w]);a.useEffect(()=>{b&&M&&M.updatedAt>=b.updatedAt&&S(null)},[b,M]);const L=g=>{S(g)},E=async()=>{if(c&&confirm(`确定取消 task ${c.id}?`)){u(!0);try{const g=await $.tasks.update(c.id,{status:"cancelled"});L(g),o({kind:"success",title:"任务已取消"})}catch(g){o({kind:"error",title:"取消失败",body:g instanceof Error?g.message:String(g)})}finally{u(!1)}}},I=async()=>{if(!c)return;const q=ss.has(c.status)?`task ${c.id} 已是 ${c.status} 状态。手动请 QA 重审会再跑一轮 review,但状态机不会把 QA 结果带回主流程。继续?`:`请 QA 重审 task ${c.id}?这会让 QA agent 立即开始新一轮 review(reviewRound +1)。`;if(confirm(q)){p(!0);try{const J=await $.tasks.review(c.id);L(J),o({kind:"success",title:`已派 QA 重审 (round ${J.reviewRound})`})}catch(J){o({kind:"error",title:"Review 派发失败",body:J instanceof Error?J.message:String(J)})}finally{p(!1)}}},z=async()=>{if(!c)return;const g=c.status==="merged"?`task ${c.id} 已 merged。Retry 会用同样的标题/描述新建一个 task 从头跑,确定继续?`:`Retry task ${c.id}?这会新建一个 task 从头开始,旧 task 保留为历史。`;if(confirm(g)){x(!0);try{const q=await $.tasks.retry(c.id);o({kind:"success",title:`已新建 task ${q.id}`}),n(q.id)}catch(q){o({kind:"error",title:"Retry 失败",body:q instanceof Error?q.message:String(q)})}finally{x(!1)}}},U=async()=>{if(c&&confirm(`将合并 PR #${c.prNumber} 并收尾(删本地分支 + 压缩 agent 上下文),确定?`)){y(!0);try{const g=await $.tasks.complete(c.id);L(g),o({kind:"success",title:"已标记完成,开始收尾"})}catch(g){o({kind:"error",title:"标记完成失败",body:g instanceof Error?g.message:String(g)})}finally{y(!1)}}},_=async()=>{if(c&&confirm(`派 dev 再修一轮(round → ${c.reviewRound+1}),完成后自动转 QA review?`)){m(!0);try{const g=await $.tasks.continue(c.id);L(g),o({kind:"success",title:`已继续一轮 (round ${g.reviewRound})`})}catch(g){o({kind:"error",title:"继续一轮失败",body:g instanceof Error?g.message:String(g)})}finally{m(!1)}}},F=async()=>{if(c&&confirm(`确认完成 task ${c.id}?project.merge 为 auto 时由 baxian 自动执行合并。`)){y(!0);try{const g=await $.tasks.complete(c.id);L(g),o({kind:"success",title:`已确认(${g.status})`})}catch(g){o({kind:"error",title:"确认失败",body:g instanceof Error?g.message:String(g)})}finally{y(!1)}}};if(r&&c)return e.jsx(yt,{mode:"edit",open:!0,onClose:()=>i(!1),task:c,onUpdated:L});const G=c?`${c.id} ${c.title}`:t;return e.jsx(ve,{open:!0,onClose:s,title:G,titleContent:c?e.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-baseline gap-2",children:[e.jsx("span",{className:"shrink-0 font-mono text-og-400",children:c.id}),e.jsx("span",{className:"min-w-0 truncate text-og-1000",children:c.title})]}):void 0,size:"lg",footer:c?j(c):void 0,children:oe()});function oe(){if(K&&!c)return e.jsxs("div",{className:"text-[13px] text-danger",children:["Error: ",K]});if(f&&!c)return e.jsxs("div",{className:"text-[13px] text-danger",children:["Task not found: ",t]});if(!c)return e.jsx("div",{className:"text-[13px] text-og-500",children:"Loading…"});const g=c.preferredAgentId==="",q=c.status==="approved"&&c.prNumber!==void 0,J=c.status==="merge-ready"&&c.prNumber!==void 0,V=c.status==="ready",ee=c.status==="max_rounds"&&c.phase!=="spec",R=c.status==="max_rounds"&&c.phase==="spec";return e.jsxs("div",{children:[K&&e.jsxs("div",{className:"mb-4 text-[13px] text-danger",children:["Error: ",K]}),g&&e.jsx("div",{className:"mb-4 rounded-md border border-[#fde68a] bg-[#fef3c7]/60 px-3 py-2.5 text-[12px] text-warn",children:c.status==="pending"?e.jsxs(e.Fragment,{children:["This task has no dev assigned yet — click ",e.jsx("b",{className:"font-semibold",children:"Edit"})," to choose one, or use the Start button on any idle dev card."]}):e.jsxs(e.Fragment,{children:["This is a legacy task with no preferred dev (read-only in status ",e.jsx("b",{className:"font-semibold",children:c.status}),")."]})}),e.jsx("div",{className:"mb-2 flex flex-wrap items-center gap-3",children:e.jsx("span",{className:xs[c.status],children:c.status})}),e.jsxs("div",{className:"mb-4 text-[12px] text-og-500",children:["Created at ",it(c.createdAt),", Updated at ",it(c.updatedAt)]}),W&&e.jsxs("div",{className:"mb-4 rounded-lg border border-[#fecaca] bg-[#fef2f2] p-4 text-[13px] text-danger",children:[e.jsx("div",{className:"font-semibold",children:"Review verdict missing"}),e.jsxs("div",{className:"mt-1 text-og-700",children:["QA dispatched at ",it(c.reviewDispatchedAt)," 超过 10 分钟未提交 verdict。 可能原因:QA agent 上下文压缩后误报已完成、agent 卡住、或 GitHub API 异常。"]}),e.jsx("div",{className:"mt-2 text-og-700",children:"建议:打开 QA terminal 检查实际状态,或手动 Call review 重新派发。"})]}),q&&e.jsxs("div",{className:"mb-4 rounded-lg border border-[#bbf7d0] bg-[#f0fdf4] p-4 text-[13px] text-success",children:[e.jsx("div",{className:"font-semibold",children:"QA approved · verifying feedback"}),e.jsx("div",{className:"mt-1 text-og-700",children:"Dev keeps the task reserved while it checks whether all human or agent feedback has been handled."}),c.prUrl&&e.jsxs("a",{href:c.prUrl,target:"_blank",rel:"noopener noreferrer",className:"btn-secondary mt-3 !border-[#bbf7d0] !text-success hover:!bg-[#dcfce7] hover:!border-success",children:["Open PR #",c.prNumber]})]}),V&&e.jsxs("div",{className:"mb-4 rounded-lg border border-[#bbf7d0] bg-[#f0fdf4] p-4 text-[13px] text-success",children:[e.jsx("div",{className:"font-semibold",children:"✅ 评审通过 · 等待人工确认"}),e.jsxs("div",{className:"mt-1 text-og-700",children:["Server review 完成(",c.reviewRound," 轮)。点击「确认」收尾",c.prNumber?"(merge:auto 时自动合并 PR)":"",",或「Cancel」丢弃。"]}),e.jsx(Gt,{taskId:c.id}),c.prUrl&&e.jsxs("a",{href:c.prUrl,target:"_blank",rel:"noopener noreferrer",className:"btn-secondary mt-3 !border-[#bbf7d0] !text-success hover:!bg-[#dcfce7] hover:!border-success",children:["Open PR #",c.prNumber]})]}),J&&e.jsxs("div",{className:"mb-4 rounded-lg border border-[#bbf7d0] bg-[#f0fdf4] p-4 text-[13px] text-success",children:[e.jsx("div",{className:"font-semibold",children:"✅ PR ready · 等待人工确认"}),e.jsx("div",{className:"mt-1 text-og-700",children:"Dev finished its post-approve checks — 点击「确认」收尾(merge:auto 时由 baxian 执行合并)。"}),c.prUrl&&e.jsxs("a",{href:c.prUrl,target:"_blank",rel:"noopener noreferrer",className:"btn-secondary mt-3 !border-[#bbf7d0] !text-success hover:!bg-[#dcfce7] hover:!border-success",children:["Open PR #",c.prNumber]})]}),ee&&e.jsxs("div",{className:"mb-4 rounded-lg border border-[#fde68a] bg-[#fef3c7]/60 p-4 text-[13px] text-warn",children:[e.jsxs("div",{className:"font-semibold",children:["已达 review 轮次上限(round ",c.reviewRound,")"]}),e.jsx("div",{className:"mt-1 text-og-700",children:"可「标记完成」合并收尾,或「继续一轮」由 dev 再修一轮(完成后自动转 QA review)。"}),e.jsx("div",{className:"mt-2 text-og-700",children:"轮次越多,Agent 越容易偏离重点。若无严重问题,建议先合并本次成果,剩余问题另开任务跟进。"})]}),R&&e.jsxs("div",{className:"mb-4 rounded-lg border border-[#fde68a] bg-[#fef3c7]/60 p-4 text-[13px] text-warn",children:[e.jsxs("div",{className:"font-semibold",children:["已达 spec review 轮次上限(round ",c.specReviewRound??0,")"]}),e.jsx("div",{className:"mt-1 text-og-700",children:"Spec 评审多轮未达成一致,任务已暂停。spec 是过程产物、没有可合并的成果, 可「Retry」新建任务从头跑(丢弃当前 worktree),或「Cancel」取消。"}),e.jsx("div",{className:"mt-2 text-og-700",children:"建议先查看下方评审记录定位分歧,细化任务描述后再 Retry。"}),e.jsx(Gt,{taskId:c.id})]}),e.jsx("pre",{className:"card mb-4 whitespace-pre-wrap p-4 text-[13px] text-og-800",children:c.description||e.jsx("span",{className:"text-og-400",children:"(无描述)"})}),e.jsxs("div",{className:"card space-y-2 p-4 text-[13px]",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-x-6 gap-y-2 md:grid-cols-2",children:[e.jsxs("div",{className:"text-og-500",children:["Project: ",e.jsx("span",{className:"font-mono text-og-800",children:c.projectId})]}),e.jsxs("div",{className:"text-og-500",children:["Round: ",e.jsx("span",{className:"font-mono text-og-800",children:c.reviewRound})," ",e.jsxs("span",{children:["spec: ",e.jsx("span",{className:"font-mono text-og-800",children:c.specReviewRound??0})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-x-6 gap-y-2 md:grid-cols-2",children:[e.jsxs("div",{className:"text-og-500",children:["Dev: ",e.jsx(Wt,{id:c.agentId,runtime:P.get(c.agentId)})]}),e.jsxs("div",{className:"text-og-500",children:["QA: ",e.jsx(Wt,{id:c.qaAgentId??"",runtime:P.get(c.qaAgentId??"")})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-x-6 gap-y-2 md:grid-cols-2",children:[e.jsxs("div",{className:"text-og-500",children:["PR:"," ",c.prNumber?c.prUrl?e.jsxs("a",{href:c.prUrl,target:"_blank",rel:"noopener noreferrer",className:"text-accent hover:text-accent-hover",children:["#",c.prNumber]}):e.jsxs("span",{className:"font-mono text-og-800",children:["#",c.prNumber]}):e.jsx("span",{className:"text-og-400",children:"—"})]}),e.jsxs("div",{className:"text-og-500",children:["Branch: ",e.jsx("span",{className:"font-mono text-og-800",children:c.branch||"—"})]})]})]})]})}function j(g){const q=g.status==="max_rounds",J=q&&g.phase!=="spec",V=q&&g.phase==="spec",ee=g.status==="ready"||g.status==="merge-ready",R=g.reviewMode==="server"&&g.status==="approved",Q=g.status==="pending",Y=g.status==="pending"||g.status==="in_progress"||q||ee||R,ce=(Ut.has(g.status)||V)&&!!g.preferredAgentId,O=!!g.prNumber&&!V&&g.reviewMode!=="server",te=g.reviewMode==="server",se=J&&(!!g.prNumber||te),k=J&&(!!g.prNumber||te)&&!!g.agentId,B=te&&g.status==="approved",D=g.preferredAgentId==="";return e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",disabled:!Q,onClick:()=>i(!0),className:"btn-secondary",children:"Edit"}),e.jsx("button",{type:"button",disabled:!Y||l,onClick:E,className:"btn-secondary !border-[#fecaca] !text-danger hover:!bg-[#fef2f2] hover:!border-danger",children:l?"Cancelling…":"Cancel"}),!J&&e.jsx("button",{type:"button",disabled:!ce||h,onClick:z,title:Ut.has(g.status)||V?D?"Legacy task has no preferred dev to retry against":"新建一个 task 从头跑,丢弃当前 worktree/branch":`Cannot retry in status ${g.status}`,className:"btn-secondary",children:h?"Retrying…":"Retry"}),e.jsx("button",{type:"button",disabled:!O||v,onClick:I,title:g.prNumber?V?"spec 阶段达上限不支持 Call review":"让 QA agent 立即开始新一轮 review(reviewRound +1)":"该 task 还没有 PR,无法派 review",className:"btn-secondary !border-accent-soft !text-accent hover:!bg-accent-soft hover:!border-accent",children:v?"Dispatching…":"Call review"}),J&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",disabled:!k||A,onClick:_,title:"派 dev 再修一轮,完成后自动转 QA review",className:"btn-secondary !border-accent-soft !text-accent hover:!bg-accent-soft hover:!border-accent",children:A?"Continuing…":"继续一轮"}),e.jsx("button",{type:"button",disabled:!se||d,onClick:U,title:"合并 PR 并收尾(删本地分支 + 压缩上下文)",className:"btn-secondary !border-[#bbf7d0] !text-success hover:!bg-[#dcfce7] hover:!border-success",children:d?"Completing…":"标记完成"})]}),ee&&e.jsx("button",{type:"button",disabled:d,onClick:F,title:"确认完成;merge:auto 时由 baxian 执行合并",className:"btn-secondary !border-[#bbf7d0] !text-success hover:!bg-[#dcfce7] hover:!border-success",children:d?"Confirming…":"确认"}),B&&e.jsx("button",{type:"button",disabled:d,onClick:F,title:"发布派发失败后重试 push/PR 步骤",className:"btn-secondary !border-accent-soft !text-accent hover:!bg-accent-soft hover:!border-accent",children:d?"Retrying…":"重试发布"})]})}}function Gt({taskId:t}){var i;const[s,n]=a.useState(null);if(a.useEffect(()=>{let l=!0;return $.tasks.reviews(t).then(u=>{l&&n(u)}).catch(()=>{l&&n([])}),()=>{l=!1}},[t]),!s||s.length===0)return null;const o=s[s.length-1],r=s.reduce((l,u)=>{var h;return l+(((h=u.findings)==null?void 0:h.findings.length)??0)},0);return e.jsxs("div",{className:"mt-2 text-[12px] text-og-700",children:["Review ",s.length," 轮 · 最终 verdict ",e.jsx("span",{className:"font-mono",children:((i=o.findings)==null?void 0:i.verdict)??"—"})," ","· findings 共 ",r," 条"]})}const ct="baxian:terminal-activated";function ps({group:t,projectId:s,agentsById:n,agentsLoaded:o,agentsError:r=!1,tasks:i,onDeleted:l,terminalMode:u="activity-preview"}){var K,P,L;const h=t.find(E=>E.role==="dev")??t[0],x=t.find(E=>E.role==="qa"),v=i.filter(E=>Yn(E,h==null?void 0:h.id,x==null?void 0:x.id)),p=h?i.filter(E=>Xn(E,s,h.id)).sort((E,I)=>E.createdAt.localeCompare(I.createdAt)):[],d=h?n.get(h.id):void 0,y=!!d&&d.runtimeStatus==="idle"&&((K=d.binding)==null?void 0:K.status)!=="awaiting_human"&&!((P=d.binding)!=null&&P.creationToken)&&!((L=d.binding)!=null&&L.taskId),A=`Agent group ${t.map(E=>E.id).join(" / ")}`,{openTask:m}=Le(),b=u==="embedded-full",S=a.useId(),[M,f]=a.useState(null);a.useEffect(()=>{if(!b)return;const E=U=>{U.composedPath().some(G=>G instanceof Element&&G.hasAttribute("data-agent-card"))||f(null)},I=U=>{if(U.key!=="Escape")return;const _=document.activeElement;_ instanceof Element&&_.closest("[data-agent-card]")||f(null)},z=U=>{const _=U.detail;(_==null?void 0:_.groupId)!==S&&f(null)};return document.addEventListener("click",E),document.addEventListener("keydown",I),document.addEventListener(ct,z),()=>{document.removeEventListener("click",E),document.removeEventListener("keydown",I),document.removeEventListener(ct,z)}},[b,S]);const N=E=>{f(E),document.dispatchEvent(new CustomEvent(ct,{detail:{groupId:S}}))},w=u==="embedded-full"?t.length<=1?"lg:grid-cols-1":t.length===2?"lg:grid-cols-2":t.length===3?"lg:grid-cols-3":"lg:grid-cols-4":"sm:grid-cols-2",c=!!h&&p.length>0,W=v.length===0&&!c;return e.jsxs("div",{role:"group","aria-label":A,className:"min-w-0",children:[c&&h&&e.jsx(Jn,{tasks:p,devId:h.id,dispatchReady:y,label:A}),v.length>0&&e.jsx("div",{className:"card mb-2 max-h-28 overflow-y-auto divide-y divide-hairline",children:v.map(E=>{const I=E.phase==="spec"?E.specReviewRound??0:E.reviewRound;return e.jsxs("button",{type:"button",onClick:()=>m(E.id),className:"flex w-full items-center gap-3 px-3 py-2 text-left text-[13px] transition-colors hover:bg-og-50/60",children:[e.jsxs("div",{className:"min-w-0 flex-1 flex items-center gap-2",children:[e.jsx("span",{className:"shrink-0 font-mono text-[11px] text-og-500",title:E.id,children:Nt(E.id)}),e.jsx("span",{className:"truncate text-og-1000",children:E.title})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.jsxs("span",{className:"shrink-0 text-[12px] text-og-500",children:["Round ",I]}),e.jsx("span",{className:`${xs[E.status]} shrink-0`,children:E.status})]})]},E.id)})}),W&&e.jsx("div",{className:"mb-2 rounded-lg border border-hairline bg-surface px-3 py-2 text-[13px] text-og-400","aria-label":`${A} no active task`,children:"暂无任务"}),e.jsx("div",{className:`grid grid-cols-1 ${w} gap-4`,children:t.map(E=>{const I=n.get(E.id),z=I??{id:E.id,projectId:s,runtimeStatus:"unknown",tmuxSessionStatus:"unknown",stale:!0};return e.jsx(Pn,{agent:z,projectId:s,role:E.role,runtime:E.runtime,pendingRestart:o&&!I,terminalLoading:!o&&!I&&!r,onDeleted:l,showTaskBinding:!1,terminalMode:u,...b?{active:M===E.id,onActivate:()=>N(E.id)}:{}},E.id)})})]})}function Jn({tasks:t,devId:s,dispatchReady:n,label:o}){const{show:r}=he(),{openTask:i}=Le(),[l,u]=a.useState(null),h=async x=>{u(x);try{await $.tasks.dispatch(x,{agentId:s}),r({kind:"success",title:`Task ${x} 已派给 ${s}`})}catch(v){r({kind:"error",title:"派遣失败",body:v instanceof Error?v.message:String(v)})}finally{u(null)}};return e.jsx("div",{role:"group",className:"card mb-2 max-h-28 overflow-y-auto divide-y divide-hairline","aria-label":`${o} claimable tasks for ${s}`,children:t.map(x=>{const v=x.preferredAgentId==="",p=l!==null;return e.jsxs("div",{className:"flex items-center gap-3 px-3 py-2 text-[13px]",children:[e.jsxs("button",{type:"button",onClick:()=>i(x.id),className:"min-w-0 flex-1 flex items-center gap-2 text-left transition-colors hover:text-accent-hover",children:[e.jsx("span",{className:"shrink-0 font-mono text-[11px] text-og-500",title:x.id,children:Nt(x.id)}),e.jsx("span",{className:"truncate text-og-1000",title:x.title,children:x.title}),v&&e.jsx("span",{className:"pill shrink-0",children:"未分配"})]}),e.jsx("button",{type:"button",onClick:()=>void h(x.id),disabled:!n||p,title:n?`派给 ${s} 并立即开始`:"Dev 当前不可派遣",className:"shrink-0 text-[13px] font-medium text-accent transition-colors hover:text-accent-hover disabled:opacity-50 disabled:cursor-not-allowed",children:l===x.id?"Starting…":"Start"})]},x.id)})})}function Yn(t,s,n){return!(!s||!ns.has(t.status)||!(t.agentId===s||t.preferredAgentId===s)||n&&t.qaAgentId&&t.qaAgentId!==n)}function Xn(t,s,n){return t.projectId!==s||t.status!=="pending"?!1:t.preferredAgentId===n||t.preferredAgentId===""}const Zn=/^[a-z][a-z0-9-]{1,31}$/,er=[/^https?:\/\/[^/\s]+\/[^\s]+$/,/^ssh:\/\/[^/\s]+\/[^\s]+$/,/^[^@/\s]+@[^:/\s]+:[^\s]+$/,/^[^/\s:@]+\/[^/\s]+$/],Qt="w-full rounded-md border border-og-100 bg-surface px-2.5 py-1.5 text-[13px] text-og-800 placeholder:text-og-400 focus:border-accent focus:outline-none focus:ring-[3px] focus:ring-accent-soft disabled:cursor-not-allowed disabled:opacity-50",We="mb-1.5 block text-[12px] font-medium text-og-700",qt="mt-1 text-[12px] text-danger";function tr({open:t,onClose:s,onCreated:n}){const[o,r]=a.useState(""),[i,l]=a.useState(""),[u,h]=a.useState(null),[x,v]=a.useState(""),[p,d]=a.useState(!1),[y,A]=a.useState(null),[m,b]=a.useState({}),[S,M]=a.useState(new Set),f=a.useRef(0),{show:N}=he(),{flagDirty:w}=Xe();a.useEffect(()=>{if(!t)return;f.current+=1;const P=f.current;r(""),l(""),h(null),v(""),A(null),b({}),M(new Set),$.config.get().then(L=>{P===f.current&&M(new Set(L.project.map(E=>E.id)))}).catch(()=>{})},[t]);const c=()=>{p||s()},W=()=>{const P={};return o?Zn.test(o)?S.has(o)&&(P.id="该 id 已被占用"):P.id="小写字母开头,只含 a-z 0-9 -,长度 2-32":P.id="必填",i?er.some(L=>L.test(i.trim()))||(P.repo="需为 git URL(https / ssh / scp,如 https://gitlab.example.com/group/proj.git)或 owner/repo"):P.repo="必填",b(P),Object.keys(P).length===0},K=async P=>{if(P.preventDefault(),!!W()){d(!0),A(null);try{const L=await $.projects.create({id:o,repo:i.trim(),merge:u,...x?{review:{mode:x}}:{}});L.restartRequired&&w(),N({kind:"success",title:`项目 ${L.project.id} 已创建`}),n(L.project.id)}catch(L){A(L instanceof Error?L.message:String(L))}finally{d(!1)}}};return e.jsx(ve,{open:t,onClose:c,title:"新建项目",size:"md",footer:e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:c,disabled:p,className:"btn-secondary",children:"取消"}),e.jsx("button",{type:"submit",form:"create-project-form",disabled:p,className:"btn-primary",children:p?"创建中…":"创建"})]}),children:e.jsxs("form",{id:"create-project-form",onSubmit:K,className:"space-y-3",children:[y&&e.jsx("div",{className:"rounded-md border border-[#fecaca] bg-[#fef2f2] px-3 py-2 text-[13px] text-danger",children:y}),e.jsxs("div",{children:[e.jsx("label",{className:We,htmlFor:"proj-id",children:"项目 ID"}),e.jsx("input",{id:"proj-id",type:"text",value:o,onChange:P=>r(P.target.value),className:Qt,placeholder:"kongkong",disabled:p}),m.id&&e.jsx("div",{className:qt,children:m.id})]}),e.jsxs("div",{children:[e.jsx("label",{className:We,htmlFor:"proj-repo",children:"Git 仓库地址"}),e.jsx("input",{id:"proj-repo",type:"text",value:i,onChange:P=>l(P.target.value),className:Qt,placeholder:"https://github.com/baxian-ai/baxian.git",disabled:p}),m.repo&&e.jsx("div",{className:qt,children:m.repo})]}),e.jsxs("div",{children:[e.jsx("span",{className:We,children:"合并策略"}),e.jsxs("label",{className:"mb-1 flex items-center gap-2",children:[e.jsx("input",{type:"radio",name:"merge",checked:u===null,onChange:()=>h(null),disabled:p,className:"h-3.5 w-3.5 accent-[#1348dc]"}),e.jsx("span",{className:"text-[13px] text-og-800",children:"人类合并(默认)"})]}),e.jsxs("label",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"radio",name:"merge",checked:u==="auto",onChange:()=>h("auto"),disabled:p,className:"h-3.5 w-3.5 accent-[#1348dc]"}),e.jsx("span",{className:"text-[13px] text-og-800",children:"QA Approve 后自动合并"})]})]}),e.jsxs("div",{children:[e.jsx("span",{className:We,children:"Review 模式"}),e.jsxs("label",{className:"mb-1 flex items-center gap-2",children:[e.jsx("input",{type:"radio",name:"review-mode",checked:x==="",onChange:()=>v(""),disabled:p,className:"h-3.5 w-3.5 accent-[#1348dc]"}),e.jsx("span",{className:"text-[13px] text-og-800",children:"跟随全局"})]}),e.jsxs("label",{className:"mb-1 flex items-center gap-2",children:[e.jsx("input",{type:"radio",name:"review-mode",checked:x==="github",onChange:()=>v("github"),disabled:p,className:"h-3.5 w-3.5 accent-[#1348dc]"}),e.jsx("span",{className:"text-[13px] text-og-800",children:"GitHub PR"})]}),e.jsxs("label",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"radio",name:"review-mode",checked:x==="server",onChange:()=>v("server"),disabled:p,className:"h-3.5 w-3.5 accent-[#1348dc]"}),e.jsx("span",{className:"text-[13px] text-og-800",children:"Server"})]})]})]})})}const Kt=/^[a-z][a-z0-9-]{1,31}$/,sr=500,Se="w-full rounded-md border border-og-100 bg-surface px-2.5 py-1.5 text-[13px] text-og-800 placeholder:text-og-400 focus:border-accent focus:outline-none focus:ring-[3px] focus:ring-accent-soft disabled:cursor-not-allowed disabled:opacity-50",ge="mb-1.5 block text-[12px] font-medium text-og-700",Vt="mt-1 text-[12px] text-danger",lt="mt-1 text-[12px] text-og-500",Ee="h-3.5 w-3.5 accent-[#1348dc]",Jt={id:"",role:"dev",pairWith:"",mode:"local",host:"",runtime:"",workdir:"",yolo:!0,model:"",addDirs:""};function nr(t){return t.alias?t.alias:`${t.user?`${t.user}@`:""}${t.hostname}${t.port!=null?`:${t.port}`:""}`}function gs({open:t,onClose:s,projectId:n,onCreated:o}){var ee;const[r,i]=a.useState(Jt),[l,u]=a.useState(null),[h,x]=a.useState([]),[v,p]=a.useState(new Set),[d,y]=a.useState(null),[A,m]=a.useState(!1),[b,S]=a.useState(!1),[M,f]=a.useState(null),N=a.useRef(null),w=a.useRef(null),c=a.useRef(0),{show:W}=he(),{flagDirty:K}=Xe();a.useEffect(()=>{if(!t)return;c.current+=1;const R=c.current;i(Jt),u(null),x([]),p(new Set),y(null),m(!1),f(null),$.config.get().then(Q=>{if(R!==c.current)return;const Y=Q.project.find(O=>O.id===n)??null;u(Y),x(Q.host??[]);const ce=new Set;Q.project.forEach(O=>O.agent.forEach(te=>te.forEach(se=>ce.add(se.id)))),p(ce)}).catch(()=>{})},[t,n]);const P=()=>{b||s()},L=a.useCallback(()=>{N.current&&N.current.abort();const R=new AbortController;N.current=R,m(!0),f(null);const Q=r.mode==="remote"?{hostId:r.host}:{};$.agents.probe(r.mode,Q,{signal:R.signal}).then(Y=>{R.signal.aborted||(y(Y),f(null))}).catch(Y=>{R.signal.aborted||(y(null),f(Y instanceof Error?Y.message:String(Y)))}).finally(()=>{N.current===R&&m(!1)})},[r.mode,r.host]);a.useEffect(()=>{if(t&&(y(null),N.current&&N.current.abort(),!(r.mode==="remote"&&!r.host)))return w.current&&clearTimeout(w.current),w.current=setTimeout(L,sr),()=>{w.current&&clearTimeout(w.current)}},[t,r.mode,r.host,L]),a.useEffect(()=>{t||N.current&&N.current.abort()},[t]),a.useEffect(()=>()=>{N.current&&N.current.abort(),w.current&&clearTimeout(w.current)},[]);const E=(l==null?void 0:l.agent.filter(R=>R.length===1&&R[0].role==="dev").map(R=>R[0]))??[],I=E.length>0,z=Kt.test(r.id)&&!v.has(r.id),U=r.mode==="local"||r.mode==="remote"&&r.host!=="",_=r.runtime!==""&&(r.runtime==="claude-code"?!!(d!=null&&d.runtimes["claude-code"].ok):!!(d!=null&&d.runtimes.codex.ok)),F=!!(d!=null&&d.tmux.ok),G=r.mode==="local"||!!((ee=d==null?void 0:d.ssh)!=null&&ee.ok),oe=r.role==="dev"||r.role==="qa"&&r.pairWith!=="",j=!b&&z&&U&&oe&&_&&F&&G,g=async R=>{if(R.preventDefault(),!!j){S(!0),f(null);try{const Q=r.addDirs.split(`
|
|
2
|
+
`).map(O=>O.trim()).filter(O=>O.length>0),Y={id:r.id,role:r.role,runtime:r.runtime,mode:r.mode,...r.mode==="remote"?{host:r.host}:{},...r.workdir?{workdir:r.workdir}:{},yolo:r.yolo,...r.model.trim()?{model:r.model.trim()}:{},...Q.length>0?{addDirs:Q}:{},...r.role==="qa"?{pairWith:r.pairWith}:{}},ce=await $.projects.addAgent(n,Y);ce.restartRequired&&K(),W({kind:"success",title:`Agent ${ce.agent.id} 已添加到 ${n}`}),o(),s()}catch(Q){f(Q instanceof Error?Q.message:String(Q))}finally{S(!1)}}},q=({rt:R})=>{if(r.mode==="remote"&&!r.host)return e.jsx("span",{className:"ml-2 text-[12px] text-og-400",children:"(请先选择 Host)"});if(A)return e.jsx("span",{className:"ml-2 text-[12px] text-og-400",children:"…探测中"});if(!d)return e.jsx("span",{className:"ml-2 text-[12px] text-og-400",children:"?"});const Y=d.runtimes[R];return Y.ok?e.jsxs("span",{className:"ml-2 text-[12px] text-success",children:["✓ ",Y.path??""]}):e.jsxs("span",{className:"ml-2 text-[12px] text-danger",title:Y.message,children:["⨯ ",Y.message]})},J=()=>r.mode==="remote"&&!r.host?null:A?e.jsx("div",{className:"text-[12px] text-og-400",children:"tmux: …探测中"}):d?d.tmux.ok?e.jsxs("div",{className:"text-[12px] text-success",children:["tmux: ✓ ",d.tmux.path??""]}):e.jsxs("div",{className:"text-[12px] text-danger",children:["tmux: ⨯ ",d.tmux.message]}):null,V=()=>r.mode!=="remote"||!r.host||!(d!=null&&d.ssh)?null:d.ssh.ok?e.jsxs("div",{className:"text-[12px] text-success",children:["SSH: ✓ ",d.ssh.message]}):e.jsxs("div",{className:"text-[12px] text-danger",children:["SSH: ⨯ ",d.ssh.message]});return e.jsx(ve,{open:t,onClose:P,title:`添加 Agent 到 ${n}`,size:"lg",footer:e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:P,disabled:b,className:"btn-secondary",children:"取消"}),e.jsx("button",{type:"submit",form:"create-agent-form",disabled:!j,className:"btn-primary",children:b?"添加中…":"添加 Agent"})]}),children:e.jsxs("form",{id:"create-agent-form",onSubmit:g,className:"space-y-3",children:[M&&e.jsx("div",{className:"rounded-md border border-[#fecaca] bg-[#fef2f2] px-3 py-2 text-[13px] text-danger",children:M}),e.jsxs("div",{children:[e.jsx("label",{className:ge,htmlFor:"agent-id",children:"Agent ID"}),e.jsx("input",{id:"agent-id",type:"text",value:r.id,onChange:R=>i({...r,id:R.target.value}),className:Se,placeholder:"kk-cc",disabled:b}),r.id&&!Kt.test(r.id)&&e.jsx("div",{className:Vt,children:"小写字母开头,只含 a-z 0-9 -,长度 2-32"}),r.id&&v.has(r.id)&&e.jsx("div",{className:Vt,children:"该 id 已被占用(全局唯一)"})]}),e.jsxs("div",{children:[e.jsx("span",{className:ge,children:"角色"}),e.jsxs("label",{className:"mr-4 inline-flex items-center gap-2",children:[e.jsx("input",{type:"radio",name:"role",checked:r.role==="dev",className:Ee,onChange:()=>i({...r,role:"dev",pairWith:""}),disabled:b}),e.jsx("span",{className:"text-[13px] text-og-800",children:"Dev"})]}),e.jsxs("label",{className:"inline-flex items-center gap-2",title:I?"":"请先创建一个 Dev Agent",children:[e.jsx("input",{type:"radio",name:"role",checked:r.role==="qa",className:Ee,onChange:()=>i({...r,role:"qa"}),disabled:b||!I}),e.jsx("span",{className:`text-[13px] ${I?"text-og-800":"text-og-400"}`,children:"QA"})]})]}),r.role==="qa"&&e.jsxs("div",{children:[e.jsx("label",{className:ge,htmlFor:"pair-with",children:"配对 Dev Agent"}),e.jsxs("select",{id:"pair-with",value:r.pairWith,onChange:R=>i({...r,pairWith:R.target.value}),className:Se,disabled:b,children:[e.jsx("option",{value:"",children:"请选择"}),E.map(R=>e.jsxs("option",{value:R.id,children:[R.id," (dev, ",R.mode,")"]},R.id))]})]}),e.jsxs("div",{children:[e.jsx("span",{className:ge,children:"运行模式"}),e.jsxs("label",{className:"mr-4 inline-flex items-center gap-2",children:[e.jsx("input",{type:"radio",name:"mode",checked:r.mode==="local",className:Ee,onChange:()=>i({...r,mode:"local",host:""}),disabled:b}),e.jsx("span",{className:"text-[13px] text-og-800",children:"本机"})]}),e.jsxs("label",{className:"inline-flex items-center gap-2",children:[e.jsx("input",{type:"radio",name:"mode",checked:r.mode==="remote",className:Ee,onChange:()=>i({...r,mode:"remote"}),disabled:b}),e.jsx("span",{className:"text-[13px] text-og-800",children:"远程 (SSH)"})]})]}),r.mode==="remote"&&e.jsxs("div",{children:[e.jsx("label",{className:ge,htmlFor:"host",children:"Host"}),h.length===0?e.jsx("div",{className:"rounded-md border border-og-100 bg-og-50/40 px-3 py-2 text-[12px] text-og-600",children:"还没有配置 Host。请先在右上角菜单的「Host 管理」中添加。"}):e.jsxs("select",{id:"host",value:r.host,onChange:R=>i({...r,host:R.target.value}),className:Se,disabled:b,children:[e.jsx("option",{value:"",children:"请选择 Host"}),h.map(R=>e.jsx("option",{value:R.id,children:nr(R)},R.id))]}),e.jsx("div",{className:lt,children:"私钥/跳板机仍可在 ~/.ssh/config 配置;端口/密码在「Host 管理」里设置。"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1.5 flex items-center justify-between",children:[e.jsx("span",{className:"text-[12px] font-medium text-og-700",children:"运行时"}),e.jsx("button",{type:"button",onClick:L,className:"text-[12px] text-accent transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",disabled:b||A||r.mode==="remote"&&!r.host,children:"↻ 重新探测"})]}),e.jsxs("label",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"radio",name:"runtime",checked:r.runtime==="claude-code",className:Ee,onChange:()=>i({...r,runtime:"claude-code"}),disabled:b||(d?!d.runtimes["claude-code"].ok:!1)}),e.jsx("span",{className:"text-[13px] text-og-800",children:"Claude Code"}),e.jsx(q,{rt:"claude-code"})]}),e.jsxs("label",{className:"mt-1 flex items-center gap-2",children:[e.jsx("input",{type:"radio",name:"runtime",checked:r.runtime==="codex",className:Ee,onChange:()=>i({...r,runtime:"codex"}),disabled:b||(d?!d.runtimes.codex.ok:!1)}),e.jsx("span",{className:"text-[13px] text-og-800",children:"Codex"}),e.jsx(q,{rt:"codex"})]}),e.jsx("div",{className:"mt-2",children:e.jsx(J,{})}),e.jsx("div",{children:e.jsx(V,{})})]}),e.jsxs("div",{children:[e.jsx("label",{className:ge,htmlFor:"workdir",children:"Workdir(可选)"}),e.jsx("input",{id:"workdir",type:"text",value:r.workdir,onChange:R=>i({...r,workdir:R.target.value}),className:Se,placeholder:"留空时自动 clone 到 ~/.baxian/repos/<owner>/<repo>",disabled:b})]}),e.jsxs("div",{children:[e.jsx("label",{className:ge,htmlFor:"model",children:"Model(可选)"}),e.jsx("input",{id:"model",type:"text",value:r.model,onChange:R=>i({...r,model:R.target.value}),className:Se,placeholder:r.runtime==="codex"?"例: o3 / gpt-4o(留空走 default)":"例: sonnet / opus / claude-sonnet-4-6(留空走 default)",disabled:b}),e.jsx("div",{className:lt,children:"透传到 launch 命令的 --model 参数;留空跟随 CLI 默认。"})]}),e.jsxs("div",{children:[e.jsx("label",{className:ge,htmlFor:"addDirs",children:"Additional Dirs(可选)"}),e.jsx("textarea",{id:"addDirs",value:r.addDirs,onChange:R=>i({...r,addDirs:R.target.value}),className:`${Se} font-mono text-[12px]`,rows:3,placeholder:`每行一个绝对路径,例:
|
|
3
|
+
/Users/me/shared-libs
|
|
4
|
+
/Users/me/extra-repo`,disabled:b}),e.jsx("div",{className:lt,children:"透传到 --add-dir。当前 YOLO 模式下不影响权限拦截,主要用于让 CLI 把额外目录纳入工作根。"})]}),e.jsx("div",{className:"rounded-md border border-[#fde68a] bg-[#fef3c7]/60 px-3 py-2.5",children:e.jsxs("label",{className:"flex cursor-pointer items-start gap-2",children:[e.jsx("input",{type:"checkbox",className:"mt-1 h-3.5 w-3.5 accent-[#1348dc]",checked:r.yolo,onChange:R=>i({...r,yolo:R.target.checked}),disabled:b}),e.jsxs("div",{className:"text-[13px] text-og-800",children:[e.jsx("div",{className:"font-medium",children:"YOLO 模式(推荐开启)"}),e.jsxs("div",{className:"mt-1 text-[12px] text-warn",children:["Agent 自主执行所有命令、文件改动,无需逐条确认。开启后体验更顺滑, 但",e.jsx("strong",{className:"font-semibold",children:"请确认在受控环境(容器、隔离 worktree)中运行"}),"。"]})]})]})})]})})}const Yt="***",Pe="w-full rounded-md border border-og-100 bg-surface px-2.5 py-1.5 text-[13px] text-og-800 placeholder:text-og-400 focus:border-accent focus:outline-none focus:ring-[3px] focus:ring-accent-soft disabled:cursor-not-allowed disabled:opacity-50",$e="mb-1.5 block text-[12px] font-medium text-og-700",dt={hostname:"",port:"",alias:"",user:"",password:""};function rr(t){return t.alias?t.alias:`${t.user?`${t.user}@`:""}${t.hostname}${t.port!=null?`:${t.port}`:""}`}function or({open:t,onClose:s}){const[n,o]=a.useState([]),[r,i]=a.useState("list"),[l,u]=a.useState(null),[h,x]=a.useState(!1),[v,p]=a.useState(!1),[d,y]=a.useState(dt),[A,m]=a.useState(null),[b,S]=a.useState(!1),[M,f]=a.useState(!1),[N,w]=a.useState(null),{show:c}=he(),W=a.useCallback(()=>{$.hosts.list().then(o).catch(j=>m(j instanceof Error?j.message:String(j)))},[]);a.useEffect(()=>{t&&(i("list"),u(null),y(dt),m(null),w(null),W())},[t,W]);const K=()=>{u(null),x(!1),p(!1),y(dt),m(null),w(null),i("form")},P=j=>{u(j.id??null),x(j.password===Yt),p(!1),y({hostname:j.hostname,port:j.port!=null?String(j.port):"",alias:j.alias??"",user:j.user??"",password:""}),m(null),w(null),i("form")},L=()=>{const j={hostname:d.hostname.trim()};return l?(j.port=d.port.trim()?Number(d.port):null,j.alias=d.alias.trim(),j.user=d.user.trim()):(d.port.trim()&&(j.port=Number(d.port)),d.alias.trim()&&(j.alias=d.alias.trim()),d.user.trim()&&(j.user=d.user.trim())),l&&v?j.password="":d.password&&(j.password=d.password),j},E=d.port.trim(),I=E===""||/^\d+$/.test(E)&&Number(E)>0&&Number(E)<=65535,z=d.hostname.trim().length>0&&I,U=async()=>{if(z){f(!0),w(null),m(null);try{const j=await $.hosts.check({...L(),...l?{id:l}:{}});w(j)}catch(j){m(j instanceof Error?j.message:String(j))}finally{f(!1)}}},_=async j=>{if(j.preventDefault(),!(!z||b)){S(!0),m(null);try{if(l)await $.hosts.update(l,L()),c({kind:"success",title:`Host ${l} 已更新`});else{const g=await $.hosts.create(L());c({kind:"success",title:`Host ${g.host.id} 已添加`})}W(),i("list")}catch(g){m(g instanceof Error?g.message:String(g))}finally{S(!1)}}},F=async j=>{m(null);try{await $.hosts.delete(j.id),c({kind:"success",title:`Host ${j.id} 已删除`}),W()}catch(g){m(g instanceof Error?g.message:String(g))}},G=e.jsx("button",{type:"button",onClick:s,className:"btn-secondary",children:"关闭"}),oe=e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:()=>i("list"),disabled:b,className:"btn-secondary",children:"返回"}),e.jsx("button",{type:"submit",form:"host-form",disabled:!z||b,className:"btn-primary",children:b?"保存中…":"保存"})]});return e.jsxs(ve,{open:t,onClose:s,title:"Host 管理",size:"md",footer:r==="list"?G:oe,children:[A&&e.jsx("div",{className:"mb-3 rounded-md border border-[#fecaca] bg-[#fef2f2] px-3 py-2 text-[13px] text-danger",children:A}),r==="list"?e.jsxs("div",{className:"space-y-3",children:[n.length===0?e.jsx("p",{className:"text-[13px] text-og-500",children:"还没有配置 Host。点击下方「添加 Host」。"}):e.jsx("ul",{className:"space-y-1.5",children:n.map(j=>e.jsxs("li",{className:"flex items-center justify-between gap-3 rounded-md border border-og-100 px-3 py-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-[13px] font-medium text-og-800",children:rr(j)}),e.jsxs("div",{className:"truncate text-[12px] text-og-500",children:[(j.user?`${j.user}@`:"")+j.hostname,j.port!=null?`:${j.port}`:"",j.password===Yt?" · 密码已保存":""]})]}),e.jsxs("div",{className:"flex shrink-0 gap-2",children:[e.jsx("button",{type:"button",onClick:()=>P(j),className:"text-[12px] text-accent transition-colors hover:text-accent-hover",children:"编辑"}),e.jsx("button",{type:"button",onClick:()=>F(j),className:"text-[12px] text-danger transition-colors hover:opacity-80",children:"删除"})]})]},j.id))}),e.jsx("button",{type:"button",onClick:K,className:"btn-secondary w-full",children:"+ 添加 Host"})]}):e.jsxs("form",{id:"host-form",onSubmit:_,className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:$e,htmlFor:"host-hostname",children:"Host 地址"}),e.jsx("input",{id:"host-hostname",type:"text",value:d.hostname,onChange:j=>y({...d,hostname:j.target.value}),className:Pe,placeholder:"remote.example.com",disabled:b})]}),e.jsxs("div",{children:[e.jsx("label",{className:$e,htmlFor:"host-port",children:"端口(可选)"}),e.jsx("input",{id:"host-port",type:"text",inputMode:"numeric",value:d.port,onChange:j=>y({...d,port:j.target.value}),className:Pe,placeholder:"22",disabled:b}),d.port.trim()!==""&&!I&&e.jsx("div",{className:"mt-1 text-[12px] text-danger",children:"端口需为 1–65535 的整数"})]}),e.jsxs("div",{children:[e.jsx("label",{className:$e,htmlFor:"host-alias",children:"别名(可选)"}),e.jsx("input",{id:"host-alias",type:"text",value:d.alias,onChange:j=>y({...d,alias:j.target.value}),className:Pe,placeholder:"Prod worker",disabled:b})]}),e.jsxs("div",{children:[e.jsx("label",{className:$e,htmlFor:"host-user",children:"用户名(可选)"}),e.jsx("input",{id:"host-user",type:"text",value:d.user,onChange:j=>y({...d,user:j.target.value}),className:Pe,placeholder:"留空则读 ~/.ssh/config 的 User",disabled:b})]}),e.jsxs("div",{children:[e.jsx("label",{className:$e,htmlFor:"host-password",children:"密码(可选)"}),e.jsx("input",{id:"host-password",type:"password",value:v?"":d.password,onChange:j=>y({...d,password:j.target.value}),className:Pe,placeholder:h?"已设置,留空保持不变":"留空使用 key 认证",disabled:b||v,autoComplete:"new-password"}),l&&h&&e.jsxs("label",{className:"mt-1.5 flex items-center gap-2 text-[12px] text-og-700",children:[e.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 accent-[#1348dc]",checked:v,onChange:j=>p(j.target.checked),disabled:b}),"清除已保存的密码(改用 key 登录)"]})]}),e.jsxs("div",{className:"rounded-md border border-[#fde68a] bg-[#fef3c7]/60 px-3 py-2.5 text-[12px] text-warn",children:["建议为该 Host 配置好",e.jsx("strong",{className:"font-semibold",children:"免密码登入(SSH key)"}),"。 否则填写的密码将以",e.jsx("strong",{className:"font-semibold",children:"明文"}),"保存到 baxian.json 中。"]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("button",{type:"button",onClick:U,disabled:!z||M||b,className:"text-[12px] text-accent transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",children:M?"测试中…":"测试连接"}),N&&e.jsxs("span",{className:`text-[12px] ${N.ok?"text-success":"text-danger"}`,children:[N.ok?"✓ ":"⨯ ",N.message]})]})]})]})}const bs="topbar-actions";function Xt(){return typeof document>"u"?null:document.getElementById(bs)}function vs({children:t}){const[s,n]=a.useState(Xt);return a.useEffect(()=>{s||n(Xt())},[s]),s?ks.createPortal(t,s):null}function ar(){const{openTask:t}=Le(),{projects:s,error:n,refresh:o}=Ze(),r=s??[],i=s!==null,[l,u]=a.useState(!1),[h,x]=a.useState(!1),[v,p]=a.useState(!1),[d,y]=a.useState({kind:"closed"}),{data:A,loaded:m,error:b}=us(),S=(b==null?void 0:b.message)??null,M=new Map((A??[]).map(I=>[I.id,I])),f=n??S,[N,w]=a.useState(!1),c=a.useRef(null),W=a.useRef(null),K=a.useId(),P=a.useId();a.useEffect(()=>{if(!N)return;const I=U=>{var F,G;const _=U.target;_&&((F=W.current)!=null&&F.contains(_)||(G=c.current)!=null&&G.contains(_)||w(!1))},z=U=>{var _;U.key==="Escape"&&(w(!1),(_=c.current)==null||_.focus())};return document.addEventListener("mousedown",I),document.addEventListener("keydown",z),()=>{document.removeEventListener("mousedown",I),document.removeEventListener("keydown",z)}},[N]);const L=r.length===0,E=e.jsx("button",{type:"button",onClick:()=>x(!0),disabled:L,"aria-describedby":L?"create-task-hint":void 0,className:"btn-ghost",children:"+ 新建 Task"});return e.jsxs("div",{children:[e.jsxs(vs,{children:[L?e.jsx("span",{className:"inline-flex",title:"请先创建项目",children:E}):E,L&&e.jsx("span",{id:"create-task-hint",className:"sr-only",children:"请先创建项目"}),e.jsxs("div",{className:"relative",children:[e.jsx("button",{ref:c,id:P,type:"button",onClick:()=>w(I=>!I),"aria-haspopup":"menu","aria-expanded":N,"aria-controls":K,"aria-label":"更多操作",className:"flex h-8 w-8 items-center justify-center rounded text-og-500 transition-colors hover:bg-og-100 hover:text-og-1000",children:e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("circle",{cx:"12",cy:"12",r:"1"}),e.jsx("circle",{cx:"12",cy:"5",r:"1"}),e.jsx("circle",{cx:"12",cy:"19",r:"1"})]})}),N&&e.jsxs("div",{ref:W,id:K,role:"menu","aria-labelledby":P,className:"absolute right-0 top-full z-10 mt-1 min-w-[140px] rounded-md border border-hairline bg-surface py-1 shadow-md",children:[e.jsx("button",{type:"button",role:"menuitem",onClick:()=>{w(!1),u(!0)},className:"block w-full px-3 py-1.5 text-left text-[13px] text-og-800 hover:text-og-1000",children:"新建项目"}),e.jsx("button",{type:"button",role:"menuitem",onClick:()=>{w(!1),p(!0)},className:"block w-full px-3 py-1.5 text-left text-[13px] text-og-800 hover:text-og-1000",children:"Host 管理"})]})]})]}),e.jsx("h1",{className:"sr-only",children:"Dashboard"}),f&&e.jsxs("div",{className:"mb-4 text-[13px] text-danger",children:["Error: ",f]}),i&&r.length===0&&!n&&e.jsx("div",{className:"rounded-lg border border-hairline bg-surface py-12 text-center text-[13px] text-og-500",children:'还没有项目。点击右上角"更多"菜单 → "新建项目"开始。'}),r.map(I=>e.jsx(ir,{project:I,agentsById:M,agentsLoaded:m,agentsError:!!b,onAgentDeleted:o},I.id)),e.jsx(tr,{open:l,onClose:()=>u(!1),onCreated:I=>{u(!1),o(),y({kind:"asking",projectId:I})}}),e.jsx(or,{open:v,onClose:()=>p(!1)}),e.jsx(ve,{open:d.kind==="asking",onClose:()=>y({kind:"closed"}),title:"项目已创建",size:"sm",footer:e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:()=>y({kind:"closed"}),className:"btn-secondary",children:"稍后再加"}),e.jsx("button",{type:"button",onClick:()=>{d.kind==="asking"&&y({kind:"addingAgent",projectId:d.projectId})},className:"btn-primary",children:"继续添加 Agent"})]}),children:e.jsx("p",{className:"text-[13px] text-og-700",children:"现在添加第一个 Agent,还是稍后再加?"})}),d.kind==="addingAgent"&&e.jsx(gs,{open:!0,projectId:d.projectId,onClose:()=>y({kind:"closed"}),onCreated:()=>{o()}}),e.jsx(yt,{open:h,onClose:()=>x(!1),onCreated:I=>t(I.id)})]})}function ir({project:t,agentsById:s,agentsLoaded:n,agentsError:o,onAgentDeleted:r}){const{data:i,error:l}=fs(t.id),u=i??[],h=(l==null?void 0:l.message)??null;return e.jsxs("div",{className:"mb-10",children:[e.jsxs("div",{className:"mb-3 -mx-2 flex items-baseline gap-x-3 gap-y-1 px-2 py-1",children:[e.jsx("h2",{className:"min-w-0 truncate font-display text-[17px] font-semibold tracking-tight text-og-1000",title:t.id,children:e.jsx(Me,{to:`/project/${t.id}`,className:"hover:text-accent-hover",children:t.id})}),e.jsx("span",{className:"hidden min-w-0 truncate font-mono text-[12px] text-og-500 sm:inline-block",title:t.repo,children:t.repo}),e.jsx(Me,{to:`/project/${t.id}`,className:"ml-auto text-[13px] text-accent hover:text-accent-hover","aria-label":`Details — ${t.id}`,children:"Details →"})]}),h&&e.jsxs("div",{className:"mb-2 text-[12px] text-danger",children:["任务列表加载失败:",h]}),t.agent.flat().length===0?e.jsx("div",{className:"rounded-lg border border-hairline bg-surface py-6 text-center text-[13px] text-og-500",children:"还没有 Agent。进入 Details 添加。"}):e.jsx("div",{className:t.agent.length===1?"space-y-3":"grid grid-cols-1 gap-3 xl:grid-cols-2",children:t.agent.map((x,v)=>e.jsx(ps,{group:x,projectId:t.id,agentsById:s,agentsLoaded:n,agentsError:o,tasks:u,onDeleted:r,terminalMode:"embedded-full"},x.map(p=>p.id).join(":")||v))})]})}function Je(t){const s=t.match(/^task-(\d+)$/);return s?parseInt(s[1],10):Number.NaN}function cr(t,s){const n=Je(t.id),o=Je(s.id);return Number.isNaN(n)||Number.isNaN(o)?t.id.localeCompare(s.id):n-o}function lr(t,s){const n=(s.updatedAt??"").localeCompare(t.updatedAt??"");if(n!==0)return n;const o=Je(t.id),r=Je(s.id);return Number.isNaN(o)||Number.isNaN(r)?s.id.localeCompare(t.id):r-o}function Zt(t,s){const[n,o]=a.useState(tt);a.useEffect(()=>o(tt),[s]);const r=t.slice(0,n),i=t.length>r.length;return{items:r,hasMore:i,loadMore:()=>o(u=>u+tt),total:t.length}}function dr(t){const[s,n]=a.useState([]),[o,r]=a.useState(!1),[i,l]=a.useState(!1),[u,h]=a.useState(!1),[x,v]=a.useState(null),p=a.useRef(0),d=a.useRef(0),y=a.useCallback(A=>{const m=++p.current,b=A==="first"?0:d.current;l(!0),v(null),$.tasks.page(t,{category:"done",offset:b}).then(S=>{p.current===m&&(n(M=>A==="first"?S.tasks:[...M,...S.tasks]),r(S.hasMore),d.current=S.nextOffset,h(!0),l(!1))},S=>{p.current===m&&(v(S instanceof Error?S.message:String(S)),l(!1))})},[t]);return a.useEffect(()=>{p.current+=1,d.current=0,n([]),r(!1),h(!1),v(null),l(!1)},[t]),{items:s,hasMore:o,loading:i,loaded:u,error:x,load:y}}function ur({projectId:t,openTasks:s,className:n=""}){const o=a.useMemo(()=>s.filter(p=>ns.has(p.status)).sort(lr),[s]),r=a.useMemo(()=>s.filter(p=>p.status==="pending").sort(cr),[s]),i=Zt(o,t),l=Zt(r,t),u=dr(t),[h,x]=a.useState(!1);a.useEffect(()=>{x(!1)},[t]);const v=()=>{if(h){x(!1);return}x(!0),u.load("first")};return e.jsx("aside",{"aria-label":"Task 面板",className:`flex flex-col rounded-lg border border-hairline bg-surface ${n}`,children:e.jsxs("div",{children:[e.jsx(es,{title:"IN PROGRESS",section:i,emptyHint:"暂无正在处理的任务"}),e.jsx(es,{title:"PENDING",section:l,emptyHint:"暂无待处理的任务"}),e.jsxs("div",{children:[e.jsxs("button",{type:"button",onClick:v,"aria-expanded":h,className:"flex w-full items-center justify-between px-3 py-2 text-left text-[11px] font-normal uppercase tracking-[0.05em] text-og-500 transition-colors hover:bg-og-50/40",children:[e.jsx("span",{children:"DONE"}),e.jsx("span",{className:"font-normal normal-case text-accent",children:h?"收起":"查看"})]}),h&&e.jsx(fr,{state:u})]})]})})}function es({title:t,section:s,emptyHint:n}){return e.jsxs("section",{"aria-label":t,className:"border-b border-hairline",children:[e.jsxs("div",{className:"px-3 py-2 text-[11px] font-normal uppercase tracking-[0.05em] text-og-500",children:[t," ",e.jsxs("span",{className:"text-og-400",children:["(",s.total,")"]})]}),s.items.length===0?e.jsx("div",{className:"px-3 pb-3 text-[12px] text-og-400",children:n}):e.jsxs("div",{className:"divide-y divide-hairline",children:[s.items.map(o=>e.jsx(ws,{task:o},o.id)),s.hasMore&&e.jsx("button",{type:"button",onClick:s.loadMore,className:"w-full px-3 py-2 text-center text-[12px] text-accent transition-colors hover:bg-og-50/40",children:"加载更多"})]})]})}function fr({state:t}){const s=t.loaded&&!t.error&&t.items.length===0;return e.jsxs("div",{className:"divide-y divide-hairline",children:[t.items.map(n=>e.jsx(ws,{task:n},n.id)),t.error&&e.jsxs("div",{className:"px-3 py-2 text-[12px] text-danger",children:["加载失败:",t.error]}),s&&e.jsx("div",{className:"px-3 pb-3 pt-1 text-[12px] text-og-400",children:"暂无已处理的任务"}),t.loading&&t.items.length===0&&e.jsx("div",{className:"px-3 py-3 text-center text-[12px] text-og-400",children:"加载中…"}),t.hasMore&&e.jsx("button",{type:"button",onClick:()=>t.load("more"),disabled:t.loading,className:"w-full px-3 py-2 text-center text-[12px] text-accent transition-colors hover:bg-og-50/40 disabled:opacity-50",children:t.loading?"加载中…":"加载更多"})]})}function hr(t){const[s,n]=a.useState(!1);return a.useEffect(()=>{function o(){if(t.status!=="review"||!t.reviewDispatchedAt||!t.qaAgentId){n(!1);return}n(Date.now()-Date.parse(t.reviewDispatchedAt)>=rs)}o();const r=setInterval(o,3e4);return()=>clearInterval(r)},[t.status,t.reviewDispatchedAt,t.qaAgentId]),s}function ws({task:t}){const{openTask:s}=Le(),n=t.phase==="spec"?t.specReviewRound??0:t.reviewRound,o=hr(t);return e.jsxs("button",{type:"button",onClick:()=>s(t.id),className:"flex w-full items-center gap-2 px-3 py-2 text-left text-[13px] transition-colors hover:bg-og-50/60",children:[e.jsx("span",{className:"shrink-0 font-mono text-[11px] text-og-500",title:t.id,children:Nt(t.id)}),e.jsx("span",{className:"min-w-0 flex-1 truncate text-og-1000",title:t.title,children:t.title}),t.phase==="spec"&&e.jsx("span",{className:"pill pill-review shrink-0",children:"spec"}),o&&e.jsx("span",{className:"pill pill-warn shrink-0",title:"Review verdict missing",children:"!"}),e.jsxs("span",{"aria-label":`Round ${n}`,className:"shrink-0 text-[11px] text-og-400",children:["R",n]}),e.jsx(Kn,{status:t.status})]})}const mr=[],ys="baxian.taskPanel.open";function xr(){try{return localStorage.getItem(ys)!=="0"}catch{return!0}}function pr(){const{id:t}=ts(),s=Rs(),{show:n}=he(),{openTask:o}=Le(),{refresh:r}=Ze(),[i,l]=a.useState(null),[u,h]=a.useState(null),[x,v]=a.useState(!1),[p,d]=a.useState(!1),[y,A]=a.useState(xr),[m,b]=a.useState(!1),[S,M]=a.useState(!1),[f,N]=a.useState(""),[w,c]=a.useState(!1),[W,K]=a.useState(null),P=a.useRef(null),L=a.useRef(null),E=a.useId(),I=a.useId(),z=a.useRef(0),{data:U,loaded:_,error:F}=us(),{data:G,error:oe}=fs(t),j=(F==null?void 0:F.message)??null,g=(oe==null?void 0:oe.message)??null,q=G??mr,J=new Map((U??[]).map(O=>[O.id,O])),V=u??j??g,ee=a.useCallback(async O=>{const te=++z.current;try{const se=await $.projects.get(O);if(te!==z.current)return;l(se),h(null)}catch(se){if(te!==z.current)return;h(se instanceof Error?se.message:String(se))}},[]);a.useEffect(()=>{t&&(l(null),h(null),ee(t))},[t,ee]),a.useEffect(()=>{if(!m)return;const O=se=>{var B,D;const k=se.target;k&&((B=L.current)!=null&&B.contains(k)||(D=P.current)!=null&&D.contains(k)||b(!1))},te=se=>{var k;se.key==="Escape"&&(b(!1),(k=P.current)==null||k.focus())};return document.addEventListener("mousedown",O),document.addEventListener("keydown",te),()=>{document.removeEventListener("mousedown",O),document.removeEventListener("keydown",te)}},[m]),a.useEffect(()=>{S||(N(""),K(null))},[S]),a.useEffect(()=>{try{localStorage.setItem(ys,y?"1":"0")}catch{}},[y]);const R=(i==null?void 0:i.agent.flat().length)??0,Q=R===0,Y=!!i&&f.trim()===i.id,ce=async()=>{if(!(!i||!Y||w)){c(!0),K(null);try{await $.projects.delete(i.id),await r(),n({kind:"success",title:`项目 ${i.id} 已删除`}),M(!1),s("/")}catch(O){K(O instanceof Error?O.message:String(O))}finally{c(!1)}}};return i?e.jsxs("div",{children:[e.jsxs(vs,{children:[e.jsx("button",{type:"button",onClick:()=>d(!0),className:"btn-ghost",children:"+ 新建 Task"}),e.jsxs("div",{className:"relative",children:[e.jsx("button",{ref:P,id:I,type:"button",onClick:()=>b(O=>!O),"aria-haspopup":"menu","aria-expanded":m,"aria-controls":E,"aria-label":`项目 ${i.id} 操作菜单`,className:"flex h-8 w-8 items-center justify-center rounded text-og-500 transition-colors hover:bg-og-100 hover:text-og-1000",children:e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("circle",{cx:"12",cy:"12",r:"1"}),e.jsx("circle",{cx:"12",cy:"5",r:"1"}),e.jsx("circle",{cx:"12",cy:"19",r:"1"})]})}),m&&e.jsxs("div",{ref:L,id:E,role:"menu","aria-labelledby":I,className:"absolute right-0 top-full z-10 mt-1 min-w-[180px] rounded-md border border-hairline bg-surface py-1 shadow-md",children:[!y&&e.jsx("button",{type:"button",role:"menuitem",onClick:()=>{var O;b(!1),A(!0),(O=P.current)==null||O.focus()},className:"block w-full px-3 py-1.5 text-left text-[13px] text-og-800 hover:bg-og-100 hover:text-og-1000",children:"显示 Task 面板"}),e.jsx("button",{type:"button",role:"menuitem",onClick:()=>{b(!1),v(!0)},className:"block w-full px-3 py-1.5 text-left text-[13px] text-og-800 hover:bg-og-100 hover:text-og-1000",children:"添加 Agent"}),e.jsx("div",{role:"none",className:"my-1 border-t border-hairline"}),e.jsx("button",{type:"button",role:"menuitem",onClick:()=>{b(!1),M(!0)},disabled:!Q,title:Q?void 0:`请先删除项目下的 ${R} 个 Agent`,className:"block w-full px-3 py-1.5 text-left text-[13px] text-danger hover:bg-[#fef2f2] disabled:cursor-not-allowed disabled:text-og-400 disabled:hover:bg-transparent",children:"删除项目…"})]})]})]}),V&&e.jsxs("div",{className:"mb-4 text-[13px] text-danger",children:["Error: ",V]}),e.jsxs("div",{className:"mb-6 flex items-baseline gap-x-3",children:[e.jsx("h1",{className:"min-w-0 truncate font-display text-[17px] font-semibold tracking-tight text-og-1000",title:i.id,children:i.id}),e.jsx("span",{className:"hidden min-w-0 truncate font-mono text-[12px] text-og-500 sm:inline-block",title:i.repo,children:i.repo})]}),e.jsxs("div",{className:"flex flex-col gap-4 lg:flex-row lg:items-start",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"mb-3 flex h-8 items-center gap-2",children:e.jsx("h2",{className:"font-display text-[12px] font-semibold uppercase tracking-[0.06em] text-og-500",children:"Agents"})}),i.agent.flat().length===0?e.jsx("div",{className:"mb-8 rounded-lg border border-hairline bg-surface py-6 text-center text-[13px] text-og-500",children:"还没有 Agent,点击右上角菜单添加。"}):e.jsx("div",{className:"mb-8 space-y-5",children:i.agent.map((O,te)=>e.jsx(ps,{group:O,projectId:i.id,agentsById:J,agentsLoaded:_,agentsError:!!F,tasks:q,onDeleted:()=>{ee(i.id)},terminalMode:"embedded-full"},O.map(se=>se.id).join(":")||te))})]}),y&&e.jsxs("div",{className:"w-full lg:w-[340px] lg:shrink-0 xl:w-[380px]",children:[e.jsxs("div",{className:"mb-3 flex h-8 items-center justify-between gap-2",children:[e.jsx("h2",{className:"font-display text-[12px] font-semibold uppercase tracking-[0.06em] text-og-500",children:"Tasks"}),e.jsx("button",{type:"button",onClick:()=>{var O;A(!1),(O=P.current)==null||O.focus()},"aria-label":"关闭 Task 面板",className:"flex h-7 w-7 items-center justify-center rounded text-og-500 transition-colors hover:bg-og-100 hover:text-og-1000",children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),e.jsx(ur,{projectId:i.id,openTasks:q})]})]}),e.jsx(gs,{open:x,projectId:i.id,onClose:()=>v(!1),onCreated:()=>{ee(i.id)}}),e.jsx(yt,{open:p,projectId:i.id,onClose:()=>d(!1),onCreated:O=>o(O.id)}),e.jsx(ve,{open:S,onClose:()=>{w||M(!1)},title:"删除项目",size:"sm",footer:e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:()=>M(!1),disabled:w,className:"btn-secondary",children:"取消"}),e.jsx("button",{type:"button",onClick:()=>void ce(),disabled:!Y||w,className:"btn-secondary !text-danger hover:!bg-[#fef2f2] hover:!text-danger disabled:!text-og-300",children:w?"删除中…":"确认删除"})]}),children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-[13px] text-og-700",children:["将从 ",e.jsx("code",{className:"font-mono text-og-1000",children:"baxian.json"})," 中移除项目"," ",e.jsx("span",{className:"font-mono text-og-1000",children:i.id}),"。此操作不可撤销,且不会删除 Git 仓库本身。"]}),e.jsxs("p",{className:"text-[13px] text-og-700",children:["如需确认,请在下方输入项目 ID ",e.jsx("span",{className:"font-mono text-og-1000",children:i.id}),":"]}),e.jsx("input",{type:"text",value:f,onChange:O=>N(O.target.value),placeholder:i.id,autoComplete:"off",autoCorrect:"off",spellCheck:!1,disabled:w,"aria-label":"输入项目 ID 以确认删除",className:"w-full rounded border border-hairline bg-surface px-3 py-2 font-mono text-[13px] text-og-1000 focus:border-accent focus:outline-none"}),W&&e.jsx("div",{className:"rounded-md border border-[#fecaca] bg-[#fef2f2] px-3 py-2 text-[12px] text-danger",children:W})]})})]}):u?e.jsxs("div",{className:"text-[13px] text-danger",children:["Error: ",u]}):e.jsx("div",{className:"text-[13px] text-og-500",children:"Loading…"})}function gr(){const{agentId:t}=ts(),{projects:s}=Ze(),n=a.useMemo(()=>{if(t)for(const o of s??[])for(const r of o.agent){const i=r.find(l=>l.id===t);if(i)return i.runtime}},[t,s]);return t?e.jsxs("div",{"data-testid":"terminal-page-container",className:"flex min-h-0 flex-1 flex-col overflow-hidden border border-hairline bg-surface",children:[e.jsxs("div",{className:"flex h-8 flex-none select-none items-center gap-3 border-b border-hairline bg-page px-3 font-mono text-[11px] text-og-500",children:[e.jsx("span",{"aria-hidden":!0,className:"block h-1.5 w-1.5 rounded-full bg-success"}),e.jsx("span",{className:"text-og-700",title:gt(t,n),children:t})]}),e.jsx("div",{className:"min-h-0 flex-1",children:e.jsx(De,{agentId:t,mode:"full",interactive:!0,arrowKeys:!0})})]}):e.jsx("div",{className:"text-[13px] text-danger",children:"No agent specified"})}function br(){const[t,s]=a.useState(!1);return e.jsx("button",{type:"button",onClick:()=>s(n=>!n),"aria-label":t?"切换为 Logo 图标":"切换为 Logo 文字",className:"flex h-7 min-w-[60px] shrink-0 items-center justify-center font-display text-[15px] font-semibold tracking-tight text-og-1000",children:t?e.jsx("span",{className:"inline-flex h-6 items-center leading-none",children:"baxian"}):e.jsx("img",{src:"/baxian-logo.png",alt:"baxian",width:20,height:24,className:"block h-6 w-auto"})})}function vr(){const{phase:t,count:s,error:n,triggerRestart:o}=Xe();return t==="idle"?null:t==="failed"?e.jsxs("div",{className:"flex items-center justify-between border-b border-[#fecaca] bg-[#fef2f2] px-4 py-2",children:[e.jsxs("div",{className:"text-[13px] text-danger",children:["❌ 重启失败:",n]}),e.jsx("button",{onClick:()=>{o()},className:"btn-ghost !text-danger hover:!bg-[#fef2f2]",children:"重试"})]}):t==="restarting"?e.jsx("div",{className:"border-b border-accent-soft bg-accent-soft/40 px-4 py-2 text-[13px] text-accent",children:"🔄 重启中…"}):e.jsxs("div",{className:"flex items-center justify-between border-b border-[#fde68a] bg-[#fef3c7]/60 px-4 py-2",children:[e.jsxs("div",{className:"text-[13px] text-warn",children:["⚠️ 有 ",s," 项配置变更待重启 baxian server 才生效"]}),e.jsx("button",{onClick:()=>{o()},className:"btn-secondary !border-warn !text-warn hover:!bg-[#fef3c7] hover:!border-warn hover:!text-warn",children:"现在重启"})]})}function wr(){const s=!Ts().pathname.startsWith("/terminal/");return e.jsxs("div",{className:"flex h-dvh flex-col bg-page",children:[e.jsxs("nav",{className:"flex h-12 flex-none items-center border-b border-hairline bg-surface px-3 sm:px-6",children:[e.jsxs(Me,{to:"/",className:"flex shrink-0 items-center gap-2 font-display text-[15px] font-semibold tracking-tight text-og-1000",children:[e.jsx("span",{"aria-hidden":!0,className:"block h-2.5 w-2.5 rounded-full bg-accent"}),"baxian"]}),e.jsx("div",{id:bs,className:"ml-auto flex min-w-0 items-center justify-end gap-2"})]}),e.jsx(vr,{}),e.jsxs("main",{className:"flex min-h-0 flex-1 flex-col overflow-y-auto px-3 py-6 sm:px-6",children:[e.jsxs(Is,{children:[e.jsx(et,{path:"/",element:e.jsx(ar,{})}),e.jsx(et,{path:"/project/:id",element:e.jsx(pr,{})}),e.jsx(et,{path:"/terminal/:agentId",element:e.jsx(gr,{})})]}),s&&e.jsx("footer",{className:"mt-auto flex justify-center pb-4 pt-24",children:e.jsx(br,{})})]})]})}function yr(){return e.jsx(As,{children:e.jsx(wr,{})})}function jr({children:t}){const[s,n]=a.useState({kind:"probing"}),o=a.useRef(s);a.useEffect(()=>{o.current=s},[s]);const r=a.useCallback(async()=>{n({kind:"probing"});try{await $.config.get(),n({kind:"authorized"})}catch(i){if(i instanceof Ce&&i.status===401){n({kind:"unauthorized"});return}const l=i instanceof Error?i.message:"无法连接服务器";n({kind:"error",message:l})}},[]);return a.useEffect(()=>{r()},[r]),a.useEffect(()=>{const i=()=>{o.current.kind!=="probing"&&n({kind:"unauthorized",message:"登录已失效,请重新输入令牌"})};return window.addEventListener(Qe,i),()=>window.removeEventListener(Qe,i)},[]),s.kind==="authorized"?e.jsx(e.Fragment,{children:t}):s.kind==="error"?e.jsxs(xt,{title:"无法连接服务器",children:[e.jsx("p",{className:"text-[13px] text-og-600",children:s.message}),e.jsx("button",{type:"button",onClick:()=>{r()},className:"btn-primary mt-4 w-full",children:"重试"})]}):s.kind==="probing"?e.jsx(xt,{title:"加载中",children:e.jsx("p",{className:"text-[13px] text-og-500",children:"正在检查登录状态…"})}):e.jsx(Nr,{message:s.message,onSubmit:async i=>{Os(i);try{await $.config.get(),n({kind:"authorized"})}catch(l){if(Ms(),l instanceof Ce&&l.status===401){n({kind:"unauthorized",message:"令牌无效,请重试"});return}const u=l instanceof Error?l.message:"登录失败";n({kind:"error",message:u})}}})}function xt({title:t,children:s}){return e.jsx("div",{className:"flex min-h-dvh items-center justify-center bg-page px-4",children:e.jsxs("div",{className:"w-full max-w-sm rounded-lg border border-hairline bg-surface px-6 py-6",children:[e.jsx("h1",{className:"mb-3 font-display text-[16px] font-semibold tracking-tight text-og-1000",children:t}),s]})})}function Nr({message:t,onSubmit:s}){const[n,o]=a.useState(""),[r,i]=a.useState(!1),[l,u]=a.useState(void 0),h=async v=>{v.preventDefault();const p=n.trim();if(!p){u("请输入访问令牌");return}u(void 0),i(!0);try{await s(p)}finally{i(!1)}},x=l??t;return e.jsxs(xt,{title:"登录 baxian",children:[e.jsx("p",{className:"mb-4 text-[13px] text-og-600",children:"服务器开启了访问鉴权,请输入访问令牌继续。"}),e.jsxs("form",{onSubmit:v=>{h(v)},children:[e.jsx("label",{className:"mb-1.5 block text-[12px] font-medium text-og-700",htmlFor:"baxian-token",children:"访问令牌"}),e.jsx("input",{id:"baxian-token",type:"password",autoComplete:"current-password",autoFocus:!0,value:n,onChange:v=>o(v.target.value),className:"w-full rounded-md border border-og-100 bg-surface px-2.5 py-1.5 font-mono text-[13px] text-og-800 placeholder:text-og-400 focus:border-accent focus:outline-none focus:ring-[3px] focus:ring-accent-soft disabled:cursor-not-allowed disabled:opacity-50",placeholder:"请输入服务器配置的 token",disabled:r}),x&&e.jsx("p",{role:"alert",className:"mt-2 text-[12px] text-danger",children:x}),e.jsx("button",{type:"submit",disabled:r,className:"btn-primary mt-4 w-full",children:r?"登录中…":"登录"})]})]})}Ss.createRoot(document.getElementById("root")).render(e.jsx(a.StrictMode,{children:e.jsx(qs,{children:e.jsx(zs,{children:e.jsx(jr,{children:e.jsx(Qn,{children:e.jsx(yr,{})})})})})}));
|
package/dist/web/index.html
CHANGED
|
@@ -6,12 +6,12 @@
|
|
|
6
6
|
<link rel="icon" type="image/png" href="/baxian-logo.png" />
|
|
7
7
|
<link rel="apple-touch-icon" href="/baxian-logo.png" />
|
|
8
8
|
<title>baxian</title>
|
|
9
|
-
<script type="module" crossorigin src="/assets/index-
|
|
9
|
+
<script type="module" crossorigin src="/assets/index-CMT0Apmv.js"></script>
|
|
10
10
|
<link rel="modulepreload" crossorigin href="/assets/react-BFCkCmbU.js">
|
|
11
11
|
<link rel="modulepreload" crossorigin href="/assets/xterm-D5X2JljJ.js">
|
|
12
12
|
<link rel="modulepreload" crossorigin href="/assets/router-D24GsdXZ.js">
|
|
13
13
|
<link rel="stylesheet" crossorigin href="/assets/xterm-CFbL2ovg.css">
|
|
14
|
-
<link rel="stylesheet" crossorigin href="/assets/index-
|
|
14
|
+
<link rel="stylesheet" crossorigin href="/assets/index-BgUL3TNI.css">
|
|
15
15
|
</head>
|
|
16
16
|
<body>
|
|
17
17
|
<div id="root"></div>
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "baxian",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.17",
|
|
4
4
|
"description": "AI agent orchestration",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -21,7 +21,8 @@
|
|
|
21
21
|
],
|
|
22
22
|
"scripts": {
|
|
23
23
|
"build": "pnpm -r build",
|
|
24
|
-
"test": "pnpm -r test",
|
|
24
|
+
"test": "pnpm -r test && npm run test:docs",
|
|
25
|
+
"test:docs": "node --test docs/scripts/*.test.mjs",
|
|
25
26
|
"test:coverage": "pnpm -r --if-present test:coverage",
|
|
26
27
|
"lint": "eslint .",
|
|
27
28
|
"clean": "pnpm -r clean && rm -rf dist",
|