baxian 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/dist/agent/bootstrap-poller.d.ts.map +1 -1
  2. package/dist/agent/bootstrap-poller.js +2 -4
  3. package/dist/agent/bootstrap-poller.js.map +1 -1
  4. package/dist/agent/bootstrap.d.ts +3 -2
  5. package/dist/agent/bootstrap.d.ts.map +1 -1
  6. package/dist/agent/bootstrap.js +12 -15
  7. package/dist/agent/bootstrap.js.map +1 -1
  8. package/dist/agent/liveness.d.ts +10 -0
  9. package/dist/agent/liveness.d.ts.map +1 -0
  10. package/dist/agent/liveness.js +11 -0
  11. package/dist/agent/liveness.js.map +1 -0
  12. package/dist/agent/manager.d.ts +5 -2
  13. package/dist/agent/manager.d.ts.map +1 -1
  14. package/dist/agent/manager.js +250 -21
  15. package/dist/agent/manager.js.map +1 -1
  16. package/dist/agent/pane-streamer-manager.d.ts +3 -1
  17. package/dist/agent/pane-streamer-manager.d.ts.map +1 -1
  18. package/dist/agent/pane-streamer-manager.js +8 -1
  19. package/dist/agent/pane-streamer-manager.js.map +1 -1
  20. package/dist/agent/pane-streamer.d.ts +3 -2
  21. package/dist/agent/pane-streamer.d.ts.map +1 -1
  22. package/dist/agent/pane-streamer.js +13 -3
  23. package/dist/agent/pane-streamer.js.map +1 -1
  24. package/dist/agent/preflight.d.ts +2 -2
  25. package/dist/agent/preflight.d.ts.map +1 -1
  26. package/dist/agent/preflight.js +10 -8
  27. package/dist/agent/preflight.js.map +1 -1
  28. package/dist/agent/repo-store.js +5 -5
  29. package/dist/agent/repo-store.js.map +1 -1
  30. package/dist/agent/runner.d.ts +13 -2
  31. package/dist/agent/runner.d.ts.map +1 -1
  32. package/dist/agent/runner.js +129 -28
  33. package/dist/agent/runner.js.map +1 -1
  34. package/dist/agent/tmux-probe-poller.d.ts.map +1 -1
  35. package/dist/agent/tmux-probe-poller.js +5 -3
  36. package/dist/agent/tmux-probe-poller.js.map +1 -1
  37. package/dist/agent/tmux.d.ts +8 -5
  38. package/dist/agent/tmux.d.ts.map +1 -1
  39. package/dist/agent/tmux.js +68 -7
  40. package/dist/agent/tmux.js.map +1 -1
  41. package/dist/api/config.d.ts +3 -1
  42. package/dist/api/config.d.ts.map +1 -1
  43. package/dist/api/config.js +66 -0
  44. package/dist/api/config.js.map +1 -1
  45. package/dist/api/hosts.d.ts +7 -0
  46. package/dist/api/hosts.d.ts.map +1 -0
  47. package/dist/api/hosts.js +321 -0
  48. package/dist/api/hosts.js.map +1 -0
  49. package/dist/api/probe.d.ts.map +1 -1
  50. package/dist/api/probe.js +32 -8
  51. package/dist/api/probe.js.map +1 -1
  52. package/dist/api/projects.d.ts.map +1 -1
  53. package/dist/api/projects.js +32 -13
  54. package/dist/api/projects.js.map +1 -1
  55. package/dist/api/tasks.d.ts.map +1 -1
  56. package/dist/api/tasks.js +10 -0
  57. package/dist/api/tasks.js.map +1 -1
  58. package/dist/app.d.ts.map +1 -1
  59. package/dist/app.js +2 -0
  60. package/dist/app.js.map +1 -1
  61. package/dist/cli.d.ts +2 -1
  62. package/dist/cli.d.ts.map +1 -1
  63. package/dist/cli.js +18 -8
  64. package/dist/cli.js.map +1 -1
  65. package/dist/config/loader.d.ts.map +1 -1
  66. package/dist/config/loader.js +28 -0
  67. package/dist/config/loader.js.map +1 -1
  68. package/dist/config/normalizer.d.ts.map +1 -1
  69. package/dist/config/normalizer.js +1 -0
  70. package/dist/config/normalizer.js.map +1 -1
  71. package/dist/config/validator.d.ts.map +1 -1
  72. package/dist/config/validator.js +70 -10
  73. package/dist/config/validator.js.map +1 -1
  74. package/dist/event/handlers.d.ts.map +1 -1
  75. package/dist/event/handlers.js +54 -11
  76. package/dist/event/handlers.js.map +1 -1
  77. package/dist/index.d.ts.map +1 -1
  78. package/dist/index.js +7 -2
  79. package/dist/index.js.map +1 -1
  80. package/dist/shared/constants.d.ts.map +1 -1
  81. package/dist/shared/constants.js +5 -2
  82. package/dist/shared/constants.js.map +1 -1
  83. package/dist/shared/types.d.ts +6 -1
  84. package/dist/shared/types.d.ts.map +1 -1
  85. package/dist/state/snapshot.d.ts.map +1 -1
  86. package/dist/state/snapshot.js +3 -2
  87. package/dist/state/snapshot.js.map +1 -1
  88. package/dist/terminal/attach.d.ts +3 -2
  89. package/dist/terminal/attach.d.ts.map +1 -1
  90. package/dist/terminal/attach.js +10 -7
  91. package/dist/terminal/attach.js.map +1 -1
  92. package/dist/web/assets/index-BfCCF072.js +4 -0
  93. package/dist/web/assets/index-CuCB0XN0.css +1 -0
  94. package/dist/web/index.html +2 -2
  95. package/package.json +1 -1
  96. package/dist/web/assets/index-BfF2mK4D.css +0 -1
  97. package/dist/web/assets/index-DCAoAnPR.js +0 -4
@@ -1,4 +0,0 @@
1
- var Wt=Object.defineProperty;var Qt=(t,s,r)=>s in t?Wt(t,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[s]=r;var H=(t,s,r)=>Qt(t,typeof s!="symbol"?s+"":s,r);import{r as o,j as e,c as qt}from"./react-BG4Iuztk.js";import{x as Gt,a as Ht}from"./xterm-D5X2JljJ.js";import{L as Ee,u as Et,a as Kt,B as Vt,b as Jt,R as Yt,c as We}from"./router-eEZdpwQZ.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))a(n);new MutationObserver(n=>{for(const i of n)if(i.type==="childList")for(const d of i.addedNodes)d.tagName==="LINK"&&d.rel==="modulepreload"&&a(d)}).observe(document,{childList:!0,subtree:!0});function r(n){const i={};return n.integrity&&(i.integrity=n.integrity),n.referrerPolicy&&(i.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?i.credentials="include":n.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function a(n){if(n.ep)return;n.ep=!0;const i=r(n);fetch(n.href,i)}})();const Ct=new Set(["merged","failed","max_rounds","cancelled"]),Rt=new Set(["in_progress","review","fixing","approved","merge-ready"]),Qe=20,Be=5*1024*1024,Ie=4,ze="/api",st="baxian.token",Le="baxian:unauthorized";function nt(){try{return typeof localStorage<"u"?localStorage.getItem(st):null}catch{return null}}function Xt(t){try{localStorage.setItem(st,t)}catch(s){console.error("Failed to save auth token to localStorage",s)}}function Zt(){try{localStorage.removeItem(st)}catch(t){console.error("Failed to clear auth token from localStorage",t)}}function Ce(t){const s=nt();return{...t??{},...s?{Authorization:`Bearer ${s}`}:{}}}class Re extends Error{constructor(s,r,a){super(r),this.status=s,this.details=a,this.name="ApiError"}}async function Ae(t){const s=await t.text();let r=s||`HTTP ${t.status}`,a;try{const n=JSON.parse(s);typeof n.error=="string"&&(r=n.error),Array.isArray(n.details)&&(a=n.details)}catch{}throw t.status===401&&typeof window<"u"&&window.dispatchEvent(new CustomEvent(Le)),new Re(t.status,r,a)}async function ge(t){const s=await fetch(`${ze}${t}`,{headers:Ce()});return s.ok||await Ae(s),s.json()}async function es(){const t=await fetch("/health");return t.ok||await Ae(t),t.json()}async function le(t,s,r){const a=s!==void 0,n=await fetch(`${ze}${t}`,{method:"POST",headers:a?Ce({"Content-Type":"application/json"}):Ce(),body:a?JSON.stringify(s):void 0,signal:r==null?void 0:r.signal});return n.ok||await Ae(n),n.json()}async function ts(t,s,r){const a=await fetch(`${ze}${t}`,{method:"PATCH",headers:Ce({"Content-Type":"application/json"}),body:s?JSON.stringify(s):void 0,signal:r==null?void 0:r.signal});if(a.ok||await Ae(a),a.status===204)return;const n=await a.text();if(n)return JSON.parse(n)}async function qe(t){const s=await fetch(`${ze}${t}`,{method:"DELETE",headers:Ce()});if(s.ok||await Ae(s),s.status===204)return;const r=await s.text();if(r)return JSON.parse(r)}const te=encodeURIComponent;function At(t){return new Promise((s,r)=>{const a=new FileReader;a.onerror=()=>r(a.error??new Error("file read failed")),a.onload=()=>{const n=a.result;if(typeof n!="string"){r(new Error("unexpected FileReader result"));return}const i=n.indexOf(",");s(i>=0?n.slice(i+1):n)},a.readAsDataURL(t)})}const _={agents:{list:()=>ge("/agents"),get:t=>ge(`/agents/${te(t)}`),stop:t=>qe(`/agents/${te(t)}/session`),probe:(t,s,r)=>le("/agents/probe",{mode:t,host:s},r),uploadImage:async(t,s)=>le(`/agents/${te(t)}/images`,{dataBase64:await At(s)})},tasks:{list:async t=>{const s=new Map;for(const r of["active","pending"]){let a=0;for(;;){const n=await _.tasks.page(t,{category:r,offset:a});for(const i of n.tasks)s.set(i.id,i);if(!n.hasMore||n.tasks.length===0)break;a=n.nextOffset}}return[...s.values()]},page:(t,s={})=>{const r=[`projectId=${te(t)}`];return s.category&&r.push(`category=${s.category}`),r.push(`offset=${s.offset??0}`),ge(`/tasks?${r.join("&")}`)},get:t=>ge(`/tasks/${te(t)}`),create:t=>le("/tasks",t),update:(t,s)=>ts(`/tasks/${te(t)}`,s),retry:t=>le(`/tasks/${te(t)}/retry`),review:t=>le(`/tasks/${te(t)}/review`),dispatch:(t,s)=>le(`/tasks/${te(t)}/dispatch`,s)},projects:{list:()=>ge("/projects"),get:t=>ge(`/projects/${te(t)}`),create:t=>le("/projects",t),delete:t=>qe(`/projects/${te(t)}`),addAgent:(t,s)=>le(`/projects/${te(t)}/agents`,s),deleteAgent:(t,s)=>qe(`/projects/${te(t)}/agents/${te(s)}`),resumeAgent:(t,s)=>le(`/projects/${te(t)}/agents/${te(s)}/resume`),bootstrap:t=>le(`/projects/${te(t)}/bootstrap`)},config:{get:()=>ge("/config")},health:{get:es},server:{restart:()=>le("/restart")}},Tt=o.createContext(null),ss={success:"border-[#bbf7d0] bg-[#f0fdf4] text-success",warn:"border-[#fde68a] bg-[#fef3c7] text-warn",error:"border-[#fecaca] bg-[#fef2f2] text-danger"},ns={success:"✅",warn:"⚠️",error:"❌"};let rs=1;function os({children:t}){const[s,r]=o.useState([]),a=o.useCallback(i=>{r(d=>d.filter(f=>f.id!==i))},[]),n=o.useCallback(i=>{const d=rs++,f=i.durationMs??3e3;r(h=>[...h,{...i,id:d}]),setTimeout(()=>a(d),f)},[a]);return e.jsxs(Tt.Provider,{value:{show:n},children:[t,e.jsx("div",{className:"pointer-events-none fixed inset-x-4 top-4 z-[60] flex flex-col items-end gap-2",children:s.map(i=>e.jsx("div",{className:`pointer-events-auto w-full max-w-xs rounded-lg border px-4 py-3 shadow-toast ${ss[i.kind]}`,role:"status",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{"aria-hidden":!0,className:"text-[14px]",children:ns[i.kind]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-[13px] font-semibold",children:i.title}),i.body&&e.jsx("div",{className:"mt-1 whitespace-pre-line text-[12px] text-og-700",children:i.body})]}),e.jsx("button",{type:"button",onClick:()=>a(i.id),className:"text-current opacity-50 transition-opacity hover:opacity-100","aria-label":"Dismiss",children:"✕"})]})},i.id))})]})}function pe(){const t=o.useContext(Tt);if(!t)throw new Error("useToast must be inside <ToastProvider>");return t}const Oe="baxian.pendingRestart",as=500,is=3e4,It=o.createContext(null);function cs(){try{const t=localStorage.getItem(Oe);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 ls(t){try{t.count<=0?localStorage.removeItem(Oe):localStorage.setItem(Oe,JSON.stringify(t))}catch{}}function ds({children:t}){const s=cs(),[r,a]=o.useState(s.count),[n,i]=o.useState(s.baselineStartedAt),[d,f]=o.useState(s.count>0?"pending":"idle"),[h,u]=o.useState(),l=o.useRef(s.count),p=o.useRef(s.count>0?"pending":"idle"),y=o.useRef(0),x=o.useCallback(g=>{l.current=g,a(g)},[]),m=o.useCallback(g=>{a(L=>{const w=g(L);return l.current=w,w})},[]),k=o.useCallback(g=>{p.current=g,f(g)},[]);o.useEffect(()=>{ls({count:r,baselineStartedAt:n})},[r,n]),o.useEffect(()=>{let g=!1;(async()=>{try{const w=await _.health.get();if(g)return;i(C=>C!==null&&w.startedAt!==C?(x(0),k("idle"),null):C)}catch{}})();const L=w=>{if(w.key===Oe){if(w.newValue===null){if(p.current==="restarting"&&y.current>0){x(y.current),i(null);return}x(0),i(null),p.current!=="restarting"&&k("idle");return}try{const C=JSON.parse(w.newValue);typeof C.count=="number"&&(p.current==="restarting"&&C.count>l.current&&(y.current+=C.count-l.current),x(C.count),p.current!=="restarting"&&k(C.count>0?"pending":"idle")),typeof C.baselineStartedAt=="string"?i(C.baselineStartedAt):C.baselineStartedAt===null&&i(null)}catch{}}};return window.addEventListener("storage",L),()=>{g=!0,window.removeEventListener("storage",L)}},[x,k]);const T=o.useRef(!1),c=o.useCallback(()=>{m(g=>g+1),p.current==="restarting"?y.current+=1:k("pending"),i(g=>(g!==null||T.current||(T.current=!0,(async()=>{try{const L=await _.health.get();i(w=>w??L.startedAt)}catch{}finally{T.current=!1}})()),g))},[k,m]),E=o.useCallback(async()=>{y.current=0,u(void 0),k("restarting");let g;try{g=(await _.health.get()).startedAt}catch(w){k("failed"),u(`获取重启前 startedAt 失败: ${w instanceof Error?w.message:String(w)}`);return}try{await _.server.restart()}catch(w){if(!(w instanceof Re&&w.status===409)){k("failed"),u(`触发重启失败: ${w instanceof Error?w.message:String(w)}`);return}}const L=Date.now();for(;Date.now()-L<is;){await new Promise(w=>setTimeout(w,as));try{const w=await _.health.get();if(w.startedAt!==g){const C=y.current;y.current=0,i(C>0?w.startedAt:null),x(C),k(C>0?"pending":"idle");return}}catch{}}k("failed"),u("重启超时(30s 未恢复)。请检查日志或手动 baxian start -c <path>")},[x,k]);return e.jsx(It.Provider,{value:{phase:d,count:r,error:h,flagDirty:c,triggerRestart:E},children:t})}function Ue(){const t=o.useContext(It);if(!t)throw new Error("usePendingRestart must be used inside PendingRestartProvider");return t}const us=[500,1e3,2e3,4e3,8e3,15e3,3e4];class Dt{constructor(s){H(this,"attempts",0);H(this,"timer",null);H(this,"delaysMs");this.opts=s,this.delaysMs=s.delaysMs??us}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 lt=0;function fs(){lt++;const t=Math.random().toString(36).slice(2,8);return`sub-${Date.now().toString(36)}-${lt}-${t}`}function hs(t){return Array.from(new TextEncoder().encode(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}function ms(){return`${location.protocol==="https:"?"wss":"ws"}://${location.host}/api/stream`}const xs=(t,s)=>s&&s.length>0?new WebSocket(t,s):new WebSocket(t);class ps{constructor(s={}){H(this,"wsUrl");H(this,"wsFactory");H(this,"tokenProvider");H(this,"ws",null);H(this,"subs",new Map);H(this,"snapshotPending",new Set);H(this,"preSubscribeQueue",new Map);H(this,"outbox",[]);H(this,"reconnectScheduler");H(this,"explicitlyClosed",!1);this.wsUrl=s.wsUrl??ms(),this.wsFactory=s.wsFactory??xs,this.tokenProvider=s.tokenProvider??nt,this.reconnectScheduler=new Dt({reconnect:()=>this.openSocket(),shouldReconnect:()=>!this.explicitlyClosed&&this.subs.size>0})}subscribe(s){const r=fs(),a={subscriberId:r,agentId:s.agentId,mode:s.mode,onSnapshot:s.onSnapshot,onData:s.onData,onError:s.onError,onSessionGone:s.onSessionGone};return this.subs.set(r,a),this.snapshotPending.add(r),this.preSubscribeQueue.set(r,[]),this.ensureSocket(),this.wsSendOrQueue({op:"subscribe",subscriberId:r,agentId:s.agentId,mode:s.mode}),{subscriberId:r,unsubscribe:()=>this.unsubscribe(r)}}send(s,r){if(this.subs.has(s)){if(this.snapshotPending.has(s)){this.outbox.push({op:"input",subscriberId:s,data:r});return}this.wsSendOrQueue({op:"input",subscriberId:s,data:r})}}resize(s,r,a){const n=this.subs.get(s);n&&(n.lastSize={cols:r,rows:a},!this.snapshotPending.has(s)&&this.wsSendOrQueue({op:"resize",subscriberId:s,cols:r,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(),r=s?[`baxian.token.${hs(s)}`]:void 0;let a;try{a=this.wsFactory(this.wsUrl,r)}catch(n){console.warn("[pane-stream] WebSocket constructor threw:",n),this.scheduleReconnect();return}this.ws=a,a.onopen=()=>{if(a!==this.ws)return;this.reconnectScheduler.reset();for(const i of this.subs.values()){this.snapshotPending.add(i.subscriberId),this.preSubscribeQueue.set(i.subscriberId,[]),i.snapshotSeq=void 0;try{a.send(JSON.stringify({op:"subscribe",subscriberId:i.subscriberId,agentId:i.agentId,mode:i.mode}))}catch(d){console.warn("[pane-stream] resubscribe send failed:",d)}}const n=this.outbox;this.outbox=[];for(const i of n)if(i.op!=="subscribe"){if("subscriberId"in i&&i.subscriberId){if(!this.subs.has(i.subscriberId))continue;if(this.snapshotPending.has(i.subscriberId)&&i.op!=="unsubscribe"){this.outbox.push(i);continue}}try{a.send(JSON.stringify(i))}catch(d){console.warn("[pane-stream] outbox flush failed:",d)}}},a.onmessage=n=>{if(a!==this.ws)return;let i;try{const d=typeof n.data=="string"?n.data:String(n.data);i=JSON.parse(d)}catch{return}this.handleMessage(i)},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(r){console.warn("[pane-stream] send failed, will queue:",r)}this.outbox.push(s)}handleMessage(s){var r,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 n of[...this.subs.values()])n.agentId===s.agentId&&((r=n.onSessionGone)==null||r.call(n));break;case"error":{if(s.subscriberId){const n=this.subs.get(s.subscriberId);(a=n==null?void 0:n.onError)==null||a.call(n,{code:s.code,message:s.message})}else console.warn("[pane-stream] connection-level error:",s.code,s.message);break}}}handleSnapshot(s){const r=this.subs.get(s.subscriberId);r&&r.onSnapshot({cols:s.cols,rows:s.rows,data:s.data})}handleSubscribed(s){const r=this.subs.get(s.subscriberId);if(!r)return;r.snapshotSeq=s.snapshotSeq,r.lastSize||(r.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 n of a)n.seq>s.snapshotSeq&&r.onData(n.data);r.mode==="full"&&r.lastSize&&this.wsSendOrQueue({op:"resize",subscriberId:r.subscriberId,cols:r.lastSize.cols,rows:r.lastSize.rows}),this.flushOutboxForSub(s.subscriberId)}flushOutboxForSub(s){if(this.outbox.length===0||!this.ws||this.ws.readyState!==WebSocket.OPEN)return;const r=[];for(const a of this.outbox)if("subscriberId"in a&&a.subscriberId===s&&a.op!=="subscribe")try{this.ws.send(JSON.stringify(a))}catch(n){console.warn("[pane-stream] flushOutboxForSub send failed:",n)}else r.push(a);this.outbox=r}dispatch(s){for(const r of this.subs.values())if(r.agentId===s.agentId)if(this.snapshotPending.has(r.subscriberId)){const a=this.preSubscribeQueue.get(r.subscriberId);a&&a.push({seq:s.seq,data:s.data})}else r.onData(s.data)}}let Ge=null;function He(){return Ge||(Ge=new ps),Ge}function bs(t){const{agentId:s,mode:r}=t,a=o.useRef(null),n=o.useRef({onSnapshot:t.onSnapshot,onData:t.onData,onError:t.onError,onSessionGone:t.onSessionGone});n.current={onSnapshot:t.onSnapshot,onData:t.onData,onError:t.onError,onSessionGone:t.onSessionGone},o.useEffect(()=>{const h=He().subscribe({agentId:s,mode:r,onSnapshot:u=>n.current.onSnapshot(u),onData:u=>n.current.onData(u),onError:u=>{var l,p;return(p=(l=n.current).onError)==null?void 0:p.call(l,u)},onSessionGone:()=>{var u,l;return(l=(u=n.current).onSessionGone)==null?void 0:l.call(u)}});return a.current=h.subscriberId,()=>{a.current=null,h.unsubscribe()}},[s,r]);const i=o.useCallback(f=>{const h=a.current;h&&He().send(h,f)},[]),d=o.useCallback((f,h)=>{const u=a.current;u&&He().resize(u,f,h)},[]);return{send:i,resize:d}}const gs=[{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"}],De=Object.fromEntries(gs.map(t=>[t.key,t]));function Pe({arrow:t,onPress:s}){return e.jsx("button",{type:"button","aria-label":`方向键 ${t.label}`,"data-arrow":t.key,onMouseDown:r=>r.preventDefault(),onClick:()=>s(t.key),className:"flex h-8 w-8 items-center justify-center rounded border border-hairline bg-surface text-og-700 transition-colors hover:bg-og-100 hover:text-og-1000 active:bg-og-200",children:e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:e.jsx("path",{d:t.path})})})}function vs({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(Pe,{arrow:De.left,onPress:t}),e.jsx(Pe,{arrow:De.up,onPress:t}),e.jsx(Pe,{arrow:De.down,onPress:t}),e.jsx(Pe,{arrow:De.right,onPress:t})]})}const ys=Math.floor(Be/1024/1024);function js({agentId:t,className:s}){const r=o.useRef(null),[a,n]=o.useState(!1),{show:i}=pe(),d=async f=>{var u;const h=(u=f.target.files)==null?void 0:u[0];if(f.target.value="",!!h){if(h.size>Be){i({kind:"error",title:"图片过大",body:`单张图片不能超过 ${ys} MiB`});return}n(!0);try{await _.agents.uploadImage(t,h),i({kind:"success",title:"图片已插入",body:"路径已粘贴到终端输入,补充说明后回车"})}catch(l){const p=l instanceof Re||l instanceof Error?l.message:String(l);i({kind:"error",title:"图片上传失败",body:p})}finally{n(!1)}}};return e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button","aria-label":"上传图片",disabled:a,onMouseDown:f=>f.preventDefault(),onClick:()=>{var f;return(f=r.current)==null?void 0:f.click()},className:s??"flex h-8 w-8 items-center justify-center rounded border border-hairline bg-surface text-og-700 transition-colors hover:bg-og-100 hover:text-og-1000 active:bg-og-200 disabled:cursor-not-allowed disabled:opacity-50",children:e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),e.jsx("circle",{cx:"9",cy:"9",r:"2"}),e.jsx("path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"})]})}),e.jsx("input",{ref:r,type:"file",accept:"image/*",className:"hidden",onChange:d})]})}const ws={up:"A",down:"B",right:"C",left:"D"};function Ns(t,s){return(s?"\x1BO":"\x1B[")+ws[t]}const dt=18,ks=250,Ss=256*1024,ut="#fdfdfd",Es='ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',Cs={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"},Rs=/\x1b\[(?:\?[\d;]*c|>[\d;]*c|\??\d+;\d+R|\d+n)/g;function As(t){return t.replace(Rs,"")}function ke({agentId:t,mode:s,interactive:r=!1,maxLines:a,className:n,autoFocus:i=!0,deferFullUntilFocus:d=!1,arrowKeys:f=!1}){const h=o.useRef(null),u=o.useRef(null),l=o.useRef(null),p=o.useRef(null),y=o.useRef(!1),x=o.useRef(""),m=o.useRef([]),k=o.useRef(0),T=o.useRef(null),c=o.useRef(null),E=o.useRef(Promise.resolve()),g=o.useRef(0),[L,w]=o.useState(null),[C,P]=o.useState(!1),R=`${t}\0${s}\0${d?"1":"0"}`,[S,$]=o.useState({key:R,active:!1}),b=S.key===R&&S.active,O=s==="full"&&d,M=O&&!b?"preview":s,K=r&&M==="full",G=(j,D)=>D.length===0?Promise.resolve():new Promise(A=>{try{j.write(D,()=>A())}catch(Y){console.warn("[pane-terminal] write failed:",Y),A()}}),U=M==="preview",Q=()=>{if(!U)return;const j=h.current,D=u.current;if(!j||!D)return;const Y=(D.buffer.active.cursorY+1)*dt;j.scrollTop=Math.max(0,Y-j.clientHeight)},V=(j,D)=>{E.current=E.current.then(async()=>{const A=u.current;if(!(!A||D!==g.current))try{await j(A),Q()}catch(Y){console.warn("[pane-terminal] terminal task failed:",Y)}}).catch(A=>{console.warn("[pane-terminal] write chain failed:",A)})},se=(j,D)=>{V(A=>G(A,j),D)},ee=()=>{T.current!==null&&(cancelAnimationFrame(T.current),T.current=null),c.current!==null&&(clearTimeout(c.current),c.current=null)},ie=()=>{ee(),m.current=[],k.current=0},ne=()=>{ee();const j=m.current;j.length!==0&&(m.current=[],k.current=0,se(j.join(""),g.current))},N=j=>{if(j.length!==0){if(m.current.push(j),k.current+=j.length,k.current>=Ss){ne();return}T.current===null&&(T.current=requestAnimationFrame(ne)),c.current===null&&(c.current=setTimeout(ne,ks))}},{send:B,resize:W}=bs({agentId:t,mode:M,onSnapshot:({cols:j,rows:D,data:A})=>{if(u.current)try{const re=g.current+1;g.current=re,ie(),V(async oe=>{var ae;oe.reset(),K?((ae=p.current)==null||ae.call(p),await G(oe,A),oe.scrollToBottom()):(j>0&&D>0&&oe.resize(j,D),await G(oe,A))},re)}catch(re){console.warn("[pane-terminal] snapshot write failed:",re)}},onData:j=>{N(j)},onError:j=>w(`${j.code}: ${j.message}`),onSessionGone:()=>P(!0)});o.useEffect(()=>{w(null),P(!1)},[t,M]),o.useEffect(()=>{x.current=""},[R]),o.useEffect(()=>{if(M!=="full")return;const j=x.current;j.length!==0&&(x.current="",B(j))},[B,M]);const X=o.useCallback(()=>{!r||!O||b||(y.current=!0,$({key:R,active:!0}))},[R,b,r,O]),J=o.useCallback(j=>{const D=As(j);if(D.length!==0){if(O&&(!b||x.current.length>0)){x.current+=D,X();return}B(D)}},[X,b,B,O]);o.useEffect(()=>{const j=h.current;if(!j)return;let D=!1;const A=new Gt.Terminal({cursorBlink:r,disableStdin:!r,theme:Cs,fontFamily:Es,fontSize:13,lineHeight:1.4,scrollback:M==="full"?5e3:1e3}),Y=new Ht.FitAddon;if(A.loadAddon(Y),A.open(j),u.current=A,l.current=Y,r&&(i||y.current)){y.current=!1;try{A.focus()}catch{}}r&&A.onData(J);const re=()=>j.clientWidth>0&&j.clientHeight>0,oe=(fe=!1)=>{if(!re())return!1;const be=A.cols,I=A.rows;try{Y.fit()}catch{return!1}return A.cols>0&&A.rows>0&&(fe||A.cols!==be||A.rows!==I)&&W(A.cols,A.rows),!0};p.current=K?()=>oe(!0):null;let ae=null,ce=null,v=null,F=0;const Z=()=>{ae||(ae=new ResizeObserver(()=>{ce&&clearTimeout(ce),ce=setTimeout(()=>{ce=null,oe()},100)}),ae.observe(j))},q=()=>{v=requestAnimationFrame(()=>{if(v=null,!(D||!K)){if(oe(!0)){Z();return}if(F++<5){q();return}Z()}})};return q(),()=>{D=!0,v!==null&&cancelAnimationFrame(v),T.current!==null&&(cancelAnimationFrame(T.current),T.current=null),c.current!==null&&(clearTimeout(c.current),c.current=null),g.current++,m.current=[],k.current=0,E.current=Promise.resolve(),ce&&clearTimeout(ce),ae==null||ae.disconnect(),u.current=null,l.current=null,p.current=null;try{A.dispose()}catch(fe){console.warn("[pane-terminal] dispose failed:",fe)}}},[t,i,K,J,r,M,W]);const ue=()=>{var j;if(r){X();try{(j=u.current)==null||j.focus()}catch{}}};o.useEffect(()=>{if(r)return;const j=h.current;if(!j)return;const D=A=>{A.stopPropagation()};return j.addEventListener("wheel",D,{capture:!0,passive:!0}),()=>j.removeEventListener("wheel",D,{capture:!0})},[r]);const z=a&&a>0?{maxHeight:`${a*dt}px`}:void 0;return e.jsxs("div",{className:n??"flex flex-col h-full w-full min-h-0 bg-[#fdfdfd]",children:[(L||C)&&e.jsx("div",{className:"border-b border-[#fecaca] bg-[#fef2f2] px-3 py-1 font-mono text-[11px] text-danger",children:C?"session ended":L}),e.jsx("div",{className:"flex flex-1 min-h-0 px-2 py-1.5",style:z,children:e.jsx("div",{ref:h,className:"flex-1 min-h-0 overflow-hidden",onMouseDown:ue})}),r&&f&&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(js,{agentId:t})}),e.jsx(vs,{className:"flex items-center justify-center gap-1",onKey:j=>{var A,Y;const D=!!((Y=(A=u.current)==null?void 0:A.modes)!=null&&Y.applicationCursorKeysMode);J(Ns(j,D))}})]})]})}const Ts={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"}},Is={present:{label:"Session present",modifier:"status-dot--healthy"},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 Ds({state:t}){const{label:s,modifier:r}=Is[t];return e.jsx("span",{role:"img","aria-label":s,title:s,className:`status-dot ml-2 ${r}`})}function Ps({agent:t,projectId:s,role:r,onDeleted:a,pendingRestart:n=!1,terminalLoading:i=!1,showTaskBinding:d=!0,terminalMode:f="activity-preview",active:h,onActivate:u}){var ce,v,F,Z,q,fe,be;const[l,p]=o.useState(!1),[y,x]=o.useState(null),{show:m}=pe(),{flagDirty:k}=Ue(),[T,c]=o.useState(!1),[E,g]=o.useState(null),[L,w]=o.useState(!1),[C,P]=o.useState(!1),[R,S]=o.useState(!1),[$,b]=o.useState(!1),O=o.useRef(null),M=o.useRef(null),K=o.useId(),G=o.useId();o.useEffect(()=>{if(!$)return;const I=we=>{var it,ct;const me=we.target;me&&((it=M.current)!=null&&it.contains(me)||(ct=O.current)!=null&&ct.contains(me)||b(!1))},he=we=>{var me;we.key==="Escape"&&(b(!1),(me=O.current)==null||me.focus())};return document.addEventListener("mousedown",I),document.addEventListener("keydown",he),()=>{document.removeEventListener("mousedown",I),document.removeEventListener("keydown",he)}},[$]),o.useEffect(()=>{var he;if(!$)return;const I=(he=M.current)==null?void 0:he.querySelector('[role="menuitem"]:not([disabled])');I==null||I.focus()},[$]);const U=(ce=t.binding)==null?void 0:ce.taskId,Q=((v=t.binding)==null?void 0:v.status)==="awaiting_human",V=!!((F=t.binding)!=null&&F.creationToken)&&!((Z=t.binding)!=null&&Z.paneId)&&!Q&&t.reason!=="PENDING_HUMAN",se=V?{label:"Starting",cls:"pill pill-review"}:Ts[t.runtimeStatus],ee=V?"starting":t.tmuxSessionStatus,ie=f==="activity-preview"&&!V&&(t.runtimeStatus==="working"||t.runtimeStatus==="pending"),ne=f==="embedded-full",N=ne&&typeof u=="function",B=N&&h===!0,W=i||n||V,X=i?"Agent 状态加载中":n?"重启 baxian server 后可用":"Agent 正在启动",J=async()=>{p(!0),x(null);try{await _.agents.stop(t.id)}catch(I){x(I instanceof Error?I.message:String(I))}finally{p(!1)}},ue=async()=>{if(U&&window.confirm(`请 QA 对 task ${U} 重审?这会让 QA agent 立即开始新一轮 review(reviewRound +1)。`)){w(!0);try{const I=await _.tasks.review(U);m({kind:"success",title:`已派 QA 重审 (round ${I.reviewRound})`})}catch(I){m({kind:"error",title:"Review 派发失败",body:I instanceof Error?I.message:String(I)})}finally{w(!1)}}},z=async()=>{S(!0);try{(await _.projects.bootstrap(s)).ok?m({kind:"success",title:"Bootstrap retry 完成",body:"agent 状态将在下一次刷新生效。"}):m({kind:"warn",title:"Bootstrap retry 仍失败",body:"看一下红色错误卡的最新原因,按提示修复后再试。"})}catch(I){m({kind:"error",title:"Bootstrap retry 失败",body:I instanceof Error?I.message:String(I)})}finally{S(!1)}},j=async()=>{if(window.confirm(`确认 Resume Agent ${t.id}?baxian 会清除 awaiting_human 状态,agent 重新可派遣。`)){P(!0);try{const I=await _.projects.resumeAgent(s,t.id);m({kind:"success",title:`Agent ${t.id} 已 Resume`,body:I.releasedBinding?"原任务已释放,agent 可接新任务。":"保留绑定(原任务仍 active)。"})}catch(I){m({kind:"error",title:"Resume 失败",body:I instanceof Error?I.message:String(I)})}finally{P(!1)}}},D=async()=>{if(window.confirm(`确认删除 Agent ${t.id}?此操作不可撤销`)){c(!0),g(null);try{const I=await _.projects.deleteAgent(s,t.id);I!=null&&I.restartRequired&&k();const he=(I==null?void 0:I.removed)??[t.id];if(he.length>1){const we=he.filter(me=>me!==t.id).join(", ");m({kind:"warn",title:`已删除 Agent ${t.id}`,body:`配对的 QA Agent ${we} 也被一并移除。`})}else m({kind:"success",title:`Agent ${t.id} 已删除`});a==null||a()}catch(I){g(I instanceof Error?I.message:String(I))}finally{c(!1)}}},A=N&&!W&&!B,Y=["card flex h-full min-w-0 flex-col p-4",B?"ring-2 ring-accent":""].filter(Boolean).join(" "),re=["mb-2 mt-3 h-80 min-h-0 overflow-hidden border border-hairline bg-surface",A?"cursor-pointer":""].filter(Boolean).join(" "),oe=A?()=>u==null?void 0:u():void 0,ae=A?I=>{(I.key==="Enter"||I.key===" ")&&(I.preventDefault(),u==null||u())}:void 0;return e.jsxs("div",{className:Y,"data-agent-card":N?t.id:void 0,children:[e.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",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:r}),e.jsx("span",{className:"min-w-0 truncate whitespace-nowrap font-display text-[14px] font-semibold text-og-1000",title:t.id,children:t.id})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-1",children:[Q&&e.jsx("span",{className:"pill pill-warn",title:((q=t.binding)==null?void 0:q.awaitingReason)??"需人工处理",children:"Held"}),e.jsx("span",{className:se.cls,children:se.label}),t.stale&&e.jsx("span",{className:"pill pill-warn",title:t.observedAt?`Last observed at ${t.observedAt}`:void 0,children:"Stale"}),e.jsx(Ds,{state:ee})]})]}),V&&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 正在启动,终端可用后会自动刷新。"}),Q&&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:(fe=t.binding)==null?void 0:fe.awaitingPhase}),((be=t.binding)==null?void 0:be.awaitingReason)&&e.jsxs("span",{children:[" · ",t.binding.awaitingReason]})]}),!V&&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(Ee,{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:z,disabled:R,className:"btn-secondary shrink-0 !border-[#fecaca] !text-danger hover:!bg-[#fef2f2] hover:!border-danger hover:!text-danger",children:R?"Retrying…":"Retry bootstrap"})]})]}),d&&U&&e.jsxs("div",{className:"mb-2 text-[12px] text-og-500",children:["Task: ",e.jsx("span",{className:"font-mono text-og-700",children:U})]}),ie&&e.jsx("div",{className:"mb-2 overflow-hidden border border-hairline bg-surface",children:e.jsx(ke,{agentId:t.id,mode:"preview",maxLines:6,interactive:!1})}),ne&&e.jsx("div",{className:re,role:A?"button":void 0,tabIndex:A?0:void 0,"aria-label":A?`激活 ${t.id} 终端`:void 0,onClick:oe,onKeyDown:ae,children:W?e.jsx("div",{className:"flex h-full items-center justify-center px-3 text-[13px] text-og-500",children:X}):N?B?e.jsx(ke,{agentId:t.id,mode:"full",interactive:!0,autoFocus:!0}):e.jsx(ke,{agentId:t.id,mode:"preview",interactive:!1}):e.jsx(ke,{agentId:t.id,mode:"full",interactive:!0,autoFocus:!1,deferFullUntilFocus:!0})}),n&&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:[W?e.jsx("span",{className:"shrink-0 cursor-not-allowed text-[13px] text-og-400",title:X,children:"Terminal"}):e.jsx(Ee,{to:`/terminal/${t.id}`,className:"btn-secondary shrink-0",children:"Terminal"}),!n&&t.runtimeStatus==="working"&&e.jsx("button",{onClick:J,disabled:l,className:"btn-ghost shrink-0 !text-danger hover:!bg-[#fef2f2]",children:l?"Stopping…":"Stop"}),Q&&e.jsx("button",{type:"button",onClick:j,disabled:C,title:"清除 awaiting_human 状态,让 agent 重新可派遣",className:"btn-ghost shrink-0 !text-warn hover:!bg-[#fef3c7]/60",children:C?"Resuming…":"Resume"}),!n&&U&&r==="dev"&&e.jsx("button",{type:"button",onClick:ue,disabled:L,title:`让 QA 立即对 task ${U} 跑一轮 review(需要该 task 已有 PR)`,className:"btn-ghost shrink-0 !text-accent hover:!bg-accent-soft",children:L?"Dispatching…":"Call review"})]}),e.jsxs("div",{className:"relative shrink-0",children:[e.jsx("button",{ref:O,id:G,type:"button",onClick:()=>b(I=>!I),disabled:T,"aria-haspopup":"menu","aria-expanded":$,"aria-controls":K,"aria-label":`Agent ${t.id} 操作菜单`,className:"flex h-8 w-8 items-center justify-center rounded text-og-500 transition-colors hover:bg-og-100 hover:text-og-1000 disabled:cursor-not-allowed disabled:opacity-50",children:e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("circle",{cx:"12",cy:"12",r:"1"}),e.jsx("circle",{cx:"12",cy:"5",r:"1"}),e.jsx("circle",{cx:"12",cy:"19",r:"1"})]})}),$&&e.jsx("div",{ref:M,id:K,role:"menu","aria-labelledby":G,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),D()},disabled:T,className:"block w-full px-3 py-1.5 text-left text-[13px] text-danger hover:bg-[#fef2f2] disabled:opacity-50",children:T?"删除中…":"删除"})})]})]}),y&&e.jsx("div",{className:"mt-1.5 break-words text-[12px] text-danger",children:y}),E&&e.jsx("div",{className:"mt-1.5 break-words text-[12px] text-danger",children:E})]})}const $s={sm:"max-w-md",md:"max-w-lg",lg:"max-w-2xl"},ft='input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), [href], [tabindex]:not([tabindex="-1"])';function je({open:t,onClose:s,title:r,children:a,footer:n,size:i="md",dismissOnBackdrop:d=!0}){const f=o.useRef(null),h=o.useRef(null),u=o.useRef(s);return o.useEffect(()=>{u.current=s},[s]),o.useEffect(()=>{if(!t)return;h.current=document.activeElement;const l=x=>{if(x.key==="Escape"){u.current();return}if(x.key!=="Tab")return;const m=f.current;if(!m)return;const k=Array.from(m.querySelectorAll(ft)).filter(g=>g.offsetParent!==null||g===document.activeElement);if(k.length===0){x.preventDefault();return}const T=k[0],c=k[k.length-1],E=document.activeElement;x.shiftKey&&(E===T||!m.contains(E))?(x.preventDefault(),c.focus()):!x.shiftKey&&(E===c||!m.contains(E))&&(x.preventDefault(),T.focus())};document.addEventListener("keydown",l);const p=document.body.style.overflow;document.body.style.overflow="hidden";const y=f.current;if(y){const x=y.querySelector(ft);x==null||x.focus()}return()=>{var x,m;document.removeEventListener("keydown",l),document.body.style.overflow=p,(m=(x=h.current)==null?void 0:x.focus)==null||m.call(x)}},[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",onClick:d?()=>u.current():void 0,role:"presentation",children:e.jsxs("div",{ref:f,className:`flex w-full ${$s[i]} max-h-[90dvh] flex-col overflow-hidden rounded-lg border border-og-100 bg-surface shadow-modal`,onClick:l=>l.stopPropagation(),role:"dialog","aria-modal":"true","aria-label":r,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:r,className:"truncate font-display text-[15px] font-semibold tracking-tight text-og-1000",children:r}),e.jsx("button",{type:"button",onClick:()=>u.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:a}),n&&e.jsx("div",{className:"flex shrink-0 flex-wrap items-center justify-end gap-2 border-t border-hairline px-5 py-3",children:n})]})}):null}const ht=200,mt=16e3,Ls="baxian.draft.createTask:";function Xe(t){return`${Ls}${t??"*"}`}function xt(t){try{const s=localStorage.getItem(t);if(!s)return null;const r=JSON.parse(s);if(!r||typeof r!="object")return null;const a=r,n=typeof a.title=="string"?a.title:"",i=typeof a.description=="string"?a.description:"",d=typeof a.projectId=="string"?a.projectId:"",f=typeof a.preferredAgentId=="string"?a.preferredAgentId:"",h=typeof a.updatedAt=="number"?a.updatedAt:void 0;return!n.trim()&&!i.trim()?null:{title:n,description:i,projectId:d,preferredAgentId:f,updatedAt:h}}catch{return null}}function Os(t,s){const r=!s.title.trim()&&!s.description.trim();try{r?localStorage.removeItem(t):localStorage.setItem(t,JSON.stringify({...s,updatedAt:Date.now()}))}catch{}}function pt(t){try{localStorage.removeItem(t)}catch{}}function Ms(t){const s=Xe(t),r=xt(s);if(!t)return r;const a=Xe(void 0),n=xt(a);if(!n||n.projectId!==t)return r;const i=!r||(n.updatedAt??0)>(r.updatedAt??0);if(i)try{localStorage.setItem(s,JSON.stringify(n))}catch{return n}try{localStorage.removeItem(a)}catch{}return i?n:r}const $e="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",Ne="mb-1.5 block text-[12px] font-medium text-og-700",bt="mt-1 text-right text-[12px] text-og-400",_s=Math.floor(Be/1024/1024);function rt(t){const s=t.mode==="edit",{show:r}=pe(),a=s?t.task.projectId:t.projectId,n=s?t.task.title:"",i=s?t.task.description:"",d=s?t.task.preferredAgentId:"",[f,h]=o.useState([]),[u,l]=o.useState([]),[p,y]=o.useState(a??""),[x,m]=o.useState(d),[k,T]=o.useState(n),[c,E]=o.useState(i),[g,L]=o.useState([]),w=o.useRef(null),[C,P]=o.useState(!1),[R,S]=o.useState(null),[$,b]=o.useState(!1),O=o.useRef(0),M=o.useRef(0),K=o.useRef(0),G=o.useRef(new Set),U=s?null:Xe(a);o.useEffect(()=>{if(!t.open)return;O.current+=1,M.current+=1;const v=O.current;h([]),l([]),G.current=new Set;const F=U?Ms(a):null;F&&G.current.add(F.projectId),y(a??(F==null?void 0:F.projectId)??""),m((F==null?void 0:F.preferredAgentId)||d),T((F==null?void 0:F.title)||n),E((F==null?void 0:F.description)||i),b(F!==null),S(null),P(!1),L([]),Promise.all([_.projects.list(),_.agents.list()]).then(([Z,q])=>{v===O.current&&(h(Z),l(q))}).catch(Z=>{v===O.current&&S(Z instanceof Error?Z.message:String(Z))})},[t.open,a,n,i,d,U]),o.useEffect(()=>{if(!(!t.open||!U)){if(K.current!==M.current){K.current=M.current;return}Os(U,{title:k,description:c,projectId:p,preferredAgentId:x})}},[t.open,U,k,c,p,x]);const Q=o.useMemo(()=>f.find(v=>v.id===p)??null,[f,p]),V=o.useMemo(()=>Q?Q.agent.flat().filter(v=>v.role==="dev"):[],[Q]),se=o.useMemo(()=>new Set(u.map(v=>v.id)),[u]),ee=o.useMemo(()=>V.filter(v=>se.has(v.id)),[V,se]),ie=o.useMemo(()=>V.filter(v=>!se.has(v.id)),[V,se]);o.useEffect(()=>{s||Q!==null&&x!==""&&!ee.find(v=>v.id===x)&&m("")},[Q,ee,x,s]),o.useEffect(()=>{s||Q&&ee.length!==0&&(G.current.has(Q.id)||(G.current.add(Q.id),m(v=>v===""?ee[0].id:v)))},[s,Q,ee]);const ne=!s||ee.find(v=>v.id===x),N=s&&!ne&&!!x,B=N&&ie.some(v=>v.id===x),W=B?`当前 dev "${x}" 在 baxian.json 中存在但 runtime 未加载,可能是手动编辑过配置文件;重启 server 可拉起`:N?`当前 dev "${x}" 不在 runtime(可能已从 project 配置移除);保存可能失败,请确认或选择新 dev`:!p||ee.length>0?null:ie.length>0?"baxian.json 里有 dev agent 但 runtime 未加载(可能是手动编辑过配置);重启 server 后生效":null,X=k.trim(),J=c.trim(),z=!!p&&X.length>0&&J.length>0&&!C,j=()=>{C||t.onClose()},D=()=>{U&&(pt(U),y(a??""),m(d),T(n),E(i),S(null),b(!1))},A=async v=>{var F,Z;if(v.preventDefault(),!!z){P(!0),S(null);try{if(t.mode==="edit"){const q=await _.tasks.update(t.task.id,{title:X,description:J,preferredAgentId:x});r({kind:"success",title:"任务已更新"}),(F=t.onUpdated)==null||F.call(t,q),t.onClose()}else{const q=g.length?await Promise.all(g.map(async be=>({dataBase64:await At(be),filename:be.name}))):void 0,fe=await _.tasks.create({projectId:p,title:X,description:J,preferredAgentId:x,...q?{images:q}:{}});U&&pt(U),r({kind:"success",title:"任务已创建"}),(Z=t.onCreated)==null||Z.call(t,fe),t.onClose()}}catch(q){S(q instanceof Error?q.message:String(q))}finally{P(!1)}}},Y=v=>{const F=Array.from(v.target.files??[]);if(v.target.value="",F.length===0)return;const Z=F.filter(q=>q.size>Be?(r({kind:"error",title:"图片过大",body:`${q.name} 超过 ${_s} MiB`}),!1):!0);L(q=>(q.length+Z.length>Ie&&r({kind:"warn",title:`最多 ${Ie} 张图片`}),[...q,...Z].slice(0,Ie)))},re=v=>L(F=>F.filter((Z,q)=>q!==v)),oe=s?"编辑 Task":"新建 Task",ae=s?C?"保存中…":"保存":C?"创建中…":"创建",ce=!s&&!a;return e.jsx(je,{open:t.open,onClose:j,title:oe,size:"md",dismissOnBackdrop:!1,footer:e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:j,disabled:C,className:"btn-secondary",children:"取消"}),e.jsx("button",{type:"submit",form:"create-task-form",disabled:!z,className:"btn-primary",children:ae})]}),children:e.jsxs("form",{id:"create-task-form",onSubmit:A,className:"space-y-3",children:[!s&&$&&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:D,className:"shrink-0 underline hover:text-accent-hover",children:"丢弃"})]}),R&&e.jsx("div",{className:"rounded-md border border-[#fecaca] bg-[#fef2f2] px-3 py-2 text-[13px] text-danger",children:R}),ce&&e.jsxs("div",{children:[e.jsx("label",{className:Ne,htmlFor:"task-project",children:"Project"}),e.jsxs("select",{id:"task-project",value:p,onChange:v=>y(v.target.value),className:$e,disabled:C,required:!0,children:[e.jsx("option",{value:"",disabled:!0,children:"选择项目"}),f.map(v=>e.jsx("option",{value:v.id,children:v.id},v.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ne,htmlFor:"task-dev",children:"Dev Agent"}),e.jsxs("select",{id:"task-dev",value:x,onChange:v=>m(v.target.value),className:$e,disabled:C,children:[e.jsx("option",{value:"",children:"暂不指定"}),N&&e.jsxs("option",{value:x,children:[x," ",B?"(待重启)":"(不在 runtime)"]}),ee.map(v=>e.jsx("option",{value:v.id,children:v.id},v.id))]}),W&&e.jsx("div",{className:"mt-1 text-[12px] text-warn",children:W})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ne,htmlFor:"task-title",children:"Title"}),e.jsx("input",{id:"task-title",type:"text",value:k,onChange:v=>T(v.target.value),maxLength:ht,className:$e,placeholder:"一句话描述要做什么",disabled:C,required:!0}),e.jsxs("div",{className:bt,children:[k.length," / ",ht]})]}),e.jsxs("div",{children:[e.jsx("label",{className:Ne,htmlFor:"task-description",children:"Description"}),e.jsx("textarea",{id:"task-description",value:c,onChange:v=>E(v.target.value),maxLength:mt,rows:8,className:`${$e} font-mono text-[12px]`,placeholder:"详细描述任务,支持 markdown",disabled:C,required:!0}),e.jsxs("div",{className:bt,children:[c.length," / ",mt]})]}),!s&&e.jsxs("div",{children:[e.jsx("label",{className:Ne,children:"图片(可选)"}),e.jsx("button",{type:"button",onClick:()=>{var v;return(v=w.current)==null?void 0:v.click()},disabled:C||g.length>=Ie,className:"btn-secondary",children:"添加图片"}),e.jsx("input",{ref:w,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:Y}),g.length>0&&e.jsx("ul",{className:"mt-2 space-y-1",children:g.map((v,F)=>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:v.name,className:"truncate text-[12px] text-og-700",children:v.name}),e.jsx("button",{type:"button","aria-label":`移除图片 ${v.name}`,onClick:()=>re(F),disabled:C,className:"ml-2 shrink-0 text-og-400 transition-colors hover:text-danger",children:"✕"})]},`${v.name}-${F}`))})]})]})})}function Fs(t){return Array.from(new TextEncoder().encode(t)).map(s=>s.toString(16).padStart(2,"0")).join("")}function Bs(){return`${location.protocol==="https:"?"wss":"ws"}://${location.host}/api/realtime`}const zs=(t,s)=>s&&s.length>0?new WebSocket(t,s):new WebSocket(t);class Us{constructor(s={}){H(this,"wsUrl");H(this,"wsFactory");H(this,"tokenProvider");H(this,"ws",null);H(this,"topics",new Map);H(this,"cache",new Map);H(this,"outbox",[]);H(this,"reconnectScheduler");H(this,"explicitlyClosed",!1);this.wsUrl=s.wsUrl??Bs(),this.wsFactory=s.wsFactory??zs,this.tokenProvider=s.tokenProvider??nt,this.reconnectScheduler=new Dt({reconnect:()=>this.openSocket(),shouldReconnect:()=>!this.explicitlyClosed&&this.topics.size>0})}subscribe(s,r,a){let n=this.topics.get(s);const i=!n;return n||(n={data:new Set,error:new Set},this.topics.set(s,n)),n.data.add(r),a&&n.error.add(a),i?(this.ensureSocket(),this.wsSendOrQueue({op:"subscribe",topic:s})):this.cache.has(s)&&queueMicrotask(()=>{var d;(d=this.topics.get(s))!=null&&d.data.has(r)&&this.cache.has(s)&&r(this.cache.get(s))}),()=>this.unsubscribe(s,r,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,r,a){const n=this.topics.get(s);n&&(n.data.delete(r),a&&n.error.delete(a),n.data.size===0&&n.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(),r=s?[`baxian.token.${Fs(s)}`]:void 0;let a;try{a=this.wsFactory(this.wsUrl,r)}catch(i){console.warn("[events-client] WebSocket constructor threw:",i),this.broadcastConnectionError({code:"connection_failed",message:i instanceof Error?i.message:"WebSocket constructor threw"}),this.scheduleReconnect();return}this.ws=a;let n=!1;a.onopen=()=>{if(a!==this.ws)return;n=!0,this.reconnectScheduler.reset();for(const d of this.topics.keys())try{a.send(JSON.stringify({op:"subscribe",topic:d}))}catch(f){console.warn("[events-client] resubscribe send failed:",f)}const i=this.outbox;this.outbox=[];for(const d of i)if(!(d.op==="subscribe"||d.op==="unsubscribe"))try{a.send(JSON.stringify(d))}catch(f){console.warn("[events-client] outbox flush failed:",f)}},a.onmessage=i=>{if(a!==this.ws)return;let d;try{const f=typeof i.data=="string"?i.data:String(i.data);d=JSON.parse(f)}catch{return}this.handleMessage(d)},a.onclose=()=>{a===this.ws&&(this.ws=null,!this.explicitlyClosed&&(n||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 r of this.topics.values())for(const a of[...r.error])try{a(s)}catch(n){console.error("[events-client] error handler threw on connection error:",n)}}wsSendOrQueue(s){if(this.ws&&this.ws.readyState===WebSocket.OPEN)try{this.ws.send(JSON.stringify(s));return}catch(r){console.warn("[events-client] send failed, will queue:",r)}this.outbox.push(s)}handleMessage(s){switch(s.type){case"data":{const r=this.topics.get(s.topic);if(this.cache.set(s.topic,s.data),!r)return;for(const a of[...r.data])try{a(s.data)}catch(n){console.error(`[events-client] handler threw on ${s.topic}:`,n)}break}case"error":{const r={code:s.code,message:s.message};if(s.topic){const a=this.topics.get(s.topic);if(a)for(const n of[...a.error])try{n(r)}catch(i){console.error(`[events-client] error handler threw on ${s.topic}:`,i)}}else console.warn("[events-client] connection-level error:",s.code,s.message);break}}}}let Ke=null;function ot(){return Ke||(Ke=new Us),Ke}function Pt(){const[t,s]=o.useState(null),[r,a]=o.useState(!1),[n,i]=o.useState(null);return o.useEffect(()=>ot().subscribe("agents",f=>{i(null),s(f),a(!0)},f=>i(f)),[]),{data:t,loaded:r,error:n}}function Ws(t){const[s,r]=o.useState(null),[a,n]=o.useState(!1),[i,d]=o.useState(null);return o.useEffect(()=>(r(null),n(!1),d(null),ot().subscribe(`task:${t}`,h=>{d(null),r(h),n(!0)},h=>d(h))),[t]),{data:s,loaded:a,error:i}}function $t(t){const[s,r]=o.useState(null),[a,n]=o.useState(!1),[i,d]=o.useState(null);return o.useEffect(()=>{if(!t){r(null),n(!1),d(null);return}r(null),n(!1),d(null);let f=!1,h=!1,u=!1;const l=ot().subscribe(`project-tasks:${t}`,p=>{f||(h=!0,d(null),r(p),n(!0))},p=>{f||(d(p),!(h||u)&&(u=!0,_.tasks.list(t).then(y=>{f||h||(r(y),n(!0))},y=>{console.warn(`[useProjectTasks] REST fallback failed for ${t}:`,y)})))});return()=>{f=!0,l()}},[t]),{data:s,loaded:a,error:i}}const Lt=o.createContext(null);function Qs({children:t}){const[s,r]=o.useState(null),a=o.useCallback(i=>r(i),[]),n=o.useCallback(()=>r(null),[]);return e.jsxs(Lt.Provider,{value:{openTask:a},children:[t,s!==null&&e.jsx(Hs,{taskId:s,onClose:n,onOpenTask:r},s)]})}function Te(){const t=o.useContext(Lt);if(!t)throw new Error("useTaskDetail must be inside <TaskDetailProvider>");return t}const gt=Ct,Ot={pending:"pill",in_progress:"pill pill-live",review:"pill pill-review",fixing:"pill pill-warn",approved:"pill pill-live","merge-ready":"pill pill-live",merged:"pill pill-live",failed:"pill pill-warn",max_rounds:"pill pill-warn",cancelled:"pill"},qs={pending:"bg-og-300",in_progress:"bg-success",review:"bg-accent",fixing:"bg-warn",approved:"bg-success","merge-ready":"bg-success",merged:"bg-success",failed:"bg-warn",max_rounds:"bg-warn",cancelled:"bg-og-300"};function Gs({status:t}){return e.jsx("span",{role:"img","aria-label":t,title:t,className:`inline-block h-2 w-2 shrink-0 rounded-full ${qs[t]??"bg-og-300"}`})}function at(t){if(!t)return"";const s=t.match(/^task-(\d+)$/);return s?s[1]:t}function Hs({taskId:t,onClose:s,onOpenTask:r}){const{show:a}=pe(),[n,i]=o.useState(!1),[d,f]=o.useState(!1),[h,u]=o.useState(!1),[l,p]=o.useState(!1),[y,x]=o.useState(null),{data:m,loaded:k,error:T}=Ws(t),c=y??m,E=(T==null?void 0:T.message)??null;o.useEffect(()=>{y&&m&&m.updatedAt>=y.updatedAt&&x(null)},[y,m]);const g=S=>{x(S)},L=async()=>{if(c&&confirm(`确定取消 task ${c.id}?`)){f(!0);try{const S=await _.tasks.update(c.id,{status:"cancelled"});g(S),a({kind:"success",title:"任务已取消"})}catch(S){a({kind:"error",title:"取消失败",body:S instanceof Error?S.message:String(S)})}finally{f(!1)}}},w=async()=>{if(!c)return;const $=Ct.has(c.status)?`task ${c.id} 已是 ${c.status} 状态。手动请 QA 重审会再跑一轮 review,但状态机不会把 QA 结果带回主流程。继续?`:`请 QA 重审 task ${c.id}?这会让 QA agent 立即开始新一轮 review(reviewRound +1)。`;if(confirm($)){p(!0);try{const b=await _.tasks.review(c.id);g(b),a({kind:"success",title:`已派 QA 重审 (round ${b.reviewRound})`})}catch(b){a({kind:"error",title:"Review 派发失败",body:b instanceof Error?b.message:String(b)})}finally{p(!1)}}},C=async()=>{if(!c)return;const S=c.status==="merged"?`task ${c.id} 已 merged。Retry 会用同样的标题/描述新建一个 task 从头跑,确定继续?`:`Retry task ${c.id}?这会新建一个 task 从头开始,旧 task 保留为历史。`;if(confirm(S)){u(!0);try{const $=await _.tasks.retry(c.id);a({kind:"success",title:`已新建 task ${$.id}`}),r($.id)}catch($){a({kind:"error",title:"Retry 失败",body:$ instanceof Error?$.message:String($)})}finally{u(!1)}}};if(n&&c)return e.jsx(rt,{mode:"edit",open:!0,onClose:()=>i(!1),task:c,onUpdated:g});return e.jsx(je,{open:!0,onClose:s,title:c?c.title:t,size:"lg",footer:c?R(c):void 0,children:P()});function P(){if(E&&!c)return e.jsxs("div",{className:"text-[13px] text-danger",children:["Error: ",E]});if(k&&!c)return e.jsxs("div",{className:"text-[13px] text-danger",children:["Task not found: ",t]});if(!c)return e.jsx("div",{className:"text-[13px] text-og-500",children:"Loading…"});const S=c.preferredAgentId==="",$=c.status==="approved"&&c.prNumber!==void 0,b=c.status==="merge-ready"&&c.prNumber!==void 0;return e.jsxs("div",{children:[E&&e.jsxs("div",{className:"mb-4 text-[13px] text-danger",children:["Error: ",E]}),S&&e.jsx("div",{className:"mb-4 rounded-md border border-[#fde68a] bg-[#fef3c7]/60 px-3 py-2.5 text-[12px] text-warn",children:c.status==="pending"?e.jsxs(e.Fragment,{children:["This task has no dev assigned yet — click ",e.jsx("b",{className:"font-semibold",children:"Edit"})," to choose one, or use the Start button on any idle dev card."]}):e.jsxs(e.Fragment,{children:["This is a legacy task with no preferred dev (read-only in status ",e.jsx("b",{className:"font-semibold",children:c.status}),")."]})}),e.jsxs("div",{className:"mb-4 flex flex-wrap items-center gap-3",children:[e.jsx("span",{className:"font-mono text-[13px] text-og-500",children:c.id}),e.jsx("span",{className:Ot[c.status],children:c.status}),c.phase==="spec"&&e.jsx("span",{className:"pill pill-review",children:"spec phase"}),e.jsxs("span",{className:"text-[12px] text-og-500",children:["created ",c.createdAt]}),e.jsxs("span",{className:"text-[12px] text-og-500",children:["updated ",c.updatedAt]})]}),$&&e.jsxs("div",{className:"mb-4 rounded-lg border border-[#bbf7d0] bg-[#f0fdf4] p-4 text-[13px] text-success",children:[e.jsx("div",{className:"font-semibold",children:"QA approved · verifying feedback"}),e.jsx("div",{className:"mt-1 text-og-700",children:"Dev keeps the task reserved while it checks whether all human or agent feedback has been handled."}),c.prUrl&&e.jsxs("a",{href:c.prUrl,target:"_blank",rel:"noopener noreferrer",className:"btn-secondary mt-3 !border-[#bbf7d0] !text-success hover:!bg-[#dcfce7] hover:!border-success",children:["Open PR #",c.prNumber]})]}),b&&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 to merge"}),e.jsx("div",{className:"mt-1 text-og-700",children:"Dev finished its post-approve checks — the PR is approved and can be merged now."}),c.prUrl&&e.jsxs("a",{href:c.prUrl,target:"_blank",rel:"noopener noreferrer",className:"btn-secondary mt-3 !border-[#bbf7d0] !text-success hover:!bg-[#dcfce7] hover:!border-success",children:["Open PR #",c.prNumber]})]}),e.jsx("pre",{className:"card mb-4 whitespace-pre-wrap p-4 text-[13px] text-og-800",children:c.description}),e.jsxs("div",{className:"card grid grid-cols-1 gap-x-6 gap-y-2 p-4 text-[13px] md:grid-cols-2",children:[e.jsxs("div",{className:"text-og-500",children:["Project: ",e.jsx("span",{className:"font-mono text-og-800",children:c.projectId})]}),e.jsxs("div",{className:"text-og-500",children:["Dev: ",e.jsx("span",{className:"font-mono text-og-800",children:c.agentId||"—"})]}),e.jsxs("div",{className:"text-og-500",children:["Preferred: ",e.jsx("span",{className:"font-mono text-og-800",children:c.preferredAgentId||"—"})]}),e.jsxs("div",{className:"text-og-500",children:["QA: ",e.jsx("span",{className:"font-mono text-og-800",children:c.qaAgentId||"—"})]}),e.jsxs("div",{className:"text-og-500",children:["PR:"," ",c.prNumber?c.prUrl?e.jsxs("a",{href:c.prUrl,target:"_blank",rel:"noopener noreferrer",className:"text-accent hover:text-accent-hover",children:["#",c.prNumber]}):e.jsxs("span",{className:"font-mono text-og-800",children:["#",c.prNumber]}):e.jsx("span",{className:"text-og-400",children:"—"})]}),e.jsxs("div",{className:"text-og-500",children:["Branch: ",e.jsx("span",{className:"font-mono text-og-800",children:c.branch||"—"})]}),e.jsxs("div",{className:"text-og-500",children:["Round: ",e.jsx("span",{className:"font-mono text-og-800",children:c.reviewRound}),c.specReviewRound!==void 0&&c.specReviewRound>0&&e.jsxs("span",{className:"ml-2 text-[12px] text-accent",children:["spec: ",c.specReviewRound]})]})]})]})}function R(S){const $=S.status==="pending",b=S.status==="pending"||S.status==="in_progress",O=gt.has(S.status)&&!!S.preferredAgentId,M=!!S.prNumber,K=S.preferredAgentId==="";return e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",disabled:!$,onClick:()=>i(!0),className:"btn-secondary",children:"Edit"}),e.jsx("button",{type:"button",disabled:!b||d,onClick:L,className:"btn-secondary !border-[#fecaca] !text-danger hover:!bg-[#fef2f2] hover:!border-danger",children:d?"Cancelling…":"Cancel"}),e.jsx("button",{type:"button",disabled:!O||h,onClick:C,title:gt.has(S.status)?K?"Legacy task has no preferred dev to retry against":"新建一个 task 从头跑,丢弃当前 worktree/branch":`Cannot retry in status ${S.status}`,className:"btn-secondary",children:h?"Retrying…":"Retry"}),e.jsx("button",{type:"button",disabled:!M||l,onClick:w,title:S.prNumber?"让 QA agent 立即开始新一轮 review(reviewRound +1)":"该 task 还没有 PR,无法派 review",className:"btn-secondary !border-accent-soft !text-accent hover:!bg-accent-soft hover:!border-accent",children:l?"Dispatching…":"Call review"})]})}}const Ve="baxian:terminal-activated";function Mt({group:t,projectId:s,agentsById:r,agentsLoaded:a,agentsError:n=!1,tasks:i,onDeleted:d,terminalMode:f="activity-preview"}){var R,S,$;const h=t.find(b=>b.role==="dev")??t[0],u=t.find(b=>b.role==="qa"),l=i.filter(b=>Vs(b,h==null?void 0:h.id,u==null?void 0:u.id)),p=h?i.filter(b=>Js(b,s,h.id)).sort((b,O)=>b.createdAt.localeCompare(O.createdAt)):[],y=h?r.get(h.id):void 0,x=!!y&&y.runtimeStatus==="idle"&&((R=y.binding)==null?void 0:R.status)!=="awaiting_human"&&!((S=y.binding)!=null&&S.creationToken)&&!(($=y.binding)!=null&&$.taskId),m=`Agent group ${t.map(b=>b.id).join(" / ")}`,{openTask:k}=Te(),T=f==="embedded-full",c=o.useId(),[E,g]=o.useState(null);o.useEffect(()=>{if(!T)return;const b=K=>{K.composedPath().some(Q=>Q instanceof Element&&Q.hasAttribute("data-agent-card"))||g(null)},O=K=>{if(K.key!=="Escape")return;const G=document.activeElement;G instanceof Element&&G.closest("[data-agent-card]")||g(null)},M=K=>{const G=K.detail;(G==null?void 0:G.groupId)!==c&&g(null)};return document.addEventListener("click",b),document.addEventListener("keydown",O),document.addEventListener(Ve,M),()=>{document.removeEventListener("click",b),document.removeEventListener("keydown",O),document.removeEventListener(Ve,M)}},[T,c]);const L=b=>{g(b),document.dispatchEvent(new CustomEvent(Ve,{detail:{groupId:c}}))},w=f==="embedded-full"?t.length<=1?"lg:grid-cols-1":t.length===2?"lg:grid-cols-2":t.length===3?"lg:grid-cols-3":"lg:grid-cols-4":"sm:grid-cols-2",C=!!h&&p.length>0,P=l.length===0&&!C;return e.jsxs("div",{role:"group","aria-label":m,className:"min-w-0",children:[C&&h&&e.jsx(Ks,{tasks:p,devId:h.id,dispatchReady:x,label:m}),l.length>0&&e.jsx("div",{className:"card mb-2 max-h-28 overflow-y-auto divide-y divide-hairline",children:l.map(b=>{const O=b.phase==="spec"?b.specReviewRound??0:b.reviewRound;return e.jsxs("button",{type:"button",onClick:()=>k(b.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:b.id,children:at(b.id)}),e.jsx("span",{className:"truncate text-og-1000",children:b.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 ",O]}),e.jsx("span",{className:`${Ot[b.status]} shrink-0`,children:b.status})]})]},b.id)})}),P&&e.jsx("div",{className:"mb-2 rounded-lg border border-hairline bg-surface px-3 py-2 text-[13px] text-og-400","aria-label":`${m} no active task`,children:"暂无任务"}),e.jsx("div",{className:`grid grid-cols-1 ${w} gap-4`,children:t.map(b=>{const O=r.get(b.id),M=O??{id:b.id,projectId:s,runtimeStatus:"unknown",tmuxSessionStatus:"unknown",stale:!0};return e.jsx(Ps,{agent:M,projectId:s,role:b.role,pendingRestart:a&&!O,terminalLoading:!a&&!O&&!n,onDeleted:d,showTaskBinding:!1,terminalMode:f,...T?{active:E===b.id,onActivate:()=>L(b.id)}:{}},b.id)})})]})}function Ks({tasks:t,devId:s,dispatchReady:r,label:a}){const{show:n}=pe(),{openTask:i}=Te(),[d,f]=o.useState(null),h=async u=>{f(u);try{await _.tasks.dispatch(u,{agentId:s}),n({kind:"success",title:`Task ${u} 已派给 ${s}`})}catch(l){n({kind:"error",title:"派遣失败",body:l instanceof Error?l.message:String(l)})}finally{f(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(u=>{const l=u.preferredAgentId==="",p=d!==null;return e.jsxs("div",{className:"flex items-center gap-3 px-3 py-2 text-[13px]",children:[e.jsxs("button",{type:"button",onClick:()=>i(u.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:u.id,children:at(u.id)}),e.jsx("span",{className:"truncate text-og-1000",title:u.title,children:u.title}),l&&e.jsx("span",{className:"pill shrink-0",children:"未分配"})]}),e.jsx("button",{type:"button",onClick:()=>void h(u.id),disabled:!r||p,title:r?`派给 ${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:d===u.id?"Starting…":"Start"})]},u.id)})})}function Vs(t,s,r){return!(!s||!Rt.has(t.status)||!(t.agentId===s||t.preferredAgentId===s)||r&&t.qaAgentId&&t.qaAgentId!==r)}function Js(t,s,r){return t.projectId!==s||t.status!=="pending"?!1:t.preferredAgentId===r||t.preferredAgentId===""}const Ys=/^[a-z][a-z0-9-]{1,31}$/,Xs=/^[A-Za-z0-9_-][A-Za-z0-9._-]*\/[A-Za-z0-9_-][A-Za-z0-9._-]*$/,vt="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",Je="mb-1.5 block text-[12px] font-medium text-og-700",yt="mt-1 text-[12px] text-danger";function Zs({open:t,onClose:s,onCreated:r}){const[a,n]=o.useState(""),[i,d]=o.useState(""),[f,h]=o.useState(null),[u,l]=o.useState(!1),[p,y]=o.useState(null),[x,m]=o.useState({}),[k,T]=o.useState(new Set),c=o.useRef(0),{show:E}=pe(),{flagDirty:g}=Ue();o.useEffect(()=>{if(!t)return;c.current+=1;const P=c.current;n(""),d(""),h(null),y(null),m({}),T(new Set),_.config.get().then(R=>{P===c.current&&T(new Set(R.project.map(S=>S.id)))}).catch(()=>{})},[t]);const L=()=>{u||s()},w=()=>{const P={};return a?Ys.test(a)?k.has(a)&&(P.id="该 id 已被占用"):P.id="小写字母开头,只含 a-z 0-9 -,长度 2-32":P.id="必填",i?Xs.test(i)||(P.repo="需为 owner/repo 形式"):P.repo="必填",m(P),Object.keys(P).length===0},C=async P=>{if(P.preventDefault(),!!w()){l(!0),y(null);try{const R=await _.projects.create({id:a,repo:i,merge:f});R.restartRequired&&g(),E({kind:"success",title:`项目 ${R.project.id} 已创建`}),r(R.project.id)}catch(R){y(R instanceof Error?R.message:String(R))}finally{l(!1)}}};return e.jsx(je,{open:t,onClose:L,title:"新建项目",size:"md",footer:e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:L,disabled:u,className:"btn-secondary",children:"取消"}),e.jsx("button",{type:"submit",form:"create-project-form",disabled:u,className:"btn-primary",children:u?"创建中…":"创建"})]}),children:e.jsxs("form",{id:"create-project-form",onSubmit:C,className:"space-y-3",children:[p&&e.jsx("div",{className:"rounded-md border border-[#fecaca] bg-[#fef2f2] px-3 py-2 text-[13px] text-danger",children:p}),e.jsxs("div",{children:[e.jsx("label",{className:Je,htmlFor:"proj-id",children:"项目 ID"}),e.jsx("input",{id:"proj-id",type:"text",value:a,onChange:P=>n(P.target.value),className:vt,placeholder:"kongkong",disabled:u}),x.id&&e.jsx("div",{className:yt,children:x.id})]}),e.jsxs("div",{children:[e.jsx("label",{className:Je,htmlFor:"proj-repo",children:"GitHub 仓库"}),e.jsx("input",{id:"proj-repo",type:"text",value:i,onChange:P=>d(P.target.value),className:vt,placeholder:"baxian-ai/baxian",disabled:u}),x.repo&&e.jsx("div",{className:yt,children:x.repo})]}),e.jsxs("div",{children:[e.jsx("span",{className:Je,children:"合并策略"}),e.jsxs("label",{className:"mb-1 flex items-center gap-2",children:[e.jsx("input",{type:"radio",name:"merge",checked:f===null,onChange:()=>h(null),disabled:u,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:f==="auto",onChange:()=>h("auto"),disabled:u,className:"h-3.5 w-3.5 accent-[#1348dc]"}),e.jsx("span",{className:"text-[13px] text-og-800",children:"QA Approve 后自动合并"})]})]})]})})}const jt=/^[a-z][a-z0-9-]{1,31}$/,en=500,ve="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",de="mb-1.5 block text-[12px] font-medium text-og-700",wt="mt-1 text-[12px] text-danger",Ye="mt-1 text-[12px] text-og-500",ye="h-3.5 w-3.5 accent-[#1348dc]",Nt={id:"",role:"dev",pairWith:"",mode:"local",hostname:"",user:"",runtime:"",workdir:"",yolo:!0,model:"",addDirs:""};function _t({open:t,onClose:s,projectId:r,onCreated:a}){var ne;const[n,i]=o.useState(Nt),[d,f]=o.useState(null),[h,u]=o.useState(new Set),[l,p]=o.useState(null),[y,x]=o.useState(!1),[m,k]=o.useState(!1),[T,c]=o.useState(null),E=o.useRef(null),g=o.useRef(null),L=o.useRef(0),{show:w}=pe(),{flagDirty:C}=Ue();o.useEffect(()=>{if(!t)return;L.current+=1;const N=L.current;i(Nt),f(null),u(new Set),p(null),x(!1),c(null),_.config.get().then(B=>{if(N!==L.current)return;const W=B.project.find(J=>J.id===r)??null;f(W);const X=new Set;B.project.forEach(J=>J.agent.forEach(ue=>ue.forEach(z=>X.add(z.id)))),u(X)}).catch(()=>{})},[t,r]);const P=()=>{m||s()},R=o.useCallback(()=>{E.current&&E.current.abort();const N=new AbortController;E.current=N,x(!0),c(null);const B=n.mode==="remote"?{hostname:n.hostname,user:n.user||void 0}:void 0;_.agents.probe(n.mode,B,{signal:N.signal}).then(W=>{N.signal.aborted||(p(W),c(null))}).catch(W=>{N.signal.aborted||(p(null),c(W instanceof Error?W.message:String(W)))}).finally(()=>{E.current===N&&x(!1)})},[n.mode,n.hostname,n.user]);o.useEffect(()=>{if(t&&(p(null),E.current&&E.current.abort(),!(n.mode==="remote"&&!n.hostname)))return g.current&&clearTimeout(g.current),g.current=setTimeout(R,en),()=>{g.current&&clearTimeout(g.current)}},[t,n.mode,n.hostname,n.user,R]),o.useEffect(()=>{t||E.current&&E.current.abort()},[t]),o.useEffect(()=>()=>{E.current&&E.current.abort(),g.current&&clearTimeout(g.current)},[]);const S=(d==null?void 0:d.agent.filter(N=>N.length===1&&N[0].role==="dev").map(N=>N[0]))??[],$=S.length>0,b=jt.test(n.id)&&!h.has(n.id),O=n.mode==="local"||n.mode==="remote"&&n.hostname.length>0,M=n.runtime!==""&&(n.runtime==="claude-code"?!!(l!=null&&l.runtimes["claude-code"].ok):!!(l!=null&&l.runtimes.codex.ok)),K=!!(l!=null&&l.tmux.ok),G=n.mode==="local"||!!((ne=l==null?void 0:l.ssh)!=null&&ne.ok),U=n.role==="dev"||n.role==="qa"&&n.pairWith!=="",Q=!m&&b&&O&&U&&M&&K&&G,V=async N=>{if(N.preventDefault(),!!Q){k(!0),c(null);try{const B=n.addDirs.split(`
2
- `).map(J=>J.trim()).filter(J=>J.length>0),W={id:n.id,role:n.role,runtime:n.runtime,mode:n.mode,...n.mode==="remote"?{host:{hostname:n.hostname,...n.user?{user:n.user}:{}}}:{},...n.workdir?{workdir:n.workdir}:{},yolo:n.yolo,...n.model.trim()?{model:n.model.trim()}:{},...B.length>0?{addDirs:B}:{},...n.role==="qa"?{pairWith:n.pairWith}:{}},X=await _.projects.addAgent(r,W);X.restartRequired&&C(),w({kind:"success",title:`Agent ${X.agent.id} 已添加到 ${r}`}),a(),s()}catch(B){c(B instanceof Error?B.message:String(B))}finally{k(!1)}}},se=({rt:N})=>{if(n.mode==="remote"&&!n.hostname)return e.jsx("span",{className:"ml-2 text-[12px] text-og-400",children:"(请先填写 hostname)"});if(y)return e.jsx("span",{className:"ml-2 text-[12px] text-og-400",children:"…探测中"});if(!l)return e.jsx("span",{className:"ml-2 text-[12px] text-og-400",children:"?"});const W=l.runtimes[N];return W.ok?e.jsxs("span",{className:"ml-2 text-[12px] text-success",children:["✓ ",W.path??""]}):e.jsxs("span",{className:"ml-2 text-[12px] text-danger",title:W.message,children:["⨯ ",W.message]})},ee=()=>n.mode==="remote"&&!n.hostname?null:y?e.jsx("div",{className:"text-[12px] text-og-400",children:"tmux: …探测中"}):l?l.tmux.ok?e.jsxs("div",{className:"text-[12px] text-success",children:["tmux: ✓ ",l.tmux.path??""]}):e.jsxs("div",{className:"text-[12px] text-danger",children:["tmux: ⨯ ",l.tmux.message]}):null,ie=()=>n.mode!=="remote"||!n.hostname||!(l!=null&&l.ssh)?null:l.ssh.ok?e.jsxs("div",{className:"text-[12px] text-success",children:["SSH: ✓ ",l.ssh.message]}):e.jsxs("div",{className:"text-[12px] text-danger",children:["SSH: ⨯ ",l.ssh.message]});return e.jsx(je,{open:t,onClose:P,title:`添加 Agent 到 ${r}`,size:"lg",footer:e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:P,disabled:m,className:"btn-secondary",children:"取消"}),e.jsx("button",{type:"submit",form:"create-agent-form",disabled:!Q,className:"btn-primary",children:m?"添加中…":"添加 Agent"})]}),children:e.jsxs("form",{id:"create-agent-form",onSubmit:V,className:"space-y-3",children:[T&&e.jsx("div",{className:"rounded-md border border-[#fecaca] bg-[#fef2f2] px-3 py-2 text-[13px] text-danger",children:T}),e.jsxs("div",{children:[e.jsx("label",{className:de,htmlFor:"agent-id",children:"Agent ID"}),e.jsx("input",{id:"agent-id",type:"text",value:n.id,onChange:N=>i({...n,id:N.target.value}),className:ve,placeholder:"kk-cc",disabled:m}),n.id&&!jt.test(n.id)&&e.jsx("div",{className:wt,children:"小写字母开头,只含 a-z 0-9 -,长度 2-32"}),n.id&&h.has(n.id)&&e.jsx("div",{className:wt,children:"该 id 已被占用(全局唯一)"})]}),e.jsxs("div",{children:[e.jsx("span",{className:de,children:"角色"}),e.jsxs("label",{className:"mr-4 inline-flex items-center gap-2",children:[e.jsx("input",{type:"radio",name:"role",checked:n.role==="dev",className:ye,onChange:()=>i({...n,role:"dev",pairWith:""}),disabled:m}),e.jsx("span",{className:"text-[13px] text-og-800",children:"Dev"})]}),e.jsxs("label",{className:"inline-flex items-center gap-2",title:$?"":"请先创建一个 Dev Agent",children:[e.jsx("input",{type:"radio",name:"role",checked:n.role==="qa",className:ye,onChange:()=>i({...n,role:"qa"}),disabled:m||!$}),e.jsx("span",{className:`text-[13px] ${$?"text-og-800":"text-og-400"}`,children:"QA"})]})]}),n.role==="qa"&&e.jsxs("div",{children:[e.jsx("label",{className:de,htmlFor:"pair-with",children:"配对 Dev Agent"}),e.jsxs("select",{id:"pair-with",value:n.pairWith,onChange:N=>i({...n,pairWith:N.target.value}),className:ve,disabled:m,children:[e.jsx("option",{value:"",children:"请选择"}),S.map(N=>e.jsxs("option",{value:N.id,children:[N.id," (dev, ",N.mode,")"]},N.id))]})]}),e.jsxs("div",{children:[e.jsx("span",{className:de,children:"运行模式"}),e.jsxs("label",{className:"mr-4 inline-flex items-center gap-2",children:[e.jsx("input",{type:"radio",name:"mode",checked:n.mode==="local",className:ye,onChange:()=>i({...n,mode:"local",hostname:"",user:""}),disabled:m}),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:n.mode==="remote",className:ye,onChange:()=>i({...n,mode:"remote"}),disabled:m}),e.jsx("span",{className:"text-[13px] text-og-800",children:"远程 (SSH)"})]})]}),n.mode==="remote"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("label",{className:de,htmlFor:"hostname",children:"Hostname"}),e.jsx("input",{id:"hostname",type:"text",value:n.hostname,onChange:N=>i({...n,hostname:N.target.value}),className:ve,placeholder:"worker-01",disabled:m}),e.jsx("div",{className:Ye,children:"端口/私钥/跳板机请配 ~/.ssh/config"})]}),e.jsxs("div",{children:[e.jsx("label",{className:de,htmlFor:"user",children:"User(可选)"}),e.jsx("input",{id:"user",type:"text",value:n.user,onChange:N=>i({...n,user:N.target.value}),className:ve,placeholder:"留空则读 ~/.ssh/config 的 User",disabled:m})]})]}),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:R,className:"text-[12px] text-accent transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",disabled:m||y||n.mode==="remote"&&!n.hostname,children:"↻ 重新探测"})]}),e.jsxs("label",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"radio",name:"runtime",checked:n.runtime==="claude-code",className:ye,onChange:()=>i({...n,runtime:"claude-code"}),disabled:m||(l?!l.runtimes["claude-code"].ok:!1)}),e.jsx("span",{className:"text-[13px] text-og-800",children:"Claude Code"}),e.jsx(se,{rt:"claude-code"})]}),e.jsxs("label",{className:"mt-1 flex items-center gap-2",children:[e.jsx("input",{type:"radio",name:"runtime",checked:n.runtime==="codex",className:ye,onChange:()=>i({...n,runtime:"codex"}),disabled:m||(l?!l.runtimes.codex.ok:!1)}),e.jsx("span",{className:"text-[13px] text-og-800",children:"Codex"}),e.jsx(se,{rt:"codex"})]}),e.jsx("div",{className:"mt-2",children:e.jsx(ee,{})}),e.jsx("div",{children:e.jsx(ie,{})})]}),e.jsxs("div",{children:[e.jsx("label",{className:de,htmlFor:"workdir",children:"Workdir(可选)"}),e.jsx("input",{id:"workdir",type:"text",value:n.workdir,onChange:N=>i({...n,workdir:N.target.value}),className:ve,placeholder:"留空时自动 clone 到 ~/.baxian/repos/<owner>/<repo>",disabled:m})]}),e.jsxs("div",{children:[e.jsx("label",{className:de,htmlFor:"model",children:"Model(可选)"}),e.jsx("input",{id:"model",type:"text",value:n.model,onChange:N=>i({...n,model:N.target.value}),className:ve,placeholder:n.runtime==="codex"?"例: o3 / gpt-4o(留空走 default)":"例: sonnet / opus / claude-sonnet-4-6(留空走 default)",disabled:m}),e.jsx("div",{className:Ye,children:"透传到 launch 命令的 --model 参数;留空跟随 CLI 默认。"})]}),e.jsxs("div",{children:[e.jsx("label",{className:de,htmlFor:"addDirs",children:"Additional Dirs(可选)"}),e.jsx("textarea",{id:"addDirs",value:n.addDirs,onChange:N=>i({...n,addDirs:N.target.value}),className:`${ve} font-mono text-[12px]`,rows:3,placeholder:`每行一个绝对路径,例:
3
- /Users/me/shared-libs
4
- /Users/me/extra-repo`,disabled:m}),e.jsx("div",{className:Ye,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:n.yolo,onChange:N=>i({...n,yolo:N.target.checked}),disabled:m}),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)中运行"}),"。"]})]})]})})]})})}let Me=null,xe=null,_e=null,Se=0;const Ze=new Set;function Ft(){Ze.forEach(t=>t())}async function tn(){const t=Se;try{const s=await _.projects.list();if(t!==Se)return;Me=s,_e=null}catch(s){if(t!==Se)return;_e=s instanceof Error?s.message:String(s)}finally{t===Se&&(xe=null,Ft())}}function et(){return xe||(xe=tn(),xe)}function sn(){Se+=1,Me=null,xe=null,_e=null,Ft()}typeof window<"u"&&window.addEventListener(Le,sn);async function nn(){const t=xe!==null;await et(),t&&await et()}function Bt(){const[,t]=o.useState(0);return o.useEffect(()=>{const s=()=>t(r=>r+1);return Ze.add(s),Me===null&&!xe&&et(),()=>{Ze.delete(s)}},[]),{projects:Me,error:_e,refresh:nn}}function rn(){const{openTask:t}=Te(),{projects:s,error:r,refresh:a}=Bt(),n=s??[],i=s!==null,[d,f]=o.useState(!1),[h,u]=o.useState(!1),[l,p]=o.useState({kind:"closed"}),{data:y,loaded:x,error:m}=Pt(),k=(m==null?void 0:m.message)??null,T=new Map((y??[]).map(R=>[R.id,R])),c=r??k,[E,g]=o.useState(!1),L=o.useRef(null),w=o.useRef(null),C=o.useId(),P=o.useId();return o.useEffect(()=>{if(!E)return;const R=$=>{var O,M;const b=$.target;b&&((O=w.current)!=null&&O.contains(b)||(M=L.current)!=null&&M.contains(b)||g(!1))},S=$=>{var b;$.key==="Escape"&&(g(!1),(b=L.current)==null||b.focus())};return document.addEventListener("mousedown",R),document.addEventListener("keydown",S),()=>{document.removeEventListener("mousedown",R),document.removeEventListener("keydown",S)}},[E]),e.jsxs("div",{children:[e.jsx("h1",{className:"sr-only",children:"Dashboard"}),e.jsxs("div",{className:"mb-6 flex flex-wrap items-center justify-end gap-2",children:[e.jsx("button",{onClick:()=>u(!0),disabled:n.length===0,"aria-describedby":n.length===0?"create-task-hint":void 0,className:"btn-primary",children:"+ 新建 Task"}),n.length===0&&e.jsx("span",{id:"create-task-hint",className:"self-center text-[12px] text-og-500",children:"请先创建项目"}),e.jsxs("div",{className:"relative",children:[e.jsx("button",{ref:L,id:P,type:"button",onClick:()=>g(R=>!R),"aria-haspopup":"menu","aria-expanded":E,"aria-controls":C,"aria-label":"更多操作",className:"flex h-8 w-8 items-center justify-center rounded text-og-500 transition-colors hover:bg-og-100 hover:text-og-1000",children:e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("circle",{cx:"12",cy:"12",r:"1"}),e.jsx("circle",{cx:"12",cy:"5",r:"1"}),e.jsx("circle",{cx:"12",cy:"19",r:"1"})]})}),E&&e.jsx("div",{ref:w,id:C,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:()=>{g(!1),f(!0)},className:"block w-full px-3 py-1.5 text-left text-[13px] text-og-800 hover:text-og-1000",children:"+ 新建项目"})})]})]}),c&&e.jsxs("div",{className:"mb-4 text-[13px] text-danger",children:["Error: ",c]}),i&&n.length===0&&!r&&e.jsx("div",{className:"rounded-lg border border-hairline bg-surface py-12 text-center text-[13px] text-og-500",children:'还没有项目。点击右上角"更多"菜单 → "新建项目"开始。'}),n.map(R=>e.jsx(on,{project:R,agentsById:T,agentsLoaded:x,agentsError:!!m,onAgentDeleted:a},R.id)),e.jsx(Zs,{open:d,onClose:()=>f(!1),onCreated:R=>{f(!1),a(),p({kind:"asking",projectId:R})}}),e.jsx(je,{open:l.kind==="asking",onClose:()=>p({kind:"closed"}),title:"项目已创建",size:"sm",footer:e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:()=>p({kind:"closed"}),className:"btn-secondary",children:"稍后再加"}),e.jsx("button",{type:"button",onClick:()=>{l.kind==="asking"&&p({kind:"addingAgent",projectId:l.projectId})},className:"btn-primary",children:"继续添加 Agent"})]}),children:e.jsx("p",{className:"text-[13px] text-og-700",children:"现在添加第一个 Agent,还是稍后再加?"})}),l.kind==="addingAgent"&&e.jsx(_t,{open:!0,projectId:l.projectId,onClose:()=>p({kind:"closed"}),onCreated:()=>{a()}}),e.jsx(rt,{open:h,onClose:()=>u(!1),onCreated:R=>t(R.id)})]})}function on({project:t,agentsById:s,agentsLoaded:r,agentsError:a,onAgentDeleted:n}){const{data:i,error:d}=$t(t.id),f=i??[],h=(d==null?void 0:d.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(Ee,{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(Ee,{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((u,l)=>e.jsx(Mt,{group:u,projectId:t.id,agentsById:s,agentsLoaded:r,agentsError:a,tasks:f,onDeleted:n,terminalMode:"embedded-full"},u.map(p=>p.id).join(":")||l))})]})}function Fe(t){const s=t.match(/^task-(\d+)$/);return s?parseInt(s[1],10):Number.NaN}function an(t,s){const r=Fe(t.id),a=Fe(s.id);return Number.isNaN(r)||Number.isNaN(a)?t.id.localeCompare(s.id):r-a}function cn(t,s){const r=(s.updatedAt??"").localeCompare(t.updatedAt??"");if(r!==0)return r;const a=Fe(t.id),n=Fe(s.id);return Number.isNaN(a)||Number.isNaN(n)?s.id.localeCompare(t.id):n-a}function kt(t,s){const[r,a]=o.useState(Qe);o.useEffect(()=>a(Qe),[s]);const n=t.slice(0,r),i=t.length>n.length;return{items:n,hasMore:i,loadMore:()=>a(f=>f+Qe),total:t.length}}function ln(t){const[s,r]=o.useState([]),[a,n]=o.useState(!1),[i,d]=o.useState(!1),[f,h]=o.useState(!1),[u,l]=o.useState(null),p=o.useRef(0),y=o.useRef(0),x=o.useCallback(m=>{const k=++p.current,T=m==="first"?0:y.current;d(!0),l(null),_.tasks.page(t,{category:"done",offset:T}).then(c=>{p.current===k&&(r(E=>m==="first"?c.tasks:[...E,...c.tasks]),n(c.hasMore),y.current=c.nextOffset,h(!0),d(!1))},c=>{p.current===k&&(l(c instanceof Error?c.message:String(c)),d(!1))})},[t]);return o.useEffect(()=>{p.current+=1,y.current=0,r([]),n(!1),h(!1),l(null),d(!1)},[t]),{items:s,hasMore:a,loading:i,loaded:f,error:u,load:x}}function dn({projectId:t,openTasks:s,onClose:r,className:a=""}){const n=o.useMemo(()=>s.filter(y=>Rt.has(y.status)).sort(cn),[s]),i=o.useMemo(()=>s.filter(y=>y.status==="pending").sort(an),[s]),d=kt(n,t),f=kt(i,t),h=ln(t),[u,l]=o.useState(!1);o.useEffect(()=>{l(!1)},[t]);const p=()=>{if(u){l(!1);return}l(!0),h.load("first")};return e.jsxs("aside",{"aria-label":"Task 面板",className:`flex flex-col rounded-lg border border-hairline bg-surface ${a}`,children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-hairline px-3 py-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:r,"aria-label":"关闭 Task 面板",className:"flex h-7 w-7 items-center justify-center rounded text-og-500 transition-colors hover:bg-og-100 hover:text-og-1000",children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),e.jsxs("div",{children:[e.jsx(St,{title:"IN PROGRESS",section:d,emptyHint:"暂无正在处理的任务"}),e.jsx(St,{title:"PENDING",section:f,emptyHint:"暂无待处理的任务"}),e.jsxs("div",{children:[e.jsxs("button",{type:"button",onClick:p,"aria-expanded":u,className:"flex w-full items-center justify-between px-3 py-2 text-left text-[11px] font-semibold 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:u?"收起":"查看"})]}),u&&e.jsx(un,{state:h})]})]})]})}function St({title:t,section:s,emptyHint:r}){return e.jsxs("section",{"aria-label":t,className:"border-b border-hairline",children:[e.jsxs("div",{className:"px-3 py-2 text-[11px] font-semibold 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:r}):e.jsxs("div",{className:"divide-y divide-hairline",children:[s.items.map(a=>e.jsx(zt,{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 un({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(r=>e.jsx(zt,{task:r},r.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 zt({task:t}){const{openTask:s}=Te(),r=t.phase==="spec"?t.specReviewRound??0:t.reviewRound;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:at(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"}),e.jsxs("span",{"aria-label":`Round ${r}`,className:"shrink-0 text-[11px] text-og-400",children:["R",r]}),e.jsx(Gs,{status:t.status})]})}const fn=[],Ut="baxian.taskPanel.open";function hn(){try{return localStorage.getItem(Ut)==="1"}catch{return!1}}function mn(){const{id:t}=Et(),s=Kt(),{show:r}=pe(),{openTask:a}=Te(),{refresh:n}=Bt(),[i,d]=o.useState(null),[f,h]=o.useState(null),[u,l]=o.useState(!1),[p,y]=o.useState(!1),[x,m]=o.useState(hn),[k,T]=o.useState(!1),[c,E]=o.useState(!1),[g,L]=o.useState(""),[w,C]=o.useState(!1),[P,R]=o.useState(null),S=o.useRef(null),$=o.useRef(null),b=o.useId(),O=o.useId(),M=o.useRef(0),{data:K,loaded:G,error:U}=Pt(),{data:Q,error:V}=$t(t),se=(U==null?void 0:U.message)??null,ee=(V==null?void 0:V.message)??null,ie=Q??fn,ne=new Map((K??[]).map(z=>[z.id,z])),N=f??se??ee,B=o.useCallback(async z=>{const j=++M.current;try{const D=await _.projects.get(z);if(j!==M.current)return;d(D),h(null)}catch(D){if(j!==M.current)return;h(D instanceof Error?D.message:String(D))}},[]);o.useEffect(()=>{t&&(d(null),h(null),B(t))},[t,B]),o.useEffect(()=>{if(!k)return;const z=D=>{var Y,re;const A=D.target;A&&((Y=$.current)!=null&&Y.contains(A)||(re=S.current)!=null&&re.contains(A)||T(!1))},j=D=>{var A;D.key==="Escape"&&(T(!1),(A=S.current)==null||A.focus())};return document.addEventListener("mousedown",z),document.addEventListener("keydown",j),()=>{document.removeEventListener("mousedown",z),document.removeEventListener("keydown",j)}},[k]),o.useEffect(()=>{c||(L(""),R(null))},[c]),o.useEffect(()=>{try{localStorage.setItem(Ut,x?"1":"0")}catch{}},[x]);const W=(i==null?void 0:i.agent.flat().length)??0,X=W===0,J=!!i&&g.trim()===i.id,ue=async()=>{if(!(!i||!J||w)){C(!0),R(null);try{await _.projects.delete(i.id),await n(),r({kind:"success",title:`项目 ${i.id} 已删除`}),E(!1),s("/")}catch(z){R(z instanceof Error?z.message:String(z))}finally{C(!1)}}};return i?e.jsxs("div",{children:[N&&e.jsxs("div",{className:"mb-4 text-[13px] text-danger",children:["Error: ",N]}),e.jsxs("div",{className:"mb-6 flex items-baseline gap-x-3",children:[e.jsx("h1",{className:"min-w-0 truncate font-display text-[17px] font-semibold tracking-tight text-og-1000",title:i.id,children:i.id}),e.jsx("span",{className:"hidden min-w-0 truncate font-mono text-[12px] text-og-500 sm:inline-block",title:i.repo,children:i.repo}),e.jsxs("div",{className:"ml-auto flex items-center gap-1 self-center",children:[!x&&e.jsx("button",{type:"button",onClick:()=>m(!0),"aria-label":"打开 Task 面板",className:"btn-ghost",children:"Tasks"}),e.jsxs("div",{className:"relative",children:[e.jsx("button",{ref:S,id:O,type:"button",onClick:()=>T(z=>!z),"aria-haspopup":"menu","aria-expanded":k,"aria-controls":b,"aria-label":`项目 ${i.id} 操作菜单`,className:"flex h-8 w-8 items-center justify-center rounded text-og-500 transition-colors hover:bg-og-100 hover:text-og-1000",children:e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("circle",{cx:"12",cy:"12",r:"1"}),e.jsx("circle",{cx:"12",cy:"5",r:"1"}),e.jsx("circle",{cx:"12",cy:"19",r:"1"})]})}),k&&e.jsxs("div",{ref:$,id:b,role:"menu","aria-labelledby":O,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:[e.jsx("button",{type:"button",role:"menuitem",onClick:()=>{T(!1),l(!0)},className:"block w-full px-3 py-1.5 text-left text-[13px] text-og-800 hover:bg-og-100 hover:text-og-1000",children:"添加 Agent"}),e.jsx("div",{role:"none",className:"my-1 border-t border-hairline"}),e.jsx("button",{type:"button",role:"menuitem",onClick:()=>{T(!1),E(!0)},disabled:!X,title:X?void 0:`请先删除项目下的 ${W} 个 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:"删除项目…"})]})]})]})]}),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.jsxs("div",{className:"mb-3 flex flex-wrap items-baseline justify-between gap-2",children:[e.jsx("h2",{className:"font-display text-[12px] font-semibold uppercase tracking-[0.06em] text-og-500",children:"Agents"}),e.jsx("button",{onClick:()=>y(!0),className:"btn-ghost",children:"+ 新建 Task"})]}),i.agent.flat().length===0?e.jsx("div",{className:"mb-8 rounded-lg border border-hairline bg-surface py-6 text-center text-[13px] text-og-500",children:"还没有 Agent,点击右上角菜单添加。"}):e.jsx("div",{className:"mb-8 space-y-5",children:i.agent.map((z,j)=>e.jsx(Mt,{group:z,projectId:i.id,agentsById:ne,agentsLoaded:G,agentsError:!!U,tasks:ie,onDeleted:()=>{B(i.id)},terminalMode:"embedded-full"},z.map(D=>D.id).join(":")||j))})]}),x&&e.jsx(dn,{projectId:i.id,openTasks:ie,onClose:()=>m(!1),className:"w-full lg:w-[340px] lg:shrink-0 xl:w-[380px]"})]}),e.jsx(_t,{open:u,projectId:i.id,onClose:()=>l(!1),onCreated:()=>{B(i.id)}}),e.jsx(rt,{open:p,projectId:i.id,onClose:()=>y(!1),onCreated:z=>a(z.id)}),e.jsx(je,{open:c,onClose:()=>{w||E(!1)},title:"删除项目",size:"sm",footer:e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:()=>E(!1),disabled:w,className:"btn-secondary",children:"取消"}),e.jsx("button",{type:"button",onClick:()=>void ue(),disabled:!J||w,className:"btn-secondary !text-danger hover:!bg-[#fef2f2] hover:!text-danger disabled:!text-og-300",children:w?"删除中…":"确认删除"})]}),children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-[13px] text-og-700",children:["将从 ",e.jsx("code",{className:"font-mono text-og-1000",children:"baxian.json"})," 中移除项目"," ",e.jsx("span",{className:"font-mono text-og-1000",children:i.id}),"。此操作不可撤销,且不会删除 Git 仓库本身。"]}),e.jsxs("p",{className:"text-[13px] text-og-700",children:["如需确认,请在下方输入项目 ID ",e.jsx("span",{className:"font-mono text-og-1000",children:i.id}),":"]}),e.jsx("input",{type:"text",value:g,onChange:z=>L(z.target.value),placeholder:i.id,autoComplete:"off",autoCorrect:"off",spellCheck:!1,disabled:w,"aria-label":"输入项目 ID 以确认删除",className:"w-full rounded border border-hairline bg-surface px-3 py-2 font-mono text-[13px] text-og-1000 focus:border-accent focus:outline-none"}),P&&e.jsx("div",{className:"rounded-md border border-[#fecaca] bg-[#fef2f2] px-3 py-2 text-[12px] text-danger",children:P})]})})]}):f?e.jsxs("div",{className:"text-[13px] text-danger",children:["Error: ",f]}):e.jsx("div",{className:"text-[13px] text-og-500",children:"Loading…"})}function xn(){const{agentId:t}=Et();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",children:t})]}),e.jsx("div",{className:"min-h-0 flex-1",children:e.jsx(ke,{agentId:t,mode:"full",interactive:!0,arrowKeys:!0})})]}):e.jsx("div",{className:"text-[13px] text-danger",children:"No agent specified"})}function pn(){const[t,s]=o.useState(!1);return e.jsx("button",{type:"button",onClick:()=>s(r=>!r),"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 bn(){const{phase:t,count:s,error:r,triggerRestart:a}=Ue();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:["❌ 重启失败:",r]}),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 gn(){const s=!Jt().pathname.startsWith("/terminal/");return e.jsxs("div",{className:"flex h-dvh flex-col bg-page",children:[e.jsx("nav",{className:"flex h-12 flex-none items-center border-b border-hairline bg-surface px-3 sm:px-6",children:e.jsxs(Ee,{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(bn,{}),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(Yt,{children:[e.jsx(We,{path:"/",element:e.jsx(rn,{})}),e.jsx(We,{path:"/project/:id",element:e.jsx(mn,{})}),e.jsx(We,{path:"/terminal/:agentId",element:e.jsx(xn,{})})]}),s&&e.jsx("footer",{className:"mt-auto flex justify-center pb-4 pt-24",children:e.jsx(pn,{})})]})]})}function vn(){return e.jsx(Vt,{children:e.jsx(gn,{})})}function yn({children:t}){const[s,r]=o.useState({kind:"probing"}),a=o.useRef(s);o.useEffect(()=>{a.current=s},[s]);const n=o.useCallback(async()=>{r({kind:"probing"});try{await _.config.get(),r({kind:"authorized"})}catch(i){if(i instanceof Re&&i.status===401){r({kind:"unauthorized"});return}const d=i instanceof Error?i.message:"无法连接服务器";r({kind:"error",message:d})}},[]);return o.useEffect(()=>{n()},[n]),o.useEffect(()=>{const i=()=>{a.current.kind!=="probing"&&r({kind:"unauthorized",message:"登录已失效,请重新输入令牌"})};return window.addEventListener(Le,i),()=>window.removeEventListener(Le,i)},[]),s.kind==="authorized"?e.jsx(e.Fragment,{children:t}):s.kind==="error"?e.jsxs(tt,{title:"无法连接服务器",children:[e.jsx("p",{className:"text-[13px] text-og-600",children:s.message}),e.jsx("button",{type:"button",onClick:()=>{n()},className:"btn-primary mt-4 w-full",children:"重试"})]}):s.kind==="probing"?e.jsx(tt,{title:"加载中",children:e.jsx("p",{className:"text-[13px] text-og-500",children:"正在检查登录状态…"})}):e.jsx(jn,{message:s.message,onSubmit:async i=>{Xt(i);try{await _.config.get(),r({kind:"authorized"})}catch(d){if(Zt(),d instanceof Re&&d.status===401){r({kind:"unauthorized",message:"令牌无效,请重试"});return}const f=d instanceof Error?d.message:"登录失败";r({kind:"error",message:f})}}})}function tt({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 jn({message:t,onSubmit:s}){const[r,a]=o.useState(""),[n,i]=o.useState(!1),[d,f]=o.useState(void 0),h=async l=>{l.preventDefault();const p=r.trim();if(!p){f("请输入访问令牌");return}f(void 0),i(!0);try{await s(p)}finally{i(!1)}},u=d??t;return e.jsxs(tt,{title:"登录 baxian",children:[e.jsx("p",{className:"mb-4 text-[13px] text-og-600",children:"服务器开启了访问鉴权,请输入访问令牌继续。"}),e.jsxs("form",{onSubmit:l=>{h(l)},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:r,onChange:l=>a(l.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:n}),u&&e.jsx("p",{role:"alert",className:"mt-2 text-[12px] text-danger",children:u}),e.jsx("button",{type:"submit",disabled:n,className:"btn-primary mt-4 w-full",children:n?"登录中…":"登录"})]})]})}qt.createRoot(document.getElementById("root")).render(e.jsx(o.StrictMode,{children:e.jsx(ds,{children:e.jsx(os,{children:e.jsx(yn,{children:e.jsx(Qs,{children:e.jsx(vn,{})})})})})}));