baxian 1.2.26 → 1.2.27

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.
@@ -0,0 +1,7 @@
1
+ var Ls=Object.defineProperty;var Os=(t,s,n)=>s in t?Ls(t,s,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[s]=n;var se=(t,s,n)=>Os(t,typeof s!="symbol"?s+"":s,n);import{r as i,j as e,a as Ms,c as _s}from"./react-BFCkCmbU.js";import{x as Fs,a as Bs}from"./xterm-D5X2JljJ.js";import{L as _e,u as Fe,a as Ze,b as ds,B as Hs,R as Us,c as $e}from"./router-BgSDZqI0.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"]'))a(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const c of o.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&a(c)}).observe(document,{childList:!0,subtree:!0});function n(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function a(r){if(r.ep)return;r.ep=!0;const o=n(r);fetch(r.href,o)}})();const Ws={"claude-code":"Claude Code",codex:"Codex"};function jt(t){return t?Ws[t]:null}function wt(t,s){const n=jt(s);return n?`${t} (${n})`:t}const us=new Set(["merged","done","failed","cancelled"]),fs=new Set(["in_progress","review","fixing","approved","merge-ready","ready","max_rounds"]),nt=20,et=5*1024*1024,He=4,xs=600*1e3,zs=1536,Qs=1872,hs=192,ms=208,Ce="/api",yt="baxian.token",Ve="baxian:unauthorized";function Nt(){try{return typeof localStorage<"u"?localStorage.getItem(yt):null}catch{return null}}function Gs(t){try{localStorage.setItem(yt,t)}catch(s){console.error("Failed to save auth token to localStorage",s)}}function qs(){try{localStorage.removeItem(yt)}catch(t){console.error("Failed to clear auth token from localStorage",t)}}function we(t){const s=Nt();return{...t??{},...s?{Authorization:`Bearer ${s}`}:{}}}class Re extends Error{constructor(s,n,a){super(n),this.status=s,this.details=a,this.name="ApiError"}}async function ye(t){const s=await t.text();let n=s||`HTTP ${t.status}`,a;try{const r=JSON.parse(s);typeof r.error=="string"&&(n=r.error),Array.isArray(r.details)&&(a=r.details)}catch{}throw t.status===401&&typeof window<"u"&&window.dispatchEvent(new CustomEvent(Ve)),new Re(t.status,n,a)}async function ue(t){const s=await fetch(`${Ce}${t}`,{headers:we()});return s.ok||await ye(s),s.json()}async function Vs(){const t=await fetch("/health");return t.ok||await ye(t),t.json()}async function ae(t,s,n){const a=s!==void 0,r=await fetch(`${Ce}${t}`,{method:"POST",headers:a?we({"Content-Type":"application/json"}):we(),body:a?JSON.stringify(s):void 0,signal:n==null?void 0:n.signal});return r.ok||await ye(r),r.json()}async function Ft(t,s,n){const a=await fetch(`${Ce}${t}`,{method:"PATCH",headers:we({"Content-Type":"application/json"}),body:s?JSON.stringify(s):void 0,signal:n==null?void 0:n.signal});if(a.ok||await ye(a),a.status===204)return;const r=await a.text();if(r)return JSON.parse(r)}async function Ks(t,s){const n=await fetch(`${Ce}${t}`,{method:"PUT",headers:we({"Content-Type":"application/json"}),body:JSON.stringify(s??null)});if(n.ok||await ye(n),n.status===204)return;const a=await n.text();if(a)return JSON.parse(a)}async function Ie(t){const s=await fetch(`${Ce}${t}`,{method:"DELETE",headers:we()});if(s.ok||await ye(s),s.status===204)return;const n=await s.text();if(n)return JSON.parse(n)}const Q=encodeURIComponent;function ht(t){return new Promise((s,n)=>{const a=new FileReader;a.onerror=()=>n(a.error??new Error("file read failed")),a.onload=()=>{const r=a.result;if(typeof r!="string"){n(new Error("unexpected FileReader result"));return}const o=r.indexOf(",");s(o>=0?r.slice(o+1):r)},a.readAsDataURL(t)})}const T={agents:{list:()=>ue("/agents"),get:t=>ue(`/agents/${Q(t)}`),stop:t=>Ie(`/agents/${Q(t)}/session`),compact:t=>ae(`/agents/${Q(t)}/compact`),clear:t=>ae(`/agents/${Q(t)}/clear`),probe:(t,s={},n)=>ae("/agents/probe",{mode:t,host:s.host,hostId:s.hostId},n),uploadImage:async(t,s)=>ae(`/agents/${Q(t)}/images`,{dataBase64:await ht(s)}),setPet:(t,s)=>Ks(`/agents/${Q(t)}/pet`,{petId:s})},pets:{list:()=>ue("/pets"),create:async(t,s)=>ae("/pets",{petJson:t,spritesheetBase64:await ht(s)}),remove:t=>Ie(`/pets/${Q(t)}`),fetchSpritesheet:async t=>{const s=await fetch(`${Ce}/pets/${Q(t)}/spritesheet`,{headers:we()});return s.ok||await ye(s),s.blob()}},tasks:{list:async t=>{const s=new Map;for(const n of["active","pending"]){let a=0;for(;;){const r=await T.tasks.page(t,{category:n,offset:a});for(const o of r.tasks)s.set(o.id,o);if(!r.hasMore||r.tasks.length===0)break;a=r.nextOffset}}return[...s.values()]},page:(t,s={})=>{const n=[`projectId=${Q(t)}`];return s.category&&n.push(`category=${s.category}`),n.push(`offset=${s.offset??0}`),ue(`/tasks?${n.join("&")}`)},get:t=>ue(`/tasks/${Q(t)}`),create:t=>ae("/tasks",t),update:(t,s)=>Ft(`/tasks/${Q(t)}`,s),retry:t=>ae(`/tasks/${Q(t)}/retry`),review:t=>ae(`/tasks/${Q(t)}/review`),complete:t=>ae(`/tasks/${Q(t)}/complete`),continue:t=>ae(`/tasks/${Q(t)}/continue`),reviews:t=>ue(`/tasks/${Q(t)}/reviews`),githubReview:t=>ue(`/tasks/${Q(t)}/github-review`),dispatch:(t,s)=>ae(`/tasks/${Q(t)}/dispatch`,s)},projects:{list:()=>ue("/projects"),get:t=>ue(`/projects/${Q(t)}`),create:t=>ae("/projects",t),delete:t=>Ie(`/projects/${Q(t)}`),addAgent:(t,s)=>ae(`/projects/${Q(t)}/agents`,s),deleteAgent:(t,s)=>Ie(`/projects/${Q(t)}/agents/${Q(s)}`),resumeAgent:(t,s)=>ae(`/projects/${Q(t)}/agents/${Q(s)}/resume`),restartRepl:(t,s)=>ae(`/projects/${Q(t)}/agents/${Q(s)}/restart-repl`),retryAgent:(t,s)=>ae(`/projects/${Q(t)}/agents/${Q(s)}/retry`),bootstrap:t=>ae(`/projects/${Q(t)}/bootstrap`)},hosts:{list:()=>ue("/hosts"),create:t=>ae("/hosts",t),update:(t,s)=>Ft(`/hosts/${Q(t)}`,s),delete:t=>Ie(`/hosts/${Q(t)}`),check:t=>ae("/hosts/check",t)},config:{get:()=>ue("/config")},health:{get:Vs},server:{restart:()=>ae("/restart")}},ps=i.createContext(null),Js={success:"border-[#bbf7d0] bg-[#f0fdf4] text-success",warn:"border-[#fde68a] bg-[#fef3c7] text-warn",error:"border-[#fecaca] bg-[#fef2f2] text-danger"},Ys={success:"✅",warn:"⚠️",error:"❌"};let Xs=1;function Zs({children:t}){const[s,n]=i.useState([]),a=i.useCallback(o=>{n(c=>c.filter(u=>u.id!==o))},[]),r=i.useCallback(o=>{const c=Xs++,u=o.durationMs??3e3;n(h=>[...h,{...o,id:c}]),setTimeout(()=>a(c),u)},[a]);return e.jsxs(ps.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(o=>e.jsx("div",{className:`pointer-events-auto w-full max-w-xs rounded-lg border px-4 py-3 shadow-toast ${Js[o.kind]}`,role:"status",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{"aria-hidden":!0,className:"text-[14px]",children:Ys[o.kind]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-[13px] font-semibold",children:o.title}),o.body&&e.jsx("div",{className:"mt-1 whitespace-pre-line text-[12px] text-og-700",children:o.body})]}),e.jsx("button",{type:"button",onClick:()=>a(o.id),className:"text-current opacity-50 transition-opacity hover:opacity-100","aria-label":"Dismiss",children:"✕"})]})},o.id))})]})}function xe(){const t=i.useContext(ps);if(!t)throw new Error("useToast must be inside <ToastProvider>");return t}const Ke="baxian.pendingRestart",en=500,tn=3e4,gs=i.createContext(null);function sn(){try{const t=localStorage.getItem(Ke);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 nn(t){try{t.count<=0?localStorage.removeItem(Ke):localStorage.setItem(Ke,JSON.stringify(t))}catch{}}function rn({children:t}){const s=sn(),[n,a]=i.useState(s.count),[r,o]=i.useState(s.baselineStartedAt),[c,u]=i.useState(s.count>0?"pending":"idle"),[h,x]=i.useState(),m=i.useRef(s.count),f=i.useRef(s.count>0?"pending":"idle"),d=i.useRef(0),j=i.useCallback(p=>{m.current=p,a(p)},[]),k=i.useCallback(p=>{a(N=>{const w=p(N);return m.current=w,w})},[]),g=i.useCallback(p=>{f.current=p,u(p)},[]);i.useEffect(()=>{nn({count:n,baselineStartedAt:r})},[n,r]),i.useEffect(()=>{let p=!1;(async()=>{try{const w=await T.health.get();if(p)return;o(l=>l!==null&&w.startedAt!==l?(j(0),g("idle"),null):l)}catch{}})();const N=w=>{if(w.key===Ke){if(w.newValue===null){if(f.current==="restarting"&&d.current>0){j(d.current),o(null);return}j(0),o(null),f.current!=="restarting"&&g("idle");return}try{const l=JSON.parse(w.newValue);typeof l.count=="number"&&(f.current==="restarting"&&l.count>m.current&&(d.current+=l.count-m.current),j(l.count),f.current!=="restarting"&&g(l.count>0?"pending":"idle")),typeof l.baselineStartedAt=="string"?o(l.baselineStartedAt):l.baselineStartedAt===null&&o(null)}catch{}}};return window.addEventListener("storage",N),()=>{p=!0,window.removeEventListener("storage",N)}},[j,g]);const v=i.useRef(!1),E=i.useCallback(()=>{k(p=>p+1),f.current==="restarting"?d.current+=1:g("pending"),o(p=>(p!==null||v.current||(v.current=!0,(async()=>{try{const N=await T.health.get();o(w=>w??N.startedAt)}catch{}finally{v.current=!1}})()),p))},[g,k]),O=i.useCallback(async()=>{d.current=0,x(void 0),g("restarting");let p;try{p=(await T.health.get()).startedAt}catch(w){g("failed"),x(`获取重启前 startedAt 失败: ${w instanceof Error?w.message:String(w)}`);return}try{await T.server.restart()}catch(w){if(!(w instanceof Re&&w.status===409)){g("failed"),x(`触发重启失败: ${w instanceof Error?w.message:String(w)}`);return}}const N=Date.now();for(;Date.now()-N<tn;){await new Promise(w=>setTimeout(w,en));try{const w=await T.health.get();if(w.startedAt!==p){const l=d.current;d.current=0,o(l>0?w.startedAt:null),j(l),g(l>0?"pending":"idle");return}}catch{}}g("failed"),x("重启超时(30s 未恢复)。请检查日志或手动 baxian start -c <path>")},[j,g]);return e.jsx(gs.Provider,{value:{phase:c,count:n,error:h,flagDirty:E,triggerRestart:O},children:t})}function tt(){const t=i.useContext(gs);if(!t)throw new Error("usePendingRestart must be used inside PendingRestartProvider");return t}const an=[500,1e3,2e3,4e3,8e3,15e3,3e4];class bs{constructor(s){se(this,"attempts",0);se(this,"timer",null);se(this,"delaysMs");this.opts=s,this.delaysMs=s.delaysMs??an}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 Bt=0;function on(){Bt++;const t=Math.random().toString(36).slice(2,8);return`sub-${Date.now().toString(36)}-${Bt}-${t}`}function cn(t){return Array.from(new TextEncoder().encode(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}function ln(){return`${location.protocol==="https:"?"wss":"ws"}://${location.host}/api/stream`}const dn=(t,s)=>s&&s.length>0?new WebSocket(t,s):new WebSocket(t);class un{constructor(s={}){se(this,"wsUrl");se(this,"wsFactory");se(this,"tokenProvider");se(this,"ws",null);se(this,"subs",new Map);se(this,"snapshotPending",new Set);se(this,"preSubscribeQueue",new Map);se(this,"outbox",[]);se(this,"reconnectScheduler");se(this,"explicitlyClosed",!1);this.wsUrl=s.wsUrl??ln(),this.wsFactory=s.wsFactory??dn,this.tokenProvider=s.tokenProvider??Nt,this.reconnectScheduler=new bs({reconnect:()=>this.openSocket(),shouldReconnect:()=>!this.explicitlyClosed&&this.subs.size>0})}subscribe(s){const n=on(),a={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,a),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,a){const r=this.subs.get(s);r&&(r.lastSize={cols:n,rows:a},!this.snapshotPending.has(s)&&this.wsSendOrQueue({op:"resize",subscriberId:s,cols:n,rows:a}))}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.${cn(s)}`]:void 0;let a;try{a=this.wsFactory(this.wsUrl,n)}catch(r){console.warn("[pane-stream] WebSocket constructor threw:",r),this.scheduleReconnect();return}this.ws=a,a.onopen=()=>{if(a!==this.ws)return;this.reconnectScheduler.reset();for(const o of this.subs.values()){this.snapshotPending.add(o.subscriberId),this.preSubscribeQueue.set(o.subscriberId,[]),o.snapshotSeq=void 0;try{a.send(JSON.stringify({op:"subscribe",subscriberId:o.subscriberId,agentId:o.agentId,mode:o.mode}))}catch(c){console.warn("[pane-stream] resubscribe send failed:",c)}}const r=this.outbox;this.outbox=[];for(const o of r)if(o.op!=="subscribe"){if("subscriberId"in o&&o.subscriberId){if(!this.subs.has(o.subscriberId))continue;if(this.snapshotPending.has(o.subscriberId)&&o.op!=="unsubscribe"){this.outbox.push(o);continue}}try{a.send(JSON.stringify(o))}catch(c){console.warn("[pane-stream] outbox flush failed:",c)}}},a.onmessage=r=>{if(a!==this.ws)return;let o;try{const c=typeof r.data=="string"?r.data:String(r.data);o=JSON.parse(c)}catch{return}this.handleMessage(o)},a.onclose=()=>{a===this.ws&&(this.ws=null,!this.explicitlyClosed&&this.subs.size!==0&&this.scheduleReconnect())},a.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,a;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);(a=r==null?void 0:r.onError)==null||a.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 a=this.preSubscribeQueue.get(s.subscriberId);if(this.preSubscribeQueue.delete(s.subscriberId),a)for(const r of a)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 a of this.outbox)if("subscriberId"in a&&a.subscriberId===s&&a.op!=="subscribe")try{this.ws.send(JSON.stringify(a))}catch(r){console.warn("[pane-stream] flushOutboxForSub send failed:",r)}else n.push(a);this.outbox=n}dispatch(s){for(const n of this.subs.values())if(n.agentId===s.agentId)if(this.snapshotPending.has(n.subscriberId)){const a=this.preSubscribeQueue.get(n.subscriberId);a&&a.push({seq:s.seq,data:s.data})}else n.onData(s.data)}}let rt=null;function at(){return rt||(rt=new un),rt}function fn(t){const{agentId:s,mode:n}=t,a=i.useRef(null),r=i.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},i.useEffect(()=>{const h=at().subscribe({agentId:s,mode:n,onSnapshot:x=>r.current.onSnapshot(x),onData:x=>r.current.onData(x),onError:x=>{var m,f;return(f=(m=r.current).onError)==null?void 0:f.call(m,x)},onSessionGone:()=>{var x,m;return(m=(x=r.current).onSessionGone)==null?void 0:m.call(x)}});return a.current=h.subscriberId,()=>{a.current=null,h.unsubscribe()}},[s,n]);const o=i.useCallback(u=>{const h=a.current;h&&at().send(h,u)},[]),c=i.useCallback((u,h)=>{const x=a.current;x&&at().resize(x,u,h)},[]);return{send:o,resize:c}}const xn=[{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"}],Ue=Object.fromEntries(xn.map(t=>[t.key,t]));function We({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-50 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 hn({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(We,{arrow:Ue.left,onPress:t}),e.jsx(We,{arrow:Ue.up,onPress:t}),e.jsx(We,{arrow:Ue.down,onPress:t}),e.jsx(We,{arrow:Ue.right,onPress:t})]})}const mn=Math.floor(et/1024/1024);function pn({agentId:t,className:s}){const n=i.useRef(null),[a,r]=i.useState(!1),{show:o}=xe(),c=async u=>{var x;const h=(x=u.target.files)==null?void 0:x[0];if(u.target.value="",!!h){if(h.size>et){o({kind:"error",title:"图片过大",body:`单张图片不能超过 ${mn} MiB`});return}r(!0);try{await T.agents.uploadImage(t,h),o({kind:"success",title:"图片已插入",body:"路径已粘贴到终端输入,补充说明后回车"})}catch(m){const f=m instanceof Re||m instanceof Error?m.message:String(m);o({kind:"error",title:"图片上传失败",body:f})}finally{r(!1)}}};return e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button","aria-label":"上传图片",disabled:a,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-50 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:c})]})}const gn={up:"A",down:"B",right:"C",left:"D"};function bn(t,s){return(s?"\x1BO":"\x1B[")+gn[t]}const Ht=18,vn=250,jn=256*1024,Ut="#fdfdfd",wn='ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',yn={background:Ut,foreground:"#474c55",cursor:"#1348dc",cursorAccent:Ut,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"},Nn=/\x1b\[(?:\?[\d;]*c|>[\d;]*c|\??\d+;\d+R|\d+n)/g;function Sn(t){return t.replace(Nn,"")}const kn=1024*1024;function En(t){const s=t.indexOf(";");if(s===-1)return null;const n=t.slice(s+1);if(n.length===0||n==="?"||n.length>kn)return null;try{const a=atob(n),r=new Uint8Array(a.length);for(let o=0;o<a.length;o++)r[o]=a.charCodeAt(o);return new TextDecoder().decode(r)}catch{return null}}function Oe({agentId:t,mode:s,interactive:n=!1,maxLines:a,className:r,autoFocus:o=!0,deferFullUntilFocus:c=!1,arrowKeys:u=!1}){const h=i.useRef(null),x=i.useRef(null),m=i.useRef(null),f=i.useRef(null),d=i.useRef(!1),j=i.useRef(""),k=i.useRef([]),g=i.useRef(0),v=i.useRef(null),E=i.useRef(null),O=i.useRef(null),p=i.useRef(Promise.resolve()),N=i.useRef(0),[w,l]=i.useState(null),[H,G]=i.useState(!1),P=`${t}\0${s}\0${c?"1":"0"}`,[M,R]=i.useState({key:P,active:!1}),I=M.key===P&&M.active,z=s==="full"&&c,U=z&&!I?"preview":s,_=n&&U==="full",B=(S,F)=>F.length===0?Promise.resolve():new Promise(D=>{try{S.write(F,()=>D())}catch(oe){console.warn("[pane-terminal] write failed:",oe),D()}}),q=U==="preview",ie=()=>{if(!q)return;const S=h.current,F=x.current;if(!S||!F||S.clientHeight<=0)return;const oe=(F.buffer.active.cursorY+1)*Ht;S.scrollTop=Math.max(0,oe-S.clientHeight)},y=()=>{if(!q||O.current!==null)return;let S=!1;const F=requestAnimationFrame(()=>{S=!0,O.current=null,ie()});S||(O.current=F)},b=(S,F)=>{p.current=p.current.then(async()=>{const D=x.current;if(!(!D||F!==N.current))try{await S(D),_&&D.scrollToBottom(),y()}catch(oe){console.warn("[pane-terminal] terminal task failed:",oe)}}).catch(D=>{console.warn("[pane-terminal] write chain failed:",D)})},V=(S,F)=>{b(D=>B(D,S),F)},Y=()=>{v.current!==null&&(cancelAnimationFrame(v.current),v.current=null),E.current!==null&&(clearTimeout(E.current),E.current=null)},K=()=>{Y(),k.current=[],g.current=0},ee=()=>{Y();const S=k.current;S.length!==0&&(k.current=[],g.current=0,V(S.join(""),N.current))},ce=S=>{if(S.length!==0){if(k.current.push(S),g.current+=S.length,g.current>=jn){ee();return}v.current===null&&(v.current=requestAnimationFrame(ee)),E.current===null&&(E.current=setTimeout(ee,vn))}},{send:ne,resize:A}=fn({agentId:t,mode:U,onSnapshot:({cols:S,rows:F,data:D})=>{if(x.current)try{const le=N.current+1;N.current=le,K(),b(async fe=>{var C;fe.reset(),_?((C=f.current)==null||C.call(f),await B(fe,D)):(S>0&&F>0&&fe.resize(S,F),await B(fe,D))},le)}catch(le){console.warn("[pane-terminal] snapshot write failed:",le)}},onData:S=>{ce(S)},onError:S=>l(`${S.code}: ${S.message}`),onSessionGone:()=>G(!0)});i.useEffect(()=>{l(null),G(!1)},[t,U]),i.useEffect(()=>{j.current=""},[P]),i.useEffect(()=>{if(U!=="full")return;const S=j.current;S.length!==0&&(j.current="",ne(S))},[ne,U]);const X=i.useCallback(()=>{!n||!z||I||(d.current=!0,R({key:P,active:!0}))},[P,I,n,z]),$=i.useCallback(S=>{const F=Sn(S);if(F.length!==0){if(z&&(!I||j.current.length>0)){j.current+=F,X();return}ne(F)}},[X,I,ne,z]);i.useEffect(()=>{const S=h.current;if(!S)return;let F=!1;const D=new Fs.Terminal({cursorBlink:n,disableStdin:!n,theme:yn,fontFamily:wn,fontSize:13,lineHeight:1.4,scrollback:U==="full"?5e3:1e3}),oe=new Bs.FitAddon;D.loadAddon(oe),D.open(S),x.current=D,m.current=oe;const le=q?D.onRender(()=>y()):null;if(n&&(o||d.current)){d.current=!1;try{D.focus()}catch{}}n&&(D.onData($),U==="full"&&D.parser.registerOscHandler(52,je=>{var Se;const Ne=En(je);return Ne!==null&&((Se=navigator.clipboard)==null||Se.writeText(Ne).catch(()=>{})),!0}));const fe=()=>S.clientWidth>0&&S.clientHeight>0,C=(je=!1)=>{if(!fe())return!1;const Ne=D.cols,Se=D.rows;try{oe.fit()}catch{return!1}return _&&D.scrollToBottom(),D.cols>0&&D.rows>0&&(je||D.cols!==Ne||D.rows!==Se)&&A(D.cols,D.rows),!0};f.current=_?()=>C(!0):null;let W=null,re=null,Z=null,Ae=0;const me=()=>{W||(W=new ResizeObserver(()=>{re&&clearTimeout(re),re=setTimeout(()=>{re=null,_?C():q&&y()},100)}),W.observe(S))},he=()=>{Z=requestAnimationFrame(()=>{if(Z=null,!F){if(!_){q&&(me(),y());return}if(C(!0)){me();return}if(Ae++<5){he();return}me()}})};return he(),()=>{F=!0,Z!==null&&cancelAnimationFrame(Z),v.current!==null&&(cancelAnimationFrame(v.current),v.current=null),E.current!==null&&(clearTimeout(E.current),E.current=null),O.current!==null&&(cancelAnimationFrame(O.current),O.current=null),N.current++,k.current=[],g.current=0,p.current=Promise.resolve(),re&&clearTimeout(re),W==null||W.disconnect(),le==null||le.dispose(),x.current=null,m.current=null,f.current=null;try{D.dispose()}catch(je){console.warn("[pane-terminal] dispose failed:",je)}}},[t,o,_,$,n,U,A]);const te=()=>{var S;if(n){X();try{(S=x.current)==null||S.focus()}catch{}}};i.useEffect(()=>{if(n)return;const S=h.current;if(!S)return;const F=D=>{D.stopPropagation()};return S.addEventListener("wheel",F,{capture:!0,passive:!0}),()=>S.removeEventListener("wheel",F,{capture:!0})},[n]);const J=a&&a>0?{maxHeight:`${a*Ht}px`}:void 0;return e.jsxs("div",{className:r??"flex flex-col h-full w-full min-h-0 bg-[#fdfdfd]",children:[(w||H)&&e.jsx("div",{className:"border-b border-[#fecaca] bg-[#fef2f2] px-3 py-1 font-mono text-[11px] text-danger",children:H?"session ended":w}),e.jsx("div",{className:"flex flex-1 min-h-0 px-2 py-1.5",style:J,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(pn,{agentId:t})}),e.jsx(hn,{className:"flex items-center justify-center gap-1",onKey:S=>{var D,oe;const F=!!((oe=(D=x.current)==null?void 0:D.modes)!=null&&oe.applicationCursorKeysMode);$(bn(S,F))}})]})]})}function Rn(){const[t,s]=i.useState([]),[n,a]=i.useState(!0),[r,o]=i.useState(null),c=i.useCallback(async()=>{a(!0);try{s(await T.pets.list()),o(null)}catch(u){o(u instanceof Error?u.message:String(u))}finally{a(!1)}},[]);return i.useEffect(()=>{c()},[c]),{pets:t,loading:n,error:r,refresh:c}}const it=new Map,ot=new Map;function Cn(t){const[s,n]=i.useState(()=>t?ot.get(t)??null:null);return i.useEffect(()=>{if(!t){n(null);return}const a=ot.get(t);if(n(a??null),a)return;let r=!1,o=it.get(t);return o||(o=T.pets.fetchSpritesheet(t).then(c=>{const u=URL.createObjectURL(c);return ot.set(t,u),u}),it.set(t,o)),o.then(c=>{r||n(c)},()=>{r||n(null),it.delete(t)}),()=>{r=!0}},[t]),s}const An=[{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 Tn(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 St=36,$n=St/ms,In=hs*$n;function Pn(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function vs({petId:t,status:s,bootstrapping:n=!1,label:a,displayHeight:r=St,className:o}){const c=Cn(t),u=Tn(s,n),h=An[u],x=h.durations.length,[m,f]=i.useState(0),d=r/ms,j=hs*d;return i.useEffect(()=>{if(f(0),!c||x<=1||Pn())return;let k,g=0;const v=()=>{g=(g+1)%x,f(g),k=setTimeout(v,h.durations[g])};return k=setTimeout(v,h.durations[0]),()=>clearTimeout(k)},[c,u,x,h]),c?e.jsx("span",{role:"img","aria-label":a,title:a,"data-pet-row":u,"data-pet-col":m,className:["inline-block shrink-0",o].filter(Boolean).join(" "),style:{width:`${j}px`,height:`${r}px`,backgroundImage:`url(${c})`,backgroundRepeat:"no-repeat",backgroundSize:`${zs*d}px ${Qs*d}px`,backgroundPositionX:`${-(m*j)}px`,backgroundPositionY:`${-(u*r)}px`,imageRendering:"pixelated"}}):e.jsx("span",{className:"pill pill-idle",title:a,children:a})}const Dn={sm:"max-w-md",md:"max-w-lg",lg:"max-w-2xl"},Wt='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:a,children:r,footer:o,size:c="md",dismissOnBackdrop:u=!0}){const h=i.useRef(null),x=i.useRef(null),m=i.useRef(!1),f=i.useRef(s);return i.useEffect(()=>{f.current=s},[s]),i.useEffect(()=>{if(!t)return;x.current=document.activeElement;const d=g=>{if(g.key==="Escape"){f.current();return}if(g.key!=="Tab")return;const v=h.current;if(!v)return;const E=Array.from(v.querySelectorAll(Wt)).filter(w=>w.offsetParent!==null||w===document.activeElement);if(E.length===0){g.preventDefault();return}const O=E[0],p=E[E.length-1],N=document.activeElement;g.shiftKey&&(N===O||!v.contains(N))?(g.preventDefault(),p.focus()):!g.shiftKey&&(N===p||!v.contains(N))&&(g.preventDefault(),O.focus())};document.addEventListener("keydown",d);const j=document.body.style.overflow;document.body.style.overflow="hidden";const k=h.current;if(k){const g=k.querySelector(Wt);g==null||g.focus()}return()=>{var g,v;document.removeEventListener("keydown",d),document.body.style.overflow=j,(v=(g=x.current)==null?void 0:g.focus)==null||v.call(g)}},[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=>{m.current=d.target===d.currentTarget}:void 0,onClick:u?d=>{d.target===d.currentTarget&&m.current&&f.current()}:void 0,role:"presentation",children:e.jsxs("div",{ref:h,className:`flex w-full ${Dn[c]} 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:a??n}),e.jsx("button",{type:"button",onClick:()=>f.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}),o&&e.jsx("div",{className:"flex shrink-0 flex-wrap items-center justify-end gap-2 border-t border-hairline px-5 py-3",children:o})]})}):null}class qe extends Error{constructor(s){super(s),this.name="PetPackageError"}}const ze=t=>t.split("/").pop()??t;function Ln(t){return typeof t.text=="function"?t.text():new Promise((s,n)=>{const a=new FileReader;a.onerror=()=>n(a.error??new Error("file read failed")),a.onload=()=>s(typeof a.result=="string"?a.result:""),a.readAsText(t)})}async function On(t){const s=t.find(c=>ze(c.name)==="pet.json"||ze(c.webkitRelativePath||"")==="pet.json");if(!s)throw new qe("文件包中未找到 pet.json");let n;try{n=JSON.parse(await Ln(s))}catch{throw new qe("pet.json 解析失败")}const a=n&&typeof n=="object"&&typeof n.spritesheetPath=="string"?n.spritesheetPath:"",r=a?ze(a):"",o=(r?t.find(c=>ze(c.name)===r):void 0)??t.find(c=>/\.(png|webp)$/i.test(c.name));if(!o)throw new qe("文件包中未找到精灵图(png/webp)");return{manifest:n,spritesheet:o}}function Mn({children:t,style:s}){const n=i.useRef(null),[a,r]=i.useState(typeof IntersectionObserver>"u");return i.useEffect(()=>{if(a||typeof IntersectionObserver>"u")return;const o=n.current;if(!o)return;const c=new IntersectionObserver(u=>{u.some(h=>h.isIntersecting)&&(r(!0),c.disconnect())});return c.observe(o),()=>c.disconnect()},[a]),e.jsx("span",{ref:n,className:"inline-block shrink-0",style:s,children:a?t:null})}function _n({agentId:t,currentPetId:s,onClose:n}){const{show:a}=xe(),{pets:r,loading:o,refresh:c}=Rn(),[u,h]=i.useState(!!s),[x,m]=i.useState(s),[f,d]=i.useState(!1),j=i.useRef(null);i.useEffect(()=>{m(s)},[s]),i.useEffect(()=>{const p=j.current;p&&(p.setAttribute("webkitdirectory",""),p.setAttribute("directory",""))},[u]);const k=p=>p instanceof Re||p instanceof Error?p.message:String(p),g=async p=>{if(h(p),!p&&x){d(!0);try{await T.agents.setPet(t,null),m(null),a({kind:"success",title:"已关闭 Agent Pet"})}catch(N){a({kind:"error",title:"关闭失败",body:k(N)}),h(!0)}finally{d(!1)}}},v=async p=>{d(!0);try{await T.agents.setPet(t,p),m(p),a({kind:"success",title:"已选择 Pet"})}catch(N){a({kind:"error",title:"选择失败",body:k(N)})}finally{d(!1)}},E=async(p,N)=>{if(window.confirm(`确认删除 Pet「${N}」?使用它的 Agent 会回到默认状态显示。`)){d(!0);try{await T.pets.remove(p),await c(),a({kind:"success",title:`Pet「${N}」已删除`})}catch(w){a({kind:"error",title:"删除失败",body:k(w)})}finally{d(!1)}}},O=async p=>{const N=p.target.files?Array.from(p.target.files):[];if(p.target.value="",!!N.length){d(!0);try{const{manifest:w,spritesheet:l}=await On(N);await T.pets.create(w,l),await c(),a({kind:"success",title:"Pet 上传成功"})}catch(w){const l=w instanceof qe?w.message:k(w);a({kind:"error",title:"Pet 上传失败",body:l})}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:f,onChange:p=>void g(p.target.checked)}),"启用 Agent Pet"]}),u?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("button",{type:"button",onClick:()=>{var p;return(p=j.current)==null?void 0:p.click()},disabled:f,className:"btn-secondary",children:"上传 Pet 文件包"}),e.jsx("input",{ref:j,type:"file","aria-label":"上传 Codex Pet 文件包",className:"hidden",onChange:p=>void O(p)}),e.jsx("p",{className:"mt-1 text-[12px] text-og-400",children:"选择 Codex Pet 目录(含 pet.json 与精灵图)。"})]}),o?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(p=>{const N=p.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(Mn,{style:{width:`${In}px`,height:`${St}px`},children:e.jsx(vs,{petId:p.id,status:"idle",label:p.displayName})}),e.jsxs("button",{type:"button",onClick:()=>void v(p.id),disabled:f||N,title:p.description||p.displayName,className:"min-w-0 flex-1 truncate text-left text-[13px] text-og-1000 hover:text-accent-hover disabled:cursor-default",children:[p.displayName,N&&e.jsx("span",{className:"ml-1 text-[11px] text-accent",children:"(当前)"})]}),e.jsx("button",{type:"button","aria-label":`删除 ${p.displayName}`,onClick:()=>void E(p.id,p.displayName),disabled:f,className:"shrink-0 text-[12px] text-danger hover:underline disabled:opacity-50",children:"删除"})]},p.id)})})]}):e.jsx("p",{className:"text-[12px] text-og-500",children:"开启后可上传 Codex Pet 文件包,或选择已上传过的 Pet 替换 Agent 卡片上的状态显示。"})]})})}const Fn={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"}},Bn=72,Hn={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 Un({state:t}){if(t==="present")return null;const{label:s,modifier:n}=Hn[t];return e.jsx("span",{role:"img","aria-label":s,title:s,className:`status-dot ml-2 ${n}`})}function Wn({agent:t,projectId:s,role:n,runtime:a,onDeleted:r,pendingRestart:o=!1,terminalLoading:c=!1,showTaskBinding:u=!0,terminalMode:h="activity-preview",active:x,onActivate:m}){var At,Tt,$t,It,Pt,Dt,Lt,Ot;const[f,d]=i.useState(!1),[j,k]=i.useState(null),{show:g}=xe(),{flagDirty:v}=tt(),[E,O]=i.useState(!1),[p,N]=i.useState(null),[w,l]=i.useState(!1),[H,G]=i.useState(!1),[P,M]=i.useState(!1),[R,I]=i.useState(!1),[z,U]=i.useState(!1),[_,B]=i.useState(!1),[q,ie]=i.useState(!1),y=i.useRef(null),b=i.useRef(null),V=i.useId(),Y=i.useId();i.useEffect(()=>{if(!_)return;const L=Te=>{var Mt,_t;const pe=Te.target;pe&&((Mt=b.current)!=null&&Mt.contains(pe)||(_t=y.current)!=null&&_t.contains(pe)||B(!1))},de=Te=>{var pe;Te.key==="Escape"&&(B(!1),(pe=y.current)==null||pe.focus())};return document.addEventListener("mousedown",L),document.addEventListener("keydown",de),()=>{document.removeEventListener("mousedown",L),document.removeEventListener("keydown",de)}},[_]),i.useEffect(()=>{var de;if(!_)return;const L=(de=b.current)==null?void 0:de.querySelector('[role="menuitem"]:not([disabled])');L==null||L.focus()},[_]);const K=(At=t.binding)==null?void 0:At.taskId,ee=((Tt=t.binding)==null?void 0:Tt.status)==="awaiting_human",ce=ee&&(($t=t.binding)==null?void 0:$t.awaitingPhase)==="greeting_failed",ne=!!((It=t.binding)!=null&&It.creationToken)&&!((Pt=t.binding)!=null&&Pt.paneId)&&!ee&&t.reason!=="PENDING_HUMAN",A=ne&&t.tmuxSessionStatus!=="present",X=ne?{label:"Starting",cls:"pill pill-review"}:Fn[t.runtimeStatus],$=ne?"starting":t.tmuxSessionStatus,te=h==="activity-preview"&&!A&&(t.runtimeStatus==="working"||t.runtimeStatus==="pending"),J=h==="embedded-full",S=J&&typeof m=="function",F=S&&x===!0,D=c||o||A,oe=c?"Agent 状态加载中":o?"重启 baxian server 后可用":"Agent 正在启动",le=jt(a),fe=async()=>{d(!0),k(null);try{await T.agents.stop(t.id)}catch(L){k(L instanceof Error?L.message:String(L))}finally{d(!1)}},C=async()=>{if(K&&window.confirm(`请 QA 对 task ${K} 重审?这会让 QA agent 立即开始新一轮 review(reviewRound +1)。`)){M(!0);try{const L=await T.tasks.review(K);g({kind:"success",title:`已派 QA 重审 (round ${L.reviewRound})`})}catch(L){g({kind:"error",title:"Review 派发失败",body:L instanceof Error?L.message:String(L)})}finally{M(!1)}}},W=async()=>{U(!0);try{(await T.projects.bootstrap(s)).ok?g({kind:"success",title:"Bootstrap retry 完成",body:"agent 状态将在下一次刷新生效。"}):g({kind:"warn",title:"Bootstrap retry 仍失败",body:"看一下红色错误卡的最新原因,按提示修复后再试。"})}catch(L){g({kind:"error",title:"Bootstrap retry 失败",body:L instanceof Error?L.message:String(L)})}finally{U(!1)}},re=async()=>{const L=ce?`确认 Resume Agent ${t.id}?greeting 能力未通过,baxian 会重跑能力握手(会话存活则重启 REPL,已丢失则重建);握手通过才解除 Held。`:`确认 Resume Agent ${t.id}?baxian 会清除 awaiting_human 状态,agent 重新可派遣。`;if(window.confirm(L)){I(!0);try{if(ce){t.tmuxSessionStatus==="present"?await T.projects.restartRepl(s,t.id):await T.projects.retryAgent(s,t.id),g({kind:"success",title:`Agent ${t.id} 正在重跑能力握手`,body:"握手通过后 Held 会在下一次刷新自动解除,仍失败则按提示修复 runtime 后再试。"});return}const de=await T.projects.resumeAgent(s,t.id);g({kind:"success",title:`Agent ${t.id} 已 Resume`,body:de.releasedBinding?"原任务已释放,agent 可接新任务。":"保留绑定(原任务仍 active)。"})}catch(de){g({kind:"error",title:"Resume 失败",body:de instanceof Error?de.message:String(de)})}finally{I(!1)}}},Z=async()=>{l(!0);try{await T.agents.compact(t.id),g({kind:"success",title:`已向 Agent ${t.id} 发送 /compact`})}catch(L){g({kind:"error",title:"Compact 失败",body:L instanceof Error?L.message:String(L)})}finally{l(!1)}},Ae=async()=>{if(window.confirm(`确认向 Agent ${t.id} 发送 /clear?这会清空整个会话上下文,不可恢复。`)){G(!0);try{await T.agents.clear(t.id),g({kind:"success",title:`已向 Agent ${t.id} 发送 /clear`})}catch(L){g({kind:"error",title:"Clear 失败",body:L instanceof Error?L.message:String(L)})}finally{G(!1)}}},me=async()=>{if(window.confirm(`确认删除 Agent ${t.id}?此操作不可撤销`)){O(!0),N(null);try{const L=await T.projects.deleteAgent(s,t.id);L!=null&&L.restartRequired&&v();const de=(L==null?void 0:L.removed)??[t.id];if(de.length>1){const Te=de.filter(pe=>pe!==t.id).join(", ");g({kind:"warn",title:`已删除 Agent ${t.id}`,body:`配对的 QA Agent ${Te} 也被一并移除。`})}else g({kind:"success",title:`Agent ${t.id} 已删除`});r==null||r()}catch(L){N(L instanceof Error?L.message:String(L))}finally{O(!1)}}},he=S&&!D&&!F,je=["card relative flex h-full min-w-0 flex-col overflow-visible p-4",F?"ring-2 ring-accent":""].filter(Boolean).join(" "),Ne=["mb-3 flex items-start justify-between gap-2",t.petId?"pr-28":""].filter(Boolean).join(" "),Se=["mb-2 mt-3 h-80 min-h-0 overflow-hidden border border-hairline bg-surface",he?"cursor-pointer":""].filter(Boolean).join(" "),Ps=he?()=>m==null?void 0:m():void 0,Ds=he?L=>{(L.key==="Enter"||L.key===" ")&&(L.preventDefault(),m==null||m())}:void 0;return e.jsxs("div",{className:je,"data-agent-card":S?t.id:void 0,children:[t.petId&&e.jsx("div",{className:"absolute -top-4 right-7 z-10",children:e.jsx(vs,{petId:t.petId,status:t.runtimeStatus,bootstrapping:ne,label:X.label,displayHeight:Bn})}),e.jsxs("div",{className:Ne,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:wt(t.id,a),children:t.id}),le&&e.jsxs("span",{className:"hidden shrink-0 whitespace-nowrap text-[12px] text-og-400 sm:inline",title:le,children:["(",le,")"]})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-1",children:[ee&&e.jsx("span",{className:"pill pill-warn",title:((Dt=t.binding)==null?void 0:Dt.awaitingReason)??"需人工处理",children:"Held"}),!t.petId&&e.jsx("span",{className:X.cls,children:X.label}),t.stale&&e.jsx("span",{className:"pill pill-warn",title:t.observedAt?`Last observed at ${t.observedAt}`:void 0,children:"Stale"}),e.jsx(Un,{state:$})]})]}),A&&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:(Lt=t.binding)==null?void 0:Lt.awaitingPhase}),((Ot=t.binding)==null?void 0:Ot.awaitingReason)&&e.jsxs("span",{children:[" · ",t.binding.awaitingReason]})]}),!ne&&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(_e,{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:W,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&&K&&e.jsxs("div",{className:"mb-2 text-[12px] text-og-500",children:["Task: ",e.jsx("span",{className:"font-mono text-og-700",children:K})]}),te&&e.jsx("div",{className:"mb-2 overflow-hidden border border-hairline bg-surface",children:e.jsx(Oe,{agentId:t.id,mode:"preview",maxLines:6,interactive:!1})}),J&&e.jsx("div",{className:Se,role:he?"button":void 0,tabIndex:he?0:void 0,"aria-label":he?`激活 ${t.id} 终端`:void 0,onClick:Ps,onKeyDown:Ds,children:D?e.jsx("div",{className:"flex h-full items-center justify-center px-3 text-[13px] text-og-500",children:oe}):S?F?e.jsx(Oe,{agentId:t.id,mode:"full",interactive:!0,autoFocus:!0}):e.jsx(Oe,{agentId:t.id,mode:"preview",interactive:!1}):e.jsx(Oe,{agentId:t.id,mode:"full",interactive:!0,autoFocus:!1,deferFullUntilFocus:!0})}),o&&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:[D?e.jsx("span",{className:"shrink-0 cursor-not-allowed text-[13px] text-og-400",title:oe,children:"Terminal"}):e.jsx(_e,{to:`/terminal/${t.id}`,className:"btn-secondary shrink-0",children:"Terminal"}),!o&&t.runtimeStatus==="working"&&e.jsx("button",{onClick:fe,disabled:f,className:"btn-ghost shrink-0 !text-danger hover:!bg-[#fef2f2]",children:f?"Stopping…":"Stop"}),ee&&e.jsx("button",{type:"button",onClick:re,disabled:R,title:ce?"重跑 greeting 能力握手以恢复(会话存活则重启 REPL,已丢失则重建;greeting_failed 无法靠清状态解除)":"清除 awaiting_human 状态,让 agent 重新可派遣",className:"btn-ghost shrink-0 !text-warn hover:!bg-[#fef3c7]/60",children:R?"Resuming…":"Resume"})]}),e.jsxs("div",{className:"relative shrink-0",children:[e.jsx("button",{ref:y,id:Y,type:"button",onClick:()=>B(L=>!L),disabled:E,"aria-haspopup":"menu","aria-expanded":_,"aria-controls":_?V:void 0,"aria-label":`Agent ${t.id} 操作菜单`,className:"flex h-8 w-8 items-center justify-center rounded text-og-500 transition-colors hover:bg-og-50 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:b,id:V,role:"menu","aria-labelledby":Y,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:()=>{B(!1),ie(!0)},disabled:w||H||E,title:"配置 Agent Pet(在状态位置显示动画宠物)",className:"block w-full px-3 py-1.5 text-left text-[13px] text-og-1000 hover:bg-og-50 disabled:opacity-50 disabled:cursor-not-allowed",children:"Agent Pet"}),e.jsx("button",{type:"button",role:"menuitem",onClick:()=>{B(!1),Z()},disabled:w||H||E,title:"向 agent runtime 发送 /compact 压缩上下文",className:"block w-full px-3 py-1.5 text-left text-[13px] text-og-1000 hover:bg-og-50 disabled:opacity-50 disabled:cursor-not-allowed",children:w?"Compacting…":"Compact"}),e.jsx("button",{type:"button",role:"menuitem",onClick:()=>{B(!1),Ae()},disabled:H||w||E,title:"向 agent runtime 发送 /clear 清空上下文",className:"block w-full px-3 py-1.5 text-left text-[13px] text-og-1000 hover:bg-og-50 disabled:opacity-50 disabled:cursor-not-allowed",children:H?"Clearing…":"Clear"}),!o&&K&&n==="dev"&&e.jsx("button",{type:"button",role:"menuitem",onClick:()=>{B(!1),C()},disabled:P||E,title:`让 QA 立即对 task ${K} 跑一轮 review(需要该 task 已有 PR)`,className:"block w-full px-3 py-1.5 text-left text-[13px] text-og-1000 hover:bg-og-50 disabled:opacity-50 disabled:cursor-not-allowed",children:P?"Dispatching…":"Call review"}),e.jsx("button",{type:"button",role:"menuitem",onClick:()=>{B(!1),me()},disabled:E||w||H,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:E?"Deleting…":"Delete"})]})]})]}),j&&e.jsx("div",{className:"mt-1.5 break-words text-[12px] text-danger",children:j}),p&&e.jsx("div",{className:"mt-1.5 break-words text-[12px] text-danger",children:p}),q&&e.jsx(_n,{agentId:t.id,currentPetId:t.petId??null,onClose:()=>ie(!1)})]})}const zt=200,Qt=16e3,zn="baxian.draft.createTask:";function mt(t){return`${zn}${t??"*"}`}function Gt(t){try{const s=localStorage.getItem(t);if(!s)return null;const n=JSON.parse(s);if(!n||typeof n!="object")return null;const a=n,r=typeof a.title=="string"?a.title:"",o=typeof a.description=="string"?a.description:"",c=typeof a.projectId=="string"?a.projectId:"",u=typeof a.preferredAgentId=="string"?a.preferredAgentId:"",h=typeof a.updatedAt=="number"?a.updatedAt:void 0;return!r.trim()&&!o.trim()?null:{title:r,description:o,projectId:c,preferredAgentId:u,updatedAt:h}}catch{return null}}function Qn(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 qt(t){try{localStorage.removeItem(t)}catch{}}function Gn(t){const s=mt(t),n=Gt(s);if(!t)return n;const a=mt(void 0),r=Gt(a);if(!r||r.projectId!==t)return n;const o=!n||(r.updatedAt??0)>(n.updatedAt??0);if(o)try{localStorage.setItem(s,JSON.stringify(r))}catch{return r}try{localStorage.removeItem(a)}catch{}return o?r:n}const Qe="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",Pe="mb-1.5 block text-[12px] font-medium text-og-700",Vt="mt-1 text-right text-[12px] text-og-400",qn=Math.floor(et/1024/1024);function kt(t){const s=t.mode==="edit",{show:n}=xe(),a=s?t.task.projectId:t.projectId,r=s?t.task.title:"",o=s?t.task.description:"",c=s?t.task.preferredAgentId:"",[u,h]=i.useState([]),[x,m]=i.useState([]),[f,d]=i.useState(a??""),[j,k]=i.useState(c),[g,v]=i.useState(r),[E,O]=i.useState(o),[p,N]=i.useState([]),w=i.useRef(null),[l,H]=i.useState(!1),[G,P]=i.useState(null),[M,R]=i.useState(!1),I=i.useRef(0),z=i.useRef(0),U=i.useRef(0),_=i.useRef(new Set),B=s?null:mt(a);i.useEffect(()=>{if(!t.open)return;I.current+=1,z.current+=1;const C=I.current;h([]),m([]),_.current=new Set;const W=B?Gn(a):null;W&&_.current.add(W.projectId),d(a??(W==null?void 0:W.projectId)??""),k((W==null?void 0:W.preferredAgentId)||c),v((W==null?void 0:W.title)||r),O((W==null?void 0:W.description)||o),R(W!==null),P(null),H(!1),N([]),Promise.all([T.projects.list(),T.agents.list()]).then(([re,Z])=>{C===I.current&&(h(re),m(Z))}).catch(re=>{C===I.current&&P(re instanceof Error?re.message:String(re))})},[t.open,a,r,o,c,B]),i.useEffect(()=>{if(!(!t.open||!B)){if(U.current!==z.current){U.current=z.current;return}Qn(B,{title:g,description:E,projectId:f,preferredAgentId:j})}},[t.open,B,g,E,f,j]);const q=i.useMemo(()=>u.find(C=>C.id===f)??null,[u,f]),ie=i.useMemo(()=>q?q.agent.flat().filter(C=>C.role==="dev"):[],[q]),y=i.useMemo(()=>new Set(x.map(C=>C.id)),[x]),b=i.useMemo(()=>ie.filter(C=>y.has(C.id)),[ie,y]),V=i.useMemo(()=>ie.filter(C=>!y.has(C.id)),[ie,y]);i.useEffect(()=>{s||q!==null&&j!==""&&!b.find(C=>C.id===j)&&k("")},[q,b,j,s]),i.useEffect(()=>{s||q&&b.length!==0&&(_.current.has(q.id)||(_.current.add(q.id),k(C=>C===""?b[0].id:C)))},[s,q,b]);const Y=!s||b.find(C=>C.id===j),K=s&&!Y&&!!j,ee=K&&V.some(C=>C.id===j),ce=ee?`当前 dev "${j}" 在 baxian.json 中存在但 runtime 未加载,可能是手动编辑过配置文件;重启 server 可拉起`:K?`当前 dev "${j}" 不在 runtime(可能已从 project 配置移除);保存可能失败,请确认或选择新 dev`:!f||b.length>0?null:V.length>0?"baxian.json 里有 dev agent 但 runtime 未加载(可能是手动编辑过配置);重启 server 后生效":null,ne=g.trim(),A=E.trim(),$=!!f&&ne.length>0&&!l,te=()=>{l||t.onClose()},J=()=>{B&&(qt(B),d(a??""),k(c),v(r),O(o),P(null),R(!1))},S=async C=>{var W,re;if(C.preventDefault(),!!$){H(!0),P(null);try{if(t.mode==="edit"){const Z=await T.tasks.update(t.task.id,{title:ne,description:A,preferredAgentId:j});n({kind:"success",title:"任务已更新"}),(W=t.onUpdated)==null||W.call(t,Z),t.onClose()}else{const Z=p.length?await Promise.all(p.map(async me=>({dataBase64:await ht(me),filename:me.name}))):void 0,Ae=await T.tasks.create({projectId:f,title:ne,description:A,preferredAgentId:j,...Z?{images:Z}:{}});B&&qt(B),n({kind:"success",title:"任务已创建"}),(re=t.onCreated)==null||re.call(t,Ae),t.onClose()}}catch(Z){P(Z instanceof Error?Z.message:String(Z))}finally{H(!1)}}},F=C=>{const W=Array.from(C.target.files??[]);if(C.target.value="",W.length===0)return;const re=W.filter(Z=>Z.size>et?(n({kind:"error",title:"图片过大",body:`${Z.name} 超过 ${qn} MiB`}),!1):!0);N(Z=>(Z.length+re.length>He&&n({kind:"warn",title:`最多 ${He} 张图片`}),[...Z,...re].slice(0,He)))},D=C=>N(W=>W.filter((re,Z)=>Z!==C)),oe=s?"编辑 Task":"新建 Task",le=s?l?"保存中…":"保存":l?"创建中…":"创建",fe=!s&&!a;return e.jsx(ve,{open:t.open,onClose:te,title:oe,size:"md",dismissOnBackdrop:!1,footer:e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:te,disabled:l,className:"btn-secondary",children:"取消"}),e.jsx("button",{type:"submit",form:"create-task-form",disabled:!$,className:"btn-primary",children:le})]}),children:e.jsxs("form",{id:"create-task-form",onSubmit:S,className:"space-y-3",children:[!s&&M&&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:J,className:"shrink-0 underline hover:text-accent-hover",children:"丢弃"})]}),G&&e.jsx("div",{className:"rounded-md border border-[#fecaca] bg-[#fef2f2] px-3 py-2 text-[13px] text-danger",children:G}),fe&&e.jsxs("div",{children:[e.jsx("label",{className:Pe,htmlFor:"task-project",children:"Project"}),e.jsxs("select",{id:"task-project",value:f,onChange:C=>d(C.target.value),className:Qe,disabled:l,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:Pe,htmlFor:"task-dev",children:"Dev Agent"}),e.jsxs("select",{id:"task-dev",value:j,onChange:C=>k(C.target.value),className:Qe,disabled:l,children:[e.jsx("option",{value:"",children:"暂不指定"}),K&&e.jsxs("option",{value:j,children:[j," ",ee?"(待重启)":"(不在 runtime)"]}),b.map(C=>e.jsx("option",{value:C.id,children:C.id},C.id))]}),ce&&e.jsx("div",{className:"mt-1 text-[12px] text-warn",children:ce})]}),e.jsxs("div",{children:[e.jsx("label",{className:Pe,htmlFor:"task-title",children:"Title"}),e.jsx("input",{id:"task-title",type:"text",value:g,onChange:C=>v(C.target.value),maxLength:zt,className:Qe,placeholder:"一句话描述要做什么",disabled:l,required:!0}),e.jsxs("div",{className:Vt,children:[g.length," / ",zt]})]}),e.jsxs("div",{children:[e.jsx("label",{className:Pe,htmlFor:"task-description",children:"Description(可选)"}),e.jsx("textarea",{id:"task-description",value:E,onChange:C=>O(C.target.value),maxLength:Qt,rows:8,className:`${Qe} font-mono text-[12px]`,placeholder:"详细描述任务,支持 markdown;简单任务可不填",disabled:l}),e.jsxs("div",{className:Vt,children:[E.length," / ",Qt]})]}),!s&&e.jsxs("div",{children:[e.jsx("label",{className:Pe,children:"图片(可选)"}),e.jsx("button",{type:"button",onClick:()=>{var C;return(C=w.current)==null?void 0:C.click()},disabled:l||p.length>=He,className:"btn-secondary",children:"添加图片"}),e.jsx("input",{ref:w,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:F}),p.length>0&&e.jsx("ul",{className:"mt-2 space-y-1",children:p.map((C,W)=>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(W),disabled:l,className:"ml-2 shrink-0 text-og-400 transition-colors hover:text-danger",children:"✕"})]},`${C.name}-${W}`))})]})]})})}function js(t,s){const[n,a]=i.useState(null),[r,o]=i.useState(!1),[c,u]=i.useState(null),h=i.useRef(t);return i.useEffect(()=>{let x=!0;return h.current!==t&&(h.current=t,a(null),o(!1)),u(null),T.tasks.reviews(t).then(m=>{x&&(a(m),o(!0))}).catch(m=>{x&&(u(m instanceof Error?m.message:String(m)),a([]),o(!0))}),()=>{x=!1}},[t,s]),{rounds:n,loaded:r,error:c}}const Vn={spec:"规格评审 (spec)",code:"代码评审 (code)"},Kn={approve:"pill pill-live","request-changes":"pill pill-warn"};function Kt(t){if(!t)return 0;const s=t.endsWith(`
2
+ `)?t.slice(0,-1):t;return s===""?0:s.split(`
3
+ `).length}function Jn(t){return t.phase==="code"?(t.diffstat??"").split(`
4
+ `).map(n=>n.trim()).filter(Boolean).pop()??`diff ${Kt(t.content)} 行`:`规格文档 ${Kt(t.content)} 行`}function Yn(t){const s={critical:0,major:0,minor:0};for(const r of t.findings)r.severity in s&&s[r.severity]++;const n=[];return s.critical&&n.push(`${s.critical} critical`),s.major&&n.push(`${s.major} major`),s.minor&&n.push(`${s.minor} minor`),`${t.findings.length} 条 findings${n.length?`(${n.join(", ")})`:""}`}function Xn(t){const s={fix:0,reject:0,"out-of-scope":0};for(const a of t.responses)a.action in s&&s[a.action]++;const n=[];return s.fix&&n.push(`${s.fix} fixed`),s.reject&&n.push(`${s.reject} rejected`),s["out-of-scope"]&&n.push(`${s["out-of-scope"]} out-of-scope`),n.join(" · ")||`${t.responses.length} 条反馈`}function Zn({task:t,onClose:s}){return t.reviewMode==="server"||(t.specReviewRound??0)>0?e.jsx(er,{task:t,onClose:s}):null}function er({task:t,onClose:s}){const n=Fe(),a=`${t.specReviewRound??0}:${t.reviewRound}:${t.status}:${t.phase??"code"}`,{rounds:r,loaded:o,error:c}=js(t.id,a);function u(x,m,f){s(),n(`/tasks/${encodeURIComponent(t.id)}/rounds/${x}/${m}${f}`)}const h=((r==null?void 0:r.length)??0)>0;return e.jsxs("section",{className:"mt-4","aria-label":"Dev ↔ QA 评审记录",children:[e.jsx("div",{className:"mb-2 text-[11px] font-normal uppercase tracking-[0.05em] text-og-500",children:"Dev ↔ QA 评审记录"}),c&&e.jsxs("div",{className:"text-[13px] text-danger",children:["加载评审记录失败:",c]}),!o&&!c&&e.jsx("div",{className:"text-[13px] text-og-400",children:"加载评审记录…"}),o&&!c&&!h&&e.jsx("div",{className:"text-[13px] text-og-400",children:"评审尚未开始"}),o&&h&&e.jsx("div",{className:"space-y-4",children:["spec","code"].map(x=>{const m=(r??[]).filter(f=>f.phase===x).sort((f,d)=>f.round-d.round);return m.length===0?null:e.jsxs("div",{children:[e.jsx("div",{className:"mb-1.5 text-[12px] font-medium text-og-700",children:Vn[x]}),e.jsx("div",{className:"space-y-3",children:m.map(f=>e.jsx(tr,{round:f,onOpen:u},`${x}-${f.round}`))})]},x)})})]})}function tr({round:t,onOpen:s}){const n=t.phase==="spec";return e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1 text-[11px] text-og-400",children:["第 ",t.round," 轮"]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ct,{role:"dev",label:n?"提交规格稿":"提交代码改动",summary:Jn(t),onClick:()=>s(t.phase,t.round,"")}),t.findings&&e.jsx(ct,{role:"qa",label:"评审",badge:e.jsx("span",{className:Kn[t.findings.verdict],children:t.findings.verdict}),summary:Yn(t.findings),onClick:()=>s(t.phase,t.round,"#review")}),t.response&&e.jsx(ct,{role:"dev",label:"反馈",summary:Xn(t.response),onClick:()=>s(t.phase,t.round,"#response")})]})]})}function ct({role:t,label:s,summary:n,badge:a,onClick:r}){return e.jsxs("button",{type:"button",onClick:r,className:"card flex w-full items-center gap-2 px-3 py-2 text-left text-[13px] hover:border-accent",children:[e.jsx("span",{className:`pill shrink-0 ${t==="qa"?"pill-review":""}`,children:t==="qa"?"QA":"dev"}),e.jsx("span",{className:"shrink-0 font-medium text-og-800",children:s}),a,e.jsx("span",{className:"min-w-0 flex-1 truncate text-og-500",children:n}),e.jsx("span",{"aria-hidden":!0,className:"shrink-0 text-og-300",children:"›"})]})}function sr({task:t,onClose:s}){const n=Fe();if(t.reviewMode==="server"||t.prNumber===void 0)return null;function a(){s(),n(`/tasks/${encodeURIComponent(t.id)}/github-review`)}return e.jsxs("section",{className:"mt-4","aria-label":"Dev ↔ QA 代码评审",children:[e.jsx("div",{className:"mb-2 text-[11px] font-normal uppercase tracking-[0.05em] text-og-500",children:"Dev ↔ QA 代码评审 (GitHub PR)"}),e.jsxs("button",{type:"button",onClick:a,className:"card flex w-full items-center gap-2 px-3 py-2 text-left text-[13px] hover:border-accent",children:[e.jsx("span",{className:"pill pill-review shrink-0",children:"QA"}),e.jsx("span",{className:"min-w-0 flex-1 truncate text-og-700",children:"查看 PR 评审过程(QA review、行内评论、dev 修复 commit)"}),e.jsx("span",{"aria-hidden":!0,className:"shrink-0 text-og-300",children:"›"})]})]})}function nr(t){return Array.from(new TextEncoder().encode(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}function rr(){return`${location.protocol==="https:"?"wss":"ws"}://${location.host}/api/realtime`}const ar=(t,s)=>s&&s.length>0?new WebSocket(t,s):new WebSocket(t);class ir{constructor(s={}){se(this,"wsUrl");se(this,"wsFactory");se(this,"tokenProvider");se(this,"ws",null);se(this,"topics",new Map);se(this,"cache",new Map);se(this,"outbox",[]);se(this,"reconnectScheduler");se(this,"explicitlyClosed",!1);this.wsUrl=s.wsUrl??rr(),this.wsFactory=s.wsFactory??ar,this.tokenProvider=s.tokenProvider??Nt,this.reconnectScheduler=new bs({reconnect:()=>this.openSocket(),shouldReconnect:()=>!this.explicitlyClosed&&this.topics.size>0})}subscribe(s,n,a){let r=this.topics.get(s);const o=!r;return r||(r={data:new Set,error:new Set},this.topics.set(s,r)),r.data.add(n),a&&r.error.add(a),o?(this.ensureSocket(),this.wsSendOrQueue({op:"subscribe",topic:s})):this.cache.has(s)&&queueMicrotask(()=>{var c;(c=this.topics.get(s))!=null&&c.data.has(n)&&this.cache.has(s)&&n(this.cache.get(s))}),()=>this.unsubscribe(s,n,a)}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,a){const r=this.topics.get(s);r&&(r.data.delete(n),a&&r.error.delete(a),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.${nr(s)}`]:void 0;let a;try{a=this.wsFactory(this.wsUrl,n)}catch(o){console.warn("[events-client] WebSocket constructor threw:",o),this.broadcastConnectionError({code:"connection_failed",message:o instanceof Error?o.message:"WebSocket constructor threw"}),this.scheduleReconnect();return}this.ws=a;let r=!1;a.onopen=()=>{if(a!==this.ws)return;r=!0,this.reconnectScheduler.reset();for(const c of this.topics.keys())try{a.send(JSON.stringify({op:"subscribe",topic:c}))}catch(u){console.warn("[events-client] resubscribe send failed:",u)}const o=this.outbox;this.outbox=[];for(const c of o)if(!(c.op==="subscribe"||c.op==="unsubscribe"))try{a.send(JSON.stringify(c))}catch(u){console.warn("[events-client] outbox flush failed:",u)}},a.onmessage=o=>{if(a!==this.ws)return;let c;try{const u=typeof o.data=="string"?o.data:String(o.data);c=JSON.parse(u)}catch{return}this.handleMessage(c)},a.onclose=()=>{a===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()))},a.onerror=()=>{}}scheduleReconnect(){this.reconnectScheduler.schedule()}broadcastConnectionError(s){for(const n of this.topics.values())for(const a of[...n.error])try{a(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 a of[...n.data])try{a(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 a=this.topics.get(s.topic);if(a)for(const r of[...a.error])try{r(n)}catch(o){console.error(`[events-client] error handler threw on ${s.topic}:`,o)}}else console.warn("[events-client] connection-level error:",s.code,s.message);break}}}}let lt=null;function Et(){return lt||(lt=new ir),lt}function ws(){const[t,s]=i.useState(null),[n,a]=i.useState(!1),[r,o]=i.useState(null);return i.useEffect(()=>Et().subscribe("agents",u=>{o(null),s(u),a(!0)},u=>o(u)),[]),{data:t,loaded:n,error:r}}function Rt(t){const[s,n]=i.useState(null),[a,r]=i.useState(!1),[o,c]=i.useState(null);return i.useEffect(()=>(n(null),r(!1),c(null),Et().subscribe(`task:${t}`,h=>{c(null),n(h),r(!0)},h=>c(h))),[t]),{data:s,loaded:a,error:o}}function ys(t){const[s,n]=i.useState(null),[a,r]=i.useState(!1),[o,c]=i.useState(null);return i.useEffect(()=>{if(!t){n(null),r(!1),c(null);return}n(null),r(!1),c(null);let u=!1,h=!1,x=!1;const m=Et().subscribe(`project-tasks:${t}`,f=>{u||(h=!0,c(null),n(f),r(!0))},f=>{u||(c(f),!(h||x)&&(x=!0,T.tasks.list(t).then(d=>{u||h||(n(d),r(!0))},d=>{console.warn(`[useProjectTasks] REST fallback failed for ${t}:`,d)})))});return()=>{u=!0,m()}},[t]),{data:s,loaded:a,error:o}}let Je=null,be=null,Ye=null,Me=0;const pt=new Set;function Ns(){pt.forEach(t=>t())}async function or(){const t=Me;try{const s=await T.projects.list();if(t!==Me)return;Je=s,Ye=null}catch(s){if(t!==Me)return;Ye=s instanceof Error?s.message:String(s)}finally{t===Me&&(be=null,Ns())}}function gt(){return be||(be=or(),be)}function cr(){Me+=1,Je=null,be=null,Ye=null,Ns()}typeof window<"u"&&window.addEventListener(Ve,cr);async function lr(){const t=be!==null;await gt(),t&&await gt()}function st(){const[,t]=i.useState(0);return i.useEffect(()=>{const s=()=>t(n=>n+1);return pt.add(s),Je===null&&!be&&gt(),()=>{pt.delete(s)}},[]),{projects:Je,error:Ye,refresh:lr}}function dr(t){const[s,n]=i.useState(!1);return i.useEffect(()=>{function a(){if(!t||t.status!=="review"||!t.reviewDispatchedAt||!t.qaAgentId){n(!1);return}const o=Date.now()-Date.parse(t.reviewDispatchedAt);n(o>=xs)}a();const r=setInterval(a,3e4);return()=>clearInterval(r)},[t==null?void 0:t.status,t==null?void 0:t.reviewDispatchedAt,t==null?void 0:t.qaAgentId]),s}const Ss=i.createContext(null);function ur({children:t}){const[s,n]=i.useState(null),a=i.useCallback(o=>n(o),[]),r=i.useCallback(()=>n(null),[]);return e.jsxs(Ss.Provider,{value:{openTask:a},children:[t,s!==null&&e.jsx(hr,{taskId:s,onClose:r,onOpenTask:n},s)]})}function Be(){const t=i.useContext(Ss);if(!t)throw new Error("useTaskDetail must be inside <TaskDetailProvider>");return t}const Jt=us,ks={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"},fr={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 xr({status:t}){return e.jsx("span",{role:"img","aria-label":t,title:t,className:`inline-block h-2 w-2 shrink-0 rounded-full ${fr[t]??"bg-og-300"}`})}function Ct(t){if(!t)return"";const s=t.match(/^task-(\d+)$/);return s?s[1]:t}function Yt({id:t,runtime:s}){const n=jt(s);return t?e.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-baseline gap-1 align-baseline",title:wt(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 dt(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 a=new Date(s);return Number.isNaN(a.getTime())?s:a.toISOString().slice(0,19).replace("T"," ")}function hr({taskId:t,onClose:s,onOpenTask:n}){const{show:a}=xe(),[r,o]=i.useState(!1),[c,u]=i.useState(!1),[h,x]=i.useState(!1),[m,f]=i.useState(!1),[d,j]=i.useState(!1),[k,g]=i.useState(!1),[v,E]=i.useState(null),{data:O,loaded:p,error:N}=Rt(t),{projects:w}=st(),l=v??O,H=dr(l),G=(N==null?void 0:N.message)??null,P=i.useMemo(()=>{const b=new Map;for(const V of w??[])for(const Y of V.agent)for(const K of Y)b.set(K.id,K.runtime);return b},[w]);i.useEffect(()=>{v&&O&&O.updatedAt>=v.updatedAt&&E(null)},[v,O]);const M=b=>{E(b)},R=async()=>{if(l&&confirm(`确定取消 task ${l.id}?`)){u(!0);try{const b=await T.tasks.update(l.id,{status:"cancelled"});M(b),a({kind:"success",title:"任务已取消"})}catch(b){a({kind:"error",title:"取消失败",body:b instanceof Error?b.message:String(b)})}finally{u(!1)}}},I=async()=>{if(!l)return;const V=us.has(l.status)?`task ${l.id} 已是 ${l.status} 状态。手动请 QA 重审会再跑一轮 review,但状态机不会把 QA 结果带回主流程。继续?`:`请 QA 重审 task ${l.id}?这会让 QA agent 立即开始新一轮 review(reviewRound +1)。`;if(confirm(V)){f(!0);try{const Y=await T.tasks.review(l.id);M(Y),a({kind:"success",title:`已派 QA 重审 (round ${Y.reviewRound})`})}catch(Y){a({kind:"error",title:"Review 派发失败",body:Y instanceof Error?Y.message:String(Y)})}finally{f(!1)}}},z=async()=>{if(!l)return;const b=l.status==="merged"?`task ${l.id} 已 merged。Retry 会用同样的标题/描述新建一个 task 从头跑,确定继续?`:`Retry task ${l.id}?这会新建一个 task 从头开始,旧 task 保留为历史。`;if(confirm(b)){x(!0);try{const V=await T.tasks.retry(l.id);a({kind:"success",title:`已新建 task ${V.id}`}),n(V.id)}catch(V){a({kind:"error",title:"Retry 失败",body:V instanceof Error?V.message:String(V)})}finally{x(!1)}}},U=async()=>{if(l&&confirm(`将合并 PR #${l.prNumber} 并收尾(删本地分支 + 压缩 agent 上下文),确定?`)){j(!0);try{const b=await T.tasks.complete(l.id);M(b),a({kind:"success",title:"已标记完成,开始收尾"})}catch(b){a({kind:"error",title:"标记完成失败",body:b instanceof Error?b.message:String(b)})}finally{j(!1)}}},_=async()=>{if(l&&confirm(`派 dev 再修一轮(round → ${l.reviewRound+1}),完成后自动转 QA review?`)){g(!0);try{const b=await T.tasks.continue(l.id);M(b),a({kind:"success",title:`已继续一轮 (round ${b.reviewRound})`})}catch(b){a({kind:"error",title:"继续一轮失败",body:b instanceof Error?b.message:String(b)})}finally{g(!1)}}},B=async()=>{if(l&&confirm(`确认完成 task ${l.id}?project.merge 为 auto 时由 baxian 自动执行合并。`)){j(!0);try{const b=await T.tasks.complete(l.id);M(b),a({kind:"success",title:`已确认(${b.status})`})}catch(b){a({kind:"error",title:"确认失败",body:b instanceof Error?b.message:String(b)})}finally{j(!1)}}};if(r&&l)return e.jsx(kt,{mode:"edit",open:!0,onClose:()=>o(!1),task:l,onUpdated:M});const q=l?`${l.id} ${l.title}`:t;return e.jsx(ve,{open:!0,onClose:s,title:q,titleContent:l?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:l.id}),e.jsx("span",{className:"min-w-0 truncate text-og-1000",children:l.title})]}):void 0,size:"lg",footer:l?y(l):void 0,children:ie()});function ie(){if(G&&!l)return e.jsxs("div",{className:"text-[13px] text-danger",children:["Error: ",G]});if(p&&!l)return e.jsxs("div",{className:"text-[13px] text-danger",children:["Task not found: ",t]});if(!l)return e.jsx("div",{className:"text-[13px] text-og-500",children:"Loading…"});const b=l.preferredAgentId==="",V=l.status==="approved"&&l.prNumber!==void 0,Y=l.status==="merge-ready"&&l.prNumber!==void 0,K=l.status==="ready",ee=l.status==="max_rounds"&&l.phase!=="spec",ce=l.status==="max_rounds"&&l.phase==="spec";return e.jsxs("div",{children:[G&&e.jsxs("div",{className:"mb-4 text-[13px] text-danger",children:["Error: ",G]}),b&&e.jsx("div",{className:"mb-4 rounded-md border border-[#fde68a] bg-[#fef3c7]/60 px-3 py-2.5 text-[12px] text-warn",children:l.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:l.status}),")."]})}),e.jsx("div",{className:"mb-2 flex flex-wrap items-center gap-3",children:e.jsx("span",{className:ks[l.status],children:l.status})}),e.jsxs("div",{className:"mb-4 text-[12px] text-og-500",children:["Created at ",dt(l.createdAt),", Updated at ",dt(l.updatedAt)]}),H&&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 ",dt(l.reviewDispatchedAt)," 超过 10 分钟未提交 verdict。 可能原因:QA agent 上下文压缩后误报已完成、agent 卡住、或 GitHub API 异常。"]}),e.jsx("div",{className:"mt-2 text-og-700",children:"建议:打开 QA terminal 检查实际状态,或手动 Call review 重新派发。"})]}),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:"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."}),l.prUrl&&e.jsxs("a",{href:l.prUrl,target:"_blank",rel:"noopener noreferrer",className:"btn-secondary mt-3 !border-[#bbf7d0] !text-success hover:!bg-[#dcfce7] hover:!border-success",children:["Open PR #",l.prNumber]})]}),K&&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 完成(",l.reviewRound," 轮)。点击「确认」收尾",l.prNumber?"(merge:auto 时自动合并 PR)":"",",或「Cancel」丢弃。"]}),e.jsx(Xt,{taskId:l.id}),l.prUrl&&e.jsxs("a",{href:l.prUrl,target:"_blank",rel:"noopener noreferrer",className:"btn-secondary mt-3 !border-[#bbf7d0] !text-success hover:!bg-[#dcfce7] hover:!border-success",children:["Open PR #",l.prNumber]})]}),Y&&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 执行合并)。"}),l.prUrl&&e.jsxs("a",{href:l.prUrl,target:"_blank",rel:"noopener noreferrer",className:"btn-secondary mt-3 !border-[#bbf7d0] !text-success hover:!bg-[#dcfce7] hover:!border-success",children:["Open PR #",l.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 ",l.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 越容易偏离重点。若无严重问题,建议先合并本次成果,剩余问题另开任务跟进。"})]}),ce&&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 ",l.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(Xt,{taskId:l.id})]}),e.jsx("pre",{className:"card mb-4 whitespace-pre-wrap p-4 text-[13px] text-og-800",children:l.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:l.projectId})]}),e.jsxs("div",{className:"text-og-500",children:["Round: ",e.jsx("span",{className:"font-mono text-og-800",children:l.reviewRound})," ",e.jsxs("span",{children:["spec: ",e.jsx("span",{className:"font-mono text-og-800",children:l.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(Yt,{id:l.agentId,runtime:P.get(l.agentId)})]}),e.jsxs("div",{className:"text-og-500",children:["QA: ",e.jsx(Yt,{id:l.qaAgentId??"",runtime:P.get(l.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:"," ",l.prNumber?l.prUrl?e.jsxs("a",{href:l.prUrl,target:"_blank",rel:"noopener noreferrer",className:"text-accent hover:text-accent-hover",children:["#",l.prNumber]}):e.jsxs("span",{className:"font-mono text-og-800",children:["#",l.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:l.branch||"—"})]})]})]}),e.jsx(Zn,{task:l,onClose:s}),e.jsx(sr,{task:l,onClose:s})]})}function y(b){const V=b.status==="max_rounds",Y=V&&b.phase!=="spec",K=V&&b.phase==="spec",ee=b.status==="ready"||b.status==="merge-ready",ce=b.reviewMode==="server"&&b.status==="approved",ne=b.status==="pending",A=b.status==="pending"||b.status==="in_progress"||V||ee||ce,X=(Jt.has(b.status)||K)&&!!b.preferredAgentId,$=!!b.prNumber&&!K&&b.reviewMode!=="server",te=b.reviewMode==="server",J=Y&&(!!b.prNumber||te),S=Y&&(!!b.prNumber||te)&&!!b.agentId,F=te&&b.status==="approved",D=b.preferredAgentId==="";return e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",disabled:!ne,onClick:()=>o(!0),className:"btn-secondary",children:"Edit"}),e.jsx("button",{type:"button",disabled:!A||c,onClick:R,className:"btn-secondary !border-[#fecaca] !text-danger hover:!bg-[#fef2f2] hover:!border-danger",children:c?"Cancelling…":"Cancel"}),!Y&&e.jsx("button",{type:"button",disabled:!X||h,onClick:z,title:Jt.has(b.status)||K?D?"Legacy task has no preferred dev to retry against":"新建一个 task 从头跑,丢弃当前 worktree/branch":`Cannot retry in status ${b.status}`,className:"btn-secondary",children:h?"Retrying…":"Retry"}),e.jsx("button",{type:"button",disabled:!$||m,onClick:I,title:b.prNumber?K?"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:m?"Dispatching…":"Call review"}),Y&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",disabled:!S||k,onClick:_,title:"派 dev 再修一轮,完成后自动转 QA review",className:"btn-secondary !border-accent-soft !text-accent hover:!bg-accent-soft hover:!border-accent",children:k?"Continuing…":"继续一轮"}),e.jsx("button",{type:"button",disabled:!J||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:B,title:"确认完成;merge:auto 时由 baxian 执行合并",className:"btn-secondary !border-[#bbf7d0] !text-success hover:!bg-[#dcfce7] hover:!border-success",children:d?"Confirming…":"确认"}),F&&e.jsx("button",{type:"button",disabled:d,onClick:B,title:"发布派发失败后重试 push/PR 步骤",className:"btn-secondary !border-accent-soft !text-accent hover:!bg-accent-soft hover:!border-accent",children:d?"Retrying…":"重试发布"})]})}}function Xt({taskId:t}){var o;const[s,n]=i.useState(null);if(i.useEffect(()=>{let c=!0;return T.tasks.reviews(t).then(u=>{c&&n(u)}).catch(()=>{c&&n([])}),()=>{c=!1}},[t]),!s||s.length===0)return null;const a=s[s.length-1],r=s.reduce((c,u)=>{var h;return c+(((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:((o=a.findings)==null?void 0:o.verdict)??"—"})," ","· findings 共 ",r," 条"]})}const ut="baxian:terminal-activated";function Es({group:t,projectId:s,agentsById:n,agentsLoaded:a,agentsError:r=!1,tasks:o,onDeleted:c,terminalMode:u="activity-preview"}){var G,P,M;const h=t.find(R=>R.role==="dev")??t[0],x=t.find(R=>R.role==="qa"),m=o.filter(R=>pr(R,h==null?void 0:h.id,x==null?void 0:x.id)),f=h?o.filter(R=>gr(R,s,h.id)).sort((R,I)=>R.createdAt.localeCompare(I.createdAt)):[],d=h?n.get(h.id):void 0,j=!!d&&d.runtimeStatus==="idle"&&((G=d.binding)==null?void 0:G.status)!=="awaiting_human"&&!((P=d.binding)!=null&&P.creationToken)&&!((M=d.binding)!=null&&M.taskId),k=`Agent group ${t.map(R=>R.id).join(" / ")}`,{openTask:g}=Be(),v=u==="embedded-full",E=i.useId(),[O,p]=i.useState(null);i.useEffect(()=>{if(!v)return;const R=U=>{U.composedPath().some(q=>q instanceof Element&&q.hasAttribute("data-agent-card"))||p(null)},I=U=>{if(U.key!=="Escape")return;const _=document.activeElement;_ instanceof Element&&_.closest("[data-agent-card]")||p(null)},z=U=>{const _=U.detail;(_==null?void 0:_.groupId)!==E&&p(null)};return document.addEventListener("click",R),document.addEventListener("keydown",I),document.addEventListener(ut,z),()=>{document.removeEventListener("click",R),document.removeEventListener("keydown",I),document.removeEventListener(ut,z)}},[v,E]);const N=R=>{p(R),document.dispatchEvent(new CustomEvent(ut,{detail:{groupId:E}}))},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",l=!!h&&f.length>0,H=m.length===0&&!l;return e.jsxs("div",{role:"group","aria-label":k,className:"min-w-0",children:[l&&h&&e.jsx(mr,{tasks:f,devId:h.id,dispatchReady:j,label:k}),m.length>0&&e.jsx("div",{className:"card mb-2 max-h-28 overflow-y-auto divide-y divide-hairline",children:m.map(R=>{const I=R.phase==="spec"?R.specReviewRound??0:R.reviewRound;return e.jsxs("button",{type:"button",onClick:()=>g(R.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:R.id,children:Ct(R.id)}),e.jsx("span",{className:"truncate text-og-1000",children:R.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:`${ks[R.status]} shrink-0`,children:R.status})]})]},R.id)})}),H&&e.jsx("div",{className:"mb-2 rounded-lg border border-hairline bg-surface px-3 py-2 text-[13px] text-og-400","aria-label":`${k} no active task`,children:"暂无任务"}),e.jsx("div",{className:`grid grid-cols-1 ${w} gap-4`,children:t.map(R=>{const I=n.get(R.id),z=I??{id:R.id,projectId:s,runtimeStatus:"unknown",tmuxSessionStatus:"unknown",stale:!0};return e.jsx(Wn,{agent:z,projectId:s,role:R.role,runtime:R.runtime,pendingRestart:a&&!I,terminalLoading:!a&&!I&&!r,onDeleted:c,showTaskBinding:!1,terminalMode:u,...v?{active:O===R.id,onActivate:()=>N(R.id)}:{}},R.id)})})]})}function mr({tasks:t,devId:s,dispatchReady:n,label:a}){const{show:r}=xe(),{openTask:o}=Be(),[c,u]=i.useState(null),h=async x=>{u(x);try{await T.tasks.dispatch(x,{agentId:s}),r({kind:"success",title:`Task ${x} 已派给 ${s}`})}catch(m){r({kind:"error",title:"派遣失败",body:m instanceof Error?m.message:String(m)})}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":`${a} claimable tasks for ${s}`,children:t.map(x=>{const m=x.preferredAgentId==="",f=c!==null;return e.jsxs("div",{className:"flex items-center gap-3 px-3 py-2 text-[13px]",children:[e.jsxs("button",{type:"button",onClick:()=>o(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:Ct(x.id)}),e.jsx("span",{className:"truncate text-og-1000",title:x.title,children:x.title}),m&&e.jsx("span",{className:"pill shrink-0",children:"未分配"})]}),e.jsx("button",{type:"button",onClick:()=>void h(x.id),disabled:!n||f,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:c===x.id?"Starting…":"Start"})]},x.id)})})}function pr(t,s,n){return!(!s||!fs.has(t.status)||!(t.agentId===s||t.preferredAgentId===s)||n&&t.qaAgentId&&t.qaAgentId!==n)}function gr(t,s,n){return t.projectId!==s||t.status!=="pending"?!1:t.preferredAgentId===n||t.preferredAgentId===""}const br=/^[a-z][a-z0-9-]{1,31}$/,vr=[/^https?:\/\/[^/\s]+\/[^\s]+$/,/^ssh:\/\/[^/\s]+\/[^\s]+$/,/^[^@/\s]+@[^:/\s]+:[^\s]+$/,/^[^/\s:@]+\/[^/\s]+$/],Zt="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",es="mt-1 text-[12px] text-danger";function jr({open:t,onClose:s,onCreated:n}){const[a,r]=i.useState(""),[o,c]=i.useState(""),[u,h]=i.useState(null),[x,m]=i.useState(""),[f,d]=i.useState(!1),[j,k]=i.useState(null),[g,v]=i.useState({}),[E,O]=i.useState(new Set),p=i.useRef(0),{show:N}=xe(),{flagDirty:w}=tt();i.useEffect(()=>{if(!t)return;p.current+=1;const P=p.current;r(""),c(""),h(null),m(""),k(null),v({}),O(new Set),T.config.get().then(M=>{P===p.current&&O(new Set(M.project.map(R=>R.id)))}).catch(()=>{})},[t]);const l=()=>{f||s()},H=()=>{const P={};return a?br.test(a)?E.has(a)&&(P.id="该 id 已被占用"):P.id="小写字母开头,只含 a-z 0-9 -,长度 2-32":P.id="必填",o?vr.some(M=>M.test(o.trim()))||(P.repo="需为 git URL(https / ssh / scp,如 https://gitlab.example.com/group/proj.git)或 owner/repo"):P.repo="必填",v(P),Object.keys(P).length===0},G=async P=>{if(P.preventDefault(),!!H()){d(!0),k(null);try{const M=await T.projects.create({id:a,repo:o.trim(),merge:u,...x?{review:{mode:x}}:{}});M.restartRequired&&w(),N({kind:"success",title:`项目 ${M.project.id} 已创建`}),n(M.project.id)}catch(M){k(M instanceof Error?M.message:String(M))}finally{d(!1)}}};return e.jsx(ve,{open:t,onClose:l,title:"新建项目",size:"md",footer:e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:l,disabled:f,className:"btn-secondary",children:"取消"}),e.jsx("button",{type:"submit",form:"create-project-form",disabled:f,className:"btn-primary",children:f?"创建中…":"创建"})]}),children:e.jsxs("form",{id:"create-project-form",onSubmit:G,className:"space-y-3",children:[j&&e.jsx("div",{className:"rounded-md border border-[#fecaca] bg-[#fef2f2] px-3 py-2 text-[13px] text-danger",children:j}),e.jsxs("div",{children:[e.jsx("label",{className:Ge,htmlFor:"proj-id",children:"项目 ID"}),e.jsx("input",{id:"proj-id",type:"text",value:a,onChange:P=>r(P.target.value),className:Zt,placeholder:"kongkong",disabled:f}),g.id&&e.jsx("div",{className:es,children:g.id})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ge,htmlFor:"proj-repo",children:"Git 仓库地址"}),e.jsx("input",{id:"proj-repo",type:"text",value:o,onChange:P=>c(P.target.value),className:Zt,placeholder:"https://github.com/baxian-ai/baxian.git",disabled:f}),g.repo&&e.jsx("div",{className:es,children:g.repo})]}),e.jsxs("div",{children:[e.jsx("span",{className:Ge,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:f,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:f,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:Ge,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:()=>m(""),disabled:f,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:()=>m("github"),disabled:f,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:()=>m("server"),disabled:f,className:"h-3.5 w-3.5 accent-[#1348dc]"}),e.jsx("span",{className:"text-[13px] text-og-800",children:"Server"})]})]})]})})}const ts=/^[a-z][a-z0-9-]{1,31}$/,wr=500,ke="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",ss="mt-1 text-[12px] text-danger",ft="mt-1 text-[12px] text-og-500",Ee="h-3.5 w-3.5 accent-[#1348dc]",ns={id:"",role:"dev",pairWith:"",mode:"local",host:"",runtime:"",workdir:"",yolo:!0,model:"",addDirs:""};function yr(t){return t.alias?t.alias:`${t.user?`${t.user}@`:""}${t.hostname}${t.port!=null?`:${t.port}`:""}`}function Rs({open:t,onClose:s,projectId:n,onCreated:a}){var ne;const[r,o]=i.useState(ns),[c,u]=i.useState(null),[h,x]=i.useState([]),[m,f]=i.useState(new Set),[d,j]=i.useState(null),[k,g]=i.useState(!1),[v,E]=i.useState(!1),[O,p]=i.useState(null),[N,w]=i.useState(!1),l=i.useRef(null),H=i.useRef(null),G=i.useRef(0),{show:P}=xe(),{flagDirty:M}=tt();i.useEffect(()=>{if(!t)return;G.current+=1;const A=G.current;o(ns),u(null),x([]),f(new Set),j(null),g(!1),p(null),w(!1),T.config.get().then(X=>{if(A!==G.current)return;const $=X.project.find(J=>J.id===n)??null;u($),x(X.host??[]);const te=new Set;X.project.forEach(J=>J.agent.forEach(S=>S.forEach(F=>te.add(F.id)))),f(te)}).catch(()=>{})},[t,n]);const R=()=>{v||s()},I=i.useCallback(()=>{l.current&&l.current.abort();const A=new AbortController;l.current=A,g(!0),p(null);const X=r.mode==="remote"?{hostId:r.host}:{};T.agents.probe(r.mode,X,{signal:A.signal}).then($=>{A.signal.aborted||(j($),p(null))}).catch($=>{A.signal.aborted||(j(null),p($ instanceof Error?$.message:String($)))}).finally(()=>{l.current===A&&g(!1)})},[r.mode,r.host]);i.useEffect(()=>{if(t&&(j(null),l.current&&l.current.abort(),!(r.mode==="remote"&&!r.host)))return H.current&&clearTimeout(H.current),H.current=setTimeout(I,wr),()=>{H.current&&clearTimeout(H.current)}},[t,r.mode,r.host,I]),i.useEffect(()=>{t||l.current&&l.current.abort()},[t]),i.useEffect(()=>()=>{l.current&&l.current.abort(),H.current&&clearTimeout(H.current)},[]);const z=(c==null?void 0:c.agent.filter(A=>A.length===1&&A[0].role==="dev").map(A=>A[0]))??[],U=z.length>0,_=ts.test(r.id)&&!m.has(r.id),B=r.mode==="local"||r.mode==="remote"&&r.host!=="",q=r.runtime!==""&&(r.runtime==="claude-code"?!!(d!=null&&d.runtimes["claude-code"].ok):!!(d!=null&&d.runtimes.codex.ok)),ie=!!(d!=null&&d.tmux.ok),y=r.mode==="local"||!!((ne=d==null?void 0:d.ssh)!=null&&ne.ok),b=r.role==="dev"||r.role==="qa"&&r.pairWith!=="",V=!v&&_&&B&&b&&q&&ie&&y,Y=async A=>{if(A.preventDefault(),!!V){E(!0),p(null);try{const X=r.addDirs.split(`
5
+ `).map(J=>J.trim()).filter(J=>J.length>0),$={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()}:{},...X.length>0?{addDirs:X}:{},...r.role==="qa"?{pairWith:r.pairWith}:{}},te=await T.projects.addAgent(n,$);te.restartRequired&&M(),P({kind:"success",title:`Agent ${te.agent.id} 已添加到 ${n}`}),a(),s()}catch(X){p(X instanceof Error?X.message:String(X))}finally{E(!1)}}},K=({rt:A})=>{if(r.mode==="remote"&&!r.host)return e.jsx("span",{className:"ml-2 text-[12px] text-og-400",children:"(请先选择 Host)"});if(k)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 $=d.runtimes[A];return $.ok?e.jsxs("span",{className:"ml-2 text-[12px] text-success",children:["✓ ",$.path??""]}):e.jsxs("span",{className:"ml-2 text-[12px] text-danger",title:$.message,children:["⨯ ",$.message]})},ee=()=>r.mode==="remote"&&!r.host?null:k?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,ce=()=>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:R,title:`添加 Agent 到 ${n}`,size:"lg",footer:e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:R,disabled:v,className:"btn-secondary",children:"取消"}),e.jsx("button",{type:"submit",form:"create-agent-form",disabled:!V,className:"btn-primary",children:v?"添加中…":"添加 Agent"})]}),children:e.jsxs("form",{id:"create-agent-form",onSubmit:Y,className:"space-y-3",children:[O&&e.jsx("div",{className:"rounded-md border border-[#fecaca] bg-[#fef2f2] px-3 py-2 text-[13px] text-danger",children:O}),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:A=>o({...r,id:A.target.value}),className:ke,placeholder:"kk-cc",disabled:v}),r.id&&!ts.test(r.id)&&e.jsx("div",{className:ss,children:"小写字母开头,只含 a-z 0-9 -,长度 2-32"}),r.id&&m.has(r.id)&&e.jsx("div",{className:ss,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:()=>o({...r,role:"dev",pairWith:""}),disabled:v}),e.jsx("span",{className:"text-[13px] text-og-800",children:"Dev"})]}),e.jsxs("label",{className:"inline-flex items-center gap-2",title:U?"":"请先创建一个 Dev Agent",children:[e.jsx("input",{type:"radio",name:"role",checked:r.role==="qa",className:Ee,onChange:()=>o({...r,role:"qa"}),disabled:v||!U}),e.jsx("span",{className:`text-[13px] ${U?"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:A=>o({...r,pairWith:A.target.value}),className:ke,disabled:v,children:[e.jsx("option",{value:"",children:"请选择"}),z.map(A=>e.jsxs("option",{value:A.id,children:[A.id," (dev, ",A.mode,")"]},A.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:()=>o({...r,mode:"local",host:""}),disabled:v}),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:()=>o({...r,mode:"remote"}),disabled:v}),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:A=>o({...r,host:A.target.value}),className:ke,disabled:v,children:[e.jsx("option",{value:"",children:"请选择 Host"}),h.map(A=>e.jsx("option",{value:A.id,children:yr(A)},A.id))]}),e.jsx("div",{className:ft,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:I,className:"text-[12px] text-accent transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",disabled:v||k||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:()=>o({...r,runtime:"claude-code"}),disabled:v||(d?!d.runtimes["claude-code"].ok:!1)}),e.jsx("span",{className:"text-[13px] text-og-800",children:"Claude Code"}),e.jsx(K,{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:()=>o({...r,runtime:"codex"}),disabled:v||(d?!d.runtimes.codex.ok:!1)}),e.jsx("span",{className:"text-[13px] text-og-800",children:"Codex"}),e.jsx(K,{rt:"codex"})]}),e.jsx("div",{className:"mt-2",children:e.jsx(ee,{})}),e.jsx("div",{children:e.jsx(ce,{})})]}),e.jsxs("div",{children:[e.jsxs("button",{type:"button",onClick:()=>w(A=>!A),"aria-expanded":N,"aria-controls":N?"advanced-options":void 0,className:"flex w-full items-center justify-between rounded-md px-1 py-1.5 text-left text-[12px] font-medium text-og-700 transition-colors hover:bg-og-50",children:[e.jsx("span",{children:"高级选项"}),e.jsx("span",{className:"text-og-400",children:N?"收起":"展开"})]}),N&&e.jsxs("div",{id:"advanced-options",className:"mt-3 space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:ge,htmlFor:"workdir",children:"Workdir(可选)"}),e.jsx("input",{id:"workdir",type:"text",value:r.workdir,onChange:A=>o({...r,workdir:A.target.value}),className:ke,placeholder:"留空时自动 clone 到 ~/.baxian/repos/<owner>/<repo>",disabled:v})]}),e.jsxs("div",{children:[e.jsx("label",{className:ge,htmlFor:"model",children:"Model(可选)"}),e.jsx("input",{id:"model",type:"text",value:r.model,onChange:A=>o({...r,model:A.target.value}),className:ke,placeholder:r.runtime==="codex"?"例: o3 / gpt-4o(留空走 default)":"例: sonnet / opus / claude-sonnet-4-6(留空走 default)",disabled:v}),e.jsx("div",{className:ft,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:A=>o({...r,addDirs:A.target.value}),className:`${ke} font-mono text-[12px]`,rows:3,placeholder:`每行一个绝对路径,例:
6
+ /Users/me/shared-libs
7
+ /Users/me/extra-repo`,disabled:v}),e.jsx("div",{className:ft,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:A=>o({...r,yolo:A.target.checked}),disabled:v}),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 rs="***",De="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",Le="mb-1.5 block text-[12px] font-medium text-og-700",xt={hostname:"",port:"",alias:"",user:"",password:""};function Nr(t){return t.alias?t.alias:`${t.user?`${t.user}@`:""}${t.hostname}${t.port!=null?`:${t.port}`:""}`}function Sr({open:t,onClose:s}){const[n,a]=i.useState([]),[r,o]=i.useState("list"),[c,u]=i.useState(null),[h,x]=i.useState(!1),[m,f]=i.useState(!1),[d,j]=i.useState(xt),[k,g]=i.useState(null),[v,E]=i.useState(!1),[O,p]=i.useState(!1),[N,w]=i.useState(null),{show:l}=xe(),H=i.useCallback(()=>{T.hosts.list().then(a).catch(y=>g(y instanceof Error?y.message:String(y)))},[]);i.useEffect(()=>{t&&(o("list"),u(null),j(xt),g(null),w(null),H())},[t,H]);const G=()=>{u(null),x(!1),f(!1),j(xt),g(null),w(null),o("form")},P=y=>{u(y.id??null),x(y.password===rs),f(!1),j({hostname:y.hostname,port:y.port!=null?String(y.port):"",alias:y.alias??"",user:y.user??"",password:""}),g(null),w(null),o("form")},M=()=>{const y={hostname:d.hostname.trim()};return c?(y.port=d.port.trim()?Number(d.port):null,y.alias=d.alias.trim(),y.user=d.user.trim()):(d.port.trim()&&(y.port=Number(d.port)),d.alias.trim()&&(y.alias=d.alias.trim()),d.user.trim()&&(y.user=d.user.trim())),c&&m?y.password="":d.password&&(y.password=d.password),y},R=d.port.trim(),I=R===""||/^\d+$/.test(R)&&Number(R)>0&&Number(R)<=65535,z=d.hostname.trim().length>0&&I,U=async()=>{if(z){p(!0),w(null),g(null);try{const y=await T.hosts.check({...M(),...c?{id:c}:{}});w(y)}catch(y){g(y instanceof Error?y.message:String(y))}finally{p(!1)}}},_=async y=>{if(y.preventDefault(),!(!z||v)){E(!0),g(null);try{if(c)await T.hosts.update(c,M()),l({kind:"success",title:`Host ${c} 已更新`});else{const b=await T.hosts.create(M());l({kind:"success",title:`Host ${b.host.id} 已添加`})}H(),o("list")}catch(b){g(b instanceof Error?b.message:String(b))}finally{E(!1)}}},B=async y=>{g(null);try{await T.hosts.delete(y.id),l({kind:"success",title:`Host ${y.id} 已删除`}),H()}catch(b){g(b instanceof Error?b.message:String(b))}},q=e.jsx("button",{type:"button",onClick:s,className:"btn-secondary",children:"关闭"}),ie=e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:()=>o("list"),disabled:v,className:"btn-secondary",children:"返回"}),e.jsx("button",{type:"submit",form:"host-form",disabled:!z||v,className:"btn-primary",children:v?"保存中…":"保存"})]});return e.jsxs(ve,{open:t,onClose:s,title:"Host 管理",size:"md",footer:r==="list"?q:ie,children:[k&&e.jsx("div",{className:"mb-3 rounded-md border border-[#fecaca] bg-[#fef2f2] px-3 py-2 text-[13px] text-danger",children:k}),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(y=>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:Nr(y)}),e.jsxs("div",{className:"truncate text-[12px] text-og-500",children:[(y.user?`${y.user}@`:"")+y.hostname,y.port!=null?`:${y.port}`:"",y.password===rs?" · 密码已保存":""]})]}),e.jsxs("div",{className:"flex shrink-0 gap-2",children:[e.jsx("button",{type:"button",onClick:()=>P(y),className:"text-[12px] text-accent transition-colors hover:text-accent-hover",children:"编辑"}),e.jsx("button",{type:"button",onClick:()=>B(y),className:"text-[12px] text-danger transition-colors hover:opacity-80",children:"删除"})]})]},y.id))}),e.jsx("button",{type:"button",onClick:G,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:Le,htmlFor:"host-hostname",children:"Host 地址"}),e.jsx("input",{id:"host-hostname",type:"text",value:d.hostname,onChange:y=>j({...d,hostname:y.target.value}),className:De,placeholder:"remote.example.com",disabled:v})]}),e.jsxs("div",{children:[e.jsx("label",{className:Le,htmlFor:"host-port",children:"端口(可选)"}),e.jsx("input",{id:"host-port",type:"text",inputMode:"numeric",value:d.port,onChange:y=>j({...d,port:y.target.value}),className:De,placeholder:"22",disabled:v}),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:Le,htmlFor:"host-alias",children:"别名(可选)"}),e.jsx("input",{id:"host-alias",type:"text",value:d.alias,onChange:y=>j({...d,alias:y.target.value}),className:De,placeholder:"Prod worker",disabled:v})]}),e.jsxs("div",{children:[e.jsx("label",{className:Le,htmlFor:"host-user",children:"用户名(可选)"}),e.jsx("input",{id:"host-user",type:"text",value:d.user,onChange:y=>j({...d,user:y.target.value}),className:De,placeholder:"留空则读 ~/.ssh/config 的 User",disabled:v})]}),e.jsxs("div",{children:[e.jsx("label",{className:Le,htmlFor:"host-password",children:"密码(可选)"}),e.jsx("input",{id:"host-password",type:"password",value:m?"":d.password,onChange:y=>j({...d,password:y.target.value}),className:De,placeholder:h?"已设置,留空保持不变":"留空使用 key 认证",disabled:v||m,autoComplete:"new-password"}),c&&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:m,onChange:y=>f(y.target.checked),disabled:v}),"清除已保存的密码(改用 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||O||v,className:"text-[12px] text-accent transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",children:O?"测试中…":"测试连接"}),N&&e.jsxs("span",{className:`text-[12px] ${N.ok?"text-success":"text-danger"}`,children:[N.ok?"✓ ":"⨯ ",N.message]})]})]})]})}const Cs="topbar-actions";function as(){return typeof document>"u"?null:document.getElementById(Cs)}function As({children:t}){const[s,n]=i.useState(as);return i.useEffect(()=>{s||n(as())},[s]),s?Ms.createPortal(t,s):null}function kr(){const{openTask:t}=Be(),{projects:s,error:n,refresh:a}=st(),r=s??[],o=s!==null,[c,u]=i.useState(!1),[h,x]=i.useState(!1),[m,f]=i.useState(!1),[d,j]=i.useState({kind:"closed"}),{data:k,loaded:g,error:v}=ws(),E=(v==null?void 0:v.message)??null,O=new Map((k??[]).map(I=>[I.id,I])),p=n??E,[N,w]=i.useState(!1),l=i.useRef(null),H=i.useRef(null),G=i.useId(),P=i.useId();i.useEffect(()=>{if(!N)return;const I=U=>{var B,q;const _=U.target;_&&((B=H.current)!=null&&B.contains(_)||(q=l.current)!=null&&q.contains(_)||w(!1))},z=U=>{var _;U.key==="Escape"&&(w(!1),(_=l.current)==null||_.focus())};return document.addEventListener("mousedown",I),document.addEventListener("keydown",z),()=>{document.removeEventListener("mousedown",I),document.removeEventListener("keydown",z)}},[N]);const M=r.length===0,R=e.jsx("button",{type:"button",onClick:()=>x(!0),disabled:M,"aria-describedby":M?"create-task-hint":void 0,className:"btn-ghost",children:"+ 新建 Task"});return e.jsxs("div",{children:[e.jsxs(As,{children:[M?e.jsx("span",{className:"inline-flex",title:"请先创建项目",children:R}):R,M&&e.jsx("span",{id:"create-task-hint",className:"sr-only",children:"请先创建项目"}),e.jsxs("div",{className:"relative",children:[e.jsx("button",{ref:l,id:P,type:"button",onClick:()=>w(I=>!I),"aria-haspopup":"menu","aria-expanded":N,"aria-controls":N?G:void 0,"aria-label":"更多操作",className:"flex h-8 w-8 items-center justify-center rounded text-og-500 transition-colors hover:bg-og-50 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:H,id:G,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),f(!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"}),p&&e.jsxs("div",{className:"mb-4 text-[13px] text-danger",children:["Error: ",p]}),o&&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(Er,{project:I,agentsById:O,agentsLoaded:g,agentsError:!!v,onAgentDeleted:a},I.id)),e.jsx(jr,{open:c,onClose:()=>u(!1),onCreated:I=>{u(!1),a(),j({kind:"asking",projectId:I})}}),e.jsx(Sr,{open:m,onClose:()=>f(!1)}),e.jsx(ve,{open:d.kind==="asking",onClose:()=>j({kind:"closed"}),title:"项目已创建",size:"sm",footer:e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:()=>j({kind:"closed"}),className:"btn-secondary",children:"稍后再加"}),e.jsx("button",{type:"button",onClick:()=>{d.kind==="asking"&&j({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(Rs,{open:!0,projectId:d.projectId,onClose:()=>j({kind:"closed"}),onCreated:()=>{a()}}),e.jsx(kt,{open:h,onClose:()=>x(!1),onCreated:I=>t(I.id)})]})}function Er({project:t,agentsById:s,agentsLoaded:n,agentsError:a,onAgentDeleted:r}){const{data:o,error:c}=ys(t.id),u=o??[],h=(c==null?void 0:c.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(_e,{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(_e,{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,m)=>e.jsx(Es,{group:x,projectId:t.id,agentsById:s,agentsLoaded:n,agentsError:a,tasks:u,onDeleted:r,terminalMode:"embedded-full"},x.map(f=>f.id).join(":")||m))})]})}function Xe(t){const s=t.match(/^task-(\d+)$/);return s?parseInt(s[1],10):Number.NaN}function Rr(t,s){const n=Xe(t.id),a=Xe(s.id);return Number.isNaN(n)||Number.isNaN(a)?t.id.localeCompare(s.id):n-a}function Cr(t,s){const n=(s.updatedAt??"").localeCompare(t.updatedAt??"");if(n!==0)return n;const a=Xe(t.id),r=Xe(s.id);return Number.isNaN(a)||Number.isNaN(r)?s.id.localeCompare(t.id):r-a}function is(t,s){const[n,a]=i.useState(nt);i.useEffect(()=>a(nt),[s]);const r=t.slice(0,n),o=t.length>r.length;return{items:r,hasMore:o,loadMore:()=>a(u=>u+nt),total:t.length}}function Ar(t){const[s,n]=i.useState([]),[a,r]=i.useState(!1),[o,c]=i.useState(!1),[u,h]=i.useState(!1),[x,m]=i.useState(null),f=i.useRef(0),d=i.useRef(0),j=i.useCallback(k=>{const g=++f.current,v=k==="first"?0:d.current;c(!0),m(null),T.tasks.page(t,{category:"done",offset:v}).then(E=>{f.current===g&&(n(O=>k==="first"?E.tasks:[...O,...E.tasks]),r(E.hasMore),d.current=E.nextOffset,h(!0),c(!1))},E=>{f.current===g&&(m(E instanceof Error?E.message:String(E)),c(!1))})},[t]);return i.useEffect(()=>{f.current+=1,d.current=0,n([]),r(!1),h(!1),m(null),c(!1)},[t]),{items:s,hasMore:a,loading:o,loaded:u,error:x,load:j}}function Tr({projectId:t,openTasks:s,className:n=""}){const a=i.useMemo(()=>s.filter(f=>fs.has(f.status)).sort(Cr),[s]),r=i.useMemo(()=>s.filter(f=>f.status==="pending").sort(Rr),[s]),o=is(a,t),c=is(r,t),u=Ar(t),[h,x]=i.useState(!1);i.useEffect(()=>{x(!1)},[t]);const m=()=>{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(os,{title:"IN PROGRESS",section:o,emptyHint:"暂无正在处理的任务"}),e.jsx(os,{title:"PENDING",section:c,emptyHint:"暂无待处理的任务"}),e.jsxs("div",{children:[e.jsxs("button",{type:"button",onClick:m,"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($r,{state:u})]})]})})}function os({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(a=>e.jsx(Ts,{task:a},a.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 $r({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(Ts,{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 Ir(t){const[s,n]=i.useState(!1);return i.useEffect(()=>{function a(){if(t.status!=="review"||!t.reviewDispatchedAt||!t.qaAgentId){n(!1);return}n(Date.now()-Date.parse(t.reviewDispatchedAt)>=xs)}a();const r=setInterval(a,3e4);return()=>clearInterval(r)},[t.status,t.reviewDispatchedAt,t.qaAgentId]),s}function Ts({task:t}){const{openTask:s}=Be(),n=t.phase==="spec"?t.specReviewRound??0:t.reviewRound,a=Ir(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:Ct(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"}),a&&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(xr,{status:t.status})]})}const Pr=[],$s="baxian.taskPanel.open";function Dr(){try{return localStorage.getItem($s)!=="0"}catch{return!0}}function Lr(){const{id:t}=Ze(),s=Fe(),{show:n}=xe(),{openTask:a}=Be(),{refresh:r}=st(),[o,c]=i.useState(null),[u,h]=i.useState(null),[x,m]=i.useState(!1),[f,d]=i.useState(!1),[j,k]=i.useState(Dr),[g,v]=i.useState(!1),[E,O]=i.useState(!1),[p,N]=i.useState(""),[w,l]=i.useState(!1),[H,G]=i.useState(null),P=i.useRef(null),M=i.useRef(null),R=i.useId(),I=i.useId(),z=i.useRef(0),{data:U,loaded:_,error:B}=ws(),{data:q,error:ie}=ys(t),y=(B==null?void 0:B.message)??null,b=(ie==null?void 0:ie.message)??null,V=q??Pr,Y=new Map((U??[]).map($=>[$.id,$])),K=u??y??b,ee=i.useCallback(async $=>{const te=++z.current;try{const J=await T.projects.get($);if(te!==z.current)return;c(J),h(null)}catch(J){if(te!==z.current)return;h(J instanceof Error?J.message:String(J))}},[]);i.useEffect(()=>{t&&(c(null),h(null),ee(t))},[t,ee]),i.useEffect(()=>{if(!g)return;const $=J=>{var F,D;const S=J.target;S&&((F=M.current)!=null&&F.contains(S)||(D=P.current)!=null&&D.contains(S)||v(!1))},te=J=>{var S;J.key==="Escape"&&(v(!1),(S=P.current)==null||S.focus())};return document.addEventListener("mousedown",$),document.addEventListener("keydown",te),()=>{document.removeEventListener("mousedown",$),document.removeEventListener("keydown",te)}},[g]),i.useEffect(()=>{E||(N(""),G(null))},[E]),i.useEffect(()=>{try{localStorage.setItem($s,j?"1":"0")}catch{}},[j]);const ce=(o==null?void 0:o.agent.flat().length)??0,ne=ce===0,A=!!o&&p.trim()===o.id,X=async()=>{if(!(!o||!A||w)){l(!0),G(null);try{await T.projects.delete(o.id),await r(),n({kind:"success",title:`项目 ${o.id} 已删除`}),O(!1),s("/")}catch($){G($ instanceof Error?$.message:String($))}finally{l(!1)}}};return o?e.jsxs("div",{children:[e.jsxs(As,{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:()=>v($=>!$),"aria-haspopup":"menu","aria-expanded":g,"aria-controls":g?R:void 0,"aria-label":`项目 ${o.id} 操作菜单`,className:"flex h-8 w-8 items-center justify-center rounded text-og-500 transition-colors hover:bg-og-50 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"})]})}),g&&e.jsxs("div",{ref:M,id:R,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:[!j&&e.jsx("button",{type:"button",role:"menuitem",onClick:()=>{var $;v(!1),k(!0),($=P.current)==null||$.focus()},className:"block w-full px-3 py-1.5 text-left text-[13px] text-og-800 hover:bg-og-50 hover:text-og-1000",children:"显示 Task 面板"}),e.jsx("button",{type:"button",role:"menuitem",onClick:()=>{v(!1),m(!0)},className:"block w-full px-3 py-1.5 text-left text-[13px] text-og-800 hover:bg-og-50 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:()=>{v(!1),O(!0)},disabled:!ne,title:ne?void 0:`请先删除项目下的 ${ce} 个 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:"删除项目…"})]})]})]}),K&&e.jsxs("div",{className:"mb-4 text-[13px] text-danger",children:["Error: ",K]}),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:o.id,children:o.id}),e.jsx("span",{className:"hidden min-w-0 truncate font-mono text-[12px] text-og-500 sm:inline-block",title:o.repo,children:o.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"})}),o.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:o.agent.map(($,te)=>e.jsx(Es,{group:$,projectId:o.id,agentsById:Y,agentsLoaded:_,agentsError:!!B,tasks:V,onDeleted:()=>{ee(o.id)},terminalMode:"embedded-full"},$.map(J=>J.id).join(":")||te))})]}),j&&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 $;k(!1),($=P.current)==null||$.focus()},"aria-label":"关闭 Task 面板",className:"flex h-7 w-7 items-center justify-center rounded text-og-500 transition-colors hover:bg-og-50 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(Tr,{projectId:o.id,openTasks:V})]})]}),e.jsx(Rs,{open:x,projectId:o.id,onClose:()=>m(!1),onCreated:()=>{ee(o.id)}}),e.jsx(kt,{open:f,projectId:o.id,onClose:()=>d(!1),onCreated:$=>a($.id)}),e.jsx(ve,{open:E,onClose:()=>{w||O(!1)},title:"删除项目",size:"sm",footer:e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:()=>O(!1),disabled:w,className:"btn-secondary",children:"取消"}),e.jsx("button",{type:"button",onClick:()=>void X(),disabled:!A||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:o.id}),"。此操作不可撤销,且不会删除 Git 仓库本身。"]}),e.jsxs("p",{className:"text-[13px] text-og-700",children:["如需确认,请在下方输入项目 ID ",e.jsx("span",{className:"font-mono text-og-1000",children:o.id}),":"]}),e.jsx("input",{type:"text",value:p,onChange:$=>N($.target.value),placeholder:o.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"}),H&&e.jsx("div",{className:"rounded-md border border-[#fecaca] bg-[#fef2f2] px-3 py-2 text-[12px] text-danger",children:H})]})})]}):u?e.jsxs("div",{className:"text-[13px] text-danger",children:["Error: ",u]}):e.jsx("div",{className:"text-[13px] text-og-500",children:"Loading…"})}function Or(){const{agentId:t}=Ze(),{projects:s}=st(),n=i.useMemo(()=>{if(t)for(const a of s??[])for(const r of a.agent){const o=r.find(c=>c.id===t);if(o)return o.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:wt(t,n),children:t})]}),e.jsx("div",{className:"min-h-0 flex-1",children:e.jsx(Oe,{agentId:t,mode:"full",interactive:!0,arrowKeys:!0})})]}):e.jsx("div",{className:"text-[13px] text-danger",children:"No agent specified"})}function Mr(t){return t.startsWith("diff --git")||t.startsWith("index ")||t.startsWith("--- ")||t.startsWith("+++ ")||t.startsWith("new file")||t.startsWith("deleted file")||t.startsWith("rename ")||t.startsWith("similarity ")||t.startsWith("old mode")||t.startsWith("new mode")}function _r(t){if(!t)return[];const s=[];let n=!1;for(const a of t.split(/\r?\n/)){let r;a.startsWith("@@")?(r="hunk",n=!0):a.startsWith("diff --git")?(r="file",n=!1):a.startsWith("\\")?r="meta":n?r=a.startsWith("+")?"add":a.startsWith("-")?"del":"context":Mr(a)?r="file":r="context",s.push({type:r,text:a})}return s}const Fr={file:"bg-og-50 font-semibold text-og-700",hunk:"bg-accent-soft text-accent",add:"bg-[#e6f4ec] text-success",del:"bg-[#fdecea] text-danger",context:"text-og-700",meta:"text-og-400"};function Br({content:t,diffstat:s}){const n=_r(t);return n.length===0?e.jsx("div",{className:"text-[13px] text-og-400",children:"无内容"}):e.jsxs("div",{children:[s&&e.jsx("pre",{className:"mb-2 overflow-x-auto rounded-md border border-hairline bg-og-50 p-3 font-mono text-[12px] text-og-700",children:s.trimEnd()}),e.jsx("div",{className:"overflow-auto rounded-md border border-hairline bg-surface font-mono text-[12px] leading-[1.5] [max-height:70vh]",children:n.map((a,r)=>e.jsx("div",{className:`whitespace-pre px-3 ${Fr[a.type]}`,children:a.text===""?" ":a.text},r))})]})}const Hr={critical:"pill !bg-[#fdecea] !text-danger",major:"pill pill-warn",minor:"pill"},Ur={fix:"pill pill-live",reject:"pill pill-warn","out-of-scope":"pill"};function cs(t){if(!t)return"";const s=t.match(/^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2})/);return s?`${s[1]} ${s[2]}`:t}function ls(t){return t.file?t.line?`${t.file}:${t.line}`:t.file:t.location??""}function Wr(){const{taskId:t="",phase:s="",round:n=""}=Ze(),a=Fe(),{hash:r}=ds(),{data:o}=Rt(t),c=o?`${o.specReviewRound??0}:${o.reviewRound}:${o.status}:${o.phase??"code"}`:void 0,{rounds:u,loaded:h,error:x}=js(t,c),m=Number(n),f=(u??[]).find(d=>d.phase===s&&d.round===m)??null;return i.useEffect(()=>{if(!f||!r)return;const d=document.getElementById(r.replace("#",""));d==null||d.scrollIntoView({behavior:"smooth",block:"start"})},[f,r]),e.jsxs("div",{className:"mx-auto w-full max-w-5xl",children:[e.jsx("button",{type:"button",onClick:()=>a(-1),className:"btn-ghost mb-3",children:"← 返回"}),e.jsxs("div",{className:"mb-1 flex flex-wrap items-baseline gap-2",children:[e.jsx("span",{className:"font-mono text-og-400",children:t}),e.jsx("span",{className:"text-[15px] font-semibold text-og-1000",children:(o==null?void 0:o.title)??""})]}),e.jsxs("div",{className:"mb-4 flex flex-wrap items-center gap-2 text-[12px] text-og-500",children:[e.jsx("span",{className:"pill",children:s}),e.jsxs("span",{children:["第 ",n," 轮"]}),(f==null?void 0:f.findings)&&e.jsx("span",{className:f.findings.verdict==="approve"?"pill pill-live":"pill pill-warn",children:f.findings.verdict}),f&&e.jsxs("span",{className:"text-og-400",children:[cs(f.startedAt),f.completedAt?` → ${cs(f.completedAt)}`:""]})]}),!h&&e.jsx("div",{className:"text-[13px] text-og-500",children:"加载中…"}),h&&x&&e.jsxs("div",{className:"text-[13px] text-danger",children:["加载评审记录失败:",x]}),h&&!x&&!f&&e.jsxs("div",{className:"text-[13px] text-danger",children:["未找到该轮评审(",s," 第 ",n," 轮)。"]}),f&&e.jsx(zr,{round:f})]})}function zr({round:t}){var r,o;const s=((r=t.findings)==null?void 0:r.findings)??[],n=((o=t.response)==null?void 0:o.responses)??[],a=new Map(s.map(c=>[c.id,c]));return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("section",{id:"diff",children:[e.jsx("h2",{className:"mb-2 text-[13px] font-semibold text-og-800",children:t.phase==="spec"?"规格稿":"代码改动"}),t.contentTruncated&&e.jsx("div",{className:"mb-2 text-[12px] text-warn",children:"内容较大,展示的是截断后的片段。"}),t.content?t.phase==="spec"?e.jsx("pre",{className:"card whitespace-pre-wrap p-4 text-[13px] text-og-800",children:t.content}):e.jsx(Br,{content:t.content,diffstat:t.diffstat}):e.jsx("div",{className:"text-[13px] text-og-400",children:"无内容"})]}),e.jsxs("section",{id:"review",children:[e.jsx("h2",{className:"mb-2 text-[13px] font-semibold text-og-800",children:"QA 评审"}),t.findings===void 0?e.jsx("div",{className:"text-[13px] text-og-400",children:"评审尚未提交。"}):s.length===0?e.jsx("div",{className:"text-[13px] text-og-400",children:"本轮无 findings。"}):e.jsx("div",{className:"space-y-2",children:s.map(c=>e.jsxs("div",{className:"card p-3 text-[13px]",children:[e.jsxs("div",{className:"mb-1 flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"font-mono text-og-400",children:c.id}),e.jsx("span",{className:Hr[c.severity],children:c.severity}),ls(c)&&e.jsx("span",{className:"font-mono text-[12px] text-og-500",children:ls(c)})]}),e.jsx("div",{className:"whitespace-pre-wrap text-og-800",children:c.message})]},c.id))})]}),n.length>0&&e.jsxs("section",{id:"response",children:[e.jsx("h2",{className:"mb-2 text-[13px] font-semibold text-og-800",children:"Dev 反馈"}),e.jsx("div",{className:"space-y-2",children:n.map(c=>{const u=a.get(c.findingId);return e.jsxs("div",{className:"card p-3 text-[13px]",children:[e.jsxs("div",{className:"mb-1 flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"font-mono text-og-400",children:c.findingId}),e.jsx("span",{className:Ur[c.action],children:c.action}),c.commitSha&&e.jsx("span",{className:"font-mono text-[12px] text-og-500",children:c.commitSha.slice(0,9)})]}),u&&e.jsxs("div",{className:"mb-1 text-[12px] text-og-500",children:["↳ ",u.message]}),e.jsx("div",{className:"whitespace-pre-wrap text-og-800",children:c.rationale})]},c.findingId)})})]})]})}function Qr(t,s){const[n,a]=i.useState(null),[r,o]=i.useState(!1),[c,u]=i.useState(null),h=i.useRef(t),x=i.useRef(s),m=i.useRef(0),f=i.useRef(!1);return i.useEffect(()=>{if(h.current!==t)h.current=t,f.current=!1,a(null),o(!1);else if(x.current===void 0&&s!==void 0&&f.current){x.current=s;return}x.current=s;const j=++m.current;u(null),T.tasks.githubReview(t).then(k=>{m.current===j&&(f.current=k.available===!0&&!k.error,a(k),o(!0))}).catch(k=>{m.current===j&&(f.current=!1,u(k instanceof Error?k.message:String(k)),a(null),o(!0))})},[t,s]),{data:n,loaded:r,error:c}}const Gr={approve:"pill pill-live","request-changes":"pill pill-warn",comment:"pill"},qr={approve:"approve","request-changes":"request-changes",comment:"comment"},Vr={"server-mode":"该 task 为 server 评审模式,代码评审记录见任务详情的「Dev ↔ QA 评审记录」。","no-pr":"该 task 还没有 PR,暂无代码评审记录。","not-github":"该 task 的仓库不是 GitHub 仓库,无法拉取 PR 评审记录。"};function Kr(t){return t==="server-mode"||t==="no-pr"||t==="not-github"?t:void 0}function bt(t){if(!t)return"";const s=t.match(/^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2})/);return s?`${s[1]} ${s[2]}`:t}function Jr(t){const s=[];let n=[];for(const a of t)a.kind==="review"?(s.push({items:n,review:a}),n=[]):n.push(a);return n.length>0&&s.push({items:n}),s}function Yr(){const{taskId:t=""}=Ze(),s=Fe(),{data:n}=Rt(t),a=n?`${n.reviewRound}:${n.latestHeadSha??""}:${n.status}`:void 0,{data:r,loaded:o,error:c}=Qr(t,a),u=(r==null?void 0:r.prNumber)??(n==null?void 0:n.prNumber),h=(r==null?void 0:r.prUrl)??(n==null?void 0:n.prUrl),x=r?Jr(r.items):[];return e.jsxs("div",{className:"mx-auto w-full max-w-5xl",children:[e.jsx("button",{type:"button",onClick:()=>s(-1),className:"btn-ghost mb-3",children:"← 返回"}),e.jsxs("div",{className:"mb-1 flex flex-wrap items-baseline gap-2",children:[e.jsx("span",{className:"font-mono text-og-400",children:t}),e.jsx("span",{className:"text-[15px] font-semibold text-og-1000",children:(n==null?void 0:n.title)??""})]}),e.jsxs("div",{className:"mb-4 flex flex-wrap items-center gap-2 text-[12px] text-og-500",children:[e.jsx("span",{className:"pill",children:"代码评审 · GitHub PR"}),h&&u!==void 0&&e.jsxs("a",{href:h,target:"_blank",rel:"noopener noreferrer",className:"text-accent hover:text-accent-hover",children:["Open PR #",u]})]}),!o&&e.jsx("div",{className:"text-[13px] text-og-500",children:"加载中…"}),o&&c&&e.jsxs("div",{className:"text-[13px] text-danger",children:["加载评审记录失败:",c]}),o&&!c&&r&&!r.available&&e.jsx("div",{className:"text-[13px] text-og-500",children:Vr[Kr(r.reason)??"no-pr"]}),o&&!c&&(r==null?void 0:r.available)&&(r.items.length===0?r.error?e.jsxs("div",{className:"text-[13px] text-warn",children:["评审记录拉取失败:",r.error]}):e.jsx("div",{className:"text-[13px] text-og-400",children:"评审尚未开始"}):e.jsxs(e.Fragment,{children:[r.error&&e.jsxs("div",{className:"mb-3 text-[12px] text-warn",children:["部分评审记录拉取失败:",r.error,"(仅展示已获取的部分)"]}),e.jsx("div",{className:"space-y-5",children:x.map((m,f)=>e.jsx(Xr,{round:m,index:f},f))})]}))]})}function Xr({round:t,index:s}){const n=t.review?`第 ${s+1} 轮`:"进行中";return e.jsxs("div",{children:[e.jsx("div",{className:"mb-1.5 text-[12px] font-medium text-og-700",children:n}),e.jsxs("div",{className:"space-y-2",children:[t.items.map(a=>e.jsx(Zr,{item:a},`${a.kind}-${a.id}`)),t.review&&e.jsx(ea,{item:t.review})]})]})}function Zr({item:t}){if(t.kind==="commit")return e.jsxs("div",{className:"card p-3 text-[13px]",children:[e.jsxs("div",{className:"mb-1 flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"pill shrink-0",children:"提交"}),t.commitSha&&e.jsx("span",{className:"font-mono text-[12px] text-og-500",children:t.commitSha.slice(0,9)}),t.author&&e.jsx("span",{className:"text-[12px] text-og-400",children:t.author}),t.createdAt&&e.jsx("span",{className:"text-[12px] text-og-400",children:bt(t.createdAt)})]}),t.body&&e.jsx("div",{className:"whitespace-pre-wrap text-og-800",children:t.body})]});const s=t.kind==="review-comment";return e.jsxs("div",{className:"card p-3 text-[13px]",children:[e.jsxs("div",{className:"mb-1 flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"pill shrink-0",children:s?"行内评论":"评论"}),t.author&&e.jsx("span",{className:"font-medium text-og-700",children:t.author}),s&&t.path&&e.jsx("span",{className:"font-mono text-[12px] text-og-500",children:t.line!==void 0?`${t.path}:${t.line}`:t.path}),t.inReplyTo&&e.jsx("span",{className:"text-[12px] text-og-400",children:"↩ 回复"}),t.createdAt&&e.jsx("span",{className:"text-[12px] text-og-400",children:bt(t.createdAt)})]}),e.jsx(Is,{item:t})]})}function ea({item:t}){const s=t.verdict??"comment";return e.jsxs("div",{className:"card p-3 text-[13px]",children:[e.jsxs("div",{className:"mb-1 flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"pill pill-review shrink-0",children:"QA"}),e.jsx("span",{className:Gr[s],children:qr[s]}),t.author&&e.jsx("span",{className:"text-[12px] text-og-400",children:t.author}),t.commitSha&&e.jsx("span",{className:"font-mono text-[12px] text-og-500",children:t.commitSha.slice(0,9)}),t.createdAt&&e.jsx("span",{className:"text-[12px] text-og-400",children:bt(t.createdAt)})]}),e.jsx(Is,{item:t,placeholder:"(无评审正文)"})]})}function Is({item:t,placeholder:s}){return e.jsxs(e.Fragment,{children:[t.body?e.jsx("div",{className:"whitespace-pre-wrap text-og-800",children:t.body}):s?e.jsx("div",{className:"text-og-400",children:s}):null,t.bodyTruncated&&e.jsx("div",{className:"mt-1 text-[12px] text-warn",children:"内容较大,已截断。"})]})}function ta(){const[t,s]=i.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 sa(){const{phase:t,count:s,error:n,triggerRestart:a}=tt();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:()=>{a()},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:()=>{a()},className:"btn-secondary !border-warn !text-warn hover:!bg-[#fef3c7] hover:!border-warn hover:!text-warn",children:"现在重启"})]})}function na(){const s=!ds().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(_e,{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:Cs,className:"ml-auto flex min-w-0 items-center justify-end gap-2"})]}),e.jsx(sa,{}),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(Us,{children:[e.jsx($e,{path:"/",element:e.jsx(kr,{})}),e.jsx($e,{path:"/project/:id",element:e.jsx(Lr,{})}),e.jsx($e,{path:"/terminal/:agentId",element:e.jsx(Or,{})}),e.jsx($e,{path:"/tasks/:taskId/rounds/:phase/:round",element:e.jsx(Wr,{})}),e.jsx($e,{path:"/tasks/:taskId/github-review",element:e.jsx(Yr,{})})]}),s&&e.jsx("footer",{className:"mt-auto flex justify-center pb-4 pt-24",children:e.jsx(ta,{})})]})]})}function ra(){return e.jsx(Hs,{children:e.jsx(ur,{children:e.jsx(na,{})})})}function aa({children:t}){const[s,n]=i.useState({kind:"probing"}),a=i.useRef(s);i.useEffect(()=>{a.current=s},[s]);const r=i.useCallback(async()=>{n({kind:"probing"});try{await T.config.get(),n({kind:"authorized"})}catch(o){if(o instanceof Re&&o.status===401){n({kind:"unauthorized"});return}const c=o instanceof Error?o.message:"无法连接服务器";n({kind:"error",message:c})}},[]);return i.useEffect(()=>{r()},[r]),i.useEffect(()=>{const o=()=>{a.current.kind!=="probing"&&n({kind:"unauthorized",message:"登录已失效,请重新输入令牌"})};return window.addEventListener(Ve,o),()=>window.removeEventListener(Ve,o)},[]),s.kind==="authorized"?e.jsx(e.Fragment,{children:t}):s.kind==="error"?e.jsxs(vt,{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(vt,{title:"加载中",children:e.jsx("p",{className:"text-[13px] text-og-500",children:"正在检查登录状态…"})}):e.jsx(ia,{message:s.message,onSubmit:async o=>{Gs(o);try{await T.config.get(),n({kind:"authorized"})}catch(c){if(qs(),c instanceof Re&&c.status===401){n({kind:"unauthorized",message:"令牌无效,请重试"});return}const u=c instanceof Error?c.message:"登录失败";n({kind:"error",message:u})}}})}function vt({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 ia({message:t,onSubmit:s}){const[n,a]=i.useState(""),[r,o]=i.useState(!1),[c,u]=i.useState(void 0),h=async m=>{m.preventDefault();const f=n.trim();if(!f){u("请输入访问令牌");return}u(void 0),o(!0);try{await s(f)}finally{o(!1)}},x=c??t;return e.jsxs(vt,{title:"登录 baxian",children:[e.jsx("p",{className:"mb-4 text-[13px] text-og-600",children:"服务器开启了访问鉴权,请输入访问令牌继续。"}),e.jsxs("form",{onSubmit:m=>{h(m)},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:m=>a(m.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?"登录中…":"登录"})]})]})}_s.createRoot(document.getElementById("root")).render(e.jsx(i.StrictMode,{children:e.jsx(rn,{children:e.jsx(Zs,{children:e.jsx(aa,{children:e.jsx(ra,{})})})})}));
@@ -6,7 +6,7 @@
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-BFsxrk2C.js"></script>
9
+ <script type="module" crossorigin src="/assets/index-DPFouq3q.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-BgSDZqI0.js">
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "baxian",
3
- "version": "1.2.26",
3
+ "version": "1.2.27",
4
4
  "description": "AI agent orchestration",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {