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