baxian 2.0.13 → 2.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/agent/manager.d.ts +1 -11
  2. package/dist/agent/manager.d.ts.map +1 -1
  3. package/dist/agent/manager.js +16 -77
  4. package/dist/agent/manager.js.map +1 -1
  5. package/dist/agent/phase-signal-watcher.js +1 -1
  6. package/dist/agent/phase-signal-watcher.js.map +1 -1
  7. package/dist/agent/phase-signal.d.ts +1 -4
  8. package/dist/agent/phase-signal.d.ts.map +1 -1
  9. package/dist/agent/phase-signal.js +6 -25
  10. package/dist/agent/phase-signal.js.map +1 -1
  11. package/dist/agent/prompt.js +3 -3
  12. package/dist/agent/prompt.js.map +1 -1
  13. package/dist/api/tasks.d.ts.map +1 -1
  14. package/dist/api/tasks.js +0 -4
  15. package/dist/api/tasks.js.map +1 -1
  16. package/dist/event/handlers.d.ts.map +1 -1
  17. package/dist/event/handlers.js +1 -41
  18. package/dist/event/handlers.js.map +1 -1
  19. package/dist/platform/feedback.d.ts +2 -2
  20. package/dist/platform/feedback.d.ts.map +1 -1
  21. package/dist/platform/feedback.js +2 -3
  22. package/dist/platform/feedback.js.map +1 -1
  23. package/dist/platform/github-driver.d.ts.map +1 -1
  24. package/dist/platform/github-driver.js +4 -7
  25. package/dist/platform/github-driver.js.map +1 -1
  26. package/dist/platform/markers.d.ts +1 -6
  27. package/dist/platform/markers.d.ts.map +1 -1
  28. package/dist/platform/markers.js +1 -5
  29. package/dist/platform/markers.js.map +1 -1
  30. package/dist/platform/platform-poller.d.ts +0 -2
  31. package/dist/platform/platform-poller.d.ts.map +1 -1
  32. package/dist/platform/platform-poller.js +1 -7
  33. package/dist/platform/platform-poller.js.map +1 -1
  34. package/dist/platform/row-schema.d.ts.map +1 -1
  35. package/dist/platform/row-schema.js +1 -11
  36. package/dist/platform/row-schema.js.map +1 -1
  37. package/dist/platform/types.d.ts +0 -1
  38. package/dist/platform/types.d.ts.map +1 -1
  39. package/dist/platform/types.js +0 -2
  40. package/dist/platform/types.js.map +1 -1
  41. package/dist/shared/constants.d.ts +2 -1
  42. package/dist/shared/constants.d.ts.map +1 -1
  43. package/dist/shared/constants.js +1 -0
  44. package/dist/shared/constants.js.map +1 -1
  45. package/dist/shared/types.d.ts +0 -3
  46. package/dist/shared/types.d.ts.map +1 -1
  47. package/dist/shared/types.js.map +1 -1
  48. package/dist/state/task-store.d.ts.map +1 -1
  49. package/dist/state/task-store.js +5 -9
  50. package/dist/state/task-store.js.map +1 -1
  51. package/dist/web/assets/index-BFjlgPUQ.js +17 -0
  52. package/dist/web/index.html +1 -1
  53. package/package.json +1 -1
  54. package/dist/web/assets/index-DC8a710m.js +0 -17
