baxian 2.0.0 → 2.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -7
- package/README.zh-CN.md +5 -7
- package/dist/agent/bootstrap.d.ts.map +1 -1
- package/dist/agent/bootstrap.js +2 -4
- package/dist/agent/bootstrap.js.map +1 -1
- package/dist/agent/branch.d.ts +0 -13
- package/dist/agent/branch.d.ts.map +1 -1
- package/dist/agent/branch.js +1 -71
- package/dist/agent/branch.js.map +1 -1
- package/dist/agent/dispatch-reconciler.d.ts.map +1 -1
- package/dist/agent/dispatch-reconciler.js +19 -14
- package/dist/agent/dispatch-reconciler.js.map +1 -1
- package/dist/agent/manager.d.ts +90 -134
- package/dist/agent/manager.d.ts.map +1 -1
- package/dist/agent/manager.js +1154 -2265
- package/dist/agent/manager.js.map +1 -1
- package/dist/agent/net-exec.d.ts +3 -0
- package/dist/agent/net-exec.d.ts.map +1 -1
- package/dist/agent/net-exec.js +6 -0
- package/dist/agent/net-exec.js.map +1 -1
- package/dist/agent/pane-streamer-manager.d.ts +6 -6
- package/dist/agent/pane-streamer-manager.d.ts.map +1 -1
- package/dist/agent/pane-streamer-manager.js.map +1 -1
- package/dist/agent/pane-streamer.d.ts +6 -3
- package/dist/agent/pane-streamer.d.ts.map +1 -1
- package/dist/agent/pane-streamer.js +70 -40
- package/dist/agent/pane-streamer.js.map +1 -1
- package/dist/agent/phase-signal-watcher.d.ts +7 -2
- package/dist/agent/phase-signal-watcher.d.ts.map +1 -1
- package/dist/agent/phase-signal-watcher.js +90 -32
- package/dist/agent/phase-signal-watcher.js.map +1 -1
- package/dist/agent/phase-signal.d.ts +19 -38
- package/dist/agent/phase-signal.d.ts.map +1 -1
- package/dist/agent/phase-signal.js +54 -88
- package/dist/agent/phase-signal.js.map +1 -1
- package/dist/agent/preflight.d.ts +0 -1
- package/dist/agent/preflight.d.ts.map +1 -1
- package/dist/agent/preflight.js +8 -15
- package/dist/agent/preflight.js.map +1 -1
- package/dist/agent/prompt.d.ts +1 -35
- package/dist/agent/prompt.d.ts.map +1 -1
- package/dist/agent/prompt.js +22 -162
- package/dist/agent/prompt.js.map +1 -1
- package/dist/agent/repo-store.d.ts +4 -1
- package/dist/agent/repo-store.d.ts.map +1 -1
- package/dist/agent/repo-store.js +33 -11
- package/dist/agent/repo-store.js.map +1 -1
- package/dist/agent/root-agent-runtime.d.ts +80 -0
- package/dist/agent/root-agent-runtime.d.ts.map +1 -0
- package/dist/agent/root-agent-runtime.js +637 -0
- package/dist/agent/root-agent-runtime.js.map +1 -0
- package/dist/agent/root-recovery-coordinator.d.ts +124 -0
- package/dist/agent/root-recovery-coordinator.d.ts.map +1 -0
- package/dist/agent/root-recovery-coordinator.js +1557 -0
- package/dist/agent/root-recovery-coordinator.js.map +1 -0
- package/dist/agent/runner.d.ts +1 -0
- package/dist/agent/runner.d.ts.map +1 -1
- package/dist/agent/runner.js +103 -7
- package/dist/agent/runner.js.map +1 -1
- package/dist/agent/tmux-probe-poller.d.ts +1 -0
- package/dist/agent/tmux-probe-poller.d.ts.map +1 -1
- package/dist/agent/tmux-probe-poller.js +16 -10
- package/dist/agent/tmux-probe-poller.js.map +1 -1
- package/dist/agent/tmux.d.ts +3 -0
- package/dist/agent/tmux.d.ts.map +1 -1
- package/dist/agent/tmux.js +11 -5
- package/dist/agent/tmux.js.map +1 -1
- package/dist/agent/vt-visible-text.d.ts +42 -0
- package/dist/agent/vt-visible-text.d.ts.map +1 -0
- package/dist/agent/vt-visible-text.js +482 -0
- package/dist/agent/vt-visible-text.js.map +1 -0
- package/dist/api/agents.d.ts.map +1 -1
- package/dist/api/agents.js +42 -1
- package/dist/api/agents.js.map +1 -1
- package/dist/api/config.d.ts.map +1 -1
- package/dist/api/config.js +83 -9
- package/dist/api/config.js.map +1 -1
- package/dist/api/hosts.d.ts.map +1 -1
- package/dist/api/hosts.js +68 -13
- package/dist/api/hosts.js.map +1 -1
- package/dist/api/platform-guard.js +2 -2
- package/dist/api/platform-guard.js.map +1 -1
- package/dist/api/projects.d.ts.map +1 -1
- package/dist/api/projects.js +621 -325
- package/dist/api/projects.js.map +1 -1
- package/dist/api/tasks.d.ts.map +1 -1
- package/dist/api/tasks.js +15 -39
- package/dist/api/tasks.js.map +1 -1
- package/dist/app.d.ts +2 -0
- package/dist/app.d.ts.map +1 -1
- package/dist/app.js +6 -0
- package/dist/app.js.map +1 -1
- package/dist/cli.d.ts +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +49 -7
- package/dist/cli.js.map +1 -1
- package/dist/config/loader.d.ts +5 -1
- package/dist/config/loader.d.ts.map +1 -1
- package/dist/config/loader.js +57 -24
- package/dist/config/loader.js.map +1 -1
- package/dist/config/normalizer.d.ts.map +1 -1
- package/dist/config/normalizer.js +18 -0
- package/dist/config/normalizer.js.map +1 -1
- package/dist/config/validator.d.ts +7 -4
- package/dist/config/validator.d.ts.map +1 -1
- package/dist/config/validator.js +251 -96
- package/dist/config/validator.js.map +1 -1
- package/dist/event/handlers.d.ts.map +1 -1
- package/dist/event/handlers.js +359 -229
- package/dist/event/handlers.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +45 -5
- package/dist/index.js.map +1 -1
- package/dist/platform/command-renderer.d.ts +6 -0
- package/dist/platform/command-renderer.d.ts.map +1 -1
- package/dist/platform/command-renderer.js +20 -0
- package/dist/platform/command-renderer.js.map +1 -1
- package/dist/platform/driver-host.d.ts.map +1 -1
- package/dist/platform/driver-host.js +3 -1
- package/dist/platform/driver-host.js.map +1 -1
- package/dist/platform/driver-spec.d.ts.map +1 -1
- package/dist/platform/driver-spec.js +32 -4
- package/dist/platform/driver-spec.js.map +1 -1
- package/dist/platform/git-driver.d.ts +2 -0
- package/dist/platform/git-driver.d.ts.map +1 -1
- package/dist/platform/git-driver.js +9 -3
- package/dist/platform/git-driver.js.map +1 -1
- package/dist/platform/platform-poller.d.ts +0 -1
- package/dist/platform/platform-poller.d.ts.map +1 -1
- package/dist/platform/platform-poller.js +1 -11
- package/dist/platform/platform-poller.js.map +1 -1
- package/dist/platform/plugins/github/driver.json +5 -0
- package/dist/platform/plugins/github/skills/baxian-cli-gh/SKILL.md +20 -14
- package/dist/platform/startup.d.ts.map +1 -1
- package/dist/platform/startup.js +5 -5
- package/dist/platform/startup.js.map +1 -1
- package/dist/platform/types.d.ts +1 -0
- package/dist/platform/types.d.ts.map +1 -1
- package/dist/platform/types.js +3 -3
- package/dist/platform/types.js.map +1 -1
- package/dist/shared/constants.d.ts +8 -7
- package/dist/shared/constants.d.ts.map +1 -1
- package/dist/shared/constants.js +6 -28
- package/dist/shared/constants.js.map +1 -1
- package/dist/shared/types.d.ts +52 -125
- package/dist/shared/types.d.ts.map +1 -1
- package/dist/shared/types.js +24 -5
- package/dist/shared/types.js.map +1 -1
- package/dist/skills/baxian-pr-feedback/SKILL.md +6 -6
- package/dist/skills/baxian-pr-recheck/SKILL.md +6 -0
- package/dist/skills/baxian-pr-review/SKILL.md +6 -0
- package/dist/skills/baxian-signals/SKILL.md +17 -28
- package/dist/skills/baxian-task-check/SKILL.md +13 -14
- package/dist/state/init.d.ts.map +1 -1
- package/dist/state/init.js +1 -0
- package/dist/state/init.js.map +1 -1
- package/dist/state/lock.d.ts +6 -0
- package/dist/state/lock.d.ts.map +1 -1
- package/dist/state/lock.js +8 -0
- package/dist/state/lock.js.map +1 -1
- package/dist/state/root-recovery-store.d.ts +107 -0
- package/dist/state/root-recovery-store.d.ts.map +1 -0
- package/dist/state/root-recovery-store.js +400 -0
- package/dist/state/root-recovery-store.js.map +1 -0
- package/dist/state/snapshot.d.ts.map +1 -1
- package/dist/state/snapshot.js +5 -2
- package/dist/state/snapshot.js.map +1 -1
- package/dist/state/task-store.d.ts.map +1 -1
- package/dist/state/task-store.js +57 -137
- package/dist/state/task-store.js.map +1 -1
- package/dist/terminal/attach.d.ts +3 -3
- package/dist/terminal/attach.d.ts.map +1 -1
- package/dist/terminal/attach.js.map +1 -1
- package/dist/terminal/stream-ws.d.ts.map +1 -1
- package/dist/terminal/stream-ws.js.map +1 -1
- package/dist/web/assets/index-BKiM0MSM.js +15 -0
- package/dist/web/assets/index-BS2adAfI.css +1 -0
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/agent/review-transport.d.ts +0 -92
- package/dist/agent/review-transport.d.ts.map +0 -1
- package/dist/agent/review-transport.js +0 -512
- package/dist/agent/review-transport.js.map +0 -1
- package/dist/event/server-handlers.d.ts +0 -4
- package/dist/event/server-handlers.d.ts.map +0 -1
- package/dist/event/server-handlers.js +0 -1221
- package/dist/event/server-handlers.js.map +0 -1
- package/dist/skills/baxian-research/SKILL.md +0 -28
- package/dist/skills/baxian-server-feedback/SKILL.md +0 -40
- package/dist/skills/baxian-server-feedback/agents/openai.yaml +0 -2
- package/dist/skills/baxian-server-review/SKILL.md +0 -58
- package/dist/skills/baxian-server-review/agents/openai.yaml +0 -2
- package/dist/state/review-store.d.ts +0 -33
- package/dist/state/review-store.d.ts.map +0 -1
- package/dist/state/review-store.js +0 -272
- package/dist/state/review-store.js.map +0 -1
- package/dist/web/assets/index-BPv6vv3U.css +0 -1
- package/dist/web/assets/index-BXfgaFNm.js +0 -18
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
var Bs=Object.defineProperty;var Ms=(e,n,s)=>n in e?Bs(e,n,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[n]=s;var ae=(e,n,s)=>Ms(e,typeof n!="symbol"?n+"":n,s);import{r as o,j as t,a as Os,c as Hs}from"./react-BFCkCmbU.js";import{x as _s,a as Us}from"./xterm-D5X2JljJ.js";import{L as _e,u as Te,a as Ze,b as Gt,B as qs,R as Ws,c as Me}from"./router-BgSDZqI0.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))r(a);new MutationObserver(a=>{for(const i of a)if(i.type==="childList")for(const l of i.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&r(l)}).observe(document,{childList:!0,subtree:!0});function s(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerPolicy&&(i.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?i.credentials="include":a.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(a){if(a.ep)return;a.ep=!0;const i=s(a);fetch(a.href,i)}})();function Se({className:e,...n}){return t.jsx("button",{type:"button",role:"menuitem",className:`block w-full px-3 py-1.5 text-left text-sm text-og-1000 hover:bg-og-50 disabled:opacity-50 disabled:cursor-not-allowed ${e??""}`,...n})}function Qt({ariaLabel:e,children:n,placement:s="down",autoFocusFirstItem:r=!1,menuClassName:a="min-w-[140px]",className:i,disabled:l=!1,triggerRef:d}){const[u,m]=o.useState(!1),h=o.useRef(null),x=o.useRef(null),c=o.useId(),g=o.useId();return o.useEffect(()=>{if(!u)return;const v=w=>{var A,R;const S=w.target;S&&((A=x.current)!=null&&A.contains(S)||(R=h.current)!=null&&R.contains(S)||m(!1))},y=w=>{var S;w.key==="Escape"&&(m(!1),(S=h.current)==null||S.focus())};return document.addEventListener("mousedown",v),document.addEventListener("keydown",y),()=>{document.removeEventListener("mousedown",v),document.removeEventListener("keydown",y)}},[u]),o.useEffect(()=>{var y;if(!u||!r)return;const v=(y=x.current)==null?void 0:y.querySelector('[role="menuitem"]:not([disabled])');v==null||v.focus()},[u,r]),t.jsxs("div",{className:`relative ${i??""}`,children:[t.jsx("button",{ref:v=>{h.current=v,d&&(d.current=v)},id:g,type:"button",onClick:()=>m(v=>!v),disabled:l,"aria-haspopup":"menu","aria-expanded":u,"aria-controls":u?c:void 0,"aria-label":e,className:"flex h-8 w-8 items-center justify-center rounded text-og-500 transition-colors hover:bg-og-50 hover:text-og-1000 disabled:cursor-not-allowed disabled:opacity-50",children:t.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:[t.jsx("circle",{cx:"12",cy:"12",r:"1"}),t.jsx("circle",{cx:"12",cy:"5",r:"1"}),t.jsx("circle",{cx:"12",cy:"19",r:"1"})]})}),u&&t.jsx("div",{ref:x,id:c,role:"menu","aria-labelledby":g,className:`absolute right-0 z-10 rounded-md border border-hairline bg-surface py-1 shadow-md ${s==="up"?"bottom-full mb-1":"top-full mt-1"} ${a}`,children:n(()=>{var v;m(!1),(v=h.current)==null||v.focus()})})]})}function Ce(e){return e==="research"||e==="spec"}const Gs={"claude-code":"Claude Code",codex:"Codex",opencode:"OpenCode",qodercli:"Qoder CLI"},Qs={"claude-code":"--permission-mode bypassPermissions",codex:"--dangerously-bypass-approvals-and-sandbox",opencode:"--auto",qodercli:"--dangerously-skip-permissions"};function Bn(e,n){const s=[e?Gs[e]:null,n||null].filter(Boolean);return s.length>0?s.join(" · "):null}function Mn(e,n,s){const r=Bn(n,s);return r?`${e} (${r})`:e}const Ft=new Set(["merged","done","failed","cancelled"]),On=new Set(["in_progress","review","fixing","spec-ready","approved","merge-ready","ready","max_rounds"]),kt=20,vt=5*1024*1024,rt=4,Hn=600*1e3;function _n(e){if(!e)return null;try{const n=new URL(e);return n.protocol==="http:"||n.protocol==="https:"?n.href:null}catch{return null}}const zs=1536,Ks=1872,Un=192,qn=208,qe="/api",zt="baxian.token",mt="baxian:unauthorized";function Kt(){try{return typeof localStorage<"u"?localStorage.getItem(zt):null}catch{return null}}function Vs(e){try{localStorage.setItem(zt,e)}catch(n){console.error("Failed to save auth token to localStorage",n)}}function Ys(){try{localStorage.removeItem(zt)}catch(e){console.error("Failed to clear auth token from localStorage",e)}}function Ee(e){const n=Kt();return{...e??{},...n?{Authorization:`Bearer ${n}`}:{}}}class De extends Error{constructor(n,s,r){super(s),this.status=n,this.details=r,this.name="ApiError"}}function Js(e){if(!Array.isArray(e))return;const n=e.filter(s=>typeof s=="object"&&s!==null&&typeof s.path=="string"&&typeof s.message=="string");return n.length>0?n:void 0}async function Ie(e){const n=await e.text();let s=n||`HTTP ${e.status}`,r;try{const a=JSON.parse(n);typeof a.error=="string"&&(s=a.error),r=Js(a.details)}catch{}throw r!==void 0&&(s=`${s}
|
|
2
|
-
${r.map(a=>`${a.path}: ${a.message}`).join(`
|
|
3
|
-
`)}`),e.status===401&&typeof window<"u"&&window.dispatchEvent(new CustomEvent(mt)),new De(e.status,s,r)}async function ke(e){const n=await fetch(`${qe}${e}`,{headers:Ee()});return n.ok||await Ie(n),n.json()}async function Xs(){const e=await fetch("/health");return e.ok||await Ie(e),e.json()}async function le(e,n,s){const r=n!==void 0,a=await fetch(`${qe}${e}`,{method:"POST",headers:r?Ee({"Content-Type":"application/json"}):Ee(),body:r?JSON.stringify(n):void 0,signal:s==null?void 0:s.signal});return a.ok||await Ie(a),a.json()}async function Nt(e,n,s){const r=await fetch(`${qe}${e}`,{method:"PATCH",headers:Ee({"Content-Type":"application/json"}),body:n?JSON.stringify(n):void 0,signal:s==null?void 0:s.signal});if(r.ok||await Ie(r),r.status===204)return;const a=await r.text();if(a)return JSON.parse(a)}async function Zs(e,n){const s=await fetch(`${qe}${e}`,{method:"PUT",headers:Ee({"Content-Type":"application/json"}),body:JSON.stringify(n??null)});if(s.ok||await Ie(s),s.status===204)return;const r=await s.text();if(r)return JSON.parse(r)}async function Ge(e){const n=await fetch(`${qe}${e}`,{method:"DELETE",headers:Ee()});if(n.ok||await Ie(n),n.status===204)return;const s=await n.text();if(s)return JSON.parse(s)}const Y=encodeURIComponent;function Bt(e){return new Promise((n,s)=>{const r=new FileReader;r.onerror=()=>s(r.error??new Error("file read failed")),r.onload=()=>{const a=r.result;if(typeof a!="string"){s(new Error("unexpected FileReader result"));return}const i=a.indexOf(",");n(i>=0?a.slice(i+1):a)},r.readAsDataURL(e)})}const F={agents:{list:()=>ke("/agents"),get:e=>ke(`/agents/${Y(e)}`),stop:e=>Ge(`/agents/${Y(e)}/session`),compact:e=>le(`/agents/${Y(e)}/compact`),clear:e=>le(`/agents/${Y(e)}/clear`),probe:(e,n={},s)=>le("/agents/probe",{mode:e,host:n.host,hostId:n.hostId},s),installTmux:(e,n={})=>le("/agents/install-tmux",{mode:e,host:n.host,hostId:n.hostId}),uploadImage:async(e,n)=>le(`/agents/${Y(e)}/images`,{dataBase64:await Bt(n)}),setPet:(e,n)=>Zs(`/agents/${Y(e)}/pet`,{petId:n})},pets:{list:()=>ke("/pets"),create:async(e,n)=>le("/pets",{petJson:e,spritesheetBase64:await Bt(n)}),remove:e=>Ge(`/pets/${Y(e)}`),fetchSpritesheet:async e=>{const n=await fetch(`${qe}/pets/${Y(e)}/spritesheet`,{headers:Ee()});return n.ok||await Ie(n),n.blob()}},tasks:{list:async e=>{const n=new Map;for(const s of["active","pending"]){let r=0;for(;;){const a=await F.tasks.page(e,{category:s,offset:r});for(const i of a.tasks)n.set(i.id,i);if(!a.hasMore||a.tasks.length===0)break;r=a.nextOffset}}return[...n.values()]},page:(e,n={})=>{const s=[`projectId=${Y(e)}`];return n.category&&s.push(`category=${n.category}`),s.push(`offset=${n.offset??0}`),ke(`/tasks?${s.join("&")}`)},get:e=>ke(`/tasks/${Y(e)}`),create:e=>le("/tasks",e),update:(e,n)=>Nt(`/tasks/${Y(e)}`,n),retry:e=>le(`/tasks/${Y(e)}/retry`),review:e=>le(`/tasks/${Y(e)}/review`),complete:e=>le(`/tasks/${Y(e)}/complete`),continue:e=>le(`/tasks/${Y(e)}/continue`),spec:(e,n)=>le(`/tasks/${Y(e)}/spec`,n),code:(e,n)=>le(`/tasks/${Y(e)}/code`,n),reviews:e=>ke(`/tasks/${Y(e)}/reviews`),interdiff:(e,n)=>ke(`/tasks/${Y(e)}/reviews/code/${n}/interdiff`),prReview:e=>ke(`/tasks/${Y(e)}/pr-review`),dispatch:(e,n)=>le(`/tasks/${Y(e)}/dispatch`,n)},projects:{list:()=>ke("/projects"),get:e=>ke(`/projects/${Y(e)}`),create:e=>le("/projects",e),delete:e=>Ge(`/projects/${Y(e)}`),addAgent:(e,n)=>le(`/projects/${Y(e)}/agents`,n),deleteAgent:(e,n)=>Ge(`/projects/${Y(e)}/agents/${Y(n)}`),resumeAgent:(e,n)=>le(`/projects/${Y(e)}/agents/${Y(n)}/resume`),restartRepl:(e,n)=>le(`/projects/${Y(e)}/agents/${Y(n)}/restart-repl`),retryAgent:(e,n)=>le(`/projects/${Y(e)}/agents/${Y(n)}/retry`),bootstrap:e=>le(`/projects/${Y(e)}/bootstrap`)},hosts:{list:()=>ke("/hosts"),create:e=>le("/hosts",e),update:(e,n)=>Nt(`/hosts/${Y(e)}`,n),delete:e=>Ge(`/hosts/${Y(e)}`),check:e=>le("/hosts/check",e)},config:{get:()=>ke("/config"),patch:e=>Nt("/config",e)},health:{get:Xs},server:{restart:()=>le("/restart")}};function Vt(e){return{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":!0,...e}}function er(e){return t.jsxs("svg",{...Vt(e),children:[t.jsx("path",{d:"M21.801 10A10 10 0 1 1 17 3.335"}),t.jsx("path",{d:"m9 11 3 3L22 4"})]})}function tr(e){return t.jsxs("svg",{...Vt(e),children:[t.jsx("path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"}),t.jsx("path",{d:"M12 9v4"}),t.jsx("path",{d:"M12 17h.01"})]})}function nr(e){return t.jsxs("svg",{...Vt(e),children:[t.jsx("circle",{cx:"12",cy:"12",r:"10"}),t.jsx("path",{d:"m15 9-6 6"}),t.jsx("path",{d:"m9 9 6 6"})]})}const Wn={common:{cancel:"Cancel",confirm:"Confirm",close:"Close",delete:"Delete",deleting:"Deleting…",edit:"Edit",retry:"Retry",retrying:"Retrying…",back:"← Back",backText:"Back",loading:"Loading…",loadFailed:e=>`Failed to load: ${e}`,idFormatError:"Must start with a lowercase letter; only a-z, 0-9, and - allowed; length 2–32",create:"Create",creating:"Creating…",save:"Save",saving:"Saving…",oneClickInstall:"Install with one click",installing:"Installing…",installingTmuxNotice:"Installing tmux — this can take a few minutes, please keep this window open…"},status:{pending:"Pending",in_progress:"In progress",review:"In review",fixing:"Fixing","spec-ready":"Spec ready",approved:"Approved","merge-ready":"Awaiting confirm",ready:"Awaiting confirm",merged:"Merged",done:"Done",failed:"Failed",max_rounds:"Max rounds reached",cancelled:"Cancelled"},notification:{taskDone:e=>`Task completed: ${e}`,bodyProject:e=>`Project: ${e}`,bodyTask:e=>`Task: ${e}`,bodyStatus:e=>`Status: ${e}`},dashboard:{moreActions:"More actions",newProject:"New project",manageHosts:"Manage hosts",newTask:"+ New task",createProjectFirst:"Create a project first",emptyProjects:'No projects yet. Open the top-right menu and choose "New project" to start.',noAgentsYet:"No agents yet. Open Details to add one.",detailsLink:"Details →",detailsAriaLabel:e=>`Details — ${e}`,tasksLoadFailed:e=>`Failed to load tasks: ${e}`,projectCreatedTitle:"Project created",addAgentNowOrLater:"Add the first agent now, or later?",later:"Later",continueAddingAgent:"Continue adding an agent"},nav:{toggleToIcon:"Switch to logo icon",toggleToText:"Switch to logo text"},agents:{runtimeStatus:{unknown:"Unknown",idle:"Idle",pending:"Awaiting human",working:"Working",waiting:"Waiting",error:"Error"},sessionStatus:{absent:"No session",unreachable:"Host unreachable"},bootstrappingBadge:"Starting",agentStatusLoading:"Agent status loading",bootstrappingTerminalDisabled:"Agent is starting",bootstrappingNotice:"Agent is starting; the terminal will refresh automatically once it is available.",terminalNeedsRestart:"Available after restarting the baxian server",pendingRestartNotice:"Takes effect after restarting the baxian server",heldBadge:"Held",heldDefaultReason:"Needs human attention",staleTitle:e=>e?`Data may be stale — last observed at ${e}`:"Data may be stale",awaitingHumanIntervention:"Awaiting human intervention",openTerminalPrefix:"Open the ",openTerminalSuffix:" to resolve it.",terminal:"Terminal",needInputBadge:"Awaiting reply",needInputTitle:e=>`Agent is waiting for your reply (${e})`,needInputNoticeTitle:"Agent is waiting for your reply",needInputPrefix:"It has a question — open the ",needInputSuffix:" to reply.",activateTerminal:e=>`Activate ${e} terminal`,actionsMenu:e=>`Agent ${e} actions menu`,taskLabel:"Task: ",stop:"Stop",stopping:"Stopping…",resume:"Resume",resuming:"Resuming…",resumeConfirmTitle:e=>`Resume agent ${e}?`,resumeGreetingBody:"The greeting capability check failed; baxian will re-run the handshake (restarts the REPL if the session is alive, or rebuilds it if lost). The hold only clears once the handshake passes.",resumeDefaultBody:"baxian will clear the awaiting_human state; the agent becomes usable again.",resumeGreetingButtonTitle:"Re-run the greeting handshake to resume (restarts the REPL if the session is alive, rebuilds it if lost; greeting_failed cannot be cleared by state alone).",resumeDefaultButtonTitle:"Clear the awaiting_human state so the agent becomes usable again.",regreetingStartedTitle:e=>`Agent ${e} is re-running the greeting handshake`,regreetingStartedBody:"Once the handshake passes, the hold clears automatically on the next refresh; if it keeps failing, fix the runtime per the hint and try again.",resumedTitle:e=>`Agent ${e} resumed`,resumedReleasedBody:"The previous task was released; the agent can take on new work.",resumedKeptBody:"The binding was kept (the previous task is still active).",resumeFailedTitle:"Resume failed",compact:"Compact context",compacting:"Compacting…",compactMenuItemTitle:"Send /compact to the agent runtime to compact context",compactSentTitle:e=>`/compact sent to agent ${e}`,compactFailedTitle:"Failed to compact context",clear:"Clear context",clearing:"Clearing…",clearMenuItemTitle:"Send /clear to the agent runtime to clear context",clearConfirmTitle:e=>`Clear the context for agent ${e}?`,clearConfirmBody:"This sends /clear; the entire session context cannot be recovered.",clearConfirmLabel:"Clear",clearSentTitle:e=>`/clear sent to agent ${e}`,clearFailedTitle:"Failed to clear context",deleteConfirmTitle:e=>`Delete agent ${e}?`,deleteConfirmBody:"This action cannot be undone.",deletedWithPairTitle:e=>`Deleted agent ${e}`,deletedWithPairBody:e=>`The paired QA agent ${e} was removed as well.`,deletedTitle:e=>`Agent ${e} deleted`,agentPetMenuItemTitle:"Configure Agent Pet (shows an animated pet in place of the status badge).",callReview:"Call review",callingReview:"Calling review…",callReviewMenuItemTitle:e=>`Have the QA agent run a review round on task ${e} right now (git review mode requires an existing PR).`,confirmReReviewTitle:"Start a QA re-review?",confirmReReviewBody:e=>`QA agent will immediately start a new review round for task ${e}. If a previous delivery is marked uncertain, continue only after verifying the QA pane did not receive it; this action confirms non-delivery.`,confirmReReviewLabel:"Start re-review",reReviewStarted:e=>`QA re-review started (round ${e})`,reReviewStartFailed:"Failed to start review",retryBootstrap:"Retry bootstrap",retryBootstrapSucceededTitle:"Retry bootstrap succeeded",retryBootstrapSucceededBody:"Agent status will update on the next refresh.",retryBootstrapStillFailingTitle:"Retry bootstrap still failed",retryBootstrapStillFailingBody:"Check the latest reason on the red error card, fix it per the hint, and try again.",retryBootstrapFailedTitle:"Retry bootstrap failed",round:e=>`Round ${e}`,noActiveTask:"No active task",noActiveTaskAriaLabel:e=>`${e} no active task`,unassigned:"Unassigned",start:"Start",starting:"Starting…",startFailed:"Failed to start",taskHandedTo:(e,n)=>`Task ${e} handed to ${n}`,handToAndStart:e=>`Hand to ${e} and start immediately`,agentUnavailable:e=>`Agent ${e} is currently unavailable`},settings:{entry:"Settings",title:"Settings",language:"Language",languageSaveFailed:e=>`Failed to save language: ${e}`,taskNotifications:"Task completion notifications",taskNotificationsDenied:"Notifications are blocked by the browser",taskNotificationsHint:"Notify via the browser when a task reaches done or merged"},auth:{checkingTitle:"Loading",checkingBody:"Checking sign-in status…",connectFailedTitle:"Cannot reach the server",connectFallback:"Cannot reach the server",loginTitle:"Sign in to baxian",loginDescription:"This server requires an access token to continue",loginFailed:"Sign-in failed",sessionExpired:"Session expired, please enter the token again",tokenInvalid:"Invalid token, please retry",tokenLabel:"Token",tokenPlaceholder:"Enter the token configured on the server",tokenRequired:"Please enter the access token",submit:"Sign in",submitting:"Signing in…"},createProject:{title:"New project",required:"Required",idLabel:"Project ID",idPlaceholder:"baxian",idTakenError:"This ID is already in use",repoLabel:"Git repository URL",repoFormatError:"Must be a Git URL (https / ssh / scp, e.g. https://gitlab.example.com/group/proj.git) or owner/repo",mergeStrategyLabel:"Merge strategy",mergeHumanLabel:"Human merge (default)",mergeAutoLabel:"Auto-merge after QA approval",specApprovalLabel:"Spec review",specApprovalHumanLabel:"Human review (default)",specApprovalAutoLabel:"Auto-start coding after QA approval",reviewModeLabel:"Review mode",reviewModeFollowGlobalLabel:"Follow global setting",reviewModeGitLabel:"Git (PR/MR)",reviewModeServerLabel:"Server",gitCliToolLabel:"Git CLI tool",gitCliToolPlaceholder:"e.g. forge",gitCliNotesLabel:"CLI instance notes (optional)",createdToastTitle:e=>`Project ${e} created`},createAgent:{modalTitle:e=>`Add agent to ${e}`,submitLabel:"Add agent",submitting:"Adding…",idTakenGlobalError:"This ID is already in use (must be globally unique)",idPlaceholder:(e,n)=>`${e}-${n}`,roleLabel:"Role",roleResearch:"Research agent",createDevFirstHint:"Create a Dev agent first",pairWithLabel:"Paired Dev agent",pairWithPlaceholder:"Select one",pairOptionLabel:(e,n)=>`${e} (${n})`,modeLabel:"Run mode",localModeLabel:"Local",remoteModeLabel:"Remote (SSH)",noHostsHint:'No hosts configured yet. Add one from the "Manage hosts" menu in the top-right corner first.',selectHostPlaceholder:"Select a host",sshConfigHint:'Private keys and jump hosts can still be configured in ~/.ssh/config; port and password are set under "Manage hosts".',runtimeLabel:"Runtime",reprobeButton:"↻ Re-probe",selectHostFirstHint:"(select a host first)",probingLabel:"probing…",tmuxProbingLabel:"tmux: probing…",advancedOptionsLabel:"Advanced options",expandLabel:"Expand",collapseLabel:"Collapse",workdirLabel:"Workdir (optional)",workdirPlaceholder:"Leave blank to auto-clone into ~/.baxian/agents/<agentId>/repo",workdirHint:"Use a dedicated directory for this agent. Do not share the same directory between agents. Leave blank to let baxian create one automatically.",modelLabel:"Model (optional)",modelPlaceholderCodex:"e.g. o3 / gpt-4o (leave blank for the default)",modelPlaceholderOther:"e.g. sonnet / opus / claude-sonnet-4-6 (leave blank for the default)",modelHint:"Passed through as the launch command's --model flag; leave blank to follow the CLI default.",addDirsLabel:"Additional Dirs (optional)",addDirsPlaceholder:`One absolute path per line, e.g.:
|
|
4
|
-
/Users/me/shared-libs
|
|
5
|
-
/Users/me/extra-repo`,addDirsHint:"Passed through to --add-dir to bring extra directories into the CLI's working root; in non-YOLO mode it also widens the permission scope.",yoloTitle:"YOLO mode (recommended)",yoloBodyLead:"Once enabled, the selected runtime launches with ",yoloBodyTrail:". When unchecked, the runtime launches in its default permission mode: permission requests pause in the terminal until a human answers (the agent shows as waiting for input).",addedToastTitle:(e,n)=>`Agent ${e} added to ${n}`},createTask:{titleCreate:"New task",titleEdit:"Edit task",selectProjectPlaceholder:"Select a project",targetAgentLabel:"Target agent",researchTargetOption:e=>`${e} (Research first)`,notAssignedOption:"Not assigned yet",pendingRestartSuffix:"(pending restart)",notInRuntimeSuffix:"(not in runtime)",titlePlaceholder:"One-sentence summary of what to do",descriptionLabel:"Description (optional)",descriptionPlaceholder:"Describe the task in detail; markdown is supported. Optional for simple tasks.",imagesLabel:"Images (optional)",addImagesButton:"Add images",removeImageAriaLabel:e=>`Remove image ${e}`,draftRestoredNotice:"Restored your last unsaved draft",discardDraftButton:"Discard",updatedToastTitle:"Task updated",createdToastTitle:"Task created",imageTooLargeToastTitle:"Image too large",imageTooLargeToastBody:(e,n)=>`${e} exceeds ${n} MiB`,tooManyImagesToastTitle:e=>`Maximum ${e} images`,noDevPendingRestartHint:e=>`Dev agent "${e}" exists in baxian.json but the runtime has not loaded it (config may have been edited by hand); restart the server to bring it up`,noDevNotInRuntimeHint:e=>`Dev agent "${e}" is not in the runtime (it may have been removed from the project config); saving may fail — confirm or choose a different Dev agent`,noDevGlobalPendingRestartHint:"baxian.json has Dev agents the runtime has not loaded (config may have been edited by hand); restart the server to apply"},hostMgmt:{title:"Manage hosts",emptyState:'No hosts configured yet. Click "Add host" below.',addHostButton:"+ Add host",passwordSavedIndicator:" · Password saved",addressLabel:"Host address",portLabel:"Port (optional)",portRangeError:"Port must be 1–65535",aliasLabel:"Alias (optional)",userLabel:"Username (optional)",userPlaceholder:"Leave blank to read the User from ~/.ssh/config",passwordLabel:"Password (optional)",passwordPlaceholderSet:"Already set; leave blank to keep it unchanged",passwordPlaceholderUnset:"Leave blank to use key-based auth",clearPasswordLabel:"Clear the saved password (switch to key-based login)",passwordHintLead:"We recommend setting up ",passwordHintStrong:"passwordless login (SSH key).",plaintextWarningLead:"Otherwise, the password you enter will be saved to baxian.json in ",plaintextWarningStrong:"plaintext",plaintextWarningTrail:".",testConnection:"Test connection",testing:"Testing…",createdToastTitle:e=>`Host ${e} added`,updatedToastTitle:e=>`Host ${e} updated`,deletedToastTitle:e=>`Host ${e} deleted`},projectPage:{newTaskButton:"+ New task",menuAriaLabel:e=>`Project ${e} actions menu`,showTaskPanel:"Show task panel",addAgent:"Add agent",deleteAgentsFirstHint:e=>`Delete the project's ${e} agent${e===1?"":"s"} first`,deleteProjectMenuItem:"Delete project…",noAgentsYet:"No agents yet. Use the menu in the top-right corner to add one.",closeTaskPanel:"Close task panel",deleteModalTitle:"Delete project",confirmDeleteButton:"Confirm delete",deleteBodyLead:"This updates ",deleteBodyMid:" to remove project ",deleteBodySuffix:". This action cannot be undone and will not delete the underlying Git repository.",confirmInputLead:"To confirm, enter the project ID below: ",confirmInputSuffix:"",confirmInputAriaLabel:"Enter the project ID to confirm deletion",deletedToastTitle:e=>`Project ${e} deleted`},taskDetail:{cancelConfirmTitle:e=>`Cancel task ${e}?`,cancelConfirmLabel:"Cancel task",cancelledToastTitle:"Task cancelled",cancelFailedTitle:"Failed to cancel",cancelForceTitle:"Force-cancels the task from any state; interrupts and releases its agents",cancelConfirmBodyTerminal:"The task is already finished; its status will not change. This interrupts and releases any agents still bound to it (stale-binding cleanup).",cancelCleanupToastTitle:"Cleaned up stale agent bindings for the task",reReviewTerminalConfirmTitle:"Re-review a finished task?",reReviewTerminalConfirmBody:(e,n)=>`Task ${e} is already in status "${n}". Manually asking the QA agent to re-review runs another round, but the state machine will not feed the QA agent's result back into the main flow.`,retryConfirmTitle:e=>`Retry task ${e}?`,retryConfirmBodyMerged:"The task is merged. Retrying creates a new task from scratch with the same title/description.",retryConfirmBodyDefault:"This creates a new task from scratch; the old task is kept as history.",retryCreatedToastTitle:e=>`Created task ${e}`,retryFailedTitle:"Failed to retry",markCompleteConfirmTitle:"Mark complete and merge?",markCompleteConfirmBody:e=>`Merges PR #${e} and wraps up: safely cleans up a baxian-owned local task branch and compacts the agent's context. User-defined branches are preserved.`,markComplete:"Mark complete",completing:"Completing…",markCompleteToastTitle:"Marked complete; wrapping up",markCompleteFailedTitle:"Failed to mark complete",branchCleanupPendingTitle:"Local branch cleanup is pending",branchCleanupSkippedTitle:"Local branch was preserved",continueConfirmTitle:"Continue another round?",continueConfirmBody:e=>`Has the Dev agent do another round of fixes (round ${e}); moves to QA review automatically once done.`,continueRound:"Continue another round",continuing:"Continuing…",continuedToastTitle:e=>`Continued to another round (round ${e})`,continueFailedTitle:"Failed to continue",specApproveConfirmTitle:"Approve Spec and start coding?",specApproveConfirmBody:e=>`Task ${e} will move into the coding phase.`,specApprove:"Approve Spec",specArchive:"Archive research",specApprovedToastTitle:"Spec approved; coding started",specApproveFailedTitle:"Failed to approve Spec",specRejectedToastTitle:"Spec rejected; Dev agent is revising",specRejectedToastTitleResearch:"Spec rejected; Research agent is revising",specArchiveConfirmTitle:"Archive this research task?",specArchiveConfirmBody:e=>`Task ${e} will end without entering the coding phase.`,specArchivedToastTitle:"Research task archived",specArchiveFailedTitle:"Failed to archive research task",specRejectFailedTitle:"Failed to reject Spec",confirmGateConfirmTitle:e=>`Confirm task ${e} is complete?`,confirmGateConfirmBody:"When project.merge is set to auto, baxian merges it automatically.",confirmComplete:"Confirm complete",confirmedToastTitle:e=>`Confirmed (${e})`,confirmFailedTitle:"Failed to confirm",taskNotFound:e=>`Task not found: ${e}`,legacyPendingNotice:'This task has no Dev agent assigned yet: click "Edit" to choose one, or click "Start" on any idle Dev agent card.',legacyReadonlyNotice:e=>`Legacy task with no Dev agent assigned. Current status: "${e}". Read-only.`,reviewRoundPrefix:"Review round ",reviewRoundSuffix:"",specRoundPrefix:"Spec round ",specRoundSuffix:"",createdAtPrefix:"Created ",updatedAtPrefix:" · Updated ",verdictOverdueTitle:"Review verdict overdue",verdictOverduePrefix:"QA agent claimed it at ",verdictOverdueSuffix:' with no verdict submitted after 10 minutes. Open the QA agent terminal to check, or click "Call review" to try again.',approvedBannerTitle:"QA agent approved · Confirming feedback",approvedBannerBody:"Dev agent is confirming all review feedback has been addressed; wraps up once done.",viewPr:e=>`View PR #${e}`,readyGateBannerTitle:"Review approved · Awaiting your confirmation",readyGateBannerBody:e=>`Server review approved — ${e} round${e===1?"":"s"} in total. Click "Confirm" to wrap up, or "Cancel" to discard.`,mergeReadyBannerTitle:"PR ready · Awaiting your confirmation",mergeReadyBannerBody:'Dev agent has finished its wrap-up self-check; click "Confirm" to let baxian finish up.',specReadyBannerTitle:"Spec requires human review",specReadyNotice:e=>`QA agent approved Spec round ${e} — see the full review below. Approving starts coding; comments from a rejection go to the Dev agent for revision and re-review.`,specReadyNoticeResearch:e=>`Research Spec round ${e} is ready — see the full review below. Approving hands the exact documents to the Dev agent; rejection comments go back to the Research agent.`,specCommentsPlaceholder:"Rejection comments (required when rejecting)",submitting:"Submitting…",specApproveButton:"Approve Spec and start coding",specRejectTitleEmpty:"Fill in rejection comments first",specRejectTitleReady:e=>`Comments will be passed to the ${e} agent as findings for revision`,specReject:"Reject Spec",specArchiveButton:"Archive research",readyGateRejectHint:"Not satisfied? Enter feedback to send it back to the Dev agent for another round.",codeRejectCommentsPlaceholder:"Change request (required to send back)",codeRejectTitleEmpty:"Fill in your change request first",codeRejectTitleReady:"Your feedback is passed to the Dev agent as a finding for revision",codeReject:"Request changes",codeRejectedToastTitle:"Sent back; Dev agent is revising",codeRejectFailedTitle:"Failed to send back",codeMaxRoundsTitle:e=>`Review round limit reached (round ${e})`,codeMaxRoundsBody:'You can click "Mark complete" to merge what you have, or "Continue another round" to keep revising. For anything left over, consider opening a new task — more rounds make the agent more likely to drift off-topic.',specMaxRoundsTitle:e=>`Spec review round limit reached (round ${e})`,specMaxRoundsBody:"No agreement was reached after multiple rounds; the task is paused. You can approve the current Spec to start coding, reject it with comments to run one more round (cap +1), or Retry / Cancel. Reviewing the round history first helps locate the disagreement.",noDescription:"(No description)",noLinkedAgent:"No linked agent",cancelling:"Cancelling…",retryDisabledStatusTitle:e=>`Cannot retry in status "${e}"`,retryDisabledLegacyTitle:"Legacy task has no Dev agent assigned; cannot retry",retryEnabledTitle:"Creates a new task from scratch in the agent's fixed Workdir",reviewNoPrTitle:"This task has no PR yet; cannot start a review",reviewServerStatusTitle:"Reviews can only be started while the task is in progress, in review, or fixing",reviewUnphasedTitle:"The dev has not delivered a spec/code signal yet, so there is nothing to review",reviewButtonTitle:"Has the QA agent start a new review round right away",continueButtonTitle:"Has the Dev agent do another round of fixes; moves to QA review automatically once done",completeButtonTitle:"Merges the PR and wraps up (safely cleans up only baxian-owned local task branches and compacts context)",confirmButtonTitle:"Confirms completion; when merge is set to auto, baxian performs the merge",confirming:"Confirming…",retryPublishButtonTitle:"Retries the push/PR steps after a failed publish",retryPublish:"Retry publish",noAgentSlot:e=>`No ${e} agent`,reviewSummaryPrefix:"Review rounds: ",reviewSummaryMid:" · Final verdict ",reviewSummaryFindingsPrefix:" · Findings: ",reviewSummaryFindingsSuffix:" total"},taskPanel:{ariaLabel:"Task panel",emptyInProgress:"No tasks in progress yet",emptyPending:"No pending tasks yet",collapse:"Collapse",view:"View",loadMore:"Load more",emptyDone:"No completed tasks yet"},review:{specDraft:"Spec draft",codeChanges:"Code changes",submitSpecDraft:"Submit Spec draft",submitCodeChanges:"Submit code changes",contentTruncated:"Content is large; showing a truncated excerpt.",noContent:"No content",qaReviewHeading:"QA review",notSubmitted:"Review not submitted yet.",noFindingsThisRound:"No findings this round.",devResponsesHeading:"Dev responses",userDecisionHeading:"User decision",loadExternalImage:"Load external image",roundNotFound:(e,n)=>`Review round not found (${e} round ${n}).`,loadFailed:e=>`Failed to load review records: ${e}`,loadingRecords:"Loading review records…",notStarted:"Review has not started",sectionTitle:"Review records",phaseLabel:{spec:"Spec review",code:"Code review"},diffLineCount:e=>`diff ${e} lines`,specDocLineCount:e=>`Spec draft ${e} lines`,findingsSummary:(e,n)=>`${e} findings${n?` (${n})`:""}`,responsesSummary:e=>`${e} responses`,reviewTurnLabel:"Review",responseTurnLabel:"Response",roleUser:"User",roleQa:"QA",roleDev:"Dev",diffUnnamed:"(diff)",expandAll:"Expand all",collapseAll:"Collapse all",findingMarker:e=>`Finding ${e}`,locationNotInDiff:"Not in this round’s diff",reviewing:"QA reviewing…",reviewingBatch:(e,n)=>`QA reviewing… (batch ${e}/${n})`,fixingCount:e=>`Dev fixing… (${e} to respond)`,batchTurn:e=>`Review (batch ${e})`,batchPartialHeading:e=>`Batch ${e} (partial)`,viewFull:"Full diff",viewInterdiff:"This round only",interdiffLoading:"Loading this round’s changes…",interdiffUnavailableHistorical:"This round has no anchor; incremental view unavailable",interdiffUnavailableReleased:"Dev is no longer bound to this task; incremental view unavailable",interdiffUnavailableGeneric:"Incremental view unavailable"},prReview:{reasonServerMode:'This task uses server review mode; code review records are under "Review records" on the task detail page.',reasonServerModeEntry:"This task uses server review mode; code review records are in the server review rounds.",reasonNoPr:"This task has no PR yet; there are no code review records.",reasonDriverUnavailable:"No git driver is resolvable for this project; PR review records cannot be fetched.",codeReviewHeading:"Code review",fetchFailed:e=>`Failed to fetch review records: ${e}`,partialFetchFailed:e=>`Some review records failed to fetch: ${e} (showing only what was retrieved).`,inlineComment:"Inline comment",comment:"Comment",replyIndicator:"↩ Reply",noReviewBody:"(No review body)",bodyTruncated:"Content is large; truncated.",truncatedSuffix:"(truncated)",noReviewBodyFallback:"No review body",ghostAuthor:"ghost (deleted account)",listTruncated:"This PR has too many comments; only the earliest part is shown."},toast:{dismissAriaLabel:"Close notification"},banner:{restartFailed:e=>`Restart failed: ${e}`,restarting:"Restarting…",pendingNotice:e=>`${e} config change${e===1?"":"s"} pending — restart the baxian server to apply`,restartNow:"Restart now",preRestartFetchFailed:e=>`Failed to read startedAt before restart: ${e}`,restartTriggerFailed:e=>`Failed to trigger restart: ${e}`,restartTimeout:"Restart timed out (30s with no recovery). Check the logs, or run baxian start -c <path> manually.",githubDegraded:e=>`Platform polling degraded for ${e} — reviews and PR updates may lag until connectivity recovers`,githubUnreachable:e=>`Platform unreachable for ${e} — task progress is paused and will resume automatically once connectivity recovers`,githubRateLimited:(e,n)=>`Platform polling rate-limited for ${e} until ${new Date(n).toLocaleTimeString()} — updates will resume automatically`},terminal:{sessionEnded:"Session ended",keyPadAriaLabel:"Terminal keys",arrowAriaLabel:e=>`${e} arrow key`,arrowLabel:{up:"Up",down:"Down",left:"Left",right:"Right"},escKeyAriaLabel:"Esc key"},imageUpload:{tooLargeBody:e=>`A single image must not exceed ${e} MiB`,insertedTitle:"Image inserted",insertedBody:"Path pasted into the terminal input — add more detail, then press Enter",uploadFailedTitle:"Failed to upload image",uploadAriaLabel:"Upload image"},pet:{missingManifest:"pet.json not found in the file package",manifestParseFailed:"Failed to parse pet.json",missingSpritesheet:"Spritesheet (png/webp) not found in the file package",disabledTitle:"Agent Pet disabled",disableFailedTitle:"Failed to disable",selectedTitle:"Pet selected",selectFailedTitle:"Failed to select",deleteConfirmTitle:e=>`Delete Pet "${e}"?`,deleteConfirmBody:"Agents using it will fall back to the default status display.",deletedTitle:e=>`Pet "${e}" deleted`,deleteFailedTitle:"Failed to delete",uploadedTitle:"Pet uploaded",uploadFailedTitle:"Failed to upload pet",enableLabel:"Enable Agent Pet",enableHint:"Once enabled, you can upload a Codex Pet package, or pick a previously uploaded pet to replace the status display on the agent card.",uploadButton:"Upload Pet package",uploadInputAriaLabel:"Upload Codex Pet package",uploadDirHint:"Select a Codex Pet directory (containing pet.json and the spritesheet).",emptyState:"No pets uploaded yet — click the button above to upload one.",currentMarker:"(current)",deleteAriaLabel:e=>`Delete ${e}`}},sr={common:{cancel:"取消",confirm:"确认",close:"关闭",delete:"删除",deleting:"删除中…",edit:"编辑",retry:"重试",retrying:"重试中…",back:"← 返回",backText:"返回",loading:"加载中…",loadFailed:e=>`加载失败:${e}`,idFormatError:"小写字母开头,只含 a-z 0-9 -,长度 2-32",create:"创建",creating:"创建中…",save:"保存",saving:"保存中…",oneClickInstall:"一键安装",installing:"安装中…",installingTmuxNotice:"正在安装 tmux,可能需要几分钟,请勿关闭窗口…"},status:{pending:"待处理",in_progress:"进行中",review:"评审中",fixing:"修订中","spec-ready":"Spec 待批",approved:"已通过","merge-ready":"待确认",ready:"待确认",merged:"已合并",done:"已完成",failed:"失败",max_rounds:"轮次达上限",cancelled:"已取消"},notification:{taskDone:e=>`任务完成:${e}`,bodyProject:e=>`项目:${e}`,bodyTask:e=>`任务:${e}`,bodyStatus:e=>`状态:${e}`},dashboard:{moreActions:"更多操作",newProject:"新建项目",manageHosts:"Host 管理",newTask:"+ 新建任务",createProjectFirst:"请先创建项目",emptyProjects:'还没有项目。点击右上角"更多"菜单 → "新建项目"开始。',noAgentsYet:"还没有 Agent。进入 Details 添加。",detailsLink:"详情 →",detailsAriaLabel:e=>`详情 — ${e}`,tasksLoadFailed:e=>`任务列表加载失败:${e}`,projectCreatedTitle:"项目已创建",addAgentNowOrLater:"现在添加第一个 Agent,还是稍后再加?",later:"稍后再加",continueAddingAgent:"继续添加 Agent"},nav:{toggleToIcon:"切换为 Logo 图标",toggleToText:"切换为 Logo 文字"},agents:{runtimeStatus:{unknown:"未知",idle:"空闲",pending:"待人工",working:"工作中",waiting:"等待中",error:"异常"},sessionStatus:{absent:"无会话",unreachable:"主机不可达"},bootstrappingBadge:"启动中",agentStatusLoading:"Agent 状态加载中",bootstrappingTerminalDisabled:"Agent 正在启动",bootstrappingNotice:"Agent 正在启动,终端可用后会自动刷新。",terminalNeedsRestart:"重启 baxian server 后可用",pendingRestartNotice:"重启 baxian server 后生效",heldBadge:"挂起",heldDefaultReason:"需人工处理",staleTitle:e=>e?`数据可能已过期 — 最后观测于 ${e}`:"数据可能已过期",awaitingHumanIntervention:"等待人工介入",openTerminalPrefix:"请打开 ",openTerminalSuffix:" 处理。",terminal:"终端",needInputBadge:"等回答",needInputTitle:e=>`Agent 在等你的回答(${e})`,needInputNoticeTitle:"Agent 在等你的回答",needInputPrefix:"它提了一个问题,请打开 ",needInputSuffix:" 回复。",activateTerminal:e=>`激活 ${e} 终端`,actionsMenu:e=>`Agent ${e} 操作菜单`,taskLabel:"任务:",stop:"停止",stopping:"停止中…",resume:"恢复",resuming:"恢复中…",resumeConfirmTitle:e=>`恢复 Agent ${e}?`,resumeGreetingBody:"greeting 能力未通过,baxian 会重跑能力握手(会话存活则重启 REPL,已丢失则重建);握手通过才解除挂起。",resumeDefaultBody:"baxian 会清除 awaiting_human 状态,agent 恢复可用。",resumeGreetingButtonTitle:"重跑 greeting 能力握手以恢复(会话存活则重启 REPL,已丢失则重建;greeting_failed 无法靠清状态解除)",resumeDefaultButtonTitle:"清除 awaiting_human 状态,让 agent 恢复可用",regreetingStartedTitle:e=>`Agent ${e} 正在重跑能力握手`,regreetingStartedBody:"握手通过后 Held 会在下一次刷新自动解除,仍失败则按提示修复 runtime 后再试。",resumedTitle:e=>`Agent ${e} 已 Resume`,resumedReleasedBody:"原任务已释放,agent 可接新任务。",resumedKeptBody:"保留绑定(原任务仍 active)。",resumeFailedTitle:"Resume 失败",compact:"压缩上下文",compacting:"压缩中…",compactMenuItemTitle:"向 agent runtime 发送 /compact 压缩上下文",compactSentTitle:e=>`已向 Agent ${e} 发送 /compact`,compactFailedTitle:"压缩上下文失败",clear:"清空上下文",clearing:"清空中…",clearMenuItemTitle:"向 agent runtime 发送 /clear 清空上下文",clearConfirmTitle:e=>`清空 Agent ${e} 的上下文?`,clearConfirmBody:"将发送 /clear,整个会话上下文不可恢复。",clearConfirmLabel:"清空",clearSentTitle:e=>`已向 Agent ${e} 发送 /clear`,clearFailedTitle:"清空上下文失败",deleteConfirmTitle:e=>`删除 Agent ${e}?`,deleteConfirmBody:"此操作不可撤销。",deletedWithPairTitle:e=>`已删除 Agent ${e}`,deletedWithPairBody:e=>`配对的 QA agent ${e} 也被一并移除。`,deletedTitle:e=>`Agent ${e} 已删除`,agentPetMenuItemTitle:"配置 Agent Pet(在状态位置显示动画宠物)",callReview:"发起评审",callingReview:"发起中…",callReviewMenuItemTitle:e=>`让 QA agent 立即对任务 ${e} 跑一轮 review(git 评审模式需已有 PR)`,confirmReReviewTitle:"发起 QA 重审?",confirmReReviewBody:e=>`QA agent 将对任务 ${e} 立即开始新一轮 review。若上一次投递状态不确定,请先核实 QA pane 未收到该投递;继续操作即确认未投递。`,confirmReReviewLabel:"发起重审",reReviewStarted:e=>`已发起 QA 重审(第 ${e} 轮)`,reReviewStartFailed:"发起评审失败",retryBootstrap:"重试 bootstrap",retryBootstrapSucceededTitle:"重试 bootstrap 完成",retryBootstrapSucceededBody:"agent 状态将在下一次刷新生效。",retryBootstrapStillFailingTitle:"重试 bootstrap 仍失败",retryBootstrapStillFailingBody:"看一下红色错误卡的最新原因,按提示修复后再试。",retryBootstrapFailedTitle:"重试 bootstrap 失败",round:e=>`第 ${e} 轮`,noActiveTask:"暂无任务",noActiveTaskAriaLabel:e=>`${e} 暂无任务`,unassigned:"未分配",start:"发起",starting:"发起中…",startFailed:"发起失败",taskHandedTo:(e,n)=>`任务 ${e} 已交给 ${n}`,handToAndStart:e=>`交给 ${e} 并立即开始`,agentUnavailable:e=>`Agent ${e} 当前不可用`},settings:{entry:"系统设置",title:"系统设置",language:"语言",languageSaveFailed:e=>`语言保存失败:${e}`,taskNotifications:"任务完成通知",taskNotificationsDenied:"浏览器已拒绝通知权限",taskNotificationsHint:"任务到达已完成或已合并时通过浏览器通知"},auth:{checkingTitle:"加载中",checkingBody:"正在检查登录状态…",connectFailedTitle:"无法连接服务器",connectFallback:"无法连接服务器",loginTitle:"登录 baxian",loginDescription:"服务器开启了访问鉴权,请输入访问令牌继续。",loginFailed:"登录失败",sessionExpired:"登录已失效,请重新输入令牌",tokenInvalid:"令牌无效,请重试",tokenLabel:"令牌",tokenPlaceholder:"请输入服务器配置的 token",tokenRequired:"请输入访问令牌",submit:"登录",submitting:"登录中…"},createProject:{title:"新建项目",required:"必填",idLabel:"项目 ID",idPlaceholder:"baxian",idTakenError:"该 id 已被占用",repoLabel:"Git 仓库地址",repoFormatError:"需为 git URL(https / ssh / scp,如 https://gitlab.example.com/group/proj.git)或 owner/repo",mergeStrategyLabel:"合并策略",mergeHumanLabel:"人类合并(默认)",mergeAutoLabel:"QA Approve 后自动合并",specApprovalLabel:"Spec 审核",specApprovalHumanLabel:"人类审核(默认)",specApprovalAutoLabel:"QA Approve 后自动开始编码",reviewModeLabel:"Review 模式",reviewModeFollowGlobalLabel:"跟随全局",reviewModeGitLabel:"Git (PR/MR)",reviewModeServerLabel:"Server",gitCliToolLabel:"Git CLI 工具",gitCliToolPlaceholder:"如 forge",gitCliNotesLabel:"CLI 实例说明(可选)",createdToastTitle:e=>`项目 ${e} 已创建`},createAgent:{modalTitle:e=>`添加 Agent 到 ${e}`,submitLabel:"添加 Agent",submitting:"添加中…",idTakenGlobalError:"该 id 已被占用(全局唯一)",idPlaceholder:(e,n)=>`${e}-${n}`,roleLabel:"角色",roleResearch:"Research agent",createDevFirstHint:"请先创建一个 Dev agent",pairWithLabel:"配对 Dev agent",pairWithPlaceholder:"请选择",pairOptionLabel:(e,n)=>`${e}(${n})`,modeLabel:"运行模式",localModeLabel:"本机",remoteModeLabel:"远程 (SSH)",noHostsHint:"还没有配置 Host。请先在右上角菜单的「Host 管理」中添加。",selectHostPlaceholder:"请选择 Host",sshConfigHint:"私钥/跳板机仍可在 ~/.ssh/config 配置;端口/密码在「Host 管理」里设置。",runtimeLabel:"运行时",reprobeButton:"↻ 重新探测",selectHostFirstHint:"(请先选择 Host)",probingLabel:"探测中…",tmuxProbingLabel:"tmux: 探测中…",advancedOptionsLabel:"高级选项",expandLabel:"展开",collapseLabel:"收起",workdirLabel:"Workdir(可选)",workdirPlaceholder:"留空时自动 clone 到 ~/.baxian/agents/<agentId>/repo",workdirHint:"该目录应由当前 Agent 独占,不同 Agent 不要共用同一目录。留空时由 baxian 自动创建。",modelLabel:"Model(可选)",modelPlaceholderCodex:"例: o3 / gpt-4o(留空走 default)",modelPlaceholderOther:"例: sonnet / opus / claude-sonnet-4-6(留空走 default)",modelHint:"透传到 launch 命令的 --model 参数;留空跟随 CLI 默认。",addDirsLabel:"Additional Dirs(可选)",addDirsPlaceholder:`每行一个绝对路径,例:
|
|
6
|
-
/Users/me/shared-libs
|
|
7
|
-
/Users/me/extra-repo`,addDirsHint:"透传到 --add-dir,让 CLI 把额外目录纳入工作根;非 YOLO 模式下同时扩大权限放行范围。",yoloTitle:"YOLO 模式(推荐开启)",yoloBodyLead:"开启后所选运行时以 ",yoloBodyTrail:" 启动。取消勾选则以运行时默认权限模式启动,权限请求会在终端挂起等待人工确认(agent 状态显示为等待输入)。",addedToastTitle:(e,n)=>`Agent ${e} 已添加到 ${n}`},createTask:{titleCreate:"新建任务",titleEdit:"编辑任务",selectProjectPlaceholder:"选择项目",targetAgentLabel:"目标 Agent",researchTargetOption:e=>`${e}(先调研)`,notAssignedOption:"暂不指定",pendingRestartSuffix:"(待重启)",notInRuntimeSuffix:"(不在 runtime)",titlePlaceholder:"一句话描述要做什么",descriptionLabel:"Description(可选)",descriptionPlaceholder:"详细描述任务,支持 markdown;简单任务可不填",imagesLabel:"图片(可选)",addImagesButton:"添加图片",removeImageAriaLabel:e=>`移除图片 ${e}`,draftRestoredNotice:"已恢复上次未提交的草稿",discardDraftButton:"丢弃",updatedToastTitle:"任务已更新",createdToastTitle:"任务已创建",imageTooLargeToastTitle:"图片过大",imageTooLargeToastBody:(e,n)=>`${e} 超过 ${n} MiB`,tooManyImagesToastTitle:e=>`最多 ${e} 张图片`,noDevPendingRestartHint:e=>`当前 Dev agent "${e}" 在 baxian.json 中存在但 runtime 未加载,可能是手动编辑过配置文件;重启 server 可拉起`,noDevNotInRuntimeHint:e=>`当前 Dev agent "${e}" 不在 runtime(可能已从 project 配置移除);保存可能失败,请确认或选择新 Dev agent`,noDevGlobalPendingRestartHint:"baxian.json 里有 Dev agent 但 runtime 未加载(可能是手动编辑过配置);重启 server 后生效"},hostMgmt:{title:"Host 管理",emptyState:"还没有配置 Host。点击下方「添加 Host」。",addHostButton:"+ 添加 Host",passwordSavedIndicator:" · 密码已保存",addressLabel:"Host 地址",portLabel:"端口(可选)",portRangeError:"端口需为 1–65535 的整数",aliasLabel:"别名(可选)",userLabel:"用户名(可选)",userPlaceholder:"留空则读 ~/.ssh/config 的 User",passwordLabel:"密码(可选)",passwordPlaceholderSet:"已设置,留空保持不变",passwordPlaceholderUnset:"留空使用 key 认证",clearPasswordLabel:"清除已保存的密码(改用 key 登录)",passwordHintLead:"建议为该 Host 配置好",passwordHintStrong:"免密码登入(SSH key)。",plaintextWarningLead:"否则填写的密码将以",plaintextWarningStrong:"明文",plaintextWarningTrail:"保存到 baxian.json 中。",testConnection:"测试连接",testing:"测试中…",createdToastTitle:e=>`Host ${e} 已添加`,updatedToastTitle:e=>`Host ${e} 已更新`,deletedToastTitle:e=>`Host ${e} 已删除`},projectPage:{newTaskButton:"+ 新建任务",menuAriaLabel:e=>`项目 ${e} 操作菜单`,showTaskPanel:"显示任务面板",addAgent:"添加 Agent",deleteAgentsFirstHint:e=>`请先删除项目下的 ${e} 个 Agent`,deleteProjectMenuItem:"删除项目…",noAgentsYet:"还没有 Agent,点击右上角菜单添加。",closeTaskPanel:"关闭任务面板",deleteModalTitle:"删除项目",confirmDeleteButton:"确认删除",deleteBodyLead:"将从 ",deleteBodyMid:" 中移除项目 ",deleteBodySuffix:"。此操作不可撤销,且不会删除 Git 仓库本身。",confirmInputLead:"如需确认,请在下方输入项目 ID ",confirmInputSuffix:":",confirmInputAriaLabel:"输入项目 ID 以确认删除",deletedToastTitle:e=>`项目 ${e} 已删除`},taskDetail:{cancelConfirmTitle:e=>`取消任务 ${e}?`,cancelConfirmLabel:"取消任务",cancelledToastTitle:"任务已取消",cancelFailedTitle:"取消失败",cancelForceTitle:"任意状态下强制取消任务,中断并释放关联 agent",cancelConfirmBodyTerminal:"任务已是终态,状态不会改变;此操作会中断并释放仍绑定在该任务上的 agent(清理残留)。",cancelCleanupToastTitle:"已清理任务的残留 agent 绑定",reReviewTerminalConfirmTitle:"重审已结束的任务?",reReviewTerminalConfirmBody:(e,n)=>`任务 ${e} 已是「${n}」状态。手动请 QA agent 重审会再跑一轮 review,但状态机不会把 QA agent 的结果带回主流程。`,retryConfirmTitle:e=>`重试任务 ${e}?`,retryConfirmBodyMerged:"任务已合并。重试会用同样的标题/描述新建一个任务从头跑。",retryConfirmBodyDefault:"会新建一个任务从头开始,旧任务保留为历史。",retryCreatedToastTitle:e=>`已新建任务 ${e}`,retryFailedTitle:"重试失败",markCompleteConfirmTitle:"标记完成并合并?",markCompleteConfirmBody:e=>`将合并 PR #${e} 并收尾:安全清理 baxian 自有的本地任务分支、压缩 Agent 上下文;用户自定义分支会保留。`,markComplete:"标记完成",completing:"完成中…",markCompleteToastTitle:"已标记完成,开始收尾",markCompleteFailedTitle:"标记完成失败",branchCleanupPendingTitle:"本地分支仍待清理",branchCleanupSkippedTitle:"本地分支已保留",continueConfirmTitle:"继续一轮?",continueConfirmBody:e=>`让 Dev agent 再修一轮(第 ${e} 轮),完成后自动转 QA review。`,continueRound:"继续一轮",continuing:"继续中…",continuedToastTitle:e=>`已继续一轮(第 ${e} 轮)`,continueFailedTitle:"继续一轮失败",specApproveConfirmTitle:"通过 Spec 并开始编码?",specApproveConfirmBody:e=>`任务 ${e} 将进入编码阶段。`,specApprove:"通过 Spec",specArchive:"完结归档",specApprovedToastTitle:"Spec 已通过,已发起编码",specApproveFailedTitle:"Spec 通过失败",specRejectedToastTitle:"Spec 已打回,Dev agent 开始修订",specRejectedToastTitleResearch:"Spec 已打回,Research agent 开始修订",specArchiveConfirmTitle:"确认完结并归档调研任务?",specArchiveConfirmBody:e=>`任务 ${e} 将直接结束,不进入编码阶段。`,specArchivedToastTitle:"调研任务已完结归档",specArchiveFailedTitle:"调研任务归档失败",specRejectFailedTitle:"Spec 打回失败",confirmGateConfirmTitle:e=>`确认完成任务 ${e}?`,confirmGateConfirmBody:"project.merge 为 auto 时由 baxian 自动执行合并。",confirmComplete:"确认完成",confirmedToastTitle:e=>`已确认(${e})`,confirmFailedTitle:"确认失败",taskNotFound:e=>`任务不存在:${e}`,legacyPendingNotice:"任务还没有指定 Dev agent:点「编辑」选择,或在任一空闲 Dev agent 卡片上点「发起」。",legacyReadonlyNotice:e=>`历史任务,无指定 Dev agent,当前状态「${e}」,只读。`,reviewRoundPrefix:"评审 ",reviewRoundSuffix:" 轮",specRoundPrefix:"Spec ",specRoundSuffix:" 轮",createdAtPrefix:"创建于 ",updatedAtPrefix:" · 更新于 ",verdictOverdueTitle:"评审逾期未交",verdictOverduePrefix:"QA agent 于 ",verdictOverdueSuffix:" 接单,超过 10 分钟未提交结论。可打开 QA agent 终端查看,或点「发起评审」重新发起。",approvedBannerTitle:"QA agent 已通过 · 正在核对反馈",approvedBannerBody:"Dev agent 正在确认所有评审反馈均已处理,完成后进入收尾。",viewPr:e=>`查看 PR #${e}`,readyGateBannerTitle:"评审通过 · 等你确认",readyGateBannerBody:e=>`Server 评审通过,共 ${e} 轮。点「确认」收尾,或「取消」丢弃。`,mergeReadyBannerTitle:"PR 就绪 · 等你确认",mergeReadyBannerBody:"Dev agent 已完成收尾自检,点「确认」交由 baxian 收尾。",specReadyBannerTitle:"Spec 需由人类审核",specReadyNotice:e=>`QA agent 已通过第 ${e} 轮 Spec,全文见下方评审记录。通过即开始编码;打回意见将交 Dev agent 修订后复审。`,specReadyNoticeResearch:e=>`Research Spec 第 ${e} 轮已就绪,全文见下方评审记录。通过后会把原样文档交给 Dev agent;打回意见会交还 Research agent。`,specCommentsPlaceholder:"打回意见(打回时必填)",submitting:"提交中…",specApproveButton:"通过 Spec,开始编码",specRejectTitleEmpty:"先填写打回意见",specRejectTitleReady:e=>`意见将作为 findings 交 ${e} agent 修订`,specReject:"打回 Spec",specArchiveButton:"完结归档",readyGateRejectHint:"不满意?填写意见可打回给 Dev agent 重做并复审。",codeRejectCommentsPlaceholder:"打回意见(打回时必填)",codeRejectTitleEmpty:"先填写打回意见",codeRejectTitleReady:"意见将作为 findings 交 Dev agent 修订",codeReject:"打回重做",codeRejectedToastTitle:"已打回,Dev agent 开始修订",codeRejectFailedTitle:"打回失败",codeMaxRoundsTitle:e=>`评审已达 ${e} 轮上限`,codeMaxRoundsBody:"可「标记完成」先合并成果,或「继续一轮」再修订。剩余问题建议另开任务,轮次越多 agent 越容易偏题。",specMaxRoundsTitle:e=>`Spec 评审已达 ${e} 轮上限`,specMaxRoundsBody:"多轮未达成一致,任务已暂停。可「批准」采用当前 Spec 进入编码,「打回」补充意见再评一轮(上限 +1),或「重试」/「取消」。建议先看评审记录定位分歧。",noDescription:"(无描述)",noLinkedAgent:"暂无关联 Agent",cancelling:"取消中…",retryDisabledStatusTitle:e=>`当前状态「${e}」不可重试`,retryDisabledLegacyTitle:"历史任务没有指定 Dev agent,无法重试",retryEnabledTitle:"在 Agent 固定 Workdir 中新建任务并从头执行",reviewNoPrTitle:"该任务还没有 PR,无法发起评审",reviewServerStatusTitle:"仅进行中 / 评审中 / 修复中可发起评审",reviewUnphasedTitle:"Dev 尚未交付 spec/code 信号,暂无可评审对象",reviewButtonTitle:"让 QA agent 立即开始新一轮评审",continueButtonTitle:"让 Dev agent 再修一轮,完成后自动转 QA review",completeButtonTitle:"合并 PR 并收尾(仅安全清理 baxian 自有本地任务分支 + 压缩上下文)",confirmButtonTitle:"确认完成;merge:auto 时由 baxian 执行合并",confirming:"确认中…",retryPublishButtonTitle:"发布失败后重试 push/PR 步骤",retryPublish:"重试发布",noAgentSlot:e=>`暂无 ${e} agent`,reviewSummaryPrefix:"Review ",reviewSummaryMid:" 轮 · 最终 verdict ",reviewSummaryFindingsPrefix:" · findings 共 ",reviewSummaryFindingsSuffix:" 条"},taskPanel:{ariaLabel:"任务面板",emptyInProgress:"暂无正在处理的任务",emptyPending:"暂无待处理的任务",collapse:"收起",view:"查看",loadMore:"加载更多",emptyDone:"暂无已处理的任务"},review:{specDraft:"规格稿",codeChanges:"代码改动",submitSpecDraft:"提交规格稿",submitCodeChanges:"提交代码改动",contentTruncated:"内容较大,展示的是截断后的片段。",noContent:"无内容",qaReviewHeading:"QA 评审",notSubmitted:"评审尚未提交。",noFindingsThisRound:"本轮无 findings。",devResponsesHeading:"Dev 反馈",userDecisionHeading:"用户裁决",loadExternalImage:"加载外部图片",roundNotFound:(e,n)=>`未找到该轮评审(${e} 第 ${n} 轮)。`,loadFailed:e=>`加载评审记录失败:${e}`,loadingRecords:"加载评审记录…",notStarted:"评审尚未开始",sectionTitle:"评审记录",phaseLabel:{spec:"Spec 评审",code:"代码评审"},diffLineCount:e=>`diff ${e} 行`,specDocLineCount:e=>`规格稿 ${e} 行`,findingsSummary:(e,n)=>`${e} 条 findings${n?`(${n})`:""}`,responsesSummary:e=>`${e} 条反馈`,reviewTurnLabel:"评审",responseTurnLabel:"反馈",roleUser:"用户",roleQa:"QA",roleDev:"Dev",diffUnnamed:"(diff)",expandAll:"展开全部",collapseAll:"收起全部",findingMarker:e=>`Finding ${e}`,locationNotInDiff:"该位置不在本轮 diff 中",reviewing:"QA 评审中…",reviewingBatch:(e,n)=>`QA 评审中…(批 ${e}/${n})`,fixingCount:e=>`Dev 修复中…(${e} 条待回应)`,batchTurn:e=>`评审(批 ${e})`,batchPartialHeading:e=>`批 ${e}(部分结果)`,viewFull:"全量",viewInterdiff:"仅本轮变化",interdiffLoading:"加载本轮增量…",interdiffUnavailableHistorical:"该轮次无历史锚点,无法生成增量",interdiffUnavailableReleased:"Dev 已不再绑定该任务,增量不可用",interdiffUnavailableGeneric:"增量视图暂不可用"},prReview:{reasonServerMode:"该 task 为 server 评审模式,代码评审记录见任务详情的「评审记录」。",reasonServerModeEntry:"该 task 为 server 评审模式,代码评审记录见 server 评审轮次。",reasonNoPr:"该 task 还没有 PR,暂无代码评审记录。",reasonDriverUnavailable:"该项目当前无法解析 git 驱动,无法拉取 PR 评审记录。",codeReviewHeading:"代码评审",fetchFailed:e=>`评审记录拉取失败:${e}`,partialFetchFailed:e=>`部分评审记录拉取失败:${e}(仅展示已获取的部分)`,inlineComment:"行内评论",comment:"评论",replyIndicator:"↩ 回复",noReviewBody:"(无评审正文)",bodyTruncated:"内容较大,已截断。",truncatedSuffix:"(已截断)",noReviewBodyFallback:"无评审正文",ghostAuthor:"ghost(账号已注销)",listTruncated:"该 PR 评论过多,仅展示靠前的一部分。"},toast:{dismissAriaLabel:"关闭通知"},banner:{restartFailed:e=>`重启失败:${e}`,restarting:"重启中…",pendingNotice:e=>`有 ${e} 项配置变更待重启 baxian server 才生效`,restartNow:"现在重启",preRestartFetchFailed:e=>`获取重启前 startedAt 失败:${e}`,restartTriggerFailed:e=>`触发重启失败:${e}`,restartTimeout:"重启超时(30s 未恢复)。请检查日志或手动 baxian start -c <path>",githubDegraded:e=>`平台轮询降级(${e})——评审与 PR 更新可能延迟,连通恢复后自动跟上`,githubUnreachable:e=>`平台无法访问(${e})——任务推进暂停,连通恢复后自动继续`,githubRateLimited:(e,n)=>`平台轮询触发限流(${e}),将于 ${new Date(n).toLocaleTimeString()} 后自动恢复`},terminal:{sessionEnded:"会话已结束",keyPadAriaLabel:"终端按键",arrowAriaLabel:e=>`方向键 ${e}`,arrowLabel:{up:"上",down:"下",left:"左",right:"右"},escKeyAriaLabel:"Esc 键"},imageUpload:{tooLargeBody:e=>`单张图片不能超过 ${e} MiB`,insertedTitle:"图片已插入",insertedBody:"路径已粘贴到终端输入,补充说明后回车",uploadFailedTitle:"图片上传失败",uploadAriaLabel:"上传图片"},pet:{missingManifest:"文件包中未找到 pet.json",manifestParseFailed:"pet.json 解析失败",missingSpritesheet:"文件包中未找到精灵图(png/webp)",disabledTitle:"已关闭 Agent Pet",disableFailedTitle:"关闭失败",selectedTitle:"已选择 Pet",selectFailedTitle:"选择失败",deleteConfirmTitle:e=>`删除 Pet「${e}」?`,deleteConfirmBody:"使用它的 Agent 会回到默认状态显示。",deletedTitle:e=>`Pet「${e}」已删除`,deleteFailedTitle:"删除失败",uploadedTitle:"Pet 上传成功",uploadFailedTitle:"Pet 上传失败",enableLabel:"启用 Agent Pet",enableHint:"开启后可上传 Codex Pet 文件包,或选择已上传过的 Pet 替换 Agent 卡片上的状态显示。",uploadButton:"上传 Pet 文件包",uploadInputAriaLabel:"上传 Codex Pet 文件包",uploadDirHint:"选择 Codex Pet 目录(含 pet.json 与精灵图)。",emptyState:"还没有上传过 Pet,点击上方按钮上传。",currentMarker:"(当前)",deleteAriaLabel:e=>`删除 ${e}`}},Yt="baxian.language",Je="en-US",Gn={"en-US":Wn,"zh-CN":sr};function Qn(e){return e==="zh-CN"||e==="en-US"}function zn(){try{const e=localStorage.getItem(Yt);return Qn(e)?e:Je}catch{return Je}}function Kn(e){try{localStorage.setItem(Yt,e)}catch{}}let Ue=zn();const Mt=new Set;let ft=0,rr=0,ln=0;function Jt(e){e!==Ue&&(Ue=e,Mt.forEach(n=>n(e)))}function Ot(e){ft+=1;const n=e??Je;Kn(n),Jt(n)}function ar(e){const n=e??Je;Kn(n),Jt(n)}function Xt(){return Gn[Ue]}const Vn=o.createContext({locale:Je,messages:Wn,saving:!1,setLocale:async()=>{throw new Error("setLocale requires I18nProvider")}});function ir({children:e}){const[n,s]=o.useState(Ue),[r,a]=o.useState(!1);o.useEffect(()=>{const l=d=>s(d);return Mt.add(l),s(Ue),()=>{Mt.delete(l)}},[]),o.useEffect(()=>{document.documentElement.lang=n==="zh-CN"?"zh-CN":"en"},[n]),o.useEffect(()=>{const l=d=>{if(d.key!==null&&d.key!==Yt)return;const u=d.key===null?zn():d.newValue;Qn(u)&&(ft+=1,Jt(u))};return window.addEventListener("storage",l),()=>window.removeEventListener("storage",l)},[]);const i=async l=>{if(l!==Ue){a(!0);try{await F.config.patch({language:l}),Ot(l)}finally{a(!1)}}};return t.jsx(Vn.Provider,{value:{locale:n,messages:Gn[n],saving:r,setLocale:i},children:e})}function Yn(){return o.useContext(Vn)}function M(){return Yn().messages}function or(){o.useEffect(()=>{const e=()=>{const s=ft,r=++rr;F.config.get().then(a=>{s===ft&&(r<=ln||(ln=r,ar(a.language)))}).catch(()=>{})},n=()=>{document.visibilityState==="visible"&&e()};return window.addEventListener("focus",e),document.addEventListener("visibilitychange",n),()=>{window.removeEventListener("focus",e),document.removeEventListener("visibilitychange",n)}},[])}const Jn=o.createContext(null),lr={success:"border-hairline bg-surface text-og-800",warn:"border-accent/25 bg-accent-soft text-accent",error:"border-accent/25 bg-accent-soft text-accent"},cr={success:er,warn:tr,error:nr};let dr=1;function ur({children:e}){const n=M(),[s,r]=o.useState([]),a=o.useRef(new Map),i=o.useRef(new Map);o.useEffect(()=>{const c=a.current,g=i.current;return()=>{for(const v of c.values())clearTimeout(v);c.clear(),g.clear()}},[]);const l=o.useCallback(c=>{const g=a.current.get(c);g&&clearTimeout(g),a.current.delete(c)},[]),d=o.useCallback(c=>{l(c),i.current.delete(c),r(g=>g.filter(v=>v.id!==c))},[l]),u=o.useCallback((c,g)=>{l(c),a.current.set(c,setTimeout(()=>d(c),g))},[l,d]),m=o.useCallback((c,g)=>{const v=i.current.get(c)??new Set;v.add(g),i.current.set(c,v),l(c)},[l]),h=o.useCallback((c,g,v)=>{const y=i.current.get(c);y==null||y.delete(g),(!y||y.size===0)&&u(c,v)},[u]),x=o.useCallback(c=>{const g=dr++,v=c.durationMs??3e3;r(y=>[...y,{...c,id:g,durationMs:v}]),u(g,v)},[u]);return t.jsxs(Jn.Provider,{value:{show:x},children:[e,t.jsx("div",{className:"pointer-events-none fixed inset-x-4 top-4 z-[60] flex flex-col items-end gap-2",children:s.map(c=>t.jsx("div",{className:`pointer-events-auto w-full max-w-xs rounded-lg border px-4 py-3 shadow-toast ${lr[c.kind]}`,role:"status",onMouseEnter:()=>m(c.id,"hover"),onMouseLeave:()=>h(c.id,"hover",c.durationMs),onFocus:()=>m(c.id,"focus"),onBlur:g=>{g.currentTarget.contains(g.relatedTarget)||h(c.id,"focus",c.durationMs)},children:t.jsxs("div",{className:"flex items-start gap-2",children:[(()=>{const g=cr[c.kind];return t.jsx(g,{className:"mt-0.5 shrink-0",width:14,height:14})})(),t.jsxs("div",{className:"flex-1",children:[t.jsx("div",{className:"text-sm font-semibold",children:c.title}),c.body&&t.jsx("div",{className:"mt-1 whitespace-pre-line text-xs text-og-700",children:c.body})]}),t.jsx("button",{type:"button",onClick:()=>d(c.id),className:"text-current opacity-50 transition-opacity hover:opacity-100","aria-label":n.toast.dismissAriaLabel,children:"✕"})]})},c.id))})]})}function Re(){const e=o.useContext(Jn);if(!e)throw new Error("useToast must be inside <ToastProvider>");return e}const mr={sm:"max-w-md",md:"max-w-lg",lg:"max-w-2xl"},cn='input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), [href], [tabindex]:not([tabindex="-1"])',$e=[];function Ae({open:e,onClose:n,title:s,titleContent:r,children:a,footer:i,size:l="md",dismissOnBackdrop:d=!0}){const u=M(),m=o.useRef(null),h=o.useRef();h.current||(h.current=Symbol("modal"));const x=o.useRef(null),c=o.useRef(!1),g=o.useRef(n);return o.useEffect(()=>{g.current=n},[n]),o.useEffect(()=>{if(!e)return;const v=h.current;$e.push(v);const y=()=>$e[$e.length-1]===v;x.current=document.activeElement;const w=R=>{if(!y())return;if(R.key==="Escape"){g.current();return}if(R.key!=="Tab")return;const b=m.current;if(!b)return;const f=Array.from(b.querySelectorAll(cn)).filter(I=>I.offsetParent!==null||I===document.activeElement);if(f.length===0){R.preventDefault();return}const k=f[0],j=f[f.length-1],$=document.activeElement;R.shiftKey&&($===k||!b.contains($))?(R.preventDefault(),j.focus()):!R.shiftKey&&($===j||!b.contains($))&&(R.preventDefault(),k.focus())};document.addEventListener("keydown",w);const S=document.body.style.overflow;document.body.style.overflow="hidden";const A=m.current;if(A){const R=A.querySelector(cn);R==null||R.focus()}return()=>{var b,f;const R=$e.indexOf(v);R>=0&&$e.splice(R,1),document.removeEventListener("keydown",w),document.body.style.overflow=S,(f=(b=x.current)==null?void 0:b.focus)==null||f.call(b)}},[e]),e?t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-og-1000/45 px-3 sm:px-4",onMouseDown:d?v=>{c.current=v.target===v.currentTarget&&$e[$e.length-1]===h.current}:void 0,onClick:d?v=>{v.target===v.currentTarget&&c.current&&g.current()}:void 0,role:"presentation",children:t.jsxs("div",{ref:m,className:`flex w-full ${mr[l]} max-h-[90dvh] flex-col overflow-hidden rounded-lg border border-og-100 bg-surface shadow-modal`,onClick:v=>v.stopPropagation(),role:"dialog","aria-modal":"true","aria-label":s,children:[t.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-hairline px-5 py-3",children:[t.jsx("h2",{title:s,className:"min-w-0 truncate font-display text-sm font-semibold tracking-tight text-og-1000",children:r??s}),t.jsx("button",{type:"button",onClick:()=>g.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":u.common.close,children:"✕"})]}),t.jsx("div",{className:"min-h-0 flex-1 overflow-auto px-5 py-4",children:a}),i&&t.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 Xn=o.createContext(null);function fr({children:e}){const n=M(),[s,r]=o.useState(null),a=o.useRef(null),i=o.useCallback(d=>new Promise(u=>{var h;(h=a.current)==null||h.resolve(!1);const m={...d,resolve:u};a.current=m,r(m)}),[]),l=o.useCallback(d=>{const u=a.current;u&&(a.current=null,r(null),u.resolve(d))},[]);return t.jsxs(Xn.Provider,{value:i,children:[e,s&&t.jsx(Ae,{open:!0,title:s.title,onClose:()=>l(!1),size:"sm",footer:t.jsxs("div",{className:"flex justify-end gap-2",children:[t.jsx("button",{type:"button",onClick:()=>l(!1),className:"btn-secondary",children:s.cancelLabel??n.common.cancel}),t.jsx("button",{type:"button",onClick:()=>l(!0),className:"btn-primary",children:s.confirmLabel??n.common.confirm})]}),children:s.body?t.jsx("p",{className:"whitespace-pre-line text-sm text-og-700",children:s.body}):null})]})}function Zt(){const e=o.useContext(Xn);if(!e)throw new Error("useConfirm must be inside <ConfirmProvider>");return e}const ht="baxian.pendingRestart",hr=500,pr=3e4,Zn=o.createContext(null);function gr(){try{const e=localStorage.getItem(ht);if(!e)return{count:0,baselineStartedAt:null};const n=JSON.parse(e);return{count:typeof n.count=="number"?n.count:0,baselineStartedAt:typeof n.baselineStartedAt=="string"?n.baselineStartedAt:null}}catch{return{count:0,baselineStartedAt:null}}}function xr(e){try{e.count<=0?localStorage.removeItem(ht):localStorage.setItem(ht,JSON.stringify(e))}catch{}}function br({children:e}){const n=M(),s=gr(),[r,a]=o.useState(s.count),[i,l]=o.useState(s.baselineStartedAt),[d,u]=o.useState(s.count>0?"pending":"idle"),[m,h]=o.useState(),x=o.useRef(s.count),c=o.useRef(s.count>0?"pending":"idle"),g=o.useRef(0),v=o.useCallback(b=>{x.current=b,a(b)},[]),y=o.useCallback(b=>{a(f=>{const k=b(f);return x.current=k,k})},[]),w=o.useCallback(b=>{c.current=b,u(b)},[]);o.useEffect(()=>{xr({count:r,baselineStartedAt:i})},[r,i]),o.useEffect(()=>{let b=!1;(async()=>{try{const k=await F.health.get();if(b)return;l(j=>j!==null&&k.startedAt!==j?(v(0),w("idle"),null):j)}catch{}})();const f=k=>{if(k.key===ht){if(k.newValue===null){if(c.current==="restarting"&&g.current>0){v(g.current),l(null);return}v(0),l(null),c.current!=="restarting"&&w("idle");return}try{const j=JSON.parse(k.newValue);typeof j.count=="number"&&(c.current==="restarting"&&j.count>x.current&&(g.current+=j.count-x.current),v(j.count),c.current!=="restarting"&&w(j.count>0?"pending":"idle")),typeof j.baselineStartedAt=="string"?l(j.baselineStartedAt):j.baselineStartedAt===null&&l(null)}catch{}}};return window.addEventListener("storage",f),()=>{b=!0,window.removeEventListener("storage",f)}},[v,w]);const S=o.useRef(!1),A=o.useCallback(()=>{y(b=>b+1),c.current==="restarting"?g.current+=1:w("pending"),l(b=>(b!==null||S.current||(S.current=!0,(async()=>{try{const f=await F.health.get();l(k=>k??f.startedAt)}catch{}finally{S.current=!1}})()),b))},[w,y]),R=o.useCallback(async()=>{g.current=0,h(void 0),w("restarting");let b;try{b=(await F.health.get()).startedAt}catch(k){w("failed"),h(n.banner.preRestartFetchFailed(k instanceof Error?k.message:String(k)));return}try{await F.server.restart()}catch(k){if(!(k instanceof De&&k.status===409)){w("failed"),h(n.banner.restartTriggerFailed(k instanceof Error?k.message:String(k)));return}}const f=Date.now();for(;Date.now()-f<pr;){await new Promise(k=>setTimeout(k,hr));try{const k=await F.health.get();if(k.startedAt!==b){const j=g.current;g.current=0,l(j>0?k.startedAt:null),v(j),w(j>0?"pending":"idle");return}}catch{}}w("failed"),h(n.banner.restartTimeout)},[v,w,n]);return t.jsx(Zn.Provider,{value:{phase:d,count:r,error:m,flagDirty:A,triggerRestart:R},children:e})}function wt(){const e=o.useContext(Zn);if(!e)throw new Error("usePendingRestart must be used inside PendingRestartProvider");return e}const vr=[500,1e3,2e3,4e3,8e3,15e3,3e4];class es{constructor(n){ae(this,"attempts",0);ae(this,"timer",null);ae(this,"delaysMs");this.opts=n,this.delaysMs=n.delaysMs??vr}schedule(){if(this.timer||!this.shouldReconnect())return;const n=this.delaysMs[Math.min(this.attempts,this.delaysMs.length-1)];this.attempts+=1,this.timer=setTimeout(()=>{this.timer=null,this.shouldReconnect()&&this.opts.reconnect()},n)}cancel(){this.timer&&(clearTimeout(this.timer),this.timer=null)}reset(){this.attempts=0}shouldReconnect(){return this.opts.shouldReconnect?this.opts.shouldReconnect():!0}}function ts(e){return Array.from(new TextEncoder().encode(e)).map(n=>n.toString(16).padStart(2,"0")).join("")}function ns(e){return`${location.protocol==="https:"?"wss":"ws"}://${location.host}${e}`}const ss=(e,n)=>n&&n.length>0?new WebSocket(e,n):new WebSocket(e);let dn=0;function wr(){dn++;const e=Math.random().toString(36).slice(2,8);return`sub-${Date.now().toString(36)}-${dn}-${e}`}function yr(){return ns("/api/stream")}class jr{constructor(n={}){ae(this,"wsUrl");ae(this,"wsFactory");ae(this,"tokenProvider");ae(this,"ws",null);ae(this,"subs",new Map);ae(this,"snapshotPending",new Set);ae(this,"preSubscribeQueue",new Map);ae(this,"outbox",[]);ae(this,"reconnectScheduler");ae(this,"explicitlyClosed",!1);this.wsUrl=n.wsUrl??yr(),this.wsFactory=n.wsFactory??ss,this.tokenProvider=n.tokenProvider??Kt,this.reconnectScheduler=new es({reconnect:()=>this.openSocket(),shouldReconnect:()=>!this.explicitlyClosed&&this.subs.size>0})}subscribe(n){const s=wr(),r={subscriberId:s,agentId:n.agentId,mode:n.mode,onSnapshot:n.onSnapshot,onData:n.onData,onError:n.onError,onSessionGone:n.onSessionGone};return this.subs.set(s,r),this.snapshotPending.add(s),this.preSubscribeQueue.set(s,[]),this.ensureSocket(),this.wsSendOrQueue({op:"subscribe",subscriberId:s,agentId:n.agentId,mode:n.mode}),{subscriberId:s,unsubscribe:()=>this.unsubscribe(s)}}send(n,s){if(this.subs.has(n)){if(this.snapshotPending.has(n)){this.outbox.push({op:"input",subscriberId:n,data:s});return}this.wsSendOrQueue({op:"input",subscriberId:n,data:s})}}resize(n,s,r){const a=this.subs.get(n);a&&(a.lastSize={cols:s,rows:r},!this.snapshotPending.has(n)&&this.wsSendOrQueue({op:"resize",subscriberId:n,cols:s,rows:r}))}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(n){this.subs.has(n)&&(this.subs.delete(n),this.snapshotPending.delete(n),this.preSubscribeQueue.delete(n),this.wsSendOrQueue({op:"unsubscribe",subscriberId:n}),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 n=this.tokenProvider(),s=n?[`baxian.token.${ts(n)}`]:void 0;let r;try{r=this.wsFactory(this.wsUrl,s)}catch(a){console.warn("[pane-stream] WebSocket constructor threw:",a),this.scheduleReconnect();return}this.ws=r,r.onopen=()=>{if(r!==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{r.send(JSON.stringify({op:"subscribe",subscriberId:i.subscriberId,agentId:i.agentId,mode:i.mode}))}catch(l){console.warn("[pane-stream] resubscribe send failed:",l)}}const a=this.outbox;this.outbox=[];for(const i of a)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{r.send(JSON.stringify(i))}catch(l){console.warn("[pane-stream] outbox flush failed:",l)}}},r.onmessage=a=>{if(r!==this.ws)return;let i;try{const l=typeof a.data=="string"?a.data:String(a.data);i=JSON.parse(l)}catch{return}this.handleMessage(i)},r.onclose=()=>{r===this.ws&&(this.ws=null,!this.explicitlyClosed&&this.subs.size!==0&&this.scheduleReconnect())},r.onerror=()=>{}}scheduleReconnect(){this.reconnectScheduler.schedule()}wsSendOrQueue(n){if(this.ws&&this.ws.readyState===WebSocket.OPEN)try{this.ws.send(JSON.stringify(n));return}catch(s){console.warn("[pane-stream] send failed, will queue:",s)}this.outbox.push(n)}handleMessage(n){var s,r;switch(n.type){case"snapshot":this.handleSnapshot(n);break;case"subscribed":this.handleSubscribed(n);break;case"data":this.dispatch(n);break;case"session_gone":for(const a of[...this.subs.values()])a.agentId===n.agentId&&((s=a.onSessionGone)==null||s.call(a));break;case"error":{if(n.subscriberId){const a=this.subs.get(n.subscriberId);(r=a==null?void 0:a.onError)==null||r.call(a,{code:n.code,message:n.message})}else console.warn("[pane-stream] connection-level error:",n.code,n.message);break}}}handleSnapshot(n){const s=this.subs.get(n.subscriberId);s&&s.onSnapshot({cols:n.cols,rows:n.rows,data:n.data})}handleSubscribed(n){const s=this.subs.get(n.subscriberId);if(!s)return;s.snapshotSeq=n.snapshotSeq,s.lastSize||(s.lastSize={cols:n.cols,rows:n.rows}),this.snapshotPending.delete(n.subscriberId);const r=this.preSubscribeQueue.get(n.subscriberId);if(this.preSubscribeQueue.delete(n.subscriberId),r)for(const a of r)a.seq>n.snapshotSeq&&s.onData(a.data);s.mode==="full"&&s.lastSize&&this.wsSendOrQueue({op:"resize",subscriberId:s.subscriberId,cols:s.lastSize.cols,rows:s.lastSize.rows}),this.flushOutboxForSub(n.subscriberId)}flushOutboxForSub(n){if(this.outbox.length===0||!this.ws||this.ws.readyState!==WebSocket.OPEN)return;const s=[];for(const r of this.outbox)if("subscriberId"in r&&r.subscriberId===n&&r.op!=="subscribe")try{this.ws.send(JSON.stringify(r))}catch(a){console.warn("[pane-stream] flushOutboxForSub send failed:",a)}else s.push(r);this.outbox=s}dispatch(n){for(const s of this.subs.values())if(s.agentId===n.agentId)if(this.snapshotPending.has(s.subscriberId)){const r=this.preSubscribeQueue.get(s.subscriberId);r&&r.push({seq:n.seq,data:n.data})}else s.onData(n.data)}}let St=null;function Tt(){return St||(St=new jr),St}function kr(e){const{agentId:n,mode:s}=e,r=o.useRef(null),a=o.useRef({onSnapshot:e.onSnapshot,onData:e.onData,onError:e.onError,onSessionGone:e.onSessionGone});a.current={onSnapshot:e.onSnapshot,onData:e.onData,onError:e.onError,onSessionGone:e.onSessionGone},o.useEffect(()=>{const u=Tt().subscribe({agentId:n,mode:s,onSnapshot:m=>a.current.onSnapshot(m),onData:m=>a.current.onData(m),onError:m=>{var h,x;return(x=(h=a.current).onError)==null?void 0:x.call(h,m)},onSessionGone:()=>{var m,h;return(h=(m=a.current).onSessionGone)==null?void 0:h.call(m)}});return r.current=u.subscriberId,()=>{r.current=null,u.unsubscribe()}},[n,s]);const i=o.useCallback(d=>{const u=r.current;u&&Tt().send(u,d)},[]),l=o.useCallback((d,u)=>{const m=r.current;m&&Tt().resize(m,d,u)},[]);return{send:i,resize:l}}const Nr=[{key:"up",path:"M12 5l-6 6m6-6l6 6m-6-6v14"},{key:"down",path:"M12 19l6-6m-6 6l-6-6m6 6V5"},{key:"left",path:"M5 12l6-6m-6 6l6 6m-6-6h14"},{key:"right",path:"M19 12l-6-6m6 6l-6 6m6-6H5"}],at=Object.fromEntries(Nr.map(e=>[e.key,e]));function it({arrow:e,ariaLabel:n,onPress:s}){return t.jsx("button",{type:"button","aria-label":n,"data-arrow":e.key,onMouseDown:r=>r.preventDefault(),onClick:()=>s(e.key),className:"flex h-8 w-8 items-center justify-center rounded border border-hairline bg-surface text-og-700 transition-colors hover:bg-og-50 hover:text-og-1000 active:bg-og-200",children:t.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:t.jsx("path",{d:e.path})})})}function Sr({onKey:e,onEscape:n,className:s}){const r=M();return t.jsxs("div",{role:"group","aria-label":r.terminal.keyPadAriaLabel,className:s??"flex flex-none items-center justify-center gap-1 border-t border-hairline bg-page px-3 py-2",children:[n&&t.jsx("button",{type:"button","aria-label":r.terminal.escKeyAriaLabel,"data-key":"escape",onMouseDown:a=>a.preventDefault(),onClick:n,className:"mr-2 flex h-8 items-center justify-center rounded border border-hairline bg-surface px-2.5 font-mono text-xs text-og-700 transition-colors hover:bg-og-50 hover:text-og-1000 active:bg-og-200",children:"ESC"}),t.jsx(it,{arrow:at.left,ariaLabel:r.terminal.arrowAriaLabel(r.terminal.arrowLabel.left),onPress:e}),t.jsx(it,{arrow:at.up,ariaLabel:r.terminal.arrowAriaLabel(r.terminal.arrowLabel.up),onPress:e}),t.jsx(it,{arrow:at.down,ariaLabel:r.terminal.arrowAriaLabel(r.terminal.arrowLabel.down),onPress:e}),t.jsx(it,{arrow:at.right,ariaLabel:r.terminal.arrowAriaLabel(r.terminal.arrowLabel.right),onPress:e})]})}const Tr=Math.floor(vt/1024/1024);function Rr({agentId:e,className:n}){const s=M(),r=o.useRef(null),[a,i]=o.useState(!1),{show:l}=Re(),d=async u=>{var h;const m=(h=u.target.files)==null?void 0:h[0];if(u.target.value="",!!m){if(m.size>vt){l({kind:"error",title:s.createTask.imageTooLargeToastTitle,body:s.imageUpload.tooLargeBody(Tr)});return}i(!0);try{await F.agents.uploadImage(e,m),l({kind:"success",title:s.imageUpload.insertedTitle,body:s.imageUpload.insertedBody})}catch(x){const c=x instanceof De||x instanceof Error?x.message:String(x);l({kind:"error",title:s.imageUpload.uploadFailedTitle,body:c})}finally{i(!1)}}};return t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button","aria-label":s.imageUpload.uploadAriaLabel,disabled:a,onMouseDown:u=>u.preventDefault(),onClick:()=>{var u;return(u=r.current)==null?void 0:u.click()},className:n??"flex h-8 w-8 items-center justify-center rounded border border-hairline bg-surface text-og-700 transition-colors hover:bg-og-50 hover:text-og-1000 active:bg-og-200 disabled:cursor-not-allowed disabled:opacity-50",children:t.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:[t.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),t.jsx("circle",{cx:"9",cy:"9",r:"2"}),t.jsx("path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"})]})}),t.jsx("input",{ref:r,type:"file",accept:"image/*",className:"hidden",onChange:d})]})}const Cr={up:"A",down:"B",right:"C",left:"D"};function Ar(e,n){return(n?"\x1BO":"\x1B[")+Cr[e]}const un=18,Lr=250,Pr=256*1024,mn="#fdfdfd",$r='ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',Er={background:mn,foreground:"#474c55",cursor:"#1348dc",cursorAccent:mn,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"},Dr=/\x1b\[(?:\?[\d;]*c|>[\d;]*c|\??\d+;\d+R|\d+n)/g;function Ir(e){return e.replace(Dr,"")}const Fr=1024*1024;function Br(e){const n=e.indexOf(";");if(n===-1)return null;const s=e.slice(n+1);if(s.length===0||s==="?"||s.length>Fr)return null;try{const r=atob(s),a=new Uint8Array(r.length);for(let i=0;i<r.length;i++)a[i]=r.charCodeAt(i);return new TextDecoder().decode(a)}catch{return null}}function ze({agentId:e,mode:n,interactive:s=!1,maxLines:r,className:a,autoFocus:i=!0,deferFullUntilFocus:l=!1,arrowKeys:d=!1}){const u=M(),m=o.useRef(null),h=o.useRef(null),x=o.useRef(null),c=o.useRef(null),g=o.useRef(!1),v=o.useRef(""),y=o.useRef([]),w=o.useRef(0),S=o.useRef(null),A=o.useRef(null),R=o.useRef(null),b=o.useRef(Promise.resolve()),f=o.useRef(0),[k,j]=o.useState(null),[$,I]=o.useState(!1),K=`${e}\0${n}\0${l?"1":"0"}`,[C,B]=o.useState({key:K,active:!1}),W=C.key===K&&C.active,J=n==="full"&&l,Z=J&&!W?"preview":n,ee=s&&Z==="full",te=(L,H)=>H.length===0?Promise.resolve():new Promise(_=>{try{L.write(H,()=>_())}catch(ue){console.warn("[pane-terminal] write failed:",ue),_()}}),X=Z==="preview",ie=()=>{if(!X)return;const L=m.current,H=h.current;if(!L||!H||L.clientHeight<=0)return;const ue=(H.buffer.active.cursorY+1)*un;L.scrollTop=Math.max(0,ue-L.clientHeight)},N=()=>{if(!X||R.current!==null)return;let L=!1;const H=requestAnimationFrame(()=>{L=!0,R.current=null,ie()});L||(R.current=H)},G=(L,H)=>{b.current=b.current.then(async()=>{const _=h.current;if(!(!_||H!==f.current))try{await L(_),ee&&_.scrollToBottom(),N()}catch(ue){console.warn("[pane-terminal] terminal task failed:",ue)}}).catch(_=>{console.warn("[pane-terminal] write chain failed:",_)})},se=(L,H)=>{G(_=>te(_,L),H)},he=()=>{S.current!==null&&(cancelAnimationFrame(S.current),S.current=null),A.current!==null&&(clearTimeout(A.current),A.current=null)},O=()=>{he(),y.current=[],w.current=0},oe=()=>{he();const L=y.current;L.length!==0&&(y.current=[],w.current=0,se(L.join(""),f.current))},ne=L=>{if(L.length!==0){if(y.current.push(L),w.current+=L.length,w.current>=Pr){oe();return}S.current===null&&(S.current=requestAnimationFrame(oe)),A.current===null&&(A.current=setTimeout(oe,Lr))}},{send:be,resize:ye}=kr({agentId:e,mode:Z,onSnapshot:({cols:L,rows:H,data:_})=>{if(h.current)try{const pe=f.current+1;f.current=pe,O(),G(async we=>{var D;we.reset(),ee?((D=c.current)==null||D.call(c),await te(we,_)):(L>0&&H>0&&we.resize(L,H),await te(we,_))},pe)}catch(pe){console.warn("[pane-terminal] snapshot write failed:",pe)}},onData:L=>{ne(L)},onError:L=>j(`${L.code}: ${L.message}`),onSessionGone:()=>I(!0)});o.useEffect(()=>{j(null),I(!1)},[e,Z]),o.useEffect(()=>{v.current=""},[K]),o.useEffect(()=>{if(Z!=="full")return;const L=v.current;L.length!==0&&(v.current="",be(L))},[be,Z]);const je=o.useCallback(()=>{!s||!J||W||(g.current=!0,B({key:K,active:!0}))},[K,W,s,J]),fe=o.useCallback(L=>{const H=Ir(L);if(H.length!==0){if(J&&(!W||v.current.length>0)){v.current+=H,je();return}be(H)}},[je,W,be,J]);o.useEffect(()=>{const L=m.current;if(!L)return;let H=!1;const _=new _s.Terminal({cursorBlink:s,disableStdin:!s,theme:Er,fontFamily:$r,fontSize:13,lineHeight:1.4,scrollback:Z==="full"?5e3:1e3}),ue=new Us.FitAddon;_.loadAddon(ue),_.open(L),h.current=_,x.current=ue;const pe=X?_.onRender(()=>N()):null;if(s&&(i||g.current)){g.current=!1;try{_.focus()}catch{}}s&&(_.onData(fe),Z==="full"&&_.parser.registerOscHandler(52,me=>{var ce;const V=Br(me);return V!==null&&((ce=navigator.clipboard)==null||ce.writeText(V).catch(()=>{})),!0}));const we=()=>L.clientWidth>0&&L.clientHeight>0,D=(me=!1)=>{if(!we())return!1;const V=_.cols,ce=_.rows;try{ue.fit()}catch{return!1}return ee&&_.scrollToBottom(),_.cols>0&&_.rows>0&&(me||_.cols!==V||_.rows!==ce)&&ye(_.cols,_.rows),!0};c.current=ee?()=>D(!0):null;let q=null,p=null,P=null,T=0;const U=()=>{q||(q=new ResizeObserver(()=>{p&&clearTimeout(p),p=setTimeout(()=>{p=null,ee?D():X&&N()},100)}),q.observe(L))},z=()=>{P=requestAnimationFrame(()=>{if(P=null,!H){if(!ee){X&&(U(),N());return}if(D(!0)){U();return}if(T++<5){z();return}U()}})};return z(),()=>{H=!0,P!==null&&cancelAnimationFrame(P),S.current!==null&&(cancelAnimationFrame(S.current),S.current=null),A.current!==null&&(clearTimeout(A.current),A.current=null),R.current!==null&&(cancelAnimationFrame(R.current),R.current=null),f.current++,y.current=[],w.current=0,b.current=Promise.resolve(),p&&clearTimeout(p),q==null||q.disconnect(),pe==null||pe.dispose(),h.current=null,x.current=null,c.current=null;try{_.dispose()}catch(me){console.warn("[pane-terminal] dispose failed:",me)}}},[e,i,ee,fe,s,Z,ye]);const ve=()=>{var L;if(s){je();try{(L=h.current)==null||L.focus()}catch{}}};o.useEffect(()=>{if(s)return;const L=m.current;if(!L)return;const H=_=>{_.stopPropagation()};return L.addEventListener("wheel",H,{capture:!0,passive:!0}),()=>L.removeEventListener("wheel",H,{capture:!0})},[s]);const E=r&&r>0?{maxHeight:`${r*un}px`}:void 0;return t.jsxs("div",{className:a??"flex flex-col h-full w-full min-h-0 bg-term",children:[(k||$)&&t.jsx("div",{className:"border-b border-accent/25 bg-accent-soft px-3 py-1 font-mono text-xs text-accent",children:$?u.terminal.sessionEnded:k}),t.jsx("div",{className:"flex flex-1 min-h-0 px-2 py-1.5",style:E,children:t.jsx("div",{ref:m,className:"flex-1 min-h-0 overflow-hidden",onMouseDown:ve})}),s&&d&&t.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:[t.jsx("div",{className:"flex items-center",children:t.jsx(Rr,{agentId:e})}),t.jsx(Sr,{className:"flex items-center justify-center gap-1",onKey:L=>{var _,ue;const H=!!((ue=(_=h.current)==null?void 0:_.modes)!=null&&ue.applicationCursorKeysMode);fe(Ar(L,H))},onEscape:()=>fe("\x1B")})]})]})}function Mr(){const[e,n]=o.useState([]),[s,r]=o.useState(!0),[a,i]=o.useState(null),l=o.useCallback(async()=>{r(!0);try{n(await F.pets.list()),i(null)}catch(d){i(d instanceof Error?d.message:String(d))}finally{r(!1)}},[]);return o.useEffect(()=>{l()},[l]),{pets:e,loading:s,error:a,refresh:l}}const Rt=new Map,Ct=new Map;function Or(e){const[n,s]=o.useState(()=>e?Ct.get(e)??null:null);return o.useEffect(()=>{if(!e){s(null);return}const r=Ct.get(e);if(s(r??null),r)return;let a=!1,i=Rt.get(e);return i||(i=F.pets.fetchSpritesheet(e).then(l=>{const d=URL.createObjectURL(l);return Ct.set(e,d),d}),Rt.set(e,i)),i.then(l=>{a||s(l)},()=>{a||s(null),Rt.delete(e)}),()=>{a=!0}},[e]),n}const Hr=[{state:"idle",row:0,durations:[280,110,110,140,140,320]},{state:"running-right",row:1,durations:[120,120,120,120,120,120,120,220]},{state:"running-left",row:2,durations:[120,120,120,120,120,120,120,220]},{state:"waving",row:3,durations:[140,140,140,280]},{state:"jumping",row:4,durations:[140,140,140,140,280]},{state:"failed",row:5,durations:[140,140,140,140,140,140,140,240]},{state:"waiting",row:6,durations:[150,150,150,150,150,260]},{state:"running",row:7,durations:[120,120,120,120,120,220]},{state:"review",row:8,durations:[150,150,150,150,150,280]}];function _r(e,n){if(n)return 3;switch(e){case"working":return 7;case"waiting":return 6;case"pending":return 6;case"error":return 5;case"idle":return 0;case"unknown":return 0;default:return 0}}const en=36,Ur=en/qn,qr=Un*Ur;function Wr(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function rs({petId:e,status:n,bootstrapping:s=!1,label:r,displayHeight:a=en,className:i}){const l=Or(e),d=_r(n,s),u=Hr[d],m=u.durations.length,[h,x]=o.useState(0),c=a/qn,g=Un*c;return o.useEffect(()=>{if(x(0),!l||m<=1||Wr())return;let v,y=0;const w=()=>{y=(y+1)%m,x(y),v=setTimeout(w,u.durations[y])};return v=setTimeout(w,u.durations[0]),()=>clearTimeout(v)},[l,d,m,u]),l?t.jsx("span",{role:"img","aria-label":r,title:r,"data-pet-row":d,"data-pet-col":h,className:["inline-block shrink-0",i].filter(Boolean).join(" "),style:{width:`${g}px`,height:`${a}px`,backgroundImage:`url(${l})`,backgroundRepeat:"no-repeat",backgroundSize:`${zs*c}px ${Ks*c}px`,backgroundPositionX:`${-(h*g)}px`,backgroundPositionY:`${-(d*a)}px`,imageRendering:"pixelated"}}):t.jsx("span",{className:"pill pill-idle",title:r,children:r})}class dt extends Error{constructor(n){super(n),this.name="PetPackageError"}}const ot=e=>e.split("/").pop()??e;function Gr(e){return typeof e.text=="function"?e.text():new Promise((n,s)=>{const r=new FileReader;r.onerror=()=>s(r.error??new Error("file read failed")),r.onload=()=>n(typeof r.result=="string"?r.result:""),r.readAsText(e)})}async function Qr(e){const n=Xt(),s=e.find(d=>ot(d.name)==="pet.json"||ot(d.webkitRelativePath||"")==="pet.json");if(!s)throw new dt(n.pet.missingManifest);let r;try{r=JSON.parse(await Gr(s))}catch{throw new dt(n.pet.manifestParseFailed)}const a=r&&typeof r=="object"&&typeof r.spritesheetPath=="string"?r.spritesheetPath:"",i=a?ot(a):"",l=(i?e.find(d=>ot(d.name)===i):void 0)??e.find(d=>/\.(png|webp)$/i.test(d.name));if(!l)throw new dt(n.pet.missingSpritesheet);return{manifest:r,spritesheet:l}}function zr({children:e,style:n}){const s=o.useRef(null),[r,a]=o.useState(typeof IntersectionObserver>"u");return o.useEffect(()=>{if(r||typeof IntersectionObserver>"u")return;const i=s.current;if(!i)return;const l=new IntersectionObserver(d=>{d.some(u=>u.isIntersecting)&&(a(!0),l.disconnect())});return l.observe(i),()=>l.disconnect()},[r]),t.jsx("span",{ref:s,className:"inline-block shrink-0",style:n,children:r?e:null})}function Kr({agentId:e,currentPetId:n,onClose:s}){const r=M(),{show:a}=Re(),i=Zt(),{pets:l,loading:d,refresh:u}=Mr(),[m,h]=o.useState(!!n),[x,c]=o.useState(n),[g,v]=o.useState(!1),y=o.useRef(null);o.useEffect(()=>{c(n)},[n]),o.useEffect(()=>{const f=y.current;f&&(f.setAttribute("webkitdirectory",""),f.setAttribute("directory",""))},[m]);const w=f=>f instanceof De||f instanceof Error?f.message:String(f),S=async f=>{if(h(f),!f&&x){v(!0);try{await F.agents.setPet(e,null),c(null),a({kind:"success",title:r.pet.disabledTitle})}catch(k){a({kind:"error",title:r.pet.disableFailedTitle,body:w(k)}),h(!0)}finally{v(!1)}}},A=async f=>{v(!0);try{await F.agents.setPet(e,f),c(f),a({kind:"success",title:r.pet.selectedTitle})}catch(k){a({kind:"error",title:r.pet.selectFailedTitle,body:w(k)})}finally{v(!1)}},R=async(f,k)=>{if(await i({title:r.pet.deleteConfirmTitle(k),body:r.pet.deleteConfirmBody,confirmLabel:r.common.delete})){v(!0);try{await F.pets.remove(f),await u(),a({kind:"success",title:r.pet.deletedTitle(k)})}catch(j){a({kind:"error",title:r.pet.deleteFailedTitle,body:w(j)})}finally{v(!1)}}},b=async f=>{const k=f.target.files?Array.from(f.target.files):[];if(f.target.value="",!!k.length){v(!0);try{const{manifest:j,spritesheet:$}=await Qr(k);await F.pets.create(j,$),await u(),a({kind:"success",title:r.pet.uploadedTitle})}catch(j){const $=j instanceof dt?j.message:w(j);a({kind:"error",title:r.pet.uploadFailedTitle,body:$})}finally{v(!1)}}};return t.jsx(Ae,{open:!0,onClose:s,title:"Agent Pet",size:"md",children:t.jsxs("div",{className:"space-y-4",children:[t.jsxs("label",{className:"flex items-center gap-2 text-sm text-og-1000",children:[t.jsx("input",{type:"checkbox",checked:m,disabled:g,onChange:f=>void S(f.target.checked)}),r.pet.enableLabel]}),m?t.jsxs(t.Fragment,{children:[t.jsxs("div",{children:[t.jsx("button",{type:"button",onClick:()=>{var f;return(f=y.current)==null?void 0:f.click()},disabled:g,className:"btn-secondary",children:r.pet.uploadButton}),t.jsx("input",{ref:y,type:"file","aria-label":r.pet.uploadInputAriaLabel,className:"hidden",onChange:f=>void b(f)}),t.jsx("p",{className:"mt-1 text-xs text-og-400",children:r.pet.uploadDirHint})]}),d?t.jsx("p",{className:"text-sm text-og-500",children:r.common.loading}):l.length===0?t.jsx("p",{className:"text-sm text-og-500",children:r.pet.emptyState}):t.jsx("ul",{className:"grid grid-cols-2 gap-2",children:l.map(f=>{const k=f.id===x;return t.jsxs("li",{className:`flex items-center gap-2 rounded-md border p-2 ${k?"border-accent bg-accent-soft/40":"border-hairline"}`,children:[t.jsx(zr,{style:{width:`${qr}px`,height:`${en}px`},children:t.jsx(rs,{petId:f.id,status:"idle",label:f.displayName})}),t.jsxs("button",{type:"button",onClick:()=>void A(f.id),disabled:g||k,title:f.description||f.displayName,className:"min-w-0 flex-1 truncate text-left text-sm text-og-1000 hover:text-accent-hover disabled:cursor-default",children:[f.displayName,k&&t.jsx("span",{className:"ml-1 text-xs text-accent",children:r.pet.currentMarker})]}),t.jsx("button",{type:"button","aria-label":r.pet.deleteAriaLabel(f.displayName),onClick:()=>void R(f.id,f.displayName),disabled:g,className:"shrink-0 text-xs text-accent hover:underline disabled:opacity-50",children:r.common.delete})]},f.id)})})]}):t.jsx("p",{className:"text-xs text-og-500",children:r.pet.enableHint})]})})}const At={unknown:"pill pill-idle",idle:"pill pill-idle",pending:"pill pill-warn",working:"pill pill-live",waiting:"pill pill-review",error:"pill pill-warn"},Vr=72;function as(e){var n;return!!((n=e.binding)!=null&&n.creationToken)&&!e.binding.paneId&&e.binding.status!=="awaiting_human"&&e.reason!=="PENDING_HUMAN"}function Yr(e,n){var s,r,a;return e.tmuxSessionStatus==="unreachable"?{kind:"alert",label:n.sessionStatus.unreachable,cls:"pill pill-danger"}:as(e)?{kind:"runtime",label:n.bootstrappingBadge,cls:"pill pill-review"}:e.tmuxSessionStatus==="absent"?{kind:"alert",label:n.sessionStatus.absent,cls:"pill pill-warn"}:e.runtimeStatus==="error"?{kind:"alert",label:n.runtimeStatus.error,cls:At.error}:((s=e.binding)==null?void 0:s.status)==="awaiting_human"?{kind:"alert",label:n.heldBadge,cls:"pill pill-warn",title:e.binding.awaitingReason??n.heldDefaultReason}:(a=(r=e.binding)==null?void 0:r.needInput)!=null&&a.at?{kind:"alert",label:n.needInputBadge,cls:"pill pill-warn",title:n.needInputTitle(new Date(e.binding.needInput.at).toLocaleString())}:e.runtimeStatus==="pending"?{kind:"alert",label:n.runtimeStatus.pending,cls:At.pending}:{kind:"runtime",label:n.runtimeStatus[e.runtimeStatus],cls:At[e.runtimeStatus]}}function Jr(e,n){const s=Yr(e,n);if(!e.stale)return{...s,stale:!1};const r=n.staleTitle(e.observedAt?new Date(e.observedAt).toLocaleString():void 0);return{...s,stale:!0,title:s.title?`${s.title} · ${r}`:r}}function is({agent:e,projectId:n,role:s,runtime:r,model:a,onDeleted:i,pendingRestart:l=!1,terminalLoading:d=!1,showTaskBinding:u=!0,terminalMode:m="activity-preview",active:h,onActivate:x}){var ce,xe,Le,Be,We,nt,st;const c=M(),[g,v]=o.useState(!1),[y,w]=o.useState(null),{show:S}=Re(),A=Zt(),{flagDirty:R}=wt(),[b,f]=o.useState(!1),[k,j]=o.useState(null),[$,I]=o.useState(!1),[K,C]=o.useState(!1),[B,W]=o.useState(!1),[J,Z]=o.useState(!1),[ee,te]=o.useState(!1),[X,ie]=o.useState(!1),N=(ce=e.binding)==null?void 0:ce.taskId,G=((xe=e.binding)==null?void 0:xe.status)==="awaiting_human",se=(Be=(Le=e.binding)==null?void 0:Le.needInput)==null?void 0:Be.at,he=G&&((We=e.binding)==null?void 0:We.awaitingPhase)==="greeting_failed",O=as(e),oe=O&&e.tmuxSessionStatus!=="present",ne=Jr(e,c.agents),be=O?c.agents.bootstrappingBadge:c.agents.runtimeStatus[e.runtimeStatus],ye=m==="activity-preview"&&!oe&&(e.runtimeStatus==="working"||e.runtimeStatus==="pending"),je=m==="embedded-full",fe=je&&typeof x=="function",ve=fe&&h===!0,E=d||l||oe,L=d?c.agents.agentStatusLoading:l?c.agents.terminalNeedsRestart:c.agents.bootstrappingTerminalDisabled,H=Bn(r,a),_=async()=>{v(!0),w(null);try{await F.agents.stop(e.id)}catch(Q){w(Q instanceof Error?Q.message:String(Q))}finally{v(!1)}},ue=async()=>{if(!(!N||!await A({title:c.agents.confirmReReviewTitle,body:c.agents.confirmReReviewBody(N),confirmLabel:c.agents.confirmReReviewLabel}))){W(!0);try{const ge=await F.tasks.review(N),jt=ge.phase==="spec"?ge.specReviewRound??0:ge.reviewRound;S({kind:"success",title:c.agents.reReviewStarted(jt)})}catch(ge){S({kind:"error",title:c.agents.reReviewStartFailed,body:ge instanceof Error?ge.message:String(ge)})}finally{W(!1)}}},pe=async()=>{te(!0);try{(await F.projects.bootstrap(n)).ok?S({kind:"success",title:c.agents.retryBootstrapSucceededTitle,body:c.agents.retryBootstrapSucceededBody}):S({kind:"warn",title:c.agents.retryBootstrapStillFailingTitle,body:c.agents.retryBootstrapStillFailingBody})}catch(Q){S({kind:"error",title:c.agents.retryBootstrapFailedTitle,body:Q instanceof Error?Q.message:String(Q)})}finally{te(!1)}},we=async()=>{if(await A({title:c.agents.resumeConfirmTitle(e.id),body:he?c.agents.resumeGreetingBody:c.agents.resumeDefaultBody,confirmLabel:c.agents.resume})){Z(!0);try{if(he){e.tmuxSessionStatus==="present"?await F.projects.restartRepl(n,e.id):await F.projects.retryAgent(n,e.id),S({kind:"success",title:c.agents.regreetingStartedTitle(e.id),body:c.agents.regreetingStartedBody});return}const ge=await F.projects.resumeAgent(n,e.id);S({kind:"success",title:c.agents.resumedTitle(e.id),body:ge.releasedBinding?c.agents.resumedReleasedBody:c.agents.resumedKeptBody})}catch(ge){S({kind:"error",title:c.agents.resumeFailedTitle,body:ge instanceof Error?ge.message:String(ge)})}finally{Z(!1)}}},D=async()=>{I(!0);try{await F.agents.compact(e.id),S({kind:"success",title:c.agents.compactSentTitle(e.id)})}catch(Q){S({kind:"error",title:c.agents.compactFailedTitle,body:Q instanceof Error?Q.message:String(Q)})}finally{I(!1)}},q=async()=>{if(await A({title:c.agents.clearConfirmTitle(e.id),body:c.agents.clearConfirmBody,confirmLabel:c.agents.clearConfirmLabel})){C(!0);try{await F.agents.clear(e.id),S({kind:"success",title:c.agents.clearSentTitle(e.id)})}catch(Q){S({kind:"error",title:c.agents.clearFailedTitle,body:Q instanceof Error?Q.message:String(Q)})}finally{C(!1)}}},p=async()=>{if(await A({title:c.agents.deleteConfirmTitle(e.id),body:c.agents.deleteConfirmBody,confirmLabel:c.common.delete})){f(!0),j(null);try{const Q=await F.projects.deleteAgent(n,e.id);Q!=null&&Q.restartRequired&&R();const ge=(Q==null?void 0:Q.removed)??[e.id];if(ge.length>1){const jt=ge.filter(Fs=>Fs!==e.id).join(", ");S({kind:"warn",title:c.agents.deletedWithPairTitle(e.id),body:c.agents.deletedWithPairBody(jt)})}else S({kind:"success",title:c.agents.deletedTitle(e.id)});i==null||i()}catch(Q){j(Q instanceof Error?Q.message:String(Q))}finally{f(!1)}}},P=fe&&!E&&!ve,T=["card relative flex h-full min-w-0 flex-col overflow-visible p-4",ve?"ring-2 ring-accent":""].filter(Boolean).join(" "),U=["mb-3 flex items-start justify-between gap-2",e.petId?"pr-28":""].filter(Boolean).join(" "),z=["mb-2 mt-3 h-80 min-h-0 overflow-hidden border border-hairline bg-surface",P?"cursor-pointer":""].filter(Boolean).join(" "),me=P?()=>x==null?void 0:x():void 0,V=P?Q=>{(Q.key==="Enter"||Q.key===" ")&&(Q.preventDefault(),x==null||x())}:void 0;return t.jsxs("div",{className:T,"data-agent-card":fe?e.id:void 0,children:[e.petId&&t.jsx("div",{className:"absolute -top-4 right-7 z-10",children:t.jsx(rs,{petId:e.petId,status:e.runtimeStatus,bootstrapping:O,label:be,displayHeight:Vr})}),t.jsxs("div",{className:U,children:[t.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[t.jsx("span",{className:"shrink-0 font-mono text-xs font-medium tracking-[0.05em] text-og-500",children:s==="qa"?"QA":s==="research"?"Research":"Dev"}),t.jsx("span",{className:"min-w-0 truncate whitespace-nowrap font-display text-sm font-semibold text-og-1000",title:Mn(e.id,r,a),children:e.id}),H&&t.jsxs("span",{className:"hidden shrink-0 whitespace-nowrap text-xs text-og-400 sm:inline",title:H,children:["(",H,")"]})]}),(!e.petId||ne.kind==="alert"||ne.stale)&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:ne.stale?`${ne.cls} pill--stale shrink-0`:`${ne.cls} shrink-0`,title:ne.title,children:ne.label}),ne.stale&&t.jsx("span",{className:"sr-only",children:ne.title})]})]}),oe&&t.jsx("div",{className:"mb-2 rounded-md border border-accent-soft bg-accent-soft/40 px-2.5 py-2 text-xs text-accent",children:c.agents.bootstrappingNotice}),G&&t.jsxs("div",{className:"mb-2 rounded-md border border-accent/25 bg-accent-soft/60 px-2.5 py-2 text-xs text-accent",children:[t.jsx("span",{className:"font-mono",children:(nt=e.binding)==null?void 0:nt.awaitingPhase}),((st=e.binding)==null?void 0:st.awaitingReason)&&t.jsxs("span",{children:[" · ",e.binding.awaitingReason]})]}),!O&&e.runtimeStatus==="pending"&&t.jsxs("div",{className:"mb-2 space-y-1 rounded-md border border-accent/25 bg-accent-soft/60 px-2.5 py-2 text-xs text-accent",children:[t.jsx("div",{className:"font-medium",children:c.agents.awaitingHumanIntervention}),t.jsxs("div",{children:[c.agents.openTerminalPrefix,t.jsx(_e,{to:`/terminal/${e.id}`,className:"text-accent hover:text-accent-hover underline",children:c.agents.terminal}),c.agents.openTerminalSuffix]})]}),se&&t.jsxs("div",{className:"mb-2 space-y-1 rounded-md border border-accent/25 bg-accent-soft/60 px-2.5 py-2 text-xs text-accent",children:[t.jsx("div",{className:"font-medium",children:c.agents.needInputNoticeTitle}),t.jsxs("div",{children:[c.agents.needInputPrefix,t.jsx(_e,{to:`/terminal/${e.id}`,className:"text-accent hover:text-accent-hover underline",children:c.agents.terminal}),c.agents.needInputSuffix]})]}),e.latestError&&t.jsxs("div",{className:"mb-2 space-y-1 rounded-md border border-accent/25 bg-accent-soft px-2.5 py-2 text-xs text-accent",children:[t.jsx("div",{className:"break-words font-medium",children:e.latestError.message}),t.jsxs("div",{className:"font-mono text-xs opacity-80",children:[e.latestError.reason," · ",e.latestError.occurredAt]})]}),e.latestBootstrapError&&t.jsxs("div",{className:"mb-2 space-y-1 rounded-md border border-accent/25 bg-accent-soft px-2.5 py-2 text-xs text-accent",children:[t.jsx("div",{className:"break-words font-medium",children:e.latestBootstrapError.message}),e.latestBootstrapError.recommendation&&t.jsx("div",{className:"break-words",children:e.latestBootstrapError.recommendation}),t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsxs("div",{className:"truncate font-mono text-xs opacity-80",children:[e.latestBootstrapError.reason," · ",e.latestBootstrapError.occurredAt]}),t.jsx("button",{type:"button",onClick:pe,disabled:ee,className:"btn-primary shrink-0",children:ee?c.common.retrying:c.agents.retryBootstrap})]})]}),u&&N&&t.jsxs("div",{className:"mb-2 text-xs text-og-500",children:[c.agents.taskLabel,t.jsx("span",{className:"font-mono text-og-700",children:N})]}),ye&&t.jsx("div",{className:"mb-2 overflow-hidden border border-hairline bg-surface",children:t.jsx(ze,{agentId:e.id,mode:"preview",maxLines:6,interactive:!1})}),je&&t.jsx("div",{className:z,role:P?"button":void 0,tabIndex:P?0:void 0,"aria-label":P?c.agents.activateTerminal(e.id):void 0,onClick:me,onKeyDown:V,children:E?t.jsx("div",{className:"flex h-full items-center justify-center px-3 text-sm text-og-500",children:L}):fe?ve?t.jsx(ze,{agentId:e.id,mode:"full",interactive:!0,autoFocus:!0}):t.jsx(ze,{agentId:e.id,mode:"preview",interactive:!1}):t.jsx(ze,{agentId:e.id,mode:"full",interactive:!0,autoFocus:!1,deferFullUntilFocus:!0})}),l&&t.jsx("div",{className:"mb-2 rounded-md border border-accent/25 bg-accent-soft/60 px-2.5 py-1.5 text-xs text-accent",children:c.agents.pendingRestartNotice}),t.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[t.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2 overflow-x-auto scrollbar-none",children:[E?t.jsx("span",{className:"shrink-0 cursor-not-allowed text-sm text-og-400",title:L,children:c.agents.terminal}):t.jsx(_e,{to:`/terminal/${e.id}`,className:"btn-secondary shrink-0",children:c.agents.terminal}),!l&&e.runtimeStatus==="working"&&t.jsx("button",{onClick:_,disabled:g,className:"btn-ghost shrink-0",children:g?c.agents.stopping:c.agents.stop}),G&&t.jsx("button",{type:"button",onClick:we,disabled:J,title:he?c.agents.resumeGreetingButtonTitle:c.agents.resumeDefaultButtonTitle,className:"btn-primary shrink-0",children:J?c.agents.resuming:c.agents.resume})]}),t.jsx(Qt,{ariaLabel:c.agents.actionsMenu(e.id),className:"shrink-0",placement:"up",autoFocusFirstItem:!0,disabled:b,children:Q=>t.jsxs(t.Fragment,{children:[t.jsx(Se,{onClick:()=>{Q(),ie(!0)},disabled:$||K||b,title:c.agents.agentPetMenuItemTitle,children:"Agent Pet"}),t.jsx(Se,{onClick:()=>{Q(),D()},disabled:$||K||b,title:c.agents.compactMenuItemTitle,children:$?c.agents.compacting:c.agents.compact}),t.jsx(Se,{onClick:()=>{Q(),q()},disabled:K||$||b,title:c.agents.clearMenuItemTitle,children:K?c.agents.clearing:c.agents.clear}),!l&&N&&(s==="dev"||s==="research")&&t.jsx(Se,{onClick:()=>{Q(),ue()},disabled:B||b,title:c.agents.callReviewMenuItemTitle(N),children:B?c.agents.callingReview:c.agents.callReview}),t.jsx(Se,{onClick:()=>{Q(),p()},disabled:b||$||K,children:b?c.common.deleting:c.common.delete})]})})]}),y&&t.jsx("div",{className:"mt-1.5 break-words text-xs text-accent",children:y}),k&&t.jsx("div",{className:"mt-1.5 break-words text-xs text-accent",children:k}),X&&t.jsx(Kr,{agentId:e.id,currentPetId:e.petId??null,onClose:()=>ie(!1)})]})}const Lt="baxian:terminal-activated";function os({coordinateAcrossInstances:e=!0}={}){const n=o.useId(),[s,r]=o.useState(null);o.useEffect(()=>{if(s===null)return;const i=u=>{u.composedPath().some(x=>x instanceof Element&&x.hasAttribute("data-agent-card"))||r(null)},l=u=>{if(u.key!=="Escape")return;const m=document.activeElement;m instanceof Element&&m.closest("[data-agent-card]")||r(null)},d=u=>{const m=u.detail;(m==null?void 0:m.ownerId)!==n&&r(null)};return document.addEventListener("click",i),document.addEventListener("keydown",l),e&&document.addEventListener(Lt,d),()=>{document.removeEventListener("click",i),document.removeEventListener("keydown",l),e&&document.removeEventListener(Lt,d)}},[s,e,n]);const a=o.useCallback(i=>{r(i),e&&document.dispatchEvent(new CustomEvent(Lt,{detail:{ownerId:n}}))},[e,n]);return{activeAgentId:s,activateAgentCard:a}}function Xr(e){return Xt().status[e]??e}const ls={pending:"pill",in_progress:"pill pill-live",review:"pill pill-review",fixing:"pill pill-warn","spec-ready":"pill pill-warn",approved:"pill pill-live","merge-ready":"pill pill-warn",ready:"pill pill-warn",merged:"pill pill-live",done:"pill pill-live",failed:"pill pill-danger",max_rounds:"pill pill-warn",cancelled:"pill"},Zr={pending:"bg-og-300",in_progress:"bg-success",review:"bg-accent",fixing:"bg-warn","spec-ready":"bg-warn",approved:"bg-success","merge-ready":"bg-warn",ready:"bg-warn",merged:"bg-success",done:"bg-success",failed:"bg-danger",max_rounds:"bg-warn",cancelled:"bg-og-300"};function ea({status:e}){return t.jsx("span",{role:"img","aria-label":e,title:e,className:`inline-block h-2 w-2 shrink-0 rounded-full ${Zr[e]??"bg-og-300"}`})}function tn(e){if(!e)return"";const n=e.match(/^task-(\d+)$/);return n?n[1]:e}function Pt(e,n=!0){if(e==null)return"";const s=String(e).trim();if(!s)return"";const r=new Date(s.replace(/^(\d{4}-\d{2}-\d{2}) /,"$1T"));if(Number.isNaN(r.getTime()))return s;const a=d=>String(d).padStart(2,"0"),i=`${r.getFullYear()}-${a(r.getMonth()+1)}-${a(r.getDate())}`,l=`${a(r.getHours())}:${a(r.getMinutes())}`;return n?`${i} ${l}:${a(r.getSeconds())}`:`${i} ${l}`}function Fe(e,n){return`/project/${encodeURIComponent(e)}/task/${encodeURIComponent(n)}`}function cs({group:e,projectId:n,agentsById:s,agentsLoaded:r,agentsError:a=!1,tasks:i,onDeleted:l,terminalMode:d="activity-preview"}){const u=M(),m=e.find(f=>f.role==="dev")??e[0],h=e.find(f=>f.role==="research"),x=i.filter(f=>sa(f,m==null?void 0:m.id)),c=m?i.filter(f=>ra(f,n,m.id,h==null?void 0:h.id)).sort((f,k)=>f.createdAt.localeCompare(k.createdAt)):[],g=`Agent group ${e.map(f=>f.id).join(" / ")}`,v=Te(),y=d==="embedded-full",{activeAgentId:w,activateAgentCard:S}=os({coordinateAcrossInstances:y}),A=d==="embedded-full"?e.length<=1?"lg:grid-cols-1":e.length===2?"lg:grid-cols-2":e.length===3?"lg:grid-cols-3":"lg:grid-cols-4":"sm:grid-cols-2",R=!!m&&c.length>0,b=x.length===0&&!R;return t.jsxs("div",{role:"group","aria-label":g,className:"min-w-0",children:[R&&m&&t.jsx(na,{tasks:c,devId:m.id,agentsById:s,label:g}),x.length>0&&t.jsx("div",{className:"card mb-2 max-h-28 overflow-y-auto divide-y divide-hairline",children:x.map(f=>{const k=Ce(f.phase)?f.specReviewRound??0:f.reviewRound;return t.jsxs("button",{type:"button",onClick:()=>v(Fe(f.projectId,f.id)),className:"flex w-full items-center gap-3 px-3 py-2 text-left text-sm transition-colors hover:bg-og-50/60",children:[t.jsxs("div",{className:"min-w-0 flex-1 flex items-center gap-2",children:[t.jsx("span",{className:"shrink-0 font-mono text-xs text-og-500",title:f.id,children:tn(f.id)}),t.jsx("span",{className:"truncate text-og-1000",children:f.title})]}),t.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[t.jsx("span",{className:"shrink-0 text-xs text-og-500",children:u.agents.round(k)}),t.jsx("span",{className:`${ls[f.status]} shrink-0`,title:f.status,children:u.status[f.status]??f.status})]})]},f.id)})}),b&&t.jsx("div",{className:"mb-2 rounded-lg border border-hairline bg-surface px-3 py-2 text-sm text-og-400","aria-label":u.agents.noActiveTaskAriaLabel(g),children:u.agents.noActiveTask}),t.jsx("div",{className:`grid grid-cols-1 ${A} gap-4`,children:e.map(f=>{const k=s.get(f.id),j=k??{id:f.id,projectId:n,runtimeStatus:"unknown",tmuxSessionStatus:"unknown",stale:!0};return t.jsx(is,{agent:j,projectId:n,role:f.role,runtime:f.runtime,model:f.model,pendingRestart:r&&!k,terminalLoading:!r&&!k&&!a,onDeleted:l,showTaskBinding:!1,terminalMode:d,...y?{active:w===f.id,onActivate:()=>S(f.id)}:{}},f.id)})})]})}function ta(e){var n,s,r;return!!e&&e.runtimeStatus==="idle"&&((n=e.binding)==null?void 0:n.status)!=="awaiting_human"&&!((s=e.binding)!=null&&s.creationToken)&&!((r=e.binding)!=null&&r.taskId)}function na({tasks:e,devId:n,agentsById:s,label:r}){const a=M(),{show:i}=Re(),l=Te(),[d,u]=o.useState(null),m=async(h,x)=>{u(h);try{await F.tasks.dispatch(h,{agentId:x}),i({kind:"success",title:a.agents.taskHandedTo(h,x)})}catch(c){i({kind:"error",title:a.agents.startFailed,body:c instanceof Error?c.message:String(c)})}finally{u(null)}};return t.jsx("div",{role:"group",className:"card mb-2 max-h-28 overflow-y-auto divide-y divide-hairline","aria-label":`${r} claimable tasks for ${n}`,children:e.map(h=>{const x=h.preferredAgentId||n,c=ta(s.get(x)),g=h.preferredAgentId==="",v=d!==null;return t.jsxs("div",{className:"flex items-center gap-3 px-3 py-2 text-sm",children:[t.jsxs("button",{type:"button",onClick:()=>l(Fe(h.projectId,h.id)),className:"min-w-0 flex-1 flex items-center gap-2 text-left transition-colors hover:text-accent-hover",children:[t.jsx("span",{className:"shrink-0 font-mono text-xs text-og-500",title:h.id,children:tn(h.id)}),t.jsx("span",{className:"truncate text-og-1000",title:h.title,children:h.title}),g&&t.jsx("span",{className:"pill shrink-0",children:a.agents.unassigned})]}),t.jsx("button",{type:"button",onClick:()=>void m(h.id,x),disabled:!c||v,title:c?a.agents.handToAndStart(x):a.agents.agentUnavailable(x),className:"shrink-0 text-sm font-medium text-accent transition-colors hover:text-accent-hover disabled:opacity-50 disabled:cursor-not-allowed",children:d===h.id?a.agents.starting:a.agents.start})]},h.id)})})}function sa(e,n){return!n||!On.has(e.status)?!1:e.devAgentId===n}function ra(e,n,s,r){return e.projectId!==n||e.status!=="pending"?!1:e.preferredAgentId===s||e.preferredAgentId===r||e.preferredAgentId===""}const de="w-full rounded-md border border-og-100 bg-surface px-2.5 py-1.5 text-sm 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-xs font-medium text-og-700",pt="mt-1 text-xs text-accent",Ke="mt-1 text-xs text-og-500",Ne="h-3.5 w-3.5 accent-accent",aa=/^[a-z][a-z0-9-]{1,31}$/,ia=[/^https?:\/\/[^/\s]+\/[^\s]+$/,/^ssh:\/\/[^/\s]+\/[^\s]+$/,/^[^@/\s]+@[^:/\s]+:[^\s]+$/,/^[^/\s:@]+\/[^/\s]+$/];function oa(e){return/^[^/\s:@]+\/[^/\s]+$/.test(e.trim())}function la({open:e,onClose:n,onCreated:s}){const r=M(),[a,i]=o.useState(""),[l,d]=o.useState(""),[u,m]=o.useState(null),[h,x]=o.useState("human"),[c,g]=o.useState(""),[v,y]=o.useState("git"),[w,S]=o.useState(""),[A,R]=o.useState(""),[b,f]=o.useState(!1),[k,j]=o.useState(null),[$,I]=o.useState({}),[K,C]=o.useState(new Set),B=o.useRef(0),{show:W}=Re(),{flagDirty:J}=wt();o.useEffect(()=>{if(!e)return;B.current+=1;const N=B.current;i(""),d(""),m(null),x("human"),g(""),y("git"),S(""),R(""),j(null),I({}),C(new Set),F.config.get().then(G=>{var se;N===B.current&&(C(new Set(G.project.map(he=>he.id))),y(((se=G.review)==null?void 0:se.mode)??"git"))}).catch(G=>{N===B.current&&j(r.common.loadFailed(G instanceof Error?G.message:String(G)))})},[e]);const Z=()=>{b||n()},te=(c===""?v:c)==="git"&&l.trim()!==""&&!oa(l),X=()=>{const N={};return a?aa.test(a)?K.has(a)&&(N.id=r.createProject.idTakenError):N.id=r.common.idFormatError:N.id=r.createProject.required,l?ia.some(G=>G.test(l.trim()))||(N.repo=r.createProject.repoFormatError):N.repo=r.createProject.required,I(N),Object.keys(N).length===0},ie=async N=>{if(N.preventDefault(),!!X()){f(!0),j(null);try{const G=await F.projects.create({id:a,repo:l.trim(),merge:u,...h?{specApproval:h}:{},...c?{review:{mode:c}}:{},...te&&w.trim()?{gitCli:{tool:w.trim(),...A.trim()?{notes:A.trim()}:{}}}:{}});G.restartRequired&&J(),W({kind:"success",title:r.createProject.createdToastTitle(G.project.id)}),s(G.project.id)}catch(G){j(G instanceof Error?G.message:String(G))}finally{f(!1)}}};return t.jsx(Ae,{open:e,onClose:Z,title:r.createProject.title,size:"md",footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:Z,disabled:b,className:"btn-secondary",children:r.common.cancel}),t.jsx("button",{type:"submit",form:"create-project-form",disabled:b,className:"btn-primary",children:b?r.common.creating:r.common.create})]}),children:t.jsxs("form",{id:"create-project-form",onSubmit:ie,className:"space-y-3",children:[k&&t.jsx("div",{className:"whitespace-pre-line rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-sm text-accent",children:k}),t.jsxs("div",{children:[t.jsx("label",{className:re,htmlFor:"proj-id",children:r.createProject.idLabel}),t.jsx("input",{id:"proj-id",type:"text",value:a,onChange:N=>i(N.target.value),className:de,placeholder:"baxian",disabled:b}),$.id&&t.jsx("div",{className:pt,children:$.id})]}),t.jsxs("div",{children:[t.jsx("label",{className:re,htmlFor:"proj-repo",children:r.createProject.repoLabel}),t.jsx("input",{id:"proj-repo",type:"text",value:l,onChange:N=>d(N.target.value),className:de,placeholder:"https://github.com/baxian-ai/baxian.git",disabled:b}),$.repo&&t.jsx("div",{className:pt,children:$.repo})]}),t.jsxs("div",{children:[t.jsx("span",{className:re,children:r.createProject.mergeStrategyLabel}),t.jsxs("label",{className:"mb-1 flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"merge",checked:u===null,onChange:()=>m(null),disabled:b,className:"h-3.5 w-3.5 accent-accent"}),t.jsx("span",{className:"text-sm text-og-800",children:r.createProject.mergeHumanLabel})]}),t.jsxs("label",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"merge",checked:u==="auto",onChange:()=>m("auto"),disabled:b,className:"h-3.5 w-3.5 accent-accent"}),t.jsx("span",{className:"text-sm text-og-800",children:r.createProject.mergeAutoLabel})]})]}),t.jsxs("div",{children:[t.jsx("span",{className:re,children:r.createProject.specApprovalLabel}),t.jsxs("label",{className:"mb-1 flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"spec-approval",checked:h==="human",onChange:()=>x("human"),disabled:b,className:"h-3.5 w-3.5 accent-accent"}),t.jsx("span",{className:"text-sm text-og-800",children:r.createProject.specApprovalHumanLabel})]}),t.jsxs("label",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"spec-approval",checked:h===null,onChange:()=>x(null),disabled:b,className:"h-3.5 w-3.5 accent-accent"}),t.jsx("span",{className:"text-sm text-og-800",children:r.createProject.specApprovalAutoLabel})]})]}),t.jsxs("div",{children:[t.jsx("span",{className:re,children:r.createProject.reviewModeLabel}),t.jsxs("label",{className:"mb-1 flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"review-mode",checked:c==="",onChange:()=>g(""),disabled:b,className:"h-3.5 w-3.5 accent-accent"}),t.jsx("span",{className:"text-sm text-og-800",children:r.createProject.reviewModeFollowGlobalLabel})]}),t.jsxs("label",{className:"mb-1 flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"review-mode",checked:c==="git",onChange:()=>g("git"),disabled:b,className:"h-3.5 w-3.5 accent-accent"}),t.jsx("span",{className:"text-sm text-og-800",children:r.createProject.reviewModeGitLabel})]}),t.jsxs("label",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"review-mode",checked:c==="server",onChange:()=>g("server"),disabled:b,className:"h-3.5 w-3.5 accent-accent"}),t.jsx("span",{className:"text-sm text-og-800",children:r.createProject.reviewModeServerLabel})]})]}),te&&t.jsxs("div",{children:[t.jsxs("label",{className:"mb-1 block",children:[t.jsx("span",{className:re,children:r.createProject.gitCliToolLabel}),t.jsx("input",{value:w,onChange:N=>S(N.target.value),placeholder:r.createProject.gitCliToolPlaceholder,disabled:b,className:de})]}),t.jsxs("label",{className:"block",children:[t.jsx("span",{className:re,children:r.createProject.gitCliNotesLabel}),t.jsx("input",{value:A,onChange:N=>R(N.target.value),disabled:b,className:de})]})]})]})})}const fn=/^[a-z][a-z0-9-]{1,31}$/,ca=500,hn={id:"",role:"dev",pairWith:"",mode:"local",host:"",runtime:"",workdir:"",yolo:!0,model:"",addDirs:""};function da(e){return e.alias?e.alias:`${e.user?`${e.user}@`:""}${e.hostname}${e.port!=null?`:${e.port}`:""}`}function ds({open:e,onClose:n,projectId:s,onCreated:r}){var pe,we,D,q,p,P;const a=M(),[i,l]=o.useState(hn),[d,u]=o.useState(null),[m,h]=o.useState([]),[x,c]=o.useState(new Set),[g,v]=o.useState(null),[y,w]=o.useState(!1),[S,A]=o.useState(!1),[R,b]=o.useState(null),[f,k]=o.useState(!1),[j,$]=o.useState(null),[I,K]=o.useState(!1),C=o.useRef(null),B=o.useRef(null),W=o.useRef(0),J=o.useRef(0),{show:Z}=Re(),{flagDirty:ee}=wt();o.useEffect(()=>{if(!e)return;J.current+=1;const T=J.current;l(hn),u(null),h([]),c(new Set),v(null),w(!1),A(!1),b(null),W.current+=1,$(null),K(!1),F.config.get().then(U=>{if(T!==J.current)return;const z=U.project.find(V=>V.id===s)??null;u(z),h(U.host??[]);const me=new Set;U.project.forEach(V=>V.agent.forEach(ce=>ce.forEach(xe=>me.add(xe.id)))),c(me)}).catch(()=>{})},[e,s]);const te=()=>{f||n()},X=o.useCallback(()=>{C.current&&C.current.abort();const T=new AbortController;C.current=T,w(!0),$(null);const U=i.mode==="remote"?{hostId:i.host}:{};F.agents.probe(i.mode,U,{signal:T.signal}).then(z=>{T.signal.aborted||(v(z),$(null))}).catch(z=>{T.signal.aborted||(v(null),$(z instanceof Error?z.message:String(z)))}).finally(()=>{C.current===T&&w(!1)})},[i.mode,i.host]);o.useEffect(()=>{if(e&&(v(null),b(null),A(!1),W.current+=1,C.current&&C.current.abort(),!(i.mode==="remote"&&!i.host)))return B.current&&clearTimeout(B.current),B.current=setTimeout(X,ca),()=>{B.current&&clearTimeout(B.current)}},[e,i.mode,i.host,X]),o.useEffect(()=>{e||C.current&&C.current.abort()},[e]),o.useEffect(()=>()=>{C.current&&C.current.abort(),B.current&&clearTimeout(B.current)},[]);const ie=()=>{if(S)return;const T=W.current;A(!0),b(null);const U=i.mode==="remote"?{hostId:i.host}:{};F.agents.installTmux(i.mode,U).then(z=>{W.current===T&&(b({ok:z.ok,message:z.message}),A(!1),z.ok&&X())}).catch(z=>{W.current===T&&(b({ok:!1,message:z instanceof Error?z.message:String(z)}),A(!1))})},N=(d==null?void 0:d.agent.filter(T=>T.some(U=>U.role==="dev")))??[],G=T=>N.filter(U=>!U.some(z=>z.role===T)).map(U=>U.find(z=>z.role==="dev")),se=G("qa"),he=G("research"),O=se.length>0,oe=he.length>0,ne=fn.test(i.id)&&!x.has(i.id),be=i.mode==="local"||i.mode==="remote"&&i.host!=="",ye=i.runtime!==""&&!!((pe=g==null?void 0:g.runtimes[i.runtime])!=null&&pe.ok),je=!!(g!=null&&g.tmux.ok),fe=i.mode==="local"||!!((we=g==null?void 0:g.ssh)!=null&&we.ok),ve=i.role==="dev"||(i.role==="qa"||i.role==="research")&&i.pairWith!=="",E=!f&&ne&&be&&ve&&ye&&je&&fe,L=async T=>{if(T.preventDefault(),!!E){k(!0),$(null);try{const U=i.addDirs.split(`
|
|
8
|
-
`).map(V=>V.trim()).filter(V=>V.length>0),z={id:i.id,role:i.role,runtime:i.runtime,mode:i.mode,...i.mode==="remote"?{host:i.host}:{},...i.workdir?{workdir:i.workdir}:{},yolo:i.yolo,...i.model.trim()?{model:i.model.trim()}:{},...U.length>0?{addDirs:U}:{},...i.role==="qa"||i.role==="research"?{pairWith:i.pairWith}:{}},me=await F.projects.addAgent(s,z);me.restartRequired&&ee(),Z({kind:"success",title:a.createAgent.addedToastTitle(me.agent.id,s)}),r(),n()}catch(U){$(U instanceof Error?U.message:String(U))}finally{k(!1)}}},H=({rt:T})=>{if(i.mode==="remote"&&!i.host)return t.jsx("span",{className:"ml-2 text-xs text-og-400",children:a.createAgent.selectHostFirstHint});if(y)return t.jsx("span",{className:"ml-2 text-xs text-og-400",children:a.createAgent.probingLabel});if(!g)return t.jsx("span",{className:"ml-2 text-xs text-og-400",children:"?"});const z=g.runtimes[T];return z?z.ok?t.jsxs("span",{className:"ml-2 text-xs text-probe-ok",children:["✓ ",z.path??""]}):t.jsxs("span",{className:"ml-2 text-xs text-accent",title:z.message,children:["⨯ ",z.message]}):t.jsx("span",{className:"ml-2 text-xs text-og-400",children:"?"})},_=()=>{var U;if(i.mode==="remote"&&!i.host)return null;if(y&&!S)return t.jsx("div",{className:"text-xs text-og-400",children:a.createAgent.tmuxProbingLabel});if(!g)return null;if(g.tmux.ok)return t.jsxs("div",{className:"text-xs text-probe-ok",children:["tmux: ✓ ",g.tmux.path??""]});const T=i.mode==="local"||!!((U=g.ssh)!=null&&U.ok);return t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"text-xs text-accent",children:["tmux: ⨯ ",g.tmux.message,T&&t.jsx("button",{type:"button",onClick:ie,className:"ml-2 text-accent underline transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",disabled:S||f,children:S?a.common.installing:a.common.oneClickInstall})]}),S&&t.jsx("div",{className:"text-xs text-og-500",children:a.common.installingTmuxNotice}),!S&&R&&t.jsxs("div",{className:`break-all text-xs ${R.ok?"text-probe-ok":"text-accent"}`,children:[R.ok?"✓ ":"⨯ ",R.message]})]})},ue=()=>i.mode!=="remote"||!i.host||!(g!=null&&g.ssh)?null:g.ssh.ok?t.jsxs("div",{className:"text-xs text-probe-ok",children:["SSH: ✓ ",g.ssh.message]}):t.jsxs("div",{className:"text-xs text-accent",children:["SSH: ⨯ ",g.ssh.message]});return t.jsx(Ae,{open:e,onClose:te,title:a.createAgent.modalTitle(s),size:"lg",footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:te,disabled:f,className:"btn-secondary",children:a.common.cancel}),t.jsx("button",{type:"submit",form:"create-agent-form",disabled:!E,className:"btn-primary",children:f?a.createAgent.submitting:a.createAgent.submitLabel})]}),children:t.jsxs("form",{id:"create-agent-form",onSubmit:L,className:"space-y-3",children:[j&&t.jsx("div",{className:"whitespace-pre-line rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-sm text-accent",children:j}),t.jsxs("div",{children:[t.jsx("label",{className:re,htmlFor:"agent-id",children:"Agent ID"}),t.jsx("input",{id:"agent-id",type:"text",value:i.id,onChange:T=>l({...i,id:T.target.value}),className:de,placeholder:a.createAgent.idPlaceholder(s,i.role),disabled:f}),i.id&&!fn.test(i.id)&&t.jsx("div",{className:pt,children:a.common.idFormatError}),i.id&&x.has(i.id)&&t.jsx("div",{className:pt,children:a.createAgent.idTakenGlobalError})]}),t.jsxs("div",{children:[t.jsx("span",{className:re,children:a.createAgent.roleLabel}),t.jsxs("label",{className:"mr-4 inline-flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"role",checked:i.role==="dev",className:Ne,onChange:()=>l({...i,role:"dev",pairWith:""}),disabled:f}),t.jsx("span",{className:"text-sm text-og-800",children:"Dev agent"})]}),t.jsxs("label",{className:"mr-4 inline-flex items-center gap-2",title:O?"":a.createAgent.createDevFirstHint,children:[t.jsx("input",{type:"radio",name:"role",checked:i.role==="qa",className:Ne,onChange:()=>l({...i,role:"qa",pairWith:""}),disabled:f||!O}),t.jsx("span",{className:`text-sm ${O?"text-og-800":"text-og-400"}`,children:"QA agent"})]}),t.jsxs("label",{className:"inline-flex items-center gap-2",title:oe?"":a.createAgent.createDevFirstHint,children:[t.jsx("input",{type:"radio",name:"role",checked:i.role==="research",className:Ne,onChange:()=>l({...i,role:"research",pairWith:""}),disabled:f||!oe}),t.jsx("span",{className:`text-sm ${oe?"text-og-800":"text-og-400"}`,children:a.createAgent.roleResearch})]})]}),(i.role==="qa"||i.role==="research")&&t.jsxs("div",{children:[t.jsx("label",{className:re,htmlFor:"pair-with",children:a.createAgent.pairWithLabel}),t.jsxs("select",{id:"pair-with",value:i.pairWith,onChange:T=>l({...i,pairWith:T.target.value}),className:de,disabled:f,children:[t.jsx("option",{value:"",children:a.createAgent.pairWithPlaceholder}),(i.role==="qa"?se:he).map(T=>t.jsx("option",{value:T.id,children:a.createAgent.pairOptionLabel(T.id,T.mode)},T.id))]})]}),t.jsxs("div",{children:[t.jsx("span",{className:re,children:a.createAgent.modeLabel}),t.jsxs("label",{className:"mr-4 inline-flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"mode",checked:i.mode==="local",className:Ne,onChange:()=>l({...i,mode:"local",host:""}),disabled:f}),t.jsx("span",{className:"text-sm text-og-800",children:a.createAgent.localModeLabel})]}),t.jsxs("label",{className:"inline-flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"mode",checked:i.mode==="remote",className:Ne,onChange:()=>l({...i,mode:"remote"}),disabled:f}),t.jsx("span",{className:"text-sm text-og-800",children:a.createAgent.remoteModeLabel})]})]}),i.mode==="remote"&&t.jsxs("div",{children:[t.jsx("label",{className:re,htmlFor:"host",children:"Host"}),m.length===0?t.jsx("div",{className:"rounded-md border border-og-100 bg-og-50/40 px-3 py-2 text-xs text-og-600",children:a.createAgent.noHostsHint}):t.jsxs("select",{id:"host",value:i.host,onChange:T=>l({...i,host:T.target.value}),className:de,disabled:f,children:[t.jsx("option",{value:"",children:a.createAgent.selectHostPlaceholder}),m.map(T=>t.jsx("option",{value:T.id,children:da(T)},T.id))]}),t.jsx("div",{className:Ke,children:a.createAgent.sshConfigHint})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"mb-1.5 flex items-center justify-between",children:[t.jsx("span",{className:"text-xs font-medium text-og-700",children:a.createAgent.runtimeLabel}),t.jsx("button",{type:"button",onClick:X,className:"text-xs text-accent transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",disabled:f||y||i.mode==="remote"&&!i.host,children:a.createAgent.reprobeButton})]}),t.jsxs("label",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"runtime",checked:i.runtime==="claude-code",className:Ne,onChange:()=>l({...i,runtime:"claude-code"}),disabled:f||(g?!((D=g.runtimes["claude-code"])!=null&&D.ok):!1)}),t.jsx("span",{className:"text-sm text-og-800",children:"Claude Code"}),t.jsx(H,{rt:"claude-code"})]}),t.jsxs("label",{className:"mt-1 flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"runtime",checked:i.runtime==="codex",className:Ne,onChange:()=>l({...i,runtime:"codex"}),disabled:f||(g?!((q=g.runtimes.codex)!=null&&q.ok):!1)}),t.jsx("span",{className:"text-sm text-og-800",children:"Codex"}),t.jsx(H,{rt:"codex"})]}),t.jsxs("label",{className:"mt-1 flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"runtime",checked:i.runtime==="opencode",className:Ne,onChange:()=>l({...i,runtime:"opencode"}),disabled:f||(g?!((p=g.runtimes.opencode)!=null&&p.ok):!1)}),t.jsx("span",{className:"text-sm text-og-800",children:"OpenCode"}),t.jsx(H,{rt:"opencode"})]}),t.jsxs("label",{className:"mt-1 flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"runtime",checked:i.runtime==="qodercli",className:Ne,onChange:()=>l({...i,runtime:"qodercli"}),disabled:f||(g?!((P=g.runtimes.qodercli)!=null&&P.ok):!1)}),t.jsx("span",{className:"text-sm text-og-800",children:"Qoder CLI"}),t.jsx(H,{rt:"qodercli"})]}),t.jsx("div",{className:"mt-2",children:t.jsx(_,{})}),t.jsx("div",{children:t.jsx(ue,{})})]}),t.jsxs("div",{children:[t.jsxs("button",{type:"button",onClick:()=>K(T=>!T),"aria-expanded":I,"aria-controls":I?"advanced-options":void 0,className:"flex w-full items-center justify-between rounded-md px-1 py-1.5 text-left text-xs font-medium text-og-700 transition-colors hover:bg-og-50",children:[t.jsx("span",{children:a.createAgent.advancedOptionsLabel}),t.jsx("span",{className:"text-og-400",children:I?a.createAgent.collapseLabel:a.createAgent.expandLabel})]}),I&&t.jsxs("div",{id:"advanced-options",className:"mt-3 space-y-3",children:[t.jsxs("div",{children:[t.jsx("label",{className:re,htmlFor:"workdir",children:a.createAgent.workdirLabel}),t.jsx("input",{id:"workdir",type:"text",value:i.workdir,onChange:T=>l({...i,workdir:T.target.value}),className:de,placeholder:a.createAgent.workdirPlaceholder,disabled:f}),t.jsx("div",{className:Ke,children:a.createAgent.workdirHint})]}),t.jsxs("div",{children:[t.jsx("label",{className:re,htmlFor:"model",children:a.createAgent.modelLabel}),t.jsx("input",{id:"model",type:"text",value:i.model,onChange:T=>l({...i,model:T.target.value}),className:de,placeholder:i.runtime==="codex"?a.createAgent.modelPlaceholderCodex:a.createAgent.modelPlaceholderOther,disabled:f}),t.jsx("div",{className:Ke,children:a.createAgent.modelHint})]}),t.jsxs("div",{children:[t.jsx("label",{className:re,htmlFor:"addDirs",children:a.createAgent.addDirsLabel}),t.jsx("textarea",{id:"addDirs",value:i.addDirs,onChange:T=>l({...i,addDirs:T.target.value}),className:`${de} font-mono text-xs`,rows:3,placeholder:a.createAgent.addDirsPlaceholder,disabled:f}),t.jsx("div",{className:Ke,children:a.createAgent.addDirsHint})]})]})]}),t.jsx("div",{className:"rounded-md border border-accent/25 bg-accent-soft/60 px-3 py-2.5",children:t.jsxs("label",{className:"flex cursor-pointer items-start gap-2",children:[t.jsx("input",{type:"checkbox",className:"mt-1 h-3.5 w-3.5 accent-accent",checked:i.yolo,onChange:T=>l({...i,yolo:T.target.checked}),disabled:f}),t.jsxs("div",{className:"text-sm text-og-800",children:[t.jsx("div",{className:"font-medium",children:a.createAgent.yoloTitle}),t.jsxs("div",{className:"mt-1 text-xs text-accent",children:[a.createAgent.yoloBodyLead,t.jsx("code",{children:Qs[i.runtime||"claude-code"]}),a.createAgent.yoloBodyTrail]})]})]})})]})})}const pn=200,gn=16e3,ua="baxian.draft.createTask:";function Ht(e){return`${ua}${e??"*"}`}function xn(e){try{const n=localStorage.getItem(e);if(!n)return null;const s=JSON.parse(n);if(!s||typeof s!="object")return null;const r=s,a=typeof r.title=="string"?r.title:"",i=typeof r.description=="string"?r.description:"",l=typeof r.projectId=="string"?r.projectId:"",d=typeof r.preferredAgentId=="string"?r.preferredAgentId:"",u=typeof r.updatedAt=="number"?r.updatedAt:void 0;return!a.trim()&&!i.trim()?null:{title:a,description:i,projectId:l,preferredAgentId:d,updatedAt:u}}catch{return null}}function ma(e,n){const s=!n.title.trim()&&!n.description.trim();try{s?localStorage.removeItem(e):localStorage.setItem(e,JSON.stringify({...n,updatedAt:Date.now()}))}catch{}}function bn(e){try{localStorage.removeItem(e)}catch{}}function fa(e){const n=Ht(e),s=xn(n);if(!e)return s;const r=Ht(void 0),a=xn(r);if(!a||a.projectId!==e)return s;const i=!s||(a.updatedAt??0)>(s.updatedAt??0);if(i)try{localStorage.setItem(n,JSON.stringify(a))}catch{return a}try{localStorage.removeItem(r)}catch{}return i?a:s}const vn="mt-1 text-right text-xs text-og-400",ha=Math.floor(vt/1024/1024);function nn(e){const n=M(),s=e.mode==="edit",{show:r}=Re(),a=s?e.task.projectId:e.projectId,i=s?e.task.title:"",l=s?e.task.description:"",d=s?e.task.preferredAgentId:"",[u,m]=o.useState([]),[h,x]=o.useState([]),[c,g]=o.useState(a??""),[v,y]=o.useState(d),[w,S]=o.useState(i),[A,R]=o.useState(l),[b,f]=o.useState([]),k=o.useRef(null),[j,$]=o.useState(!1),[I,K]=o.useState(null),[C,B]=o.useState(!1),W=o.useRef(0),J=o.useRef(0),Z=o.useRef(0),ee=o.useRef(new Set),te=s?null:Ht(a);o.useEffect(()=>{if(!e.open)return;W.current+=1,J.current+=1;const D=W.current;m([]),x([]),ee.current=new Set;const q=te?fa(a):null;q&&ee.current.add(q.projectId),g(a??(q==null?void 0:q.projectId)??""),y((q==null?void 0:q.preferredAgentId)||d),S((q==null?void 0:q.title)||i),R((q==null?void 0:q.description)||l),B(q!==null),K(null),$(!1),f([]),Promise.all([F.projects.list(),F.agents.list()]).then(([p,P])=>{D===W.current&&(m(p),x(P))}).catch(p=>{D===W.current&&K(p instanceof Error?p.message:String(p))})},[e.open,a,i,l,d,te]),o.useEffect(()=>{if(!(!e.open||!te)){if(Z.current!==J.current){Z.current=J.current;return}ma(te,{title:w,description:A,projectId:c,preferredAgentId:v})}},[e.open,te,w,A,c,v]);const X=o.useMemo(()=>u.find(D=>D.id===c)??null,[u,c]),ie=o.useMemo(()=>X?X.agent.flat().filter(D=>D.role==="dev"||D.role==="research"):[],[X]),N=o.useMemo(()=>new Set(h.map(D=>D.id)),[h]),G=o.useMemo(()=>ie.filter(D=>N.has(D.id)),[ie,N]),se=o.useMemo(()=>ie.filter(D=>!N.has(D.id)),[ie,N]);o.useEffect(()=>{s||X!==null&&v!==""&&!G.find(D=>D.id===v)&&y("")},[X,G,v,s]),o.useEffect(()=>{if(s||!X)return;const D=G.find(q=>q.role==="dev");D&&(ee.current.has(X.id)||(ee.current.add(X.id),y(q=>q===""?D.id:q)))},[s,X,G]);const he=!s||G.find(D=>D.id===v),O=s&&!he&&!!v,oe=O&&se.some(D=>D.id===v),ne=oe?n.createTask.noDevPendingRestartHint(v):O?n.createTask.noDevNotInRuntimeHint(v):!c||G.length>0?null:se.length>0?n.createTask.noDevGlobalPendingRestartHint:null,be=w.trim(),ye=A.trim(),fe=!!c&&be.length>0&&!j,ve=()=>{j||e.onClose()},E=()=>{te&&(bn(te),g(a??""),y(d),S(i),R(l),K(null),B(!1))},L=async D=>{var q,p;if(D.preventDefault(),!!fe){$(!0),K(null);try{if(e.mode==="edit"){const P=await F.tasks.update(e.task.id,{title:be,description:ye,preferredAgentId:v});r({kind:"success",title:n.createTask.updatedToastTitle}),(q=e.onUpdated)==null||q.call(e,P),e.onClose()}else{const P=b.length?await Promise.all(b.map(async U=>({dataBase64:await Bt(U),filename:U.name}))):void 0,T=await F.tasks.create({projectId:c,title:be,description:ye,preferredAgentId:v,...P?{images:P}:{}});te&&bn(te),r({kind:"success",title:n.createTask.createdToastTitle}),(p=e.onCreated)==null||p.call(e,T),e.onClose()}}catch(P){K(P instanceof Error?P.message:String(P))}finally{$(!1)}}},H=D=>{const q=Array.from(D.target.files??[]);if(D.target.value="",q.length===0)return;const p=q.filter(P=>P.size>vt?(r({kind:"error",title:n.createTask.imageTooLargeToastTitle,body:n.createTask.imageTooLargeToastBody(P.name,ha)}),!1):!0);f(P=>(P.length+p.length>rt&&r({kind:"warn",title:n.createTask.tooManyImagesToastTitle(rt)}),[...P,...p].slice(0,rt)))},_=D=>f(q=>q.filter((p,P)=>P!==D)),ue=s?n.createTask.titleEdit:n.createTask.titleCreate,pe=s?j?n.common.saving:n.common.save:j?n.common.creating:n.common.create,we=!s&&!a;return t.jsx(Ae,{open:e.open,onClose:ve,title:ue,size:"md",dismissOnBackdrop:!1,footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:ve,disabled:j,className:"btn-secondary",children:n.common.cancel}),t.jsx("button",{type:"submit",form:"create-task-form",disabled:!fe,className:"btn-primary",children:pe})]}),children:t.jsxs("form",{id:"create-task-form",onSubmit:L,className:"space-y-3",children:[!s&&C&&t.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-xs text-accent",children:[t.jsx("span",{children:n.createTask.draftRestoredNotice}),t.jsx("button",{type:"button",onClick:E,className:"shrink-0 underline hover:text-accent-hover",children:n.createTask.discardDraftButton})]}),I&&t.jsx("div",{className:"rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-sm text-accent",children:I}),we&&t.jsxs("div",{children:[t.jsx("label",{className:re,htmlFor:"task-project",children:"Project"}),t.jsxs("select",{id:"task-project",value:c,onChange:D=>g(D.target.value),className:de,disabled:j,required:!0,children:[t.jsx("option",{value:"",disabled:!0,children:n.createTask.selectProjectPlaceholder}),u.map(D=>t.jsx("option",{value:D.id,children:D.id},D.id))]})]}),t.jsxs("div",{children:[t.jsx("label",{className:re,htmlFor:"task-dev",children:n.createTask.targetAgentLabel}),t.jsxs("select",{id:"task-dev",value:v,onChange:D=>y(D.target.value),className:de,disabled:j,children:[t.jsx("option",{value:"",children:n.createTask.notAssignedOption}),O&&t.jsxs("option",{value:v,children:[v," ",oe?n.createTask.pendingRestartSuffix:n.createTask.notInRuntimeSuffix]}),G.map(D=>t.jsx("option",{value:D.id,children:D.role==="research"?n.createTask.researchTargetOption(D.id):D.id},D.id))]}),ne&&t.jsx("div",{className:"mt-1 text-xs text-accent",children:ne})]}),t.jsxs("div",{children:[t.jsx("label",{className:re,htmlFor:"task-title",children:"Title"}),t.jsx("input",{id:"task-title",type:"text",value:w,onChange:D=>S(D.target.value),maxLength:pn,className:de,placeholder:n.createTask.titlePlaceholder,disabled:j,required:!0}),t.jsxs("div",{className:vn,children:[w.length," / ",pn]})]}),t.jsxs("div",{children:[t.jsx("label",{className:re,htmlFor:"task-description",children:n.createTask.descriptionLabel}),t.jsx("textarea",{id:"task-description",value:A,onChange:D=>R(D.target.value),maxLength:gn,rows:8,className:`${de} font-mono text-xs`,placeholder:n.createTask.descriptionPlaceholder,disabled:j}),t.jsxs("div",{className:vn,children:[A.length," / ",gn]})]}),!s&&t.jsxs("div",{children:[t.jsx("label",{className:re,children:n.createTask.imagesLabel}),t.jsx("button",{type:"button",onClick:()=>{var D;return(D=k.current)==null?void 0:D.click()},disabled:j||b.length>=rt,className:"btn-secondary",children:n.createTask.addImagesButton}),t.jsx("input",{ref:k,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:H}),b.length>0&&t.jsx("ul",{className:"mt-2 space-y-1",children:b.map((D,q)=>t.jsxs("li",{className:"flex items-center justify-between rounded-md border border-og-100 bg-surface px-2.5 py-1.5",children:[t.jsx("span",{title:D.name,className:"truncate text-xs text-og-700",children:D.name}),t.jsx("button",{type:"button","aria-label":n.createTask.removeImageAriaLabel(D.name),onClick:()=>_(q),disabled:j,className:"ml-2 shrink-0 text-og-400 transition-colors",children:"✕"})]},`${D.name}-${q}`))})]})]})})}const wn="***",$t={hostname:"",port:"",alias:"",user:"",password:""};function pa(e){return e.alias?e.alias:`${e.user?`${e.user}@`:""}${e.hostname}${e.port!=null?`:${e.port}`:""}`}function ga({open:e,onClose:n}){var ve;const s=M(),[r,a]=o.useState([]),[i,l]=o.useState("list"),[d,u]=o.useState(null),[m,h]=o.useState(null),[x,c]=o.useState(!1),[g,v]=o.useState(!1),[y,w]=o.useState($t),[S,A]=o.useState(null),[R,b]=o.useState(!1),[f,k]=o.useState(!1),[j,$]=o.useState(null),[I,K]=o.useState(!1),[C,B]=o.useState(null),W=o.useRef(0),J=o.useRef(null),{show:Z}=Re(),ee=o.useCallback(()=>{F.hosts.list().then(a).catch(E=>A(E instanceof Error?E.message:String(E)))},[]);o.useEffect(()=>{if(!e){J.current&&J.current.abort();return}l("list"),u(null),h(null),w($t),A(null),ee()},[e,ee]),o.useEffect(()=>{W.current+=1,J.current&&J.current.abort(),k(!1),$(null),K(!1),B(null)},[y.hostname,y.user,y.port,y.password,g,i]),o.useEffect(()=>()=>{J.current&&J.current.abort()},[]);const te=()=>{u(null),h(null),c(!1),v(!1),w($t),A(null),l("form")},X=E=>{u(E.id??null),h(E),c(E.password===wn),v(!1),w({hostname:E.hostname,port:E.port!=null?String(E.port):"",alias:E.alias??"",user:E.user??"",password:""}),A(null),l("form")},ie=()=>{const E={hostname:y.hostname.trim()};return d?(E.port=y.port.trim()?Number(y.port):null,E.alias=y.alias.trim(),E.user=y.user.trim()):(y.port.trim()&&(E.port=Number(y.port)),y.alias.trim()&&(E.alias=y.alias.trim()),y.user.trim()&&(E.user=y.user.trim())),d&&g?E.password="":y.password&&(E.password=y.password),E},N=y.port.trim(),G=N===""||/^\d+$/.test(N)&&Number(N)>0&&Number(N)<=65535,se=y.hostname.trim().length>0&&G,he=!!m&&y.hostname.trim()===m.hostname&&y.user.trim()===(m.user??"")&&y.port.trim()===(m.port!=null?String(m.port):""),O=()=>d&&he&&!y.password&&!g?{hostId:d}:{host:{hostname:y.hostname.trim(),...y.user.trim()?{user:y.user.trim()}:{},...N?{port:Number(N)}:{},...!g&&y.password?{password:y.password}:{}}},oe=async()=>{if(!se||f)return;J.current&&J.current.abort();const E=new AbortController;J.current=E;const L=W.current;k(!0),$(null),B(null),A(null);try{const H=await F.agents.probe("remote",O(),{signal:E.signal});if(E.signal.aborted||W.current!==L)return;$(H)}catch(H){if(E.signal.aborted||W.current!==L)return;A(H instanceof Error?H.message:String(H))}finally{W.current===L&&k(!1)}},ne=async()=>{if(I)return;const E=W.current;K(!0),B(null),A(null);try{const L=await F.agents.installTmux("remote",O());if(W.current!==E)return;B({ok:L.ok,message:L.message}),$(H=>H&&{...H,tmux:L.tmux})}catch(L){if(W.current!==E)return;A(L instanceof Error?L.message:String(L))}finally{W.current===E&&K(!1)}},be=async E=>{if(E.preventDefault(),!(!se||R)){b(!0),A(null);try{if(d)await F.hosts.update(d,ie()),Z({kind:"success",title:s.hostMgmt.updatedToastTitle(d)});else{const L=await F.hosts.create(ie());Z({kind:"success",title:s.hostMgmt.createdToastTitle(L.host.id)})}ee(),l("list")}catch(L){A(L instanceof Error?L.message:String(L))}finally{b(!1)}}},ye=async E=>{A(null);try{await F.hosts.delete(E.id),Z({kind:"success",title:s.hostMgmt.deletedToastTitle(E.id)}),ee()}catch(L){A(L instanceof Error?L.message:String(L))}},je=t.jsx("button",{type:"button",onClick:n,className:"btn-secondary",children:s.common.close}),fe=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:()=>l("list"),disabled:R,className:"btn-secondary",children:s.common.backText}),t.jsx("button",{type:"submit",form:"host-form",disabled:!se||R,className:"btn-primary",children:R?s.common.saving:s.common.save})]});return t.jsxs(Ae,{open:e,onClose:n,title:s.hostMgmt.title,size:"md",footer:i==="list"?je:fe,children:[S&&t.jsx("div",{className:"mb-3 whitespace-pre-line rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-sm text-accent",children:S}),i==="list"?t.jsxs("div",{className:"space-y-3",children:[r.length===0?t.jsx("p",{className:"text-sm text-og-500",children:s.hostMgmt.emptyState}):t.jsx("ul",{className:"space-y-1.5",children:r.map(E=>t.jsxs("li",{className:"flex items-center justify-between gap-3 rounded-md border border-og-100 px-3 py-2",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"truncate text-sm font-medium text-og-800",children:pa(E)}),t.jsxs("div",{className:"truncate text-xs text-og-500",children:[(E.user?`${E.user}@`:"")+E.hostname,E.port!=null?`:${E.port}`:"",E.password===wn?s.hostMgmt.passwordSavedIndicator:""]})]}),t.jsxs("div",{className:"flex shrink-0 gap-2",children:[t.jsx("button",{type:"button",onClick:()=>X(E),className:"text-xs text-accent transition-colors hover:text-accent-hover",children:s.common.edit}),t.jsx("button",{type:"button",onClick:()=>ye(E),className:"text-xs text-accent transition-colors hover:opacity-80",children:s.common.delete})]})]},E.id))}),t.jsx("button",{type:"button",onClick:te,className:"btn-secondary w-full",children:s.hostMgmt.addHostButton})]}):t.jsxs("form",{id:"host-form",onSubmit:be,className:"space-y-3",children:[t.jsxs("div",{children:[t.jsx("label",{className:re,htmlFor:"host-hostname",children:s.hostMgmt.addressLabel}),t.jsx("input",{id:"host-hostname",type:"text",value:y.hostname,onChange:E=>w({...y,hostname:E.target.value}),className:de,placeholder:"remote.example.com",disabled:R})]}),t.jsxs("div",{children:[t.jsx("label",{className:re,htmlFor:"host-port",children:s.hostMgmt.portLabel}),t.jsx("input",{id:"host-port",type:"text",inputMode:"numeric",value:y.port,onChange:E=>w({...y,port:E.target.value}),className:de,placeholder:"22",disabled:R}),y.port.trim()!==""&&!G&&t.jsx("div",{className:"mt-1 text-xs text-accent",children:s.hostMgmt.portRangeError})]}),t.jsxs("div",{children:[t.jsx("label",{className:re,htmlFor:"host-alias",children:s.hostMgmt.aliasLabel}),t.jsx("input",{id:"host-alias",type:"text",value:y.alias,onChange:E=>w({...y,alias:E.target.value}),className:de,placeholder:"Prod worker",disabled:R})]}),t.jsxs("div",{children:[t.jsx("label",{className:re,htmlFor:"host-user",children:s.hostMgmt.userLabel}),t.jsx("input",{id:"host-user",type:"text",value:y.user,onChange:E=>w({...y,user:E.target.value}),className:de,placeholder:s.hostMgmt.userPlaceholder,disabled:R})]}),t.jsxs("div",{children:[t.jsx("label",{className:re,htmlFor:"host-password",children:s.hostMgmt.passwordLabel}),t.jsx("input",{id:"host-password",type:"password",value:g?"":y.password,onChange:E=>w({...y,password:E.target.value}),className:de,placeholder:x?s.hostMgmt.passwordPlaceholderSet:s.hostMgmt.passwordPlaceholderUnset,disabled:R||g,autoComplete:"new-password"}),d&&x&&t.jsxs("label",{className:"mt-1.5 flex items-center gap-2 text-xs text-og-700",children:[t.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 accent-accent",checked:g,onChange:E=>v(E.target.checked),disabled:R}),s.hostMgmt.clearPasswordLabel]})]}),t.jsxs("div",{className:"rounded-md border border-accent/25 bg-accent-soft/60 px-3 py-2.5 text-xs text-accent",children:[s.hostMgmt.passwordHintLead,t.jsx("strong",{className:"font-semibold",children:s.hostMgmt.passwordHintStrong})," ",s.hostMgmt.plaintextWarningLead,t.jsx("strong",{className:"font-semibold",children:s.hostMgmt.plaintextWarningStrong}),s.hostMgmt.plaintextWarningTrail]}),t.jsxs("div",{className:"space-y-1.5",children:[t.jsx("button",{type:"button",onClick:oe,disabled:!se||f||R||I,className:"text-xs text-accent transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",children:f?s.hostMgmt.testing:s.hostMgmt.testConnection}),(j==null?void 0:j.ssh)&&t.jsxs("div",{className:`text-xs ${j.ssh.ok?"text-og-800":"text-accent"}`,children:["SSH: ",j.ssh.ok?"✓":"⨯"," ",j.ssh.message]}),j&&(j.tmux.ok?t.jsxs("div",{className:"text-xs text-og-800",children:["tmux: ✓ ",j.tmux.path??""]}):t.jsxs("div",{className:"text-xs text-accent",children:["tmux: ⨯ ",j.tmux.message,((ve=j.ssh)==null?void 0:ve.ok)&&t.jsx("button",{type:"button",onClick:ne,disabled:I||R,className:"ml-2 text-accent underline transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",children:I?s.common.installing:s.common.oneClickInstall})]})),I&&t.jsx("div",{className:"text-xs text-og-500",children:s.common.installingTmuxNotice}),!I&&C&&t.jsxs("div",{className:`break-all text-xs ${C.ok?"text-og-800":"text-accent"}`,children:[C.ok?"✓ ":"⨯ ",C.message]})]})]})]})}const sn="baxian.taskNotifications.enabled";function rn(){if(typeof window>"u")return null;const e=window.Notification;return typeof e=="function"?e:null}function lt(){const e=rn();return e?e.permission:"unsupported"}function Et(){try{return localStorage.getItem(sn)!=="0"}catch{return!0}}function ct(e){try{localStorage.setItem(sn,e?"1":"0")}catch{}}const us=o.createContext(null);function xa({children:e}){const[n,s]=o.useState(lt),[r,a]=o.useState(Et),[i,l]=o.useState(!1),d=o.useRef(!1),u=o.useRef(0);o.useEffect(()=>{const x=()=>{s(lt()),d.current||a(Et())},c=g=>{if(g.key!==null&&g.key!==sn)return;s(lt());const v=g.key===null?Et():g.newValue!=="0";v||(u.current+=1),a(v)};return window.addEventListener("focus",x),window.addEventListener("storage",c),()=>{window.removeEventListener("focus",x),window.removeEventListener("storage",c)}},[]);const m=o.useCallback(()=>{a(!0);const x=rn();if(!x){ct(!0);return}if(x.permission!=="default"){s(x.permission),ct(!0);return}if(d.current)return;d.current=!0,l(!0);const c=u.current;x.requestPermission().then(s).catch(g=>{console.warn("[task-notifications] permission request failed:",g),s(lt())}).finally(()=>{u.current===c&&ct(!0),d.current=!1,l(!1)})},[]),h=o.useCallback(()=>{u.current+=1,a(!1),ct(!1)},[]);return t.jsx(us.Provider,{value:{permission:n,preferenceEnabled:r,enabled:n==="granted"&&r,requesting:i,enable:m,disable:h},children:e})}function ms(){const e=o.useContext(us);if(!e)throw new Error("useTaskNotifications must be used inside TaskNotificationsProvider");return e}const ba=[{value:"en-US",label:"English"},{value:"zh-CN",label:"简体中文"}];function va({open:e,onClose:n}){const s=M(),{locale:r,saving:a,setLocale:i}=Yn(),{show:l}=Re(),d=async u=>{try{await i(u)}catch(m){const h=m instanceof Error?m.message:String(m);l({kind:"error",title:s.settings.languageSaveFailed(h)})}};return t.jsx(Ae,{open:e,onClose:n,title:s.settings.title,size:"sm",children:t.jsxs("div",{className:"space-y-5",children:[t.jsxs("fieldset",{children:[t.jsx("legend",{className:re,children:s.settings.language}),t.jsx("div",{className:"flex gap-4",children:ba.map(u=>t.jsxs("label",{className:"inline-flex items-center gap-2 text-sm text-og-800",children:[t.jsx("input",{type:"radio",name:"baxian-language",className:Ne,checked:r===u.value,disabled:a,onChange:()=>void d(u.value)}),u.label]},u.value))})]}),t.jsx(wa,{})]})})}function wa(){const e=M(),{permission:n,enabled:s,requesting:r,enable:a,disable:i}=ms();if(n==="unsupported")return null;const l=n==="denied";return t.jsxs("div",{children:[t.jsxs("label",{className:"inline-flex items-center gap-2 text-sm text-og-800",children:[t.jsx("input",{type:"checkbox",className:Ne,checked:s,disabled:l||r,onChange:()=>s?i():a()}),e.settings.taskNotifications]}),t.jsx("p",{className:Ke,children:l?e.settings.taskNotificationsDenied:e.settings.taskNotificationsHint})]})}const fs="topbar-actions";function yn(){return typeof document>"u"?null:document.getElementById(fs)}function hs({children:e}){const[n,s]=o.useState(yn);return o.useEffect(()=>{n||s(yn())},[n]),n?Os.createPortal(e,n):null}function ya(){return ns("/api/realtime")}class ja{constructor(n={}){ae(this,"wsUrl");ae(this,"wsFactory");ae(this,"tokenProvider");ae(this,"ws",null);ae(this,"topics",new Map);ae(this,"cache",new Map);ae(this,"outbox",[]);ae(this,"reconnectScheduler");ae(this,"explicitlyClosed",!1);this.wsUrl=n.wsUrl??ya(),this.wsFactory=n.wsFactory??ss,this.tokenProvider=n.tokenProvider??Kt,this.reconnectScheduler=new es({reconnect:()=>this.openSocket(),shouldReconnect:()=>!this.explicitlyClosed&&this.topics.size>0})}subscribe(n,s,r){let a=this.topics.get(n);const i=!a;return a||(a={data:new Set,error:new Set},this.topics.set(n,a)),a.data.add(s),r&&a.error.add(r),i?(this.ensureSocket(),this.wsSendOrQueue({op:"subscribe",topic:n})):this.cache.has(n)&&queueMicrotask(()=>{var l;(l=this.topics.get(n))!=null&&l.data.has(s)&&this.cache.has(n)&&s(this.cache.get(n))}),()=>this.unsubscribe(n,s,r)}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(n,s,r){const a=this.topics.get(n);a&&(a.data.delete(s),r&&a.error.delete(r),a.data.size===0&&a.error.size===0&&(this.topics.delete(n),this.cache.delete(n),this.wsSendOrQueue({op:"unsubscribe",topic:n}),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 n=this.tokenProvider(),s=n?[`baxian.token.${ts(n)}`]:void 0;let r;try{r=this.wsFactory(this.wsUrl,s)}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=r;let a=!1;r.onopen=()=>{if(r!==this.ws)return;a=!0,this.reconnectScheduler.reset();for(const l of this.topics.keys())try{r.send(JSON.stringify({op:"subscribe",topic:l}))}catch(d){console.warn("[events-client] resubscribe send failed:",d)}const i=this.outbox;this.outbox=[];for(const l of i)if(!(l.op==="subscribe"||l.op==="unsubscribe"))try{r.send(JSON.stringify(l))}catch(d){console.warn("[events-client] outbox flush failed:",d)}},r.onmessage=i=>{if(r!==this.ws)return;let l;try{const d=typeof i.data=="string"?i.data:String(i.data);l=JSON.parse(d)}catch{return}this.handleMessage(l)},r.onclose=()=>{r===this.ws&&(this.ws=null,!this.explicitlyClosed&&(a||this.broadcastConnectionError({code:"connection_failed",message:"WebSocket failed to connect (auth, network, or proxy issue)"}),this.topics.size!==0&&this.scheduleReconnect()))},r.onerror=()=>{}}scheduleReconnect(){this.reconnectScheduler.schedule()}broadcastConnectionError(n){for(const s of this.topics.values())for(const r of[...s.error])try{r(n)}catch(a){console.error("[events-client] error handler threw on connection error:",a)}}wsSendOrQueue(n){if(this.ws&&this.ws.readyState===WebSocket.OPEN)try{this.ws.send(JSON.stringify(n));return}catch(s){console.warn("[events-client] send failed, will queue:",s)}this.outbox.push(n)}handleMessage(n){switch(n.type){case"data":{const s=this.topics.get(n.topic);if(this.cache.set(n.topic,n.data),!s)return;for(const r of[...s.data])try{r(n.data)}catch(a){console.error(`[events-client] handler threw on ${n.topic}:`,a)}break}case"error":{const s={code:n.code,message:n.message};if(n.topic){const r=this.topics.get(n.topic);if(r)for(const a of[...r.error])try{a(s)}catch(i){console.error(`[events-client] error handler threw on ${n.topic}:`,i)}}else console.warn("[events-client] connection-level error:",n.code,n.message);break}}}}let Dt=null;function et(){return Dt||(Dt=new ja),Dt}function an(){const[e,n]=o.useState(null),[s,r]=o.useState(!1),[a,i]=o.useState(null);return o.useEffect(()=>et().subscribe("agents",d=>{i(null),n(d),r(!0)},d=>i(d)),[]),{data:e,loaded:s,error:a}}function on(e){const[n,s]=o.useState(null),[r,a]=o.useState(!1),[i,l]=o.useState(null);return o.useEffect(()=>(s(null),a(!1),l(null),et().subscribe(`task:${e}`,u=>{l(null),s(u),a(!0)},u=>l(u))),[e]),{data:n,loaded:r,error:i}}function ps(e){const[n,s]=o.useState(null),[r,a]=o.useState(!1),[i,l]=o.useState(null);return o.useEffect(()=>{if(!e){s(null),a(!1),l(null);return}s(null),a(!1),l(null);let d=!1,u=!1,m=!1;const h=et().subscribe(`project-tasks:${e}`,x=>{d||(u=!0,l(null),s(x),a(!0))},x=>{d||(l(x),!(u||m)&&(m=!0,F.tasks.list(e).then(c=>{d||u||(s(c),a(!0))},c=>{console.warn(`[useProjectTasks] REST fallback failed for ${e}:`,c)})))});return()=>{d=!0,h()}},[e]),{data:n,loaded:r,error:i}}let gt=null,Pe=null,xt=null,Ve=0;const _t=new Set;function gs(){_t.forEach(e=>e())}async function ka(){const e=Ve;try{const n=await F.projects.list();if(e!==Ve)return;gt=n,xt=null}catch(n){if(e!==Ve)return;xt=n instanceof Error?n.message:String(n)}finally{e===Ve&&(Pe=null,gs())}}function Ut(){return Pe||(Pe=ka(),Pe)}function Na(){Ve+=1,gt=null,Pe=null,xt=null,gs()}typeof window<"u"&&window.addEventListener(mt,Na);async function Sa(){const e=Pe!==null;await Ut(),e&&await Ut()}function tt(){const[,e]=o.useState(0);return o.useEffect(()=>{const n=()=>e(s=>s+1);return _t.add(n),gt===null&&!Pe&&Ut(),()=>{_t.delete(n)}},[]),{projects:gt,error:xt,refresh:Sa}}function Ta(){const e=M(),n=Te(),{projects:s,error:r,refresh:a}=tt(),i=s??[],l=s!==null,[d,u]=o.useState(!1),[m,h]=o.useState(!1),[x,c]=o.useState(!1),[g,v]=o.useState(!1),[y,w]=o.useState({kind:"closed"}),{data:S,loaded:A,error:R}=an(),b=(R==null?void 0:R.message)??null,f=new Map((S??[]).map(I=>[I.id,I])),k=r??b,j=i.length===0,$=t.jsx("button",{type:"button",onClick:()=>h(!0),disabled:j,"aria-describedby":j?"create-task-hint":void 0,className:"btn-ghost",children:e.dashboard.newTask});return t.jsxs("div",{children:[t.jsxs(hs,{children:[j?t.jsx("span",{className:"inline-flex",title:e.dashboard.createProjectFirst,children:$}):$,j&&t.jsx("span",{id:"create-task-hint",className:"sr-only",children:e.dashboard.createProjectFirst}),t.jsx(Qt,{ariaLabel:e.dashboard.moreActions,children:I=>t.jsxs(t.Fragment,{children:[t.jsx(Se,{onClick:()=>{I(),u(!0)},children:e.dashboard.newProject}),t.jsx(Se,{onClick:()=>{I(),c(!0)},children:e.dashboard.manageHosts}),t.jsx(Se,{onClick:()=>{I(),v(!0)},children:e.settings.entry})]})})]}),t.jsx("h1",{className:"sr-only",children:"Dashboard"}),k&&t.jsx("div",{className:"mb-4 text-sm text-accent",children:e.common.loadFailed(k)}),l&&i.length===0&&!r&&t.jsx("div",{className:"rounded-lg border border-hairline bg-surface py-12 text-center text-sm text-og-500",children:e.dashboard.emptyProjects}),i.map(I=>t.jsx(Ra,{project:I,agentsById:f,agentsLoaded:A,agentsError:!!R,onAgentDeleted:a},I.id)),t.jsx(la,{open:d,onClose:()=>u(!1),onCreated:I=>{u(!1),a(),w({kind:"asking",projectId:I})}}),t.jsx(ga,{open:x,onClose:()=>c(!1)}),t.jsx(Ae,{open:y.kind==="asking",onClose:()=>w({kind:"closed"}),title:e.dashboard.projectCreatedTitle,size:"sm",footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:()=>w({kind:"closed"}),className:"btn-secondary",children:e.dashboard.later}),t.jsx("button",{type:"button",onClick:()=>{y.kind==="asking"&&w({kind:"addingAgent",projectId:y.projectId})},className:"btn-primary",children:e.dashboard.continueAddingAgent})]}),children:t.jsx("p",{className:"text-sm text-og-700",children:e.dashboard.addAgentNowOrLater})}),y.kind==="addingAgent"&&t.jsx(ds,{open:!0,projectId:y.projectId,onClose:()=>w({kind:"closed"}),onCreated:()=>{a()}}),t.jsx(nn,{open:m,onClose:()=>h(!1),onCreated:I=>n(Fe(I.projectId,I.id))}),t.jsx(va,{open:g,onClose:()=>v(!1)})]})}function Ra({project:e,agentsById:n,agentsLoaded:s,agentsError:r,onAgentDeleted:a}){const i=M(),{data:l,error:d}=ps(e.id),u=l??[],m=(d==null?void 0:d.message)??null;return t.jsxs("div",{className:"mb-10",children:[t.jsxs("div",{className:"mb-3 -mx-2 flex items-baseline gap-x-3 gap-y-1 px-2 py-1",children:[t.jsx("h2",{className:"min-w-0 truncate font-display text-sm font-semibold tracking-tight text-og-1000",title:e.id,children:t.jsx(_e,{to:`/project/${e.id}`,className:"hover:text-accent-hover",children:e.id})}),t.jsx("span",{className:"hidden min-w-0 truncate font-mono text-xs text-og-500 sm:inline-block",title:e.repo,children:e.repo}),t.jsx(_e,{to:`/project/${e.id}`,className:"ml-auto text-sm text-accent hover:text-accent-hover","aria-label":i.dashboard.detailsAriaLabel(e.id),children:i.dashboard.detailsLink})]}),m&&t.jsx("div",{className:"mb-2 text-xs text-accent",children:i.dashboard.tasksLoadFailed(m)}),e.agent.flat().length===0?t.jsx("div",{className:"rounded-lg border border-hairline bg-surface py-6 text-center text-sm text-og-500",children:i.dashboard.noAgentsYet}):t.jsx("div",{className:e.agent.length===1?"space-y-3":"grid grid-cols-1 gap-3 xl:grid-cols-2",children:e.agent.map((h,x)=>t.jsx(cs,{group:h,projectId:e.id,agentsById:n,agentsLoaded:s,agentsError:r,tasks:u,onDeleted:a,terminalMode:"embedded-full"},h.map(c=>c.id).join(":")||x))})]})}const xs="baxian.taskPanel.doneOpen";function Ca(){try{return localStorage.getItem(xs)==="1"}catch{return!1}}function bt(e){const n=e.match(/^task-(\d+)$/);return n?parseInt(n[1],10):Number.NaN}function Aa(e,n){const s=bt(e.id),r=bt(n.id);return Number.isNaN(s)||Number.isNaN(r)?e.id.localeCompare(n.id):s-r}function La(e,n){const s=(n.updatedAt??"").localeCompare(e.updatedAt??"");if(s!==0)return s;const r=bt(e.id),a=bt(n.id);return Number.isNaN(r)||Number.isNaN(a)?n.id.localeCompare(e.id):a-r}function jn(e,n){const[s,r]=o.useState(kt);o.useEffect(()=>r(kt),[n]);const a=e.slice(0,s),i=e.length>a.length;return{items:a,hasMore:i,loadMore:()=>r(d=>d+kt),total:e.length}}function Pa(e){const[n,s]=o.useState([]),[r,a]=o.useState(!1),[i,l]=o.useState(!1),[d,u]=o.useState(!1),[m,h]=o.useState(null),x=o.useRef(0),c=o.useRef(0),g=o.useCallback(v=>{const y=++x.current,w=v==="first"?0:c.current;l(!0),h(null),F.tasks.page(e,{category:"done",offset:w}).then(S=>{x.current===y&&(s(A=>v==="first"?S.tasks:[...A,...S.tasks]),a(S.hasMore),c.current=S.nextOffset,u(!0),l(!1))},S=>{x.current===y&&(h(S instanceof Error?S.message:String(S)),l(!1))})},[e]);return o.useEffect(()=>{x.current+=1,c.current=0,s([]),a(!1),u(!1),h(null),l(!1)},[e]),{items:n,hasMore:r,loading:i,loaded:d,error:m,load:g}}function $a({projectId:e,openTasks:n,className:s=""}){const r=M(),a=o.useMemo(()=>n.filter(c=>On.has(c.status)).sort(La),[n]),i=o.useMemo(()=>n.filter(c=>c.status==="pending").sort(Aa),[n]),l=jn(a,e),d=jn(i,e),u=Pa(e),[m,h]=o.useState(Ca);o.useEffect(()=>{try{localStorage.setItem(xs,m?"1":"0")}catch{}},[m]),o.useEffect(()=>{m&&u.load("first")},[m,u.load]);const x=()=>h(c=>!c);return t.jsx("aside",{"aria-label":r.taskPanel.ariaLabel,className:`flex flex-col rounded-lg border border-hairline bg-surface ${s}`,children:t.jsxs("div",{children:[t.jsx(kn,{title:"IN PROGRESS",section:l,emptyHint:r.taskPanel.emptyInProgress}),t.jsx(kn,{title:"PENDING",section:d,emptyHint:r.taskPanel.emptyPending}),t.jsxs("div",{children:[t.jsxs("button",{type:"button",onClick:x,"aria-expanded":m,className:"flex w-full items-center justify-between px-3 py-2 text-left text-xs font-normal uppercase tracking-[0.05em] text-og-500 transition-colors hover:bg-og-50/40",children:[t.jsx("span",{children:"DONE"}),t.jsx("span",{className:"font-normal normal-case text-accent",children:m?r.taskPanel.collapse:r.taskPanel.view})]}),m&&t.jsx(Ea,{state:u})]})]})})}function kn({title:e,section:n,emptyHint:s}){const r=M();return t.jsxs("section",{"aria-label":e,className:"border-b border-hairline",children:[t.jsxs("div",{className:"px-3 py-2 text-xs font-normal uppercase tracking-[0.05em] text-og-500",children:[e," ",t.jsxs("span",{className:"text-og-400",children:["(",n.total,")"]})]}),n.items.length===0?t.jsx("div",{className:"px-3 pb-3 text-xs text-og-400",children:s}):t.jsxs("div",{className:"divide-y divide-hairline",children:[n.items.map(a=>t.jsx(bs,{task:a},a.id)),n.hasMore&&t.jsx("button",{type:"button",onClick:n.loadMore,className:"w-full px-3 py-2 text-center text-xs text-accent transition-colors hover:bg-og-50/40",children:r.taskPanel.loadMore})]})]})}function Ea({state:e}){const n=M(),s=e.loaded&&!e.error&&e.items.length===0;return t.jsxs("div",{className:"divide-y divide-hairline",children:[e.items.map(r=>t.jsx(bs,{task:r},r.id)),e.error&&t.jsx("div",{className:"px-3 py-2 text-xs text-accent",children:n.common.loadFailed(e.error)}),s&&t.jsx("div",{className:"px-3 pb-3 pt-1 text-xs text-og-400",children:n.taskPanel.emptyDone}),e.loading&&e.items.length===0&&t.jsx("div",{className:"px-3 py-3 text-center text-xs text-og-400",children:n.common.loading}),e.hasMore&&t.jsx("button",{type:"button",onClick:()=>e.load("more"),disabled:e.loading,className:"w-full px-3 py-2 text-center text-xs text-accent transition-colors hover:bg-og-50/40 disabled:opacity-50",children:e.loading?n.common.loading:n.taskPanel.loadMore})]})}function Da(e){const[n,s]=o.useState(!1);return o.useEffect(()=>{function r(){if(e.status!=="review"||!e.reviewDispatchedAt||!e.qaAgentId){s(!1);return}s(Date.now()-Date.parse(e.reviewDispatchedAt)>=Hn)}r();const a=setInterval(r,3e4);return()=>clearInterval(a)},[e.status,e.reviewDispatchedAt,e.qaAgentId]),n}function bs({task:e}){const n=M(),s=Te(),r=Ce(e.phase)?e.specReviewRound??0:e.reviewRound,a=Da(e);return t.jsxs("button",{type:"button",onClick:()=>s(Fe(e.projectId,e.id)),className:"flex w-full items-center gap-2 px-3 py-2 text-left text-sm transition-colors hover:bg-og-50/60",children:[t.jsx("span",{className:"shrink-0 font-mono text-xs text-og-500",title:e.id,children:tn(e.id)}),t.jsx("span",{className:"min-w-0 flex-1 truncate text-og-1000",title:e.title,children:e.title}),Ce(e.phase)&&t.jsx("span",{className:"pill pill-review shrink-0",children:e.phase}),a&&t.jsx("span",{className:"pill pill-warn shrink-0",title:"Review verdict missing",children:"!"}),t.jsxs("span",{"aria-label":n.agents.round(r),className:"shrink-0 text-xs text-og-400",children:["R",r]}),t.jsx(ea,{status:e.status})]})}const Ia=[],vs="baxian.taskPanel.open";function Fa(){try{return localStorage.getItem(vs)!=="0"}catch{return!0}}function Ba(){const{id:e}=Ze(),n=Te(),s=M(),{show:r}=Re(),{refresh:a}=tt(),[i,l]=o.useState(null),[d,u]=o.useState(null),[m,h]=o.useState(!1),[x,c]=o.useState(!1),g=o.useRef(null),[v,y]=o.useState(Fa),[w,S]=o.useState(!1),[A,R]=o.useState(""),[b,f]=o.useState(!1),[k,j]=o.useState(null),$=o.useRef(0),{data:I,loaded:K,error:C}=an(),{data:B,error:W}=ps(e),J=(C==null?void 0:C.message)??null,Z=(W==null?void 0:W.message)??null,ee=B??Ia,te=new Map((I??[]).map(O=>[O.id,O])),X=d??J??Z,ie=o.useCallback(async O=>{const oe=++$.current;try{const ne=await F.projects.get(O);if(oe!==$.current)return;l(ne),u(null)}catch(ne){if(oe!==$.current)return;u(ne instanceof Error?ne.message:String(ne))}},[]);o.useEffect(()=>{e&&(l(null),u(null),ie(e))},[e,ie]),o.useEffect(()=>{w||(R(""),j(null))},[w]),o.useEffect(()=>{try{localStorage.setItem(vs,v?"1":"0")}catch{}},[v]);const N=(i==null?void 0:i.agent.flat().length)??0,G=N===0,se=!!i&&A.trim()===i.id,he=async()=>{if(!(!i||!se||b)){f(!0),j(null);try{await F.projects.delete(i.id),await a(),r({kind:"success",title:s.projectPage.deletedToastTitle(i.id)}),S(!1),n("/")}catch(O){j(O instanceof Error?O.message:String(O))}finally{f(!1)}}};return i?t.jsxs("div",{children:[t.jsxs(hs,{children:[t.jsx("button",{type:"button",onClick:()=>c(!0),className:"btn-ghost",children:s.projectPage.newTaskButton}),t.jsx(Qt,{ariaLabel:s.projectPage.menuAriaLabel(i.id),menuClassName:"min-w-[180px]",triggerRef:g,children:O=>t.jsxs(t.Fragment,{children:[!v&&t.jsx(Se,{onClick:()=>{O(),y(!0)},children:s.projectPage.showTaskPanel}),t.jsx(Se,{onClick:()=>{O(),h(!0)},children:s.projectPage.addAgent}),t.jsx("div",{role:"none",className:"my-1 border-t border-hairline"}),t.jsx(Se,{onClick:()=>{O(),S(!0)},disabled:!G,title:G?void 0:s.projectPage.deleteAgentsFirstHint(N),children:s.projectPage.deleteProjectMenuItem})]})})]}),X&&t.jsx("div",{className:"mb-4 text-sm text-accent",children:s.common.loadFailed(X)}),t.jsxs("div",{className:"mb-6 flex items-baseline gap-x-3",children:[t.jsx("h1",{className:"min-w-0 truncate font-display text-sm font-semibold tracking-tight text-og-1000",title:i.id,children:i.id}),t.jsx("span",{className:"hidden min-w-0 truncate font-mono text-xs text-og-500 sm:inline-block",title:i.repo,children:i.repo})]}),t.jsxs("div",{className:"flex flex-col gap-4 lg:flex-row lg:items-start",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:"mb-3 flex h-8 items-center gap-2",children:t.jsx("h2",{className:"font-display text-xs font-semibold uppercase tracking-[0.06em] text-og-500",children:"Agents"})}),i.agent.flat().length===0?t.jsx("div",{className:"mb-8 rounded-lg border border-hairline bg-surface py-6 text-center text-sm text-og-500",children:s.projectPage.noAgentsYet}):t.jsx("div",{className:"mb-8 space-y-5",children:i.agent.map((O,oe)=>t.jsx(cs,{group:O,projectId:i.id,agentsById:te,agentsLoaded:K,agentsError:!!C,tasks:ee,onDeleted:()=>{ie(i.id)},terminalMode:"embedded-full"},O.map(ne=>ne.id).join(":")||oe))})]}),v&&t.jsxs("div",{className:"w-full lg:w-[340px] lg:shrink-0 xl:w-[380px]",children:[t.jsxs("div",{className:"mb-3 flex h-8 items-center justify-between gap-2",children:[t.jsx("h2",{className:"font-display text-xs font-semibold uppercase tracking-[0.06em] text-og-500",children:"Tasks"}),t.jsx("button",{type:"button",onClick:()=>{var O;y(!1),(O=g.current)==null||O.focus()},"aria-label":s.projectPage.closeTaskPanel,className:"flex h-7 w-7 items-center justify-center rounded text-og-500 transition-colors hover:bg-og-50 hover:text-og-1000",children:t.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:[t.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),t.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),t.jsx($a,{projectId:i.id,openTasks:ee})]})]}),t.jsx(ds,{open:m,projectId:i.id,onClose:()=>h(!1),onCreated:()=>{ie(i.id)}}),t.jsx(nn,{open:x,projectId:i.id,onClose:()=>c(!1),onCreated:O=>n(Fe(O.projectId,O.id))}),t.jsx(Ae,{open:w,onClose:()=>{b||S(!1)},title:s.projectPage.deleteModalTitle,size:"sm",footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:()=>S(!1),disabled:b,className:"btn-secondary",children:s.common.cancel}),t.jsx("button",{type:"button",onClick:()=>void he(),disabled:!se||b,className:"btn-primary",children:b?s.common.deleting:s.projectPage.confirmDeleteButton})]}),children:t.jsxs("div",{className:"space-y-4",children:[t.jsxs("p",{className:"text-sm text-og-700",children:[s.projectPage.deleteBodyLead,t.jsx("code",{className:"font-mono text-og-1000",children:"baxian.json"}),s.projectPage.deleteBodyMid,t.jsx("span",{className:"font-mono text-og-1000",children:i.id}),s.projectPage.deleteBodySuffix]}),t.jsxs("p",{className:"text-sm text-og-700",children:[s.projectPage.confirmInputLead,t.jsx("span",{className:"font-mono text-og-1000",children:i.id}),s.projectPage.confirmInputSuffix]}),t.jsx("input",{type:"text",value:A,onChange:O=>R(O.target.value),placeholder:i.id,autoComplete:"off",autoCorrect:"off",spellCheck:!1,disabled:b,"aria-label":s.projectPage.confirmInputAriaLabel,className:"w-full rounded border border-hairline bg-surface px-3 py-2 font-mono text-sm text-og-1000 focus:border-accent focus:outline-none"}),k&&t.jsx("div",{className:"rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-xs text-accent",children:k})]})})]}):d?t.jsx("div",{className:"text-sm text-accent",children:s.common.loadFailed(d)}):t.jsx("div",{className:"text-sm text-og-500",children:s.common.loading})}function ws(e){return[e.specReviewRound??0,e.reviewRound,e.status,e.phase??"code",e.batchIndex??-1,e.batchTotal??-1].join(":")}function ys(e,n){const[s,r]=o.useState(null),[a,i]=o.useState(!1),[l,d]=o.useState(null),u=o.useRef(e);return o.useEffect(()=>{let m=!0;return u.current!==e&&(u.current=e,r(null),i(!1)),d(null),F.tasks.reviews(e).then(h=>{m&&(r(h),i(!0))}).catch(h=>{m&&(d(h instanceof Error?h.message:String(h)),r([]),i(!0))}),()=>{m=!1}},[e,n]),{rounds:s,loaded:a,error:l}}const js={approve:"pill pill-live","request-changes":"pill pill-warn",comment:"pill"};function ks(e){const n=e.some(i=>i.roundToken!==void 0),s=i=>n?i.roundToken!==void 0:i.kind==="review",r=[];let a=[];for(const i of e)s(i)?(r.push({items:a,review:i}),a=[]):a.push(i);return a.length>0&&r.push({items:a}),r}function Xe(e,n){const s=e.id||e.commitSha||e.createdAt||e.body||n;return e.sourceKey!==void 0?JSON.stringify([e.kind,e.sourceKey,s]):`${e.kind}-${s}`}function yt(e){if(e.id)return e.sourceKey!==void 0?`pr-${e.kind}.${e.sourceKey}.${e.id}`:`pr-${e.kind}-${e.id}`}function Ns(e,n){return e.review?`round-${Xe(e.review,n)}`:`round-in-progress-${e.items[0]?Xe(e.items[0],n):n}`}function Ss(e){return[e.reviewRound,e.latestHeadSha??"",e.status,e.reviewDispatchedAt??"",e.prFeedbackReceivedAt??"",e.prNumber??"",e.reviewConversationUpdatedAt??""].join(":")}const Ma=4e3,Oa=6e4;function Ts(e,n){const[s,r]=o.useState(null),[a,i]=o.useState(!1),[l,d]=o.useState(null),[u,m]=o.useState(0),h=o.useRef(e),x=o.useRef(n),c=o.useRef(0),g=o.useRef(0);return o.useEffect(()=>{h.current!==e&&(h.current=e,r(null),i(!1),g.current=0),x.current!==n&&(x.current=n,g.current=0);const v=++c.current;let y;return d(null),F.tasks.prReview(e).then(w=>{if(c.current===v)if(r(w),i(!0),w.available&&w.error&&g.current<3){g.current+=1;const S=w.rateLimited?Oa*2**(g.current-1):Ma*g.current;y=setTimeout(()=>m(A=>A+1),S)}else w.error||(g.current=0)}).catch(w=>{c.current===v&&(d(w instanceof Error?w.message:String(w)),r(null),i(!0))}),()=>clearTimeout(y)},[e,n,u]),{data:s,loaded:a,error:l}}function Oe({role:e,label:n,summary:s,badge:r,onClick:a}){const i=M();return t.jsxs("button",{type:"button",onClick:a,className:"card flex w-full items-center gap-2 px-3 py-2 text-left text-sm",children:[t.jsx("span",{className:"shrink-0 min-w-[1.75rem] text-xs tracking-wide text-og-600",children:e==="qa"?i.review.roleQa:e==="user"?i.review.roleUser:i.review.roleDev}),t.jsx("span",{className:"shrink-0 text-og-800",children:n}),r,t.jsx("span",{className:"min-w-0 flex-1 truncate text-og-500",children:s}),t.jsx("span",{"aria-hidden":!0,className:"shrink-0 text-og-300",children:"›"})]})}function Ha(e){return{"server-mode":e.prReview.reasonServerModeEntry,"no-pr":e.prReview.reasonNoPr,"driver-unavailable":e.prReview.reasonDriverUnavailable}}function _a(e){return(e==null?void 0:e.trim().split(`
|
|
9
|
-
`,1)[0])??""}function Ua(e){if(!(e.kind!=="review-comment"||!e.path))return e.line!==void 0?`${e.path}:${e.line}`:e.path}function qa(e,n){return n.bodyTruncated?e.prReview.truncatedSuffix:""}function Wa(e,n){const s=_a(n.body),r=qa(e,n);if(n.kind==="review-comment"){const a=Ua(n);if(n.inReplyTo){const i=[n.author,a,s].filter(l=>!!l);if(i.length>0)return`${i.join(" · ")}${r}`}return a&&s?`${a} · ${s}${r}`:`${s||a||e.prReview.inlineComment}${r}`}return n.kind==="issue-comment"?n.author&&s?`${n.author} · ${s}${r}`:`${s||n.author||e.prReview.comment}${r}`:`${s||e.prReview.noReviewBodyFallback}${r}`}function Ga(e,n){return n.verdict!==void 0||n.kind==="review"?e.review.reviewTurnLabel:n.kind==="review-comment"?n.inReplyTo?e.review.responseTurnLabel:e.prReview.inlineComment:e.prReview.comment}function Qa(e){return e.verdict!==void 0?"qa":e.kind==="issue-comment"||e.inReplyTo?"dev":"qa"}function za({task:e}){const n=M(),s=Te(),r=Ss(e),{data:a,loaded:i,error:l}=Ts(e.id,r);function d(m){s(`/tasks/${encodeURIComponent(e.id)}/pr-review${m?`#${m}`:""}`)}if(l)return t.jsx(Qe,{children:t.jsx("div",{className:"text-sm text-accent",children:n.review.loadFailed(l)})});if(!i)return t.jsx(Qe,{children:t.jsx("div",{className:"text-sm text-og-400",children:n.review.loadingRecords})});if(!(a!=null&&a.available)){const m=Ha(n);return t.jsx(Qe,{children:t.jsx("div",{className:"text-sm text-og-400",children:m[(a==null?void 0:a.reason)??"no-pr"]??m["no-pr"]})})}if(a.items.length===0)return t.jsx(Qe,{children:a.truncated?t.jsx("div",{className:"text-sm text-accent",children:n.prReview.listTruncated}):a.error?t.jsx("div",{className:"text-sm text-accent",children:n.prReview.fetchFailed(a.error)}):t.jsx("div",{className:"text-sm text-og-400",children:n.review.notStarted})});const u=ks(a.items);return t.jsxs(Qe,{children:[a.error&&t.jsx("div",{className:"text-xs text-accent",children:n.prReview.partialFetchFailed(a.error)}),a.truncated&&t.jsx("div",{className:"text-xs text-accent",children:n.prReview.listTruncated}),u.map((m,h)=>t.jsx(Ka,{round:m,index:h,onOpen:d},Ns(m,String(h))))]})}function Qe({children:e}){const n=M();return t.jsxs("div",{children:[t.jsx("div",{className:"mb-1.5 text-xs text-og-700",children:n.prReview.codeReviewHeading}),t.jsx("div",{className:"space-y-3",children:e})]})}function Ka({round:e,index:n,onOpen:s}){const r=M(),a=e.review?r.agents.round(n+1):r.status.in_progress;return t.jsxs("div",{children:[t.jsx("div",{className:"mb-1 text-xs text-og-400",children:a}),t.jsxs("div",{className:"space-y-1.5",children:[e.items.map((i,l)=>t.jsx(Nn,{item:i,onOpen:s},Xe(i,`${n}-${l}`))),e.review&&t.jsx(Nn,{item:e.review,onOpen:s})]})]})}function Nn({item:e,onOpen:n}){const s=M(),r=e.verdict,a=r?t.jsx("span",{className:js[r],children:r}):e.kind==="review"&&e.reviewState?t.jsx("span",{className:"pill",children:e.reviewState}):void 0;return t.jsx(Oe,{role:Qa(e),label:Ga(s,e),badge:a,summary:Wa(s,e),onClick:()=>n(yt(e))})}const Sn={approve:"pill pill-live","request-changes":"pill pill-warn",archive:"pill"};function Tn(e){if(!e)return 0;const n=e.endsWith(`
|
|
10
|
-
`)?e.slice(0,-1):e;return n===""?0:n.split(`
|
|
11
|
-
`).length}function Va(e,n){return n.phase==="code"?(n.diffstat??"").split(`
|
|
12
|
-
`).map(r=>r.trim()).filter(Boolean).pop()??e.review.diffLineCount(Tn(n.content)):e.review.specDocLineCount(Tn(n.content))}function Rn(e,n){const s={critical:0,major:0,minor:0};for(const i of n.findings)i.severity in s&&s[i.severity]++;const r=[];s.critical&&r.push(`${s.critical} critical`),s.major&&r.push(`${s.major} major`),s.minor&&r.push(`${s.minor} minor`);const a=n.findings.length;return e.review.findingsSummary(a,r.join(", "))}function Ya(e,n){const s={fix:0,reject:0,"out-of-scope":0};for(const a of n.responses)a.action in s&&s[a.action]++;const r=[];return s.fix&&r.push(`${s.fix} fixed`),s.reject&&r.push(`${s.reject} rejected`),s["out-of-scope"]&&r.push(`${s["out-of-scope"]} out-of-scope`),r.join(" · ")||e.review.responsesSummary(n.responses.length)}function Ja({task:e}){const n=M(),s=e.reviewMode==="server"||(e.specReviewRound??0)>0,r=e.reviewMode!=="server"&&e.prNumber!==void 0;return!s&&!r?null:t.jsxs("section",{className:"mt-4","aria-label":n.review.sectionTitle,children:[t.jsx("div",{className:"mb-2 text-sm text-og-700",children:n.review.sectionTitle}),t.jsxs("div",{className:"space-y-4",children:[s&&t.jsx(Xa,{task:e}),r&&t.jsx(za,{task:e})]})]})}function Xa({task:e}){const n=M(),s=Te(),{rounds:r,loaded:a,error:i}=ys(e.id,ws(e));function l(d,u,m){s(`/tasks/${encodeURIComponent(e.id)}/rounds/${d}/${u}${m}`)}return i?t.jsx("div",{className:"text-sm text-accent",children:n.review.loadFailed(i)}):a?((r==null?void 0:r.length)??0)===0?t.jsx("div",{className:"text-sm text-og-400",children:n.review.notStarted}):t.jsx(t.Fragment,{children:["spec","code"].map(d=>{const u=(r??[]).filter(m=>m.phase===d).sort((m,h)=>m.round-h.round);return u.length===0?null:t.jsx(Za,{title:n.review.phaseLabel[d],children:u.map(m=>t.jsx(ei,{round:m,task:e,onOpen:l},`${d}-${m.round}`))},d)})}):t.jsx("div",{className:"text-sm text-og-400",children:n.review.loadingRecords})}function Za({title:e,children:n}){return t.jsxs("div",{children:[t.jsx("div",{className:"mb-1.5 text-xs text-og-700",children:e}),t.jsx("div",{className:"space-y-3",children:n})]})}function ei({round:e,task:n,onOpen:s}){const r=M(),a=e.phase==="spec",i=n.phase??"code",l=Math.max(i==="spec"?n.specReviewRound??0:n.reviewRound,1),u=e.phase===i&&e.round===l&&(n.status==="fixing"||n.status==="review"&&e.findings===void 0),m=e.findings===void 0?(e.batchFindings??[]).filter(Boolean):[];return t.jsxs("div",{children:[t.jsx("div",{className:"mb-1 text-xs text-og-400",children:r.agents.round(e.round)}),t.jsxs("div",{className:"space-y-1.5",children:[t.jsx(Oe,{role:"dev",label:a?r.review.submitSpecDraft:r.review.submitCodeChanges,summary:Va(r,e),onClick:()=>s(e.phase,e.round,"#diff")}),m.map((h,x)=>t.jsx(Oe,{role:"qa",label:r.review.batchTurn(x+1),summary:Rn(r,h),onClick:()=>s(e.phase,e.round,`#batch-${x}`)},x)),e.findings&&t.jsx(Oe,{role:"qa",label:r.review.reviewTurnLabel,badge:t.jsx("span",{className:Sn[e.findings.verdict],children:e.findings.verdict}),summary:Rn(r,e.findings),onClick:()=>s(e.phase,e.round,"#review")}),e.response&&t.jsx(Oe,{role:"dev",label:r.review.responseTurnLabel,summary:Ya(r,e.response),onClick:()=>s(e.phase,e.round,"#response")}),e.userDecision&&t.jsx(Oe,{role:"user",label:e.userDecision.verdict==="approve"?r.taskDetail.specApprove:e.userDecision.verdict==="archive"?r.taskDetail.specArchive:e.phase==="spec"?r.taskDetail.specReject:r.taskDetail.codeReject,badge:t.jsx("span",{className:Sn[e.userDecision.verdict],children:e.userDecision.verdict}),summary:e.userDecision.comments??"",onClick:()=>s(e.phase,e.round,"#user-decision")}),u&&t.jsx(ti,{t:r,task:n,round:e})]})]})}function ti({t:e,task:n,round:s}){var i;const r=((i=s.findings)==null?void 0:i.findings.length)??(s.batchFindings??[]).filter(Boolean).reduce((l,d)=>l+d.findings.length,0),a=n.status==="review"?n.batchTotal!==void 0?e.review.reviewingBatch((n.batchIndex??0)+1,n.batchTotal):e.review.reviewing:e.review.fixingCount(r);return t.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 text-sm text-og-500",children:[t.jsx("span",{"aria-hidden":!0,className:"h-1.5 w-1.5 shrink-0 animate-pulse rounded-full bg-accent"}),t.jsx("span",{children:a})]})}const Cn=Ft;function ni(e){const[n,s]=o.useState(!1);return o.useEffect(()=>{function r(){if(!e||e.status!=="review"||!e.reviewDispatchedAt||!e.qaAgentId){s(!1);return}const i=Date.now()-Date.parse(e.reviewDispatchedAt);s(i>=Hn)}r();const a=setInterval(r,3e4);return()=>clearInterval(a)},[e==null?void 0:e.status,e==null?void 0:e.reviewDispatchedAt,e==null?void 0:e.qaAgentId]),n}function si(e,n){if(!e||!n)return null;const s=e.match(/^(https?:\/\/[^/]+\/[^/]+\/[^/]+)\/pull\/\d+/);if(!s)return null;const r=n.split("/").map(encodeURIComponent).join("/");return`${s[1]}/tree/${r}`}function ri(){const{taskId:e=""}=Ze();return t.jsx(ai,{taskId:e},e)}function ai({taskId:e}){const n=Te(),s=M(),{show:r}=Re(),a=Zt(),[i,l]=o.useState(!1),[d,u]=o.useState(!1),[m,h]=o.useState(!1),[x,c]=o.useState(!1),[g,v]=o.useState(!1),[y,w]=o.useState(!1),[S,A]=o.useState(!1),[R,b]=o.useState(""),[f,k]=o.useState(!1),[j,$]=o.useState(""),[I,K]=o.useState(null),{data:C,loaded:B,error:W}=on(e),{projects:J}=tt(),{data:Z,loaded:ee,error:te}=an(),{activeAgentId:X,activateAgentCard:ie}=os(),N=I??C,G=ni(N),se=(W==null?void 0:W.message)??null,he=o.useMemo(()=>new Map((Z??[]).map(p=>[p.id,p])),[Z]);o.useEffect(()=>{I&&C&&C.updatedAt>=I.updatedAt&&K(null)},[I,C]);const O=p=>{K(p)},oe=async()=>{if(!N)return;const p=Ft.has(N.status);if(await a({title:s.taskDetail.cancelConfirmTitle(N.id),...p?{body:s.taskDetail.cancelConfirmBodyTerminal}:{},confirmLabel:s.taskDetail.cancelConfirmLabel,cancelLabel:s.common.backText})){u(!0);try{const T=await F.tasks.update(N.id,{status:"cancelled"});O(T),r({kind:"success",title:T.status==="cancelled"?s.taskDetail.cancelledToastTitle:s.taskDetail.cancelCleanupToastTitle})}catch(T){r({kind:"error",title:s.taskDetail.cancelFailedTitle,body:T instanceof Error?T.message:String(T)})}finally{u(!1)}}},ne=async()=>{if(!N)return;const p=Ft.has(N.status);if(await a(p?{title:s.taskDetail.reReviewTerminalConfirmTitle,body:s.taskDetail.reReviewTerminalConfirmBody(N.id,s.status[N.status]??N.status),confirmLabel:s.agents.confirmReReviewLabel}:{title:s.agents.confirmReReviewTitle,body:s.agents.confirmReReviewBody(N.id),confirmLabel:s.agents.confirmReReviewLabel})){c(!0);try{const T=await F.tasks.review(N.id);O(T);const U=Ce(T.phase)?T.specReviewRound??0:T.reviewRound;r({kind:"success",title:s.agents.reReviewStarted(U)})}catch(T){r({kind:"error",title:s.agents.reReviewStartFailed,body:T instanceof Error?T.message:String(T)})}finally{c(!1)}}},be=async()=>{if(!(!N||!await a({title:s.taskDetail.retryConfirmTitle(N.id),body:N.status==="merged"?s.taskDetail.retryConfirmBodyMerged:s.taskDetail.retryConfirmBodyDefault,confirmLabel:s.common.retry}))){h(!0);try{const P=await F.tasks.retry(N.id);r({kind:"success",title:s.taskDetail.retryCreatedToastTitle(P.id)}),n(Fe(P.projectId,P.id))}catch(P){r({kind:"error",title:s.taskDetail.retryFailedTitle,body:P instanceof Error?P.message:String(P)})}finally{h(!1)}}},ye=async()=>{if(N&&await a({title:s.taskDetail.markCompleteConfirmTitle,body:s.taskDetail.markCompleteConfirmBody(N.prNumber??0),confirmLabel:s.taskDetail.markComplete})){v(!0);try{const p=await F.tasks.complete(N.id);O(p),r({kind:"success",title:s.taskDetail.markCompleteToastTitle})}catch(p){r({kind:"error",title:s.taskDetail.markCompleteFailedTitle,body:p instanceof Error?p.message:String(p)})}finally{v(!1)}}},je=async()=>{if(N&&await a({title:s.taskDetail.continueConfirmTitle,body:s.taskDetail.continueConfirmBody(N.reviewRound+1),confirmLabel:s.taskDetail.continueRound})){w(!0);try{const p=await F.tasks.continue(N.id);O(p),r({kind:"success",title:s.taskDetail.continuedToastTitle(p.reviewRound)})}catch(p){r({kind:"error",title:s.taskDetail.continueFailedTitle,body:p instanceof Error?p.message:String(p)})}finally{w(!1)}}},fe=async(p,P)=>{if(N){A(!0);try{const T=await F.tasks.spec(N.id,p);O(T),b(""),r({kind:"success",title:P.success})}catch(T){r({kind:"error",title:P.failure,body:T instanceof Error?T.message:String(T)})}finally{A(!1)}}},ve=async()=>{N&&await a({title:s.taskDetail.specApproveConfirmTitle,body:s.taskDetail.specApproveConfirmBody(N.id),confirmLabel:s.taskDetail.specApprove})&&await fe({verdict:"approve"},{success:s.taskDetail.specApprovedToastTitle,failure:s.taskDetail.specApproveFailedTitle})},E=async()=>{const p=R.trim();p&&await fe({verdict:"request-changes",comments:p},{success:N!=null&&N.researchAgentId?s.taskDetail.specRejectedToastTitleResearch:s.taskDetail.specRejectedToastTitle,failure:s.taskDetail.specRejectFailedTitle})},L=async()=>{!N||!await a({title:s.taskDetail.specArchiveConfirmTitle,body:s.taskDetail.specArchiveConfirmBody(N.id),confirmLabel:s.taskDetail.specArchive})||await fe({verdict:"archive"},{success:s.taskDetail.specArchivedToastTitle,failure:s.taskDetail.specArchiveFailedTitle})},H=async()=>{if(!N)return;const p=j.trim();if(p){k(!0);try{const P=await F.tasks.code(N.id,{verdict:"request-changes",comments:p});O(P),$(""),r({kind:"success",title:s.taskDetail.codeRejectedToastTitle})}catch(P){r({kind:"error",title:s.taskDetail.codeRejectFailedTitle,body:P instanceof Error?P.message:String(P)})}finally{k(!1)}}},_=async()=>{if(N&&await a({title:s.taskDetail.confirmGateConfirmTitle(N.id),body:s.taskDetail.confirmGateConfirmBody,confirmLabel:s.taskDetail.confirmComplete})){v(!0);try{const p=await F.tasks.complete(N.id);O(p),r({kind:"success",title:s.taskDetail.confirmedToastTitle(p.status)})}catch(p){r({kind:"error",title:s.taskDetail.confirmFailedTitle,body:p instanceof Error?p.message:String(p)})}finally{v(!1)}}};return t.jsxs("div",{children:[t.jsx("button",{type:"button",onClick:()=>n(-1),className:"btn-ghost mb-3",children:s.common.back}),se&&!N&&t.jsx("div",{className:"text-sm text-accent",children:s.common.loadFailed(se)}),B&&!N&&!se&&t.jsx("div",{className:"text-sm text-accent",children:s.taskDetail.taskNotFound(e)}),!N&&!se&&!B&&t.jsx("div",{className:"text-sm text-og-500",children:s.common.loading}),N&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mb-4",children:t.jsxs("h1",{className:"flex min-w-0 items-baseline gap-2",children:[t.jsx("span",{className:"shrink-0 font-mono text-sm text-og-400",children:N.id}),t.jsx("span",{className:"min-w-0 truncate font-display text-sm font-semibold tracking-tight text-og-1000",title:N.title,children:N.title})]})}),t.jsxs("div",{className:"grid grid-cols-1 items-start gap-6 lg:grid-cols-2",children:[t.jsx("section",{className:"min-w-0",children:ue(N)}),t.jsx("aside",{className:"min-w-0 space-y-4",children:we(N)})]})]}),i&&N&&t.jsx(nn,{mode:"edit",open:!0,onClose:()=>l(!1),task:N,onUpdated:O})]});function ue(p){const P=p.preferredAgentId==="",T=p.status==="approved"&&p.prNumber!==void 0,U=p.status==="merge-ready"&&p.prNumber!==void 0,z=p.status==="spec-ready",me=p.status==="ready",V=p.status==="max_rounds"&&!Ce(p.phase),ce=p.status==="max_rounds"&&Ce(p.phase),xe=_n(p.prUrl),Le=si(xe??void 0,p.branch??"");return t.jsxs("div",{children:[se&&t.jsx("div",{className:"mb-4 text-sm text-accent",children:s.common.loadFailed(se)}),p.branchCleanupPending&&t.jsxs("div",{className:"mb-4 rounded-md border border-accent/25 bg-accent-soft/60 px-3 py-2.5 text-xs text-accent",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.branchCleanupPendingTitle}),t.jsx("div",{className:"mt-1 text-og-700",children:p.branchCleanupPending.reason})]}),p.branchCleanupSkipped&&t.jsxs("div",{className:"mb-4 rounded-md border border-hairline bg-og-25 px-3 py-2.5 text-xs text-og-700",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.branchCleanupSkippedTitle}),t.jsx("div",{className:"mt-1",children:p.branchCleanupSkipped.reason})]}),P&&t.jsx("div",{className:"mb-4 rounded-md border border-accent/25 bg-accent-soft/60 px-3 py-2.5 text-xs text-accent",children:p.status==="pending"?s.taskDetail.legacyPendingNotice:s.taskDetail.legacyReadonlyNotice(s.status[p.status]??p.status)}),t.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-3",children:[t.jsx("span",{className:`${ls[p.status]} text-sm`,title:p.status,children:s.status[p.status]??p.status}),t.jsxs("span",{className:"text-sm text-og-500",children:[s.taskDetail.reviewRoundPrefix,t.jsx("span",{className:"text-og-800",children:p.reviewRound}),s.taskDetail.reviewRoundSuffix]}),t.jsxs("span",{className:"text-sm text-og-500",children:[s.taskDetail.specRoundPrefix,t.jsx("span",{className:"text-og-800",children:p.specReviewRound??0}),s.taskDetail.specRoundSuffix]})]}),t.jsx("div",{className:"mb-4 flex flex-wrap items-center gap-2",children:q(p)}),t.jsxs("div",{className:"mb-4 text-sm text-og-500",children:[s.taskDetail.createdAtPrefix,Pt(p.createdAt,!1),s.taskDetail.updatedAtPrefix,Pt(p.updatedAt,!1)]}),G&&t.jsxs("div",{className:"mb-4 rounded-lg border border-accent/25 bg-accent-soft p-4 text-sm text-accent",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.verdictOverdueTitle}),t.jsxs("div",{className:"mt-1 text-og-700",children:[s.taskDetail.verdictOverduePrefix,Pt(p.reviewDispatchedAt),s.taskDetail.verdictOverdueSuffix]})]}),T&&t.jsxs("div",{className:"mb-4 rounded-lg border border-hairline bg-og-25 p-4 text-sm text-og-800",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.approvedBannerTitle}),t.jsx("div",{className:"mt-1 text-og-700",children:s.taskDetail.approvedBannerBody}),xe&&t.jsx("a",{href:xe,target:"_blank",rel:"noopener noreferrer",className:"btn-secondary mt-3",children:s.taskDetail.viewPr(p.prNumber??0)})]}),me&&t.jsxs("div",{className:"mb-4 rounded-lg border border-accent/25 bg-accent-soft p-4 text-sm text-accent",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.readyGateBannerTitle}),t.jsx("div",{className:"mt-1 text-og-700",children:s.taskDetail.readyGateBannerBody(p.reviewRound)}),t.jsx(Ln,{taskId:p.id}),xe&&t.jsx("a",{href:xe,target:"_blank",rel:"noopener noreferrer",className:"btn-secondary mt-3",children:s.taskDetail.viewPr(p.prNumber??0)}),p.reviewMode==="server"&&!Ce(p.phase)&&t.jsxs("div",{className:"mt-3 flex flex-col gap-2",children:[t.jsx("div",{className:"text-og-700",children:s.taskDetail.readyGateRejectHint}),t.jsx("textarea",{value:j,onChange:Be=>$(Be.target.value),placeholder:s.taskDetail.codeRejectCommentsPlaceholder,rows:3,disabled:f,className:de}),t.jsx("div",{children:t.jsx("button",{type:"button",disabled:f||g||j.trim()==="",onClick:H,title:j.trim()===""?s.taskDetail.codeRejectTitleEmpty:s.taskDetail.codeRejectTitleReady,className:"btn-secondary",children:f?s.taskDetail.submitting:s.taskDetail.codeReject})})]})]}),U&&t.jsxs("div",{className:"mb-4 rounded-lg border border-accent/25 bg-accent-soft p-4 text-sm text-accent",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.mergeReadyBannerTitle}),t.jsx("div",{className:"mt-1 text-og-700",children:s.taskDetail.mergeReadyBannerBody}),xe&&t.jsx("a",{href:xe,target:"_blank",rel:"noopener noreferrer",className:"btn-secondary mt-3",children:s.taskDetail.viewPr(p.prNumber??0)})]}),z&&t.jsxs("div",{className:"mb-4 rounded-lg border border-accent-soft bg-accent-soft/40 p-4 text-sm text-accent",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.specReadyBannerTitle}),t.jsx("div",{className:"mt-1 text-og-700",children:p.researchAgentId?s.taskDetail.specReadyNoticeResearch(p.specReviewRound??0):s.taskDetail.specReadyNotice(p.specReviewRound??0)}),pe(p)]}),V&&t.jsxs("div",{className:"mb-4 rounded-lg border border-accent/25 bg-accent-soft/60 p-4 text-sm text-accent",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.codeMaxRoundsTitle(p.reviewRound)}),t.jsx("div",{className:"mt-1 text-og-700",children:s.taskDetail.codeMaxRoundsBody})]}),ce&&t.jsxs("div",{className:"mb-4 rounded-lg border border-accent/25 bg-accent-soft/60 p-4 text-sm text-accent",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.specMaxRoundsTitle(p.specReviewRound??0)}),t.jsx("div",{className:"mt-1 text-og-700",children:s.taskDetail.specMaxRoundsBody}),t.jsx(Ln,{taskId:p.id}),pe(p)]}),t.jsxs("div",{className:"card mb-4 flex flex-wrap items-center gap-x-6 gap-y-1 p-4 text-sm",children:[t.jsxs("span",{className:"text-og-500",children:["PR:"," ",p.prNumber?xe?t.jsxs("a",{href:xe,target:"_blank",rel:"noopener noreferrer",className:"text-accent hover:text-accent-hover",children:["#",p.prNumber]}):t.jsxs("span",{className:"font-mono text-og-800",children:["#",p.prNumber]}):t.jsx("span",{className:"text-og-400",children:"—"})]}),t.jsxs("span",{className:"text-og-500",children:["Branch:"," ",p.branch?Le?t.jsx("a",{href:Le,target:"_blank",rel:"noopener noreferrer",className:"font-mono text-accent hover:text-accent-hover",children:p.branch}):t.jsx("span",{className:"font-mono text-og-800",children:p.branch}):t.jsx("span",{className:"text-og-400",children:"—"})]})]}),t.jsx("pre",{className:"card mb-4 whitespace-pre-wrap p-4 text-sm text-og-800",children:p.description||t.jsx("span",{className:"text-og-400",children:s.taskDetail.noDescription})}),t.jsx(Ja,{task:p})]})}function pe(p){return t.jsxs("div",{className:"mt-3 flex flex-col gap-2",children:[t.jsx("textarea",{value:R,onChange:P=>b(P.target.value),placeholder:s.taskDetail.specCommentsPlaceholder,rows:3,disabled:S,className:de}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",disabled:S,onClick:ve,className:"btn-primary",children:S?s.taskDetail.submitting:s.taskDetail.specApproveButton}),t.jsx("button",{type:"button",disabled:S||R.trim()==="",onClick:E,title:R.trim()===""?s.taskDetail.specRejectTitleEmpty:s.taskDetail.specRejectTitleReady(p.researchAgentId?"Research":"Dev"),className:"btn-secondary",children:S?s.taskDetail.submitting:s.taskDetail.specReject}),p.researchAgentId&&t.jsx("button",{type:"button",disabled:S,onClick:L,className:"btn-secondary",children:S?s.taskDetail.submitting:s.taskDetail.specArchiveButton})]})]})}function we(p){if(J===null)return t.jsx("div",{className:"rounded-lg border border-hairline bg-surface px-3 py-6 text-center text-sm text-og-400",children:s.common.loading});const P=J.find(V=>V.id===p.projectId),T=(P==null?void 0:P.agent.find(V=>V.some(ce=>ce.id===p.devAgentId)))??(p.qaAgentId?P==null?void 0:P.agent.find(V=>V.some(ce=>ce.id===p.qaAgentId)):void 0)??(p.researchAgentId?P==null?void 0:P.agent.find(V=>V.some(ce=>ce.id===p.researchAgentId)):void 0),U=T==null?void 0:T.find(V=>V.role==="dev"&&V.id===p.devAgentId),z=p.qaAgentId?T==null?void 0:T.find(V=>V.role==="qa"&&V.id===p.qaAgentId):void 0,me=p.researchAgentId?T==null?void 0:T.find(V=>V.role==="research"&&V.id===p.researchAgentId):void 0;return!U&&!z&&!me?t.jsx("div",{className:"rounded-lg border border-hairline bg-surface px-3 py-6 text-center text-sm text-og-400",children:s.taskDetail.noLinkedAgent}):t.jsxs(t.Fragment,{children:[me?D(p,me):null,U?D(p,U):t.jsx(An,{role:"dev"}),z?D(p,z):t.jsx(An,{role:"qa"})]})}function D(p,P){const T=he.get(P.id),U=T??{id:P.id,projectId:p.projectId,runtimeStatus:"unknown",tmuxSessionStatus:"unknown",stale:!0};return t.jsx(is,{agent:U,projectId:p.projectId,role:P.role,runtime:P.runtime,model:P.model,pendingRestart:ee&&!T,terminalLoading:!ee&&!T&&!te,showTaskBinding:!1,terminalMode:"embedded-full",active:X===P.id,onActivate:()=>ie(P.id)},P.id)}function q(p){const P=p.status==="max_rounds",T=P&&!Ce(p.phase),U=P&&Ce(p.phase),z=p.status==="ready"||p.status==="merge-ready",me=p.status==="pending",V=(Cn.has(p.status)||U)&&!!p.preferredAgentId,ce=p.reviewMode==="server",xe=ce||Ce(p.phase),Le=p.status==="in_progress"&&p.phase===void 0,Be=!Le&&(p.status==="in_progress"||p.status==="review"||p.status==="fixing"),We=xe?Be:!!p.prNumber,nt=T&&(!!p.prNumber||ce),st=T&&(!!p.prNumber||ce)&&!!p.agentId,Q=ce&&p.status==="approved",ge=p.preferredAgentId==="";return t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",disabled:!me,onClick:()=>l(!0),className:"btn-secondary",children:s.common.edit}),t.jsx("button",{type:"button",disabled:d,onClick:oe,title:s.taskDetail.cancelForceTitle,className:"btn-secondary",children:d?s.taskDetail.cancelling:s.common.cancel}),!T&&t.jsx("button",{type:"button",disabled:!V||m,onClick:be,title:Cn.has(p.status)||U?ge?s.taskDetail.retryDisabledLegacyTitle:s.taskDetail.retryEnabledTitle:s.taskDetail.retryDisabledStatusTitle(s.status[p.status]??p.status),className:"btn-secondary",children:m?s.common.retrying:s.common.retry}),t.jsx("button",{type:"button",disabled:!We||x,onClick:ne,title:xe?We?s.taskDetail.reviewButtonTitle:Le?s.taskDetail.reviewUnphasedTitle:s.taskDetail.reviewServerStatusTitle:p.prNumber?s.taskDetail.reviewButtonTitle:s.taskDetail.reviewNoPrTitle,className:"btn-secondary",children:x?s.agents.callingReview:s.agents.callReview}),T&&t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",disabled:!st||y,onClick:je,title:s.taskDetail.continueButtonTitle,className:"btn-secondary",children:y?s.taskDetail.continuing:s.taskDetail.continueRound}),t.jsx("button",{type:"button",disabled:!nt||g,onClick:ye,title:s.taskDetail.completeButtonTitle,className:"btn-primary",children:g?s.taskDetail.completing:s.taskDetail.markComplete})]}),z&&t.jsx("button",{type:"button",disabled:g||f,onClick:_,title:s.taskDetail.confirmButtonTitle,className:"btn-primary",children:g?s.taskDetail.confirming:s.common.confirm}),Q&&t.jsx("button",{type:"button",disabled:g,onClick:_,title:s.taskDetail.retryPublishButtonTitle,className:"btn-primary",children:g?s.common.retrying:s.taskDetail.retryPublish})]})}}function An({role:e}){const n=M();return t.jsx("div",{className:"rounded-lg border border-hairline bg-surface px-3 py-6 text-center text-sm text-og-400",children:n.taskDetail.noAgentSlot(e==="dev"?"Dev":"QA")})}function Ln({taskId:e}){var l;const n=M(),[s,r]=o.useState(null);if(o.useEffect(()=>{let d=!0;return F.tasks.reviews(e).then(u=>{d&&r(u)}).catch(()=>{d&&r([])}),()=>{d=!1}},[e]),!s||s.length===0)return null;const a=s[s.length-1],i=s.reduce((d,u)=>{var m;return d+(((m=u.findings)==null?void 0:m.findings.length)??0)},0);return t.jsxs("div",{className:"mt-2 text-xs text-og-700",children:[n.taskDetail.reviewSummaryPrefix,s.length,n.taskDetail.reviewSummaryMid,t.jsx("span",{className:"font-mono",children:((l=a.findings)==null?void 0:l.verdict)??"—"}),n.taskDetail.reviewSummaryFindingsPrefix,i,n.taskDetail.reviewSummaryFindingsSuffix]})}function ii(){const{agentId:e}=Ze(),{projects:n}=tt(),s=o.useMemo(()=>{if(e)for(const r of n??[])for(const a of r.agent){const i=a.find(l=>l.id===e);if(i)return i.runtime}},[e,n]);return e?t.jsxs("div",{"data-testid":"terminal-page-container",className:"flex min-h-0 flex-1 flex-col overflow-hidden border border-hairline bg-surface",children:[t.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-xs text-og-500",children:[t.jsx("span",{"aria-hidden":!0,className:"block h-1.5 w-1.5 rounded-full bg-og-1000"}),t.jsx("span",{className:"text-og-700",title:Mn(e,s),children:e})]}),t.jsx("div",{className:"min-h-0 flex-1",children:t.jsx(ze,{agentId:e,mode:"full",interactive:!0,arrowKeys:!0})})]}):t.jsx("div",{className:"text-sm text-accent",children:"No agent specified"})}const oi=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/,li={a:"\x07",b:"\b",f:"\f",n:`
|
|
13
|
-
`,r:"\r",t:" ",v:"\v",'"':'"',"\\":"\\"};function Rs(e){return e.replace(/\\([abfnrtv"\\]|[0-7]{1,3})/g,(n,s)=>li[s]??String.fromCharCode(parseInt(s,8)))}function Cs(e){let n=e.endsWith(" ")?e.slice(0,-1):e;return n.startsWith('"')&&n.endsWith('"')&&(n=Rs(n.slice(1,-1))),n}function Pn(e){const n=Cs(e);return n.startsWith("a/")||n.startsWith("b/")?n.slice(2):n}function ci(e){return e.startsWith("diff --git")||e.startsWith("index ")||e.startsWith("--- ")||e.startsWith("+++ ")}function As(e){if(!e)return[];const n=[];let s=null,r=0,a=0,i=!1;const l=()=>(s||(s={file:"",status:"modified",adds:0,dels:0,lines:[]},n.push(s)),s),d=e.split(/\r?\n/);d.length>0&&d[d.length-1]===""&&d.pop();for(const u of d){if(u.startsWith("diff --git")){s={file:"",status:"modified",adds:0,dels:0,lines:[]},n.push(s),i=!1;const h=u.match(/^diff --git a\/(.+) b\/\1$/),x=h?null:u.match(/^diff --git "a\/(.+)" "b\/\1"$/);h?s.file=h[1]:x&&(s.file=Rs(x[1])),s.lines.push({type:"file",text:u});continue}if(u.startsWith("@@")){const h=l(),x=u.match(oi);r=x?parseInt(x[1],10):0,a=x?parseInt(x[2],10):0,i=!0,h.lines.push({type:"hunk",text:u});continue}if(u.startsWith("\\")){l().lines.push({type:"meta",text:u});continue}if(i){const h=l();u.startsWith("+")?(h.lines.push({type:"add",text:u,newLine:a}),a++,h.adds++):u.startsWith("-")?(h.lines.push({type:"del",text:u,oldLine:r}),r++,h.dels++):(h.lines.push({type:"context",text:u,oldLine:r,newLine:a}),r++,a++);continue}const m=l();if(u.startsWith("new file"))m.status="added";else if(u.startsWith("deleted file"))m.status="deleted";else if(u.startsWith("rename to "))m.status="renamed",m.file=Cs(u.slice(10));else if(u.startsWith("rename from "))m.status="renamed";else if(u.startsWith("+++ ")){const h=u.slice(4);h==="/dev/null"?m.status="deleted":m.file=Pn(h)}else if(u.startsWith("--- ")){const h=u.slice(4);h!=="/dev/null"&&!m.file&&(m.file=Pn(h))}m.lines.push({type:"file",text:u})}return n}const di={file:"bg-og-50 font-semibold text-og-700",hunk:"bg-accent-soft text-accent",add:"bg-diff-add text-diff-add-ink",del:"bg-diff-del text-diff-del-ink",context:"text-og-700",meta:"text-og-400"},ui={critical:"finding-dot finding-dot-critical",major:"finding-dot finding-dot-major",minor:"finding-dot"},mi={modified:"text-og-500",added:"text-diff-add-ink",deleted:"text-diff-del-ink",renamed:"text-accent"};function fi(e){if(!e)return"";const n=e.split(`
|
|
14
|
-
`).map(s=>s.trim()).filter(Boolean);return n[n.length-1]??""}function ut(e){return`diff-file-${encodeURIComponent(e)}`}function Ls(e,n){return`diff-${encodeURIComponent(e)}-L${n}`}function Ps(e,n){return`diff-${encodeURIComponent(e)}-OLD${n}`}function hi(e,n){if(n.newLine!=null)return Ls(e,n.newLine);if(n.type==="del"&&n.oldLine!=null)return Ps(e,n.oldLine)}function pi(e,n,s,r){if(n.newLine!=null)return s.get(`${e}:${n.newLine}`);if(n.type==="del"&&n.oldLine!=null)return r.get(`${e}:${n.oldLine}`)}function $n(e){if(typeof requestAnimationFrame=="function"){const s=requestAnimationFrame(e);return()=>cancelAnimationFrame(s)}const n=setTimeout(e,0);return()=>clearTimeout(n)}function En({content:e,diffstat:n,findings:s,onFindingClick:r,expandRequest:a}){const i=M(),l=o.useMemo(()=>As(e),[e]),d=o.useMemo(()=>{const b=new Set,f=new Set;for(const k of l)for(const j of k.lines)j.newLine!=null?b.add(`${k.file}:${j.newLine}`):j.type==="del"&&j.oldLine!=null&&f.add(`${k.file}:${j.oldLine}`);return{newKeys:b,delKeys:f}},[l]),{findingsByLine:u,findingsByOldLine:m}=o.useMemo(()=>{const b=new Map,f=new Map,k=(j,$,I)=>{const K=j.get($);K?K.push(I):j.set($,[I])};for(const j of s??[]){if(!j.file||j.line==null)continue;const $=`${j.file}:${j.line}`;d.newKeys.has($)?k(b,$,j):d.delKeys.has($)&&k(f,$,j)}return{findingsByLine:b,findingsByOldLine:f}},[s,d]),h=o.useMemo(()=>{const b=new Set;for(const f of s??[])f.file&&b.add(f.file);return b},[s]),x=o.useMemo(()=>{const b=l.some(j=>h.has(j.file)),f=!b&&l.length>5,k={};for(const j of l)k[j.file]=b?!h.has(j.file):f;return k},[l,h]),[c,g]=o.useState(x);o.useEffect(()=>g(x),[x]);const[v,y]=o.useState(null);if(o.useEffect(()=>{if(!v)return;const b=setTimeout(()=>y(null),2e3);return()=>clearTimeout(b)},[v]),o.useEffect(()=>{if(!a)return;const{file:b,line:f}=a;g($=>({...$,[b]:!1}));let k=!0;const j=$n(()=>{if(!k)return;const $=f!=null?[Ls(b,f),Ps(b,f),ut(b)]:[ut(b)];let I=null;for(const K of $)if(I=document.getElementById(K),I)break;I==null||I.scrollIntoView({behavior:"smooth",block:"center"}),y(I?I.id:null)});return()=>{k=!1,j()}},[a==null?void 0:a.nonce]),l.length===0)return t.jsx("div",{className:"text-sm text-og-400",children:i.review.noContent});const w=l.some(b=>c[b.file]),S=()=>{const b=!w;g(Object.fromEntries(l.map(f=>[f.file,b])))},A=b=>{g(f=>({...f,[b]:!1})),$n(()=>{var f;return(f=document.getElementById(ut(b)))==null?void 0:f.scrollIntoView({behavior:"smooth",block:"start"})})},R=fi(n);return t.jsxs("div",{children:[t.jsxs("div",{className:"mb-2 rounded-md border border-hairline bg-og-50 p-2",children:[t.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2",children:[R?t.jsx("span",{className:"min-w-0 truncate font-mono text-xs text-og-600",children:R}):t.jsx("span",{}),t.jsx("button",{type:"button",onClick:S,className:"btn-ghost shrink-0 px-2 py-0.5 text-xs",children:w?i.review.expandAll:i.review.collapseAll})]}),t.jsx("ul",{className:"space-y-0.5",children:l.map((b,f)=>t.jsx("li",{children:t.jsxs("button",{type:"button",onClick:()=>A(b.file),className:"flex w-full items-center gap-2 rounded px-1 py-0.5 text-left font-mono text-xs hover:bg-surface",children:[t.jsx("span",{className:"min-w-0 flex-1 truncate text-og-700",children:b.file||i.review.diffUnnamed}),b.adds>0&&t.jsxs("span",{className:"shrink-0 text-diff-add-ink",children:["+",b.adds]}),b.dels>0&&t.jsxs("span",{className:"shrink-0 text-diff-del-ink",children:["−",b.dels]})]})},`${b.file}-${f}`))})]}),t.jsx("div",{className:"overflow-auto rounded-md border border-hairline bg-surface font-mono text-xs leading-[1.5] [max-height:70vh]",children:l.map((b,f)=>t.jsx(gi,{section:b,collapsed:!!c[b.file],onToggle:()=>g(k=>({...k,[b.file]:!k[b.file]})),findingsByLine:u,findingsByOldLine:m,flashId:v,onFindingClick:r},`${b.file}-${f}`))})]})}function gi({section:e,collapsed:n,onToggle:s,findingsByLine:r,findingsByOldLine:a,flashId:i,onFindingClick:l}){const d=M(),u=e.lines.filter(m=>m.type!=="file"||!ci(m.text));return t.jsxs("div",{id:ut(e.file),className:"border-b border-hairline last:border-b-0",children:[t.jsxs("button",{type:"button",onClick:s,className:"flex w-full items-center gap-2 bg-og-50 px-3 py-1.5 text-left",children:[t.jsx("span",{"aria-hidden":!0,className:"shrink-0 text-og-400",children:n?"▸":"▾"}),t.jsx("span",{className:`shrink-0 text-xs uppercase ${mi[e.status]}`,children:e.status}),t.jsx("span",{className:"min-w-0 flex-1 truncate font-semibold text-og-700",children:e.file||d.review.diffUnnamed}),e.adds>0&&t.jsxs("span",{className:"shrink-0 text-diff-add-ink",children:["+",e.adds]}),e.dels>0&&t.jsxs("span",{className:"shrink-0 text-diff-del-ink",children:["−",e.dels]})]}),!n&&u.map((m,h)=>t.jsx(xi,{file:e.file,line:m,findings:pi(e.file,m,r,a),flashId:i,onFindingClick:l},h))]})}function xi({file:e,line:n,findings:s,flashId:r,onFindingClick:a}){const i=M(),l=hi(e,n),d=l!=null&&r===l;return t.jsxs("div",{id:l,className:`flex ${d?"ring-2 ring-inset ring-accent":""}`,children:[t.jsx("span",{className:"flex w-5 shrink-0 select-none items-center justify-center gap-0.5 overflow-hidden",children:(s??[]).map(u=>t.jsx("button",{type:"button",title:`${u.id} ${u.severity}: ${u.message.slice(0,120)}`,"aria-label":i.review.findingMarker(u.id),onClick:()=>a==null?void 0:a(u.id),className:ui[u.severity]},u.id))}),t.jsx("span",{className:"w-8 shrink-0 select-none border-r border-hairline px-1 text-right text-og-300",children:n.oldLine??""}),t.jsx("span",{className:"w-8 shrink-0 select-none border-r border-hairline px-1 text-right text-og-300",children:n.newLine??""}),t.jsx("div",{className:`min-w-0 flex-1 whitespace-pre px-2 ${di[n.type]}`,children:n.text===""?" ":n.text})]})}const bi=65536,vi=8e3,wi=["text-[18px] font-bold","text-[17px] font-bold","text-[16px] font-semibold","text-[15px] font-semibold","text-[15px] font-semibold","text-[15px] font-semibold"],yi=/^(https?:\/\/|mailto:)/i,ji=/^https?:\/\//i;function ki(e){try{const n=new URL(e).hostname.toLowerCase();return n==="githubusercontent.com"||n.endsWith(".githubusercontent.com")}catch{return!1}}function Ni({src:e,alt:n}){const s=M(),[r,a]=o.useState(!1);if(r||ki(e))return t.jsx("img",{src:e,alt:n,loading:"lazy",className:"max-w-full rounded border border-hairline"});let i=e;try{i=new URL(e).hostname}catch{i=e}return t.jsxs("button",{type:"button",onClick:()=>a(!0),className:"inline-flex max-w-full items-center gap-1.5 rounded border border-hairline bg-og-25 px-2 py-1 text-xs text-og-700",children:[t.jsx("span",{className:"shrink-0",children:s.review.loadExternalImage}),n&&t.jsx("span",{className:"min-w-0 truncate text-og-500",children:n}),t.jsx("span",{className:"min-w-0 truncate font-mono text-og-400",children:i})]})}function Dn(e,n){let s=-1,r=-2;return a=>(r!==-2&&a>=s&&(r===-1||a<=r)||(s=a,r=e.indexOf(n,a)),r)}function Si(e){const n=/\s/g;let s=-1,r=-2;return a=>{if(r!==-2&&a>=s&&(r===-1||a<=r))return r;s=a,n.lastIndex=a;const i=n.exec(e);return r=i?i.index:-1,r}}function In(e,n,s){const r=n+1,a=s.bracket(r);if(a===-1||e[a+1]!=="(")return null;const i=a+2,l=s.paren(i);if(l===-1||l===i)return null;const d=s.whitespace(i);return d!==-1&&d<l?null:{label:e.slice(r,a),url:e.slice(i,l),end:l+1}}class $s extends Error{}class Ti{constructor(n){ae(this,"count",0);this.max=n}charge(){if(++this.count>this.max)throw new $s}}function He(e,n,s){const r=[];let a="",i=0;const l={bracket:Dn(e,"]"),paren:Dn(e,")"),whitespace:Si(e)},d=()=>{a!==""&&(n.charge(),r.push(a),a="")},u=h=>{d(),n.charge(),r.push(h)},m=()=>`${s}-${r.length}`;for(;i<e.length;){const h=e[i];if(h==="`"){const x=e.indexOf("`",i+1);if(x!==-1){const c=e.slice(i+1,x);d(),n.charge(),n.charge(),r.push(t.jsx("code",{className:"rounded bg-og-25 px-1 font-mono text-xs",children:c},m())),i=x+1;continue}}else if(h==="!"&&e[i+1]==="["){const x=In(e,i+1,l);if(x){ji.test(x.url)?u(t.jsx(Ni,{src:x.url,alt:x.label},m())):a+=e.slice(i,x.end),i=x.end;continue}}else if(h==="["){const x=In(e,i,l);if(x){if(yi.test(x.url)){d(),n.charge();const c=He(x.label,n,`${s}-a${r.length}`);r.push(t.jsx("a",{href:x.url,target:"_blank",rel:"noopener noreferrer",className:"text-accent hover:text-accent-hover",children:c},m()))}else a+=e.slice(i,x.end);i=x.end;continue}}else if(h==="*"){if(e.startsWith("***",i)){const c=e.indexOf("***",i+3);if(c>i+3){d(),n.charge(),n.charge();const g=He(e.slice(i+3,c),n,`${s}-bi${r.length}`);r.push(t.jsx("strong",{children:t.jsx("em",{children:g})},m())),i=c+3;continue}}if(e.startsWith("**",i)){const c=e.indexOf("**",i+2);if(c>i+2){d(),n.charge();const g=He(e.slice(i+2,c),n,`${s}-b${r.length}`);r.push(t.jsx("strong",{children:g},m())),i=c+2;continue}}const x=e.indexOf("*",i+1);if(x>i+1){d(),n.charge();const c=He(e.slice(i+1,x),n,`${s}-i${r.length}`);r.push(t.jsx("em",{children:c},m())),i=x+1;continue}}a+=h,i++}return d(),r}function Ri(e,n){const s=[],r=e.split(`
|
|
15
|
-
`);let a=[];const i=()=>{if(a.length===0)return;const l=a;a=[],n.charge();const d=[];l.forEach((u,m)=>{m>0&&(n.charge(),d.push(t.jsx("br",{},`br-${s.length}-${m}`))),d.push(...He(u,n,`p${s.length}-l${m}`))}),s.push(t.jsx("p",{children:d},`p-${s.length}`))};for(let l=0;l<r.length;l++){const d=r[l];if(d.startsWith("```")){i();const m=[];let h=l+1;for(;h<r.length&&!/^```\s*$/.test(r[h]);)m.push(r[h]),h++;n.charge(),n.charge(),n.charge(),s.push(t.jsx("pre",{className:"overflow-x-auto rounded bg-og-25 p-2 font-mono text-xs",children:t.jsx("code",{children:m.join(`
|
|
16
|
-
`)})},`pre-${s.length}`)),l=h;continue}const u=/^(#{1,6}) (.*)$/.exec(d);if(u){i(),n.charge();const m=u[1].length,h=`h${m}`;s.push(t.jsx(h,{className:wi[m-1],children:He(d,n,`h${s.length}`)},`h-${s.length}`));continue}if(d.trim()===""){i();continue}a.push(d)}return i(),s}function Ci(e){if(typeof e!="string")return[];if(e.length>bi)return null;const n=new Ti(vi);try{return n.charge(),Ri(e.replace(/\r\n/g,`
|
|
17
|
-
`),n)}catch(s){if(s instanceof $s)return null;throw s}}function Ye({text:e}){const n=o.useMemo(()=>Ci(e),[e]);return n===null?t.jsx("pre",{className:"whitespace-pre-wrap break-words",children:e}):t.jsx("div",{className:"space-y-2 break-words",children:n})}function Ai(e){if(e instanceof De){if(e.status===404)return"historical";if(e.status===409)return"released"}return"generic"}function Li(e,n,s){const[r,a]=o.useState({status:"idle"});return o.useEffect(()=>{if(!s){a({status:"idle"});return}let i=!0;return a({status:"loading"}),F.tasks.interdiff(e,n).then(l=>{i&&a({status:"ready",diff:l.diff})}).catch(l=>{i&&a({status:"unavailable",reason:Ai(l)})}),()=>{i=!1}},[e,n,s]),r}const Pi={critical:"pill pill-danger font-semibold",major:"pill pill-warn",minor:"pill"},$i={fix:"pill pill-live",reject:"pill pill-warn","out-of-scope":"pill"},Ei={approve:"pill pill-live","request-changes":"pill pill-warn",archive:"pill"};function qt(e){if(!e)return"";const n=e.match(/^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2})/);return n?`${n[1]} ${n[2]}`:e}function Di(e){return e.file?e.line?`${e.file}:${e.line}`:e.file:e.location??""}function Ii(){const e=M(),{taskId:n="",phase:s="",round:r=""}=Ze(),a=Te(),{hash:i}=Gt(),{data:l}=on(n),d=l?ws(l):void 0,{rounds:u,loaded:m,error:h}=ys(n,d),x=Number(r),c=(u??[]).find(g=>g.phase===s&&g.round===x)??null;return o.useEffect(()=>{if(!c||!i)return;const g=document.getElementById(i.replace("#",""));g==null||g.scrollIntoView({behavior:"smooth",block:"start"})},[c,i]),t.jsxs("div",{className:"mx-auto w-full max-w-5xl",children:[t.jsx("button",{type:"button",onClick:()=>a(-1),className:"btn-ghost mb-3",children:e.common.back}),t.jsxs("div",{className:"mb-1 flex flex-wrap items-baseline gap-2",children:[t.jsx("span",{className:"font-mono text-og-400",children:n}),t.jsx("span",{className:"text-sm font-semibold text-og-1000",children:(l==null?void 0:l.title)??""})]}),t.jsxs("div",{className:"mb-4 flex flex-wrap items-center gap-2 text-xs text-og-500",children:[t.jsx("span",{className:"pill",children:s}),t.jsx("span",{children:e.agents.round(x)}),(c==null?void 0:c.findings)&&t.jsx("span",{className:c.findings.verdict==="approve"?"pill pill-live":"pill pill-warn",children:c.findings.verdict}),c&&t.jsxs("span",{className:"text-og-400",children:[qt(c.startedAt),c.completedAt?` → ${qt(c.completedAt)}`:""]})]}),!m&&t.jsx("div",{className:"text-sm text-og-500",children:e.common.loading}),m&&h&&t.jsx("div",{className:"text-sm text-accent",children:e.review.loadFailed(h)}),m&&!h&&!c&&t.jsx("div",{className:"text-sm text-accent",children:e.review.roundNotFound(s,r)}),c&&t.jsx(Fi,{round:c,taskId:n},`${n}:${s}:${x}`)]})}function Fi({round:e,taskId:n}){var I,K;const s=M(),r=e.phase==="code"&&e.round>=2,[a,i]=o.useState("full"),l=Li(n,e.round,r&&a==="interdiff"),d=r&&a==="interdiff"&&l.status==="ready",u=r&&a==="interdiff"&&l.status==="loading",m=!d&&!u;function h(C){return C==="historical"?s.review.interdiffUnavailableHistorical:C==="released"?s.review.interdiffUnavailableReleased:s.review.interdiffUnavailableGeneric}const x=((I=e.response)==null?void 0:I.responses)??[],c=o.useMemo(()=>(e.batchFindings??[]).filter(Boolean).map((C,B)=>C.findings.map(W=>({...W,id:/^b\d+-/.test(W.id)?W.id:`b${B}-${W.id}`}))),[e.batchFindings]),g=((K=e.findings)==null?void 0:K.findings)??[],v=new Map(g.map(C=>[C.id,C])),y=o.useMemo(()=>new Set(As(e.content).map(C=>C.file)),[e.content]),w=o.useMemo(()=>{var C;return((C=e.findings)==null?void 0:C.findings)??c.flat()},[e.findings,c]),[S,A]=o.useState(),[R,b]=o.useState(null);o.useEffect(()=>{var B;if(!R)return;(B=document.getElementById(`finding-${R.id}`))==null||B.scrollIntoView({behavior:"smooth",block:"center"});const C=setTimeout(()=>b(null),2e3);return()=>clearTimeout(C)},[R]);const f=C=>{C.file&&A(B=>({file:C.file,line:C.line,nonce:((B==null?void 0:B.nonce)??0)+1}))},k=C=>b(B=>({id:C,nonce:((B==null?void 0:B.nonce)??0)+1}));function j(C){const B=Di(C);return B?C.file&&y.has(C.file)?t.jsx("button",{type:"button",onClick:()=>f(C),className:"min-w-0 break-all font-mono text-xs text-accent hover:underline",children:B}):t.jsx("span",{title:C.file?s.review.locationNotInDiff:void 0,className:"min-w-0 break-all font-mono text-xs text-og-500",children:B}):null}function $(C){return t.jsxs("div",{id:`finding-${C.id}`,className:`card p-3 text-sm ${(R==null?void 0:R.id)===C.id?"ring-2 ring-accent":""}`,children:[t.jsxs("div",{className:"mb-1 flex flex-wrap items-center gap-2",children:[t.jsx("span",{className:"font-mono text-og-400",children:C.id}),t.jsx("span",{className:Pi[C.severity],children:C.severity}),C.id.startsWith("u-")&&t.jsx("span",{className:"pill pill-warn",children:s.review.roleUser}),j(C)]}),t.jsx("div",{className:"text-og-800",children:t.jsx(Ye,{text:C.message})})]},C.id)}return t.jsxs("div",{className:"space-y-6",children:[t.jsxs("section",{id:"diff",children:[t.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[t.jsx("h2",{className:"text-sm font-semibold text-og-800",children:e.phase==="spec"?s.review.specDraft:s.review.codeChanges}),r&&t.jsxs("div",{className:"flex items-center gap-1",children:[t.jsx("button",{type:"button",onClick:()=>i("full"),className:`btn-ghost px-2 py-0.5 text-xs ${m?"text-accent":""}`,children:s.review.viewFull}),t.jsx("button",{type:"button",onClick:()=>i("interdiff"),disabled:l.status==="unavailable",title:l.status==="unavailable"?h(l.reason):void 0,className:`btn-ghost px-2 py-0.5 text-xs ${d||u?"text-accent":""}`,children:s.review.viewInterdiff})]})]}),e.contentTruncated&&m&&t.jsx("div",{className:"mb-2 text-xs text-accent",children:s.review.contentTruncated}),e.phase==="spec"?e.content?t.jsx("div",{className:"card p-4 text-sm text-og-800",children:t.jsx(Ye,{text:e.content})}):t.jsx("div",{className:"text-sm text-og-400",children:s.review.noContent}):u?t.jsx("div",{className:"text-sm text-og-500",children:s.review.interdiffLoading}):d?t.jsx(En,{content:l.diff}):e.content?t.jsx(En,{content:e.content,diffstat:e.diffstat,findings:w,onFindingClick:k,expandRequest:S}):t.jsx("div",{className:"text-sm text-og-400",children:s.review.noContent})]}),t.jsxs("section",{id:"review",children:[t.jsx("h2",{className:"mb-2 text-sm font-semibold text-og-800",children:s.review.qaReviewHeading}),e.findings===void 0?c.length>0?t.jsx("div",{className:"space-y-3",children:c.map((C,B)=>t.jsxs("div",{id:`batch-${B}`,className:"space-y-2",children:[t.jsx("div",{className:"text-xs text-og-500",children:s.review.batchPartialHeading(B+1)}),C.length===0?t.jsx("div",{className:"text-sm text-og-400",children:s.review.noFindingsThisRound}):C.map($)]},B))}):t.jsx("div",{className:"text-sm text-og-400",children:s.review.notSubmitted}):g.length===0?t.jsx("div",{className:"text-sm text-og-400",children:s.review.noFindingsThisRound}):t.jsx("div",{className:"space-y-2",children:g.map($)})]}),e.response&&t.jsxs("section",{id:"response",children:[t.jsx("h2",{className:"mb-2 text-sm font-semibold text-og-800",children:s.review.devResponsesHeading}),x.length===0?t.jsx("div",{className:"text-sm text-og-400",children:s.review.noContent}):t.jsx("div",{className:"space-y-2",children:x.map(C=>{const B=v.get(C.findingId);return t.jsxs("div",{className:"card p-3 text-sm",children:[t.jsxs("div",{className:"mb-1 flex flex-wrap items-center gap-2",children:[t.jsx("span",{className:"font-mono text-og-400",children:C.findingId}),t.jsx("span",{className:$i[C.action],children:C.action}),C.commitSha&&t.jsx("span",{className:"font-mono text-xs text-og-500",children:C.commitSha.slice(0,9)})]}),B&&t.jsxs("div",{className:"mb-1 break-words text-xs text-og-500",children:["↳ ",B.message]}),t.jsx("div",{className:"text-og-800",children:t.jsx(Ye,{text:C.rationale})})]},C.findingId)})})]}),e.userDecision&&t.jsxs("section",{id:"user-decision",children:[t.jsx("h2",{className:"mb-2 text-sm font-semibold text-og-800",children:s.review.userDecisionHeading}),t.jsxs("div",{className:"card p-3 text-sm",children:[t.jsxs("div",{className:"mb-1 flex flex-wrap items-center gap-2",children:[t.jsx("span",{className:Ei[e.userDecision.verdict],children:e.userDecision.verdict}),t.jsx("span",{className:"text-xs text-og-400",children:qt(e.userDecision.at)})]}),e.userDecision.comments&&t.jsx("div",{className:"text-og-800",children:t.jsx(Ye,{text:e.userDecision.comments})})]})]})]})}const Bi={approve:"approve","request-changes":"request-changes",comment:"comment"};function Mi(e){return e==="server-mode"||e==="no-pr"||e==="driver-unavailable"?e:void 0}function Oi(e){return{"server-mode":e.prReview.reasonServerMode,"no-pr":e.prReview.reasonNoPr,"driver-unavailable":e.prReview.reasonDriverUnavailable}}function Es(e){if(!e)return"";const n=e.match(/^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2})/);return n?`${n[1]} ${n[2]}`:e}function Hi(){const e=M(),{taskId:n=""}=Ze(),s=Te(),{hash:r}=Gt(),{data:a}=on(n),i=a?Ss(a):void 0,{data:l,loaded:d,error:u}=Ts(n,i),[m,h]=o.useState(null),x=(l==null?void 0:l.prNumber)??(a==null?void 0:a.prNumber),c=(l==null?void 0:l.prUrl)??(a==null?void 0:a.prUrl),g=_n(c),v=l?ks(l.items):[],y=d&&!u&&(l==null?void 0:l.available)===!0&&l.items.length>0,w=o.useRef(null),S=o.useRef(void 0);return o.useEffect(()=>()=>clearTimeout(S.current),[]),o.useEffect(()=>{let A=null;if(r)try{A=decodeURIComponent(r.slice(1))}catch{A=null}if(!A){w.current=null,h(null);return}if(w.current===A||!y||!l)return;const R=document.getElementById(A);R&&(w.current=A,R.scrollIntoView({behavior:"smooth",block:"center"}),h(A),clearTimeout(S.current),S.current=setTimeout(()=>h(null),2e3))},[y,l,r]),t.jsxs("div",{className:"mx-auto w-full max-w-5xl",children:[t.jsx("button",{type:"button",onClick:()=>s(-1),className:"btn-ghost mb-3",children:e.common.back}),t.jsxs("div",{className:"mb-1 flex flex-wrap items-baseline gap-2",children:[t.jsx("span",{className:"font-mono text-og-400",children:n}),t.jsx("span",{className:"text-sm font-semibold text-og-1000",children:(a==null?void 0:a.title)??""})]}),t.jsxs("div",{className:"mb-4 flex flex-wrap items-center gap-2 text-xs text-og-500",children:[t.jsx("span",{className:"pill",children:e.prReview.codeReviewHeading}),g&&x!==void 0&&t.jsx("a",{href:g,target:"_blank",rel:"noopener noreferrer",className:"text-accent hover:text-accent-hover",children:e.taskDetail.viewPr(x)})]}),!d&&t.jsx("div",{className:"text-sm text-og-500",children:e.common.loading}),d&&u&&t.jsx("div",{className:"text-sm text-accent",children:e.review.loadFailed(u)}),d&&!u&&l&&!l.available&&t.jsx("div",{className:"text-sm text-og-500",children:Oi(e)[Mi(l.reason)??"no-pr"]}),d&&!u&&(l==null?void 0:l.available)&&(l.items.length===0?l.truncated?t.jsx("div",{className:"text-sm text-accent",children:e.prReview.listTruncated}):l.error?t.jsx("div",{className:"text-sm text-accent",children:e.prReview.fetchFailed(l.error)}):t.jsx("div",{className:"text-sm text-og-400",children:e.review.notStarted}):t.jsxs(t.Fragment,{children:[l.error&&t.jsx("div",{className:"mb-3 text-xs text-accent",children:e.prReview.partialFetchFailed(l.error)}),l.truncated&&t.jsx("div",{className:"mb-3 text-xs text-accent",children:e.prReview.listTruncated}),t.jsx("div",{className:"space-y-5",children:v.map((A,R)=>t.jsx(_i,{round:A,index:R,flashId:m},Ns(A,String(R))))})]}))]})}function _i({round:e,index:n,flashId:s}){const r=M(),a=e.review?r.agents.round(n+1):r.status.in_progress;return t.jsxs("div",{children:[t.jsx("div",{className:"mb-1.5 text-xs font-medium text-og-700",children:a}),t.jsxs("div",{className:"space-y-2",children:[e.items.map((i,l)=>i.kind==="review"?t.jsx(Fn,{item:i,flashId:s},Xe(i,`${n}-${l}`)):t.jsx(Ui,{item:i,flashId:s},Xe(i,`${n}-${l}`))),e.review&&t.jsx(Fn,{item:e.review,flashId:s})]})]})}function Ds(e,n){const s=yt(e);return`card p-3 text-sm${s&&s===n?" ring-2 ring-accent":""}`}function Ui({item:e,flashId:n}){const s=M(),r=e.kind==="review-comment";return t.jsxs("div",{id:yt(e),className:Ds(e,n),children:[t.jsxs("div",{className:"mb-1 flex flex-wrap items-center gap-2",children:[t.jsx("span",{className:"pill shrink-0",children:r?s.prReview.inlineComment:s.prReview.comment}),e.author?t.jsx("span",{className:"font-medium text-og-700",children:e.author}):t.jsx("span",{className:"text-xs italic text-og-400",children:s.prReview.ghostAuthor}),r&&e.path&&t.jsx("span",{className:"min-w-0 break-all font-mono text-xs text-og-500",children:e.line!==void 0?`${e.path}:${e.line}`:e.path}),e.inReplyTo&&t.jsx("span",{className:"text-xs text-og-400",children:s.prReview.replyIndicator}),e.createdAt&&t.jsx("span",{className:"text-xs text-og-400",children:Es(e.createdAt)})]}),t.jsx(Is,{item:e})]})}function Fn({item:e,flashId:n}){const s=M(),r=e.verdict??"comment";return t.jsxs("div",{id:yt(e),className:Ds(e,n),children:[t.jsxs("div",{className:"mb-1 flex flex-wrap items-center gap-2",children:[t.jsx("span",{className:"shrink-0 min-w-[1.75rem] text-xs font-semibold tracking-wide text-og-600",children:s.review.roleQa}),t.jsx("span",{className:js[r],children:Bi[r]}),e.reviewState&&t.jsx("span",{className:"pill shrink-0",children:e.reviewState}),e.author?t.jsx("span",{className:"text-xs text-og-400",children:e.author}):t.jsx("span",{className:"text-xs italic text-og-400",children:s.prReview.ghostAuthor}),e.commitSha&&t.jsx("span",{className:"font-mono text-xs text-og-500",children:e.commitSha.slice(0,9)}),!e.commitSha&&e.anchorSha&&t.jsx("span",{className:"font-mono text-xs text-og-500",children:e.anchorSha.slice(0,9)}),e.createdAt&&t.jsx("span",{className:"text-xs text-og-400",children:Es(e.createdAt)})]}),t.jsx(Is,{item:e,placeholder:s.prReview.noReviewBody})]})}function Is({item:e,placeholder:n}){const s=M();return t.jsxs(t.Fragment,{children:[e.body?t.jsx("div",{className:"text-og-800",children:t.jsx(Ye,{text:e.body})}):n?t.jsx("div",{className:"text-og-400",children:n}):null,e.bodyTruncated&&t.jsx("div",{className:"mt-1 text-xs text-accent",children:s.prReview.bodyTruncated})]})}function qi(){const e=M(),[n,s]=o.useState(!1);return t.jsx("button",{type:"button",onClick:()=>s(r=>!r),"aria-label":n?e.nav.toggleToIcon:e.nav.toggleToText,className:"flex h-7 min-w-[60px] shrink-0 items-center justify-center font-display text-sm font-semibold tracking-tight text-og-1000",children:n?t.jsx("span",{className:"inline-flex h-6 items-center leading-none",children:"baxian"}):t.jsx("img",{src:"/baxian-logo.png",alt:"baxian",width:20,height:24,className:"block h-6 w-auto"})})}function Wi(){const[e,n]=o.useState(null),[s,r]=o.useState(!1),[a,i]=o.useState(null);return o.useEffect(()=>et().subscribe("pollers",d=>{i(null),n(d),r(!0)},d=>i(d)),[]),{data:e,loaded:s,error:a}}function Gi(e){return e.lastErrorClass==="RATE_LIMIT"&&e.rateLimitedUntil!==void 0&&Date.parse(e.rateLimitedUntil)>Date.now()}function Qi(e){const n=e.find(a=>a.health==="failed");if(n)return{poller:n,kind:"failed"};const s=e.find(Gi);if(s)return{poller:s,kind:"rate-limited"};const r=e.find(a=>a.health==="degraded");return r?{poller:r,kind:"degraded"}:null}function zi(){const e=M(),{data:n}=Wi();if(!n)return null;const s=Qi(n);if(!s)return null;const{poller:r,kind:a}=s,i=a==="failed"?e.banner.githubUnreachable(r.repo):a==="rate-limited"?e.banner.githubRateLimited(r.repo,r.rateLimitedUntil):e.banner.githubDegraded(r.repo);return t.jsx("div",{className:"border-b border-accent/25 bg-accent-soft/60 px-4 py-2 text-sm text-accent",title:r.lastErrorMessage??"",children:i})}function Ki(){const e=M(),{phase:n,count:s,error:r,triggerRestart:a}=wt();return n==="idle"?null:n==="failed"?t.jsxs("div",{className:"flex items-center justify-between border-b border-accent/25 bg-accent-soft px-4 py-2",children:[t.jsx("div",{className:"text-sm text-accent",children:e.banner.restartFailed(r??"")}),t.jsx("button",{onClick:()=>{a()},className:"btn-ghost",children:e.common.retry})]}):n==="restarting"?t.jsx("div",{className:"border-b border-accent-soft bg-accent-soft/40 px-4 py-2 text-sm text-accent",children:e.banner.restarting}):t.jsxs("div",{className:"flex items-center justify-between border-b border-accent/25 bg-accent-soft/60 px-4 py-2",children:[t.jsx("div",{className:"text-sm text-accent",children:e.banner.pendingNotice(s)}),t.jsx("button",{onClick:()=>{a()},className:"btn-primary",children:e.banner.restartNow})]})}const Vi=new Set(["done","merged"]);function It(e,n){const s=e.trim().replace(/\s+/g," ");return s.length>n?`${s.slice(0,n-1)}…`:s}function Yi(e,n){return e?e.repo?`${e.id} · ${e.repo}`:e.id:n}function Ji(e){return e.title?`${e.id} · ${e.title}`:e.id}function Xi(e){return Vi.has(e)}function Zi(e,n,s){const r=rn();if(!(!r||r.permission!=="granted"))try{const a=Xt(),i=new r(a.notification.taskDone(It(e.title||e.id,80)),{body:[a.notification.bodyProject(It(n,120)),a.notification.bodyTask(It(Ji(e),120)),a.notification.bodyStatus(Xr(e.status))].join(`
|
|
18
|
-
`),icon:"/baxian-logo.png",tag:`baxian-task-${e.id}`});i.onclick=()=>{window.focus(),s(),i.close()}}catch(a){console.warn("[task-notifications] failed to show notification:",a)}}function eo(e,n,s){const r=o.useRef(new Map),a=o.useRef(new Set),i=o.useRef(new Map),l=o.useRef(new Set),d=o.useRef(new Set),u=o.useRef(new Map),m=o.useRef(n),h=o.useRef(new Map),x=o.useMemo(()=>s?(e??[]).map(c=>c.id).sort().join("\0"):"",[s,e]);o.useEffect(()=>{m.current=n},[n]),o.useEffect(()=>{h.current=new Map((e??[]).map(c=>[c.id,Yi(c,c.id)]))},[e]),o.useEffect(()=>{const c=w=>{u.current.set(w,(u.current.get(w)??0)+1)};if(x===""){for(const w of d.current)c(w);d.current=new Set,r.current.clear(),i.current.clear(),l.current.clear();return}const g=x.split("\0"),v=new Set(g);for(const w of d.current)v.has(w)||c(w);d.current=v;for(const w of r.current.keys())v.has(w)||r.current.delete(w);for(const w of i.current.keys())v.has(w)||i.current.delete(w);const y=g.map(w=>et().subscribe(`project-tasks:${w}`,S=>{const A=r.current.get(w),R=new Map(S.map(f=>[f.id,f]));r.current.set(w,R);const b=i.current.get(w)??new Set;if(i.current.set(w,b),!A){for(const f of R.keys())b.delete(f);return}for(const[f]of A)R.has(f)||a.current.has(f)||b.add(f);for(const f of[...b]){if(R.has(f)){b.delete(f);continue}const k=u.current.get(w)??0,j=`${w}:${k}:${f}`;l.current.has(j)||(l.current.add(j),F.tasks.get(f).then($=>{if((u.current.get(w)??0)!==k)return;if(!$||$.projectId!==w||!Xi($.status)){b.delete(f);return}b.delete(f),a.current.add($.id);const I=h.current.get(w)??w;Zi($,I,()=>m.current($))}).catch($=>{console.warn(`[task-notifications] failed to confirm completed task ${f}:`,$)}).finally(()=>{l.current.delete(j)}))}},S=>{console.warn(`[task-notifications] project task stream failed for ${w}:`,S)}));return()=>{for(const w of y)w()}},[x])}function to(){const e=Gt(),n=Te(),{projects:s}=tt(),{enabled:r}=ms(),a=!e.pathname.startsWith("/terminal/");return or(),eo(s,i=>n(Fe(i.projectId,i.id)),r),t.jsxs("div",{className:"flex h-dvh flex-col bg-page",children:[t.jsxs("nav",{className:"flex h-12 flex-none items-center border-b border-hairline bg-surface px-3 sm:px-6",children:[t.jsxs(_e,{to:"/",className:"flex shrink-0 items-center gap-2 font-display text-sm font-semibold tracking-tight text-og-1000",children:[t.jsx("span",{"aria-hidden":!0,className:"block h-2.5 w-2.5 rounded-full bg-accent"}),"baxian"]}),t.jsx("div",{id:fs,className:"ml-auto flex min-w-0 items-center justify-end gap-2"})]}),t.jsx(Ki,{}),t.jsx(zi,{}),t.jsxs("main",{className:"flex min-h-0 flex-1 flex-col overflow-y-auto px-3 py-6 sm:px-6",children:[t.jsxs(Ws,{children:[t.jsx(Me,{path:"/",element:t.jsx(Ta,{})}),t.jsx(Me,{path:"/project/:id",element:t.jsx(Ba,{})}),t.jsx(Me,{path:"/project/:id/task/:taskId",element:t.jsx(ri,{})}),t.jsx(Me,{path:"/terminal/:agentId",element:t.jsx(ii,{})}),t.jsx(Me,{path:"/tasks/:taskId/rounds/:phase/:round",element:t.jsx(Ii,{})}),t.jsx(Me,{path:"/tasks/:taskId/pr-review",element:t.jsx(Hi,{})})]}),a&&t.jsx("footer",{className:"mt-auto flex justify-center pb-4 pt-24",children:t.jsx(qi,{})})]})]})}function no(){return t.jsx(qs,{children:t.jsx(xa,{children:t.jsx(to,{})})})}function so({children:e}){const n=M(),[s,r]=o.useState({kind:"probing"}),a=o.useRef(s);o.useEffect(()=>{a.current=s},[s]);const i=o.useCallback(async()=>{r({kind:"probing"});try{const d=await F.config.get();Ot(d.language),r({kind:"authorized"})}catch(d){if(d instanceof De&&d.status===401){r({kind:"unauthorized"});return}r({kind:"error",message:d instanceof Error?d.message:void 0,fallback:"connectFallback"})}},[]);if(o.useEffect(()=>{i()},[i]),o.useEffect(()=>{const d=()=>{a.current.kind!=="probing"&&r({kind:"unauthorized",reason:"expired"})};return window.addEventListener(mt,d),()=>window.removeEventListener(mt,d)},[]),s.kind==="authorized")return t.jsx(t.Fragment,{children:e});if(s.kind==="error")return t.jsxs(Wt,{title:n.auth.connectFailedTitle,children:[t.jsx("p",{className:"text-sm text-og-600",children:s.message??n.auth[s.fallback]}),t.jsx("button",{type:"button",onClick:()=>{i()},className:"btn-primary mt-4 w-full",children:n.common.retry})]});if(s.kind==="probing")return t.jsx(Wt,{title:n.auth.checkingTitle,children:t.jsx("p",{className:"text-sm text-og-500",children:n.auth.checkingBody})});const l=s.reason==="expired"?n.auth.sessionExpired:s.reason==="invalid"?n.auth.tokenInvalid:void 0;return t.jsx(ro,{message:l,onSubmit:async d=>{Vs(d);try{const u=await F.config.get();Ot(u.language),r({kind:"authorized"})}catch(u){if(Ys(),u instanceof De&&u.status===401){r({kind:"unauthorized",reason:"invalid"});return}r({kind:"error",message:u instanceof Error?u.message:void 0,fallback:"loginFailed"})}}})}function Wt({title:e,children:n}){return t.jsx("div",{className:"flex min-h-dvh items-center justify-center bg-page px-4",children:t.jsxs("div",{className:"w-full max-w-sm rounded-lg border border-hairline bg-surface px-6 py-6",children:[t.jsx("h1",{className:"mb-3 font-display text-sm font-semibold tracking-tight text-og-1000",children:e}),n]})})}function ro({message:e,onSubmit:n}){const s=M(),[r,a]=o.useState(""),[i,l]=o.useState(!1),[d,u]=o.useState(void 0),m=async x=>{x.preventDefault();const c=r.trim();if(!c){u(s.auth.tokenRequired);return}u(void 0),l(!0);try{await n(c)}finally{l(!1)}},h=d??e;return t.jsxs(Wt,{title:s.auth.loginTitle,children:[t.jsx("p",{className:"mb-4 text-sm text-og-600",children:s.auth.loginDescription}),t.jsxs("form",{onSubmit:x=>{m(x)},children:[t.jsx("label",{className:re,htmlFor:"baxian-token",children:s.auth.tokenLabel}),t.jsx("input",{id:"baxian-token",type:"password",autoComplete:"current-password",autoFocus:!0,value:r,onChange:x=>a(x.target.value),className:`${de} font-mono`,placeholder:s.auth.tokenPlaceholder,disabled:i}),h&&t.jsx("p",{role:"alert",className:"mt-2 text-xs text-accent",children:h}),t.jsx("button",{type:"submit",disabled:i,className:"btn-primary mt-4 w-full",children:i?s.auth.submitting:s.auth.submit})]})]})}Hs.createRoot(document.getElementById("root")).render(t.jsx(o.StrictMode,{children:t.jsx(ir,{children:t.jsx(br,{children:t.jsx(ur,{children:t.jsx(fr,{children:t.jsx(so,{children:t.jsx(no,{})})})})})})}));
|