baxian 2.0.2 → 2.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (232) hide show
  1. package/README.md +2 -2
  2. package/README.zh-CN.md +3 -3
  3. package/dist/agent/bootstrap.js +4 -4
  4. package/dist/agent/branch.d.ts.map +1 -1
  5. package/dist/agent/branch.js +0 -7
  6. package/dist/agent/branch.js.map +1 -1
  7. package/dist/agent/detect/region.d.ts.map +1 -1
  8. package/dist/agent/detect/region.js +0 -3
  9. package/dist/agent/detect/region.js.map +1 -1
  10. package/dist/agent/dispatch-reconciler.d.ts +2 -0
  11. package/dist/agent/dispatch-reconciler.d.ts.map +1 -1
  12. package/dist/agent/dispatch-reconciler.js +48 -55
  13. package/dist/agent/dispatch-reconciler.js.map +1 -1
  14. package/dist/agent/lineage.d.ts.map +1 -1
  15. package/dist/agent/lineage.js +0 -9
  16. package/dist/agent/lineage.js.map +1 -1
  17. package/dist/agent/manager.d.ts +42 -8
  18. package/dist/agent/manager.d.ts.map +1 -1
  19. package/dist/agent/manager.js +717 -375
  20. package/dist/agent/manager.js.map +1 -1
  21. package/dist/agent/net-exec.d.ts.map +1 -1
  22. package/dist/agent/net-exec.js +0 -5
  23. package/dist/agent/net-exec.js.map +1 -1
  24. package/dist/agent/pane-streamer-manager.d.ts.map +1 -1
  25. package/dist/agent/pane-streamer-manager.js +0 -36
  26. package/dist/agent/pane-streamer-manager.js.map +1 -1
  27. package/dist/agent/pane-streamer.d.ts +6 -0
  28. package/dist/agent/pane-streamer.d.ts.map +1 -1
  29. package/dist/agent/pane-streamer.js +126 -83
  30. package/dist/agent/pane-streamer.js.map +1 -1
  31. package/dist/agent/phase-signal-watcher.d.ts.map +1 -1
  32. package/dist/agent/phase-signal-watcher.js +2 -77
  33. package/dist/agent/phase-signal-watcher.js.map +1 -1
  34. package/dist/agent/phase-signal.d.ts +0 -1
  35. package/dist/agent/phase-signal.d.ts.map +1 -1
  36. package/dist/agent/phase-signal.js +0 -17
  37. package/dist/agent/phase-signal.js.map +1 -1
  38. package/dist/agent/preflight.d.ts.map +1 -1
  39. package/dist/agent/preflight.js +0 -18
  40. package/dist/agent/preflight.js.map +1 -1
  41. package/dist/agent/prompt.d.ts.map +1 -1
  42. package/dist/agent/prompt.js +0 -1
  43. package/dist/agent/prompt.js.map +1 -1
  44. package/dist/agent/repo-store.d.ts.map +1 -1
  45. package/dist/agent/repo-store.js +0 -38
  46. package/dist/agent/repo-store.js.map +1 -1
  47. package/dist/agent/runner.d.ts.map +1 -1
  48. package/dist/agent/runner.js +0 -2
  49. package/dist/agent/runner.js.map +1 -1
  50. package/dist/agent/tmux-install.js +0 -1
  51. package/dist/agent/tmux-install.js.map +1 -1
  52. package/dist/agent/tmux-probe-poller.d.ts.map +1 -1
  53. package/dist/agent/tmux-probe-poller.js +4 -11
  54. package/dist/agent/tmux-probe-poller.js.map +1 -1
  55. package/dist/agent/tmux.d.ts.map +1 -1
  56. package/dist/agent/tmux.js +0 -86
  57. package/dist/agent/tmux.js.map +1 -1
  58. package/dist/agent/vt-visible-text.d.ts +46 -1
  59. package/dist/agent/vt-visible-text.d.ts.map +1 -1
  60. package/dist/agent/vt-visible-text.js +639 -63
  61. package/dist/agent/vt-visible-text.js.map +1 -1
  62. package/dist/api/agents.d.ts.map +1 -1
  63. package/dist/api/agents.js +3 -49
  64. package/dist/api/agents.js.map +1 -1
  65. package/dist/api/config.d.ts.map +1 -1
  66. package/dist/api/config.js +10 -59
  67. package/dist/api/config.js.map +1 -1
  68. package/dist/api/hosts.d.ts.map +1 -1
  69. package/dist/api/hosts.js +8 -63
  70. package/dist/api/hosts.js.map +1 -1
  71. package/dist/api/platform-guard.d.ts.map +1 -1
  72. package/dist/api/platform-guard.js +2 -3
  73. package/dist/api/platform-guard.js.map +1 -1
  74. package/dist/api/probe.d.ts.map +1 -1
  75. package/dist/api/probe.js +0 -1
  76. package/dist/api/probe.js.map +1 -1
  77. package/dist/api/projects.d.ts.map +1 -1
  78. package/dist/api/projects.js +15 -28
  79. package/dist/api/projects.js.map +1 -1
  80. package/dist/api/tasks.d.ts.map +1 -1
  81. package/dist/api/tasks.js +94 -58
  82. package/dist/api/tasks.js.map +1 -1
  83. package/dist/app.d.ts +2 -2
  84. package/dist/app.d.ts.map +1 -1
  85. package/dist/app.js +0 -6
  86. package/dist/app.js.map +1 -1
  87. package/dist/cli.d.ts.map +1 -1
  88. package/dist/cli.js +6 -31
  89. package/dist/cli.js.map +1 -1
  90. package/dist/config/hot-reload.d.ts.map +1 -1
  91. package/dist/config/hot-reload.js +0 -4
  92. package/dist/config/hot-reload.js.map +1 -1
  93. package/dist/config/loader.d.ts.map +1 -1
  94. package/dist/config/loader.js +6 -29
  95. package/dist/config/loader.js.map +1 -1
  96. package/dist/config/normalizer.d.ts.map +1 -1
  97. package/dist/config/normalizer.js +0 -19
  98. package/dist/config/normalizer.js.map +1 -1
  99. package/dist/config/validator.d.ts.map +1 -1
  100. package/dist/config/validator.js +31 -229
  101. package/dist/config/validator.js.map +1 -1
  102. package/dist/event/handlers.d.ts.map +1 -1
  103. package/dist/event/handlers.js +3 -11
  104. package/dist/event/handlers.js.map +1 -1
  105. package/dist/event/log.js +0 -2
  106. package/dist/event/log.js.map +1 -1
  107. package/dist/event/ws.d.ts.map +1 -1
  108. package/dist/event/ws.js +3 -3
  109. package/dist/event/ws.js.map +1 -1
  110. package/dist/index.d.ts.map +1 -1
  111. package/dist/index.js +5 -46
  112. package/dist/index.js.map +1 -1
  113. package/dist/platform/body-digest.d.ts.map +1 -1
  114. package/dist/platform/body-digest.js +0 -4
  115. package/dist/platform/body-digest.js.map +1 -1
  116. package/dist/platform/command-renderer.d.ts.map +1 -1
  117. package/dist/platform/command-renderer.js +0 -3
  118. package/dist/platform/command-renderer.js.map +1 -1
  119. package/dist/platform/comment-cursor.d.ts.map +1 -1
  120. package/dist/platform/comment-cursor.js +0 -21
  121. package/dist/platform/comment-cursor.js.map +1 -1
  122. package/dist/platform/driver-spec.d.ts.map +1 -1
  123. package/dist/platform/driver-spec.js +1 -42
  124. package/dist/platform/driver-spec.js.map +1 -1
  125. package/dist/platform/feedback.d.ts +5 -1
  126. package/dist/platform/feedback.d.ts.map +1 -1
  127. package/dist/platform/feedback.js +7 -1
  128. package/dist/platform/feedback.js.map +1 -1
  129. package/dist/platform/field-mapper.d.ts.map +1 -1
  130. package/dist/platform/field-mapper.js +3 -11
  131. package/dist/platform/field-mapper.js.map +1 -1
  132. package/dist/platform/git-driver.d.ts.map +1 -1
  133. package/dist/platform/git-driver.js +0 -20
  134. package/dist/platform/git-driver.js.map +1 -1
  135. package/dist/platform/manifest.d.ts.map +1 -1
  136. package/dist/platform/manifest.js +0 -3
  137. package/dist/platform/manifest.js.map +1 -1
  138. package/dist/platform/markers.d.ts.map +1 -1
  139. package/dist/platform/markers.js +0 -19
  140. package/dist/platform/markers.js.map +1 -1
  141. package/dist/platform/platform-poller.d.ts +5 -1
  142. package/dist/platform/platform-poller.d.ts.map +1 -1
  143. package/dist/platform/platform-poller.js +8 -49
  144. package/dist/platform/platform-poller.js.map +1 -1
  145. package/dist/platform/plugin-registry.d.ts.map +1 -1
  146. package/dist/platform/plugin-registry.js +1 -12
  147. package/dist/platform/plugin-registry.js.map +1 -1
  148. package/dist/platform/pr-conversation-cache.d.ts +12 -7
  149. package/dist/platform/pr-conversation-cache.d.ts.map +1 -1
  150. package/dist/platform/pr-conversation-cache.js +60 -40
  151. package/dist/platform/pr-conversation-cache.js.map +1 -1
  152. package/dist/platform/preflight-exec.d.ts.map +1 -1
  153. package/dist/platform/preflight-exec.js +0 -9
  154. package/dist/platform/preflight-exec.js.map +1 -1
  155. package/dist/platform/response-parser.d.ts.map +1 -1
  156. package/dist/platform/response-parser.js +0 -4
  157. package/dist/platform/response-parser.js.map +1 -1
  158. package/dist/platform/review-timeline.d.ts +17 -2
  159. package/dist/platform/review-timeline.d.ts.map +1 -1
  160. package/dist/platform/review-timeline.js +93 -106
  161. package/dist/platform/review-timeline.js.map +1 -1
  162. package/dist/platform/row-schema.d.ts.map +1 -1
  163. package/dist/platform/row-schema.js +0 -11
  164. package/dist/platform/row-schema.js.map +1 -1
  165. package/dist/platform/startup.d.ts.map +1 -1
  166. package/dist/platform/startup.js +1 -12
  167. package/dist/platform/startup.js.map +1 -1
  168. package/dist/platform/types.d.ts.map +1 -1
  169. package/dist/platform/types.js +0 -5
  170. package/dist/platform/types.js.map +1 -1
  171. package/dist/platform/verdict-engine.d.ts.map +1 -1
  172. package/dist/platform/verdict-engine.js +0 -15
  173. package/dist/platform/verdict-engine.js.map +1 -1
  174. package/dist/shared/concurrency.d.ts.map +1 -1
  175. package/dist/shared/concurrency.js +0 -2
  176. package/dist/shared/concurrency.js.map +1 -1
  177. package/dist/shared/constants.d.ts +0 -2
  178. package/dist/shared/constants.d.ts.map +1 -1
  179. package/dist/shared/constants.js +0 -3
  180. package/dist/shared/constants.js.map +1 -1
  181. package/dist/shared/git-url.d.ts.map +1 -1
  182. package/dist/shared/git-url.js +0 -9
  183. package/dist/shared/git-url.js.map +1 -1
  184. package/dist/shared/types.d.ts +31 -12
  185. package/dist/shared/types.d.ts.map +1 -1
  186. package/dist/shared/types.js +14 -0
  187. package/dist/shared/types.js.map +1 -1
  188. package/dist/skill/registry.d.ts.map +1 -1
  189. package/dist/skill/registry.js +0 -5
  190. package/dist/skill/registry.js.map +1 -1
  191. package/dist/skills/baxian-signals/SKILL.md +0 -6
  192. package/dist/state/agent-store.d.ts.map +1 -1
  193. package/dist/state/agent-store.js +0 -6
  194. package/dist/state/agent-store.js.map +1 -1
  195. package/dist/state/error-record-store.d.ts.map +1 -1
  196. package/dist/state/error-record-store.js +0 -5
  197. package/dist/state/error-record-store.js.map +1 -1
  198. package/dist/state/init.d.ts.map +1 -1
  199. package/dist/state/init.js +0 -1
  200. package/dist/state/init.js.map +1 -1
  201. package/dist/state/lock.d.ts.map +1 -1
  202. package/dist/state/lock.js +0 -1
  203. package/dist/state/lock.js.map +1 -1
  204. package/dist/state/snapshot.d.ts +0 -1
  205. package/dist/state/snapshot.d.ts.map +1 -1
  206. package/dist/state/snapshot.js +0 -13
  207. package/dist/state/snapshot.js.map +1 -1
  208. package/dist/state/task-store.d.ts.map +1 -1
  209. package/dist/state/task-store.js +96 -11
  210. package/dist/state/task-store.js.map +1 -1
  211. package/dist/terminal/attach.d.ts.map +1 -1
  212. package/dist/terminal/attach.js +0 -4
  213. package/dist/terminal/attach.js.map +1 -1
  214. package/dist/terminal/stream-ws.js +0 -5
  215. package/dist/terminal/stream-ws.js.map +1 -1
  216. package/dist/web/assets/index-CzVzThuT.js +15 -0
  217. package/dist/web/assets/{index-BS2adAfI.css → index-Rmp4wT_5.css} +1 -1
  218. package/dist/web/index.html +2 -2
  219. package/package.json +1 -1
  220. package/dist/agent/root-agent-runtime.d.ts +0 -80
  221. package/dist/agent/root-agent-runtime.d.ts.map +0 -1
  222. package/dist/agent/root-agent-runtime.js +0 -637
  223. package/dist/agent/root-agent-runtime.js.map +0 -1
  224. package/dist/agent/root-recovery-coordinator.d.ts +0 -124
  225. package/dist/agent/root-recovery-coordinator.d.ts.map +0 -1
  226. package/dist/agent/root-recovery-coordinator.js +0 -1557
  227. package/dist/agent/root-recovery-coordinator.js.map +0 -1
  228. package/dist/state/root-recovery-store.d.ts +0 -107
  229. package/dist/state/root-recovery-store.d.ts.map +0 -1
  230. package/dist/state/root-recovery-store.js +0 -400
  231. package/dist/state/root-recovery-store.js.map +0 -1
  232. package/dist/web/assets/index-BKiM0MSM.js +0 -15
@@ -1,15 +0,0 @@
1
- var Rs=Object.defineProperty;var Cs=(e,n,s)=>n in e?Rs(e,n,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[n]=s;var oe=(e,n,s)=>Cs(e,typeof n!="symbol"?n+"":n,s);import{r as o,j as t,a as As,c as Ps}from"./react-BFCkCmbU.js";import{x as Ls,a as Es}from"./xterm-D5X2JljJ.js";import{L as He,u as Pe,a as xt,b as An,B as Ds,R as $s,c as ze}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[m,g]=o.useState(!1),h=o.useRef(null),p=o.useRef(null),u=o.useId(),c=o.useId();return o.useEffect(()=>{if(!m)return;const b=v=>{var S,j;const A=v.target;A&&((S=p.current)!=null&&S.contains(A)||(j=h.current)!=null&&j.contains(A)||g(!1))},w=v=>{var A;v.key==="Escape"&&(g(!1),(A=h.current)==null||A.focus())};return document.addEventListener("mousedown",b),document.addEventListener("keydown",w),()=>{document.removeEventListener("mousedown",b),document.removeEventListener("keydown",w)}},[m]),o.useEffect(()=>{var w;if(!m||!r)return;const b=(w=p.current)==null?void 0:w.querySelector('[role="menuitem"]:not([disabled])');b==null||b.focus()},[m,r]),t.jsxs("div",{className:`relative ${i??""}`,children:[t.jsx("button",{ref:b=>{h.current=b,d&&(d.current=b)},id:c,type:"button",onClick:()=>g(b=>!b),disabled:l,"aria-haspopup":"menu","aria-expanded":m,"aria-controls":m?u: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"})]})}),m&&t.jsx("div",{ref:p,id:u,role:"menu","aria-labelledby":c,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 b;g(!1),(b=h.current)==null||b.focus()})})]})}function Ce(e){return e==="spec"}function It(e){var n;return e.prNumber===void 0||e.phase===void 0||((n=e.deliveryConfirmation)==null?void 0:n.phase)!==e.phase||e.replyActorStatus!=="verified"}const Is={"claude-code":"Claude Code",codex:"Codex",opencode:"OpenCode",qodercli:"Qoder CLI"},Bs={"claude-code":"--permission-mode bypassPermissions",codex:"--dangerously-bypass-approvals-and-sandbox",opencode:"--auto",qodercli:"--dangerously-skip-permissions"};function Pn(e,n){const s=[e?Is[e]:null,n||null].filter(Boolean);return s.length>0?s.join(" · "):null}function Ln(e,n,s){const r=Pn(n,s);return r?`${e} (${r})`:e}const ct=new Set(["merged","done","failed","cancelled"]),En=new Set(["in_progress","review","fixing","spec-ready","approved","merge-ready","max_rounds"]),wt=20,bt=5*1024*1024,st=4,Dn=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 Fs=1536,Ms=1872,In=192,Bn=208,qe="/api",Gt="baxian.token",ut="baxian:unauthorized";function zt(){try{return typeof localStorage<"u"?localStorage.getItem(Gt):null}catch{return null}}function Os(e){try{localStorage.setItem(Gt,e)}catch(n){console.error("Failed to save auth token to localStorage",n)}}function Hs(){try{localStorage.removeItem(Gt)}catch(e){console.error("Failed to clear auth token from localStorage",e)}}function Ie(e){const n=zt();return{...e??{},...n?{Authorization:`Bearer ${n}`}:{}}}class Ue extends Error{constructor(n,s,r){super(s),this.status=n,this.details=r,this.name="ApiError"}}function _s(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 Be(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=_s(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(ut)),new Ue(e.status,s,r)}async function Re(e){const n=await fetch(`${qe}${e}`,{headers:Ie()});return n.ok||await Be(n),n.json()}async function Us(){const e=await fetch("/health");return e.ok||await Be(e),e.json()}async function ce(e,n,s){const r=n!==void 0,a=await fetch(`${qe}${e}`,{method:"POST",headers:r?Ie({"Content-Type":"application/json"}):Ie(),body:r?JSON.stringify(n):void 0,signal:s==null?void 0:s.signal});return a.ok||await Be(a),a.json()}async function jt(e,n,s){const r=await fetch(`${qe}${e}`,{method:"PATCH",headers:Ie({"Content-Type":"application/json"}),body:n?JSON.stringify(n):void 0,signal:s==null?void 0:s.signal});if(r.ok||await Be(r),r.status===204)return;const a=await r.text();if(a)return JSON.parse(a)}async function an(e,n){const s=await fetch(`${qe}${e}`,{method:"PUT",headers:Ie({"Content-Type":"application/json"}),body:JSON.stringify(n??null)});if(s.ok||await Be(s),s.status===204)return;const r=await s.text();if(r)return JSON.parse(r)}async function We(e){const n=await fetch(`${qe}${e}`,{method:"DELETE",headers:Ie()});if(n.ok||await Be(n),n.status===204)return;const s=await n.text();if(s)return JSON.parse(s)}const W=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 E={agents:{list:()=>Re("/agents"),get:e=>Re(`/agents/${W(e)}`),stop:e=>We(`/agents/${W(e)}/session`),compact:e=>ce(`/agents/${W(e)}/compact`),clear:e=>ce(`/agents/${W(e)}/clear`),probe:(e,n={},s)=>ce("/agents/probe",{mode:e,host:n.host,hostId:n.hostId},s),installTmux:(e,n={})=>ce("/agents/install-tmux",{mode:e,host:n.host,hostId:n.hostId}),uploadImage:async(e,n)=>ce(`/agents/${W(e)}/images`,{dataBase64:await Bt(n)}),setPet:(e,n)=>an(`/agents/${W(e)}/pet`,{petId:n})},pets:{list:()=>Re("/pets"),create:async(e,n)=>ce("/pets",{petJson:e,spritesheetBase64:await Bt(n)}),remove:e=>We(`/pets/${W(e)}`),fetchSpritesheet:async e=>{const n=await fetch(`${qe}/pets/${W(e)}/spritesheet`,{headers:Ie()});return n.ok||await Be(n),n.blob()}},tasks:{list:async e=>{const n=new Map;for(const s of["active","pending"]){let r=0;for(;;){const a=await E.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=${W(e)}`];return n.category&&s.push(`category=${n.category}`),s.push(`offset=${n.offset??0}`),Re(`/tasks?${s.join("&")}`)},get:e=>Re(`/tasks/${W(e)}`),create:e=>ce("/tasks",e),update:(e,n)=>jt(`/tasks/${W(e)}`,n),retry:e=>ce(`/tasks/${W(e)}/retry`),review:(e,n)=>ce(`/tasks/${W(e)}/review`,n),complete:e=>ce(`/tasks/${W(e)}/complete`),continue:e=>ce(`/tasks/${W(e)}/continue`),spec:(e,n)=>ce(`/tasks/${W(e)}/spec`,n),prReview:e=>Re(`/tasks/${W(e)}/pr-review`),dispatch:(e,n)=>ce(`/tasks/${W(e)}/dispatch`,n)},projects:{list:()=>Re("/projects"),get:e=>Re(`/projects/${W(e)}`),create:e=>ce("/projects",e),delete:e=>We(`/projects/${W(e)}`),addAgentGroup:(e,n)=>ce(`/projects/${W(e)}/agents`,n),replaceAgent:(e,n,s)=>an(`/projects/${W(e)}/agents/${W(n)}`,s),deleteAgent:(e,n)=>We(`/projects/${W(e)}/agents/${W(n)}`),resumeAgent:(e,n)=>ce(`/projects/${W(e)}/agents/${W(n)}/resume`),restartRepl:(e,n)=>ce(`/projects/${W(e)}/agents/${W(n)}/restart-repl`),retryAgent:(e,n)=>ce(`/projects/${W(e)}/agents/${W(n)}/retry`),bootstrap:e=>ce(`/projects/${W(e)}/bootstrap`)},hosts:{list:()=>Re("/hosts"),create:e=>ce("/hosts",e),update:(e,n)=>jt(`/hosts/${W(e)}`,n),delete:e=>We(`/hosts/${W(e)}`),check:e=>ce("/hosts/check",e)},config:{get:()=>Re("/config"),patch:e=>jt("/config",e)},health:{get:Us},server:{restart:()=>ce("/restart")}};function Wt(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 qs(e){return t.jsxs("svg",{...Wt(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 Gs(e){return t.jsxs("svg",{...Wt(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 zs(e){return t.jsxs("svg",{...Wt(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 Fn={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",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 agent groups 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 group now, or later?",later:"Later",continueAddingAgent:"Continue adding an agent group"},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 the agent group containing ${e}?`,deleteConfirmBody:"Both paired agents will be removed. This action cannot be undone.",deletedWithPairTitle:e=>`Deleted the agent group containing ${e}`,deletedWithPairBody:e=>`The paired 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 (requires an existing PR).`,callReviewRecoveryTaskTitle:e=>`Open task ${e} and use Call review to confirm the PR number when needed, delivered stage, and platform actor first.`,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:"GitHub accepts HTTPS, SSH, scp, or owner/repo; other platforms require an HTTP(S) URL",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",gitCliToolLabel:"Git CLI tool",gitCliToolPlaceholder:"e.g. forge",gitCliToolRequired:"Required for non-GitHub repositories",gitCliNotesLabel:"CLI instance notes (optional)",createdToastTitle:e=>`Project ${e} created`},createAgent:{modalTitle:e=>`Add agent group to ${e}`,submitLabel:"Add group",continueLabel:"Continue to QA",submitting:"Adding group…",idTakenGlobalError:"This ID is already in use (must be globally unique)",idPlaceholder:(e,n)=>`${e}-${n}`,roleLabel:"Role",devStepLabel:"Dev agent (step 1 of 2)",qaStepLabel:"QA agent (step 2 of 2)",pairedDevLabel:e=>`Paired with Dev agent ${e}`,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,s)=>`Agent group ${e} + ${n} added to ${s}`},createTask:{titleCreate:"New task",titleEdit:"Edit task",selectProjectPlaceholder:"Select a project",targetAgentLabel:"Target agent",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 group",deleteAgentsFirstHint:e=>`Delete the project's ${e} agent${e===1?"":"s"} first`,deleteProjectMenuItem:"Delete project…",noAgentsYet:"No agent groups 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",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",specApprovedToastTitle:"Spec approved; coding started",specApproveFailedTitle:"Failed to approve Spec",specRejectedToastTitle:"Spec rejected; Dev agent is revising",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}`,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.`,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",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",reviewButtonTitle:"Has the QA agent start a new review round right away",reviewTerminalTitle:"Finished tasks cannot start another PR review",reviewRecoveryTitle:"Recover PR delivery",reviewRecoveryBody:"The PR is visible, but its pane delivery proof is incomplete. Confirm its PR number when needed, delivered stage, and platform actor ID before starting QA.",reviewRecoveryPrNumberLabel:"PR number (required)",reviewRecoveryPrNumberPlaceholder:"For example, 601",reviewRecoveryStageLabel:"Delivered stage (required)",reviewRecoveryActorLabel:"Platform actor ID (required)",reviewRecoveryActorPlaceholder:"For GitHub, use the numeric user ID",reviewRecoverySubmit:"Recover and start review",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…",noAgentSlot:e=>`No ${e} agent`},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:{loadExternalImage:"Load external image",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"},reviewTurnLabel:"Review",responseTurnLabel:"Response",roleUser:"User",roleQa:"QA",roleDev:"Dev"},prReview:{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.",specReviewHeading:"Spec review",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}`}},Ws={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":"待确认",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} 的 Agent 组?`,deleteConfirmBody:"配对的两个 Agent 都会被移除,此操作不可撤销。",deletedWithPairTitle:e=>`已删除包含 Agent ${e} 的 Agent 组`,deletedWithPairBody:e=>`配对的 Agent ${e} 也被一并移除。`,deletedTitle:e=>`Agent ${e} 已删除`,agentPetMenuItemTitle:"配置 Agent Pet(在状态位置显示动画宠物)",callReview:"发起评审",callingReview:"发起中…",callReviewMenuItemTitle:e=>`让 QA agent 立即对任务 ${e} 跑一轮 review(需已有 PR)`,callReviewRecoveryTaskTitle:e=>`请打开任务 ${e},通过「发起评审」按需确认 PR 号,并确认交付阶段和平台 actor。`,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:"GitHub 可使用 HTTPS、SSH、scp 或 owner/repo;其他平台必须使用 HTTP(S) URL",mergeStrategyLabel:"合并策略",mergeHumanLabel:"人类合并(默认)",mergeAutoLabel:"QA Approve 后自动合并",specApprovalLabel:"Spec 审核",specApprovalHumanLabel:"人类审核(默认)",specApprovalAutoLabel:"QA Approve 后自动开始编码",gitCliToolLabel:"Git CLI 工具",gitCliToolPlaceholder:"如 forge",gitCliToolRequired:"非 GitHub 仓库必填",gitCliNotesLabel:"CLI 实例说明(可选)",createdToastTitle:e=>`项目 ${e} 已创建`},createAgent:{modalTitle:e=>`添加 Agent 组到 ${e}`,submitLabel:"添加 Agent 组",continueLabel:"继续配置 QA",submitting:"添加 Agent 组中…",idTakenGlobalError:"该 id 已被占用(全局唯一)",idPlaceholder:(e,n)=>`${e}-${n}`,roleLabel:"角色",devStepLabel:"Dev Agent(第 1/2 步)",qaStepLabel:"QA Agent(第 2/2 步)",pairedDevLabel:e=>`与 Dev Agent ${e} 配对`,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,s)=>`Agent 组 ${e} + ${n} 已添加到 ${s}`},createTask:{titleCreate:"新建任务",titleEdit:"编辑任务",selectProjectPlaceholder:"选择项目",targetAgentLabel:"目标 Agent",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 绑定",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",specApprovedToastTitle:"Spec 已通过,已发起编码",specApproveFailedTitle:"Spec 通过失败",specRejectedToastTitle:"Spec 已打回,Dev agent 开始修订",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}`,mergeReadyBannerTitle:"PR 就绪 · 等你确认",mergeReadyBannerBody:"Dev agent 已完成收尾自检,点「确认」交由 baxian 收尾。",specReadyBannerTitle:"Spec 需由人类审核",specReadyNotice:e=>`QA agent 已通过第 ${e} 轮 Spec,全文见下方评审记录。通过即开始编码;打回意见将交 Dev agent 修订后复审。`,specCommentsPlaceholder:"打回意见(打回时必填)",submitting:"提交中…",specApproveButton:"通过 Spec,开始编码",specRejectTitleEmpty:"先填写打回意见",specRejectTitleReady:e=>`意见将作为 findings 交 ${e} agent 修订`,specReject:"打回 Spec",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,无法发起评审",reviewButtonTitle:"让 QA agent 立即开始新一轮评审",reviewTerminalTitle:"已结束的任务不能再次发起 PR 评审",reviewRecoveryTitle:"恢复 PR 交付",reviewRecoveryBody:"PR 已可见,但 pane 交付凭据不完整。启动 QA 前,请按需确认 PR 号,并确认已交付阶段和平台 actor ID。",reviewRecoveryPrNumberLabel:"PR 号(必填)",reviewRecoveryPrNumberPlaceholder:"例如 601",reviewRecoveryStageLabel:"已交付阶段(必填)",reviewRecoveryActorLabel:"平台 actor ID(必填)",reviewRecoveryActorPlaceholder:"GitHub 请填写数字用户 ID",reviewRecoverySubmit:"恢复并开始评审",continueButtonTitle:"让 Dev agent 再修一轮,完成后自动转 QA review",completeButtonTitle:"合并 PR 并收尾(仅安全清理 baxian 自有本地任务分支 + 压缩上下文)",confirmButtonTitle:"确认完成;merge:auto 时由 baxian 执行合并",confirming:"确认中…",noAgentSlot:e=>`暂无 ${e} agent`},taskPanel:{ariaLabel:"任务面板",emptyInProgress:"暂无正在处理的任务",emptyPending:"暂无待处理的任务",collapse:"收起",view:"查看",loadMore:"加载更多",emptyDone:"暂无已处理的任务"},review:{loadExternalImage:"加载外部图片",loadFailed:e=>`加载评审记录失败:${e}`,loadingRecords:"加载评审记录…",notStarted:"评审尚未开始",sectionTitle:"评审记录",phaseLabel:{spec:"Spec 评审",code:"代码评审"},reviewTurnLabel:"评审",responseTurnLabel:"反馈",roleUser:"用户",roleQa:"QA",roleDev:"Dev"},prReview:{reasonNoPr:"该 task 还没有 PR,暂无代码评审记录。",reasonDriverUnavailable:"该项目当前无法解析 git 驱动,无法拉取 PR 评审记录。",specReviewHeading:"Spec 评审",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}`}},Qt="baxian.language",Je="en-US",Mn={"en-US":Fn,"zh-CN":Ws};function On(e){return e==="zh-CN"||e==="en-US"}function Hn(){try{const e=localStorage.getItem(Qt);return On(e)?e:Je}catch{return Je}}function _n(e){try{localStorage.setItem(Qt,e)}catch{}}let _e=Hn();const Ft=new Set;let mt=0,Qs=0,on=0;function Kt(e){e!==_e&&(_e=e,Ft.forEach(n=>n(e)))}function Mt(e){mt+=1;const n=e??Je;_n(n),Kt(n)}function Ks(e){const n=e??Je;_n(n),Kt(n)}function Vt(){return Mn[_e]}const Un=o.createContext({locale:Je,messages:Fn,saving:!1,setLocale:async()=>{throw new Error("setLocale requires I18nProvider")}});function Vs({children:e}){const[n,s]=o.useState(_e),[r,a]=o.useState(!1);o.useEffect(()=>{const l=d=>s(d);return Ft.add(l),s(_e),()=>{Ft.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!==Qt)return;const m=d.key===null?Hn():d.newValue;On(m)&&(mt+=1,Kt(m))};return window.addEventListener("storage",l),()=>window.removeEventListener("storage",l)},[]);const i=async l=>{if(l!==_e){a(!0);try{await E.config.patch({language:l}),Mt(l)}finally{a(!1)}}};return t.jsx(Un.Provider,{value:{locale:n,messages:Mn[n],saving:r,setLocale:i},children:e})}function qn(){return o.useContext(Un)}function q(){return qn().messages}function Ys(){o.useEffect(()=>{const e=()=>{const s=mt,r=++Qs;E.config.get().then(a=>{s===mt&&(r<=on||(on=r,Ks(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 Gn=o.createContext(null),Js={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"},Xs={success:qs,warn:Gs,error:zs};let Zs=1;function er({children:e}){const n=q(),[s,r]=o.useState([]),a=o.useRef(new Map),i=o.useRef(new Map);o.useEffect(()=>{const u=a.current,c=i.current;return()=>{for(const b of u.values())clearTimeout(b);u.clear(),c.clear()}},[]);const l=o.useCallback(u=>{const c=a.current.get(u);c&&clearTimeout(c),a.current.delete(u)},[]),d=o.useCallback(u=>{l(u),i.current.delete(u),r(c=>c.filter(b=>b.id!==u))},[l]),m=o.useCallback((u,c)=>{l(u),a.current.set(u,setTimeout(()=>d(u),c))},[l,d]),g=o.useCallback((u,c)=>{const b=i.current.get(u)??new Set;b.add(c),i.current.set(u,b),l(u)},[l]),h=o.useCallback((u,c,b)=>{const w=i.current.get(u);w==null||w.delete(c),(!w||w.size===0)&&m(u,b)},[m]),p=o.useCallback(u=>{const c=Zs++,b=u.durationMs??3e3;r(w=>[...w,{...u,id:c,durationMs:b}]),m(c,b)},[m]);return t.jsxs(Gn.Provider,{value:{show:p},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(u=>t.jsx("div",{className:`pointer-events-auto w-full max-w-xs rounded-lg border px-4 py-3 shadow-toast ${Js[u.kind]}`,role:"status",onMouseEnter:()=>g(u.id,"hover"),onMouseLeave:()=>h(u.id,"hover",u.durationMs),onFocus:()=>g(u.id,"focus"),onBlur:c=>{c.currentTarget.contains(c.relatedTarget)||h(u.id,"focus",u.durationMs)},children:t.jsxs("div",{className:"flex items-start gap-2",children:[(()=>{const c=Xs[u.kind];return t.jsx(c,{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:u.title}),u.body&&t.jsx("div",{className:"mt-1 whitespace-pre-line text-xs text-og-700",children:u.body})]}),t.jsx("button",{type:"button",onClick:()=>d(u.id),className:"text-current opacity-50 transition-opacity hover:opacity-100","aria-label":n.toast.dismissAriaLabel,children:"✕"})]})},u.id))})]})}function Te(){const e=o.useContext(Gn);if(!e)throw new Error("useToast must be inside <ToastProvider>");return e}const tr={sm:"max-w-md",md:"max-w-lg",lg:"max-w-2xl"},ln='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 m=q(),g=o.useRef(null),h=o.useRef();h.current||(h.current=Symbol("modal"));const p=o.useRef(null),u=o.useRef(!1),c=o.useRef(n);return o.useEffect(()=>{c.current=n},[n]),o.useEffect(()=>{if(!e)return;const b=h.current;$e.push(b);const w=()=>$e[$e.length-1]===b;p.current=document.activeElement;const v=j=>{if(!w())return;if(j.key==="Escape"){c.current();return}if(j.key!=="Tab")return;const y=g.current;if(!y)return;const x=Array.from(y.querySelectorAll(ln)).filter($=>$.offsetParent!==null||$===document.activeElement);if(x.length===0){j.preventDefault();return}const R=x[0],T=x[x.length-1],D=document.activeElement;j.shiftKey&&(D===R||!y.contains(D))?(j.preventDefault(),T.focus()):!j.shiftKey&&(D===T||!y.contains(D))&&(j.preventDefault(),R.focus())};document.addEventListener("keydown",v);const A=document.body.style.overflow;document.body.style.overflow="hidden";const S=g.current;if(S){const j=S.querySelector(ln);j==null||j.focus()}return()=>{var y,x;const j=$e.indexOf(b);j>=0&&$e.splice(j,1),document.removeEventListener("keydown",v),document.body.style.overflow=A,(x=(y=p.current)==null?void 0:y.focus)==null||x.call(y)}},[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?b=>{u.current=b.target===b.currentTarget&&$e[$e.length-1]===h.current}:void 0,onClick:d?b=>{b.target===b.currentTarget&&u.current&&c.current()}:void 0,role:"presentation",children:t.jsxs("div",{ref:g,className:`flex w-full ${tr[l]} max-h-[90dvh] flex-col overflow-hidden rounded-lg border border-og-100 bg-surface shadow-modal`,onClick:b=>b.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:()=>c.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":m.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 zn=o.createContext(null);function nr({children:e}){const n=q(),[s,r]=o.useState(null),a=o.useRef(null),i=o.useCallback(d=>new Promise(m=>{var h;(h=a.current)==null||h.resolve(!1);const g={...d,resolve:m};a.current=g,r(g)}),[]),l=o.useCallback(d=>{const m=a.current;m&&(a.current=null,r(null),m.resolve(d))},[]);return t.jsxs(zn.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 Yt(){const e=o.useContext(zn);if(!e)throw new Error("useConfirm must be inside <ConfirmProvider>");return e}const ht="baxian.pendingRestart",sr=500,rr=3e4,Wn=o.createContext(null);function ar(){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 ir(e){try{e.count<=0?localStorage.removeItem(ht):localStorage.setItem(ht,JSON.stringify(e))}catch{}}function or({children:e}){const n=q(),s=ar(),[r,a]=o.useState(s.count),[i,l]=o.useState(s.baselineStartedAt),[d,m]=o.useState(s.count>0?"pending":"idle"),[g,h]=o.useState(),p=o.useRef(s.count),u=o.useRef(s.count>0?"pending":"idle"),c=o.useRef(0),b=o.useCallback(y=>{p.current=y,a(y)},[]),w=o.useCallback(y=>{a(x=>{const R=y(x);return p.current=R,R})},[]),v=o.useCallback(y=>{u.current=y,m(y)},[]);o.useEffect(()=>{ir({count:r,baselineStartedAt:i})},[r,i]),o.useEffect(()=>{let y=!1;(async()=>{try{const R=await E.health.get();if(y)return;l(T=>T!==null&&R.startedAt!==T?(b(0),v("idle"),null):T)}catch{}})();const x=R=>{if(R.key===ht){if(R.newValue===null){if(u.current==="restarting"&&c.current>0){b(c.current),l(null);return}b(0),l(null),u.current!=="restarting"&&v("idle");return}try{const T=JSON.parse(R.newValue);typeof T.count=="number"&&(u.current==="restarting"&&T.count>p.current&&(c.current+=T.count-p.current),b(T.count),u.current!=="restarting"&&v(T.count>0?"pending":"idle")),typeof T.baselineStartedAt=="string"?l(T.baselineStartedAt):T.baselineStartedAt===null&&l(null)}catch{}}};return window.addEventListener("storage",x),()=>{y=!0,window.removeEventListener("storage",x)}},[b,v]);const A=o.useRef(!1),S=o.useCallback(()=>{w(y=>y+1),u.current==="restarting"?c.current+=1:v("pending"),l(y=>(y!==null||A.current||(A.current=!0,(async()=>{try{const x=await E.health.get();l(R=>R??x.startedAt)}catch{}finally{A.current=!1}})()),y))},[v,w]),j=o.useCallback(async()=>{c.current=0,h(void 0),v("restarting");let y;try{y=(await E.health.get()).startedAt}catch(R){v("failed"),h(n.banner.preRestartFetchFailed(R instanceof Error?R.message:String(R)));return}try{await E.server.restart()}catch(R){if(!(R instanceof Ue&&R.status===409)){v("failed"),h(n.banner.restartTriggerFailed(R instanceof Error?R.message:String(R)));return}}const x=Date.now();for(;Date.now()-x<rr;){await new Promise(R=>setTimeout(R,sr));try{const R=await E.health.get();if(R.startedAt!==y){const T=c.current;c.current=0,l(T>0?R.startedAt:null),b(T),v(T>0?"pending":"idle");return}}catch{}}v("failed"),h(n.banner.restartTimeout)},[b,v,n]);return t.jsx(Wn.Provider,{value:{phase:d,count:r,error:g,flagDirty:S,triggerRestart:j},children:e})}function vt(){const e=o.useContext(Wn);if(!e)throw new Error("usePendingRestart must be used inside PendingRestartProvider");return e}const lr=[500,1e3,2e3,4e3,8e3,15e3,3e4];class Qn{constructor(n){oe(this,"attempts",0);oe(this,"timer",null);oe(this,"delaysMs");this.opts=n,this.delaysMs=n.delaysMs??lr}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 Kn(e){return Array.from(new TextEncoder().encode(e)).map(n=>n.toString(16).padStart(2,"0")).join("")}function Vn(e){return`${location.protocol==="https:"?"wss":"ws"}://${location.host}${e}`}const Yn=(e,n)=>n&&n.length>0?new WebSocket(e,n):new WebSocket(e);let cn=0;function cr(){cn++;const e=Math.random().toString(36).slice(2,8);return`sub-${Date.now().toString(36)}-${cn}-${e}`}function dr(){return Vn("/api/stream")}class ur{constructor(n={}){oe(this,"wsUrl");oe(this,"wsFactory");oe(this,"tokenProvider");oe(this,"ws",null);oe(this,"subs",new Map);oe(this,"snapshotPending",new Set);oe(this,"preSubscribeQueue",new Map);oe(this,"outbox",[]);oe(this,"reconnectScheduler");oe(this,"explicitlyClosed",!1);this.wsUrl=n.wsUrl??dr(),this.wsFactory=n.wsFactory??Yn,this.tokenProvider=n.tokenProvider??zt,this.reconnectScheduler=new Qn({reconnect:()=>this.openSocket(),shouldReconnect:()=>!this.explicitlyClosed&&this.subs.size>0})}subscribe(n){const s=cr(),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.${Kn(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 kt=null;function St(){return kt||(kt=new ur),kt}function mr(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 m=St().subscribe({agentId:n,mode:s,onSnapshot:g=>a.current.onSnapshot(g),onData:g=>a.current.onData(g),onError:g=>{var h,p;return(p=(h=a.current).onError)==null?void 0:p.call(h,g)},onSessionGone:()=>{var g,h;return(h=(g=a.current).onSessionGone)==null?void 0:h.call(g)}});return r.current=m.subscriberId,()=>{r.current=null,m.unsubscribe()}},[n,s]);const i=o.useCallback(d=>{const m=r.current;m&&St().send(m,d)},[]),l=o.useCallback((d,m)=>{const g=r.current;g&&St().resize(g,d,m)},[]);return{send:i,resize:l}}const hr=[{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"}],rt=Object.fromEntries(hr.map(e=>[e.key,e]));function at({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 pr({onKey:e,onEscape:n,className:s}){const r=q();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(at,{arrow:rt.left,ariaLabel:r.terminal.arrowAriaLabel(r.terminal.arrowLabel.left),onPress:e}),t.jsx(at,{arrow:rt.up,ariaLabel:r.terminal.arrowAriaLabel(r.terminal.arrowLabel.up),onPress:e}),t.jsx(at,{arrow:rt.down,ariaLabel:r.terminal.arrowAriaLabel(r.terminal.arrowLabel.down),onPress:e}),t.jsx(at,{arrow:rt.right,ariaLabel:r.terminal.arrowAriaLabel(r.terminal.arrowLabel.right),onPress:e})]})}const fr=Math.floor(bt/1024/1024);function gr({agentId:e,className:n}){const s=q(),r=o.useRef(null),[a,i]=o.useState(!1),{show:l}=Te(),d=async m=>{var h;const g=(h=m.target.files)==null?void 0:h[0];if(m.target.value="",!!g){if(g.size>bt){l({kind:"error",title:s.createTask.imageTooLargeToastTitle,body:s.imageUpload.tooLargeBody(fr)});return}i(!0);try{await E.agents.uploadImage(e,g),l({kind:"success",title:s.imageUpload.insertedTitle,body:s.imageUpload.insertedBody})}catch(p){const u=p instanceof Ue||p instanceof Error?p.message:String(p);l({kind:"error",title:s.imageUpload.uploadFailedTitle,body:u})}finally{i(!1)}}};return t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button","aria-label":s.imageUpload.uploadAriaLabel,disabled:a,onMouseDown:m=>m.preventDefault(),onClick:()=>{var m;return(m=r.current)==null?void 0:m.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 xr={up:"A",down:"B",right:"C",left:"D"};function br(e,n){return(n?"\x1BO":"\x1B[")+xr[e]}const dn=18,vr=250,yr=256*1024,un="#fdfdfd",wr='ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',jr={background:un,foreground:"#474c55",cursor:"#1348dc",cursorAccent:un,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"},kr=/\x1b\[(?:\?[\d;]*c|>[\d;]*c|\??\d+;\d+R|\d+n)/g;function Sr(e){return e.replace(kr,"")}const Tr=1024*1024;function Nr(e){const n=e.indexOf(";");if(n===-1)return null;const s=e.slice(n+1);if(s.length===0||s==="?"||s.length>Tr)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 Ke({agentId:e,mode:n,interactive:s=!1,maxLines:r,className:a,autoFocus:i=!0,deferFullUntilFocus:l=!1,arrowKeys:d=!1}){const m=q(),g=o.useRef(null),h=o.useRef(null),p=o.useRef(null),u=o.useRef(null),c=o.useRef(!1),b=o.useRef(""),w=o.useRef([]),v=o.useRef(0),A=o.useRef(null),S=o.useRef(null),j=o.useRef(null),y=o.useRef(Promise.resolve()),x=o.useRef(0),[R,T]=o.useState(null),[D,$]=o.useState(!1),Q=`${e}\0${n}\0${l?"1":"0"}`,[z,te]=o.useState({key:Q,active:!1}),G=z.key===Q&&z.active,K=n==="full"&&l,I=K&&!G?"preview":n,_=s&&I==="full",J=(N,M)=>M.length===0?Promise.resolve():new Promise(F=>{try{N.write(M,()=>F())}catch(ae){console.warn("[pane-terminal] write failed:",ae),F()}}),V=I==="preview",de=()=>{if(!V)return;const N=g.current,M=h.current;if(!N||!M||N.clientHeight<=0)return;const ae=(M.buffer.active.cursorY+1)*dn;N.scrollTop=Math.max(0,ae-N.clientHeight)},Z=()=>{if(!V||j.current!==null)return;let N=!1;const M=requestAnimationFrame(()=>{N=!0,j.current=null,de()});N||(j.current=M)},X=(N,M)=>{y.current=y.current.then(async()=>{const F=h.current;if(!(!F||M!==x.current))try{await N(F),_&&F.scrollToBottom(),Z()}catch(ae){console.warn("[pane-terminal] terminal task failed:",ae)}}).catch(F=>{console.warn("[pane-terminal] write chain failed:",F)})},me=(N,M)=>{X(F=>J(F,N),M)},be=()=>{A.current!==null&&(cancelAnimationFrame(A.current),A.current=null),S.current!==null&&(clearTimeout(S.current),S.current=null)},k=()=>{be(),w.current=[],v.current=0},ue=()=>{be();const N=w.current;N.length!==0&&(w.current=[],v.current=0,me(N.join(""),x.current))},ee=N=>{if(N.length!==0){if(w.current.push(N),v.current+=N.length,v.current>=yr){ue();return}A.current===null&&(A.current=requestAnimationFrame(ue)),S.current===null&&(S.current=setTimeout(ue,vr))}},{send:pe,resize:se}=mr({agentId:e,mode:I,onSnapshot:({cols:N,rows:M,data:F})=>{if(h.current)try{const fe=x.current+1;x.current=fe,k(),X(async O=>{var C;O.reset(),_?((C=u.current)==null||C.call(u),await J(O,F)):(N>0&&M>0&&O.resize(N,M),await J(O,F))},fe)}catch(fe){console.warn("[pane-terminal] snapshot write failed:",fe)}},onData:N=>{ee(N)},onError:N=>T(`${N.code}: ${N.message}`),onSessionGone:()=>$(!0)});o.useEffect(()=>{T(null),$(!1)},[e,I]),o.useEffect(()=>{b.current=""},[Q]),o.useEffect(()=>{if(I!=="full")return;const N=b.current;N.length!==0&&(b.current="",pe(N))},[pe,I]);const ye=o.useCallback(()=>{!s||!K||G||(c.current=!0,te({key:Q,active:!0}))},[Q,G,s,K]),ve=o.useCallback(N=>{const M=Sr(N);if(M.length!==0){if(K&&(!G||b.current.length>0)){b.current+=M,ye();return}pe(M)}},[ye,G,pe,K]);o.useEffect(()=>{const N=g.current;if(!N)return;let M=!1;const F=new Ls.Terminal({cursorBlink:s,disableStdin:!s,theme:jr,fontFamily:wr,fontSize:13,lineHeight:1.4,scrollback:I==="full"?5e3:1e3}),ae=new Es.FitAddon;F.loadAddon(ae),F.open(N),h.current=F,p.current=ae;const fe=V?F.onRender(()=>Z()):null;if(s&&(i||c.current)){c.current=!1;try{F.focus()}catch{}}s&&(F.onData(ve),I==="full"&&F.parser.registerOscHandler(52,B=>{var je;const he=Nr(B);return he!==null&&((je=navigator.clipboard)==null||je.writeText(he).catch(()=>{})),!0}));const O=()=>N.clientWidth>0&&N.clientHeight>0,C=(B=!1)=>{if(!O())return!1;const he=F.cols,je=F.rows;try{ae.fit()}catch{return!1}return _&&F.scrollToBottom(),F.cols>0&&F.rows>0&&(B||F.cols!==he||F.rows!==je)&&se(F.cols,F.rows),!0};u.current=_?()=>C(!0):null;let L=null,ne=null,Y=null,ie=0;const f=()=>{L||(L=new ResizeObserver(()=>{ne&&clearTimeout(ne),ne=setTimeout(()=>{ne=null,_?C():V&&Z()},100)}),L.observe(N))},H=()=>{Y=requestAnimationFrame(()=>{if(Y=null,!M){if(!_){V&&(f(),Z());return}if(C(!0)){f();return}if(ie++<5){H();return}f()}})};return H(),()=>{M=!0,Y!==null&&cancelAnimationFrame(Y),A.current!==null&&(cancelAnimationFrame(A.current),A.current=null),S.current!==null&&(clearTimeout(S.current),S.current=null),j.current!==null&&(cancelAnimationFrame(j.current),j.current=null),x.current++,w.current=[],v.current=0,y.current=Promise.resolve(),ne&&clearTimeout(ne),L==null||L.disconnect(),fe==null||fe.dispose(),h.current=null,p.current=null,u.current=null;try{F.dispose()}catch(B){console.warn("[pane-terminal] dispose failed:",B)}}},[e,i,_,ve,s,I,se]);const we=()=>{var N;if(s){ye();try{(N=h.current)==null||N.focus()}catch{}}};o.useEffect(()=>{if(s)return;const N=g.current;if(!N)return;const M=F=>{F.stopPropagation()};return N.addEventListener("wheel",M,{capture:!0,passive:!0}),()=>N.removeEventListener("wheel",M,{capture:!0})},[s]);const P=r&&r>0?{maxHeight:`${r*dn}px`}:void 0;return t.jsxs("div",{className:a??"flex flex-col h-full w-full min-h-0 bg-term",children:[(R||D)&&t.jsx("div",{className:"border-b border-accent/25 bg-accent-soft px-3 py-1 font-mono text-xs text-accent",children:D?m.terminal.sessionEnded:R}),t.jsx("div",{className:"flex flex-1 min-h-0 px-2 py-1.5",style:P,children:t.jsx("div",{ref:g,className:"flex-1 min-h-0 overflow-hidden",onMouseDown:we})}),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(gr,{agentId:e})}),t.jsx(pr,{className:"flex items-center justify-center gap-1",onKey:N=>{var F,ae;const M=!!((ae=(F=h.current)==null?void 0:F.modes)!=null&&ae.applicationCursorKeysMode);ve(br(N,M))},onEscape:()=>ve("\x1B")})]})]})}function Rr(){const[e,n]=o.useState([]),[s,r]=o.useState(!0),[a,i]=o.useState(null),l=o.useCallback(async()=>{r(!0);try{n(await E.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 Tt=new Map,Nt=new Map;function Cr(e){const[n,s]=o.useState(()=>e?Nt.get(e)??null:null);return o.useEffect(()=>{if(!e){s(null);return}const r=Nt.get(e);if(s(r??null),r)return;let a=!1,i=Tt.get(e);return i||(i=E.pets.fetchSpritesheet(e).then(l=>{const d=URL.createObjectURL(l);return Nt.set(e,d),d}),Tt.set(e,i)),i.then(l=>{a||s(l)},()=>{a||s(null),Tt.delete(e)}),()=>{a=!0}},[e]),n}const Ar=[{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 Pr(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 Jt=36,Lr=Jt/Bn,Er=In*Lr;function Dr(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Jn({petId:e,status:n,bootstrapping:s=!1,label:r,displayHeight:a=Jt,className:i}){const l=Cr(e),d=Pr(n,s),m=Ar[d],g=m.durations.length,[h,p]=o.useState(0),u=a/Bn,c=In*u;return o.useEffect(()=>{if(p(0),!l||g<=1||Dr())return;let b,w=0;const v=()=>{w=(w+1)%g,p(w),b=setTimeout(v,m.durations[w])};return b=setTimeout(v,m.durations[0]),()=>clearTimeout(b)},[l,d,g,m]),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:`${c}px`,height:`${a}px`,backgroundImage:`url(${l})`,backgroundRepeat:"no-repeat",backgroundSize:`${Fs*u}px ${Ms*u}px`,backgroundPositionX:`${-(h*c)}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 it=e=>e.split("/").pop()??e;function $r(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 Ir(e){const n=Vt(),s=e.find(d=>it(d.name)==="pet.json"||it(d.webkitRelativePath||"")==="pet.json");if(!s)throw new dt(n.pet.missingManifest);let r;try{r=JSON.parse(await $r(s))}catch{throw new dt(n.pet.manifestParseFailed)}const a=r&&typeof r=="object"&&typeof r.spritesheetPath=="string"?r.spritesheetPath:"",i=a?it(a):"",l=(i?e.find(d=>it(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 Br({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(m=>m.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 Fr({agentId:e,currentPetId:n,onClose:s}){const r=q(),{show:a}=Te(),i=Yt(),{pets:l,loading:d,refresh:m}=Rr(),[g,h]=o.useState(!!n),[p,u]=o.useState(n),[c,b]=o.useState(!1),w=o.useRef(null);o.useEffect(()=>{u(n)},[n]),o.useEffect(()=>{const x=w.current;x&&(x.setAttribute("webkitdirectory",""),x.setAttribute("directory",""))},[g]);const v=x=>x instanceof Ue||x instanceof Error?x.message:String(x),A=async x=>{if(h(x),!x&&p){b(!0);try{await E.agents.setPet(e,null),u(null),a({kind:"success",title:r.pet.disabledTitle})}catch(R){a({kind:"error",title:r.pet.disableFailedTitle,body:v(R)}),h(!0)}finally{b(!1)}}},S=async x=>{b(!0);try{await E.agents.setPet(e,x),u(x),a({kind:"success",title:r.pet.selectedTitle})}catch(R){a({kind:"error",title:r.pet.selectFailedTitle,body:v(R)})}finally{b(!1)}},j=async(x,R)=>{if(await i({title:r.pet.deleteConfirmTitle(R),body:r.pet.deleteConfirmBody,confirmLabel:r.common.delete})){b(!0);try{await E.pets.remove(x),await m(),a({kind:"success",title:r.pet.deletedTitle(R)})}catch(T){a({kind:"error",title:r.pet.deleteFailedTitle,body:v(T)})}finally{b(!1)}}},y=async x=>{const R=x.target.files?Array.from(x.target.files):[];if(x.target.value="",!!R.length){b(!0);try{const{manifest:T,spritesheet:D}=await Ir(R);await E.pets.create(T,D),await m(),a({kind:"success",title:r.pet.uploadedTitle})}catch(T){const D=T instanceof dt?T.message:v(T);a({kind:"error",title:r.pet.uploadFailedTitle,body:D})}finally{b(!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:g,disabled:c,onChange:x=>void A(x.target.checked)}),r.pet.enableLabel]}),g?t.jsxs(t.Fragment,{children:[t.jsxs("div",{children:[t.jsx("button",{type:"button",onClick:()=>{var x;return(x=w.current)==null?void 0:x.click()},disabled:c,className:"btn-secondary",children:r.pet.uploadButton}),t.jsx("input",{ref:w,type:"file","aria-label":r.pet.uploadInputAriaLabel,className:"hidden",onChange:x=>void y(x)}),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(x=>{const R=x.id===p;return t.jsxs("li",{className:`flex items-center gap-2 rounded-md border p-2 ${R?"border-accent bg-accent-soft/40":"border-hairline"}`,children:[t.jsx(Br,{style:{width:`${Er}px`,height:`${Jt}px`},children:t.jsx(Jn,{petId:x.id,status:"idle",label:x.displayName})}),t.jsxs("button",{type:"button",onClick:()=>void S(x.id),disabled:c||R,title:x.description||x.displayName,className:"min-w-0 flex-1 truncate text-left text-sm text-og-1000 hover:text-accent-hover disabled:cursor-default",children:[x.displayName,R&&t.jsx("span",{className:"ml-1 text-xs text-accent",children:r.pet.currentMarker})]}),t.jsx("button",{type:"button","aria-label":r.pet.deleteAriaLabel(x.displayName),onClick:()=>void j(x.id,x.displayName),disabled:c,className:"shrink-0 text-xs text-accent hover:underline disabled:opacity-50",children:r.common.delete})]},x.id)})})]}):t.jsx("p",{className:"text-xs text-og-500",children:r.pet.enableHint})]})})}const Rt={unknown:"pill pill-idle",idle:"pill pill-idle",pending:"pill pill-warn",working:"pill pill-live",waiting:"pill pill-review",error:"pill pill-warn"},Mr=72;function Xn(e){var n;return!!((n=e.binding)!=null&&n.creationToken)&&!e.binding.paneId&&e.binding.status!=="awaiting_human"&&e.reason!=="PENDING_HUMAN"}function Or(e,n){var s,r,a;return e.tmuxSessionStatus==="unreachable"?{kind:"alert",label:n.sessionStatus.unreachable,cls:"pill pill-danger"}:Xn(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:Rt.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:Rt.pending}:{kind:"runtime",label:n.runtimeStatus[e.runtimeStatus],cls:Rt[e.runtimeStatus]}}function Hr(e,n){const s=Or(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 Zn({agent:e,projectId:n,role:s,runtime:r,model:a,onDeleted:i,pendingRestart:l=!1,terminalLoading:d=!1,showTaskBinding:m=!0,terminalMode:g="activity-preview",active:h,onActivate:p,task:u}){var Ne,ke,Le,tt,nt,sn,rn;const c=q(),[b,w]=o.useState(!1),[v,A]=o.useState(null),{show:S}=Te(),j=Yt(),{flagDirty:y}=vt(),[x,R]=o.useState(!1),[T,D]=o.useState(null),[$,Q]=o.useState(!1),[z,te]=o.useState(!1),[G,K]=o.useState(!1),[I,_]=o.useState(!1),[J,V]=o.useState(!1),[de,Z]=o.useState(!1),X=(Ne=e.binding)==null?void 0:Ne.taskId,me=u!==void 0&&u.id===X&&It(u),be=((ke=e.binding)==null?void 0:ke.status)==="awaiting_human",k=(tt=(Le=e.binding)==null?void 0:Le.needInput)==null?void 0:tt.at,ue=be&&((nt=e.binding)==null?void 0:nt.awaitingPhase)==="greeting_failed",ee=Xn(e),pe=ee&&e.tmuxSessionStatus!=="present",se=Hr(e,c.agents),ye=ee?c.agents.bootstrappingBadge:c.agents.runtimeStatus[e.runtimeStatus],ve=g==="activity-preview"&&!pe&&(e.runtimeStatus==="working"||e.runtimeStatus==="pending"),we=g==="embedded-full",P=we&&typeof p=="function",N=P&&h===!0,M=d||l||pe,F=d?c.agents.agentStatusLoading:l?c.agents.terminalNeedsRestart:c.agents.bootstrappingTerminalDisabled,ae=Pn(r,a),fe=async()=>{w(!0),A(null);try{await E.agents.stop(e.id)}catch(U){A(U instanceof Error?U.message:String(U))}finally{w(!1)}},O=async()=>{if(!(!X||!await j({title:c.agents.confirmReReviewTitle,body:c.agents.confirmReReviewBody(X),confirmLabel:c.agents.confirmReReviewLabel}))){K(!0);try{const xe=await E.tasks.review(X),Ge=xe.phase==="spec"?xe.specReviewRound??0:xe.reviewRound;S({kind:"success",title:c.agents.reReviewStarted(Ge)})}catch(xe){S({kind:"error",title:c.agents.reReviewStartFailed,body:xe instanceof Error?xe.message:String(xe)})}finally{K(!1)}}},C=async()=>{V(!0);try{(await E.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(U){S({kind:"error",title:c.agents.retryBootstrapFailedTitle,body:U instanceof Error?U.message:String(U)})}finally{V(!1)}},L=async()=>{if(await j({title:c.agents.resumeConfirmTitle(e.id),body:ue?c.agents.resumeGreetingBody:c.agents.resumeDefaultBody,confirmLabel:c.agents.resume})){_(!0);try{if(ue){e.tmuxSessionStatus==="present"?await E.projects.restartRepl(n,e.id):await E.projects.retryAgent(n,e.id),S({kind:"success",title:c.agents.regreetingStartedTitle(e.id),body:c.agents.regreetingStartedBody});return}const xe=await E.projects.resumeAgent(n,e.id);S({kind:"success",title:c.agents.resumedTitle(e.id),body:xe.releasedBinding?c.agents.resumedReleasedBody:c.agents.resumedKeptBody})}catch(xe){S({kind:"error",title:c.agents.resumeFailedTitle,body:xe instanceof Error?xe.message:String(xe)})}finally{_(!1)}}},ne=async()=>{Q(!0);try{await E.agents.compact(e.id),S({kind:"success",title:c.agents.compactSentTitle(e.id)})}catch(U){S({kind:"error",title:c.agents.compactFailedTitle,body:U instanceof Error?U.message:String(U)})}finally{Q(!1)}},Y=async()=>{if(await j({title:c.agents.clearConfirmTitle(e.id),body:c.agents.clearConfirmBody,confirmLabel:c.agents.clearConfirmLabel})){te(!0);try{await E.agents.clear(e.id),S({kind:"success",title:c.agents.clearSentTitle(e.id)})}catch(U){S({kind:"error",title:c.agents.clearFailedTitle,body:U instanceof Error?U.message:String(U)})}finally{te(!1)}}},ie=async()=>{if(await j({title:c.agents.deleteConfirmTitle(e.id),body:c.agents.deleteConfirmBody,confirmLabel:c.common.delete})){R(!0),D(null);try{const U=await E.projects.deleteAgent(n,e.id);U!=null&&U.restartRequired&&y();const xe=(U==null?void 0:U.removed)??[e.id],Ge=[...(U==null?void 0:U.warnings)??[]];if(xe.length>1){const Ts=xe.filter(Ns=>Ns!==e.id).join(", ");Ge.unshift(c.agents.deletedWithPairBody(Ts))}Ge.length>0?S({kind:"warn",title:xe.length>1?c.agents.deletedWithPairTitle(e.id):c.agents.deletedTitle(e.id),body:Ge.join(`
8
- `)}):S({kind:"success",title:c.agents.deletedTitle(e.id)}),i==null||i()}catch(U){D(U instanceof Error?U.message:String(U))}finally{R(!1)}}},f=P&&!M&&!N,H=["card relative flex h-full min-w-0 flex-col overflow-visible p-4",N?"ring-2 ring-accent":""].filter(Boolean).join(" "),B=["mb-3 flex items-start justify-between gap-2",e.petId?"pr-28":""].filter(Boolean).join(" "),he=["mb-2 mt-3 h-80 min-h-0 overflow-hidden border border-hairline bg-surface",f?"cursor-pointer":""].filter(Boolean).join(" "),je=f?()=>p==null?void 0:p():void 0,ge=f?U=>{(U.key==="Enter"||U.key===" ")&&(U.preventDefault(),p==null||p())}:void 0;return t.jsxs("div",{className:H,"data-agent-card":P?e.id:void 0,children:[e.petId&&t.jsx("div",{className:"absolute -top-4 right-7 z-10",children:t.jsx(Jn,{petId:e.petId,status:e.runtimeStatus,bootstrapping:ee,label:ye,displayHeight:Mr})}),t.jsxs("div",{className:B,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":"Dev"}),t.jsx("span",{className:"min-w-0 truncate whitespace-nowrap font-display text-sm font-semibold text-og-1000",title:Ln(e.id,r,a),children:e.id}),ae&&t.jsxs("span",{className:"hidden shrink-0 whitespace-nowrap text-xs text-og-400 sm:inline",title:ae,children:["(",ae,")"]})]}),(!e.petId||se.kind==="alert"||se.stale)&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:se.stale?`${se.cls} pill--stale shrink-0`:`${se.cls} shrink-0`,title:se.title,children:se.label}),se.stale&&t.jsx("span",{className:"sr-only",children:se.title})]})]}),pe&&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}),be&&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:(sn=e.binding)==null?void 0:sn.awaitingPhase}),((rn=e.binding)==null?void 0:rn.awaitingReason)&&t.jsxs("span",{children:[" · ",e.binding.awaitingReason]})]}),!ee&&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(He,{to:`/terminal/${e.id}`,className:"text-accent hover:text-accent-hover underline",children:c.agents.terminal}),c.agents.openTerminalSuffix]})]}),k&&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(He,{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:C,disabled:J,className:"btn-primary shrink-0",children:J?c.common.retrying:c.agents.retryBootstrap})]})]}),m&&X&&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:X})]}),ve&&t.jsx("div",{className:"mb-2 overflow-hidden border border-hairline bg-surface",children:t.jsx(Ke,{agentId:e.id,mode:"preview",maxLines:6,interactive:!1})}),we&&t.jsx("div",{className:he,role:f?"button":void 0,tabIndex:f?0:void 0,"aria-label":f?c.agents.activateTerminal(e.id):void 0,onClick:je,onKeyDown:ge,children:M?t.jsx("div",{className:"flex h-full items-center justify-center px-3 text-sm text-og-500",children:F}):P?N?t.jsx(Ke,{agentId:e.id,mode:"full",interactive:!0,autoFocus:!0}):t.jsx(Ke,{agentId:e.id,mode:"preview",interactive:!1}):t.jsx(Ke,{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:[M?t.jsx("span",{className:"shrink-0 cursor-not-allowed text-sm text-og-400",title:F,children:c.agents.terminal}):t.jsx(He,{to:`/terminal/${e.id}`,className:"btn-secondary shrink-0",children:c.agents.terminal}),!l&&e.runtimeStatus==="working"&&t.jsx("button",{onClick:fe,disabled:b,className:"btn-ghost shrink-0",children:b?c.agents.stopping:c.agents.stop}),be&&t.jsx("button",{type:"button",onClick:L,disabled:I,title:ue?c.agents.resumeGreetingButtonTitle:c.agents.resumeDefaultButtonTitle,className:"btn-primary shrink-0",children:I?c.agents.resuming:c.agents.resume})]}),t.jsx(qt,{ariaLabel:c.agents.actionsMenu(e.id),className:"shrink-0",placement:"up",autoFocusFirstItem:!0,disabled:x,children:U=>t.jsxs(t.Fragment,{children:[t.jsx(Se,{onClick:()=>{U(),Z(!0)},disabled:$||z||x,title:c.agents.agentPetMenuItemTitle,children:"Agent Pet"}),t.jsx(Se,{onClick:()=>{U(),ne()},disabled:$||z||x,title:c.agents.compactMenuItemTitle,children:$?c.agents.compacting:c.agents.compact}),t.jsx(Se,{onClick:()=>{U(),Y()},disabled:z||$||x,title:c.agents.clearMenuItemTitle,children:z?c.agents.clearing:c.agents.clear}),!l&&X&&s==="dev"&&t.jsx(Se,{onClick:()=>{U(),O()},disabled:G||x||me,title:me?c.agents.callReviewRecoveryTaskTitle(X):c.agents.callReviewMenuItemTitle(X),children:G?c.agents.callingReview:c.agents.callReview}),t.jsx(Se,{onClick:()=>{U(),ie()},disabled:x||$||z,children:x?c.common.deleting:c.common.delete})]})})]}),v&&t.jsx("div",{className:"mt-1.5 break-words text-xs text-accent",children:v}),T&&t.jsx("div",{className:"mt-1.5 break-words text-xs text-accent",children:T}),de&&t.jsx(Fr,{agentId:e.id,currentPetId:e.petId??null,onClose:()=>Z(!1)})]})}const Ct="baxian:terminal-activated";function es({coordinateAcrossInstances:e=!0}={}){const n=o.useId(),[s,r]=o.useState(null);o.useEffect(()=>{if(s===null)return;const i=m=>{m.composedPath().some(p=>p instanceof Element&&p.hasAttribute("data-agent-card"))||r(null)},l=m=>{if(m.key!=="Escape")return;const g=document.activeElement;g instanceof Element&&g.closest("[data-agent-card]")||r(null)},d=m=>{const g=m.detail;(g==null?void 0:g.ownerId)!==n&&r(null)};return document.addEventListener("click",i),document.addEventListener("keydown",l),e&&document.addEventListener(Ct,d),()=>{document.removeEventListener("click",i),document.removeEventListener("keydown",l),e&&document.removeEventListener(Ct,d)}},[s,e,n]);const a=o.useCallback(i=>{r(i),e&&document.dispatchEvent(new CustomEvent(Ct,{detail:{ownerId:n}}))},[e,n]);return{activeAgentId:s,activateAgentCard:a}}function _r(e){return Vt().status[e]??e}const ts={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",merged:"pill pill-live",done:"pill pill-live",failed:"pill pill-danger",max_rounds:"pill pill-warn",cancelled:"pill"},Ur={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",merged:"bg-success",done:"bg-success",failed:"bg-danger",max_rounds:"bg-warn",cancelled:"bg-og-300"};function qr({status:e}){return t.jsx("span",{role:"img","aria-label":e,title:e,className:`inline-block h-2 w-2 shrink-0 rounded-full ${Ur[e]??"bg-og-300"}`})}function Xt(e){if(!e)return"";const n=e.match(/^task-(\d+)$/);return n?n[1]:e}function At(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 ns({group:e,projectId:n,agentsById:s,agentsLoaded:r,agentsError:a=!1,tasks:i,onDeleted:l,terminalMode:d="activity-preview"}){const m=q(),g=e.find(y=>y.role==="dev")??e[0],h=i.filter(y=>Wr(y,g==null?void 0:g.id)),p=g?i.filter(y=>Qr(y,n,g.id)).sort((y,x)=>y.createdAt.localeCompare(x.createdAt)):[],u=`Agent group ${e.map(y=>y.id).join(" / ")}`,c=Pe(),b=d==="embedded-full",{activeAgentId:w,activateAgentCard:v}=es({coordinateAcrossInstances:b}),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",S=!!g&&p.length>0,j=h.length===0&&!S;return t.jsxs("div",{role:"group","aria-label":u,className:"min-w-0",children:[S&&g&&t.jsx(zr,{tasks:p,devId:g.id,agentsById:s,label:u}),h.length>0&&t.jsx("div",{className:"card mb-2 max-h-28 overflow-y-auto divide-y divide-hairline",children:h.map(y=>{const x=Ce(y.phase)?y.specReviewRound??0:y.reviewRound;return t.jsxs("button",{type:"button",onClick:()=>c(Fe(y.projectId,y.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:y.id,children:Xt(y.id)}),t.jsx("span",{className:"truncate text-og-1000",children:y.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:m.agents.round(x)}),t.jsx("span",{className:`${ts[y.status]} shrink-0`,title:y.status,children:m.status[y.status]??y.status})]})]},y.id)})}),j&&t.jsx("div",{className:"mb-2 rounded-lg border border-hairline bg-surface px-3 py-2 text-sm text-og-400","aria-label":m.agents.noActiveTaskAriaLabel(u),children:m.agents.noActiveTask}),t.jsx("div",{className:`grid grid-cols-1 ${A} gap-4`,children:e.map(y=>{var D;const x=s.get(y.id),R=x??{id:y.id,projectId:n,runtimeStatus:"unknown",tmuxSessionStatus:"unknown",stale:!0},T=((D=R.binding)==null?void 0:D.taskId)===void 0?void 0:i.find($=>{var Q;return $.id===((Q=R.binding)==null?void 0:Q.taskId)});return t.jsx(Zn,{agent:R,projectId:n,role:y.role,runtime:y.runtime,model:y.model,pendingRestart:r&&!x,terminalLoading:!r&&!x&&!a,onDeleted:l,showTaskBinding:!1,terminalMode:d,task:T,...b?{active:w===y.id,onActivate:()=>v(y.id)}:{}},y.id)})})]})}function Gr(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 zr({tasks:e,devId:n,agentsById:s,label:r}){const a=q(),{show:i}=Te(),l=Pe(),[d,m]=o.useState(null),g=async(h,p)=>{m(h);try{await E.tasks.dispatch(h,{agentId:p}),i({kind:"success",title:a.agents.taskHandedTo(h,p)})}catch(u){i({kind:"error",title:a.agents.startFailed,body:u instanceof Error?u.message:String(u)})}finally{m(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 p=h.preferredAgentId||n,u=Gr(s.get(p)),c=h.preferredAgentId==="",b=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:Xt(h.id)}),t.jsx("span",{className:"truncate text-og-1000",title:h.title,children:h.title}),c&&t.jsx("span",{className:"pill shrink-0",children:a.agents.unassigned})]}),t.jsx("button",{type:"button",onClick:()=>void g(h.id,p),disabled:!u||b,title:u?a.agents.handToAndStart(p):a.agents.agentUnavailable(p),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 Wr(e,n){return!n||!En.has(e.status)?!1:e.devAgentId===n}function Qr(e,n,s){return e.projectId!==n||e.status!=="pending"?!1:e.preferredAgentId===s||e.preferredAgentId===""}const le="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",Ye="mt-1 text-xs text-accent",Me="mt-1 text-xs text-og-500",Ee="h-3.5 w-3.5 accent-accent",Kr=/^[a-z][a-z0-9-]{1,31}$/,Vr=/^https?:\/\/[^/\s]+\/[^\s]+$/,ss=/^[^/\s:@]+\/[^/\s]+$/,Yr=[Vr,/^ssh:\/\/git@github\.com\/[^\s]+$/,/^git@github\.com:[^\s]+$/,ss];function rs(e){return ss.test(e.trim())}function Jr(e){const n=e.trim();return rs(n)||/^https?:\/\/github\.com\//.test(n)||/^ssh:\/\/git@github\.com\//.test(n)||/^git@github\.com:/.test(n)}function Xr({open:e,onClose:n,onCreated:s}){const r=q(),[a,i]=o.useState(""),[l,d]=o.useState(""),[m,g]=o.useState(null),[h,p]=o.useState("human"),[u,c]=o.useState(""),[b,w]=o.useState(""),[v,A]=o.useState(!1),[S,j]=o.useState(null),[y,x]=o.useState({}),[R,T]=o.useState(new Set),D=o.useRef(0),{show:$}=Te(),{flagDirty:Q}=vt();o.useEffect(()=>{if(!e)return;D.current+=1;const I=D.current;i(""),d(""),g(null),p("human"),c(""),w(""),j(null),x({}),T(new Set),E.config.get().then(_=>{I===D.current&&T(new Set(_.project.map(J=>J.id)))}).catch(_=>{I===D.current&&j(r.common.loadFailed(_ instanceof Error?_.message:String(_)))})},[e]);const z=()=>{v||n()},te=l.trim()!==""&&!rs(l),G=()=>{const I={},_=l.trim();a?Kr.test(a)?R.has(a)&&(I.id=r.createProject.idTakenError):I.id=r.common.idFormatError:I.id=r.createProject.required;const J=Yr.some(V=>V.test(_));return l?J||(I.repo=r.createProject.repoFormatError):I.repo=r.createProject.required,J&&!Jr(_)&&u.trim()===""&&(I.gitCliTool=r.createProject.gitCliToolRequired),x(I),Object.keys(I).length===0},K=async I=>{if(I.preventDefault(),!!G()){A(!0),j(null);try{const _=await E.projects.create({id:a,repo:l.trim(),merge:m,...h?{specApproval:h}:{},...te&&u.trim()?{gitCli:{tool:u.trim(),...b.trim()?{notes:b.trim()}:{}}}:{}});_.restartRequired&&Q(),$({kind:"success",title:r.createProject.createdToastTitle(_.project.id)}),s(_.project.id)}catch(_){j(_ instanceof Error?_.message:String(_))}finally{A(!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:v,className:"btn-secondary",children:r.common.cancel}),t.jsx("button",{type:"submit",form:"create-project-form",disabled:v,className:"btn-primary",children:v?r.common.creating:r.common.create})]}),children:t.jsxs("form",{id:"create-project-form",onSubmit:K,className:"space-y-3",children:[S&&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:S}),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:I=>i(I.target.value),className:le,placeholder:"baxian",disabled:v}),y.id&&t.jsx("div",{className:Ye,children:y.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:I=>d(I.target.value),className:le,placeholder:"https://github.com/baxian-ai/baxian.git",disabled:v}),y.repo&&t.jsx("div",{className:Ye,children:y.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:m===null,onChange:()=>g(null),disabled:v,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:m==="auto",onChange:()=>g("auto"),disabled:v,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:()=>p("human"),disabled:v,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:()=>p(null),disabled:v,className:"h-3.5 w-3.5 accent-accent"}),t.jsx("span",{className:"text-sm text-og-800",children:r.createProject.specApprovalAutoLabel})]})]}),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:u,onChange:I=>c(I.target.value),placeholder:r.createProject.gitCliToolPlaceholder,disabled:v,className:le}),y.gitCliTool&&t.jsx("div",{className:Ye,children:y.gitCliTool})]}),t.jsxs("label",{className:"block",children:[t.jsx("span",{className:re,children:r.createProject.gitCliNotesLabel}),t.jsx("input",{value:b,onChange:I=>w(I.target.value),disabled:v,className:le})]})]})]})})}const mn=/^[a-z][a-z0-9-]{1,31}$/,Zr=500,Pt={id:"",mode:"local",host:"",runtime:"",workdir:"",yolo:!0,model:"",addDirs:""};function ea(e){return e.alias?e.alias:`${e.user?`${e.user}@`:""}${e.hostname}${e.port!=null?`:${e.port}`:""}`}function as({open:e,onClose:n,projectId:s,onCreated:r}){var P,N,M,F,ae,fe;const a=q(),[i,l]=o.useState(Pt),[d,m]=o.useState(null),[g,h]=o.useState([]),[p,u]=o.useState(new Set),[c,b]=o.useState(null),[w,v]=o.useState(!1),[A,S]=o.useState(!1),[j,y]=o.useState(null),[x,R]=o.useState(!1),[T,D]=o.useState(null),[$,Q]=o.useState(!1),z=o.useRef(null),te=o.useRef(null),G=o.useRef(0),K=o.useRef(0),{show:I}=Te(),{flagDirty:_}=vt();o.useEffect(()=>{if(!e)return;K.current+=1;const O=K.current;l(Pt),m(null),h([]),u(new Set),b(null),v(!1),S(!1),y(null),G.current+=1,D(null),Q(!1),E.config.get().then(C=>{if(O!==K.current)return;h(C.host??[]);const L=new Set;C.project.forEach(ne=>ne.agent.forEach(Y=>Y.forEach(ie=>L.add(ie.id)))),u(L)}).catch(()=>{})},[e,s]);const J=()=>{x||n()},V=o.useCallback(()=>{z.current&&z.current.abort();const O=new AbortController;z.current=O,v(!0),D(null);const C=i.mode==="remote"?{hostId:i.host}:{};E.agents.probe(i.mode,C,{signal:O.signal}).then(L=>{O.signal.aborted||(b(L),D(null))}).catch(L=>{O.signal.aborted||(b(null),D(L instanceof Error?L.message:String(L)))}).finally(()=>{z.current===O&&v(!1)})},[i.mode,i.host]);o.useEffect(()=>{if(e&&(b(null),y(null),S(!1),G.current+=1,z.current&&z.current.abort(),!(i.mode==="remote"&&!i.host)))return te.current&&clearTimeout(te.current),te.current=setTimeout(V,Zr),()=>{te.current&&clearTimeout(te.current)}},[e,i.mode,i.host,d,V]),o.useEffect(()=>{e||z.current&&z.current.abort()},[e]),o.useEffect(()=>()=>{z.current&&z.current.abort(),te.current&&clearTimeout(te.current)},[]);const de=()=>{if(A)return;const O=G.current;S(!0),y(null);const C=i.mode==="remote"?{hostId:i.host}:{};E.agents.installTmux(i.mode,C).then(L=>{G.current===O&&(y({ok:L.ok,message:L.message}),S(!1),L.ok&&V())}).catch(L=>{G.current===O&&(y({ok:!1,message:L instanceof Error?L.message:String(L)}),S(!1))})},Z=d?"qa":"dev",X=mn.test(i.id)&&!p.has(i.id)&&i.id!==(d==null?void 0:d.agent.id),me=i.mode==="local"||i.mode==="remote"&&i.host!=="",be=i.runtime!==""&&!!((P=c==null?void 0:c.runtimes[i.runtime])!=null&&P.ok),k=!!(c!=null&&c.tmux.ok),ue=i.mode==="local"||!!((N=c==null?void 0:c.ssh)!=null&&N.ok),ee=!x&&X&&me&&be&&k&&ue,pe=async O=>{var ne,Y;if(O.preventDefault(),!ee)return;D(null);const C=i.addDirs.split(`
9
- `).map(ie=>ie.trim()).filter(ie=>ie.length>0),L={id:i.id,role:Z,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()}:{},...C.length>0?{addDirs:C}:{}};if(!d){m({agent:L,form:i}),l(Pt),b(null),y(null),Q(!1);return}R(!0);try{const ie=await E.projects.addAgentGroup(s,{agents:[d.agent,L]});ie.restartRequired&&_(),I({kind:(ne=ie.warnings)!=null&&ne.length?"warn":"success",title:a.createAgent.addedToastTitle(ie.agents.find(f=>f.role==="dev").id,ie.agents.find(f=>f.role==="qa").id,s),...(Y=ie.warnings)!=null&&Y.length?{body:ie.warnings.join(`
10
- `)}:{}}),r(),n()}catch(ie){D(ie instanceof Error?ie.message:String(ie))}finally{R(!1)}},se=()=>{!d||x||(l(d.form),m(null),b(null),y(null),Q(!1))},ye=({rt:O})=>{if(i.mode==="remote"&&!i.host)return t.jsx("span",{className:"ml-2 text-xs text-og-400",children:a.createAgent.selectHostFirstHint});if(w)return t.jsx("span",{className:"ml-2 text-xs text-og-400",children:a.createAgent.probingLabel});if(!c)return t.jsx("span",{className:"ml-2 text-xs text-og-400",children:"?"});const L=c.runtimes[O];return L?L.ok?t.jsxs("span",{className:"ml-2 text-xs text-probe-ok",children:["✓ ",L.path??""]}):t.jsxs("span",{className:"ml-2 text-xs text-accent",title:L.message,children:["⨯ ",L.message]}):t.jsx("span",{className:"ml-2 text-xs text-og-400",children:"?"})},ve=()=>{var C;if(i.mode==="remote"&&!i.host)return null;if(w&&!A)return t.jsx("div",{className:"text-xs text-og-400",children:a.createAgent.tmuxProbingLabel});if(!c)return null;if(c.tmux.ok)return t.jsxs("div",{className:"text-xs text-probe-ok",children:["tmux: ✓ ",c.tmux.path??""]});const O=i.mode==="local"||!!((C=c.ssh)!=null&&C.ok);return t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"text-xs text-accent",children:["tmux: ⨯ ",c.tmux.message,O&&t.jsx("button",{type:"button",onClick:de,className:"ml-2 text-accent underline transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",disabled:A||x,children:A?a.common.installing:a.common.oneClickInstall})]}),A&&t.jsx("div",{className:"text-xs text-og-500",children:a.common.installingTmuxNotice}),!A&&j&&t.jsxs("div",{className:`break-all text-xs ${j.ok?"text-probe-ok":"text-accent"}`,children:[j.ok?"✓ ":"⨯ ",j.message]})]})},we=()=>i.mode!=="remote"||!i.host||!(c!=null&&c.ssh)?null:c.ssh.ok?t.jsxs("div",{className:"text-xs text-probe-ok",children:["SSH: ✓ ",c.ssh.message]}):t.jsxs("div",{className:"text-xs text-accent",children:["SSH: ⨯ ",c.ssh.message]});return t.jsx(Ae,{open:e,onClose:J,title:a.createAgent.modalTitle(s),size:"lg",footer:t.jsxs(t.Fragment,{children:[d&&t.jsx("button",{type:"button",onClick:se,disabled:x,className:"btn-secondary",children:a.common.back}),t.jsx("button",{type:"button",onClick:J,disabled:x,className:"btn-secondary",children:a.common.cancel}),t.jsx("button",{type:"submit",form:"create-agent-form",disabled:!ee,className:"btn-primary",children:x?a.createAgent.submitting:d?a.createAgent.submitLabel:a.createAgent.continueLabel})]}),children:t.jsxs("form",{id:"create-agent-form",onSubmit:pe,className:"space-y-3",children:[T&&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:T}),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:O=>l({...i,id:O.target.value}),className:le,placeholder:a.createAgent.idPlaceholder(s,Z),disabled:x}),i.id&&!mn.test(i.id)&&t.jsx("div",{className:Ye,children:a.common.idFormatError}),i.id&&(p.has(i.id)||i.id===(d==null?void 0:d.agent.id))&&t.jsx("div",{className:Ye,children:a.createAgent.idTakenGlobalError})]}),t.jsxs("div",{children:[t.jsx("span",{className:re,children:a.createAgent.roleLabel}),t.jsx("div",{className:"text-sm text-og-800",children:Z==="dev"?a.createAgent.devStepLabel:a.createAgent.qaStepLabel}),d&&t.jsx("div",{className:Me,children:a.createAgent.pairedDevLabel(d.agent.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:Ee,onChange:()=>l({...i,mode:"local",host:""}),disabled:x}),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:Ee,onChange:()=>l({...i,mode:"remote"}),disabled:x}),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"}),g.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:O=>l({...i,host:O.target.value}),className:le,disabled:x,children:[t.jsx("option",{value:"",children:a.createAgent.selectHostPlaceholder}),g.map(O=>t.jsx("option",{value:O.id,children:ea(O)},O.id))]}),t.jsx("div",{className:Me,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:V,className:"text-xs text-accent transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",disabled:x||w||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:Ee,onChange:()=>l({...i,runtime:"claude-code"}),disabled:x||(c?!((M=c.runtimes["claude-code"])!=null&&M.ok):!1)}),t.jsx("span",{className:"text-sm text-og-800",children:"Claude Code"}),t.jsx(ye,{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:Ee,onChange:()=>l({...i,runtime:"codex"}),disabled:x||(c?!((F=c.runtimes.codex)!=null&&F.ok):!1)}),t.jsx("span",{className:"text-sm text-og-800",children:"Codex"}),t.jsx(ye,{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:Ee,onChange:()=>l({...i,runtime:"opencode"}),disabled:x||(c?!((ae=c.runtimes.opencode)!=null&&ae.ok):!1)}),t.jsx("span",{className:"text-sm text-og-800",children:"OpenCode"}),t.jsx(ye,{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:Ee,onChange:()=>l({...i,runtime:"qodercli"}),disabled:x||(c?!((fe=c.runtimes.qodercli)!=null&&fe.ok):!1)}),t.jsx("span",{className:"text-sm text-og-800",children:"Qoder CLI"}),t.jsx(ye,{rt:"qodercli"})]}),t.jsx("div",{className:"mt-2",children:t.jsx(ve,{})}),t.jsx("div",{children:t.jsx(we,{})})]}),t.jsxs("div",{children:[t.jsxs("button",{type:"button",onClick:()=>Q(O=>!O),"aria-expanded":$,"aria-controls":$?"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:$?a.createAgent.collapseLabel:a.createAgent.expandLabel})]}),$&&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:O=>l({...i,workdir:O.target.value}),className:le,placeholder:a.createAgent.workdirPlaceholder,disabled:x}),t.jsx("div",{className:Me,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:O=>l({...i,model:O.target.value}),className:le,placeholder:i.runtime==="codex"?a.createAgent.modelPlaceholderCodex:a.createAgent.modelPlaceholderOther,disabled:x}),t.jsx("div",{className:Me,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:O=>l({...i,addDirs:O.target.value}),className:`${le} font-mono text-xs`,rows:3,placeholder:a.createAgent.addDirsPlaceholder,disabled:x}),t.jsx("div",{className:Me,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:O=>l({...i,yolo:O.target.checked}),disabled:x}),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:Bs[i.runtime||"claude-code"]}),a.createAgent.yoloBodyTrail]})]})]})})]})})}const hn=200,pn=16e3,ta="baxian.draft.createTask:";function Ot(e){return`${ta}${e??"*"}`}function fn(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:"",m=typeof r.updatedAt=="number"?r.updatedAt:void 0;return!a.trim()&&!i.trim()?null:{title:a,description:i,projectId:l,preferredAgentId:d,updatedAt:m}}catch{return null}}function na(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 gn(e){try{localStorage.removeItem(e)}catch{}}function sa(e){const n=Ot(e),s=fn(n);if(!e)return s;const r=Ot(void 0),a=fn(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 xn="mt-1 text-right text-xs text-og-400",ra=Math.floor(bt/1024/1024);function Zt(e){const n=q(),s=e.mode==="edit",{show:r}=Te(),a=s?e.task.projectId:e.projectId,i=s?e.task.title:"",l=s?e.task.description:"",d=s?e.task.preferredAgentId:"",[m,g]=o.useState([]),[h,p]=o.useState([]),[u,c]=o.useState(a??""),[b,w]=o.useState(d),[v,A]=o.useState(i),[S,j]=o.useState(l),[y,x]=o.useState([]),R=o.useRef(null),[T,D]=o.useState(!1),[$,Q]=o.useState(null),[z,te]=o.useState(!1),G=o.useRef(0),K=o.useRef(0),I=o.useRef(0),_=o.useRef(new Set),J=s?null:Ot(a);o.useEffect(()=>{if(!e.open)return;G.current+=1,K.current+=1;const C=G.current;g([]),p([]),_.current=new Set;const L=J?sa(a):null;L&&_.current.add(L.projectId),c(a??(L==null?void 0:L.projectId)??""),w((L==null?void 0:L.preferredAgentId)||d),A((L==null?void 0:L.title)||i),j((L==null?void 0:L.description)||l),te(L!==null),Q(null),D(!1),x([]),Promise.all([E.projects.list(),E.agents.list()]).then(([ne,Y])=>{C===G.current&&(g(ne),p(Y))}).catch(ne=>{C===G.current&&Q(ne instanceof Error?ne.message:String(ne))})},[e.open,a,i,l,d,J]),o.useEffect(()=>{if(!(!e.open||!J)){if(I.current!==K.current){I.current=K.current;return}na(J,{title:v,description:S,projectId:u,preferredAgentId:b})}},[e.open,J,v,S,u,b]);const V=o.useMemo(()=>m.find(C=>C.id===u)??null,[m,u]),de=o.useMemo(()=>V?V.agent.flat().filter(C=>C.role==="dev"):[],[V]),Z=o.useMemo(()=>new Set(h.map(C=>C.id)),[h]),X=o.useMemo(()=>de.filter(C=>Z.has(C.id)),[de,Z]),me=o.useMemo(()=>de.filter(C=>!Z.has(C.id)),[de,Z]);o.useEffect(()=>{s||V!==null&&b!==""&&!X.find(C=>C.id===b)&&w("")},[V,X,b,s]),o.useEffect(()=>{if(s||!V)return;const C=X.find(L=>L.role==="dev");C&&(_.current.has(V.id)||(_.current.add(V.id),w(L=>L===""?C.id:L)))},[s,V,X]);const be=!s||X.find(C=>C.id===b),k=s&&!be&&!!b,ue=k&&me.some(C=>C.id===b),ee=ue?n.createTask.noDevPendingRestartHint(b):k?n.createTask.noDevNotInRuntimeHint(b):!u||X.length>0?null:me.length>0?n.createTask.noDevGlobalPendingRestartHint:null,pe=v.trim(),se=S.trim(),ve=!!u&&pe.length>0&&!T,we=()=>{T||e.onClose()},P=()=>{J&&(gn(J),c(a??""),w(d),A(i),j(l),Q(null),te(!1))},N=async C=>{var L,ne;if(C.preventDefault(),!!ve){D(!0),Q(null);try{if(e.mode==="edit"){const Y=await E.tasks.update(e.task.id,{title:pe,description:se,preferredAgentId:b});r({kind:"success",title:n.createTask.updatedToastTitle}),(L=e.onUpdated)==null||L.call(e,Y),e.onClose()}else{const Y=y.length?await Promise.all(y.map(async f=>({dataBase64:await Bt(f),filename:f.name}))):void 0,ie=await E.tasks.create({projectId:u,title:pe,description:se,preferredAgentId:b,...Y?{images:Y}:{}});J&&gn(J),r({kind:"success",title:n.createTask.createdToastTitle}),(ne=e.onCreated)==null||ne.call(e,ie),e.onClose()}}catch(Y){Q(Y instanceof Error?Y.message:String(Y))}finally{D(!1)}}},M=C=>{const L=Array.from(C.target.files??[]);if(C.target.value="",L.length===0)return;const ne=L.filter(Y=>Y.size>bt?(r({kind:"error",title:n.createTask.imageTooLargeToastTitle,body:n.createTask.imageTooLargeToastBody(Y.name,ra)}),!1):!0);x(Y=>(Y.length+ne.length>st&&r({kind:"warn",title:n.createTask.tooManyImagesToastTitle(st)}),[...Y,...ne].slice(0,st)))},F=C=>x(L=>L.filter((ne,Y)=>Y!==C)),ae=s?n.createTask.titleEdit:n.createTask.titleCreate,fe=s?T?n.common.saving:n.common.save:T?n.common.creating:n.common.create,O=!s&&!a;return t.jsx(Ae,{open:e.open,onClose:we,title:ae,size:"md",dismissOnBackdrop:!1,footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:we,disabled:T,className:"btn-secondary",children:n.common.cancel}),t.jsx("button",{type:"submit",form:"create-task-form",disabled:!ve,className:"btn-primary",children:fe})]}),children:t.jsxs("form",{id:"create-task-form",onSubmit:N,className:"space-y-3",children:[!s&&z&&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:P,className:"shrink-0 underline hover:text-accent-hover",children:n.createTask.discardDraftButton})]}),$&&t.jsx("div",{className:"rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-sm text-accent",children:$}),O&&t.jsxs("div",{children:[t.jsx("label",{className:re,htmlFor:"task-project",children:"Project"}),t.jsxs("select",{id:"task-project",value:u,onChange:C=>c(C.target.value),className:le,disabled:T,required:!0,children:[t.jsx("option",{value:"",disabled:!0,children:n.createTask.selectProjectPlaceholder}),m.map(C=>t.jsx("option",{value:C.id,children:C.id},C.id))]})]}),t.jsxs("div",{children:[t.jsx("label",{className:re,htmlFor:"task-dev",children:n.createTask.targetAgentLabel}),t.jsxs("select",{id:"task-dev",value:b,onChange:C=>w(C.target.value),className:le,disabled:T,children:[t.jsx("option",{value:"",children:n.createTask.notAssignedOption}),k&&t.jsxs("option",{value:b,children:[b," ",ue?n.createTask.pendingRestartSuffix:n.createTask.notInRuntimeSuffix]}),X.map(C=>t.jsx("option",{value:C.id,children:C.id},C.id))]}),ee&&t.jsx("div",{className:"mt-1 text-xs text-accent",children:ee})]}),t.jsxs("div",{children:[t.jsx("label",{className:re,htmlFor:"task-title",children:"Title"}),t.jsx("input",{id:"task-title",type:"text",value:v,onChange:C=>A(C.target.value),maxLength:hn,className:le,placeholder:n.createTask.titlePlaceholder,disabled:T,required:!0}),t.jsxs("div",{className:xn,children:[v.length," / ",hn]})]}),t.jsxs("div",{children:[t.jsx("label",{className:re,htmlFor:"task-description",children:n.createTask.descriptionLabel}),t.jsx("textarea",{id:"task-description",value:S,onChange:C=>j(C.target.value),maxLength:pn,rows:8,className:`${le} font-mono text-xs`,placeholder:n.createTask.descriptionPlaceholder,disabled:T}),t.jsxs("div",{className:xn,children:[S.length," / ",pn]})]}),!s&&t.jsxs("div",{children:[t.jsx("label",{className:re,children:n.createTask.imagesLabel}),t.jsx("button",{type:"button",onClick:()=>{var C;return(C=R.current)==null?void 0:C.click()},disabled:T||y.length>=st,className:"btn-secondary",children:n.createTask.addImagesButton}),t.jsx("input",{ref:R,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:M}),y.length>0&&t.jsx("ul",{className:"mt-2 space-y-1",children:y.map((C,L)=>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:C.name,className:"truncate text-xs text-og-700",children:C.name}),t.jsx("button",{type:"button","aria-label":n.createTask.removeImageAriaLabel(C.name),onClick:()=>F(L),disabled:T,className:"ml-2 shrink-0 text-og-400 transition-colors",children:"✕"})]},`${C.name}-${L}`))})]})]})})}const bn="***",Lt={hostname:"",port:"",alias:"",user:"",password:""};function aa(e){return e.alias?e.alias:`${e.user?`${e.user}@`:""}${e.hostname}${e.port!=null?`:${e.port}`:""}`}function ia({open:e,onClose:n}){var we;const s=q(),[r,a]=o.useState([]),[i,l]=o.useState("list"),[d,m]=o.useState(null),[g,h]=o.useState(null),[p,u]=o.useState(!1),[c,b]=o.useState(!1),[w,v]=o.useState(Lt),[A,S]=o.useState(null),[j,y]=o.useState(!1),[x,R]=o.useState(!1),[T,D]=o.useState(null),[$,Q]=o.useState(!1),[z,te]=o.useState(null),G=o.useRef(0),K=o.useRef(null),{show:I}=Te(),_=o.useCallback(()=>{E.hosts.list().then(a).catch(P=>S(P instanceof Error?P.message:String(P)))},[]);o.useEffect(()=>{if(!e){K.current&&K.current.abort();return}l("list"),m(null),h(null),v(Lt),S(null),_()},[e,_]),o.useEffect(()=>{G.current+=1,K.current&&K.current.abort(),R(!1),D(null),Q(!1),te(null)},[w.hostname,w.user,w.port,w.password,c,i]),o.useEffect(()=>()=>{K.current&&K.current.abort()},[]);const J=()=>{m(null),h(null),u(!1),b(!1),v(Lt),S(null),l("form")},V=P=>{m(P.id??null),h(P),u(P.password===bn),b(!1),v({hostname:P.hostname,port:P.port!=null?String(P.port):"",alias:P.alias??"",user:P.user??"",password:""}),S(null),l("form")},de=()=>{const P={hostname:w.hostname.trim()};return d?(P.port=w.port.trim()?Number(w.port):null,P.alias=w.alias.trim(),P.user=w.user.trim()):(w.port.trim()&&(P.port=Number(w.port)),w.alias.trim()&&(P.alias=w.alias.trim()),w.user.trim()&&(P.user=w.user.trim())),d&&c?P.password="":w.password&&(P.password=w.password),P},Z=w.port.trim(),X=Z===""||/^\d+$/.test(Z)&&Number(Z)>0&&Number(Z)<=65535,me=w.hostname.trim().length>0&&X,be=!!g&&w.hostname.trim()===g.hostname&&w.user.trim()===(g.user??"")&&w.port.trim()===(g.port!=null?String(g.port):""),k=()=>d&&be&&!w.password&&!c?{hostId:d}:{host:{hostname:w.hostname.trim(),...w.user.trim()?{user:w.user.trim()}:{},...Z?{port:Number(Z)}:{},...!c&&w.password?{password:w.password}:{}}},ue=async()=>{if(!me||x)return;K.current&&K.current.abort();const P=new AbortController;K.current=P;const N=G.current;R(!0),D(null),te(null),S(null);try{const M=await E.agents.probe("remote",k(),{signal:P.signal});if(P.signal.aborted||G.current!==N)return;D(M)}catch(M){if(P.signal.aborted||G.current!==N)return;S(M instanceof Error?M.message:String(M))}finally{G.current===N&&R(!1)}},ee=async()=>{if($)return;const P=G.current;Q(!0),te(null),S(null);try{const N=await E.agents.installTmux("remote",k());if(G.current!==P)return;te({ok:N.ok,message:N.message}),D(M=>M&&{...M,tmux:N.tmux})}catch(N){if(G.current!==P)return;S(N instanceof Error?N.message:String(N))}finally{G.current===P&&Q(!1)}},pe=async P=>{if(P.preventDefault(),!(!me||j)){y(!0),S(null);try{if(d)await E.hosts.update(d,de()),I({kind:"success",title:s.hostMgmt.updatedToastTitle(d)});else{const N=await E.hosts.create(de());I({kind:"success",title:s.hostMgmt.createdToastTitle(N.host.id)})}_(),l("list")}catch(N){S(N instanceof Error?N.message:String(N))}finally{y(!1)}}},se=async P=>{S(null);try{await E.hosts.delete(P.id),I({kind:"success",title:s.hostMgmt.deletedToastTitle(P.id)}),_()}catch(N){S(N instanceof Error?N.message:String(N))}},ye=t.jsx("button",{type:"button",onClick:n,className:"btn-secondary",children:s.common.close}),ve=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:()=>l("list"),disabled:j,className:"btn-secondary",children:s.common.backText}),t.jsx("button",{type:"submit",form:"host-form",disabled:!me||j,className:"btn-primary",children:j?s.common.saving:s.common.save})]});return t.jsxs(Ae,{open:e,onClose:n,title:s.hostMgmt.title,size:"md",footer:i==="list"?ye:ve,children:[A&&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:A}),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(P=>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:aa(P)}),t.jsxs("div",{className:"truncate text-xs text-og-500",children:[(P.user?`${P.user}@`:"")+P.hostname,P.port!=null?`:${P.port}`:"",P.password===bn?s.hostMgmt.passwordSavedIndicator:""]})]}),t.jsxs("div",{className:"flex shrink-0 gap-2",children:[t.jsx("button",{type:"button",onClick:()=>V(P),className:"text-xs text-accent transition-colors hover:text-accent-hover",children:s.common.edit}),t.jsx("button",{type:"button",onClick:()=>se(P),className:"text-xs text-accent transition-colors hover:opacity-80",children:s.common.delete})]})]},P.id))}),t.jsx("button",{type:"button",onClick:J,className:"btn-secondary w-full",children:s.hostMgmt.addHostButton})]}):t.jsxs("form",{id:"host-form",onSubmit:pe,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:w.hostname,onChange:P=>v({...w,hostname:P.target.value}),className:le,placeholder:"remote.example.com",disabled:j})]}),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:w.port,onChange:P=>v({...w,port:P.target.value}),className:le,placeholder:"22",disabled:j}),w.port.trim()!==""&&!X&&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:w.alias,onChange:P=>v({...w,alias:P.target.value}),className:le,placeholder:"Prod worker",disabled:j})]}),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:w.user,onChange:P=>v({...w,user:P.target.value}),className:le,placeholder:s.hostMgmt.userPlaceholder,disabled:j})]}),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:c?"":w.password,onChange:P=>v({...w,password:P.target.value}),className:le,placeholder:p?s.hostMgmt.passwordPlaceholderSet:s.hostMgmt.passwordPlaceholderUnset,disabled:j||c,autoComplete:"new-password"}),d&&p&&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:c,onChange:P=>b(P.target.checked),disabled:j}),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:ue,disabled:!me||x||j||$,className:"text-xs text-accent transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",children:x?s.hostMgmt.testing:s.hostMgmt.testConnection}),(T==null?void 0:T.ssh)&&t.jsxs("div",{className:`text-xs ${T.ssh.ok?"text-og-800":"text-accent"}`,children:["SSH: ",T.ssh.ok?"✓":"⨯"," ",T.ssh.message]}),T&&(T.tmux.ok?t.jsxs("div",{className:"text-xs text-og-800",children:["tmux: ✓ ",T.tmux.path??""]}):t.jsxs("div",{className:"text-xs text-accent",children:["tmux: ⨯ ",T.tmux.message,((we=T.ssh)==null?void 0:we.ok)&&t.jsx("button",{type:"button",onClick:ee,disabled:$||j,className:"ml-2 text-accent underline transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",children:$?s.common.installing:s.common.oneClickInstall})]})),$&&t.jsx("div",{className:"text-xs text-og-500",children:s.common.installingTmuxNotice}),!$&&z&&t.jsxs("div",{className:`break-all text-xs ${z.ok?"text-og-800":"text-accent"}`,children:[z.ok?"✓ ":"⨯ ",z.message]})]})]})]})}const en="baxian.taskNotifications.enabled";function tn(){if(typeof window>"u")return null;const e=window.Notification;return typeof e=="function"?e:null}function ot(){const e=tn();return e?e.permission:"unsupported"}function Et(){try{return localStorage.getItem(en)!=="0"}catch{return!0}}function lt(e){try{localStorage.setItem(en,e?"1":"0")}catch{}}const is=o.createContext(null);function oa({children:e}){const[n,s]=o.useState(ot),[r,a]=o.useState(Et),[i,l]=o.useState(!1),d=o.useRef(!1),m=o.useRef(0);o.useEffect(()=>{const p=()=>{s(ot()),d.current||a(Et())},u=c=>{if(c.key!==null&&c.key!==en)return;s(ot());const b=c.key===null?Et():c.newValue!=="0";b||(m.current+=1),a(b)};return window.addEventListener("focus",p),window.addEventListener("storage",u),()=>{window.removeEventListener("focus",p),window.removeEventListener("storage",u)}},[]);const g=o.useCallback(()=>{a(!0);const p=tn();if(!p){lt(!0);return}if(p.permission!=="default"){s(p.permission),lt(!0);return}if(d.current)return;d.current=!0,l(!0);const u=m.current;p.requestPermission().then(s).catch(c=>{console.warn("[task-notifications] permission request failed:",c),s(ot())}).finally(()=>{m.current===u&&lt(!0),d.current=!1,l(!1)})},[]),h=o.useCallback(()=>{m.current+=1,a(!1),lt(!1)},[]);return t.jsx(is.Provider,{value:{permission:n,preferenceEnabled:r,enabled:n==="granted"&&r,requesting:i,enable:g,disable:h},children:e})}function os(){const e=o.useContext(is);if(!e)throw new Error("useTaskNotifications must be used inside TaskNotificationsProvider");return e}const la=[{value:"en-US",label:"English"},{value:"zh-CN",label:"简体中文"}];function ca({open:e,onClose:n}){const s=q(),{locale:r,saving:a,setLocale:i}=qn(),{show:l}=Te(),d=async m=>{try{await i(m)}catch(g){const h=g instanceof Error?g.message:String(g);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:la.map(m=>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:Ee,checked:r===m.value,disabled:a,onChange:()=>void d(m.value)}),m.label]},m.value))})]}),t.jsx(da,{})]})})}function da(){const e=q(),{permission:n,enabled:s,requesting:r,enable:a,disable:i}=os();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:Ee,checked:s,disabled:l||r,onChange:()=>s?i():a()}),e.settings.taskNotifications]}),t.jsx("p",{className:Me,children:l?e.settings.taskNotificationsDenied:e.settings.taskNotificationsHint})]})}const ls="topbar-actions";function vn(){return typeof document>"u"?null:document.getElementById(ls)}function cs({children:e}){const[n,s]=o.useState(vn);return o.useEffect(()=>{n||s(vn())},[n]),n?As.createPortal(e,n):null}function ua(){return Vn("/api/realtime")}class ma{constructor(n={}){oe(this,"wsUrl");oe(this,"wsFactory");oe(this,"tokenProvider");oe(this,"ws",null);oe(this,"topics",new Map);oe(this,"cache",new Map);oe(this,"outbox",[]);oe(this,"reconnectScheduler");oe(this,"explicitlyClosed",!1);this.wsUrl=n.wsUrl??ua(),this.wsFactory=n.wsFactory??Yn,this.tokenProvider=n.tokenProvider??zt,this.reconnectScheduler=new Qn({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.${Kn(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 Ze(){return Dt||(Dt=new ma),Dt}function nn(){const[e,n]=o.useState(null),[s,r]=o.useState(!1),[a,i]=o.useState(null);return o.useEffect(()=>Ze().subscribe("agents",d=>{i(null),n(d),r(!0)},d=>i(d)),[]),{data:e,loaded:s,error:a}}function ds(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),Ze().subscribe(`task:${e}`,m=>{l(null),s(m),a(!0)},m=>l(m))),[e]),{data:n,loaded:r,error:i}}function us(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,m=!1,g=!1;const h=Ze().subscribe(`project-tasks:${e}`,p=>{d||(m=!0,l(null),s(p),a(!0))},p=>{d||(l(p),!(m||g)&&(g=!0,E.tasks.list(e).then(u=>{d||m||(s(u),a(!0))},u=>{console.warn(`[useProjectTasks] REST fallback failed for ${e}:`,u)})))});return()=>{d=!0,h()}},[e]),{data:n,loaded:r,error:i}}let pt=null,De=null,ft=null,Ve=0;const Ht=new Set;function ms(){Ht.forEach(e=>e())}async function ha(){const e=Ve;try{const n=await E.projects.list();if(e!==Ve)return;pt=n,ft=null}catch(n){if(e!==Ve)return;ft=n instanceof Error?n.message:String(n)}finally{e===Ve&&(De=null,ms())}}function _t(){return De||(De=ha(),De)}function pa(){Ve+=1,pt=null,De=null,ft=null,ms()}typeof window<"u"&&window.addEventListener(ut,pa);async function fa(){const e=De!==null;await _t(),e&&await _t()}function et(){const[,e]=o.useState(0);return o.useEffect(()=>{const n=()=>e(s=>s+1);return Ht.add(n),pt===null&&!De&&_t(),()=>{Ht.delete(n)}},[]),{projects:pt,error:ft,refresh:fa}}function ga(){const e=q(),n=Pe(),{projects:s,error:r,refresh:a}=et(),i=s??[],l=s!==null,[d,m]=o.useState(!1),[g,h]=o.useState(!1),[p,u]=o.useState(!1),[c,b]=o.useState(!1),[w,v]=o.useState({kind:"closed"}),{data:A,loaded:S,error:j}=nn(),y=(j==null?void 0:j.message)??null,x=new Map((A??[]).map($=>[$.id,$])),R=r??y,T=i.length===0,D=t.jsx("button",{type:"button",onClick:()=>h(!0),disabled:T,"aria-describedby":T?"create-task-hint":void 0,className:"btn-ghost",children:e.dashboard.newTask});return t.jsxs("div",{children:[t.jsxs(cs,{children:[T?t.jsx("span",{className:"inline-flex",title:e.dashboard.createProjectFirst,children:D}):D,T&&t.jsx("span",{id:"create-task-hint",className:"sr-only",children:e.dashboard.createProjectFirst}),t.jsx(qt,{ariaLabel:e.dashboard.moreActions,children:$=>t.jsxs(t.Fragment,{children:[t.jsx(Se,{onClick:()=>{$(),m(!0)},children:e.dashboard.newProject}),t.jsx(Se,{onClick:()=>{$(),u(!0)},children:e.dashboard.manageHosts}),t.jsx(Se,{onClick:()=>{$(),b(!0)},children:e.settings.entry})]})})]}),t.jsx("h1",{className:"sr-only",children:"Dashboard"}),R&&t.jsx("div",{className:"mb-4 text-sm text-accent",children:e.common.loadFailed(R)}),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($=>t.jsx(xa,{project:$,agentsById:x,agentsLoaded:S,agentsError:!!j,onAgentDeleted:a},$.id)),t.jsx(Xr,{open:d,onClose:()=>m(!1),onCreated:$=>{m(!1),a(),v({kind:"asking",projectId:$})}}),t.jsx(ia,{open:p,onClose:()=>u(!1)}),t.jsx(Ae,{open:w.kind==="asking",onClose:()=>v({kind:"closed"}),title:e.dashboard.projectCreatedTitle,size:"sm",footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:()=>v({kind:"closed"}),className:"btn-secondary",children:e.dashboard.later}),t.jsx("button",{type:"button",onClick:()=>{w.kind==="asking"&&v({kind:"addingAgent",projectId:w.projectId})},className:"btn-primary",children:e.dashboard.continueAddingAgent})]}),children:t.jsx("p",{className:"text-sm text-og-700",children:e.dashboard.addAgentNowOrLater})}),w.kind==="addingAgent"&&t.jsx(as,{open:!0,projectId:w.projectId,onClose:()=>v({kind:"closed"}),onCreated:()=>{a()}}),t.jsx(Zt,{open:g,onClose:()=>h(!1),onCreated:$=>n(Fe($.projectId,$.id))}),t.jsx(ca,{open:c,onClose:()=>b(!1)})]})}function xa({project:e,agentsById:n,agentsLoaded:s,agentsError:r,onAgentDeleted:a}){const i=q(),{data:l,error:d}=us(e.id),m=l??[],g=(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(He,{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(He,{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})]}),g&&t.jsx("div",{className:"mb-2 text-xs text-accent",children:i.dashboard.tasksLoadFailed(g)}),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,p)=>t.jsx(ns,{group:h,projectId:e.id,agentsById:n,agentsLoaded:s,agentsError:r,tasks:m,onDeleted:a,terminalMode:"embedded-full"},h.map(u=>u.id).join(":")||p))})]})}const hs="baxian.taskPanel.doneOpen";function ba(){try{return localStorage.getItem(hs)==="1"}catch{return!1}}function gt(e){const n=e.match(/^task-(\d+)$/);return n?parseInt(n[1],10):Number.NaN}function va(e,n){const s=gt(e.id),r=gt(n.id);return Number.isNaN(s)||Number.isNaN(r)?e.id.localeCompare(n.id):s-r}function ya(e,n){const s=(n.updatedAt??"").localeCompare(e.updatedAt??"");if(s!==0)return s;const r=gt(e.id),a=gt(n.id);return Number.isNaN(r)||Number.isNaN(a)?n.id.localeCompare(e.id):a-r}function yn(e,n){const[s,r]=o.useState(wt);o.useEffect(()=>r(wt),[n]);const a=e.slice(0,s),i=e.length>a.length;return{items:a,hasMore:i,loadMore:()=>r(d=>d+wt),total:e.length}}function wa(e){const[n,s]=o.useState([]),[r,a]=o.useState(!1),[i,l]=o.useState(!1),[d,m]=o.useState(!1),[g,h]=o.useState(null),p=o.useRef(0),u=o.useRef(0),c=o.useCallback(b=>{const w=++p.current,v=b==="first"?0:u.current;l(!0),h(null),E.tasks.page(e,{category:"done",offset:v}).then(A=>{p.current===w&&(s(S=>b==="first"?A.tasks:[...S,...A.tasks]),a(A.hasMore),u.current=A.nextOffset,m(!0),l(!1))},A=>{p.current===w&&(h(A instanceof Error?A.message:String(A)),l(!1))})},[e]);return o.useEffect(()=>{p.current+=1,u.current=0,s([]),a(!1),m(!1),h(null),l(!1)},[e]),{items:n,hasMore:r,loading:i,loaded:d,error:g,load:c}}function ja({projectId:e,openTasks:n,className:s=""}){const r=q(),a=o.useMemo(()=>n.filter(u=>En.has(u.status)).sort(ya),[n]),i=o.useMemo(()=>n.filter(u=>u.status==="pending").sort(va),[n]),l=yn(a,e),d=yn(i,e),m=wa(e),[g,h]=o.useState(ba);o.useEffect(()=>{try{localStorage.setItem(hs,g?"1":"0")}catch{}},[g]),o.useEffect(()=>{g&&m.load("first")},[g,m.load]);const p=()=>h(u=>!u);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(wn,{title:"IN PROGRESS",section:l,emptyHint:r.taskPanel.emptyInProgress}),t.jsx(wn,{title:"PENDING",section:d,emptyHint:r.taskPanel.emptyPending}),t.jsxs("div",{children:[t.jsxs("button",{type:"button",onClick:p,"aria-expanded":g,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:g?r.taskPanel.collapse:r.taskPanel.view})]}),g&&t.jsx(ka,{state:m})]})]})})}function wn({title:e,section:n,emptyHint:s}){const r=q();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(ps,{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 ka({state:e}){const n=q(),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(ps,{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 Sa(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)>=Dn)}r();const a=setInterval(r,3e4);return()=>clearInterval(a)},[e.status,e.reviewDispatchedAt,e.qaAgentId]),n}function ps({task:e}){const n=q(),s=Pe(),r=Ce(e.phase)?e.specReviewRound??0:e.reviewRound,a=Sa(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:Xt(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(qr,{status:e.status})]})}const Ta=[],fs="baxian.taskPanel.open";function Na(){try{return localStorage.getItem(fs)!=="0"}catch{return!0}}function Ra(){const{id:e}=xt(),n=Pe(),s=q(),{show:r}=Te(),{refresh:a}=et(),[i,l]=o.useState(null),[d,m]=o.useState(null),[g,h]=o.useState(!1),[p,u]=o.useState(!1),c=o.useRef(null),[b,w]=o.useState(Na),[v,A]=o.useState(!1),[S,j]=o.useState(""),[y,x]=o.useState(!1),[R,T]=o.useState(null),D=o.useRef(0),{data:$,loaded:Q,error:z}=nn(),{data:te,error:G}=us(e),K=(z==null?void 0:z.message)??null,I=(G==null?void 0:G.message)??null,_=te??Ta,J=new Map(($??[]).map(k=>[k.id,k])),V=d??K??I,de=o.useCallback(async k=>{const ue=++D.current;try{const ee=await E.projects.get(k);if(ue!==D.current)return;l(ee),m(null)}catch(ee){if(ue!==D.current)return;m(ee instanceof Error?ee.message:String(ee))}},[]);o.useEffect(()=>{e&&(l(null),m(null),de(e))},[e,de]),o.useEffect(()=>{v||(j(""),T(null))},[v]),o.useEffect(()=>{try{localStorage.setItem(fs,b?"1":"0")}catch{}},[b]);const Z=(i==null?void 0:i.agent.flat().length)??0,X=Z===0,me=!!i&&S.trim()===i.id,be=async()=>{if(!(!i||!me||y)){x(!0),T(null);try{await E.projects.delete(i.id),await a(),r({kind:"success",title:s.projectPage.deletedToastTitle(i.id)}),A(!1),n("/")}catch(k){T(k instanceof Error?k.message:String(k))}finally{x(!1)}}};return i?t.jsxs("div",{children:[t.jsxs(cs,{children:[t.jsx("button",{type:"button",onClick:()=>u(!0),className:"btn-ghost",children:s.projectPage.newTaskButton}),t.jsx(qt,{ariaLabel:s.projectPage.menuAriaLabel(i.id),menuClassName:"min-w-[180px]",triggerRef:c,children:k=>t.jsxs(t.Fragment,{children:[!b&&t.jsx(Se,{onClick:()=>{k(),w(!0)},children:s.projectPage.showTaskPanel}),t.jsx(Se,{onClick:()=>{k(),h(!0)},children:s.projectPage.addAgent}),t.jsx("div",{role:"none",className:"my-1 border-t border-hairline"}),t.jsx(Se,{onClick:()=>{k(),A(!0)},disabled:!X,title:X?void 0:s.projectPage.deleteAgentsFirstHint(Z),children:s.projectPage.deleteProjectMenuItem})]})})]}),V&&t.jsx("div",{className:"mb-4 text-sm text-accent",children:s.common.loadFailed(V)}),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((k,ue)=>t.jsx(ns,{group:k,projectId:i.id,agentsById:J,agentsLoaded:Q,agentsError:!!z,tasks:_,onDeleted:()=>{de(i.id)},terminalMode:"embedded-full"},k.map(ee=>ee.id).join(":")||ue))})]}),b&&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 k;w(!1),(k=c.current)==null||k.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(ja,{projectId:i.id,openTasks:_})]})]}),t.jsx(as,{open:g,projectId:i.id,onClose:()=>h(!1),onCreated:()=>{de(i.id)}}),t.jsx(Zt,{open:p,projectId:i.id,onClose:()=>u(!1),onCreated:k=>n(Fe(k.projectId,k.id))}),t.jsx(Ae,{open:v,onClose:()=>{y||A(!1)},title:s.projectPage.deleteModalTitle,size:"sm",footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:()=>A(!1),disabled:y,className:"btn-secondary",children:s.common.cancel}),t.jsx("button",{type:"button",onClick:()=>void be(),disabled:!me||y,className:"btn-primary",children:y?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:S,onChange:k=>j(k.target.value),placeholder:i.id,autoComplete:"off",autoCorrect:"off",spellCheck:!1,disabled:y,"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"}),R&&t.jsx("div",{className:"rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-xs text-accent",children:R})]})})]}):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})}const gs={approve:"pill pill-live","request-changes":"pill pill-warn",comment:"pill"};function xs(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 bs(e,n){return e.review?`round-${Xe(e.review,n)}`:`round-in-progress-${e.items[0]?Xe(e.items[0],n):n}`}function vs(e){return[e.reviewRound,e.latestHeadSha??"",e.status,e.reviewDispatchedAt??"",e.prFeedbackReceivedAt??"",e.prNumber??"",e.reviewConversationUpdatedAt??""].join(":")}const Ca=4e3,Aa=6e4;function ys(e,n){const[s,r]=o.useState(null),[a,i]=o.useState(!1),[l,d]=o.useState(null),[m,g]=o.useState(0),h=o.useRef(e),p=o.useRef(n),u=o.useRef(0),c=o.useRef(0);return o.useEffect(()=>{h.current!==e&&(h.current=e,r(null),i(!1),c.current=0),p.current!==n&&(p.current=n,c.current=0);const b=++u.current;let w;return d(null),E.tasks.prReview(e).then(v=>{if(u.current===b)if(r(v),i(!0),v.available&&v.error&&c.current<3){c.current+=1;const A=v.rateLimited?Aa*2**(c.current-1):Ca*c.current;w=setTimeout(()=>g(S=>S+1),A)}else v.error||(c.current=0)}).catch(v=>{u.current===b&&(d(v instanceof Error?v.message:String(v)),r(null),i(!0))}),()=>clearTimeout(w)},[e,n,m]),{data:s,loaded:a,error:l}}function Pa({role:e,label:n,summary:s,badge:r,onClick:a}){const i=q();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 La(e){return{"no-pr":e.prReview.reasonNoPr,"driver-unavailable":e.prReview.reasonDriverUnavailable}}function Ea(e){return(e==null?void 0:e.trim().split(`
11
- `,1)[0])??""}function Da(e){if(!(e.kind!=="review-comment"||!e.path))return e.line!==void 0?`${e.path}:${e.line}`:e.path}function $a(e,n){return n.bodyTruncated?e.prReview.truncatedSuffix:""}function Ia(e,n){const s=Ea(n.body),r=$a(e,n);if(n.kind==="review-comment"){const a=Da(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 Ba(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 Fa(e){return e.verdict!==void 0?"qa":e.kind==="issue-comment"||e.inReplyTo?"dev":"qa"}function Ma({task:e}){const n=q(),s=Pe(),r=vs(e),{data:a,loaded:i,error:l}=ys(e.id,r),d=Ce(e.phase)?n.prReview.specReviewHeading:n.prReview.codeReviewHeading;function m(h){s(`/tasks/${encodeURIComponent(e.id)}/pr-review${h?`#${h}`:""}`)}if(l)return t.jsx(Qe,{title:d,children:t.jsx("div",{className:"text-sm text-accent",children:n.review.loadFailed(l)})});if(!i)return t.jsx(Qe,{title:d,children:t.jsx("div",{className:"text-sm text-og-400",children:n.review.loadingRecords})});if(!(a!=null&&a.available)){const h=La(n);return t.jsx(Qe,{title:d,children:t.jsx("div",{className:"text-sm text-og-400",children:h[(a==null?void 0:a.reason)??"no-pr"]??h["no-pr"]})})}if(a.items.length===0)return t.jsx(Qe,{title:d,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 g=xs(a.items);return t.jsxs(Qe,{title:d,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}),g.map((h,p)=>t.jsx(Oa,{round:h,index:p,onOpen:m},bs(h,String(p))))]})}function Qe({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 Oa({round:e,index:n,onOpen:s}){const r=q(),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(jn,{item:i,onOpen:s},Xe(i,`${n}-${l}`))),e.review&&t.jsx(jn,{item:e.review,onOpen:s})]})]})}function jn({item:e,onOpen:n}){const s=q(),r=e.verdict,a=r?t.jsx("span",{className:gs[r],children:r}):e.kind==="review"&&e.reviewState?t.jsx("span",{className:"pill",children:e.reviewState}):void 0;return t.jsx(Pa,{role:Fa(e),label:Ba(s,e),badge:a,summary:Ia(s,e),onClick:()=>n(yt(e))})}function Ha({task:e}){const n=q();return e.prNumber===void 0?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.jsx(Ma,{task:e})]})}const kn=ct;function _a(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>=Dn)}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 Ua(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 Sn(e){if(!/^[1-9]\d*$/.test(e.trim()))return;const n=Number(e);return Number.isSafeInteger(n)?n:void 0}function qa(){const{taskId:e=""}=xt();return t.jsx(Ga,{taskId:e},e)}function Ga({taskId:e}){const n=Pe(),s=q(),{show:r}=Te(),a=Yt(),[i,l]=o.useState(!1),[d,m]=o.useState(!1),[g,h]=o.useState(!1),[p,u]=o.useState(!1),[c,b]=o.useState(!1),[w,v]=o.useState("spec"),[A,S]=o.useState(""),[j,y]=o.useState(""),[x,R]=o.useState(!1),[T,D]=o.useState(!1),[$,Q]=o.useState(!1),[z,te]=o.useState(""),[G,K]=o.useState(null),{data:I,loaded:_,error:J}=ds(e),{projects:V}=et(),{data:de,loaded:Z,error:X}=nn(),{activeAgentId:me,activateAgentCard:be}=es(),k=G??I,ue=_a(k),ee=(J==null?void 0:J.message)??null,pe=o.useMemo(()=>new Map((de??[]).map(f=>[f.id,f])),[de]);o.useEffect(()=>{G&&I&&I.updatedAt>=G.updatedAt&&K(null)},[G,I]);const se=f=>{K(f)},ye=async()=>{if(!k)return;const f=ct.has(k.status);if(await a({title:s.taskDetail.cancelConfirmTitle(k.id),...f?{body:s.taskDetail.cancelConfirmBodyTerminal}:{},confirmLabel:s.taskDetail.cancelConfirmLabel,cancelLabel:s.common.backText})){m(!0);try{const B=await E.tasks.update(k.id,{status:"cancelled"});se(B),r({kind:"success",title:B.status==="cancelled"?s.taskDetail.cancelledToastTitle:s.taskDetail.cancelCleanupToastTitle})}catch(B){r({kind:"error",title:s.taskDetail.cancelFailedTitle,body:B instanceof Error?B.message:String(B)})}finally{m(!1)}}},ve=async(f,H)=>{u(!0);try{const B=H===void 0?await E.tasks.review(f.id):await E.tasks.review(f.id,H);se(B),b(!1);const he=Ce(B.phase)?B.specReviewRound??0:B.reviewRound;r({kind:"success",title:s.agents.reReviewStarted(he)})}catch(B){r({kind:"error",title:s.agents.reReviewStartFailed,body:B instanceof Error?B.message:String(B)})}finally{u(!1)}},we=async()=>{var H;if(!k)return;if(It(k)){v(k.phase??"spec"),S(k.replyActorId??""),y(((H=k.prNumber)==null?void 0:H.toString())??""),b(!0);return}await a({title:s.agents.confirmReReviewTitle,body:s.agents.confirmReReviewBody(k.id),confirmLabel:s.agents.confirmReReviewLabel})&&await ve(k)},P=async()=>{if(!(!k||!await a({title:s.taskDetail.retryConfirmTitle(k.id),body:k.status==="merged"?s.taskDetail.retryConfirmBodyMerged:s.taskDetail.retryConfirmBodyDefault,confirmLabel:s.common.retry}))){h(!0);try{const H=await E.tasks.retry(k.id);r({kind:"success",title:s.taskDetail.retryCreatedToastTitle(H.id)}),n(Fe(H.projectId,H.id))}catch(H){r({kind:"error",title:s.taskDetail.retryFailedTitle,body:H instanceof Error?H.message:String(H)})}finally{h(!1)}}},N=async()=>{if(k&&await a({title:s.taskDetail.markCompleteConfirmTitle,body:s.taskDetail.markCompleteConfirmBody(k.prNumber??0),confirmLabel:s.taskDetail.markComplete})){R(!0);try{const f=await E.tasks.complete(k.id);se(f),r({kind:"success",title:s.taskDetail.markCompleteToastTitle})}catch(f){r({kind:"error",title:s.taskDetail.markCompleteFailedTitle,body:f instanceof Error?f.message:String(f)})}finally{R(!1)}}},M=async()=>{if(k&&await a({title:s.taskDetail.continueConfirmTitle,body:s.taskDetail.continueConfirmBody(k.reviewRound+1),confirmLabel:s.taskDetail.continueRound})){D(!0);try{const f=await E.tasks.continue(k.id);se(f),r({kind:"success",title:s.taskDetail.continuedToastTitle(f.reviewRound)})}catch(f){r({kind:"error",title:s.taskDetail.continueFailedTitle,body:f instanceof Error?f.message:String(f)})}finally{D(!1)}}},F=async(f,H)=>{if(k){Q(!0);try{const B=await E.tasks.spec(k.id,f);se(B),te(""),r({kind:"success",title:H.success})}catch(B){r({kind:"error",title:H.failure,body:B instanceof Error?B.message:String(B)})}finally{Q(!1)}}},ae=async()=>{k&&await a({title:s.taskDetail.specApproveConfirmTitle,body:s.taskDetail.specApproveConfirmBody(k.id),confirmLabel:s.taskDetail.specApprove})&&await F({verdict:"approve"},{success:s.taskDetail.specApprovedToastTitle,failure:s.taskDetail.specApproveFailedTitle})},fe=async()=>{const f=z.trim();f&&await F({verdict:"request-changes",comments:f},{success:s.taskDetail.specRejectedToastTitle,failure:s.taskDetail.specRejectFailedTitle})},O=async()=>{if(k&&await a({title:s.taskDetail.confirmGateConfirmTitle(k.id),body:s.taskDetail.confirmGateConfirmBody,confirmLabel:s.taskDetail.confirmComplete})){R(!0);try{const f=await E.tasks.complete(k.id);se(f),r({kind:"success",title:s.taskDetail.confirmedToastTitle(f.status)})}catch(f){r({kind:"error",title:s.taskDetail.confirmFailedTitle,body:f instanceof Error?f.message:String(f)})}finally{R(!1)}}};return t.jsxs("div",{children:[t.jsx("button",{type:"button",onClick:()=>n(-1),className:"btn-ghost mb-3",children:s.common.back}),ee&&!k&&t.jsx("div",{className:"text-sm text-accent",children:s.common.loadFailed(ee)}),_&&!k&&!ee&&t.jsx("div",{className:"text-sm text-accent",children:s.taskDetail.taskNotFound(e)}),!k&&!ee&&!_&&t.jsx("div",{className:"text-sm text-og-500",children:s.common.loading}),k&&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:k.id}),t.jsx("span",{className:"min-w-0 truncate font-display text-sm font-semibold tracking-tight text-og-1000",title:k.title,children:k.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:C(k)}),t.jsx("aside",{className:"min-w-0 space-y-4",children:ne(k)})]})]}),i&&k&&t.jsx(Zt,{mode:"edit",open:!0,onClose:()=>l(!1),task:k,onUpdated:se}),c&&k&&t.jsx(Ae,{open:!0,title:s.taskDetail.reviewRecoveryTitle,onClose:()=>{p||b(!1)},size:"sm",dismissOnBackdrop:!p,footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",disabled:p,onClick:()=>b(!1),className:"btn-secondary",children:s.common.cancel}),t.jsx("button",{type:"submit",form:"review-recovery-form",disabled:p||A.trim()===""||k.prNumber===void 0&&Sn(j)===void 0,className:"btn-primary",children:p?s.agents.callingReview:s.taskDetail.reviewRecoverySubmit})]}),children:t.jsxs("form",{id:"review-recovery-form",className:"space-y-4",onSubmit:f=>{f.preventDefault();const H=A.trim(),B=k.prNumber??Sn(j);!H||B===void 0||p||ve(k,{stage:w,actorId:H,...k.prNumber===void 0?{prNumber:B}:{}})},children:[t.jsx("p",{className:"text-sm text-og-700",children:s.taskDetail.reviewRecoveryBody}),k.prNumber===void 0&&t.jsxs("div",{children:[t.jsx("label",{htmlFor:"review-recovery-pr-number",className:"mb-1 block text-sm text-og-700",children:s.taskDetail.reviewRecoveryPrNumberLabel}),t.jsx("input",{id:"review-recovery-pr-number",type:"number",min:1,step:1,value:j,required:!0,disabled:p,onChange:f=>y(f.target.value),placeholder:s.taskDetail.reviewRecoveryPrNumberPlaceholder,className:le})]}),t.jsxs("div",{children:[t.jsx("label",{htmlFor:"review-recovery-stage",className:"mb-1 block text-sm text-og-700",children:s.taskDetail.reviewRecoveryStageLabel}),t.jsxs("select",{id:"review-recovery-stage",value:w,required:!0,disabled:p||k.phase!==void 0,onChange:f=>v(f.target.value),className:le,children:[t.jsx("option",{value:"spec",children:s.review.phaseLabel.spec}),t.jsx("option",{value:"code",children:s.review.phaseLabel.code})]})]}),t.jsxs("div",{children:[t.jsx("label",{htmlFor:"review-recovery-actor",className:"mb-1 block text-sm text-og-700",children:s.taskDetail.reviewRecoveryActorLabel}),t.jsx("input",{id:"review-recovery-actor",value:A,required:!0,disabled:p||k.replyActorStatus==="verified"&&k.replyActorId!==void 0,onChange:f=>S(f.target.value),placeholder:s.taskDetail.reviewRecoveryActorPlaceholder,className:le})]})]})})]});function C(f){const H=f.preferredAgentId==="",B=f.status==="approved"&&f.prNumber!==void 0,he=f.status==="merge-ready"&&f.prNumber!==void 0,je=f.status==="spec-ready",ge=f.status==="max_rounds"&&!Ce(f.phase),Ne=f.status==="max_rounds"&&Ce(f.phase),ke=$n(f.prUrl),Le=Ua(ke??void 0,f.branch??"");return t.jsxs("div",{children:[ee&&t.jsx("div",{className:"mb-4 text-sm text-accent",children:s.common.loadFailed(ee)}),f.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:f.branchCleanupPending.reason})]}),f.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:f.branchCleanupSkipped.reason})]}),H&&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:f.status==="pending"?s.taskDetail.legacyPendingNotice:s.taskDetail.legacyReadonlyNotice(s.status[f.status]??f.status)}),t.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-3",children:[t.jsx("span",{className:`${ts[f.status]} text-sm`,title:f.status,children:s.status[f.status]??f.status}),t.jsxs("span",{className:"text-sm text-og-500",children:[s.taskDetail.reviewRoundPrefix,t.jsx("span",{className:"text-og-800",children:f.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:f.specReviewRound??0}),s.taskDetail.specRoundSuffix]})]}),t.jsx("div",{className:"mb-4 flex flex-wrap items-center gap-2",children:ie(f)}),t.jsxs("div",{className:"mb-4 text-sm text-og-500",children:[s.taskDetail.createdAtPrefix,At(f.createdAt,!1),s.taskDetail.updatedAtPrefix,At(f.updatedAt,!1)]}),ue&&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,At(f.reviewDispatchedAt),s.taskDetail.verdictOverdueSuffix]})]}),B&&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}),ke&&t.jsx("a",{href:ke,target:"_blank",rel:"noopener noreferrer",className:"btn-secondary mt-3",children:s.taskDetail.viewPr(f.prNumber??0)})]}),he&&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}),ke&&t.jsx("a",{href:ke,target:"_blank",rel:"noopener noreferrer",className:"btn-secondary mt-3",children:s.taskDetail.viewPr(f.prNumber??0)})]}),je&&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:s.taskDetail.specReadyNotice(f.specReviewRound??0)}),L()]}),ge&&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(f.reviewRound)}),t.jsx("div",{className:"mt-1 text-og-700",children:s.taskDetail.codeMaxRoundsBody})]}),Ne&&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(f.specReviewRound??0)}),t.jsx("div",{className:"mt-1 text-og-700",children:s.taskDetail.specMaxRoundsBody}),L()]}),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:"," ",f.prNumber?ke?t.jsxs("a",{href:ke,target:"_blank",rel:"noopener noreferrer",className:"text-accent hover:text-accent-hover",children:["#",f.prNumber]}):t.jsxs("span",{className:"font-mono text-og-800",children:["#",f.prNumber]}):t.jsx("span",{className:"text-og-400",children:"—"})]}),t.jsxs("span",{className:"text-og-500",children:["Branch:"," ",f.branch?Le?t.jsx("a",{href:Le,target:"_blank",rel:"noopener noreferrer",className:"font-mono text-accent hover:text-accent-hover",children:f.branch}):t.jsx("span",{className:"font-mono text-og-800",children:f.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:f.description||t.jsx("span",{className:"text-og-400",children:s.taskDetail.noDescription})}),t.jsx(Ha,{task:f})]})}function L(){return t.jsxs("div",{className:"mt-3 flex flex-col gap-2",children:[t.jsx("textarea",{value:z,onChange:f=>te(f.target.value),placeholder:s.taskDetail.specCommentsPlaceholder,rows:3,disabled:$,className:le}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",disabled:$,onClick:ae,className:"btn-primary",children:$?s.taskDetail.submitting:s.taskDetail.specApproveButton}),t.jsx("button",{type:"button",disabled:$||z.trim()==="",onClick:fe,title:z.trim()===""?s.taskDetail.specRejectTitleEmpty:s.taskDetail.specRejectTitleReady("Dev"),className:"btn-secondary",children:$?s.taskDetail.submitting:s.taskDetail.specReject})]})]})}function ne(f){if(V===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 H=V.find(ge=>ge.id===f.projectId),B=(H==null?void 0:H.agent.find(ge=>ge.some(Ne=>Ne.id===f.devAgentId)))??(f.qaAgentId?H==null?void 0:H.agent.find(ge=>ge.some(Ne=>Ne.id===f.qaAgentId)):void 0),he=B==null?void 0:B.find(ge=>ge.role==="dev"&&ge.id===f.devAgentId),je=f.qaAgentId?B==null?void 0:B.find(ge=>ge.role==="qa"&&ge.id===f.qaAgentId):void 0;return!he&&!je?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:[he?Y(f,he):t.jsx(Tn,{role:"dev"}),je?Y(f,je):t.jsx(Tn,{role:"qa"})]})}function Y(f,H){const B=pe.get(H.id),he=B??{id:H.id,projectId:f.projectId,runtimeStatus:"unknown",tmuxSessionStatus:"unknown",stale:!0};return t.jsx(Zn,{agent:he,projectId:f.projectId,role:H.role,runtime:H.runtime,model:H.model,pendingRestart:Z&&!B,terminalLoading:!Z&&!B&&!X,showTaskBinding:!1,terminalMode:"embedded-full",active:me===H.id,onActivate:()=>be(H.id),task:f},H.id)}function ie(f){const H=f.status==="max_rounds",B=H&&!Ce(f.phase),he=H&&Ce(f.phase),je=f.status==="merge-ready",ge=f.status==="pending",Ne=(kn.has(f.status)||he)&&!!f.preferredAgentId,ke=(f.prNumber!==void 0||f.branch!==void 0&&It(f))&&f.status!=="pending"&&!ct.has(f.status),Le=B&&f.prNumber!==void 0,tt=Le&&!!f.agentId,nt=f.preferredAgentId==="";return t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",disabled:!ge,onClick:()=>l(!0),className:"btn-secondary",children:s.common.edit}),t.jsx("button",{type:"button",disabled:d,onClick:ye,title:s.taskDetail.cancelForceTitle,className:"btn-secondary",children:d?s.taskDetail.cancelling:s.common.cancel}),!B&&t.jsx("button",{type:"button",disabled:!Ne||g,onClick:P,title:kn.has(f.status)||he?nt?s.taskDetail.retryDisabledLegacyTitle:s.taskDetail.retryEnabledTitle:s.taskDetail.retryDisabledStatusTitle(s.status[f.status]??f.status),className:"btn-secondary",children:g?s.common.retrying:s.common.retry}),t.jsx("button",{type:"button",disabled:!ke||p,onClick:we,title:ct.has(f.status)?s.taskDetail.reviewTerminalTitle:ke?s.taskDetail.reviewButtonTitle:s.taskDetail.reviewNoPrTitle,className:"btn-secondary",children:p?s.agents.callingReview:s.agents.callReview}),B&&t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",disabled:!tt||T,onClick:M,title:s.taskDetail.continueButtonTitle,className:"btn-secondary",children:T?s.taskDetail.continuing:s.taskDetail.continueRound}),t.jsx("button",{type:"button",disabled:!Le||x,onClick:N,title:s.taskDetail.completeButtonTitle,className:"btn-primary",children:x?s.taskDetail.completing:s.taskDetail.markComplete})]}),je&&t.jsx("button",{type:"button",disabled:x,onClick:O,title:s.taskDetail.confirmButtonTitle,className:"btn-primary",children:x?s.taskDetail.confirming:s.common.confirm})]})}}function Tn({role:e}){const n=q();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 za(){const{agentId:e}=xt(),{projects:n}=et(),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:Ln(e,s),children:e})]}),t.jsx("div",{className:"min-h-0 flex-1",children:t.jsx(Ke,{agentId:e,mode:"full",interactive:!0,arrowKeys:!0})})]}):t.jsx("div",{className:"text-sm text-accent",children:"No agent specified"})}const Wa=65536,Qa=8e3,Ka=["text-[18px] font-bold","text-[17px] font-bold","text-[16px] font-semibold","text-[15px] font-semibold","text-[15px] font-semibold","text-[15px] font-semibold"],Va=/^(https?:\/\/|mailto:)/i,Ya=/^https?:\/\//i;function Ja(e){try{const n=new URL(e).hostname.toLowerCase();return n==="githubusercontent.com"||n.endsWith(".githubusercontent.com")}catch{return!1}}function Xa({src:e,alt:n}){const s=q(),[r,a]=o.useState(!1);if(r||Ja(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 Nn(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 Za(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 Rn(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 ws extends Error{}class ei{constructor(n){oe(this,"count",0);this.max=n}charge(){if(++this.count>this.max)throw new ws}}function Oe(e,n,s){const r=[];let a="",i=0;const l={bracket:Nn(e,"]"),paren:Nn(e,")"),whitespace:Za(e)},d=()=>{a!==""&&(n.charge(),r.push(a),a="")},m=h=>{d(),n.charge(),r.push(h)},g=()=>`${s}-${r.length}`;for(;i<e.length;){const h=e[i];if(h==="`"){const p=e.indexOf("`",i+1);if(p!==-1){const u=e.slice(i+1,p);d(),n.charge(),n.charge(),r.push(t.jsx("code",{className:"rounded bg-og-25 px-1 font-mono text-xs",children:u},g())),i=p+1;continue}}else if(h==="!"&&e[i+1]==="["){const p=Rn(e,i+1,l);if(p){Ya.test(p.url)?m(t.jsx(Xa,{src:p.url,alt:p.label},g())):a+=e.slice(i,p.end),i=p.end;continue}}else if(h==="["){const p=Rn(e,i,l);if(p){if(Va.test(p.url)){d(),n.charge();const u=Oe(p.label,n,`${s}-a${r.length}`);r.push(t.jsx("a",{href:p.url,target:"_blank",rel:"noopener noreferrer",className:"text-accent hover:text-accent-hover",children:u},g()))}else a+=e.slice(i,p.end);i=p.end;continue}}else if(h==="*"){if(e.startsWith("***",i)){const u=e.indexOf("***",i+3);if(u>i+3){d(),n.charge(),n.charge();const c=Oe(e.slice(i+3,u),n,`${s}-bi${r.length}`);r.push(t.jsx("strong",{children:t.jsx("em",{children:c})},g())),i=u+3;continue}}if(e.startsWith("**",i)){const u=e.indexOf("**",i+2);if(u>i+2){d(),n.charge();const c=Oe(e.slice(i+2,u),n,`${s}-b${r.length}`);r.push(t.jsx("strong",{children:c},g())),i=u+2;continue}}const p=e.indexOf("*",i+1);if(p>i+1){d(),n.charge();const u=Oe(e.slice(i+1,p),n,`${s}-i${r.length}`);r.push(t.jsx("em",{children:u},g())),i=p+1;continue}}a+=h,i++}return d(),r}function ti(e,n){const s=[],r=e.split(`
12
- `);let a=[];const i=()=>{if(a.length===0)return;const l=a;a=[],n.charge();const d=[];l.forEach((m,g)=>{g>0&&(n.charge(),d.push(t.jsx("br",{},`br-${s.length}-${g}`))),d.push(...Oe(m,n,`p${s.length}-l${g}`))}),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 g=[];let h=l+1;for(;h<r.length&&!/^```\s*$/.test(r[h]);)g.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:g.join(`
13
- `)})},`pre-${s.length}`)),l=h;continue}const m=/^(#{1,6}) (.*)$/.exec(d);if(m){i(),n.charge();const g=m[1].length,h=`h${g}`;s.push(t.jsx(h,{className:Ka[g-1],children:Oe(d,n,`h${s.length}`)},`h-${s.length}`));continue}if(d.trim()===""){i();continue}a.push(d)}return i(),s}function ni(e){if(typeof e!="string")return[];if(e.length>Wa)return null;const n=new ei(Qa);try{return n.charge(),ti(e.replace(/\r\n/g,`
14
- `),n)}catch(s){if(s instanceof ws)return null;throw s}}function si({text:e}){const n=o.useMemo(()=>ni(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})}const ri={approve:"approve","request-changes":"request-changes",comment:"comment"};function ai(e){return e==="no-pr"||e==="driver-unavailable"?e:void 0}function ii(e){return{"no-pr":e.prReview.reasonNoPr,"driver-unavailable":e.prReview.reasonDriverUnavailable}}function js(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 oi(){const e=q(),{taskId:n=""}=xt(),s=Pe(),{hash:r}=An(),{data:a}=ds(n),i=a?vs(a):void 0,{data:l,loaded:d,error:m}=ys(n,i),[g,h]=o.useState(null),p=(l==null?void 0:l.prNumber)??(a==null?void 0:a.prNumber),u=(l==null?void 0:l.prUrl)??(a==null?void 0:a.prUrl),c=$n(u),b=l?xs(l.items):[],w=d&&!m&&(l==null?void 0:l.available)===!0&&l.items.length>0,v=Ce(a==null?void 0:a.phase)?e.prReview.specReviewHeading:e.prReview.codeReviewHeading,A=o.useRef(null),S=o.useRef(void 0);return o.useEffect(()=>()=>clearTimeout(S.current),[]),o.useEffect(()=>{let j=null;if(r)try{j=decodeURIComponent(r.slice(1))}catch{j=null}if(!j){A.current=null,h(null);return}if(A.current===j||!w||!l)return;const y=document.getElementById(j);y&&(A.current=j,y.scrollIntoView({behavior:"smooth",block:"center"}),h(j),clearTimeout(S.current),S.current=setTimeout(()=>h(null),2e3))},[w,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:v}),c&&p!==void 0&&t.jsx("a",{href:c,target:"_blank",rel:"noopener noreferrer",className:"text-accent hover:text-accent-hover",children:e.taskDetail.viewPr(p)})]}),!d&&t.jsx("div",{className:"text-sm text-og-500",children:e.common.loading}),d&&m&&t.jsx("div",{className:"text-sm text-accent",children:e.review.loadFailed(m)}),d&&!m&&l&&!l.available&&t.jsx("div",{className:"text-sm text-og-500",children:ii(e)[ai(l.reason)??"no-pr"]}),d&&!m&&(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:b.map((j,y)=>t.jsx(li,{round:j,index:y,flashId:g},bs(j,String(y))))})]}))]})}function li({round:e,index:n,flashId:s}){const r=q(),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(Cn,{item:i,flashId:s},Xe(i,`${n}-${l}`)):t.jsx(ci,{item:i,flashId:s},Xe(i,`${n}-${l}`))),e.review&&t.jsx(Cn,{item:e.review,flashId:s})]})]})}function ks(e,n){const s=yt(e);return`card p-3 text-sm${s&&s===n?" ring-2 ring-accent":""}`}function ci({item:e,flashId:n}){const s=q(),r=e.kind==="review-comment";return t.jsxs("div",{id:yt(e),className:ks(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:js(e.createdAt)})]}),t.jsx(Ss,{item:e})]})}function Cn({item:e,flashId:n}){const s=q(),r=e.verdict??"comment";return t.jsxs("div",{id:yt(e),className:ks(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:gs[r],children:ri[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:js(e.createdAt)})]}),t.jsx(Ss,{item:e,placeholder:s.prReview.noReviewBody})]})}function Ss({item:e,placeholder:n}){const s=q();return t.jsxs(t.Fragment,{children:[e.body?t.jsx("div",{className:"text-og-800",children:t.jsx(si,{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 di(){const e=q(),[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 ui(){const[e,n]=o.useState(null),[s,r]=o.useState(!1),[a,i]=o.useState(null);return o.useEffect(()=>Ze().subscribe("pollers",d=>{i(null),n(d),r(!0)},d=>i(d)),[]),{data:e,loaded:s,error:a}}function mi(e){return e.lastErrorClass==="RATE_LIMIT"&&e.rateLimitedUntil!==void 0&&Date.parse(e.rateLimitedUntil)>Date.now()}function hi(e){const n=e.find(a=>a.health==="failed");if(n)return{poller:n,kind:"failed"};const s=e.find(mi);if(s)return{poller:s,kind:"rate-limited"};const r=e.find(a=>a.health==="degraded");return r?{poller:r,kind:"degraded"}:null}function pi(){const e=q(),{data:n}=ui();if(!n)return null;const s=hi(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 fi(){const e=q(),{phase:n,count:s,error:r,triggerRestart:a}=vt();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 gi=new Set(["done","merged"]);function $t(e,n){const s=e.trim().replace(/\s+/g," ");return s.length>n?`${s.slice(0,n-1)}…`:s}function xi(e,n){return e?e.repo?`${e.id} · ${e.repo}`:e.id:n}function bi(e){return e.title?`${e.id} · ${e.title}`:e.id}function vi(e){return gi.has(e)}function yi(e,n,s){const r=tn();if(!(!r||r.permission!=="granted"))try{const a=Vt(),i=new r(a.notification.taskDone($t(e.title||e.id,80)),{body:[a.notification.bodyProject($t(n,120)),a.notification.bodyTask($t(bi(e),120)),a.notification.bodyStatus(_r(e.status))].join(`
15
- `),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 wi(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),m=o.useRef(new Map),g=o.useRef(n),h=o.useRef(new Map),p=o.useMemo(()=>s?(e??[]).map(u=>u.id).sort().join("\0"):"",[s,e]);o.useEffect(()=>{g.current=n},[n]),o.useEffect(()=>{h.current=new Map((e??[]).map(u=>[u.id,xi(u,u.id)]))},[e]),o.useEffect(()=>{const u=v=>{m.current.set(v,(m.current.get(v)??0)+1)};if(p===""){for(const v of d.current)u(v);d.current=new Set,r.current.clear(),i.current.clear(),l.current.clear();return}const c=p.split("\0"),b=new Set(c);for(const v of d.current)b.has(v)||u(v);d.current=b;for(const v of r.current.keys())b.has(v)||r.current.delete(v);for(const v of i.current.keys())b.has(v)||i.current.delete(v);const w=c.map(v=>Ze().subscribe(`project-tasks:${v}`,A=>{const S=r.current.get(v),j=new Map(A.map(x=>[x.id,x]));r.current.set(v,j);const y=i.current.get(v)??new Set;if(i.current.set(v,y),!S){for(const x of j.keys())y.delete(x);return}for(const[x]of S)j.has(x)||a.current.has(x)||y.add(x);for(const x of[...y]){if(j.has(x)){y.delete(x);continue}const R=m.current.get(v)??0,T=`${v}:${R}:${x}`;l.current.has(T)||(l.current.add(T),E.tasks.get(x).then(D=>{if((m.current.get(v)??0)!==R)return;if(!D||D.projectId!==v||!vi(D.status)){y.delete(x);return}y.delete(x),a.current.add(D.id);const $=h.current.get(v)??v;yi(D,$,()=>g.current(D))}).catch(D=>{console.warn(`[task-notifications] failed to confirm completed task ${x}:`,D)}).finally(()=>{l.current.delete(T)}))}},A=>{console.warn(`[task-notifications] project task stream failed for ${v}:`,A)}));return()=>{for(const v of w)v()}},[p])}function ji(){const e=An(),n=Pe(),{projects:s}=et(),{enabled:r}=os(),a=!e.pathname.startsWith("/terminal/");return Ys(),wi(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(He,{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:ls,className:"ml-auto flex min-w-0 items-center justify-end gap-2"})]}),t.jsx(fi,{}),t.jsx(pi,{}),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($s,{children:[t.jsx(ze,{path:"/",element:t.jsx(ga,{})}),t.jsx(ze,{path:"/project/:id",element:t.jsx(Ra,{})}),t.jsx(ze,{path:"/project/:id/task/:taskId",element:t.jsx(qa,{})}),t.jsx(ze,{path:"/terminal/:agentId",element:t.jsx(za,{})}),t.jsx(ze,{path:"/tasks/:taskId/pr-review",element:t.jsx(oi,{})})]}),a&&t.jsx("footer",{className:"mt-auto flex justify-center pb-4 pt-24",children:t.jsx(di,{})})]})]})}function ki(){return t.jsx(Ds,{children:t.jsx(oa,{children:t.jsx(ji,{})})})}function Si({children:e}){const n=q(),[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 E.config.get();Mt(d.language),r({kind:"authorized"})}catch(d){if(d instanceof Ue&&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(ut,d),()=>window.removeEventListener(ut,d)},[]),s.kind==="authorized")return t.jsx(t.Fragment,{children:e});if(s.kind==="error")return t.jsxs(Ut,{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(Ut,{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(Ti,{message:l,onSubmit:async d=>{Os(d);try{const m=await E.config.get();Mt(m.language),r({kind:"authorized"})}catch(m){if(Hs(),m instanceof Ue&&m.status===401){r({kind:"unauthorized",reason:"invalid"});return}r({kind:"error",message:m instanceof Error?m.message:void 0,fallback:"loginFailed"})}}})}function Ut({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 Ti({message:e,onSubmit:n}){const s=q(),[r,a]=o.useState(""),[i,l]=o.useState(!1),[d,m]=o.useState(void 0),g=async p=>{p.preventDefault();const u=r.trim();if(!u){m(s.auth.tokenRequired);return}m(void 0),l(!0);try{await n(u)}finally{l(!1)}},h=d??e;return t.jsxs(Ut,{title:s.auth.loginTitle,children:[t.jsx("p",{className:"mb-4 text-sm text-og-600",children:s.auth.loginDescription}),t.jsxs("form",{onSubmit:p=>{g(p)},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:p=>a(p.target.value),className:`${le} 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})]})]})}Ps.createRoot(document.getElementById("root")).render(t.jsx(o.StrictMode,{children:t.jsx(Vs,{children:t.jsx(or,{children:t.jsx(er,{children:t.jsx(nr,{children:t.jsx(Si,{children:t.jsx(ki,{})})})})})})}));