@@ -0,0 +1,17 @@
1
+ var Os=Object.defineProperty;var _s=(e,n,s)=>n in e?Os(e,n,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[n]=s;var oe=(e,n,s)=>_s(e,typeof n!="symbol"?n+"":n,s);import{r as o,j as t,a as Hs,c as qs}from"./react-BFCkCmbU.js";import{x as Us,a as Gs}from"./xterm-D5X2JljJ.js";import{L as $e,u as Ee,a as Pt,b as qn,B as Ws,R as zs,c as Je}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 Ne({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 sn({ariaLabel:e,children:n,placement:s="down",autoFocusFirstItem:r=!1,menuClassName:a="min-w-[140px]",className:i,disabled:l=!1,triggerRef:c}){const[m,h]=o.useState(!1),g=o.useRef(null),f=o.useRef(null),u=o.useId(),d=o.useId();return o.useEffect(()=>{if(!m)return;const x=w=>{var S,R;const C=w.target;C&&((S=f.current)!=null&&S.contains(C)||(R=g.current)!=null&&R.contains(C)||h(!1))},y=w=>{var C;w.key==="Escape"&&(h(!1),(C=g.current)==null||C.focus())};return document.addEventListener("mousedown",x),document.addEventListener("keydown",y),()=>{document.removeEventListener("mousedown",x),document.removeEventListener("keydown",y)}},[m]),o.useEffect(()=>{var y;if(!m||!r)return;const x=(y=f.current)==null?void 0:y.querySelector('[role="menuitem"]:not([disabled])');x==null||x.focus()},[m,r]),t.jsxs("div",{className:`relative ${i??""}`,children:[t.jsx("button",{ref:x=>{g.current=x,c&&(c.current=x)},id:d,type:"button",onClick:()=>h(x=>!x),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:f,id:u,role:"menu","aria-labelledby":d,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 x;h(!1),(x=g.current)==null||x.focus()})})]})}function Be(e){return e==="spec"}function Un(e){var n;return e.prNumber===void 0||e.phase===void 0||((n=e.deliveryConfirmation)==null?void 0:n.phase)!==e.phase}const Vs={"claude-code":"Claude Code",codex:"Codex",opencode:"OpenCode",qodercli:"Qoder CLI"},Ks={"claude-code":"--permission-mode bypassPermissions",codex:"--dangerously-bypass-approvals-and-sandbox",opencode:"--auto",qodercli:"--dangerously-skip-permissions"};function Gn(e,n){const s=[e?Vs[e]:null,n||null].filter(Boolean);return s.length>0?s.join(" · "):null}function Wn(e,n,s){const r=Gn(n,s);return r?`${e} (${r})`:e}const zn=new Set(["merged","done","failed","cancelled"]),rn=new Set(["in_progress","review","fixing","spec-ready","approved","merge-ready","max_rounds"]),Bt=20,Lt=5*1024*1024,pt=4;function Vn(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 Ys=1536,Qs=1872,Kn=192,Yn=208,Ke="/api",an="baxian.token",jt="baxian:unauthorized";function on(){try{return typeof localStorage<"u"?localStorage.getItem(an):null}catch{return null}}function Js(e){try{localStorage.setItem(an,e)}catch(n){console.error("Failed to save auth token to localStorage",n)}}function Xs(){try{localStorage.removeItem(an)}catch(e){console.error("Failed to clear auth token from localStorage",e)}}function Oe(e){const n=on();return{...e??{},...n?{Authorization:`Bearer ${n}`}:{}}}class Ve extends Error{constructor(n,s,r){super(s),this.status=n,this.details=r,this.name="ApiError"}}function Zs(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 _e(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=Zs(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(jt)),new Ve(e.status,s,r)}async function Te(e){const n=await fetch(`${Ke}${e}`,{headers:Oe()});return n.ok||await _e(n),n.json()}async function er(){const e=await fetch("/health");return e.ok||await _e(e),e.json()}async function pe(e,n,s){const r=n!==void 0,a=await fetch(`${Ke}${e}`,{method:"POST",headers:r?Oe({"Content-Type":"application/json"}):Oe(),body:r?JSON.stringify(n):void 0,signal:s==null?void 0:s.signal});return a.ok||await _e(a),a.json()}async function Mt(e,n,s){const r=await fetch(`${Ke}${e}`,{method:"PATCH",headers:Oe({"Content-Type":"application/json"}),body:n?JSON.stringify(n):void 0,signal:s==null?void 0:s.signal});if(r.ok||await _e(r),r.status===204)return;const a=await r.text();if(a)return JSON.parse(a)}async function yn(e,n){const s=await fetch(`${Ke}${e}`,{method:"PUT",headers:Oe({"Content-Type":"application/json"}),body:JSON.stringify(n??null)});if(s.ok||await _e(s),s.status===204)return;const r=await s.text();if(r)return JSON.parse(r)}async function Xe(e){const n=await fetch(`${Ke}${e}`,{method:"DELETE",headers:Oe()});if(n.ok||await _e(n),n.status===204)return;const s=await n.text();if(s)return JSON.parse(s)}const V=encodeURIComponent;function Qt(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 D={agents:{list:()=>Te("/agents"),get:e=>Te(`/agents/${V(e)}`),stop:e=>Xe(`/agents/${V(e)}/session`),compact:e=>pe(`/agents/${V(e)}/compact`),clear:e=>pe(`/agents/${V(e)}/clear`),probe:(e,n={},s)=>pe("/agents/probe",{mode:e,host:n.host,hostId:n.hostId},s),installTmux:(e,n={})=>pe("/agents/install-tmux",{mode:e,host:n.host,hostId:n.hostId}),uploadImage:async(e,n)=>pe(`/agents/${V(e)}/images`,{dataBase64:await Qt(n)}),setPet:(e,n)=>yn(`/agents/${V(e)}/pet`,{petId:n})},pets:{list:()=>Te("/pets"),create:async(e,n)=>pe("/pets",{petJson:e,spritesheetBase64:await Qt(n)}),remove:e=>Xe(`/pets/${V(e)}`),fetchSpritesheet:async e=>{const n=await fetch(`${Ke}/pets/${V(e)}/spritesheet`,{headers:Oe()});return n.ok||await _e(n),n.blob()}},tasks:{list:async e=>{const n=new Map;for(const s of["active","pending"]){let r=0;for(;;){const a=await D.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=${V(e)}`];return n.category&&s.push(`category=${n.category}`),s.push(`offset=${n.offset??0}`),Te(`/tasks?${s.join("&")}`)},get:e=>Te(`/tasks/${V(e)}`),create:e=>pe("/tasks",e),update:(e,n)=>Mt(`/tasks/${V(e)}`,n),retry:e=>pe(`/tasks/${V(e)}/retry`),advance:(e,n)=>pe(`/tasks/${V(e)}/advance`,n),verdict:(e,n)=>pe(`/tasks/${V(e)}/verdict`,n),prReview:e=>Te(`/tasks/${V(e)}/pr-review`),prReviewRefresh:e=>pe(`/tasks/${V(e)}/pr-review/refresh`)},projects:{list:()=>Te("/projects"),get:e=>Te(`/projects/${V(e)}`),create:e=>pe("/projects",e),delete:e=>Xe(`/projects/${V(e)}`),addAgentTeam:(e,n)=>pe(`/projects/${V(e)}/agents`,n),replaceAgent:(e,n,s)=>yn(`/projects/${V(e)}/agents/${V(n)}`,s),deleteAgent:(e,n)=>Xe(`/projects/${V(e)}/agents/${V(n)}`),resumeAgent:(e,n)=>pe(`/projects/${V(e)}/agents/${V(n)}/resume`),restartRepl:(e,n)=>pe(`/projects/${V(e)}/agents/${V(n)}/restart-repl`),retryAgent:(e,n)=>pe(`/projects/${V(e)}/agents/${V(n)}/retry`),bootstrap:e=>pe(`/projects/${V(e)}/bootstrap`)},hosts:{list:()=>Te("/hosts"),create:e=>pe("/hosts",e),update:(e,n)=>Mt(`/hosts/${V(e)}`,n),delete:e=>Xe(`/hosts/${V(e)}`),check:e=>pe("/hosts/check",e)},config:{get:()=>Te("/config"),patch:e=>Mt("/config",e)},health:{get:er},server:{restart:()=>pe("/restart")}};function ln(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 tr(e){return t.jsxs("svg",{...ln(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 nr(e){return t.jsxs("svg",{...ln(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 sr(e){return t.jsxs("svg",{...ln(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 Qn={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…",technicalDetails:"Technical details"},status:{pending:"Waiting to start",in_progress:"In progress",review:"In review",fixing:"Revising","spec-ready":"Plan awaiting approval",approved:"Running pre-merge checks","merge-ready":"Result awaiting confirmation",merged:"PR merged",done:"Complete",failed:"Couldn’t complete",max_rounds:"Review needs a decision",cancelled:"Cancelled"},statusContext:{pendingUnassigned:"Unassigned",inProgressSpec:"Drafting plan",inProgressCode:"Developing",reviewSpec:"Reviewing plan",reviewCode:"Reviewing code",fixingSpec:"Revising plan",fixingCode:"Revising code",maxRoundsSpec:"Plan review needs a decision",maxRoundsCode:"Code review needs a decision"},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 Teams 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 Team now, or later?",later:"Later",continueAddingAgent:"Continue adding an Agent Team"},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:"Cancel task",stopping:"Cancelling…",restartRuntime:"Restart / retry runtime",openTerminalAction:"Open terminal",openTaskActions:"Open task actions",deleteToRecover:"Delete agent",holdRecovery:{resume:"Recommended action: resolve the cause, then resume the agent.","restart-runtime":"Required recovery: restart or retry the runtime so it can pass the greeting capability check again.",terminal:"Required recovery: open the terminal and dismiss the startup dialog; baxian resumes automatically.",task:"Required recovery: open the task and use Advance, Verdict, or Cancel.","delete-agent":"Required recovery: cancel the task or delete and recreate the agent; Resume cannot safely recover this state."},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 Team containing ${e}?`,deleteConfirmBody:"All agents in this Agent Team will be removed. This action cannot be undone.",deletedWithTeamTitle:e=>`Deleted the Agent Team containing ${e}`,deletedWithTeamBody:e=>`The Agent Team member ${e} was removed as well.`,deletedTitle:e=>`Agent ${e} deleted`,agentPetMenuItemTitle:"Configure Agent Pet (shows an animated pet in place of the status badge).",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",mergeStrategyLabel:"Merge method",mergeHumanLabel:"Merge manually (default)",mergeAutoLabel:"Merge automatically after review",specApprovalLabel:"Plan approval",specApprovalHumanLabel:"Require your approval (default)",specApprovalAutoLabel:"Start development automatically after plan review",createdToastTitle:e=>`Project ${e} created`},createAgent:{modalTitle:e=>`Add Agent Team to ${e}`,submitLabel:"Add Agent Team",continueLabel:"Continue to QA",submitting:"Adding Agent Team…",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)",teamDevLabel:e=>`In the same Agent Team as 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 Team ${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 Team",deleteAgentsFirstHint:e=>`Delete the project's ${e} agent${e===1?"":"s"} first`,deleteProjectMenuItem:"Delete project…",noAgentsYet:"No Agent Teams 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:"Couldn’t cancel the task",cancelForceTitle:"Stops the task and releases its development and review agents",cancelConfirmBodyActive:"Current work will stop and the assigned agents will be released. If a PR has already been published, Baxian will close it and retire the task branch. Run the task again later if you still need the work.",cancelConfirmBodyTerminal:"This task is already finished, so its status will not change. Baxian will only release any agents that are still linked to it.",cancelCleanupToastTitle:"Released the remaining agent links",retryTask:"Run task again",retryConfirmTitle:e=>`Run task ${e} again?`,retryConfirmBodyMerged:"The PR is already merged. Baxian will create a new task with the same title and description and start it from the beginning.",retryConfirmBodyDefault:"Baxian will create a new task and start it from the beginning. This task remains in the history.",retryCreatedToastTitle:e=>`Created task ${e}`,retryFailedTitle:"Couldn’t start the new task",markCompleteConfirmTitle:"Accept the current version and merge?",markCompleteConfirmBody:e=>`PR #${e} will be merged as it is and the task will finish. Any remaining review concerns will not be revised in this task.`,completing:"Finishing…",markCompleteToastTitle:"Accepted the current version; merging the PR",markCompleteFailedTitle:"Couldn’t accept and merge the current version",branchCleanupPendingTitle:"The local task branch was kept for now",branchCleanupPendingBody:"Baxian could not safely remove the local task branch, so it kept the branch to avoid losing work.",branchCleanupSkippedTitle:"The local task branch was kept",branchCleanupSkippedBody:"Baxian deliberately kept the local task branch. You can inspect or remove it later.",continueConfirmTitle:"Continue revising?",continueConfirmBody:e=>`The development agent will start revision round ${e}. Code review starts again when the changes are ready.`,continuing:"Starting revisions…",continuedToastTitle:e=>`Started revision round ${e}`,continueFailedTitle:"Couldn’t start another revision",specApproveConfirmTitle:"Approve the plan and start development?",specApproveConfirmBody:e=>`Task ${e} will start development using this plan.`,specApprove:"Approve plan",specApprovedToastTitle:"Plan approved; development started",specApproveFailedTitle:"Couldn’t approve the plan",specRejectedToastTitle:"Change request sent; the development agent is revising the plan",specRejectFailedTitle:"Couldn’t request plan changes",confirmAndMerge:"Confirm and merge",confirmComplete:"Confirm complete",confirmResult:"Confirm result",confirmAutoMergeTitle:e=>`Confirm and merge PR #${e}?`,confirmAutoMergeBody:e=>`Baxian will merge PR #${e}, finish the task, and release its agents.`,confirmManualCompleteTitle:"Confirm this result is complete?",confirmManualCompleteBody:e=>`Baxian will finish the task and release its agents. PR #${e} will remain open for you to merge on the code platform.`,confirmResultTitle:"Confirm this result?",confirmResultBody:"Project merge settings are unavailable. Confirming may merge the PR immediately, finish the task, and release its agents. Review the PR before continuing.",confirmedMergedToastTitle:"PR merged; task complete",confirmedCompleteToastTitle:"Task marked complete",confirmFailedTitle:"Couldn’t confirm the result",taskNotFound:e=>`Task not found: ${e}`,unassignedPendingNotice:"Choose a development agent with “Edit task”, or start this task from an idle development agent card.",unassignedReadonlyNotice:"No development agent is assigned. This task can only be viewed in its current state.",specReviewRound:e=>`Plan review · round ${e}`,codeReviewRound:e=>`Code review · round ${e}`,createdAtPrefix:"Created ",updatedAtPrefix:" · Updated ",editTask:"Edit task",startTask:"Start task",startReview:"Start review",restartReview:"Restart review",retryCurrentStep:"Retry current step",retryPreMergeCheck:"Retry pre-merge checks",advancing:"Starting…",advanceSucceededTitle:"Current step started",advanceFailedTitle:"Couldn’t start this step",advanceConfirmTitle:e=>`${e}?`,startTaskConfirmBody:(e,n)=>`Task ${e} will start with development agent ${n}.`,startReviewConfirmBody:e=>`The current result for task ${e} will be sent to the review agent. Existing work is kept.`,restartReviewConfirmBody:e=>`The current review for task ${e} will be sent to the review agent again. Existing review records are kept.`,retryCurrentStepConfirmBody:e=>`The current step for task ${e} will be sent to the development agent again. Existing work and review records are kept.`,retryPreMergeConfirmBody:"The development agent will run the pre-merge checks again. The accepted review result will be verified before work continues.",advanceRevokedConfirmTitle:"Check the PR again and continue finishing?",advanceRevokedRequestChangesBody:"New feedback appeared after the review passed. Baxian will continue only if the accepted result is still valid and no feedback remains unresolved.",advanceRevokedRetryLimitBody:"The pre-merge checks did not finish after several attempts. Baxian will verify the PR and unresolved feedback before trying again.",handleReview:"Handle review",verdictContinue:"Continue revising",verdictComplete:"Accept current version and merge",codeVerdictTitle:"Code review needs your decision",codeVerdictBody:"Automatic review has not produced a usable result. Review the PR, then confirm it or describe what needs to change.",codeCommentsPlaceholder:"What needs to change? Required when requesting changes; optional when confirming",codePass:"Confirm pass",codeRequestChanges:"Request changes",codePassConfirmTitle:"Confirm this code review passed?",codeRejectConfirmTitle:"Send this change request?",codeVerdictConfirmBody:"Your decision will be recorded on the PR so the task can continue.",codeVerdictSubmittedTitle:"Review decision saved to the PR",codeVerdictFailedTitle:"Couldn’t save the review decision",approvedBannerTitle:"Code review passed · Running final checks",approvedBannerBody:"The development agent is checking that every review comment has been handled. The task will wait for your confirmation when the checks finish.",viewPr:e=>`View PR #${e}`,mergeReadyBannerTitle:"Review complete · Confirm the result",mergeReadyAutoBody:e=>`All review feedback has been handled. Review PR #${e}; confirming will merge it and finish the task.`,mergeReadyManualBody:e=>`All review feedback has been handled. Confirming will finish the task; you will still need to merge PR #${e} on the code platform.`,mergeReadyLoadingBody:"Loading the project’s merge setting. Confirmation will be available when it is ready.",mergeReadyUnknownBody:"The project’s merge setting is unavailable. Confirming may merge the PR immediately; review it before continuing.",specReadyBannerTitle:"Plan ready for your approval",specReadyNotice:e=>`The review agent approved plan round ${e}. Read the plan and review record below. Approving starts development; requesting changes sends your comments back for revision.`,specCommentsPlaceholder:"What needs to change? Required when requesting changes",submitting:"Submitting…",specApproveButton:"Approve plan and start development",specRejectTitleEmpty:"Describe what needs to change first",specRejectTitleReady:"The development agent will revise the plan using these comments",specReject:"Request plan changes",codeMaxRoundsTitle:e=>`Code review still has open questions after ${e} rounds`,codeMaxRoundsBody:"Choose “Continue revising” to address the remaining concerns, or “Accept current version and merge” to merge the PR as it is. Consider a separate task for work that is outside the original scope.",specMaxRoundsTitle:e=>`Plan review still has open questions after ${e} rounds`,specMaxRoundsBody:"Review the discussion below, then approve the current plan or describe what should change. You can also cancel this task or run it again from the beginning.",noDescription:"(No description)",noLinkedAgent:"No linked agent",cancelling:"Cancelling…",retryDisabledUnassignedTitle:"Choose a development agent before running this task again",retryEnabledTitle:"Creates a new task with the same content and starts it from the beginning",reviewRecoveryTitle:"Restore PR review",reviewRecoveryBody:"Use this only when the development agent has already published a PR but the task did not enter review. Add the PR details below to start review.",reviewRecoveryPrNumberLabel:"PR number (required)",reviewRecoveryPrNumberPlaceholder:"For example, 601",reviewRecoveryStageLabel:"PR contains (required)",reviewRecoveryStageSpec:"Plan",reviewRecoveryStageCode:"Code",reviewRecoverySubmit:"Save and start review",continueButtonTitle:"Starts another revision and sends the result back for review",completeButtonTitle:"Accepts the current version and merges the PR without another revision",confirmButtonTitle:"Review the PR before confirming the result",confirmLoadingTitle:"Wait for the project merge setting before confirming",loadingMergeSetting:"Loading merge setting…",confirming:"Confirming…",actionFailedBody:"Refresh the page to confirm the current task status before trying again.",attentionReviewTitle:"Review needs your attention",attentionMergeTitle:"The final checks could not finish",attentionAgentTitle:"The linked agent was interrupted",attentionHandoffTitle:"The next step did not start",attentionDefaultTitle:"This task needs your attention",attentionVerdictGuidance:"Review the PR and the discussion below, then confirm the result or request changes.",attentionAdvanceGuidance:"Check that the linked agent and code platform are available, then retry the current step.",attentionRetryGuidance:"This task cannot continue in its current run. Run it again from the beginning when you are ready.",attentionCancelGuidance:"Review the task details, then cancel it if you no longer want it to continue.",noAgentSlot:e=>e==="dev"?"No development agent":"No review agent"},taskPanel:{ariaLabel:"Task panel",inProgressTitle:"In progress",pendingTitle:"Waiting to start",doneTitle:"Finished",round:e=>`Round ${e}`,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:"Plan review",code:"Code review"},reviewTurnLabel:"Review",responseTurnLabel:"Response",roleUser:"User",roleQa:"Review agent",roleDev:"Development agent"},prReview:{reasonNoPr:"This task does not have a PR yet. Code review records will appear after the PR is created.",reasonDriverUnavailable:"PR review records are unavailable. Check the project’s code-platform configuration.",specReviewHeading:"Plan 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.",fetchedAtLabel:e=>`Fetched at ${e}`,nextCheck:e=>`next check in ≤${e}s`,autoRefreshStopped:"Auto-refresh stopped",refresh:"Refresh",refreshing:"Refreshing…",refreshFailed:e=>`Refresh failed: ${e}`},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 --home <dir> manually.",platformDegraded:e=>`Platform polling degraded for ${e} — reviews and PR updates may lag until connectivity recovers`,platformUnreachable:e=>`Platform unreachable for ${e} — task progress is paused and will resume automatically once connectivity recovers`,platformAccessDenied:(e,n)=>`Platform access denied for ${e} — credentials are invalid or lack permission; task progress stays paused until they are fixed manually.${n?` ${n}`:""}`,platformRateLimited:(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}`}},rr={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,可能需要几分钟,请勿关闭窗口…",technicalDetails:"技术详情"},status:{pending:"待开始",in_progress:"处理中",review:"评审中",fixing:"修改中","spec-ready":"方案待确认",approved:"合并前检查中","merge-ready":"结果待确认",merged:"PR 已合并",done:"已完成",failed:"未能完成",max_rounds:"评审待决定",cancelled:"已取消"},statusContext:{pendingUnassigned:"待分配",inProgressSpec:"方案编写中",inProgressCode:"开发中",reviewSpec:"方案评审中",reviewCode:"代码评审中",fixingSpec:"方案修改中",fixingCode:"代码修改中",maxRoundsSpec:"方案评审待决定",maxRoundsCode:"代码评审待决定"},notification:{taskDone:e=>`任务完成:${e}`,bodyProject:e=>`项目:${e}`,bodyTask:e=>`任务:${e}`,bodyStatus:e=>`状态:${e}`},dashboard:{moreActions:"更多操作",newProject:"新建项目",manageHosts:"Host 管理",newTask:"+ 新建任务",createProjectFirst:"请先创建项目",emptyProjects:'还没有项目。点击右上角"更多"菜单 → "新建项目"开始。',noAgentsYet:"还没有 Agent Team。进入 Details 添加。",detailsLink:"详情 →",detailsAriaLabel:e=>`详情 — ${e}`,tasksLoadFailed:e=>`任务列表加载失败:${e}`,projectCreatedTitle:"项目已创建",addAgentNowOrLater:"现在添加第一个 Agent Team,还是稍后再加?",later:"稍后再加",continueAddingAgent:"继续添加 Agent Team"},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:"取消中…",restartRuntime:"重启 / 重试 Runtime",openTerminalAction:"打开终端处理",openTaskActions:"打开任务操作",deleteToRecover:"删除 Agent",holdRecovery:{resume:"建议动作:确认原因已处理后恢复 Agent。","restart-runtime":"指定出路:重启或重试 Runtime,重新完成 greeting 能力检查。",terminal:"指定出路:打开终端关闭启动对话框;baxian 会自动恢复。",task:"指定出路:打开任务页,使用推进 / 裁决 / 取消完成恢复。","delete-agent":"指定出路:取消任务或删除 Agent 重建;Resume 无法安全恢复此状态。"},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 Team?`,deleteConfirmBody:"此 Agent Team 内的所有 Agent 都会被移除,此操作不可撤销。",deletedWithTeamTitle:e=>`已删除包含 Agent ${e} 的 Agent Team`,deletedWithTeamBody:e=>`同一 Agent Team 的 Agent ${e} 也被一并移除。`,deletedTitle:e=>`Agent ${e} 已删除`,agentPetMenuItemTitle:"配置 Agent Pet(在状态位置显示动画宠物)",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 仓库地址",mergeStrategyLabel:"合并方式",mergeHumanLabel:"手动合并(默认)",mergeAutoLabel:"评审通过后自动合并",specApprovalLabel:"方案确认",specApprovalHumanLabel:"需要你确认(默认)",specApprovalAutoLabel:"方案评审通过后自动开始开发",createdToastTitle:e=>`项目 ${e} 已创建`},createAgent:{modalTitle:e=>`添加 Agent Team 到 ${e}`,submitLabel:"添加 Agent Team",continueLabel:"继续配置 QA",submitting:"添加 Agent Team 中…",idTakenGlobalError:"该 id 已被占用(全局唯一)",idPlaceholder:(e,n)=>`${e}-${n}`,roleLabel:"角色",devStepLabel:"Dev Agent(第 1/2 步)",qaStepLabel:"QA Agent(第 2/2 步)",teamDevLabel:e=>`与 Dev Agent ${e} 同属一个 Agent Team`,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 Team ${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 Team",deleteAgentsFirstHint:e=>`请先删除项目下的 ${e} 个 Agent`,deleteProjectMenuItem:"删除项目…",noAgentsYet:"还没有 Agent Team,点击右上角菜单添加。",closeTaskPanel:"关闭任务面板",deleteModalTitle:"删除项目",confirmDeleteButton:"确认删除",deleteBodyLead:"将从 ",deleteBodyMid:" 中移除项目 ",deleteBodySuffix:"。此操作不可撤销,且不会删除 Git 仓库本身。",confirmInputLead:"如需确认,请在下方输入项目 ID ",confirmInputSuffix:":",confirmInputAriaLabel:"输入项目 ID 以确认删除",deletedToastTitle:e=>`项目 ${e} 已删除`},taskDetail:{cancelConfirmTitle:e=>`取消任务 ${e}?`,cancelConfirmLabel:"取消任务",cancelledToastTitle:"任务已取消",cancelFailedTitle:"未能取消任务",cancelForceTitle:"停止任务并释放关联的开发与评审 Agent",cancelConfirmBodyActive:"当前处理会停止,已分配的 Agent 会被释放。如果已经发布 PR,Baxian 还会关闭 PR 并清理任务分支。之后如仍需处理,可以重新执行该任务。",cancelConfirmBodyTerminal:"任务已经结束,状态不会改变。Baxian 只会释放仍与该任务关联的 Agent。",cancelCleanupToastTitle:"已释放残留的 Agent 关联",retryTask:"重新执行任务",retryConfirmTitle:e=>`重新执行任务 ${e}?`,retryConfirmBodyMerged:"PR 已经合并。Baxian 会用相同标题和描述新建任务,并从头开始处理。",retryConfirmBodyDefault:"Baxian 会新建任务并从头开始处理;当前任务仍保留在历史记录中。",retryCreatedToastTitle:e=>`已新建任务 ${e}`,retryFailedTitle:"未能启动新任务",markCompleteConfirmTitle:"接受当前版本并合并?",markCompleteConfirmBody:e=>`PR #${e} 会按当前内容直接合并,任务随后结束;尚未解决的评审意见不会在本任务中继续修改。`,completing:"收尾中…",markCompleteToastTitle:"已接受当前版本,正在合并 PR",markCompleteFailedTitle:"未能接受并合并当前版本",branchCleanupPendingTitle:"本地任务分支暂时保留",branchCleanupPendingBody:"Baxian 暂时无法安全删除本地任务分支,因此保留了分支,避免丢失改动。",branchCleanupSkippedTitle:"本地任务分支已保留",branchCleanupSkippedBody:"Baxian 有意保留了本地任务分支,你可以稍后检查或手动删除。",continueConfirmTitle:"继续修改?",continueConfirmBody:e=>`开发 Agent 将开始第 ${e} 轮修改;改动完成后会重新开始代码评审。`,continuing:"正在开始修改…",continuedToastTitle:e=>`已开始第 ${e} 轮修改`,continueFailedTitle:"未能开始新一轮修改",specApproveConfirmTitle:"批准方案并开始开发?",specApproveConfirmBody:e=>`任务 ${e} 将按当前方案开始开发。`,specApprove:"批准方案",specApprovedToastTitle:"方案已批准,开发已开始",specApproveFailedTitle:"未能批准方案",specRejectedToastTitle:"修改要求已发送,开发 Agent 正在修改方案",specRejectFailedTitle:"未能提交方案修改要求",confirmAndMerge:"确认并合并",confirmComplete:"确认完成",confirmResult:"确认结果",confirmAutoMergeTitle:e=>`确认并合并 PR #${e}?`,confirmAutoMergeBody:e=>`Baxian 会合并 PR #${e}、结束任务并释放关联 Agent。`,confirmManualCompleteTitle:"确认当前结果已完成?",confirmManualCompleteBody:e=>`Baxian 会结束任务并释放关联 Agent;PR #${e} 仍需你在代码平台手动合并。`,confirmResultTitle:"确认当前结果?",confirmResultBody:"项目合并设置暂不可用。确认后可能会立即合并 PR、结束任务并释放关联 Agent;继续前请先检查 PR。",confirmedMergedToastTitle:"PR 已合并,任务已完成",confirmedCompleteToastTitle:"任务已确认完成",confirmFailedTitle:"未能确认结果",taskNotFound:e=>`任务不存在:${e}`,unassignedPendingNotice:"请通过「编辑任务」选择开发 Agent,或从空闲的开发 Agent 卡片开始此任务。",unassignedReadonlyNotice:"任务没有分配开发 Agent,目前只能查看。",specReviewRound:e=>`方案评审 · 第 ${e} 轮`,codeReviewRound:e=>`代码评审 · 第 ${e} 轮`,createdAtPrefix:"创建于 ",updatedAtPrefix:" · 更新于 ",editTask:"编辑任务",startTask:"开始任务",startReview:"开始评审",restartReview:"重新发起评审",retryCurrentStep:"重试当前步骤",retryPreMergeCheck:"重试合并前检查",advancing:"正在开始…",advanceSucceededTitle:"当前步骤已开始",advanceFailedTitle:"未能开始当前步骤",advanceConfirmTitle:e=>`${e}?`,startTaskConfirmBody:(e,n)=>`任务 ${e} 将交给开发 Agent ${n} 开始处理。`,startReviewConfirmBody:e=>`任务 ${e} 的当前结果将交给评审 Agent,已有改动会保留。`,restartReviewConfirmBody:e=>`任务 ${e} 的当前评审会重新交给评审 Agent,已有评审记录会保留。`,retryCurrentStepConfirmBody:e=>`任务 ${e} 的当前步骤会重新交给开发 Agent,已有改动和评审记录会保留。`,retryPreMergeConfirmBody:"开发 Agent 会重新执行合并前检查;继续前,系统会再次确认已通过的评审结果仍然有效。",advanceRevokedConfirmTitle:"重新检查 PR 并继续收尾?",advanceRevokedRequestChangesBody:"评审通过后出现了新反馈。只有评审结果仍然有效、且没有未处理反馈时,Baxian 才会继续。",advanceRevokedRetryLimitBody:"合并前检查多次尝试后仍未完成。Baxian 会先检查 PR 和未处理反馈,再重新尝试。",handleReview:"处理评审",verdictContinue:"继续修改",verdictComplete:"接受当前版本并合并",codeVerdictTitle:"代码评审需要你决定",codeVerdictBody:"自动评审暂未给出可用结果。请先查看 PR,再确认通过或填写修改要求。",codeCommentsPlaceholder:"需要修改什么?要求修改时必填,确认通过时可选",codePass:"确认通过",codeRequestChanges:"要求修改",codePassConfirmTitle:"确认代码评审通过?",codeRejectConfirmTitle:"发送这些修改要求?",codeVerdictConfirmBody:"你的决定会记录到 PR,任务随后继续。",codeVerdictSubmittedTitle:"评审决定已保存到 PR",codeVerdictFailedTitle:"未能保存评审决定",approvedBannerTitle:"代码评审已通过 · 正在做最终检查",approvedBannerBody:"开发 Agent 正在确认所有评审意见都已处理。检查完成后,任务会等待你确认结果。",viewPr:e=>`查看 PR #${e}`,mergeReadyBannerTitle:"评审已完成 · 等待你确认结果",mergeReadyAutoBody:e=>`所有评审意见都已处理。请检查 PR #${e};确认后,Baxian 会合并 PR 并结束任务。`,mergeReadyManualBody:e=>`所有评审意见都已处理。确认后任务会结束;PR #${e} 仍需你在代码平台手动合并。`,mergeReadyLoadingBody:"正在加载项目合并设置,加载完成后才能确认结果。",mergeReadyUnknownBody:"项目合并设置暂不可用。确认后可能会立即合并 PR;继续前请先检查 PR。",specReadyBannerTitle:"方案已就绪,等待你确认",specReadyNotice:e=>`评审 Agent 已通过第 ${e} 轮方案。请查看下方方案和评审记录;批准后开始开发,要求修改后会按你的意见重新调整。`,specCommentsPlaceholder:"需要修改什么?要求修改时必填",submitting:"提交中…",specApproveButton:"批准方案并开始开发",specRejectTitleEmpty:"请先填写需要修改的内容",specRejectTitleReady:"开发 Agent 会根据这些意见修改方案",specReject:"要求修改方案",codeMaxRoundsTitle:e=>`代码评审经过 ${e} 轮仍有待确认问题`,codeMaxRoundsBody:"选择「继续修改」处理剩余问题,或选择「接受当前版本并合并」按现状合并 PR。超出原任务范围的工作建议另建任务。",specMaxRoundsTitle:e=>`方案评审经过 ${e} 轮仍有待确认问题`,specMaxRoundsBody:"请查看下方讨论,然后批准当前方案,或说明还需要修改什么。你也可以取消任务,或从头重新执行。",noDescription:"(无描述)",noLinkedAgent:"暂无关联 Agent",cancelling:"取消中…",retryDisabledUnassignedTitle:"重新执行前,请先选择开发 Agent",retryEnabledTitle:"使用相同内容新建任务并从头开始处理",reviewRecoveryTitle:"恢复 PR 评审",reviewRecoveryBody:"仅在开发 Agent 已经发布 PR、但任务没有进入评审时使用。补充下面的 PR 信息后即可开始评审。",reviewRecoveryPrNumberLabel:"PR 号(必填)",reviewRecoveryPrNumberPlaceholder:"例如 601",reviewRecoveryStageLabel:"PR 内容(必填)",reviewRecoveryStageSpec:"方案",reviewRecoveryStageCode:"代码",reviewRecoverySubmit:"保存并开始评审",continueButtonTitle:"开始新一轮修改,完成后重新评审",completeButtonTitle:"不再修改,接受当前版本并合并 PR",confirmButtonTitle:"确认结果前请先检查 PR",confirmLoadingTitle:"请等待项目合并设置加载完成",loadingMergeSetting:"正在加载合并设置…",confirming:"确认中…",actionFailedBody:"请刷新页面确认任务当前状态,再决定是否重试。",attentionReviewTitle:"评审需要你处理",attentionMergeTitle:"最终检查未能完成",attentionAgentTitle:"关联 Agent 的处理已中断",attentionHandoffTitle:"下一步骤未能开始",attentionDefaultTitle:"任务需要你处理",attentionVerdictGuidance:"请查看 PR 和下方评审记录,然后确认结果或提出修改要求。",attentionAdvanceGuidance:"请确认关联 Agent 和代码平台可用,然后重试当前步骤。",attentionRetryGuidance:"本次任务已经无法继续;准备好后,可以从头重新执行。",attentionCancelGuidance:"请先检查任务详情;如果不再需要继续,可以取消任务。",noAgentSlot:e=>e==="dev"?"暂无开发 Agent":"暂无评审 Agent"},taskPanel:{ariaLabel:"任务面板",inProgressTitle:"处理中",pendingTitle:"待开始",doneTitle:"已结束",round:e=>`第 ${e} 轮`,emptyInProgress:"暂无正在处理的任务",emptyPending:"暂无待处理的任务",collapse:"收起",view:"查看",loadMore:"加载更多",emptyDone:"暂无已处理的任务"},review:{loadExternalImage:"加载外部图片",loadFailed:e=>`加载评审记录失败:${e}`,loadingRecords:"加载评审记录…",notStarted:"评审尚未开始",sectionTitle:"评审记录",phaseLabel:{spec:"方案评审",code:"代码评审"},reviewTurnLabel:"评审",responseTurnLabel:"反馈",roleUser:"用户",roleQa:"评审 Agent",roleDev:"开发 Agent"},prReview:{reasonNoPr:"任务还没有 PR;创建 PR 后,这里会显示代码评审记录。",reasonDriverUnavailable:"暂时无法读取 PR 评审记录,请检查项目的代码平台配置。",specReviewHeading:"方案评审",codeReviewHeading:"代码评审",fetchFailed:e=>`评审记录拉取失败:${e}`,partialFetchFailed:e=>`部分评审记录拉取失败:${e}(仅展示已获取的部分)`,inlineComment:"行内评论",comment:"评论",replyIndicator:"↩ 回复",noReviewBody:"(无评审正文)",bodyTruncated:"内容较大,已截断。",truncatedSuffix:"(已截断)",noReviewBodyFallback:"无评审正文",ghostAuthor:"ghost(账号已注销)",listTruncated:"该 PR 评论过多,仅展示靠前的一部分。",fetchedAtLabel:e=>`数据拉取于 ${e}`,nextCheck:e=>`下次检查 ≤${e} 秒`,autoRefreshStopped:"已停止自动更新",refresh:"刷新",refreshing:"刷新中…",refreshFailed:e=>`刷新失败:${e}`},toast:{dismissAriaLabel:"关闭通知"},banner:{restartFailed:e=>`重启失败:${e}`,restarting:"重启中…",pendingNotice:e=>`有 ${e} 项配置变更待重启 baxian server 才生效`,restartNow:"现在重启",preRestartFetchFailed:e=>`获取重启前 startedAt 失败:${e}`,restartTriggerFailed:e=>`触发重启失败:${e}`,restartTimeout:"重启超时(30s 未恢复)。请检查日志或手动执行 baxian start --home <dir>",platformDegraded:e=>`平台轮询降级(${e})——评审与 PR 更新可能延迟,连通恢复后自动跟上`,platformUnreachable:e=>`平台无法访问(${e})——任务推进暂停,连通恢复后自动继续`,platformAccessDenied:(e,n)=>`平台拒绝访问(${e})——凭证失效或权限不足,任务推进暂停,需人工修复凭证后才会恢复。${n??""}`,platformRateLimited:(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}`}},cn="baxian.language",nt="en-US",Jn={"en-US":Qn,"zh-CN":rr};function Xn(e){return e==="zh-CN"||e==="en-US"}function Zn(){try{const e=localStorage.getItem(cn);return Xn(e)?e:nt}catch{return nt}}function es(e){try{localStorage.setItem(cn,e)}catch{}}let ze=Zn();const Jt=new Set;let Tt=0,ar=0,wn=0;function dn(e){e!==ze&&(ze=e,Jt.forEach(n=>n(e)))}function Xt(e){Tt+=1;const n=e??nt;es(n),dn(n)}function ir(e){const n=e??nt;es(n),dn(n)}function un(){return Jn[ze]}const ts=o.createContext({locale:nt,messages:Qn,saving:!1,setLocale:async()=>{throw new Error("setLocale requires I18nProvider")}});function or({children:e}){const[n,s]=o.useState(ze),[r,a]=o.useState(!1);o.useEffect(()=>{const l=c=>s(c);return Jt.add(l),s(ze),()=>{Jt.delete(l)}},[]),o.useEffect(()=>{document.documentElement.lang=n==="zh-CN"?"zh-CN":"en"},[n]),o.useEffect(()=>{const l=c=>{if(c.key!==null&&c.key!==cn)return;const m=c.key===null?Zn():c.newValue;Xn(m)&&(Tt+=1,dn(m))};return window.addEventListener("storage",l),()=>window.removeEventListener("storage",l)},[]);const i=async l=>{if(l!==ze){a(!0);try{await D.config.patch({language:l}),Xt(l)}finally{a(!1)}}};return t.jsx(ts.Provider,{value:{locale:n,messages:Jn[n],saving:r,setLocale:i},children:e})}function ns(){return o.useContext(ts)}function q(){return ns().messages}function lr(){o.useEffect(()=>{const e=()=>{const s=Tt,r=++ar;D.config.get().then(a=>{s===Tt&&(r<=wn||(wn=r,ir(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 ss=o.createContext(null),cr={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"},dr={success:tr,warn:nr,error:sr};let ur=1;function mr({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,d=i.current;return()=>{for(const x of u.values())clearTimeout(x);u.clear(),d.clear()}},[]);const l=o.useCallback(u=>{const d=a.current.get(u);d&&clearTimeout(d),a.current.delete(u)},[]),c=o.useCallback(u=>{l(u),i.current.delete(u),r(d=>d.filter(x=>x.id!==u))},[l]),m=o.useCallback((u,d)=>{l(u),a.current.set(u,setTimeout(()=>c(u),d))},[l,c]),h=o.useCallback((u,d)=>{const x=i.current.get(u)??new Set;x.add(d),i.current.set(u,x),l(u)},[l]),g=o.useCallback((u,d,x)=>{const y=i.current.get(u);y==null||y.delete(d),(!y||y.size===0)&&m(u,x)},[m]),f=o.useCallback(u=>{const d=ur++,x=u.durationMs??3e3;r(y=>[...y,{...u,id:d,durationMs:x}]),m(d,x)},[m]);return t.jsxs(ss.Provider,{value:{show:f},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 ${cr[u.kind]}`,role:"status",onMouseEnter:()=>h(u.id,"hover"),onMouseLeave:()=>g(u.id,"hover",u.durationMs),onFocus:()=>h(u.id,"focus"),onBlur:d=>{d.currentTarget.contains(d.relatedTarget)||g(u.id,"focus",u.durationMs)},children:t.jsxs("div",{className:"flex items-start gap-2",children:[(()=>{const d=dr[u.kind];return t.jsx(d,{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}),u.details&&t.jsxs("details",{className:"mt-1 text-xs text-og-500",children:[t.jsx("summary",{className:"cursor-pointer select-none text-accent",children:n.common.technicalDetails}),t.jsx("div",{className:"mt-1 whitespace-pre-wrap break-words font-mono",children:u.details})]})]}),t.jsx("button",{type:"button",onClick:()=>c(u.id),className:"text-current opacity-50 transition-opacity hover:opacity-100","aria-label":n.toast.dismissAriaLabel,children:"✕"})]})},u.id))})]})}function ke(){const e=o.useContext(ss);if(!e)throw new Error("useToast must be inside <ToastProvider>");return e}const hr={sm:"max-w-md",md:"max-w-lg",lg:"max-w-2xl"},kn='input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), [href], [tabindex]:not([tabindex="-1"])',Fe=[];function Se({open:e,onClose:n,title:s,titleContent:r,children:a,footer:i,size:l="md",dismissOnBackdrop:c=!0}){const m=q(),h=o.useRef(null),g=o.useRef();g.current||(g.current=Symbol("modal"));const f=o.useRef(null),u=o.useRef(!1),d=o.useRef(n);return o.useEffect(()=>{d.current=n},[n]),o.useEffect(()=>{if(!e)return;const x=g.current;Fe.push(x);const y=()=>Fe[Fe.length-1]===x;f.current=document.activeElement;const w=R=>{if(!y())return;if(R.key==="Escape"){d.current();return}if(R.key!=="Tab")return;const v=h.current;if(!v)return;const b=Array.from(v.querySelectorAll(kn)).filter(I=>I.offsetParent!==null||I===document.activeElement);if(b.length===0){R.preventDefault();return}const j=b[0],k=b[b.length-1],E=document.activeElement;R.shiftKey&&(E===j||!v.contains(E))?(R.preventDefault(),k.focus()):!R.shiftKey&&(E===k||!v.contains(E))&&(R.preventDefault(),j.focus())};document.addEventListener("keydown",w);const C=document.body.style.overflow;document.body.style.overflow="hidden";const S=h.current;if(S){const R=S.querySelector(kn);R==null||R.focus()}return()=>{var v,b;const R=Fe.indexOf(x);R>=0&&Fe.splice(R,1),document.removeEventListener("keydown",w),document.body.style.overflow=C,(b=(v=f.current)==null?void 0:v.focus)==null||b.call(v)}},[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:c?x=>{u.current=x.target===x.currentTarget&&Fe[Fe.length-1]===g.current}:void 0,onClick:c?x=>{x.target===x.currentTarget&&u.current&&d.current()}:void 0,role:"presentation",children:t.jsxs("div",{ref:h,className:`flex w-full ${hr[l]} max-h-[90dvh] flex-col overflow-hidden rounded-lg border border-og-100 bg-surface shadow-modal`,onClick:x=>x.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:()=>d.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 rs=o.createContext(null);function fr({children:e}){const n=q(),[s,r]=o.useState(null),a=o.useRef(null),i=o.useCallback(c=>new Promise(m=>{var g;(g=a.current)==null||g.resolve(!1);const h={...c,resolve:m};a.current=h,r(h)}),[]),l=o.useCallback(c=>{const m=a.current;m&&(a.current=null,r(null),m.resolve(c))},[]);return t.jsxs(rs.Provider,{value:i,children:[e,s&&t.jsx(Se,{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 mn(){const e=o.useContext(rs);if(!e)throw new Error("useConfirm must be inside <ConfirmProvider>");return e}const Nt="baxian.pendingRestart",pr=500,gr=3e4,as=o.createContext(null);function xr(){try{const e=localStorage.getItem(Nt);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 br(e){try{e.count<=0?localStorage.removeItem(Nt):localStorage.setItem(Nt,JSON.stringify(e))}catch{}}function vr({children:e}){const n=q(),s=xr(),[r,a]=o.useState(s.count),[i,l]=o.useState(s.baselineStartedAt),[c,m]=o.useState(s.count>0?"pending":"idle"),[h,g]=o.useState(),f=o.useRef(s.count),u=o.useRef(s.count>0?"pending":"idle"),d=o.useRef(0),x=o.useCallback(v=>{f.current=v,a(v)},[]),y=o.useCallback(v=>{a(b=>{const j=v(b);return f.current=j,j})},[]),w=o.useCallback(v=>{u.current=v,m(v)},[]);o.useEffect(()=>{br({count:r,baselineStartedAt:i})},[r,i]),o.useEffect(()=>{let v=!1;(async()=>{try{const j=await D.health.get();if(v)return;l(k=>k!==null&&j.startedAt!==k?(x(0),w("idle"),null):k)}catch{}})();const b=j=>{if(j.key===Nt){if(j.newValue===null){if(u.current==="restarting"&&d.current>0){x(d.current),l(null);return}x(0),l(null),u.current!=="restarting"&&w("idle");return}try{const k=JSON.parse(j.newValue);typeof k.count=="number"&&(u.current==="restarting"&&k.count>f.current&&(d.current+=k.count-f.current),x(k.count),u.current!=="restarting"&&w(k.count>0?"pending":"idle")),typeof k.baselineStartedAt=="string"?l(k.baselineStartedAt):k.baselineStartedAt===null&&l(null)}catch{}}};return window.addEventListener("storage",b),()=>{v=!0,window.removeEventListener("storage",b)}},[x,w]);const C=o.useRef(!1),S=o.useCallback(()=>{y(v=>v+1),u.current==="restarting"?d.current+=1:w("pending"),l(v=>(v!==null||C.current||(C.current=!0,(async()=>{try{const b=await D.health.get();l(j=>j??b.startedAt)}catch{}finally{C.current=!1}})()),v))},[w,y]),R=o.useCallback(async()=>{d.current=0,g(void 0),w("restarting");let v;try{v=(await D.health.get()).startedAt}catch(j){w("failed"),g(n.banner.preRestartFetchFailed(j instanceof Error?j.message:String(j)));return}try{await D.server.restart()}catch(j){if(!(j instanceof Ve&&j.status===409)){w("failed"),g(n.banner.restartTriggerFailed(j instanceof Error?j.message:String(j)));return}}const b=Date.now();for(;Date.now()-b<gr;){await new Promise(j=>setTimeout(j,pr));try{const j=await D.health.get();if(j.startedAt!==v){const k=d.current;d.current=0,l(k>0?j.startedAt:null),x(k),w(k>0?"pending":"idle");return}}catch{}}w("failed"),g(n.banner.restartTimeout)},[x,w,n]);return t.jsx(as.Provider,{value:{phase:c,count:r,error:h,flagDirty:S,triggerRestart:R},children:e})}function Et(){const e=o.useContext(as);if(!e)throw new Error("usePendingRestart must be used inside PendingRestartProvider");return e}const yr=[500,1e3,2e3,4e3,8e3,15e3,3e4];class is{constructor(n){oe(this,"attempts",0);oe(this,"timer",null);oe(this,"delaysMs");this.opts=n,this.delaysMs=n.delaysMs??yr}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 os(e){return Array.from(new TextEncoder().encode(e)).map(n=>n.toString(16).padStart(2,"0")).join("")}function ls(e){return`${location.protocol==="https:"?"wss":"ws"}://${location.host}${e}`}const cs=(e,n)=>n&&n.length>0?new WebSocket(e,n):new WebSocket(e);let jn=0;function wr(){jn++;const e=Math.random().toString(36).slice(2,8);return`sub-${Date.now().toString(36)}-${jn}-${e}`}function kr(){return ls("/api/stream")}class jr{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??kr(),this.wsFactory=n.wsFactory??cs,this.tokenProvider=n.tokenProvider??on,this.reconnectScheduler=new is({reconnect:()=>this.openSocket(),shouldReconnect:()=>!this.explicitlyClosed&&this.subs.size>0})}subscribe(n){const s=wr(),r={subscriberId:s,agentId:n.agentId,mode:n.mode,onSnapshot:n.onSnapshot,onData:n.onData,onError:n.onError,onSessionGone:n.onSessionGone};return this.subs.set(s,r),this.snapshotPending.add(s),this.preSubscribeQueue.set(s,[]),this.ensureSocket(),this.wsSendOrQueue({op:"subscribe",subscriberId:s,agentId:n.agentId,mode:n.mode}),{subscriberId:s,unsubscribe:()=>this.unsubscribe(s)}}send(n,s){if(this.subs.has(n)){if(this.snapshotPending.has(n)){this.outbox.push({op:"input",subscriberId:n,data:s});return}this.wsSendOrQueue({op:"input",subscriberId:n,data:s})}}resize(n,s,r){const a=this.subs.get(n);a&&(a.lastSize={cols:s,rows:r},!this.snapshotPending.has(n)&&this.wsSendOrQueue({op:"resize",subscriberId:n,cols:s,rows:r}))}ping(){this.wsSendOrQueue({op:"ping"})}close(){if(this.explicitlyClosed=!0,this.reconnectScheduler.cancel(),this.reconnectScheduler.reset(),this.ws){try{this.ws.close()}catch{}this.ws=null}this.subs.clear(),this.snapshotPending.clear(),this.preSubscribeQueue.clear(),this.outbox=[]}unsubscribe(n){this.subs.has(n)&&(this.subs.delete(n),this.snapshotPending.delete(n),this.preSubscribeQueue.delete(n),this.wsSendOrQueue({op:"unsubscribe",subscriberId:n}),this.subs.size===0&&this.teardownSocket())}teardownSocket(){if(this.reconnectScheduler.cancel(),this.reconnectScheduler.reset(),this.outbox=[],this.ws){try{this.ws.close()}catch{}this.ws=null}}ensureSocket(){this.explicitlyClosed||this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING)||this.openSocket()}openSocket(){if(this.explicitlyClosed)return;this.reconnectScheduler.cancel();const n=this.tokenProvider(),s=n?[`baxian.token.${os(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 Ft=null;function Ot(){return Ft||(Ft=new jr),Ft}function Tr(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=Ot().subscribe({agentId:n,mode:s,onSnapshot:h=>a.current.onSnapshot(h),onData:h=>a.current.onData(h),onError:h=>{var g,f;return(f=(g=a.current).onError)==null?void 0:f.call(g,h)},onSessionGone:()=>{var h,g;return(g=(h=a.current).onSessionGone)==null?void 0:g.call(h)}});return r.current=m.subscriberId,()=>{r.current=null,m.unsubscribe()}},[n,s]);const i=o.useCallback(c=>{const m=r.current;m&&Ot().send(m,c)},[]),l=o.useCallback((c,m)=>{const h=r.current;h&&Ot().resize(h,c,m)},[]);return{send:i,resize:l}}const Nr=[{key:"up",path:"M12 5l-6 6m6-6l6 6m-6-6v14"},{key:"down",path:"M12 19l6-6m-6 6l-6-6m6 6V5"},{key:"left",path:"M5 12l6-6m-6 6l6 6m-6-6h14"},{key:"right",path:"M19 12l-6-6m6 6l-6 6m6-6H5"}],gt=Object.fromEntries(Nr.map(e=>[e.key,e]));function xt({arrow:e,ariaLabel:n,onPress:s}){return t.jsx("button",{type:"button","aria-label":n,"data-arrow":e.key,onMouseDown:r=>r.preventDefault(),onClick:()=>s(e.key),className:"flex h-8 w-8 items-center justify-center rounded border border-hairline bg-surface text-og-700 transition-colors hover:bg-og-50 hover:text-og-1000 active:bg-og-200",children:t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:t.jsx("path",{d:e.path})})})}function Sr({onKey:e,onEscape:n,className:s}){const r=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(xt,{arrow:gt.left,ariaLabel:r.terminal.arrowAriaLabel(r.terminal.arrowLabel.left),onPress:e}),t.jsx(xt,{arrow:gt.up,ariaLabel:r.terminal.arrowAriaLabel(r.terminal.arrowLabel.up),onPress:e}),t.jsx(xt,{arrow:gt.down,ariaLabel:r.terminal.arrowAriaLabel(r.terminal.arrowLabel.down),onPress:e}),t.jsx(xt,{arrow:gt.right,ariaLabel:r.terminal.arrowAriaLabel(r.terminal.arrowLabel.right),onPress:e})]})}const Rr=Math.floor(Lt/1024/1024);function Cr({agentId:e,className:n}){const s=q(),r=o.useRef(null),[a,i]=o.useState(!1),{show:l}=ke(),c=async m=>{var g;const h=(g=m.target.files)==null?void 0:g[0];if(m.target.value="",!!h){if(h.size>Lt){l({kind:"error",title:s.createTask.imageTooLargeToastTitle,body:s.imageUpload.tooLargeBody(Rr)});return}i(!0);try{await D.agents.uploadImage(e,h),l({kind:"success",title:s.imageUpload.insertedTitle,body:s.imageUpload.insertedBody})}catch(f){const u=f instanceof Ve||f instanceof Error?f.message:String(f);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:c})]})}const Ar={up:"A",down:"B",right:"C",left:"D"};function Pr(e,n){return(n?"\x1BO":"\x1B[")+Ar[e]}const Tn=18,Lr=250,Er=256*1024,Nn="#fdfdfd",Dr='ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',$r={background:Nn,foreground:"#474c55",cursor:"#1348dc",cursorAccent:Nn,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"},Ir=/\x1b\[(?:\?[\d;]*c|>[\d;]*c|\??\d+;\d+R|\d+n)/g;function Br(e){return e.replace(Ir,"")}const Mr=1024*1024;function Fr(e){const n=e.indexOf(";");if(n===-1)return null;const s=e.slice(n+1);if(s.length===0||s==="?"||s.length>Mr)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 et({agentId:e,mode:n,interactive:s=!1,maxLines:r,className:a,autoFocus:i=!0,deferFullUntilFocus:l=!1,arrowKeys:c=!1}){const m=q(),h=o.useRef(null),g=o.useRef(null),f=o.useRef(null),u=o.useRef(null),d=o.useRef(!1),x=o.useRef(""),y=o.useRef([]),w=o.useRef(0),C=o.useRef(null),S=o.useRef(null),R=o.useRef(null),v=o.useRef(Promise.resolve()),b=o.useRef(0),[j,k]=o.useState(null),[E,I]=o.useState(!1),_=`${e}\0${n}\0${l?"1":"0"}`,[F,ee]=o.useState({key:_,active:!1}),z=F.key===_&&F.active,K=n==="full"&&l,ae=K&&!z?"preview":n,X=s&&ae==="full",te=(T,B)=>B.length===0?Promise.resolve():new Promise(M=>{try{T.write(B,()=>M())}catch(he){console.warn("[pane-terminal] write failed:",he),M()}}),Y=ae==="preview",ne=()=>{var $;if(!Y)return;const T=h.current,B=g.current;if(!T||!B||T.clientHeight<=0)return;const M=(($=T.querySelector(".xterm-screen"))==null?void 0:$.getBoundingClientRect().height)??0,he=M>0&&B.rows>0?M/B.rows:Tn,se=(B.buffer.active.cursorY+1)*he;T.scrollTop=Math.max(0,se-T.clientHeight)},Z=()=>{if(!Y||R.current!==null)return;let T=!1;const B=requestAnimationFrame(()=>{T=!0,R.current=null,ne()});T||(R.current=B)},J=(T,B)=>{v.current=v.current.then(async()=>{const M=g.current;if(!(!M||B!==b.current))try{await T(M),X&&M.scrollToBottom(),Z()}catch(he){console.warn("[pane-terminal] terminal task failed:",he)}}).catch(M=>{console.warn("[pane-terminal] write chain failed:",M)})},me=(T,B)=>{J(M=>te(M,T),B)},ge=()=>{C.current!==null&&(cancelAnimationFrame(C.current),C.current=null),S.current!==null&&(clearTimeout(S.current),S.current=null)},H=()=>{ge(),y.current=[],w.current=0},le=()=>{ge();const T=y.current;T.length!==0&&(y.current=[],w.current=0,me(T.join(""),b.current))},ce=T=>{if(T.length!==0){if(y.current.push(T),w.current+=T.length,w.current>=Er){le();return}C.current===null&&(C.current=requestAnimationFrame(le)),S.current===null&&(S.current=setTimeout(le,Lr))}},{send:ie,resize:we}=Tr({agentId:e,mode:ae,onSnapshot:({cols:T,rows:B,data:M})=>{if(g.current)try{const se=b.current+1;b.current=se,H(),J(async $=>{var A;$.reset(),X?((A=u.current)==null||A.call(u),await te($,M)):(T>0&&B>0&&$.resize(T,B),await te($,M))},se)}catch(se){console.warn("[pane-terminal] snapshot write failed:",se)}},onData:T=>{ce(T)},onError:T=>k(`${T.code}: ${T.message}`),onSessionGone:()=>I(!0)});o.useEffect(()=>{k(null),I(!1)},[e,ae]),o.useEffect(()=>{x.current=""},[_]),o.useEffect(()=>{if(ae!=="full")return;const T=x.current;T.length!==0&&(x.current="",ie(T))},[ie,ae]);const N=o.useCallback(()=>{!s||!K||z||(d.current=!0,ee({key:_,active:!0}))},[_,z,s,K]),xe=o.useCallback(T=>{const B=Br(T);if(B.length!==0){if(K&&(!z||x.current.length>0)){x.current+=B,N();return}ie(B)}},[N,z,ie,K]);o.useEffect(()=>{const T=h.current;if(!T)return;let B=!1;const M=new Us.Terminal({cursorBlink:s,disableStdin:!s,theme:$r,fontFamily:Dr,fontSize:13,lineHeight:1.4,scrollback:ae==="full"?5e3:1e3}),he=new Gs.FitAddon;M.loadAddon(he),M.open(T),g.current=M,f.current=he;const se=Y?M.onRender(()=>Z()):null;if(s&&(i||d.current)){d.current=!1;try{M.focus()}catch{}}s&&(M.onData(xe),ae==="full"&&M.parser.registerOscHandler(52,Re=>{var Ae;const Ce=Fr(Re);return Ce!==null&&((Ae=navigator.clipboard)==null||Ae.writeText(Ce).catch(()=>{})),!0}));const $=()=>T.clientWidth>0&&T.clientHeight>0,A=(Re=!1)=>{if(!$())return!1;const Ce=M.cols,Ae=M.rows;try{he.fit()}catch{return!1}return X&&M.scrollToBottom(),M.cols>0&&M.rows>0&&(Re||M.cols!==Ce||M.rows!==Ae)&&we(M.cols,M.rows),!0};u.current=X?()=>A(!0):null;let L=null,Q=null,W=null,re=0;const ye=()=>{L||(L=new ResizeObserver(()=>{Q&&clearTimeout(Q),Q=setTimeout(()=>{Q=null,X?A():Y&&Z()},100)}),L.observe(T))},He=()=>{W=requestAnimationFrame(()=>{if(W=null,!B){if(!X){Y&&(ye(),Z());return}if(A(!0)){ye();return}if(re++<5){He();return}ye()}})};return He(),()=>{B=!0,W!==null&&cancelAnimationFrame(W),C.current!==null&&(cancelAnimationFrame(C.current),C.current=null),S.current!==null&&(clearTimeout(S.current),S.current=null),R.current!==null&&(cancelAnimationFrame(R.current),R.current=null),b.current++,y.current=[],w.current=0,v.current=Promise.resolve(),Q&&clearTimeout(Q),L==null||L.disconnect(),se==null||se.dispose(),g.current=null,f.current=null,u.current=null;try{M.dispose()}catch(Re){console.warn("[pane-terminal] dispose failed:",Re)}}},[e,i,X,xe,s,ae,we]);const be=()=>{var T;if(s){N();try{(T=g.current)==null||T.focus()}catch{}}};o.useEffect(()=>{if(s)return;const T=h.current;if(!T)return;const B=M=>{M.stopPropagation()};return T.addEventListener("wheel",B,{capture:!0,passive:!0}),()=>T.removeEventListener("wheel",B,{capture:!0})},[s]);const P=r&&r>0?{maxHeight:`${r*Tn}px`}:void 0;return t.jsxs("div",{className:a??"flex flex-col h-full w-full min-h-0 bg-term",children:[(j||E)&&t.jsx("div",{className:"border-b border-accent/25 bg-accent-soft px-3 py-1 font-mono text-xs text-accent",children:E?m.terminal.sessionEnded:j}),t.jsx("div",{className:"flex flex-1 min-h-0 px-2 py-1.5",style:P,children:t.jsx("div",{ref:h,className:"flex-1 min-h-0 overflow-hidden",onMouseDown:be})}),s&&c&&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(Cr,{agentId:e})}),t.jsx(Sr,{className:"flex items-center justify-center gap-1",onKey:T=>{var M,he;const B=!!((he=(M=g.current)==null?void 0:M.modes)!=null&&he.applicationCursorKeysMode);xe(Pr(T,B))},onEscape:()=>xe("\x1B")})]})]})}function Or(){const[e,n]=o.useState([]),[s,r]=o.useState(!0),[a,i]=o.useState(null),l=o.useCallback(async()=>{r(!0);try{n(await D.pets.list()),i(null)}catch(c){i(c instanceof Error?c.message:String(c))}finally{r(!1)}},[]);return o.useEffect(()=>{l()},[l]),{pets:e,loading:s,error:a,refresh:l}}const _t=new Map,Ht=new Map;function _r(e){const[n,s]=o.useState(()=>e?Ht.get(e)??null:null);return o.useEffect(()=>{if(!e){s(null);return}const r=Ht.get(e);if(s(r??null),r)return;let a=!1,i=_t.get(e);return i||(i=D.pets.fetchSpritesheet(e).then(l=>{const c=URL.createObjectURL(l);return Ht.set(e,c),c}),_t.set(e,i)),i.then(l=>{a||s(l)},()=>{a||s(null),_t.delete(e)}),()=>{a=!0}},[e]),n}const Hr=[{state:"idle",row:0,durations:[280,110,110,140,140,320]},{state:"running-right",row:1,durations:[120,120,120,120,120,120,120,220]},{state:"running-left",row:2,durations:[120,120,120,120,120,120,120,220]},{state:"waving",row:3,durations:[140,140,140,280]},{state:"jumping",row:4,durations:[140,140,140,140,280]},{state:"failed",row:5,durations:[140,140,140,140,140,140,140,240]},{state:"waiting",row:6,durations:[150,150,150,150,150,260]},{state:"running",row:7,durations:[120,120,120,120,120,220]},{state:"review",row:8,durations:[150,150,150,150,150,280]}];function qr(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 hn=36,Ur=hn/Yn,Gr=Kn*Ur;function Wr(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function ds({petId:e,status:n,bootstrapping:s=!1,label:r,displayHeight:a=hn,className:i}){const l=_r(e),c=qr(n,s),m=Hr[c],h=m.durations.length,[g,f]=o.useState(0),u=a/Yn,d=Kn*u;return o.useEffect(()=>{if(f(0),!l||h<=1||Wr())return;let x,y=0;const w=()=>{y=(y+1)%h,f(y),x=setTimeout(w,m.durations[y])};return x=setTimeout(w,m.durations[0]),()=>clearTimeout(x)},[l,c,h,m]),l?t.jsx("span",{role:"img","aria-label":r,title:r,"data-pet-row":c,"data-pet-col":g,className:["inline-block shrink-0",i].filter(Boolean).join(" "),style:{width:`${d}px`,height:`${a}px`,backgroundImage:`url(${l})`,backgroundRepeat:"no-repeat",backgroundSize:`${Ys*u}px ${Qs*u}px`,backgroundPositionX:`${-(g*d)}px`,backgroundPositionY:`${-(c*a)}px`,imageRendering:"pixelated"}}):t.jsx("span",{className:"pill pill-idle",title:r,children:r})}class kt extends Error{constructor(n){super(n),this.name="PetPackageError"}}const bt=e=>e.split("/").pop()??e;function zr(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 Vr(e){const n=un(),s=e.find(c=>bt(c.name)==="pet.json"||bt(c.webkitRelativePath||"")==="pet.json");if(!s)throw new kt(n.pet.missingManifest);let r;try{r=JSON.parse(await zr(s))}catch{throw new kt(n.pet.manifestParseFailed)}const a=r&&typeof r=="object"&&typeof r.spritesheetPath=="string"?r.spritesheetPath:"",i=a?bt(a):"",l=(i?e.find(c=>bt(c.name)===i):void 0)??e.find(c=>/\.(png|webp)$/i.test(c.name));if(!l)throw new kt(n.pet.missingSpritesheet);return{manifest:r,spritesheet:l}}function Kr({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(c=>{c.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 Yr({agentId:e,currentPetId:n,onClose:s}){const r=q(),{show:a}=ke(),i=mn(),{pets:l,loading:c,refresh:m}=Or(),[h,g]=o.useState(!!n),[f,u]=o.useState(n),[d,x]=o.useState(!1),y=o.useRef(null);o.useEffect(()=>{u(n)},[n]),o.useEffect(()=>{const b=y.current;b&&(b.setAttribute("webkitdirectory",""),b.setAttribute("directory",""))},[h]);const w=b=>b instanceof Ve||b instanceof Error?b.message:String(b),C=async b=>{if(g(b),!b&&f){x(!0);try{await D.agents.setPet(e,null),u(null),a({kind:"success",title:r.pet.disabledTitle})}catch(j){a({kind:"error",title:r.pet.disableFailedTitle,body:w(j)}),g(!0)}finally{x(!1)}}},S=async b=>{x(!0);try{await D.agents.setPet(e,b),u(b),a({kind:"success",title:r.pet.selectedTitle})}catch(j){a({kind:"error",title:r.pet.selectFailedTitle,body:w(j)})}finally{x(!1)}},R=async(b,j)=>{if(await i({title:r.pet.deleteConfirmTitle(j),body:r.pet.deleteConfirmBody,confirmLabel:r.common.delete})){x(!0);try{await D.pets.remove(b),await m(),a({kind:"success",title:r.pet.deletedTitle(j)})}catch(k){a({kind:"error",title:r.pet.deleteFailedTitle,body:w(k)})}finally{x(!1)}}},v=async b=>{const j=b.target.files?Array.from(b.target.files):[];if(b.target.value="",!!j.length){x(!0);try{const{manifest:k,spritesheet:E}=await Vr(j);await D.pets.create(k,E),await m(),a({kind:"success",title:r.pet.uploadedTitle})}catch(k){const E=k instanceof kt?k.message:w(k);a({kind:"error",title:r.pet.uploadFailedTitle,body:E})}finally{x(!1)}}};return t.jsx(Se,{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:h,disabled:d,onChange:b=>void C(b.target.checked)}),r.pet.enableLabel]}),h?t.jsxs(t.Fragment,{children:[t.jsxs("div",{children:[t.jsx("button",{type:"button",onClick:()=>{var b;return(b=y.current)==null?void 0:b.click()},disabled:d,className:"btn-secondary",children:r.pet.uploadButton}),t.jsx("input",{ref:y,type:"file","aria-label":r.pet.uploadInputAriaLabel,className:"hidden",onChange:b=>void v(b)}),t.jsx("p",{className:"mt-1 text-xs text-og-400",children:r.pet.uploadDirHint})]}),c?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(b=>{const j=b.id===f;return t.jsxs("li",{className:`flex items-center gap-2 rounded-md border p-2 ${j?"border-accent bg-accent-soft/40":"border-hairline"}`,children:[t.jsx(Kr,{style:{width:`${Gr}px`,height:`${hn}px`},children:t.jsx(ds,{petId:b.id,status:"idle",label:b.displayName})}),t.jsxs("button",{type:"button",onClick:()=>void S(b.id),disabled:d||j,title:b.description||b.displayName,className:"min-w-0 flex-1 truncate text-left text-sm text-og-1000 hover:text-accent-hover disabled:cursor-default",children:[b.displayName,j&&t.jsx("span",{className:"ml-1 text-xs text-accent",children:r.pet.currentMarker})]}),t.jsx("button",{type:"button","aria-label":r.pet.deleteAriaLabel(b.displayName),onClick:()=>void R(b.id,b.displayName),disabled:d,className:"shrink-0 text-xs text-accent hover:underline disabled:opacity-50",children:r.common.delete})]},b.id)})})]}):t.jsx("p",{className:"text-xs text-og-500",children:r.pet.enableHint})]})})}function us(e,n){const s=typeof n=="string"?{status:n}:n,{status:r,phase:a}=s;if(r==="pending"&&s.preferredAgentId==="")return e.statusContext.pendingUnassigned;if(r==="in_progress"){if(a==="spec")return e.statusContext.inProgressSpec;if(a==="code")return e.statusContext.inProgressCode}if(r==="review"){if(a==="spec")return e.statusContext.reviewSpec;if(a==="code")return e.statusContext.reviewCode}if(r==="fixing"){if(a==="spec")return e.statusContext.fixingSpec;if(a==="code")return e.statusContext.fixingCode}if(r==="max_rounds"){if(a==="spec")return e.statusContext.maxRoundsSpec;if(a==="code")return e.statusContext.maxRoundsCode}return e.status[r]??r}function Qr(e){return us(un(),e)}function ms(e,n){const{reason:s,recommendedActions:r}=n,a=/confirm-merge|post-approve|merge/.test(s)?e.taskDetail.attentionMergeTitle:/review|verdict/.test(s)?e.taskDetail.attentionReviewTitle:/runtime|session|recovery|tmux|repl/.test(s)?e.taskDetail.attentionAgentTitle:/dispatch|delivery|pr-created/.test(s)?e.taskDetail.attentionHandoffTitle:e.taskDetail.attentionDefaultTitle,i=r.includes("verdict")?e.taskDetail.attentionVerdictGuidance:r.includes("advance")?e.taskDetail.attentionAdvanceGuidance:r.includes("retry")?e.taskDetail.attentionRetryGuidance:e.taskDetail.attentionCancelGuidance;return{title:a,guidance:i}}const Jr={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"};function fn({task:e,className:n=""}){const s=q(),r=us(s,e);return t.jsx("span",{className:`${Jr[e.status]??"pill"} ${n}`,title:r,"data-status":e.status,children:r})}function pn(e){if(!e)return"";const n=e.match(/^task-(\d+)$/);return n?n[1]:e}function qt(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=c=>String(c).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 Me(e,n){return`/project/${encodeURIComponent(e)}/task/${encodeURIComponent(n)}`}const Ut={unknown:"pill pill-idle",idle:"pill pill-idle",pending:"pill pill-warn",working:"pill pill-live",waiting:"pill pill-review",error:"pill pill-warn"},Xr=72;function Zr(e,n,s){const r=s!==void 0&&rn.has(s.status);return e==="greeting_failed"?"restart-runtime":e==="agent_dialog_pending"?"terminal":r&&(e==="agent_dialog_resolved_runtime"||e!=null&&e.startsWith("signal-arm-failed"))||r&&(e==="dispatch-failed:ack_unknown"||e==="dev-wait-gate-failed-after-qa-started")||r&&s.status!=="spec-ready"&&s.status!=="max_rounds"&&(e==="dirty-workdir"||e==="checkout-preparation-failed")&&n==="dev"?"task":"resume"}function hs(e){var n;return!!((n=e.binding)!=null&&n.creationToken)&&!e.binding.paneId&&e.binding.status!=="awaiting_human"&&e.reason!=="PENDING_HUMAN"}function ea(e,n){var s,r,a;return e.tmuxSessionStatus==="unreachable"?{kind:"alert",label:n.sessionStatus.unreachable,cls:"pill pill-danger"}:hs(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:Ut.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:Ut.pending}:{kind:"runtime",label:n.runtimeStatus[e.runtimeStatus],cls:Ut[e.runtimeStatus]}}function ta(e,n){const s=ea(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 fs({agent:e,projectId:n,role:s,runtime:r,model:a,onDeleted:i,pendingRestart:l=!1,terminalLoading:c=!1,showTaskBinding:m=!0,terminalMode:h="activity-preview",active:g,onActivate:f,task:u}){var Ae,it,Ye,ot,lt,ct,Qe,dt;const d=q(),[x,y]=o.useState(!1),[w,C]=o.useState(null),{show:S}=ke(),R=mn(),{flagDirty:v}=Et(),[b,j]=o.useState(!1),[k,E]=o.useState(null),[I,_]=o.useState(!1),[F,ee]=o.useState(!1),[z,K]=o.useState(!1),[ae,X]=o.useState(!1),[te,Y]=o.useState(!1),ne=(Ae=e.binding)==null?void 0:Ae.taskId,Z=(u==null?void 0:u.id)===ne?u:void 0,J=((it=e.binding)==null?void 0:it.status)==="awaiting_human",me=(ot=(Ye=e.binding)==null?void 0:Ye.needInput)==null?void 0:ot.at,ge=J&&((lt=e.binding)==null?void 0:lt.awaitingPhase)==="greeting_failed",H=Zr((ct=e.binding)==null?void 0:ct.awaitingPhase,s,Z),le=hs(e),ce=le&&e.tmuxSessionStatus!=="present",ie=ta(e,d.agents),we=le?d.agents.bootstrappingBadge:d.agents.runtimeStatus[e.runtimeStatus],N=h==="activity-preview"&&!ce&&(e.runtimeStatus==="working"||e.runtimeStatus==="pending"),xe=h==="embedded-full",be=xe&&typeof f=="function",P=be&&g===!0,T=c||l||ce,B=c?d.agents.agentStatusLoading:l?d.agents.terminalNeedsRestart:d.agents.bootstrappingTerminalDisabled,M=Gn(r,a),he=async()=>{y(!0),C(null);try{await D.agents.stop(e.id)}catch(U){C(U instanceof Error?U.message:String(U))}finally{y(!1)}},se=async()=>{X(!0);try{(await D.projects.bootstrap(n)).ok?S({kind:"success",title:d.agents.retryBootstrapSucceededTitle,body:d.agents.retryBootstrapSucceededBody}):S({kind:"warn",title:d.agents.retryBootstrapStillFailingTitle,body:d.agents.retryBootstrapStillFailingBody})}catch(U){S({kind:"error",title:d.agents.retryBootstrapFailedTitle,body:U instanceof Error?U.message:String(U)})}finally{X(!1)}},$=async()=>{if(await R({title:d.agents.resumeConfirmTitle(e.id),body:ge?d.agents.resumeGreetingBody:d.agents.resumeDefaultBody,confirmLabel:d.agents.resume})){K(!0);try{if(ge){e.tmuxSessionStatus==="present"?await D.projects.restartRepl(n,e.id):await D.projects.retryAgent(n,e.id),S({kind:"success",title:d.agents.regreetingStartedTitle(e.id),body:d.agents.regreetingStartedBody});return}const je=await D.projects.resumeAgent(n,e.id);S({kind:"success",title:d.agents.resumedTitle(e.id),body:je.releasedBinding?d.agents.resumedReleasedBody:d.agents.resumedKeptBody})}catch(je){S({kind:"error",title:d.agents.resumeFailedTitle,body:je instanceof Error?je.message:String(je)})}finally{K(!1)}}},A=async()=>{_(!0);try{await D.agents.compact(e.id),S({kind:"success",title:d.agents.compactSentTitle(e.id)})}catch(U){S({kind:"error",title:d.agents.compactFailedTitle,body:U instanceof Error?U.message:String(U)})}finally{_(!1)}},L=async()=>{if(await R({title:d.agents.clearConfirmTitle(e.id),body:d.agents.clearConfirmBody,confirmLabel:d.agents.clearConfirmLabel})){ee(!0);try{await D.agents.clear(e.id),S({kind:"success",title:d.agents.clearSentTitle(e.id)})}catch(U){S({kind:"error",title:d.agents.clearFailedTitle,body:U instanceof Error?U.message:String(U)})}finally{ee(!1)}}},Q=async()=>{if(await R({title:d.agents.deleteConfirmTitle(e.id),body:d.agents.deleteConfirmBody,confirmLabel:d.common.delete})){j(!0),E(null);try{const U=await D.projects.deleteAgent(n,e.id);U!=null&&U.restartRequired&&v();const je=(U==null?void 0:U.removed)??[e.id],qe=[...(U==null?void 0:U.warnings)??[]];if(je.length>1){const $t=je.filter(ut=>ut!==e.id).join(", ");qe.unshift(d.agents.deletedWithTeamBody($t))}qe.length>0?S({kind:"warn",title:je.length>1?d.agents.deletedWithTeamTitle(e.id):d.agents.deletedTitle(e.id),body:qe.join(`
8
+ `)}):S({kind:"success",title:d.agents.deletedTitle(e.id)}),i==null||i()}catch(U){E(U instanceof Error?U.message:String(U))}finally{j(!1)}}},W=be&&!T&&!P,re=["card relative flex h-full min-w-0 flex-col overflow-visible p-4",P?"ring-2 ring-accent":""].filter(Boolean).join(" "),ye=["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",W?"cursor-pointer":""].filter(Boolean).join(" "),Re=W?()=>f==null?void 0:f():void 0,Ce=W?U=>{(U.key==="Enter"||U.key===" ")&&(U.preventDefault(),f==null||f())}:void 0;return t.jsxs("div",{className:re,"data-agent-card":be?e.id:void 0,children:[e.petId&&t.jsx("div",{className:"absolute -top-4 right-7 z-10",children:t.jsx(ds,{petId:e.petId,status:e.runtimeStatus,bootstrapping:le,label:we,displayHeight:Xr})}),t.jsxs("div",{className:ye,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:Wn(e.id,r,a),children:e.id}),M&&t.jsxs("span",{className:"hidden shrink-0 whitespace-nowrap text-xs text-og-400 sm:inline",title:M,children:["(",M,")"]})]}),(!e.petId||ie.kind==="alert"||ie.stale)&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:ie.stale?`${ie.cls} pill--stale shrink-0`:`${ie.cls} shrink-0`,title:ie.title,children:ie.label}),ie.stale&&t.jsx("span",{className:"sr-only",children:ie.title})]})]}),ce&&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:d.agents.bootstrappingNotice}),J&&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.jsxs("div",{children:[t.jsx("span",{className:"font-mono",children:(Qe=e.binding)==null?void 0:Qe.awaitingPhase}),((dt=e.binding)==null?void 0:dt.awaitingReason)&&t.jsxs("span",{children:[" · ",e.binding.awaitingReason]})]}),t.jsx("div",{className:"text-og-700",children:d.agents.holdRecovery[H]})]}),!le&&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:d.agents.awaitingHumanIntervention}),t.jsxs("div",{children:[d.agents.openTerminalPrefix,t.jsx($e,{to:`/terminal/${e.id}`,className:"text-accent hover:text-accent-hover underline",children:d.agents.terminal}),d.agents.openTerminalSuffix]})]}),me&&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:d.agents.needInputNoticeTitle}),t.jsxs("div",{children:[d.agents.needInputPrefix,t.jsx($e,{to:`/terminal/${e.id}`,className:"text-accent hover:text-accent-hover underline",children:d.agents.terminal}),d.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:se,disabled:ae,className:"btn-primary shrink-0",children:ae?d.common.retrying:d.agents.retryBootstrap})]})]}),m&&ne&&t.jsxs("div",{className:"mb-2 text-xs text-og-500",children:[d.agents.taskLabel,t.jsx("span",{className:"font-mono text-og-700",children:ne})]}),N&&t.jsx("div",{className:"mb-2 overflow-hidden border border-hairline bg-surface",children:t.jsx(et,{agentId:e.id,mode:"preview",maxLines:6,interactive:!1})}),xe&&t.jsx("div",{className:He,role:W?"button":void 0,tabIndex:W?0:void 0,"aria-label":W?d.agents.activateTerminal(e.id):void 0,onClick:Re,onKeyDown:Ce,children:T?t.jsx("div",{className:"flex h-full items-center justify-center px-3 text-sm text-og-500",children:B}):be?P?t.jsx(et,{agentId:e.id,mode:"full",interactive:!0,autoFocus:!0}):t.jsx(et,{agentId:e.id,mode:"preview",interactive:!1}):t.jsx(et,{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:d.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:[T?t.jsx("span",{className:"shrink-0 cursor-not-allowed text-sm text-og-400",title:B,children:d.agents.terminal}):t.jsx($e,{to:`/terminal/${e.id}`,className:"btn-secondary shrink-0",children:d.agents.terminal}),!l&&e.runtimeStatus==="working"&&t.jsx("button",{onClick:he,disabled:x,className:"btn-ghost shrink-0",children:x?d.agents.stopping:d.agents.stop}),J&&(H==="resume"||H==="restart-runtime")&&t.jsx("button",{type:"button",onClick:$,disabled:z,title:ge?d.agents.resumeGreetingButtonTitle:d.agents.resumeDefaultButtonTitle,className:"btn-primary shrink-0",children:z?d.agents.resuming:H==="restart-runtime"?d.agents.restartRuntime:d.agents.resume}),J&&H==="terminal"&&t.jsx($e,{to:`/terminal/${e.id}`,className:"btn-primary shrink-0",children:d.agents.openTerminalAction}),J&&H==="task"&&ne&&t.jsx($e,{to:Me(n,ne),className:"btn-primary shrink-0",children:d.agents.openTaskActions}),J&&H==="delete-agent"&&t.jsx("button",{type:"button",onClick:()=>void Q(),disabled:b,className:"btn-primary shrink-0",children:b?d.common.deleting:d.agents.deleteToRecover})]}),t.jsx(sn,{ariaLabel:d.agents.actionsMenu(e.id),className:"shrink-0",placement:"up",autoFocusFirstItem:!0,disabled:b,children:U=>t.jsxs(t.Fragment,{children:[t.jsx(Ne,{onClick:()=>{U(),Y(!0)},disabled:I||F||b,title:d.agents.agentPetMenuItemTitle,children:"Agent Pet"}),t.jsx(Ne,{onClick:()=>{U(),A()},disabled:I||F||b,title:d.agents.compactMenuItemTitle,children:I?d.agents.compacting:d.agents.compact}),t.jsx(Ne,{onClick:()=>{U(),L()},disabled:F||I||b,title:d.agents.clearMenuItemTitle,children:F?d.agents.clearing:d.agents.clear}),t.jsx(Ne,{onClick:()=>{U(),Q()},disabled:b||I||F,children:b?d.common.deleting:d.common.delete})]})})]}),w&&t.jsx("div",{className:"mt-1.5 break-words text-xs text-accent",children:w}),k&&t.jsx("div",{className:"mt-1.5 break-words text-xs text-accent",children:k}),te&&t.jsx(Yr,{agentId:e.id,currentPetId:e.petId??null,onClose:()=>Y(!1)})]})}const Gt="baxian:terminal-activated";function ps({coordinateAcrossInstances:e=!0}={}){const n=o.useId(),[s,r]=o.useState(null);o.useEffect(()=>{if(s===null)return;const i=m=>{m.composedPath().some(f=>f instanceof Element&&f.hasAttribute("data-agent-card"))||r(null)},l=m=>{if(m.key!=="Escape")return;const h=document.activeElement;h instanceof Element&&h.closest("[data-agent-card]")||r(null)},c=m=>{const h=m.detail;(h==null?void 0:h.ownerId)!==n&&r(null)};return document.addEventListener("click",i),document.addEventListener("keydown",l),e&&document.addEventListener(Gt,c),()=>{document.removeEventListener("click",i),document.removeEventListener("keydown",l),e&&document.removeEventListener(Gt,c)}},[s,e,n]);const a=o.useCallback(i=>{r(i),e&&document.dispatchEvent(new CustomEvent(Gt,{detail:{ownerId:n}}))},[e,n]);return{activeAgentId:s,activateAgentCard:a}}function gs({team:e,projectId:n,agentsById:s,agentsLoaded:r,agentsError:a=!1,tasks:i,onDeleted:l,terminalMode:c="activity-preview"}){const m=q(),h=e.find(v=>v.role==="dev")??e[0],g=i.filter(v=>ra(v,h==null?void 0:h.id)),f=h?i.filter(v=>aa(v,n,h.id)).sort((v,b)=>v.createdAt.localeCompare(b.createdAt)):[],u=`Agent Team ${e.map(v=>v.id).join(" / ")}`,d=Ee(),x=c==="embedded-full",{activeAgentId:y,activateAgentCard:w}=ps({coordinateAcrossInstances:x}),C=c==="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=!!h&&f.length>0,R=g.length===0&&!S;return t.jsxs("div",{role:"group","aria-label":u,className:"min-w-0",children:[S&&h&&t.jsx(sa,{tasks:f,devId:h.id,agentsById:s,label:u}),g.length>0&&t.jsx("div",{className:"card mb-2 max-h-28 overflow-y-auto divide-y divide-hairline",children:g.map(v=>{const b=Be(v.phase)?v.specReviewRound??0:v.reviewRound;return t.jsxs("button",{type:"button",onClick:()=>d(Me(v.projectId,v.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:v.id,children:pn(v.id)}),t.jsx("span",{className:"truncate text-og-1000",children:v.title})]}),t.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[b>0&&t.jsx("span",{className:"shrink-0 text-xs text-og-500",children:m.agents.round(b)}),t.jsx(fn,{task:v,className:"shrink-0"})]})]},v.id)})}),R&&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 ${C} gap-4`,children:e.map(v=>{var E;const b=s.get(v.id),j=b??{id:v.id,projectId:n,runtimeStatus:"unknown",tmuxSessionStatus:"unknown",stale:!0},k=((E=j.binding)==null?void 0:E.taskId)===void 0?void 0:i.find(I=>{var _;return I.id===((_=j.binding)==null?void 0:_.taskId)});return t.jsx(fs,{agent:j,projectId:n,role:v.role,runtime:v.runtime,model:v.model,pendingRestart:r&&!b,terminalLoading:!r&&!b&&!a,onDeleted:l,showTaskBinding:!1,terminalMode:c,task:k,...x?{active:y===v.id,onActivate:()=>w(v.id)}:{}},v.id)})})]})}function na(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 sa({tasks:e,devId:n,agentsById:s,label:r}){const a=q(),{show:i}=ke(),l=Ee(),[c,m]=o.useState(null),h=async(g,f)=>{m(g);try{await D.tasks.advance(g,{executor:"dev",agentId:f}),i({kind:"success",title:a.agents.taskHandedTo(g,f)})}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(g=>{const f=g.preferredAgentId||n,u=na(s.get(f)),d=g.preferredAgentId==="",x=c!==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(Me(g.projectId,g.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:g.id,children:pn(g.id)}),t.jsx("span",{className:"truncate text-og-1000",title:g.title,children:g.title}),d&&t.jsx("span",{className:"pill shrink-0",children:a.agents.unassigned})]}),t.jsx("button",{type:"button",onClick:()=>void h(g.id,f),disabled:!u||x,title:u?a.agents.handToAndStart(f):a.agents.agentUnavailable(f),className:"shrink-0 text-sm font-medium text-accent transition-colors hover:text-accent-hover disabled:opacity-50 disabled:cursor-not-allowed",children:c===g.id?a.agents.starting:a.agents.start})]},g.id)})})}function ra(e,n){return!n||!rn.has(e.status)?!1:e.devAgentId===n}function aa(e,n,s){return e.projectId!==n||e.status!=="pending"?!1:e.preferredAgentId===s||e.preferredAgentId===""}const fe="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",ue="mb-1.5 block text-xs font-medium text-og-700",St="mt-1 text-xs text-accent",Ge="mt-1 text-xs text-og-500",De="h-3.5 w-3.5 accent-accent",ia=/^[a-z][a-z0-9-]{1,31}$/;function oa({open:e,onClose:n,onCreated:s}){const r=q(),[a,i]=o.useState(""),[l,c]=o.useState(""),[m,h]=o.useState(null),[g,f]=o.useState("human"),[u,d]=o.useState(!1),[x,y]=o.useState(null),[w,C]=o.useState({}),[S,R]=o.useState(new Set),v=o.useRef(0),{show:b}=ke(),{flagDirty:j}=Et();o.useEffect(()=>{if(!e)return;v.current+=1;const _=v.current;i(""),c(""),h(null),f("human"),y(null),C({}),R(new Set),D.config.get().then(F=>{_===v.current&&R(new Set(F.project.map(ee=>ee.id)))}).catch(F=>{_===v.current&&y(r.common.loadFailed(F instanceof Error?F.message:String(F)))})},[e]);const k=()=>{u||n()},E=()=>{const _={};return a?ia.test(a)?S.has(a)&&(_.id=r.createProject.idTakenError):_.id=r.common.idFormatError:_.id=r.createProject.required,l.trim()||(_.repo=r.createProject.required),C(_),Object.keys(_).length===0},I=async _=>{if(_.preventDefault(),!!E()){d(!0),y(null);try{const F=await D.projects.create({id:a,repo:l.trim(),merge:m,...g?{specApproval:g}:{}});F.restartRequired&&j(),b({kind:"success",title:r.createProject.createdToastTitle(F.project.id)}),s(F.project.id)}catch(F){y(F instanceof Error?F.message:String(F))}finally{d(!1)}}};return t.jsx(Se,{open:e,onClose:k,title:r.createProject.title,size:"md",footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:k,disabled:u,className:"btn-secondary",children:r.common.cancel}),t.jsx("button",{type:"submit",form:"create-project-form",disabled:u,className:"btn-primary",children:u?r.common.creating:r.common.create})]}),children:t.jsxs("form",{id:"create-project-form",onSubmit:I,className:"space-y-3",children:[x&&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:x}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"proj-id",children:r.createProject.idLabel}),t.jsx("input",{id:"proj-id",type:"text",value:a,onChange:_=>i(_.target.value),className:fe,placeholder:"baxian",disabled:u}),w.id&&t.jsx("div",{className:St,children:w.id})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"proj-repo",children:r.createProject.repoLabel}),t.jsx("input",{id:"proj-repo",type:"text",value:l,onChange:_=>c(_.target.value),className:fe,placeholder:"https://github.com/baxian-ai/baxian.git",disabled:u}),w.repo&&t.jsx("div",{className:St,children:w.repo})]}),t.jsxs("div",{children:[t.jsx("span",{className:ue,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:()=>h(null),disabled:u,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:()=>h("auto"),disabled:u,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:ue,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:g==="human",onChange:()=>f("human"),disabled:u,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:g===null,onChange:()=>f(null),disabled:u,className:"h-3.5 w-3.5 accent-accent"}),t.jsx("span",{className:"text-sm text-og-800",children:r.createProject.specApprovalAutoLabel})]})]})]})})}const Sn=/^[a-z][a-z0-9-]{1,31}$/,la=500,Wt={id:"",mode:"local",host:"",runtime:"",workdir:"",yolo:!0,model:"",addDirs:""};function ca(e){return e.alias?e.alias:`${e.user?`${e.user}@`:""}${e.hostname}${e.port!=null?`:${e.port}`:""}`}function xs({open:e,onClose:n,projectId:s,onCreated:r}){var P,T,B,M,he,se;const a=q(),[i,l]=o.useState(Wt),[c,m]=o.useState(null),[h,g]=o.useState([]),[f,u]=o.useState(new Set),[d,x]=o.useState(null),[y,w]=o.useState(!1),[C,S]=o.useState(!1),[R,v]=o.useState(null),[b,j]=o.useState(!1),[k,E]=o.useState(null),[I,_]=o.useState(!1),F=o.useRef(null),ee=o.useRef(null),z=o.useRef(0),K=o.useRef(0),{show:ae}=ke(),{flagDirty:X}=Et();o.useEffect(()=>{if(!e)return;K.current+=1;const $=K.current;l(Wt),m(null),g([]),u(new Set),x(null),w(!1),S(!1),v(null),z.current+=1,E(null),_(!1),D.config.get().then(A=>{if($!==K.current)return;g(A.host??[]);const L=new Set;A.project.forEach(Q=>Q.agent.forEach(W=>W.forEach(re=>L.add(re.id)))),u(L)}).catch(()=>{})},[e,s]);const te=()=>{b||n()},Y=o.useCallback(()=>{F.current&&F.current.abort();const $=new AbortController;F.current=$,w(!0),E(null);const A=i.mode==="remote"?{hostId:i.host}:{};D.agents.probe(i.mode,A,{signal:$.signal}).then(L=>{$.signal.aborted||(x(L),E(null))}).catch(L=>{$.signal.aborted||(x(null),E(L instanceof Error?L.message:String(L)))}).finally(()=>{F.current===$&&w(!1)})},[i.mode,i.host]);o.useEffect(()=>{if(e&&(x(null),v(null),S(!1),z.current+=1,F.current&&F.current.abort(),!(i.mode==="remote"&&!i.host)))return ee.current&&clearTimeout(ee.current),ee.current=setTimeout(Y,la),()=>{ee.current&&clearTimeout(ee.current)}},[e,i.mode,i.host,c,Y]),o.useEffect(()=>{e||F.current&&F.current.abort()},[e]),o.useEffect(()=>()=>{F.current&&F.current.abort(),ee.current&&clearTimeout(ee.current)},[]);const ne=()=>{if(C)return;const $=z.current;S(!0),v(null);const A=i.mode==="remote"?{hostId:i.host}:{};D.agents.installTmux(i.mode,A).then(L=>{z.current===$&&(v({ok:L.ok,message:L.message}),S(!1),L.ok&&Y())}).catch(L=>{z.current===$&&(v({ok:!1,message:L instanceof Error?L.message:String(L)}),S(!1))})},Z=c?"qa":"dev",J=Sn.test(i.id)&&!f.has(i.id)&&i.id!==(c==null?void 0:c.agent.id),me=i.mode==="local"||i.mode==="remote"&&i.host!=="",ge=i.runtime!==""&&!!((P=d==null?void 0:d.runtimes[i.runtime])!=null&&P.ok),H=!!(d!=null&&d.tmux.ok),le=i.mode==="local"||!!((T=d==null?void 0:d.ssh)!=null&&T.ok),ce=!b&&J&&me&&ge&&H&&le,ie=async $=>{var Q,W;if($.preventDefault(),!ce)return;E(null);const A=i.addDirs.split(`
9
+ `).map(re=>re.trim()).filter(re=>re.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()}:{},...A.length>0?{addDirs:A}:{}};if(!c){m({agent:L,form:i}),l(Wt),x(null),v(null),_(!1);return}j(!0);try{const re=await D.projects.addAgentTeam(s,{agents:[c.agent,L]});re.restartRequired&&X(),ae({kind:(Q=re.warnings)!=null&&Q.length?"warn":"success",title:a.createAgent.addedToastTitle(re.agents.find(ye=>ye.role==="dev").id,re.agents.find(ye=>ye.role==="qa").id,s),...(W=re.warnings)!=null&&W.length?{body:re.warnings.join(`
10
+ `)}:{}}),r(),n()}catch(re){E(re instanceof Error?re.message:String(re))}finally{j(!1)}},we=()=>{!c||b||(l(c.form),m(null),x(null),v(null),_(!1))},N=({rt:$})=>{if(i.mode==="remote"&&!i.host)return t.jsx("span",{className:"ml-2 text-xs text-og-400",children:a.createAgent.selectHostFirstHint});if(y)return t.jsx("span",{className:"ml-2 text-xs text-og-400",children:a.createAgent.probingLabel});if(!d)return t.jsx("span",{className:"ml-2 text-xs text-og-400",children:"?"});const L=d.runtimes[$];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:"?"})},xe=()=>{var A;if(i.mode==="remote"&&!i.host)return null;if(y&&!C)return t.jsx("div",{className:"text-xs text-og-400",children:a.createAgent.tmuxProbingLabel});if(!d)return null;if(d.tmux.ok)return t.jsxs("div",{className:"text-xs text-probe-ok",children:["tmux: ✓ ",d.tmux.path??""]});const $=i.mode==="local"||!!((A=d.ssh)!=null&&A.ok);return t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"text-xs text-accent",children:["tmux: ⨯ ",d.tmux.message,$&&t.jsx("button",{type:"button",onClick:ne,className:"ml-2 text-accent underline transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",disabled:C||b,children:C?a.common.installing:a.common.oneClickInstall})]}),C&&t.jsx("div",{className:"text-xs text-og-500",children:a.common.installingTmuxNotice}),!C&&R&&t.jsxs("div",{className:`break-all text-xs ${R.ok?"text-probe-ok":"text-accent"}`,children:[R.ok?"✓ ":"⨯ ",R.message]})]})},be=()=>i.mode!=="remote"||!i.host||!(d!=null&&d.ssh)?null:d.ssh.ok?t.jsxs("div",{className:"text-xs text-probe-ok",children:["SSH: ✓ ",d.ssh.message]}):t.jsxs("div",{className:"text-xs text-accent",children:["SSH: ⨯ ",d.ssh.message]});return t.jsx(Se,{open:e,onClose:te,title:a.createAgent.modalTitle(s),size:"lg",footer:t.jsxs(t.Fragment,{children:[c&&t.jsx("button",{type:"button",onClick:we,disabled:b,className:"btn-secondary",children:a.common.back}),t.jsx("button",{type:"button",onClick:te,disabled:b,className:"btn-secondary",children:a.common.cancel}),t.jsx("button",{type:"submit",form:"create-agent-form",disabled:!ce,className:"btn-primary",children:b?a.createAgent.submitting:c?a.createAgent.submitLabel:a.createAgent.continueLabel})]}),children:t.jsxs("form",{id:"create-agent-form",onSubmit:ie,className:"space-y-3",children:[k&&t.jsx("div",{className:"whitespace-pre-line rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-sm text-accent",children:k}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"agent-id",children:"Agent ID"}),t.jsx("input",{id:"agent-id",type:"text",value:i.id,onChange:$=>l({...i,id:$.target.value}),className:fe,placeholder:a.createAgent.idPlaceholder(s,Z),disabled:b}),i.id&&!Sn.test(i.id)&&t.jsx("div",{className:St,children:a.common.idFormatError}),i.id&&(f.has(i.id)||i.id===(c==null?void 0:c.agent.id))&&t.jsx("div",{className:St,children:a.createAgent.idTakenGlobalError})]}),t.jsxs("div",{children:[t.jsx("span",{className:ue,children:a.createAgent.roleLabel}),t.jsx("div",{className:"text-sm text-og-800",children:Z==="dev"?a.createAgent.devStepLabel:a.createAgent.qaStepLabel}),c&&t.jsx("div",{className:Ge,children:a.createAgent.teamDevLabel(c.agent.id)})]}),t.jsxs("div",{children:[t.jsx("span",{className:ue,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:De,onChange:()=>l({...i,mode:"local",host:""}),disabled:b}),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:De,onChange:()=>l({...i,mode:"remote"}),disabled:b}),t.jsx("span",{className:"text-sm text-og-800",children:a.createAgent.remoteModeLabel})]})]}),i.mode==="remote"&&t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"host",children:"Host"}),h.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:$=>l({...i,host:$.target.value}),className:fe,disabled:b,children:[t.jsx("option",{value:"",children:a.createAgent.selectHostPlaceholder}),h.map($=>t.jsx("option",{value:$.id,children:ca($)},$.id))]}),t.jsx("div",{className:Ge,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:Y,className:"text-xs text-accent transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",disabled:b||y||i.mode==="remote"&&!i.host,children:a.createAgent.reprobeButton})]}),t.jsxs("label",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"runtime",checked:i.runtime==="claude-code",className:De,onChange:()=>l({...i,runtime:"claude-code"}),disabled:b||(d?!((B=d.runtimes["claude-code"])!=null&&B.ok):!1)}),t.jsx("span",{className:"text-sm text-og-800",children:"Claude Code"}),t.jsx(N,{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:De,onChange:()=>l({...i,runtime:"codex"}),disabled:b||(d?!((M=d.runtimes.codex)!=null&&M.ok):!1)}),t.jsx("span",{className:"text-sm text-og-800",children:"Codex"}),t.jsx(N,{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:De,onChange:()=>l({...i,runtime:"opencode"}),disabled:b||(d?!((he=d.runtimes.opencode)!=null&&he.ok):!1)}),t.jsx("span",{className:"text-sm text-og-800",children:"OpenCode"}),t.jsx(N,{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:De,onChange:()=>l({...i,runtime:"qodercli"}),disabled:b||(d?!((se=d.runtimes.qodercli)!=null&&se.ok):!1)}),t.jsx("span",{className:"text-sm text-og-800",children:"Qoder CLI"}),t.jsx(N,{rt:"qodercli"})]}),t.jsx("div",{className:"mt-2",children:t.jsx(xe,{})}),t.jsx("div",{children:t.jsx(be,{})})]}),t.jsxs("div",{children:[t.jsxs("button",{type:"button",onClick:()=>_($=>!$),"aria-expanded":I,"aria-controls":I?"advanced-options":void 0,className:"flex w-full items-center justify-between rounded-md px-1 py-1.5 text-left text-xs font-medium text-og-700 transition-colors hover:bg-og-50",children:[t.jsx("span",{children:a.createAgent.advancedOptionsLabel}),t.jsx("span",{className:"text-og-400",children:I?a.createAgent.collapseLabel:a.createAgent.expandLabel})]}),I&&t.jsxs("div",{id:"advanced-options",className:"mt-3 space-y-3",children:[t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"workdir",children:a.createAgent.workdirLabel}),t.jsx("input",{id:"workdir",type:"text",value:i.workdir,onChange:$=>l({...i,workdir:$.target.value}),className:fe,placeholder:a.createAgent.workdirPlaceholder,disabled:b}),t.jsx("div",{className:Ge,children:a.createAgent.workdirHint})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"model",children:a.createAgent.modelLabel}),t.jsx("input",{id:"model",type:"text",value:i.model,onChange:$=>l({...i,model:$.target.value}),className:fe,placeholder:i.runtime==="codex"?a.createAgent.modelPlaceholderCodex:a.createAgent.modelPlaceholderOther,disabled:b}),t.jsx("div",{className:Ge,children:a.createAgent.modelHint})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"addDirs",children:a.createAgent.addDirsLabel}),t.jsx("textarea",{id:"addDirs",value:i.addDirs,onChange:$=>l({...i,addDirs:$.target.value}),className:`${fe} font-mono text-xs`,rows:3,placeholder:a.createAgent.addDirsPlaceholder,disabled:b}),t.jsx("div",{className:Ge,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:$=>l({...i,yolo:$.target.checked}),disabled:b}),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:Ks[i.runtime||"claude-code"]}),a.createAgent.yoloBodyTrail]})]})]})})]})})}const Rn=200,Cn=16e3,da="baxian.draft.createTask:";function Zt(e){return`${da}${e??"*"}`}function An(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:"",c=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:c,updatedAt:m}}catch{return null}}function ua(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 Pn(e){try{localStorage.removeItem(e)}catch{}}function ma(e){const n=Zt(e),s=An(n);if(!e)return s;const r=Zt(void 0),a=An(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 Ln="mt-1 text-right text-xs text-og-400",ha=Math.floor(Lt/1024/1024);function gn(e){const n=q(),s=e.mode==="edit",{show:r}=ke(),a=s?e.task.projectId:e.projectId,i=s?e.task.title:"",l=s?e.task.description:"",c=s?e.task.preferredAgentId:"",[m,h]=o.useState([]),[g,f]=o.useState([]),[u,d]=o.useState(a??""),[x,y]=o.useState(c),[w,C]=o.useState(i),[S,R]=o.useState(l),[v,b]=o.useState([]),j=o.useRef(null),[k,E]=o.useState(!1),[I,_]=o.useState(null),[F,ee]=o.useState(!1),z=o.useRef(0),K=o.useRef(0),ae=o.useRef(0),X=o.useRef(new Set),te=s?null:Zt(a);o.useEffect(()=>{if(!e.open)return;z.current+=1,K.current+=1;const A=z.current;h([]),f([]),X.current=new Set;const L=te?ma(a):null;L&&X.current.add(L.projectId),d(a??(L==null?void 0:L.projectId)??""),y((L==null?void 0:L.preferredAgentId)||c),C((L==null?void 0:L.title)||i),R((L==null?void 0:L.description)||l),ee(L!==null),_(null),E(!1),b([]),Promise.all([D.projects.list(),D.agents.list()]).then(([Q,W])=>{A===z.current&&(h(Q),f(W))}).catch(Q=>{A===z.current&&_(Q instanceof Error?Q.message:String(Q))})},[e.open,a,i,l,c,te]),o.useEffect(()=>{if(!(!e.open||!te)){if(ae.current!==K.current){ae.current=K.current;return}ua(te,{title:w,description:S,projectId:u,preferredAgentId:x})}},[e.open,te,w,S,u,x]);const Y=o.useMemo(()=>m.find(A=>A.id===u)??null,[m,u]),ne=o.useMemo(()=>Y?Y.agent.flat().filter(A=>A.role==="dev"):[],[Y]),Z=o.useMemo(()=>new Set(g.map(A=>A.id)),[g]),J=o.useMemo(()=>ne.filter(A=>Z.has(A.id)),[ne,Z]),me=o.useMemo(()=>ne.filter(A=>!Z.has(A.id)),[ne,Z]);o.useEffect(()=>{s||Y!==null&&x!==""&&!J.find(A=>A.id===x)&&y("")},[Y,J,x,s]),o.useEffect(()=>{if(s||!Y)return;const A=J.find(L=>L.role==="dev");A&&(X.current.has(Y.id)||(X.current.add(Y.id),y(L=>L===""?A.id:L)))},[s,Y,J]);const ge=!s||J.find(A=>A.id===x),H=s&&!ge&&!!x,le=H&&me.some(A=>A.id===x),ce=le?n.createTask.noDevPendingRestartHint(x):H?n.createTask.noDevNotInRuntimeHint(x):!u||J.length>0?null:me.length>0?n.createTask.noDevGlobalPendingRestartHint:null,ie=w.trim(),we=S.trim(),xe=!!u&&ie.length>0&&!k,be=()=>{k||e.onClose()},P=()=>{te&&(Pn(te),d(a??""),y(c),C(i),R(l),_(null),ee(!1))},T=async A=>{var L,Q;if(A.preventDefault(),!!xe){E(!0),_(null);try{if(e.mode==="edit"){const W=await D.tasks.update(e.task.id,{title:ie,description:we,preferredAgentId:x});r({kind:"success",title:n.createTask.updatedToastTitle}),(L=e.onUpdated)==null||L.call(e,W),e.onClose()}else{const W=v.length?await Promise.all(v.map(async ye=>({dataBase64:await Qt(ye),filename:ye.name}))):void 0,re=await D.tasks.create({projectId:u,title:ie,description:we,preferredAgentId:x,...W?{images:W}:{}});te&&Pn(te),r({kind:"success",title:n.createTask.createdToastTitle}),(Q=e.onCreated)==null||Q.call(e,re),e.onClose()}}catch(W){_(W instanceof Error?W.message:String(W))}finally{E(!1)}}},B=A=>{const L=Array.from(A.target.files??[]);if(A.target.value="",L.length===0)return;const Q=L.filter(W=>W.size>Lt?(r({kind:"error",title:n.createTask.imageTooLargeToastTitle,body:n.createTask.imageTooLargeToastBody(W.name,ha)}),!1):!0);b(W=>(W.length+Q.length>pt&&r({kind:"warn",title:n.createTask.tooManyImagesToastTitle(pt)}),[...W,...Q].slice(0,pt)))},M=A=>b(L=>L.filter((Q,W)=>W!==A)),he=s?n.createTask.titleEdit:n.createTask.titleCreate,se=s?k?n.common.saving:n.common.save:k?n.common.creating:n.common.create,$=!s&&!a;return t.jsx(Se,{open:e.open,onClose:be,title:he,size:"md",dismissOnBackdrop:!1,footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:be,disabled:k,className:"btn-secondary",children:n.common.cancel}),t.jsx("button",{type:"submit",form:"create-task-form",disabled:!xe,className:"btn-primary",children:se})]}),children:t.jsxs("form",{id:"create-task-form",onSubmit:T,className:"space-y-3",children:[!s&&F&&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})]}),I&&t.jsx("div",{className:"rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-sm text-accent",children:I}),$&&t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"task-project",children:"Project"}),t.jsxs("select",{id:"task-project",value:u,onChange:A=>d(A.target.value),className:fe,disabled:k,required:!0,children:[t.jsx("option",{value:"",disabled:!0,children:n.createTask.selectProjectPlaceholder}),m.map(A=>t.jsx("option",{value:A.id,children:A.id},A.id))]})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"task-dev",children:n.createTask.targetAgentLabel}),t.jsxs("select",{id:"task-dev",value:x,onChange:A=>y(A.target.value),className:fe,disabled:k,children:[t.jsx("option",{value:"",children:n.createTask.notAssignedOption}),H&&t.jsxs("option",{value:x,children:[x," ",le?n.createTask.pendingRestartSuffix:n.createTask.notInRuntimeSuffix]}),J.map(A=>t.jsx("option",{value:A.id,children:A.id},A.id))]}),ce&&t.jsx("div",{className:"mt-1 text-xs text-accent",children:ce})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"task-title",children:"Title"}),t.jsx("input",{id:"task-title",type:"text",value:w,onChange:A=>C(A.target.value),maxLength:Rn,className:fe,placeholder:n.createTask.titlePlaceholder,disabled:k,required:!0}),t.jsxs("div",{className:Ln,children:[w.length," / ",Rn]})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"task-description",children:n.createTask.descriptionLabel}),t.jsx("textarea",{id:"task-description",value:S,onChange:A=>R(A.target.value),maxLength:Cn,rows:8,className:`${fe} font-mono text-xs`,placeholder:n.createTask.descriptionPlaceholder,disabled:k}),t.jsxs("div",{className:Ln,children:[S.length," / ",Cn]})]}),!s&&t.jsxs("div",{children:[t.jsx("label",{className:ue,children:n.createTask.imagesLabel}),t.jsx("button",{type:"button",onClick:()=>{var A;return(A=j.current)==null?void 0:A.click()},disabled:k||v.length>=pt,className:"btn-secondary",children:n.createTask.addImagesButton}),t.jsx("input",{ref:j,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:B}),v.length>0&&t.jsx("ul",{className:"mt-2 space-y-1",children:v.map((A,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:A.name,className:"truncate text-xs text-og-700",children:A.name}),t.jsx("button",{type:"button","aria-label":n.createTask.removeImageAriaLabel(A.name),onClick:()=>M(L),disabled:k,className:"ml-2 shrink-0 text-og-400 transition-colors",children:"✕"})]},`${A.name}-${L}`))})]})]})})}const En="***",zt={hostname:"",port:"",alias:"",user:"",password:""};function fa(e){return e.alias?e.alias:`${e.user?`${e.user}@`:""}${e.hostname}${e.port!=null?`:${e.port}`:""}`}function pa({open:e,onClose:n}){var be;const s=q(),[r,a]=o.useState([]),[i,l]=o.useState("list"),[c,m]=o.useState(null),[h,g]=o.useState(null),[f,u]=o.useState(!1),[d,x]=o.useState(!1),[y,w]=o.useState(zt),[C,S]=o.useState(null),[R,v]=o.useState(!1),[b,j]=o.useState(!1),[k,E]=o.useState(null),[I,_]=o.useState(!1),[F,ee]=o.useState(null),z=o.useRef(0),K=o.useRef(null),{show:ae}=ke(),X=o.useCallback(()=>{D.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),g(null),w(zt),S(null),X()},[e,X]),o.useEffect(()=>{z.current+=1,K.current&&K.current.abort(),j(!1),E(null),_(!1),ee(null)},[y.hostname,y.user,y.port,y.password,d,i]),o.useEffect(()=>()=>{K.current&&K.current.abort()},[]);const te=()=>{m(null),g(null),u(!1),x(!1),w(zt),S(null),l("form")},Y=P=>{m(P.id??null),g(P),u(P.password===En),x(!1),w({hostname:P.hostname,port:P.port!=null?String(P.port):"",alias:P.alias??"",user:P.user??"",password:""}),S(null),l("form")},ne=()=>{const P={hostname:y.hostname.trim()};return c?(P.port=y.port.trim()?Number(y.port):null,P.alias=y.alias.trim(),P.user=y.user.trim()):(y.port.trim()&&(P.port=Number(y.port)),y.alias.trim()&&(P.alias=y.alias.trim()),y.user.trim()&&(P.user=y.user.trim())),c&&d?P.password="":y.password&&(P.password=y.password),P},Z=y.port.trim(),J=Z===""||/^\d+$/.test(Z)&&Number(Z)>0&&Number(Z)<=65535,me=y.hostname.trim().length>0&&J,ge=!!h&&y.hostname.trim()===h.hostname&&y.user.trim()===(h.user??"")&&y.port.trim()===(h.port!=null?String(h.port):""),H=()=>c&&ge&&!y.password&&!d?{hostId:c}:{host:{hostname:y.hostname.trim(),...y.user.trim()?{user:y.user.trim()}:{},...Z?{port:Number(Z)}:{},...!d&&y.password?{password:y.password}:{}}},le=async()=>{if(!me||b)return;K.current&&K.current.abort();const P=new AbortController;K.current=P;const T=z.current;j(!0),E(null),ee(null),S(null);try{const B=await D.agents.probe("remote",H(),{signal:P.signal});if(P.signal.aborted||z.current!==T)return;E(B)}catch(B){if(P.signal.aborted||z.current!==T)return;S(B instanceof Error?B.message:String(B))}finally{z.current===T&&j(!1)}},ce=async()=>{if(I)return;const P=z.current;_(!0),ee(null),S(null);try{const T=await D.agents.installTmux("remote",H());if(z.current!==P)return;ee({ok:T.ok,message:T.message}),E(B=>B&&{...B,tmux:T.tmux})}catch(T){if(z.current!==P)return;S(T instanceof Error?T.message:String(T))}finally{z.current===P&&_(!1)}},ie=async P=>{if(P.preventDefault(),!(!me||R)){v(!0),S(null);try{if(c)await D.hosts.update(c,ne()),ae({kind:"success",title:s.hostMgmt.updatedToastTitle(c)});else{const T=await D.hosts.create(ne());ae({kind:"success",title:s.hostMgmt.createdToastTitle(T.host.id)})}X(),l("list")}catch(T){S(T instanceof Error?T.message:String(T))}finally{v(!1)}}},we=async P=>{S(null);try{await D.hosts.delete(P.id),ae({kind:"success",title:s.hostMgmt.deletedToastTitle(P.id)}),X()}catch(T){S(T instanceof Error?T.message:String(T))}},N=t.jsx("button",{type:"button",onClick:n,className:"btn-secondary",children:s.common.close}),xe=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:()=>l("list"),disabled:R,className:"btn-secondary",children:s.common.backText}),t.jsx("button",{type:"submit",form:"host-form",disabled:!me||R,className:"btn-primary",children:R?s.common.saving:s.common.save})]});return t.jsxs(Se,{open:e,onClose:n,title:s.hostMgmt.title,size:"md",footer:i==="list"?N:xe,children:[C&&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:C}),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:fa(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===En?s.hostMgmt.passwordSavedIndicator:""]})]}),t.jsxs("div",{className:"flex shrink-0 gap-2",children:[t.jsx("button",{type:"button",onClick:()=>Y(P),className:"text-xs text-accent transition-colors hover:text-accent-hover",children:s.common.edit}),t.jsx("button",{type:"button",onClick:()=>we(P),className:"text-xs text-accent transition-colors hover:opacity-80",children:s.common.delete})]})]},P.id))}),t.jsx("button",{type:"button",onClick:te,className:"btn-secondary w-full",children:s.hostMgmt.addHostButton})]}):t.jsxs("form",{id:"host-form",onSubmit:ie,className:"space-y-3",children:[t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"host-hostname",children:s.hostMgmt.addressLabel}),t.jsx("input",{id:"host-hostname",type:"text",value:y.hostname,onChange:P=>w({...y,hostname:P.target.value}),className:fe,placeholder:"remote.example.com",disabled:R})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"host-port",children:s.hostMgmt.portLabel}),t.jsx("input",{id:"host-port",type:"text",inputMode:"numeric",value:y.port,onChange:P=>w({...y,port:P.target.value}),className:fe,placeholder:"22",disabled:R}),y.port.trim()!==""&&!J&&t.jsx("div",{className:"mt-1 text-xs text-accent",children:s.hostMgmt.portRangeError})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"host-alias",children:s.hostMgmt.aliasLabel}),t.jsx("input",{id:"host-alias",type:"text",value:y.alias,onChange:P=>w({...y,alias:P.target.value}),className:fe,placeholder:"Prod worker",disabled:R})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"host-user",children:s.hostMgmt.userLabel}),t.jsx("input",{id:"host-user",type:"text",value:y.user,onChange:P=>w({...y,user:P.target.value}),className:fe,placeholder:s.hostMgmt.userPlaceholder,disabled:R})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"host-password",children:s.hostMgmt.passwordLabel}),t.jsx("input",{id:"host-password",type:"password",value:d?"":y.password,onChange:P=>w({...y,password:P.target.value}),className:fe,placeholder:f?s.hostMgmt.passwordPlaceholderSet:s.hostMgmt.passwordPlaceholderUnset,disabled:R||d,autoComplete:"new-password"}),c&&f&&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:d,onChange:P=>x(P.target.checked),disabled:R}),s.hostMgmt.clearPasswordLabel]})]}),t.jsxs("div",{className:"rounded-md border border-accent/25 bg-accent-soft/60 px-3 py-2.5 text-xs text-accent",children:[s.hostMgmt.passwordHintLead,t.jsx("strong",{className:"font-semibold",children:s.hostMgmt.passwordHintStrong})," ",s.hostMgmt.plaintextWarningLead,t.jsx("strong",{className:"font-semibold",children:s.hostMgmt.plaintextWarningStrong}),s.hostMgmt.plaintextWarningTrail]}),t.jsxs("div",{className:"space-y-1.5",children:[t.jsx("button",{type:"button",onClick:le,disabled:!me||b||R||I,className:"text-xs text-accent transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",children:b?s.hostMgmt.testing:s.hostMgmt.testConnection}),(k==null?void 0:k.ssh)&&t.jsxs("div",{className:`text-xs ${k.ssh.ok?"text-og-800":"text-accent"}`,children:["SSH: ",k.ssh.ok?"✓":"⨯"," ",k.ssh.message]}),k&&(k.tmux.ok?t.jsxs("div",{className:"text-xs text-og-800",children:["tmux: ✓ ",k.tmux.path??""]}):t.jsxs("div",{className:"text-xs text-accent",children:["tmux: ⨯ ",k.tmux.message,((be=k.ssh)==null?void 0:be.ok)&&t.jsx("button",{type:"button",onClick:ce,disabled:I||R,className:"ml-2 text-accent underline transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",children:I?s.common.installing:s.common.oneClickInstall})]})),I&&t.jsx("div",{className:"text-xs text-og-500",children:s.common.installingTmuxNotice}),!I&&F&&t.jsxs("div",{className:`break-all text-xs ${F.ok?"text-og-800":"text-accent"}`,children:[F.ok?"✓ ":"⨯ ",F.message]})]})]})]})}const xn="baxian.taskNotifications.enabled";function bn(){if(typeof window>"u")return null;const e=window.Notification;return typeof e=="function"?e:null}function vt(){const e=bn();return e?e.permission:"unsupported"}function Vt(){try{return localStorage.getItem(xn)!=="0"}catch{return!0}}function yt(e){try{localStorage.setItem(xn,e?"1":"0")}catch{}}const bs=o.createContext(null);function ga({children:e}){const[n,s]=o.useState(vt),[r,a]=o.useState(Vt),[i,l]=o.useState(!1),c=o.useRef(!1),m=o.useRef(0);o.useEffect(()=>{const f=()=>{s(vt()),c.current||a(Vt())},u=d=>{if(d.key!==null&&d.key!==xn)return;s(vt());const x=d.key===null?Vt():d.newValue!=="0";x||(m.current+=1),a(x)};return window.addEventListener("focus",f),window.addEventListener("storage",u),()=>{window.removeEventListener("focus",f),window.removeEventListener("storage",u)}},[]);const h=o.useCallback(()=>{a(!0);const f=bn();if(!f){yt(!0);return}if(f.permission!=="default"){s(f.permission),yt(!0);return}if(c.current)return;c.current=!0,l(!0);const u=m.current;f.requestPermission().then(s).catch(d=>{console.warn("[task-notifications] permission request failed:",d),s(vt())}).finally(()=>{m.current===u&&yt(!0),c.current=!1,l(!1)})},[]),g=o.useCallback(()=>{m.current+=1,a(!1),yt(!1)},[]);return t.jsx(bs.Provider,{value:{permission:n,preferenceEnabled:r,enabled:n==="granted"&&r,requesting:i,enable:h,disable:g},children:e})}function vs(){const e=o.useContext(bs);if(!e)throw new Error("useTaskNotifications must be used inside TaskNotificationsProvider");return e}const xa=[{value:"en-US",label:"English"},{value:"zh-CN",label:"简体中文"}];function ba({open:e,onClose:n}){const s=q(),{locale:r,saving:a,setLocale:i}=ns(),{show:l}=ke(),c=async m=>{try{await i(m)}catch(h){const g=h instanceof Error?h.message:String(h);l({kind:"error",title:s.settings.languageSaveFailed(g)})}};return t.jsx(Se,{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:ue,children:s.settings.language}),t.jsx("div",{className:"flex gap-4",children:xa.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:De,checked:r===m.value,disabled:a,onChange:()=>void c(m.value)}),m.label]},m.value))})]}),t.jsx(va,{})]})})}function va(){const e=q(),{permission:n,enabled:s,requesting:r,enable:a,disable:i}=vs();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:De,checked:s,disabled:l||r,onChange:()=>s?i():a()}),e.settings.taskNotifications]}),t.jsx("p",{className:Ge,children:l?e.settings.taskNotificationsDenied:e.settings.taskNotificationsHint})]})}const ys="topbar-actions";function Dn(){return typeof document>"u"?null:document.getElementById(ys)}function ws({children:e}){const[n,s]=o.useState(Dn);return o.useEffect(()=>{n||s(Dn())},[n]),n?Hs.createPortal(e,n):null}function ya(){return ls("/api/realtime")}class wa{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??ya(),this.wsFactory=n.wsFactory??cs,this.tokenProvider=n.tokenProvider??on,this.reconnectScheduler=new is({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.${os(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(c){console.warn("[events-client] resubscribe send failed:",c)}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(c){console.warn("[events-client] outbox flush failed:",c)}},r.onmessage=i=>{if(r!==this.ws)return;let l;try{const c=typeof i.data=="string"?i.data:String(i.data);l=JSON.parse(c)}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 Kt=null;function rt(){return Kt||(Kt=new wa),Kt}function vn(){const[e,n]=o.useState(null),[s,r]=o.useState(!1),[a,i]=o.useState(null);return o.useEffect(()=>rt().subscribe("agents",c=>{i(null),n(c),r(!0)},c=>i(c)),[]),{data:e,loaded:s,error:a}}function ks(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),rt().subscribe(`task:${e}`,m=>{l(null),s(m),a(!0)},m=>l(m))),[e]),{data:n,loaded:r,error:i}}function js(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 c=!1,m=!1,h=!1;const g=rt().subscribe(`project-tasks:${e}`,f=>{c||(m=!0,l(null),s(f),a(!0))},f=>{c||(l(f),!(m||h)&&(h=!0,D.tasks.list(e).then(u=>{c||m||(s(u),a(!0))},u=>{console.warn(`[useProjectTasks] REST fallback failed for ${e}:`,u)})))});return()=>{c=!0,g()}},[e]),{data:n,loaded:r,error:i}}let Rt=null,Ie=null,Ct=null,tt=0;const en=new Set;function Ts(){en.forEach(e=>e())}async function ka(){const e=tt;try{const n=await D.projects.list();if(e!==tt)return;Rt=n,Ct=null}catch(n){if(e!==tt)return;Ct=n instanceof Error?n.message:String(n)}finally{e===tt&&(Ie=null,Ts())}}function tn(){return Ie||(Ie=ka(),Ie)}function ja(){tt+=1,Rt=null,Ie=null,Ct=null,Ts()}typeof window<"u"&&window.addEventListener(jt,ja);async function Ta(){const e=Ie!==null;await tn(),e&&await tn()}function at(){const[,e]=o.useState(0);return o.useEffect(()=>{const n=()=>e(s=>s+1);return en.add(n),Rt===null&&!Ie&&tn(),()=>{en.delete(n)}},[]),{projects:Rt,error:Ct,refresh:Ta}}function Na(){const e=q(),n=Ee(),{projects:s,error:r,refresh:a}=at(),i=s??[],l=s!==null,[c,m]=o.useState(!1),[h,g]=o.useState(!1),[f,u]=o.useState(!1),[d,x]=o.useState(!1),[y,w]=o.useState({kind:"closed"}),{data:C,loaded:S,error:R}=vn(),v=(R==null?void 0:R.message)??null,b=new Map((C??[]).map(I=>[I.id,I])),j=r??v,k=i.length===0,E=t.jsx("button",{type:"button",onClick:()=>g(!0),disabled:k,"aria-describedby":k?"create-task-hint":void 0,className:"btn-ghost",children:e.dashboard.newTask});return t.jsxs("div",{children:[t.jsxs(ws,{children:[k?t.jsx("span",{className:"inline-flex",title:e.dashboard.createProjectFirst,children:E}):E,k&&t.jsx("span",{id:"create-task-hint",className:"sr-only",children:e.dashboard.createProjectFirst}),t.jsx(sn,{ariaLabel:e.dashboard.moreActions,children:I=>t.jsxs(t.Fragment,{children:[t.jsx(Ne,{onClick:()=>{I(),m(!0)},children:e.dashboard.newProject}),t.jsx(Ne,{onClick:()=>{I(),u(!0)},children:e.dashboard.manageHosts}),t.jsx(Ne,{onClick:()=>{I(),x(!0)},children:e.settings.entry})]})})]}),t.jsx("h1",{className:"sr-only",children:"Dashboard"}),j&&t.jsx("div",{className:"mb-4 text-sm text-accent",children:e.common.loadFailed(j)}),l&&i.length===0&&!r&&t.jsx("div",{className:"rounded-lg border border-hairline bg-surface py-12 text-center text-sm text-og-500",children:e.dashboard.emptyProjects}),i.map(I=>t.jsx(Sa,{project:I,agentsById:b,agentsLoaded:S,agentsError:!!R,onAgentDeleted:a},I.id)),t.jsx(oa,{open:c,onClose:()=>m(!1),onCreated:I=>{m(!1),a(),w({kind:"asking",projectId:I})}}),t.jsx(pa,{open:f,onClose:()=>u(!1)}),t.jsx(Se,{open:y.kind==="asking",onClose:()=>w({kind:"closed"}),title:e.dashboard.projectCreatedTitle,size:"sm",footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:()=>w({kind:"closed"}),className:"btn-secondary",children:e.dashboard.later}),t.jsx("button",{type:"button",onClick:()=>{y.kind==="asking"&&w({kind:"addingAgent",projectId:y.projectId})},className:"btn-primary",children:e.dashboard.continueAddingAgent})]}),children:t.jsx("p",{className:"text-sm text-og-700",children:e.dashboard.addAgentNowOrLater})}),y.kind==="addingAgent"&&t.jsx(xs,{open:!0,projectId:y.projectId,onClose:()=>w({kind:"closed"}),onCreated:()=>{a()}}),t.jsx(gn,{open:h,onClose:()=>g(!1),onCreated:I=>n(Me(I.projectId,I.id))}),t.jsx(ba,{open:d,onClose:()=>x(!1)})]})}function Sa({project:e,agentsById:n,agentsLoaded:s,agentsError:r,onAgentDeleted:a}){const i=q(),{data:l,error:c}=js(e.id),m=l??[],h=(c==null?void 0:c.message)??null;return t.jsxs("div",{className:"mb-10",children:[t.jsxs("div",{className:"mb-3 -mx-2 flex items-baseline gap-x-3 gap-y-1 px-2 py-1",children:[t.jsx("h2",{className:"min-w-0 truncate font-display text-sm font-semibold tracking-tight text-og-1000",title:e.id,children:t.jsx($e,{to:`/project/${e.id}`,className:"hover:text-accent-hover",children:e.id})}),t.jsx("span",{className:"hidden min-w-0 truncate font-mono text-xs text-og-500 sm:inline-block",title:e.repo,children:e.repo}),t.jsx($e,{to:`/project/${e.id}`,className:"ml-auto text-sm text-accent hover:text-accent-hover","aria-label":i.dashboard.detailsAriaLabel(e.id),children:i.dashboard.detailsLink})]}),h&&t.jsx("div",{className:"mb-2 text-xs text-accent",children:i.dashboard.tasksLoadFailed(h)}),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((g,f)=>t.jsx(gs,{team:g,projectId:e.id,agentsById:n,agentsLoaded:s,agentsError:r,tasks:m,onDeleted:a,terminalMode:"embedded-full"},g.map(u=>u.id).join(":")||f))})]})}const Ns="baxian.taskPanel.doneOpen";function Ra(){try{return localStorage.getItem(Ns)==="1"}catch{return!1}}function At(e){const n=e.match(/^task-(\d+)$/);return n?parseInt(n[1],10):Number.NaN}function Ca(e,n){const s=At(e.id),r=At(n.id);return Number.isNaN(s)||Number.isNaN(r)?e.id.localeCompare(n.id):s-r}function Aa(e,n){const s=(n.updatedAt??"").localeCompare(e.updatedAt??"");if(s!==0)return s;const r=At(e.id),a=At(n.id);return Number.isNaN(r)||Number.isNaN(a)?n.id.localeCompare(e.id):a-r}function $n(e,n){const[s,r]=o.useState(Bt);o.useEffect(()=>r(Bt),[n]);const a=e.slice(0,s),i=e.length>a.length;return{items:a,hasMore:i,loadMore:()=>r(c=>c+Bt),total:e.length}}function Pa(e){const[n,s]=o.useState([]),[r,a]=o.useState(!1),[i,l]=o.useState(!1),[c,m]=o.useState(!1),[h,g]=o.useState(null),f=o.useRef(0),u=o.useRef(0),d=o.useCallback(x=>{const y=++f.current,w=x==="first"?0:u.current;l(!0),g(null),D.tasks.page(e,{category:"done",offset:w}).then(C=>{f.current===y&&(s(S=>x==="first"?C.tasks:[...S,...C.tasks]),a(C.hasMore),u.current=C.nextOffset,m(!0),l(!1))},C=>{f.current===y&&(g(C instanceof Error?C.message:String(C)),l(!1))})},[e]);return o.useEffect(()=>{f.current+=1,u.current=0,s([]),a(!1),m(!1),g(null),l(!1)},[e]),{items:n,hasMore:r,loading:i,loaded:c,error:h,load:d}}function La({projectId:e,openTasks:n,className:s=""}){const r=q(),a=o.useMemo(()=>n.filter(u=>rn.has(u.status)).sort(Aa),[n]),i=o.useMemo(()=>n.filter(u=>u.status==="pending").sort(Ca),[n]),l=$n(a,e),c=$n(i,e),m=Pa(e),[h,g]=o.useState(Ra);o.useEffect(()=>{try{localStorage.setItem(Ns,h?"1":"0")}catch{}},[h]),o.useEffect(()=>{h&&m.load("first")},[h,m.load]);const f=()=>g(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(In,{title:r.taskPanel.inProgressTitle,section:l,emptyHint:r.taskPanel.emptyInProgress}),t.jsx(In,{title:r.taskPanel.pendingTitle,section:c,emptyHint:r.taskPanel.emptyPending}),t.jsxs("div",{children:[t.jsxs("button",{type:"button",onClick:f,"aria-expanded":h,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:r.taskPanel.doneTitle}),t.jsx("span",{className:"font-normal normal-case text-accent",children:h?r.taskPanel.collapse:r.taskPanel.view})]}),h&&t.jsx(Ea,{state:m})]})]})})}function In({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(Ss,{task:a},a.id)),n.hasMore&&t.jsx("button",{type:"button",onClick:n.loadMore,className:"w-full px-3 py-2 text-center text-xs text-accent transition-colors hover:bg-og-50/40",children:r.taskPanel.loadMore})]})]})}function Ea({state:e}){const n=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(Ss,{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 Ss({task:e}){const n=q(),s=Ee(),{show:r}=ke(),[a,i]=o.useState(!1),l=Be(e.phase)?e.specReviewRound??0:e.reviewRound,c=e.status==="pending"&&e.preferredAgentId==="",m=c?n.taskDetail.editTask:e.status==="pending"?n.taskDetail.startTask:e.status==="review"?n.taskDetail.restartReview:e.status==="approved"?n.taskDetail.retryPreMergeCheck:n.taskDetail.retryCurrentStep,h=e.attention?ms(n,e.attention):null,g=()=>s(Me(e.projectId,e.id)),f=async()=>{if(c||e.postApproveRevoked||e.status==="review"&&Un(e)){g();return}i(!0);try{await D.tasks.advance(e.id),r({kind:"success",title:n.taskDetail.advanceSucceededTitle})}catch(u){r({kind:"error",title:n.taskDetail.advanceFailedTitle,body:n.taskDetail.actionFailedBody,details:u instanceof Error?u.message:String(u)})}finally{i(!1)}};return t.jsxs("div",{className:"px-3 py-2",children:[t.jsx("div",{className:"flex items-center gap-2 text-sm",children:t.jsxs("button",{type:"button",onClick:g,className:"flex min-w-0 flex-1 items-center gap-2 text-left",children:[t.jsx("span",{className:"shrink-0 font-mono text-xs text-og-500",title:e.id,children:pn(e.id)}),t.jsx("span",{className:"min-w-0 flex-1 truncate text-og-1000",title:e.title,children:e.title}),l>0&&t.jsx("span",{"aria-label":n.agents.round(l),className:"shrink-0 text-xs text-og-400",children:n.taskPanel.round(l)}),t.jsx(fn,{task:e,className:"shrink-0"})]})}),e.attention&&h&&t.jsxs("div",{className:"mt-2 rounded border border-accent/25 bg-accent-soft/60 px-2 py-1.5 text-xs text-accent",children:[t.jsxs("button",{type:"button",onClick:g,className:"block w-full text-left",children:[t.jsx("span",{className:"font-medium",children:h.title}),t.jsx("span",{className:"mt-0.5 block text-og-700",children:h.guidance})]}),t.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1.5",children:e.attention.recommendedActions.map(u=>t.jsx("button",{type:"button",disabled:u==="advance"&&a,onClick:()=>u==="advance"?void f():g(),className:u==="advance"?"btn-primary":"btn-secondary",children:u==="advance"?a?n.taskDetail.advancing:m:u==="verdict"?n.taskDetail.handleReview:u==="cancel"?n.taskDetail.cancelConfirmLabel:n.taskDetail.retryTask},u))}),t.jsxs("details",{className:"mt-1.5 text-og-500",children:[t.jsx("summary",{className:"cursor-pointer select-none text-accent",children:n.common.technicalDetails}),t.jsxs("div",{className:"mt-1 whitespace-pre-wrap break-words font-mono",children:[e.attention.reason,`
11
+ `,e.attention.runbook]})]})]})]})}const Da=[],Rs="baxian.taskPanel.open";function $a(){try{return localStorage.getItem(Rs)!=="0"}catch{return!0}}function Ia(){const{id:e}=Pt(),n=Ee(),s=q(),{show:r}=ke(),{refresh:a}=at(),[i,l]=o.useState(null),[c,m]=o.useState(null),[h,g]=o.useState(!1),[f,u]=o.useState(!1),d=o.useRef(null),[x,y]=o.useState($a),[w,C]=o.useState(!1),[S,R]=o.useState(""),[v,b]=o.useState(!1),[j,k]=o.useState(null),E=o.useRef(0),{data:I,loaded:_,error:F}=vn(),{data:ee,error:z}=js(e),K=(F==null?void 0:F.message)??null,ae=(z==null?void 0:z.message)??null,X=ee??Da,te=new Map((I??[]).map(H=>[H.id,H])),Y=c??K??ae,ne=o.useCallback(async H=>{const le=++E.current;try{const ce=await D.projects.get(H);if(le!==E.current)return;l(ce),m(null)}catch(ce){if(le!==E.current)return;m(ce instanceof Error?ce.message:String(ce))}},[]);o.useEffect(()=>{e&&(l(null),m(null),ne(e))},[e,ne]),o.useEffect(()=>{w||(R(""),k(null))},[w]),o.useEffect(()=>{try{localStorage.setItem(Rs,x?"1":"0")}catch{}},[x]);const Z=(i==null?void 0:i.agent.flat().length)??0,J=Z===0,me=!!i&&S.trim()===i.id,ge=async()=>{if(!(!i||!me||v)){b(!0),k(null);try{await D.projects.delete(i.id),await a(),r({kind:"success",title:s.projectPage.deletedToastTitle(i.id)}),C(!1),n("/")}catch(H){k(H instanceof Error?H.message:String(H))}finally{b(!1)}}};return i?t.jsxs("div",{children:[t.jsxs(ws,{children:[t.jsx("button",{type:"button",onClick:()=>u(!0),className:"btn-ghost",children:s.projectPage.newTaskButton}),t.jsx(sn,{ariaLabel:s.projectPage.menuAriaLabel(i.id),menuClassName:"min-w-[180px]",triggerRef:d,children:H=>t.jsxs(t.Fragment,{children:[!x&&t.jsx(Ne,{onClick:()=>{H(),y(!0)},children:s.projectPage.showTaskPanel}),t.jsx(Ne,{onClick:()=>{H(),g(!0)},children:s.projectPage.addAgent}),t.jsx("div",{role:"none",className:"my-1 border-t border-hairline"}),t.jsx(Ne,{onClick:()=>{H(),C(!0)},disabled:!J,title:J?void 0:s.projectPage.deleteAgentsFirstHint(Z),children:s.projectPage.deleteProjectMenuItem})]})})]}),Y&&t.jsx("div",{className:"mb-4 text-sm text-accent",children:s.common.loadFailed(Y)}),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((H,le)=>t.jsx(gs,{team:H,projectId:i.id,agentsById:te,agentsLoaded:_,agentsError:!!F,tasks:X,onDeleted:()=>{ne(i.id)},terminalMode:"embedded-full"},H.map(ce=>ce.id).join(":")||le))})]}),x&&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 H;y(!1),(H=d.current)==null||H.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(La,{projectId:i.id,openTasks:X})]})]}),t.jsx(xs,{open:h,projectId:i.id,onClose:()=>g(!1),onCreated:()=>{ne(i.id)}}),t.jsx(gn,{open:f,projectId:i.id,onClose:()=>u(!1),onCreated:H=>n(Me(H.projectId,H.id))}),t.jsx(Se,{open:w,onClose:()=>{v||C(!1)},title:s.projectPage.deleteModalTitle,size:"sm",footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:()=>C(!1),disabled:v,className:"btn-secondary",children:s.common.cancel}),t.jsx("button",{type:"button",onClick:()=>void ge(),disabled:!me||v,className:"btn-primary",children:v?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:H=>R(H.target.value),placeholder:i.id,autoComplete:"off",autoCorrect:"off",spellCheck:!1,disabled:v,"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"}),j&&t.jsx("div",{className:"rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-xs text-accent",children:j})]})})]}):c?t.jsx("div",{className:"text-sm text-accent",children:s.common.loadFailed(c)}):t.jsx("div",{className:"text-sm text-og-500",children:s.common.loading})}const Cs={approve:"pill pill-live","request-changes":"pill pill-warn",comment:"pill"};function As(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 st(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 Dt(e){if(e.id)return e.sourceKey!==void 0?`pr-${e.kind}.${e.sourceKey}.${e.id}`:`pr-${e.kind}-${e.id}`}function Ps(e,n){return e.review?`round-${st(e.review,n)}`:`round-in-progress-${e.items[0]?st(e.items[0],n):n}`}function Ls(e){const n=e.closedUnmergedAnchor;return[e.reviewRound,e.latestHeadSha??"",e.status,e.reviewDispatchedAt??"",e.prFeedbackReceivedAt??"",e.prNumber??"",e.reviewConversationUpdatedAt??"",n===void 0?"":`${n.generation}/${n.cleared===!0?"reopened":"closed"}`].join(":")}const Ba=4e3,Ma=6e4;function Es(e,n){const[s,r]=o.useState(null),[a,i]=o.useState(!1),[l,c]=o.useState(null),[m,h]=o.useState(!1),[g,f]=o.useState(null),[u,d]=o.useState(0),x=o.useRef(e),y=o.useRef(n),w=o.useRef(0),C=o.useRef(0),S=o.useRef(void 0),R=o.useRef(0),v=o.useRef(null);o.useEffect(()=>{const j=()=>{v.current!==null&&(v.current=null,h(!1),f(null))};x.current!==e&&(x.current=e,r(null),i(!1),f(null),C.current=0,j()),y.current!==n&&(y.current=n,C.current=0,j());const k=++w.current;return c(null),D.tasks.prReview(e).then(E=>{if(w.current===k)if(r(E),i(!0),E.available&&E.error&&C.current<3){C.current+=1;const I=E.rateLimited?Ma*2**(C.current-1):Ba*C.current;S.current=setTimeout(()=>d(_=>_+1),I)}else E.error||(C.current=0)}).catch(E=>{w.current===k&&(c(E instanceof Error?E.message:String(E)),r(null),i(!0))}),()=>{clearTimeout(S.current),S.current=void 0}},[e,n,u]);const b=o.useCallback(()=>{if(v.current!==null)return;const j=++R.current;v.current=j,h(!0),f(null),D.tasks.prReviewRefresh(x.current).then(k=>{if(v.current===j){if(k.available&&(k.error!==void 0||k.rateLimited===!0)){f(k.error??"rate limited");return}clearTimeout(S.current),S.current=void 0,w.current+=1,C.current=0,r(k),i(!0),c(null)}}).catch(k=>{v.current===j&&f(k instanceof Error?k.message:String(k))}).finally(()=>{v.current===j&&(v.current=null,h(!1))})},[]);return{data:s,loaded:a,error:l,refresh:b,refreshing:m,refreshError:g}}function Fa(e){const n=new Date(e);if(Number.isNaN(n.getTime()))return e;const s=r=>String(r).padStart(2,"0");return`${n.getFullYear()}-${s(n.getMonth()+1)}-${s(n.getDate())} ${s(n.getHours())}:${s(n.getMinutes())}:${s(n.getSeconds())}`}function Ds({data:e,onRefresh:n,refreshing:s,refreshError:r}){const a=q(),i=e.autoRefresh===!0?e.autoRefreshIntervalMs:void 0,[l,c]=o.useState(void 0),m=o.useRef(Date.now());return o.useEffect(()=>{m.current=Date.now()},[e]),o.useEffect(()=>{if(i===void 0||i<=0){c(void 0);return}const h=()=>{const f=Date.now()-m.current;c(Math.ceil((i-f%i)/1e3))};h();const g=setInterval(h,1e3);return()=>clearInterval(g)},[i,e]),e.available?t.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-og-400",children:[e.fetchedAt&&t.jsx("span",{children:a.prReview.fetchedAtLabel(Fa(e.fetchedAt))}),e.autoRefresh===!1&&t.jsx("span",{children:a.prReview.autoRefreshStopped}),e.autoRefresh===!0&&l!==void 0&&t.jsx("span",{children:a.prReview.nextCheck(l)}),t.jsx("button",{type:"button",className:"text-accent hover:text-accent-hover disabled:opacity-60",onClick:n,disabled:s,children:s?a.prReview.refreshing:a.prReview.refresh}),r&&t.jsx("span",{className:"text-accent",children:a.prReview.refreshFailed(r)})]}):null}function Oa({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 _a(e){return{"no-pr":e.prReview.reasonNoPr,"driver-unavailable":e.prReview.reasonDriverUnavailable}}function Ha(e){return(e==null?void 0:e.trim().split(`
12
+ `,1)[0])??""}function qa(e){if(!(e.kind!=="review-comment"||!e.path))return e.line!==void 0?`${e.path}:${e.line}`:e.path}function Ua(e,n){return n.bodyTruncated?e.prReview.truncatedSuffix:""}function Ga(e,n){const s=Ha(n.body),r=Ua(e,n);if(n.kind==="review-comment"){const a=qa(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 Wa(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 za(e){return e.verdict!==void 0?"qa":e.kind==="issue-comment"||e.inReplyTo?"dev":"qa"}function Va({task:e}){const n=q(),s=Ee(),r=Ls(e),{data:a,loaded:i,error:l,refresh:c,refreshing:m,refreshError:h}=Es(e.id,r),g=Be(e.phase)?n.prReview.specReviewHeading:n.prReview.codeReviewHeading;function f(x){s(`/tasks/${encodeURIComponent(e.id)}/pr-review${x?`#${x}`:""}`)}if(l)return t.jsx(Ze,{title:g,children:t.jsx("div",{className:"text-sm text-accent",children:n.review.loadFailed(l)})});if(!i)return t.jsx(Ze,{title:g,children:t.jsx("div",{className:"text-sm text-og-400",children:n.review.loadingRecords})});if(!(a!=null&&a.available)){const x=_a(n);return t.jsx(Ze,{title:g,children:t.jsx("div",{className:"text-sm text-og-400",children:x[(a==null?void 0:a.reason)??"no-pr"]??x["no-pr"]})})}const u=t.jsx(Ds,{data:a,onRefresh:c,refreshing:m,refreshError:h});if(a.items.length===0)return t.jsxs(Ze,{title:g,children:[u,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 d=As(a.items);return t.jsxs(Ze,{title:g,children:[u,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}),d.map((x,y)=>t.jsx(Ka,{round:x,index:y,onOpen:f},Ps(x,String(y))))]})}function Ze({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 Ka({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(Bn,{item:i,onOpen:s},st(i,`${n}-${l}`))),e.review&&t.jsx(Bn,{item:e.review,onOpen:s})]})]})}function Bn({item:e,onOpen:n}){const s=q(),r=e.verdict,a=r?t.jsx("span",{className:Cs[r],children:r}):e.kind==="review"&&e.reviewState?t.jsx("span",{className:"pill",children:e.reviewState}):void 0;return t.jsx(Oa,{role:za(e),label:Wa(s,e),badge:a,summary:Ga(s,e),onClick:()=>n(Dt(e))})}function Ya({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(Va,{task:e})]})}const Qa=zn;function Ja(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 Mn(e){if(!/^[1-9]\d*$/.test(e.trim()))return;const n=Number(e);return Number.isSafeInteger(n)?n:void 0}function Xa(e){return e.status==="review"&&!Be(e.phase)}function wt({children:e}){const n=q();return t.jsxs("details",{className:"mt-2 text-xs text-og-500",children:[t.jsx("summary",{className:"cursor-pointer select-none text-accent",children:n.common.technicalDetails}),t.jsx("div",{className:"mt-1 whitespace-pre-wrap break-words font-mono",children:e})]})}function Za(){const{taskId:e=""}=Pt();return t.jsx(ei,{taskId:e},e)}function ei({taskId:e}){var ut;const n=Ee(),s=q(),{show:r}=ke(),a=mn(),[i,l]=o.useState(!1),[c,m]=o.useState(!1),[h,g]=o.useState(!1),[f,u]=o.useState(!1),[d,x]=o.useState(!1),[y,w]=o.useState("spec"),[C,S]=o.useState(""),[R,v]=o.useState(!1),[b,j]=o.useState(!1),[k,E]=o.useState(!1),[I,_]=o.useState(""),[F,ee]=o.useState(!1),[z,K]=o.useState(""),[ae,X]=o.useState(!1),[te,Y]=o.useState(null),{data:ne,loaded:Z,error:J}=ks(e),{projects:me,error:ge}=at(),{data:H,loaded:le,error:ce}=vn(),{activeAgentId:ie,activateAgentCard:we}=ps(),N=te??ne,xe=N!==null&&Xa(N),be=xe&&(ae||((ut=N==null?void 0:N.attention)==null?void 0:ut.recommendedActions.includes("verdict"))===!0),P=(J==null?void 0:J.message)??null,T=N?me==null?void 0:me.find(p=>p.id===N.projectId):void 0,B=T===void 0?"unknown":T.merge==="auto"?"auto":"manual",M=me===null&&ge===null,he=o.useMemo(()=>new Map((H??[]).map(p=>[p.id,p])),[H]);o.useEffect(()=>{te&&ne&&ne.updatedAt>=te.updatedAt&&Y(null)},[te,ne]),o.useEffect(()=>{X(!1)},[N==null?void 0:N.status,N==null?void 0:N.reviewRound]);const se=p=>{Y(p)},$=p=>({body:s.taskDetail.actionFailedBody,details:p instanceof Error?p.message:String(p)}),A=(p,O)=>{const G=O??(p.status==="review"?"qa":"dev");return p.status==="pending"?p.preferredAgentId===""?s.taskDetail.editTask:s.taskDetail.startTask:G==="qa"&&p.status!=="review"?s.taskDetail.startReview:p.status==="review"?s.taskDetail.restartReview:p.status==="approved"?s.taskDetail.retryPreMergeCheck:s.taskDetail.retryCurrentStep},L=()=>M?s.taskDetail.loadingMergeSetting:B==="auto"?s.taskDetail.confirmAndMerge:B==="manual"?s.taskDetail.confirmComplete:s.taskDetail.confirmResult,Q=async()=>{if(!N)return;const p=zn.has(N.status);if(await a({title:s.taskDetail.cancelConfirmTitle(N.id),body:p?s.taskDetail.cancelConfirmBodyTerminal:s.taskDetail.cancelConfirmBodyActive,confirmLabel:s.taskDetail.cancelConfirmLabel,cancelLabel:s.common.backText})){m(!0);try{const G=await D.tasks.update(N.id,{status:"cancelled"});se(G),r({kind:"success",title:G.status==="cancelled"?s.taskDetail.cancelledToastTitle:s.taskDetail.cancelCleanupToastTitle})}catch(G){r({kind:"error",title:s.taskDetail.cancelFailedTitle,...$(G)})}finally{m(!1)}}},W=async(p,O,G)=>{u(!0);try{const de=await D.tasks.advance(p.id,{executor:O,...p.status==="pending"&&p.preferredAgentId?{agentId:p.preferredAgentId}:{},...G??{}});se(de),x(!1),r({kind:"success",title:s.taskDetail.advanceSucceededTitle})}catch(de){r({kind:"error",title:s.taskDetail.advanceFailedTitle,...$(de)})}finally{u(!1)}},re=async p=>{var ve;if(!N)return;if(N.status==="pending"&&N.preferredAgentId===""){l(!0);return}const O=p??(N.status==="review"?"qa":"dev"),G=A(N,O);if(O==="qa"&&Un(N)){w(N.phase??"spec"),S(((ve=N.prNumber)==null?void 0:ve.toString())??""),x(!0);return}if(N.postApproveRevoked){if(!await a({title:s.taskDetail.advanceRevokedConfirmTitle,body:N.postApproveRevoked.reason==="request-changes"?s.taskDetail.advanceRevokedRequestChangesBody:s.taskDetail.advanceRevokedRetryLimitBody,confirmLabel:G}))return;await W(N,O,{confirmRevoked:!0});return}await a({title:s.taskDetail.advanceConfirmTitle(G),body:N.status==="pending"?s.taskDetail.startTaskConfirmBody(N.id,N.preferredAgentId):O==="qa"&&N.status==="review"?s.taskDetail.restartReviewConfirmBody(N.id):O==="qa"?s.taskDetail.startReviewConfirmBody(N.id):N.status==="approved"?s.taskDetail.retryPreMergeConfirmBody:s.taskDetail.retryCurrentStepConfirmBody(N.id),confirmLabel:G})&&await W(N,O)},ye=async()=>{if(!(!N||!await a({title:s.taskDetail.retryConfirmTitle(N.id),body:N.status==="merged"?s.taskDetail.retryConfirmBodyMerged:s.taskDetail.retryConfirmBodyDefault,confirmLabel:s.taskDetail.retryTask}))){g(!0);try{const O=await D.tasks.retry(N.id);r({kind:"success",title:s.taskDetail.retryCreatedToastTitle(O.id)}),n(Me(O.projectId,O.id))}catch(O){r({kind:"error",title:s.taskDetail.retryFailedTitle,...$(O)})}finally{g(!1)}}},He=async()=>{if(N&&await a({title:s.taskDetail.markCompleteConfirmTitle,body:s.taskDetail.markCompleteConfirmBody(N.prNumber??0),confirmLabel:s.taskDetail.verdictComplete})){v(!0);try{const p=await D.tasks.verdict(N.id,{action:"complete"});se(p),r({kind:"success",title:s.taskDetail.markCompleteToastTitle})}catch(p){r({kind:"error",title:s.taskDetail.markCompleteFailedTitle,...$(p)})}finally{v(!1)}}},Re=async()=>{if(N&&await a({title:s.taskDetail.continueConfirmTitle,body:s.taskDetail.continueConfirmBody(N.reviewRound+1),confirmLabel:s.taskDetail.verdictContinue})){j(!0);try{const p=await D.tasks.verdict(N.id,{action:"continue"});se(p),r({kind:"success",title:s.taskDetail.continuedToastTitle(p.reviewRound)})}catch(p){r({kind:"error",title:s.taskDetail.continueFailedTitle,...$(p)})}finally{j(!1)}}},Ce=async(p,O)=>{if(N){E(!0);try{const G=await D.tasks.verdict(N.id,{action:p.verdict,...p.comments!==void 0?{comments:p.comments}:{}});se(G),_(""),r({kind:"success",title:O.success})}catch(G){r({kind:"error",title:O.failure,...$(G)})}finally{E(!1)}}},Ae=async()=>{N&&await a({title:s.taskDetail.specApproveConfirmTitle,body:s.taskDetail.specApproveConfirmBody(N.id),confirmLabel:s.taskDetail.specApprove})&&await Ce({verdict:"approve"},{success:s.taskDetail.specApprovedToastTitle,failure:s.taskDetail.specApproveFailedTitle})},it=async()=>{const p=I.trim();p&&await Ce({verdict:"request-changes",comments:p},{success:s.taskDetail.specRejectedToastTitle,failure:s.taskDetail.specRejectFailedTitle})},Ye=async p=>{if(!N)return;const O=z.trim();if(!(p==="request-changes"&&!O||!await a({title:p==="pass"?s.taskDetail.codePassConfirmTitle:s.taskDetail.codeRejectConfirmTitle,body:s.taskDetail.codeVerdictConfirmBody,confirmLabel:p==="pass"?s.taskDetail.codePass:s.taskDetail.codeRequestChanges}))){ee(!0);try{const de=await D.tasks.verdict(N.id,{action:p,...O?{comments:O}:{}});se(de),K(""),r({kind:"success",title:s.taskDetail.codeVerdictSubmittedTitle})}catch(de){r({kind:"error",title:s.taskDetail.codeVerdictFailedTitle,...$(de)})}finally{ee(!1)}}},ot=()=>{var p;(p=document.getElementById("task-verdict-controls"))==null||p.scrollIntoView({behavior:"smooth",block:"center"})},lt=async()=>{if(!N||M)return;const p=N.prNumber??0,O=B==="auto"?s.taskDetail.confirmAutoMergeTitle(p):B==="manual"?s.taskDetail.confirmManualCompleteTitle:s.taskDetail.confirmResultTitle,G=B==="auto"?s.taskDetail.confirmAutoMergeBody(p):B==="manual"?s.taskDetail.confirmManualCompleteBody(p):s.taskDetail.confirmResultBody;if(await a({title:O,body:G,confirmLabel:L()})){v(!0);try{const de=await D.tasks.verdict(N.id,{action:"confirm-merge"});se(de),r({kind:"success",title:de.status==="merged"?s.taskDetail.confirmedMergedToastTitle:s.taskDetail.confirmedCompleteToastTitle})}catch(de){r({kind:"error",title:s.taskDetail.confirmFailedTitle,...$(de)})}finally{v(!1)}}};return t.jsxs("div",{children:[t.jsx("button",{type:"button",onClick:()=>n(-1),className:"btn-ghost mb-3",children:s.common.back}),P&&!N&&t.jsx("div",{className:"text-sm text-accent",children:s.common.loadFailed(P)}),Z&&!N&&!P&&t.jsx("div",{className:"text-sm text-accent",children:s.taskDetail.taskNotFound(e)}),!N&&!P&&!Z&&t.jsx("div",{className:"text-sm text-og-500",children:s.common.loading}),N&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mb-4",children:t.jsxs("h1",{className:"flex min-w-0 items-baseline gap-2",children:[t.jsx("span",{className:"shrink-0 font-mono text-sm text-og-400",children:N.id}),t.jsx("span",{className:"min-w-0 truncate font-display text-sm font-semibold tracking-tight text-og-1000",title:N.title,children:N.title})]})}),t.jsxs("div",{className:"grid grid-cols-1 items-start gap-6 lg:grid-cols-2",children:[t.jsx("section",{className:"min-w-0",children:ct(N)}),t.jsx("aside",{className:"min-w-0 space-y-4",children:je(N)})]})]}),i&&N&&t.jsx(gn,{mode:"edit",open:!0,onClose:()=>l(!1),task:N,onUpdated:se}),d&&N&&t.jsx(Se,{open:!0,title:s.taskDetail.reviewRecoveryTitle,onClose:()=>{f||x(!1)},size:"sm",dismissOnBackdrop:!f,footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",disabled:f,onClick:()=>x(!1),className:"btn-secondary",children:s.common.cancel}),t.jsx("button",{type:"submit",form:"review-recovery-form",disabled:f||N.prNumber===void 0&&Mn(C)===void 0,className:"btn-primary",children:f?s.taskDetail.advancing:s.taskDetail.reviewRecoverySubmit})]}),children:t.jsxs("form",{id:"review-recovery-form",className:"space-y-4",onSubmit:p=>{p.preventDefault();const O=N.prNumber??Mn(C);O===void 0||f||W(N,"qa",{stage:y,...N.prNumber===void 0?{prNumber:O}:{}})},children:[t.jsx("p",{className:"text-sm text-og-700",children:s.taskDetail.reviewRecoveryBody}),N.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:C,required:!0,disabled:f,onChange:p=>S(p.target.value),placeholder:s.taskDetail.reviewRecoveryPrNumberPlaceholder,className:fe})]}),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:y,required:!0,disabled:f||N.phase!==void 0,onChange:p=>w(p.target.value),className:fe,children:[t.jsx("option",{value:"spec",children:s.taskDetail.reviewRecoveryStageSpec}),t.jsx("option",{value:"code",children:s.taskDetail.reviewRecoveryStageCode})]})]})]})})]});function ct(p){var ft;const O=p.preferredAgentId==="",G=p.status==="approved"&&p.prNumber!==void 0,de=p.status==="merge-ready"&&p.prNumber!==void 0,ve=p.status==="spec-ready",Pe=be,It=p.status==="max_rounds"&&!Be(p.phase),mt=p.status==="max_rounds"&&Be(p.phase),Le=Vn(p.prUrl),ht=Ja(Le??void 0,p.branch??""),Ue=p.attention?ms(s,p.attention):null;return t.jsxs("div",{children:[P&&t.jsx("div",{className:"mb-4 text-sm text-accent",children:s.common.loadFailed(P)}),p.branchCleanupPending&&t.jsxs("div",{className:"mb-4 rounded-md border border-accent/25 bg-accent-soft/60 px-3 py-2.5 text-xs text-accent",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.branchCleanupPendingTitle}),t.jsx("div",{className:"mt-1 text-og-700",children:s.taskDetail.branchCleanupPendingBody}),t.jsx(wt,{children:p.branchCleanupPending.reason})]}),p.branchCleanupSkipped&&t.jsxs("div",{className:"mb-4 rounded-md border border-hairline bg-og-25 px-3 py-2.5 text-xs text-og-700",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.branchCleanupSkippedTitle}),t.jsx("div",{className:"mt-1",children:s.taskDetail.branchCleanupSkippedBody}),t.jsx(wt,{children:p.branchCleanupSkipped.reason})]}),O&&t.jsx("div",{className:"mb-4 rounded-md border border-accent/25 bg-accent-soft/60 px-3 py-2.5 text-xs text-accent",children:p.status==="pending"?s.taskDetail.unassignedPendingNotice:s.taskDetail.unassignedReadonlyNotice}),t.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-3",children:[t.jsx(fn,{task:p,className:"text-sm"}),(p.specReviewRound??0)>0&&t.jsx("span",{className:"text-sm text-og-500",children:s.taskDetail.specReviewRound(p.specReviewRound??0)}),p.reviewRound>0&&t.jsx("span",{className:"text-sm text-og-500",children:s.taskDetail.codeReviewRound(p.reviewRound)})]}),t.jsx("div",{className:"mb-4 flex flex-wrap items-center gap-2",children:$t(p)}),t.jsxs("div",{className:"mb-4 text-sm text-og-500",children:[s.taskDetail.createdAtPrefix,qt(p.createdAt,!1),s.taskDetail.updatedAtPrefix,qt(p.updatedAt,!1)]}),p.attention&&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:Ue.title}),t.jsx("div",{className:"mt-1 text-og-700",children:Ue.guidance}),t.jsx("div",{className:"mt-1 text-xs text-og-500",children:qt(p.attention.occurredAt)}),t.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:U(p)}),t.jsx(wt,{children:`${p.attention.reason}
13
+ ${p.attention.runbook}`})]}),G&&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}),Le&&t.jsx("a",{href:Le,target:"_blank",rel:"noopener noreferrer",className:"btn-secondary mt-3",children:s.taskDetail.viewPr(p.prNumber??0)})]}),de&&t.jsxs("div",{id:"task-verdict-controls",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:B==="auto"?s.taskDetail.mergeReadyAutoBody(p.prNumber??0):B==="manual"?s.taskDetail.mergeReadyManualBody(p.prNumber??0):M?s.taskDetail.mergeReadyLoadingBody:s.taskDetail.mergeReadyUnknownBody}),B==="unknown"&&ge&&t.jsx(wt,{children:ge}),Le&&t.jsx("a",{href:Le,target:"_blank",rel:"noopener noreferrer",className:"btn-secondary mt-3",children:s.taskDetail.viewPr(p.prNumber??0)})]}),ve&&t.jsxs("div",{id:"task-verdict-controls",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(p.specReviewRound??0)}),Qe()]}),Pe&&t.jsxs("div",{id:"task-verdict-controls",className:`mb-4 rounded-lg p-4 text-sm ${((ft=p.attention)==null?void 0:ft.reason)==="review-verdict-overdue"?"border border-accent/25 bg-accent-soft text-accent":"border border-hairline bg-og-25 text-og-800"}`,children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.codeVerdictTitle}),t.jsx("div",{className:"mt-1 text-og-700",children:s.taskDetail.codeVerdictBody}),dt()]}),It&&t.jsxs("div",{id:"task-verdict-controls",className:"mb-4 rounded-lg border border-accent/25 bg-accent-soft/60 p-4 text-sm text-accent",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.codeMaxRoundsTitle(p.reviewRound)}),t.jsx("div",{className:"mt-1 text-og-700",children:s.taskDetail.codeMaxRoundsBody})]}),mt&&t.jsxs("div",{id:"task-verdict-controls",className:"mb-4 rounded-lg border border-accent/25 bg-accent-soft/60 p-4 text-sm text-accent",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.specMaxRoundsTitle(p.specReviewRound??0)}),t.jsx("div",{className:"mt-1 text-og-700",children:s.taskDetail.specMaxRoundsBody}),Qe()]}),t.jsxs("div",{className:"card mb-4 flex flex-wrap items-center gap-x-6 gap-y-1 p-4 text-sm",children:[t.jsxs("span",{className:"text-og-500",children:["PR:"," ",p.prNumber?Le?t.jsxs("a",{href:Le,target:"_blank",rel:"noopener noreferrer",className:"text-accent hover:text-accent-hover",children:["#",p.prNumber]}):t.jsxs("span",{className:"font-mono text-og-800",children:["#",p.prNumber]}):t.jsx("span",{className:"text-og-400",children:"—"})]}),t.jsxs("span",{className:"text-og-500",children:["Branch:"," ",p.branch?ht?t.jsx("a",{href:ht,target:"_blank",rel:"noopener noreferrer",className:"font-mono text-accent hover:text-accent-hover",children:p.branch}):t.jsx("span",{className:"font-mono text-og-800",children:p.branch}):t.jsx("span",{className:"text-og-400",children:"—"})]})]}),t.jsx("pre",{className:"card mb-4 whitespace-pre-wrap p-4 text-sm text-og-800",children:p.description||t.jsx("span",{className:"text-og-400",children:s.taskDetail.noDescription})}),t.jsx(Ya,{task:p})]})}function Qe(){return t.jsxs("div",{className:"mt-3 flex flex-col gap-2",children:[t.jsx("textarea",{value:I,onChange:p=>_(p.target.value),placeholder:s.taskDetail.specCommentsPlaceholder,rows:3,disabled:k,className:fe}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",disabled:k,onClick:Ae,className:"btn-primary",children:k?s.taskDetail.submitting:s.taskDetail.specApproveButton}),t.jsx("button",{type:"button",disabled:k||I.trim()==="",onClick:it,title:I.trim()===""?s.taskDetail.specRejectTitleEmpty:s.taskDetail.specRejectTitleReady,className:"btn-secondary",children:k?s.taskDetail.submitting:s.taskDetail.specReject})]})]})}function dt(){return t.jsxs("div",{className:"mt-3 flex flex-col gap-2",children:[t.jsx("textarea",{value:z,onChange:p=>K(p.target.value),placeholder:s.taskDetail.codeCommentsPlaceholder,rows:3,disabled:F,className:fe}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",disabled:F,onClick:()=>void Ye("pass"),className:"btn-secondary",children:F?s.taskDetail.submitting:s.taskDetail.codePass}),t.jsx("button",{type:"button",disabled:F||z.trim()==="",onClick:()=>void Ye("request-changes"),className:"btn-secondary",children:F?s.taskDetail.submitting:s.taskDetail.codeRequestChanges})]})]})}function U(p){var O;return(O=p.attention)==null?void 0:O.recommendedActions.map(G=>G==="advance"?t.jsx("button",{type:"button",disabled:f,onClick:()=>void re(),className:"btn-primary",children:f?s.taskDetail.advancing:A(p)},G):G==="verdict"?t.jsx("button",{type:"button",onClick:ot,className:"btn-primary",children:s.taskDetail.handleReview},G):G==="cancel"?t.jsx("button",{type:"button",disabled:c,onClick:Q,className:"btn-secondary",children:c?s.taskDetail.cancelling:s.taskDetail.cancelConfirmLabel},G):t.jsx("button",{type:"button",disabled:h,onClick:ye,className:"btn-secondary",children:h?s.common.retrying:s.taskDetail.retryTask},G))}function je(p){if(me===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 O=(T==null?void 0:T.agent.find(ve=>ve.some(Pe=>Pe.id===p.devAgentId)))??(p.qaAgentId?T==null?void 0:T.agent.find(ve=>ve.some(Pe=>Pe.id===p.qaAgentId)):void 0),G=O==null?void 0:O.find(ve=>ve.role==="dev"&&ve.id===p.devAgentId),de=p.qaAgentId?O==null?void 0:O.find(ve=>ve.role==="qa"&&ve.id===p.qaAgentId):void 0;return!G&&!de?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:[G?qe(p,G):t.jsx(Fn,{role:"dev"}),de?qe(p,de):t.jsx(Fn,{role:"qa"})]})}function qe(p,O){const G=he.get(O.id),de=G??{id:O.id,projectId:p.projectId,runtimeStatus:"unknown",tmuxSessionStatus:"unknown",stale:!0};return t.jsx(fs,{agent:de,projectId:p.projectId,role:O.role,runtime:O.runtime,model:O.model,pendingRestart:le&&!G,terminalLoading:!le&&!G&&!ce,showTaskBinding:!1,terminalMode:"embedded-full",active:ie===O.id,onActivate:()=>we(O.id),task:p},O.id)}function $t(p){const G=p.status==="max_rounds"&&!Be(p.phase),de=p.status==="merge-ready",ve=p.status==="pending",Pe=Qa.has(p.status),It=Pe&&!!p.preferredAgentId,mt=p.preferredAgentId==="",Le=["pending","in_progress","fixing","review","approved"].includes(p.status)&&!(p.status==="pending"&&mt),ht=(p.status==="in_progress"||p.status==="fixing")&&p.qaAgentId!==void 0,Ue=G&&p.prNumber!==void 0,ft=Ue&&!!p.agentId,Fs=xe&&!be;return t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",disabled:!ve,onClick:()=>l(!0),className:"btn-secondary",children:s.taskDetail.editTask}),t.jsx("button",{type:"button",disabled:c,onClick:Q,title:s.taskDetail.cancelForceTitle,className:"btn-secondary",children:c?s.taskDetail.cancelling:s.taskDetail.cancelConfirmLabel}),Pe&&p.replacementTaskId===void 0&&t.jsx("button",{type:"button",disabled:!It||h,onClick:ye,title:mt?s.taskDetail.retryDisabledUnassignedTitle:s.taskDetail.retryEnabledTitle,className:"btn-secondary",children:h?s.common.retrying:s.taskDetail.retryTask}),Le&&t.jsx("button",{type:"button",disabled:f,onClick:()=>void re(),className:"btn-primary",children:f?s.taskDetail.advancing:A(p)}),ht&&t.jsx("button",{type:"button",disabled:f,onClick:()=>void re("qa"),className:"btn-secondary",children:A(p,"qa")}),Fs&&t.jsx("button",{type:"button",onClick:()=>X(!0),className:"btn-secondary",children:s.taskDetail.handleReview}),G&&t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",disabled:!ft||b,onClick:Re,title:s.taskDetail.continueButtonTitle,className:"btn-secondary",children:b?s.taskDetail.continuing:s.taskDetail.verdictContinue}),t.jsx("button",{type:"button",disabled:!Ue||R,onClick:He,title:s.taskDetail.completeButtonTitle,className:"btn-primary",children:R?s.taskDetail.completing:s.taskDetail.verdictComplete})]}),de&&t.jsx("button",{type:"button",disabled:R||M,onClick:lt,title:M?s.taskDetail.confirmLoadingTitle:s.taskDetail.confirmButtonTitle,className:"btn-primary",children:R?s.taskDetail.confirming:L()})]})}}function Fn({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)})}function ti(){const{agentId:e}=Pt(),{projects:n}=at(),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:Wn(e,s),children:e})]}),t.jsx("div",{className:"min-h-0 flex-1",children:t.jsx(et,{agentId:e,mode:"full",interactive:!0,arrowKeys:!0})})]}):t.jsx("div",{className:"text-sm text-accent",children:"No agent specified"})}const ni=65536,si=8e3,ri=["text-[18px] font-bold","text-[17px] font-bold","text-[16px] font-semibold","text-[15px] font-semibold","text-[15px] font-semibold","text-[15px] font-semibold"],ai=/^(https?:\/\/|mailto:)/i,ii=/^https?:\/\//i;function oi(e){try{const n=new URL(e).hostname.toLowerCase();return n==="githubusercontent.com"||n.endsWith(".githubusercontent.com")}catch{return!1}}function li({src:e,alt:n}){const s=q(),[r,a]=o.useState(!1);if(r||oi(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 On(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 ci(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 _n(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 c=s.whitespace(i);return c!==-1&&c<l?null:{label:e.slice(r,a),url:e.slice(i,l),end:l+1}}class $s extends Error{}class di{constructor(n){oe(this,"count",0);this.max=n}charge(){if(++this.count>this.max)throw new $s}}function We(e,n,s){const r=[];let a="",i=0;const l={bracket:On(e,"]"),paren:On(e,")"),whitespace:ci(e)},c=()=>{a!==""&&(n.charge(),r.push(a),a="")},m=g=>{c(),n.charge(),r.push(g)},h=()=>`${s}-${r.length}`;for(;i<e.length;){const g=e[i];if(g==="`"){const f=e.indexOf("`",i+1);if(f!==-1){const u=e.slice(i+1,f);c(),n.charge(),n.charge(),r.push(t.jsx("code",{className:"rounded bg-og-25 px-1 font-mono text-xs",children:u},h())),i=f+1;continue}}else if(g==="!"&&e[i+1]==="["){const f=_n(e,i+1,l);if(f){ii.test(f.url)?m(t.jsx(li,{src:f.url,alt:f.label},h())):a+=e.slice(i,f.end),i=f.end;continue}}else if(g==="["){const f=_n(e,i,l);if(f){if(ai.test(f.url)){c(),n.charge();const u=We(f.label,n,`${s}-a${r.length}`);r.push(t.jsx("a",{href:f.url,target:"_blank",rel:"noopener noreferrer",className:"text-accent hover:text-accent-hover",children:u},h()))}else a+=e.slice(i,f.end);i=f.end;continue}}else if(g==="*"){if(e.startsWith("***",i)){const u=e.indexOf("***",i+3);if(u>i+3){c(),n.charge(),n.charge();const d=We(e.slice(i+3,u),n,`${s}-bi${r.length}`);r.push(t.jsx("strong",{children:t.jsx("em",{children:d})},h())),i=u+3;continue}}if(e.startsWith("**",i)){const u=e.indexOf("**",i+2);if(u>i+2){c(),n.charge();const d=We(e.slice(i+2,u),n,`${s}-b${r.length}`);r.push(t.jsx("strong",{children:d},h())),i=u+2;continue}}const f=e.indexOf("*",i+1);if(f>i+1){c(),n.charge();const u=We(e.slice(i+1,f),n,`${s}-i${r.length}`);r.push(t.jsx("em",{children:u},h())),i=f+1;continue}}a+=g,i++}return c(),r}function ui(e,n){const s=[],r=e.split(`
14
+ `);let a=[];const i=()=>{if(a.length===0)return;const l=a;a=[],n.charge();const c=[];l.forEach((m,h)=>{h>0&&(n.charge(),c.push(t.jsx("br",{},`br-${s.length}-${h}`))),c.push(...We(m,n,`p${s.length}-l${h}`))}),s.push(t.jsx("p",{children:c},`p-${s.length}`))};for(let l=0;l<r.length;l++){const c=r[l];if(c.startsWith("```")){i();const h=[];let g=l+1;for(;g<r.length&&!/^```\s*$/.test(r[g]);)h.push(r[g]),g++;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:h.join(`
15
+ `)})},`pre-${s.length}`)),l=g;continue}const m=/^(#{1,6}) (.*)$/.exec(c);if(m){i(),n.charge();const h=m[1].length,g=`h${h}`;s.push(t.jsx(g,{className:ri[h-1],children:We(c,n,`h${s.length}`)},`h-${s.length}`));continue}if(c.trim()===""){i();continue}a.push(c)}return i(),s}function mi(e){if(typeof e!="string")return[];if(e.length>ni)return null;const n=new di(si);try{return n.charge(),ui(e.replace(/\r\n/g,`
16
+ `),n)}catch(s){if(s instanceof $s)return null;throw s}}function hi({text:e}){const n=o.useMemo(()=>mi(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 fi={approve:"approve","request-changes":"request-changes",comment:"comment"};function pi(e){return e==="no-pr"||e==="driver-unavailable"?e:void 0}function gi(e){return{"no-pr":e.prReview.reasonNoPr,"driver-unavailable":e.prReview.reasonDriverUnavailable}}function Is(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 xi(){const e=q(),{taskId:n=""}=Pt(),s=Ee(),{hash:r}=qn(),{data:a}=ks(n),i=a?Ls(a):void 0,{data:l,loaded:c,error:m,refresh:h,refreshing:g,refreshError:f}=Es(n,i),[u,d]=o.useState(null),x=(l==null?void 0:l.prNumber)??(a==null?void 0:a.prNumber),y=(l==null?void 0:l.prUrl)??(a==null?void 0:a.prUrl),w=Vn(y),C=l?As(l.items):[],S=c&&!m&&(l==null?void 0:l.available)===!0&&l.items.length>0,R=Be(a==null?void 0:a.phase)?e.prReview.specReviewHeading:e.prReview.codeReviewHeading,v=o.useRef(null),b=o.useRef(void 0);return o.useEffect(()=>()=>clearTimeout(b.current),[]),o.useEffect(()=>{let j=null;if(r)try{j=decodeURIComponent(r.slice(1))}catch{j=null}if(!j){v.current=null,d(null);return}if(v.current===j||!S||!l)return;const k=document.getElementById(j);k&&(v.current=j,k.scrollIntoView({behavior:"smooth",block:"center"}),d(j),clearTimeout(b.current),b.current=setTimeout(()=>d(null),2e3))},[S,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:R}),w&&x!==void 0&&t.jsx("a",{href:w,target:"_blank",rel:"noopener noreferrer",className:"text-accent hover:text-accent-hover",children:e.taskDetail.viewPr(x)}),(l==null?void 0:l.available)&&t.jsx(Ds,{data:l,onRefresh:h,refreshing:g,refreshError:f})]}),!c&&t.jsx("div",{className:"text-sm text-og-500",children:e.common.loading}),c&&m&&t.jsx("div",{className:"text-sm text-accent",children:e.review.loadFailed(m)}),c&&!m&&l&&!l.available&&t.jsx("div",{className:"text-sm text-og-500",children:gi(e)[pi(l.reason)??"no-pr"]}),c&&!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:C.map((j,k)=>t.jsx(bi,{round:j,index:k,flashId:u},Ps(j,String(k))))})]}))]})}function bi({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(Hn,{item:i,flashId:s},st(i,`${n}-${l}`)):t.jsx(vi,{item:i,flashId:s},st(i,`${n}-${l}`))),e.review&&t.jsx(Hn,{item:e.review,flashId:s})]})]})}function Bs(e,n){const s=Dt(e);return`card p-3 text-sm${s&&s===n?" ring-2 ring-accent":""}`}function vi({item:e,flashId:n}){const s=q(),r=e.kind==="review-comment";return t.jsxs("div",{id:Dt(e),className:Bs(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:Is(e.createdAt)})]}),t.jsx(Ms,{item:e})]})}function Hn({item:e,flashId:n}){const s=q(),r=e.verdict??"comment";return t.jsxs("div",{id:Dt(e),className:Bs(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:Cs[r],children:fi[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:Is(e.createdAt)})]}),t.jsx(Ms,{item:e,placeholder:s.prReview.noReviewBody})]})}function Ms({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(hi,{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 yi(){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 wi(){const[e,n]=o.useState(null),[s,r]=o.useState(!1),[a,i]=o.useState(null);return o.useEffect(()=>rt().subscribe("pollers",c=>{i(null),n(c),r(!0)},c=>i(c)),[]),{data:e,loaded:s,error:a}}function ki(e){return e.lastErrorClass==="RATE_LIMIT"&&e.rateLimitedUntil!==void 0&&Date.parse(e.rateLimitedUntil)>Date.now()}function ji(e){const n=e.find(i=>i.lastErrorClass==="ACCESS_DENIED");if(n)return{poller:n,kind:"access-denied"};const s=e.find(i=>i.health==="failed");if(s)return{poller:s,kind:"failed"};const r=e.find(ki);if(r)return{poller:r,kind:"rate-limited"};const a=e.find(i=>i.health==="degraded");return a?{poller:a,kind:"degraded"}:null}function Ti(){const e=q(),{data:n}=wi();if(!n)return null;const s=ji(n);if(!s)return null;const{poller:r,kind:a}=s,i=a==="access-denied"?e.banner.platformAccessDenied(r.repo,r.lastErrorMessage):a==="failed"?e.banner.platformUnreachable(r.repo):a==="rate-limited"?e.banner.platformRateLimited(r.repo,r.rateLimitedUntil):e.banner.platformDegraded(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 Ni(){const e=q(),{phase:n,count:s,error:r,triggerRestart:a}=Et();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 Si=new Set(["done","merged"]);function Yt(e,n){const s=e.trim().replace(/\s+/g," ");return s.length>n?`${s.slice(0,n-1)}…`:s}function Ri(e,n){return e?e.repo?`${e.id} · ${e.repo}`:e.id:n}function Ci(e){return e.title?`${e.id} · ${e.title}`:e.id}function Ai(e){return Si.has(e)}function Pi(e,n,s){const r=bn();if(!(!r||r.permission!=="granted"))try{const a=un(),i=new r(a.notification.taskDone(Yt(e.title||e.id,80)),{body:[a.notification.bodyProject(Yt(n,120)),a.notification.bodyTask(Yt(Ci(e),120)),a.notification.bodyStatus(Qr(e.status))].join(`
17
+ `),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 Li(e,n,s){const r=o.useRef(new Map),a=o.useRef(new Set),i=o.useRef(new Map),l=o.useRef(new Set),c=o.useRef(new Set),m=o.useRef(new Map),h=o.useRef(n),g=o.useRef(new Map),f=o.useMemo(()=>s?(e??[]).map(u=>u.id).sort().join("\0"):"",[s,e]);o.useEffect(()=>{h.current=n},[n]),o.useEffect(()=>{g.current=new Map((e??[]).map(u=>[u.id,Ri(u,u.id)]))},[e]),o.useEffect(()=>{const u=w=>{m.current.set(w,(m.current.get(w)??0)+1)};if(f===""){for(const w of c.current)u(w);c.current=new Set,r.current.clear(),i.current.clear(),l.current.clear();return}const d=f.split("\0"),x=new Set(d);for(const w of c.current)x.has(w)||u(w);c.current=x;for(const w of r.current.keys())x.has(w)||r.current.delete(w);for(const w of i.current.keys())x.has(w)||i.current.delete(w);const y=d.map(w=>rt().subscribe(`project-tasks:${w}`,C=>{const S=r.current.get(w),R=new Map(C.map(b=>[b.id,b]));r.current.set(w,R);const v=i.current.get(w)??new Set;if(i.current.set(w,v),!S){for(const b of R.keys())v.delete(b);return}for(const[b]of S)R.has(b)||a.current.has(b)||v.add(b);for(const b of[...v]){if(R.has(b)){v.delete(b);continue}const j=m.current.get(w)??0,k=`${w}:${j}:${b}`;l.current.has(k)||(l.current.add(k),D.tasks.get(b).then(E=>{if((m.current.get(w)??0)!==j)return;if(!E||E.projectId!==w||!Ai(E.status)){v.delete(b);return}v.delete(b),a.current.add(E.id);const I=g.current.get(w)??w;Pi(E,I,()=>h.current(E))}).catch(E=>{console.warn(`[task-notifications] failed to confirm completed task ${b}:`,E)}).finally(()=>{l.current.delete(k)}))}},C=>{console.warn(`[task-notifications] project task stream failed for ${w}:`,C)}));return()=>{for(const w of y)w()}},[f])}function Ei(){const e=qn(),n=Ee(),{projects:s}=at(),{enabled:r}=vs(),a=!e.pathname.startsWith("/terminal/");return lr(),Li(s,i=>n(Me(i.projectId,i.id)),r),t.jsxs("div",{className:"flex h-dvh flex-col bg-page",children:[t.jsxs("nav",{className:"flex h-12 flex-none items-center border-b border-hairline bg-surface px-3 sm:px-6",children:[t.jsxs($e,{to:"/",className:"flex shrink-0 items-center gap-2 font-display text-sm font-semibold tracking-tight text-og-1000",children:[t.jsx("span",{"aria-hidden":!0,className:"block h-2.5 w-2.5 rounded-full bg-accent"}),"baxian"]}),t.jsx("div",{id:ys,className:"ml-auto flex min-w-0 items-center justify-end gap-2"})]}),t.jsx(Ni,{}),t.jsx(Ti,{}),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(zs,{children:[t.jsx(Je,{path:"/",element:t.jsx(Na,{})}),t.jsx(Je,{path:"/project/:id",element:t.jsx(Ia,{})}),t.jsx(Je,{path:"/project/:id/task/:taskId",element:t.jsx(Za,{})}),t.jsx(Je,{path:"/terminal/:agentId",element:t.jsx(ti,{})}),t.jsx(Je,{path:"/tasks/:taskId/pr-review",element:t.jsx(xi,{})})]}),a&&t.jsx("footer",{className:"mt-auto flex justify-center pb-4 pt-24",children:t.jsx(yi,{})})]})]})}function Di(){return t.jsx(Ws,{children:t.jsx(ga,{children:t.jsx(Ei,{})})})}function $i({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 c=await D.config.get();Xt(c.language),r({kind:"authorized"})}catch(c){if(c instanceof Ve&&c.status===401){r({kind:"unauthorized"});return}r({kind:"error",message:c instanceof Error?c.message:void 0,fallback:"connectFallback"})}},[]);if(o.useEffect(()=>{i()},[i]),o.useEffect(()=>{const c=()=>{a.current.kind!=="probing"&&r({kind:"unauthorized",reason:"expired"})};return window.addEventListener(jt,c),()=>window.removeEventListener(jt,c)},[]),s.kind==="authorized")return t.jsx(t.Fragment,{children:e});if(s.kind==="error")return t.jsxs(nn,{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(nn,{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(Ii,{message:l,onSubmit:async c=>{Js(c);try{const m=await D.config.get();Xt(m.language),r({kind:"authorized"})}catch(m){if(Xs(),m instanceof Ve&&m.status===401){r({kind:"unauthorized",reason:"invalid"});return}r({kind:"error",message:m instanceof Error?m.message:void 0,fallback:"loginFailed"})}}})}function nn({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 Ii({message:e,onSubmit:n}){const s=q(),[r,a]=o.useState(""),[i,l]=o.useState(!1),[c,m]=o.useState(void 0),h=async f=>{f.preventDefault();const u=r.trim();if(!u){m(s.auth.tokenRequired);return}m(void 0),l(!0);try{await n(u)}finally{l(!1)}},g=c??e;return t.jsxs(nn,{title:s.auth.loginTitle,children:[t.jsx("p",{className:"mb-4 text-sm text-og-600",children:s.auth.loginDescription}),t.jsxs("form",{onSubmit:f=>{h(f)},children:[t.jsx("label",{className:ue,htmlFor:"baxian-token",children:s.auth.tokenLabel}),t.jsx("input",{id:"baxian-token",type:"password",autoComplete:"current-password",autoFocus:!0,value:r,onChange:f=>a(f.target.value),className:`${fe} font-mono`,placeholder:s.auth.tokenPlaceholder,disabled:i}),g&&t.jsx("p",{role:"alert",className:"mt-2 text-xs text-accent",children:g}),t.jsx("button",{type:"submit",disabled:i,className:"btn-primary mt-4 w-full",children:i?s.auth.submitting:s.auth.submit})]})]})}qs.createRoot(document.getElementById("root")).render(t.jsx(o.StrictMode,{children:t.jsx(or,{children:t.jsx(vr,{children:t.jsx(mr,{children:t.jsx(fr,{children:t.jsx($i,{children:t.jsx(Di,{})})})})})})}));