baxian 2.0.30 → 2.0.32

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 (49) hide show
  1. package/README.md +1 -1
  2. package/README.zh-CN.md +1 -1
  3. package/dist/agent/manager.d.ts +1 -0
  4. package/dist/agent/manager.d.ts.map +1 -1
  5. package/dist/agent/manager.js +133 -37
  6. package/dist/agent/manager.js.map +1 -1
  7. package/dist/agent/tmux.d.ts +6 -1
  8. package/dist/agent/tmux.d.ts.map +1 -1
  9. package/dist/agent/tmux.js +84 -9
  10. package/dist/agent/tmux.js.map +1 -1
  11. package/dist/api/projects.d.ts.map +1 -1
  12. package/dist/api/projects.js +0 -11
  13. package/dist/api/projects.js.map +1 -1
  14. package/dist/app.d.ts +0 -2
  15. package/dist/app.d.ts.map +1 -1
  16. package/dist/app.js +0 -2
  17. package/dist/app.js.map +1 -1
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +1 -5
  20. package/dist/index.js.map +1 -1
  21. package/dist/shared/constants.d.ts +0 -6
  22. package/dist/shared/constants.d.ts.map +1 -1
  23. package/dist/shared/constants.js +0 -6
  24. package/dist/shared/constants.js.map +1 -1
  25. package/dist/shared/types.d.ts +0 -9
  26. package/dist/shared/types.d.ts.map +1 -1
  27. package/dist/shared/types.js.map +1 -1
  28. package/dist/state/snapshot.d.ts +1 -5
  29. package/dist/state/snapshot.d.ts.map +1 -1
  30. package/dist/state/snapshot.js +5 -30
  31. package/dist/state/snapshot.js.map +1 -1
  32. package/dist/web/assets/index-CiQfh8FL.js +19 -0
  33. package/dist/web/assets/index-ZHKFSFZy.css +1 -0
  34. package/dist/web/index.html +2 -2
  35. package/package.json +1 -1
  36. package/dist/agent/pet-input.d.ts +0 -18
  37. package/dist/agent/pet-input.d.ts.map +0 -1
  38. package/dist/agent/pet-input.js +0 -88
  39. package/dist/agent/pet-input.js.map +0 -1
  40. package/dist/api/pets.d.ts +0 -3
  41. package/dist/api/pets.d.ts.map +0 -1
  42. package/dist/api/pets.js +0 -77
  43. package/dist/api/pets.js.map +0 -1
  44. package/dist/state/pet-store.d.ts +0 -35
  45. package/dist/state/pet-store.d.ts.map +0 -1
  46. package/dist/state/pet-store.js +0 -189
  47. package/dist/state/pet-store.js.map +0 -1
  48. package/dist/web/assets/index-B77QkCk7.css +0 -1
  49. package/dist/web/assets/index-vQFMnvpO.js +0 -17
@@ -0,0 +1,19 @@
1
+ var Us=Object.defineProperty;var Gs=(e,n,s)=>n in e?Us(e,n,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[n]=s;var ie=(e,n,s)=>Gs(e,typeof n!="symbol"?n+"":n,s);import{r as o,j as t,a as Ws,c as zs}from"./react-BFCkCmbU.js";import{a as Vs,b as Ks,x as Qs,c as Ys}from"./xterm-DYzQPKhn.js";import{L as Ae,u as Pe,a as kt,b as Mn,B as Js,R as Xs,c as ze}from"./router-BgSDZqI0.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))r(a);new MutationObserver(a=>{for(const i of a)if(i.type==="childList")for(const l of i.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&r(l)}).observe(document,{childList:!0,subtree:!0});function s(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerPolicy&&(i.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?i.credentials="include":a.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(a){if(a.ep)return;a.ep=!0;const i=s(a);fetch(a.href,i)}})();function ke({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 jt({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),p=o.useRef(null),g=o.useRef(null),u=o.useId(),d=o.useId();return o.useEffect(()=>{if(!m)return;const x=y=>{var A,R;const S=y.target;S&&((A=g.current)!=null&&A.contains(S)||(R=p.current)!=null&&R.contains(S)||h(!1))},b=y=>{var S;y.key==="Escape"&&(h(!1),(S=p.current)==null||S.focus())};return document.addEventListener("mousedown",x),document.addEventListener("keydown",b),()=>{document.removeEventListener("mousedown",x),document.removeEventListener("keydown",b)}},[m]),o.useEffect(()=>{var b;if(!m||!r)return;const x=(b=g.current)==null?void 0:b.querySelector('[role="menuitem"]:not([disabled])');x==null||x.focus()},[m,r]),t.jsxs("div",{className:`relative ${i??""}`,children:[t.jsx("button",{ref:x=>{p.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:g,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=p.current)==null||x.focus()})})]})}function Me(e){return e==="spec"}function Fn(e,n){var r;const s=e.binding;return(s==null?void 0:s.bootstrappingTaskId)!==void 0&&s.bootstrappingTaskId===s.taskId&&(n===void 0||s.taskId===n)&&s.status!=="awaiting_human"&&((r=s.needInput)==null?void 0:r.at)===void 0}function On(e){var n;return e.prNumber===void 0||e.phase===void 0||((n=e.deliveryConfirmation)==null?void 0:n.phase)!==e.phase}const Zs={"claude-code":"Claude Code",codex:"Codex",opencode:"OpenCode",qodercli:"Qoder CLI"},er={"claude-code":"--permission-mode bypassPermissions",codex:"--dangerously-bypass-approvals-and-sandbox",opencode:"--auto",qodercli:"--dangerously-skip-permissions"};function _n(e,n){const s=[e?Zs[e]:null,n||null].filter(Boolean);return s.length>0?s.join(" · "):null}function Hn(e,n,s){const r=_n(n,s);return r?`${e} (${r})`:e}const qn=new Set(["merged","done","failed","cancelled"]),Kt=new Set(["in_progress","review","fixing","spec-ready","approved","merge-ready","max_rounds"]),At=20,Tt=5*1024*1024,ot=4;function Un(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 et="/api",Qt="baxian.token",Ye="baxian:unauthorized";function Yt(){try{return typeof localStorage<"u"?localStorage.getItem(Qt):null}catch{return null}}function tr(e){try{localStorage.setItem(Qt,e)}catch(n){console.error("Failed to save auth token to localStorage",n)}}function nr(){try{localStorage.removeItem(Qt)}catch(e){console.error("Failed to clear auth token from localStorage",e)}}function Ge(e){const n=Yt();return{...e??{},...n?{Authorization:`Bearer ${n}`}:{}}}class Je extends Error{constructor(n,s,r){super(s),this.status=n,this.details=r,this.name="ApiError"}}function sr(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 We(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=sr(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(Ye)),new Je(e.status,s,r)}async function Ce(e){const n=await fetch(`${et}${e}`,{headers:Ge()});return n.ok||await We(n),n.json()}async function rr(){const e=await fetch("/health");return e.ok||await We(e),e.json()}async function pe(e,n,s){const r=n!==void 0,a=await fetch(`${et}${e}`,{method:"POST",headers:r?Ge({"Content-Type":"application/json"}):Ge(),body:r?JSON.stringify(n):void 0,signal:s==null?void 0:s.signal});return a.ok||await We(a),a.json()}async function Dt(e,n,s){const r=await fetch(`${et}${e}`,{method:"PATCH",headers:Ge({"Content-Type":"application/json"}),body:n?JSON.stringify(n):void 0,signal:s==null?void 0:s.signal});if(r.ok||await We(r),r.status===204)return;const a=await r.text();if(a)return JSON.parse(a)}async function ar(e,n){const s=await fetch(`${et}${e}`,{method:"PUT",headers:Ge({"Content-Type":"application/json"}),body:JSON.stringify(n??null)});if(s.ok||await We(s),s.status===204)return;const r=await s.text();if(r)return JSON.parse(r)}async function lt(e){const n=await fetch(`${et}${e}`,{method:"DELETE",headers:Ge()});if(n.ok||await We(n),n.status===204)return;const s=await n.text();if(s)return JSON.parse(s)}const ne=encodeURIComponent;function Gn(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 _={agents:{list:()=>Ce("/agents"),get:e=>Ce(`/agents/${ne(e)}`),stop:e=>lt(`/agents/${ne(e)}/session`),compact:e=>pe(`/agents/${ne(e)}/compact`),clear:e=>pe(`/agents/${ne(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/${ne(e)}/images`,{dataBase64:await Gn(n)})},tasks:{list:async e=>{const n=new Map;for(const s of["active","pending"]){let r=0;for(;;){const a=await _.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=${ne(e)}`];return n.category&&s.push(`category=${n.category}`),s.push(`offset=${n.offset??0}`),Ce(`/tasks?${s.join("&")}`)},get:e=>Ce(`/tasks/${ne(e)}`),create:e=>pe("/tasks",e),update:(e,n)=>Dt(`/tasks/${ne(e)}`,n),retry:e=>pe(`/tasks/${ne(e)}/retry`),advance:(e,n)=>pe(`/tasks/${ne(e)}/advance`,n),verdict:(e,n)=>pe(`/tasks/${ne(e)}/verdict`,n),prReview:e=>Ce(`/tasks/${ne(e)}/pr-review`),prReviewRefresh:e=>pe(`/tasks/${ne(e)}/pr-review/refresh`)},projects:{list:()=>Ce("/projects"),get:e=>Ce(`/projects/${ne(e)}`),create:e=>pe("/projects",e),delete:e=>lt(`/projects/${ne(e)}`),addAgentTeam:(e,n)=>pe(`/projects/${ne(e)}/agents`,n),replaceAgent:(e,n,s)=>ar(`/projects/${ne(e)}/agents/${ne(n)}`,s),deleteAgent:(e,n)=>lt(`/projects/${ne(e)}/agents/${ne(n)}`),resumeAgent:(e,n)=>pe(`/projects/${ne(e)}/agents/${ne(n)}/resume`),restartRepl:(e,n)=>pe(`/projects/${ne(e)}/agents/${ne(n)}/restart-repl`),retryAgent:(e,n)=>pe(`/projects/${ne(e)}/agents/${ne(n)}/retry`),bootstrap:e=>pe(`/projects/${ne(e)}/bootstrap`)},hosts:{list:()=>Ce("/hosts"),create:e=>pe("/hosts",e),update:(e,n)=>Dt(`/hosts/${ne(e)}`,n),delete:e=>lt(`/hosts/${ne(e)}`),check:e=>pe("/hosts/check",e)},config:{get:()=>Ce("/config"),patch:e=>Dt("/config",e)},health:{get:rr},server:{restart:()=>pe("/restart")}};function Jt(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 ir(e){return t.jsxs("svg",{...Jt(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 or(e){return t.jsxs("svg",{...Jt(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 lr(e){return t.jsxs("svg",{...Jt(e),children:[t.jsx("circle",{cx:"12",cy:"12",r:"10"}),t.jsx("path",{d:"m15 9-6 6"}),t.jsx("path",{d:"m9 9 6 6"})]})}const Wn={common:{cancel:"Cancel",confirm:"Confirm",close:"Close",delete:"Delete",deleting:"Deleting…",edit:"Edit",retry:"Retry",retrying:"Retrying…",back:"← Back",backText:"Back",loading:"Loading…",loadFailed:e=>`Failed to load: ${e}`,idFormatError:"Must start with a lowercase letter; only a-z, 0-9, and - allowed; length 2–32",create:"Create",creating:"Creating…",save:"Save",saving:"Saving…",oneClickInstall:"Install with one click",installing:"Installing…",installingTmuxNotice:"Installing tmux — this can take a few minutes, please keep this window open…",technicalDetails:"Technical details"},status:{pending:"Waiting to start",in_progress:"In progress",review:"In review",fixing:"Revising","spec-ready":"Plan ready",approved:"Running pre-merge checks","merge-ready":"Merge ready",merged:"PR merged",done:"Complete",failed:"Failed",max_rounds:"Review needs a decision",cancelled:"Cancelled"},statusContext:{pendingUnassigned:"Unassigned",inProgressSpec:"Drafting plan",inProgressCode:"Coding",reviewSpec:"Reviewing",reviewCode:"Reviewing",fixingSpec:"Fixing",fixingCode:"Fixing",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",dispatchingBadge:"Dispatching",dispatchingTitle:"baxian is preparing the workspace, switching branches, and injecting the prompt",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",teamActionsMenu:e=>`Agent Team ${e} actions menu`,teamCompactMenuItemTitle:"Send /compact to every agent runtime in this Agent Team",teamClearMenuItemTitle:"Send /clear to every agent runtime in this Agent Team",teamCompactSentTitle:e=>`/compact sent to Agent Team ${e}`,teamClearConfirmTitle:e=>`Clear the context for Agent Team ${e}?`,teamClearConfirmBody:"This sends /clear to every agent in this Agent Team; their session contexts cannot be recovered.",teamClearSentTitle:e=>`/clear sent to Agent Team ${e}`,teamDeleteConfirmTitle:e=>`Delete Agent Team ${e}?`,teamDeletedTitle:e=>`Agent Team ${e} deleted`,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`,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}`,dispatching:"Dispatching to the agent…",dispatchingHint:"baxian is preparing the workspace, switching branches, and injecting the prompt; this step usually takes a few seconds.",createdAtPrefix:"Created ",updatedAtPrefix:" · Updated ",originPrefix:" · From ",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",attentionDirtyWorkdirTitle:"The working directory has uncommitted changes",attentionDirtyWorkdirGuidance:"The operation requires a clean working directory. Commit or stash the changes you need to keep in the linked agent’s working directory.",attentionCheckoutTitle:"The task working directory could not be prepared",attentionCheckoutGuidance:"Inspect the working directory or branch error below and resolve its cause.",attentionReplayTitle:"The task prompt could not be resent",attentionReplayGuidance:"Inspect the prompt delivery error below and resolve its cause. Resuming the agent does not resend the task prompt.",attentionBootstrapDeliveredTitle:"The initial prompt was already sent",attentionDeliveryUnknownTitle:"Prompt delivery is unconfirmed",attentionDeliveryUnknownGuidance:"The prompt may already be running. Check the linked agent’s terminal and confirm the outcome before choosing an action.",attentionBootstrapDeliveredGuidance:"Check the task outcome in the linked agent’s terminal on the task page. Replaying this prompt could run the task twice.",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}`:""}`,platformRepoNotFound:e=>`Platform returned not-found for ${e} — the repository or a requested resource does not exist, was renamed/deleted, or the current credentials cannot see it; task progress stays paused until this is fixed manually`,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"}},cr={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:"启动中",dispatchingBadge:"派发中",dispatchingTitle:"baxian 正在准备工作区、切换分支并注入任务指令",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:"清空上下文失败",teamActionsMenu:e=>`Agent Team ${e} 操作菜单`,teamCompactMenuItemTitle:"向该 Agent Team 的每个 agent runtime 发送 /compact",teamClearMenuItemTitle:"向该 Agent Team 的每个 agent runtime 发送 /clear",teamCompactSentTitle:e=>`已向 Agent Team ${e} 发送 /compact`,teamClearConfirmTitle:e=>`清空 Agent Team ${e} 的上下文?`,teamClearConfirmBody:"将向该 Agent Team 的每个 agent 发送 /clear,会话上下文不可恢复。",teamClearSentTitle:e=>`已向 Agent Team ${e} 发送 /clear`,teamDeleteConfirmTitle:e=>`删除 Agent Team ${e}?`,teamDeletedTitle:e=>`已删除 Agent Team ${e}`,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} 已删除`,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} 轮`,dispatching:"正在派发给 Agent…",dispatchingHint:"baxian 正在准备工作区、切换分支并注入提示词,这一步通常需要十几秒。",createdAtPrefix:"创建于 ",updatedAtPrefix:" · 更新于 ",originPrefix:" · 来自 ",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:"任务需要你处理",attentionDirtyWorkdirTitle:"工作目录有未提交改动",attentionDirtyWorkdirGuidance:"本次操作要求工作目录干净。请在关联 Agent 的工作目录提交或暂存需要保留的改动。",attentionCheckoutTitle:"任务工作目录准备失败",attentionCheckoutGuidance:"请检查并处理下方工作目录或分支错误。",attentionReplayTitle:"任务指令未能重新发送",attentionReplayGuidance:"请检查并处理下方指令发送错误。“恢复 Agent”不会重新发送任务指令。",attentionBootstrapDeliveredTitle:"初始任务指令已经发送",attentionDeliveryUnknownTitle:"任务指令的发送结果尚未确认",attentionDeliveryUnknownGuidance:"指令可能已经在执行。请先到关联 Agent 的终端核实结果,再选择后续操作。",attentionBootstrapDeliveredGuidance:"请在任务页的关联 Agent 终端核实执行结果。再次发送这条指令可能导致任务重复执行。",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??""}`,platformRepoNotFound:e=>`平台返回资源不存在(${e})——仓库或所需资源不存在、已改名/删除,或当前凭证无权访问,任务推进暂停,需人工修复后才会恢复`,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:"上传图片"}},Xt="baxian.language",Xe="en-US",zn={"en-US":Wn,"zh-CN":cr};function Vn(e){return e==="zh-CN"||e==="en-US"}function Kn(){try{const e=localStorage.getItem(Xt);return Vn(e)?e:Xe}catch{return Xe}}function Qn(e){try{localStorage.setItem(Xt,e)}catch{}}let Ue=Kn();const Ht=new Set;let gt=0,dr=0,hn=0;function Zt(e){e!==Ue&&(Ue=e,Ht.forEach(n=>n(e)))}function qt(e){gt+=1;const n=e??Xe;Qn(n),Zt(n)}function ur(e){const n=e??Xe;Qn(n),Zt(n)}function Yn(){return zn[Ue]}const Jn=o.createContext({locale:Xe,messages:Wn,saving:!1,setLocale:async()=>{throw new Error("setLocale requires I18nProvider")}});function mr({children:e}){const[n,s]=o.useState(Ue),[r,a]=o.useState(!1);o.useEffect(()=>{const l=c=>s(c);return Ht.add(l),s(Ue),()=>{Ht.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!==Xt)return;const m=c.key===null?Kn():c.newValue;Vn(m)&&(gt+=1,Zt(m))};return window.addEventListener("storage",l),()=>window.removeEventListener("storage",l)},[]);const i=async l=>{if(l!==Ue){a(!0);try{await _.config.patch({language:l}),qt(l)}finally{a(!1)}}};return t.jsx(Jn.Provider,{value:{locale:n,messages:zn[n],saving:r,setLocale:i},children:e})}function Xn(){return o.useContext(Jn)}function U(){return Xn().messages}function hr(){o.useEffect(()=>{const e=()=>{const s=gt,r=++dr;_.config.get().then(a=>{s===gt&&(r<=hn||(hn=r,ur(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 Zn=o.createContext(null),fr={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"},pr={success:ir,warn:or,error:lr};let gr=1;function xr({children:e}){const n=U(),[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]),p=o.useCallback((u,d,x)=>{const b=i.current.get(u);b==null||b.delete(d),(!b||b.size===0)&&m(u,x)},[m]),g=o.useCallback(u=>{const d=gr++,x=u.durationMs??3e3;r(b=>[...b,{...u,id:d,durationMs:x}]),m(d,x)},[m]);return t.jsxs(Zn.Provider,{value:{show:g},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 ${fr[u.kind]}`,role:"status",onMouseEnter:()=>h(u.id,"hover"),onMouseLeave:()=>p(u.id,"hover",u.durationMs),onFocus:()=>h(u.id,"focus"),onBlur:d=>{d.currentTarget.contains(d.relatedTarget)||p(u.id,"focus",u.durationMs)},children:t.jsxs("div",{className:"flex items-start gap-2",children:[(()=>{const d=pr[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 je(){const e=o.useContext(Zn);if(!e)throw new Error("useToast must be inside <ToastProvider>");return e}const br={sm:"max-w-md",md:"max-w-lg",lg:"max-w-2xl"},fn='input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), [href], [tabindex]:not([tabindex="-1"])',_e=[];function Le({open:e,onClose:n,title:s,titleContent:r,children:a,footer:i,size:l="md",dismissOnBackdrop:c=!0}){const m=U(),h=o.useRef(null),p=o.useRef();p.current||(p.current=Symbol("modal"));const g=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=p.current;_e.push(x);const b=()=>_e[_e.length-1]===x;g.current=document.activeElement;const y=R=>{if(!b())return;if(R.key==="Escape"){d.current();return}if(R.key!=="Tab")return;const w=h.current;if(!w)return;const k=Array.from(w.querySelectorAll(fn)).filter($=>$.offsetParent!==null||$===document.activeElement);if(k.length===0){R.preventDefault();return}const T=k[0],v=k[k.length-1],L=document.activeElement;R.shiftKey&&(L===T||!w.contains(L))?(R.preventDefault(),v.focus()):!R.shiftKey&&(L===v||!w.contains(L))&&(R.preventDefault(),T.focus())};document.addEventListener("keydown",y);const S=document.body.style.overflow;document.body.style.overflow="hidden";const A=h.current;if(A){const R=A.querySelector(fn);R==null||R.focus()}return()=>{var w,k;const R=_e.indexOf(x);R>=0&&_e.splice(R,1),document.removeEventListener("keydown",y),document.body.style.overflow=S,(k=(w=g.current)==null?void 0:w.focus)==null||k.call(w)}},[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&&_e[_e.length-1]===p.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 ${br[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 es=o.createContext(null);function vr({children:e}){const n=U(),[s,r]=o.useState(null),a=o.useRef(null),i=o.useCallback(c=>new Promise(m=>{var p;(p=a.current)==null||p.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(es.Provider,{value:i,children:[e,s&&t.jsx(Le,{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 en(){const e=o.useContext(es);if(!e)throw new Error("useConfirm must be inside <ConfirmProvider>");return e}const xt="baxian.pendingRestart",yr=500,wr=3e4,ts=o.createContext(null);function kr(){try{const e=localStorage.getItem(xt);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 jr(e){try{e.count<=0?localStorage.removeItem(xt):localStorage.setItem(xt,JSON.stringify(e))}catch{}}function Tr({children:e}){const n=U(),s=kr(),[r,a]=o.useState(s.count),[i,l]=o.useState(s.baselineStartedAt),[c,m]=o.useState(s.count>0?"pending":"idle"),[h,p]=o.useState(),g=o.useRef(s.count),u=o.useRef(s.count>0?"pending":"idle"),d=o.useRef(0),x=o.useCallback(w=>{g.current=w,a(w)},[]),b=o.useCallback(w=>{a(k=>{const T=w(k);return g.current=T,T})},[]),y=o.useCallback(w=>{u.current=w,m(w)},[]);o.useEffect(()=>{jr({count:r,baselineStartedAt:i})},[r,i]),o.useEffect(()=>{let w=!1;(async()=>{try{const T=await _.health.get();if(w)return;l(v=>v!==null&&T.startedAt!==v?(x(0),y("idle"),null):v)}catch{}})();const k=T=>{if(T.key===xt){if(T.newValue===null){if(u.current==="restarting"&&d.current>0){x(d.current),l(null);return}x(0),l(null),u.current!=="restarting"&&y("idle");return}try{const v=JSON.parse(T.newValue);typeof v.count=="number"&&(u.current==="restarting"&&v.count>g.current&&(d.current+=v.count-g.current),x(v.count),u.current!=="restarting"&&y(v.count>0?"pending":"idle")),typeof v.baselineStartedAt=="string"?l(v.baselineStartedAt):v.baselineStartedAt===null&&l(null)}catch{}}};return window.addEventListener("storage",k),()=>{w=!0,window.removeEventListener("storage",k)}},[x,y]);const S=o.useRef(!1),A=o.useCallback(()=>{b(w=>w+1),u.current==="restarting"?d.current+=1:y("pending"),l(w=>(w!==null||S.current||(S.current=!0,(async()=>{try{const k=await _.health.get();l(T=>T??k.startedAt)}catch{}finally{S.current=!1}})()),w))},[y,b]),R=o.useCallback(async()=>{d.current=0,p(void 0),y("restarting");let w;try{w=(await _.health.get()).startedAt}catch(T){y("failed"),p(n.banner.preRestartFetchFailed(T instanceof Error?T.message:String(T)));return}try{await _.server.restart()}catch(T){if(!(T instanceof Je&&T.status===409)){y("failed"),p(n.banner.restartTriggerFailed(T instanceof Error?T.message:String(T)));return}}const k=Date.now();for(;Date.now()-k<wr;){await new Promise(T=>setTimeout(T,yr));try{const T=await _.health.get();if(T.startedAt!==w){const v=d.current;d.current=0,l(v>0?T.startedAt:null),x(v),y(v>0?"pending":"idle");return}}catch{}}y("failed"),p(n.banner.restartTimeout)},[x,y,n]);return t.jsx(ts.Provider,{value:{phase:c,count:r,error:h,flagDirty:A,triggerRestart:R},children:e})}function Nt(){const e=o.useContext(ts);if(!e)throw new Error("usePendingRestart must be used inside PendingRestartProvider");return e}function pn(e){return e instanceof Error?e.message:String(e)}function ns(e,n,s){const r=U(),{show:a}=je(),i=en(),{flagDirty:l}=Nt(),[c,m]=o.useState(!1),[h,p]=o.useState(!1),[g,u]=o.useState(!1),[d,x]=o.useState(null),b=n[0]??"",y=n.join(" / "),S=n.length>1,A=async T=>(await Promise.allSettled(n.map(L=>T(L)))).flatMap((L,$)=>L.status==="rejected"?[`${n[$]}: ${pn(L.reason)}`]:[]);return{compact:async()=>{m(!0);try{const T=await A(v=>_.agents.compact(v));if(T.length>0){a({kind:"error",title:r.agents.compactFailedTitle,body:T.join(`
8
+ `)});return}a({kind:"success",title:S?r.agents.teamCompactSentTitle(y):r.agents.compactSentTitle(b)})}finally{m(!1)}},clear:async()=>{if(await i({title:S?r.agents.teamClearConfirmTitle(y):r.agents.clearConfirmTitle(b),body:S?r.agents.teamClearConfirmBody:r.agents.clearConfirmBody,confirmLabel:r.agents.clearConfirmLabel})){p(!0);try{const v=await A(L=>_.agents.clear(L));if(v.length>0){a({kind:"error",title:r.agents.clearFailedTitle,body:v.join(`
9
+ `)});return}a({kind:"success",title:S?r.agents.teamClearSentTitle(y):r.agents.clearSentTitle(b)})}finally{p(!1)}}},remove:async()=>{if(await i({title:S?r.agents.teamDeleteConfirmTitle(y):r.agents.deleteConfirmTitle(b),body:r.agents.deleteConfirmBody,confirmLabel:r.common.delete})){u(!0),x(null);try{const v=await _.projects.deleteAgent(e,b);v!=null&&v.restartRequired&&l();const L=(v==null?void 0:v.removed)??[b],$=[...(v==null?void 0:v.warnings)??[]],H=S?[]:L.filter(Q=>Q!==b);H.length>0&&$.unshift(r.agents.deletedWithTeamBody(H.join(", ")));const F=S?r.agents.teamDeletedTitle(y):H.length>0?r.agents.deletedWithTeamTitle(b):r.agents.deletedTitle(b);a($.length>0?{kind:"warn",title:F,body:$.join(`
10
+ `)}:{kind:"success",title:F}),s==null||s()}catch(v){x(pn(v))}finally{u(!1)}}},compacting:c,clearing:h,deleting:g,deleteError:d,busy:c||h||g}}const Nr=[500,1e3,2e3,4e3,8e3,15e3,3e4];class ss{constructor(n){ie(this,"attempts",0);ie(this,"timer",null);ie(this,"delaysMs");this.opts=n,this.delaysMs=n.delaysMs??Nr}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 rs(e,n,s){return(e==null?void 0:e.code)!==4401||n!==s?!1:(window.dispatchEvent(new CustomEvent(Ye)),!0)}function as(e){return Array.from(new TextEncoder().encode(e)).map(n=>n.toString(16).padStart(2,"0")).join("")}function is(e){return`${location.protocol==="https:"?"wss":"ws"}://${location.host}${e}`}const os=(e,n)=>n&&n.length>0?new WebSocket(e,n):new WebSocket(e);let gn=0;function Sr(){gn++;const e=Math.random().toString(36).slice(2,8);return`sub-${Date.now().toString(36)}-${gn}-${e}`}function Rr(){return is("/api/stream")}class Cr{constructor(n={}){ie(this,"wsUrl");ie(this,"wsFactory");ie(this,"tokenProvider");ie(this,"ws",null);ie(this,"subs",new Map);ie(this,"snapshotPending",new Set);ie(this,"preSubscribeQueue",new Map);ie(this,"outbox",[]);ie(this,"reconnectScheduler");ie(this,"explicitlyClosed",!1);this.wsUrl=n.wsUrl??Rr(),this.wsFactory=n.wsFactory??os,this.tokenProvider=n.tokenProvider??Yt,this.reconnectScheduler=new ss({reconnect:()=>this.openSocket(),shouldReconnect:()=>!this.explicitlyClosed&&this.subs.size>0})}subscribe(n){const s=Sr(),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.${as(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=a=>{r===this.ws&&(this.ws=null,!this.explicitlyClosed&&(rs(a,n,this.tokenProvider())||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 Pt=null;function Lt(){return Pt||(Pt=new Cr),Pt}function Ar(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=Lt().subscribe({agentId:n,mode:s,onSnapshot:h=>a.current.onSnapshot(h),onData:h=>a.current.onData(h),onError:h=>{var p,g;return(g=(p=a.current).onError)==null?void 0:g.call(p,h)},onSessionGone:()=>{var h,p;return(p=(h=a.current).onSessionGone)==null?void 0:p.call(h)}});return r.current=m.subscriberId,()=>{r.current=null,m.unsubscribe()}},[n,s]);const i=o.useCallback(c=>{const m=r.current;m&&Lt().send(m,c)},[]),l=o.useCallback((c,m)=>{const h=r.current;h&&Lt().resize(h,c,m)},[]);return{send:i,resize:l}}const Dr=8;let ct=0,dt,xn=!0;function ls(e){var n;return Array.from(((n=e.element)==null?void 0:n.querySelectorAll("canvas"))??[])}function bn(e){for(const n of ls(e)){const s=n.getContext("webgl2");if(s)return s}return null}function Ut(e){var n;(n=e==null?void 0:e.getExtension("WEBGL_lose_context"))==null||n.loseContext()}function Pr(){const e=document.createElement("canvas").getContext("webgl2");return e?(Ut(e),!0):!1}function Lr(e,n){let s=null,r=!1;const a=()=>{if(r||!xn)return;const h=new Ks.CanvasAddon;try{e.loadAddon(h),s={kind:"canvas",addon:h}}catch(p){xn=!1,console.warn("[terminal-renderer] canvas renderer unavailable, using dom renderer:",p),h.dispose()}},i=()=>{if(!s)return;const{kind:h,addon:p}=s;s=null;const g=h==="webgl"?bn(e):null;p.dispose(),h==="webgl"&&(ct--,Ut(g))},l=()=>{if(dt===void 0&&(dt=Pr()),!dt||ct>=Dr)return!1;let h=null;try{return h=new Vs.WebglAddon,h.onContextLoss(()=>{i(),a()}),e.loadAddon(h),ct++,s={kind:"webgl",addon:h},!0}catch(p){dt=!1,console.warn("[terminal-renderer] webgl renderer unavailable, using canvas from now on:",p),h==null||h.dispose();for(const g of ls(e))g.remove();return!1}},c=()=>{r||s||l()||a()},m=typeof IntersectionObserver=="function"?new IntersectionObserver(h=>{if(r)return;const p=h[h.length-1];p!=null&&p.isIntersecting?c():i()}):null;return m?m.observe(n):c(),{get kind(){return(s==null?void 0:s.kind)??"dom"},dispose(){if(r)return;r=!0,m==null||m.disconnect();const h=s;s=null;const p=(h==null?void 0:h.kind)==="webgl"?bn(e):null;try{e.dispose()}catch(g){console.warn("[terminal-renderer] dispose failed:",g)}(h==null?void 0:h.kind)==="webgl"&&(ct--,Ut(p))}}}const Er=[{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"}],ut=Object.fromEntries(Er.map(e=>[e.key,e]));function mt({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 $r({onKey:e,onEscape:n,className:s}){const r=U();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(mt,{arrow:ut.left,ariaLabel:r.terminal.arrowAriaLabel(r.terminal.arrowLabel.left),onPress:e}),t.jsx(mt,{arrow:ut.up,ariaLabel:r.terminal.arrowAriaLabel(r.terminal.arrowLabel.up),onPress:e}),t.jsx(mt,{arrow:ut.down,ariaLabel:r.terminal.arrowAriaLabel(r.terminal.arrowLabel.down),onPress:e}),t.jsx(mt,{arrow:ut.right,ariaLabel:r.terminal.arrowAriaLabel(r.terminal.arrowLabel.right),onPress:e})]})}const Ir=Math.floor(Tt/1024/1024);function Br({agentId:e,className:n}){const s=U(),r=o.useRef(null),[a,i]=o.useState(!1),{show:l}=je(),c=async m=>{var p;const h=(p=m.target.files)==null?void 0:p[0];if(m.target.value="",!!h){if(h.size>Tt){l({kind:"error",title:s.createTask.imageTooLargeToastTitle,body:s.imageUpload.tooLargeBody(Ir)});return}i(!0);try{await _.agents.uploadImage(e,h),l({kind:"success",title:s.imageUpload.insertedTitle,body:s.imageUpload.insertedBody})}catch(g){const u=g instanceof Je||g instanceof Error?g.message:String(g);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 Mr={up:"A",down:"B",right:"C",left:"D"};function Fr(e,n){return(n?"\x1BO":"\x1B[")+Mr[e]}const vn=18,Or=250,_r=256*1024,yn="#fdfdfd",Hr='ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',qr={background:yn,foreground:"#474c55",cursor:"#1348dc",cursorAccent:yn,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"},Ur=/\x1b\[(?:\?[\d;]*c|>[\d;]*c|\??\d+;\d+R|\d+n)/g;function Gr(e){return e.replace(Ur,"")}const Wr=1024*1024;function zr(e){const n=e.indexOf(";");if(n===-1)return null;const s=e.slice(n+1);if(s.length===0||s==="?"||s.length>Wr)return null;try{const r=atob(s),a=new Uint8Array(r.length);for(let i=0;i<r.length;i++)a[i]=r.charCodeAt(i);return new TextDecoder().decode(a)}catch{return null}}function Ke({agentId:e,mode:n,interactive:s=!1,maxLines:r,className:a,autoFocus:i=!0,deferFullUntilFocus:l=!1,arrowKeys:c=!1}){const m=U(),h=o.useRef(null),p=o.useRef(null),g=o.useRef(null),u=o.useRef(null),d=o.useRef(!1),x=o.useRef(""),b=o.useRef([]),y=o.useRef(0),S=o.useRef(null),A=o.useRef(null),R=o.useRef(null),w=o.useRef(Promise.resolve()),k=o.useRef(0),[T,v]=o.useState(null),[L,$]=o.useState(!1),H=`${e}\0${n}\0${l?"1":"0"}`,[F,Q]=o.useState({key:H,active:!1}),P=F.key===H&&F.active,G=n==="full"&&l,te=G&&!P?"preview":n,V=s&&te==="full",Y=(N,O)=>O.length===0?Promise.resolve():new Promise(B=>{try{N.write(O,()=>B())}catch(ue){console.warn("[pane-terminal] write failed:",ue),B()}}),W=te==="preview",se=()=>{var I;if(!W)return;const N=h.current,O=p.current;if(!N||!O||N.clientHeight<=0)return;const B=((I=N.querySelector(".xterm-screen"))==null?void 0:I.getBoundingClientRect().height)??0,ue=B>0&&O.rows>0?B/O.rows:vn,re=(O.buffer.active.cursorY+1)*ue;N.scrollTop=Math.max(0,re-N.clientHeight)},J=()=>{if(!W||R.current!==null)return;let N=!1;const O=requestAnimationFrame(()=>{N=!0,R.current=null,se()});N||(R.current=O)},X=(N,O)=>{w.current=w.current.then(async()=>{const B=p.current;if(!(!B||O!==k.current))try{await N(B),V&&B.scrollToBottom(),J()}catch(ue){console.warn("[pane-terminal] terminal task failed:",ue)}}).catch(B=>{console.warn("[pane-terminal] write chain failed:",B)})},oe=(N,O)=>{X(B=>Y(B,N),O)},ge=()=>{S.current!==null&&(cancelAnimationFrame(S.current),S.current=null),A.current!==null&&(clearTimeout(A.current),A.current=null)},q=()=>{ge(),b.current=[],y.current=0},he=()=>{ge();const N=b.current;N.length!==0&&(b.current=[],y.current=0,oe(N.join(""),k.current))},de=N=>{if(N.length!==0){if(b.current.push(N),y.current+=N.length,y.current>=_r){he();return}S.current===null&&(S.current=requestAnimationFrame(he)),A.current===null&&(A.current=setTimeout(he,Or))}},{send:fe,resize:ye}=Ar({agentId:e,mode:te,onSnapshot:({cols:N,rows:O,data:B})=>{if(p.current)try{const re=k.current+1;k.current=re,q(),X(async I=>{var C;I.reset(),V?((C=u.current)==null||C.call(u),await Y(I,B)):(N>0&&O>0&&I.resize(N,O),await Y(I,B))},re)}catch(re){console.warn("[pane-terminal] snapshot write failed:",re)}},onData:N=>{de(N)},onError:N=>v(`${N.code}: ${N.message}`),onSessionGone:()=>$(!0)});o.useEffect(()=>{v(null),$(!1)},[e,te]),o.useEffect(()=>{x.current=""},[H]),o.useEffect(()=>{if(te!=="full")return;const N=x.current;N.length!==0&&(x.current="",fe(N))},[fe,te]);const j=o.useCallback(()=>{!s||!G||P||(d.current=!0,Q({key:H,active:!0}))},[H,P,s,G]),xe=o.useCallback(N=>{const O=Gr(N);if(O.length!==0){if(G&&(!P||x.current.length>0)){x.current+=O,j();return}fe(O)}},[j,P,fe,G]);o.useEffect(()=>{const N=h.current;if(!N)return;let O=!1;const B=new Qs.Terminal({cursorBlink:s,disableStdin:!s,theme:qr,fontFamily:Hr,fontSize:13,lineHeight:1.4,scrollback:te==="full"?5e3:1e3}),ue=new Ys.FitAddon;B.loadAddon(ue),B.open(N);const re=Lr(B,N);p.current=B,g.current=ue;const I=W?B.onRender(()=>J()):null;if(s&&(i||d.current)){d.current=!1;try{B.focus()}catch{}}s&&(B.onData(xe),te==="full"&&B.parser.registerOscHandler(52,Te=>{var ae;const Ne=zr(Te);return Ne!==null&&((ae=navigator.clipboard)==null||ae.writeText(Ne).catch(()=>{})),!0}));const C=()=>N.clientWidth>0&&N.clientHeight>0,E=(Te=!1)=>{if(!C())return!1;const Ne=B.cols,ae=B.rows;try{ue.fit()}catch{return!1}return V&&B.scrollToBottom(),B.cols>0&&B.rows>0&&(Te||B.cols!==Ne||B.rows!==ae)&&ye(B.cols,B.rows),!0};u.current=V?()=>E(!0):null;let Z=null,z=null,ee=null,we=0;const Ee=()=>{Z||(Z=new ResizeObserver(()=>{z&&clearTimeout(z),z=setTimeout(()=>{z=null,V?E():W&&J()},100)}),Z.observe(N))},Fe=()=>{ee=requestAnimationFrame(()=>{if(ee=null,!O){if(!V){W&&(Ee(),J());return}if(E(!0)){Ee();return}if(we++<5){Fe();return}Ee()}})};return Fe(),()=>{O=!0,ee!==null&&cancelAnimationFrame(ee),S.current!==null&&(cancelAnimationFrame(S.current),S.current=null),A.current!==null&&(clearTimeout(A.current),A.current=null),R.current!==null&&(cancelAnimationFrame(R.current),R.current=null),k.current++,b.current=[],y.current=0,w.current=Promise.resolve(),z&&clearTimeout(z),Z==null||Z.disconnect(),I==null||I.dispose(),p.current=null,g.current=null,u.current=null,re.dispose()}},[e,i,V,xe,s,te,ye]);const be=()=>{var N;if(s){j();try{(N=p.current)==null||N.focus()}catch{}}};o.useEffect(()=>{if(s)return;const N=h.current;if(!N)return;const O=B=>{B.stopPropagation()};return N.addEventListener("wheel",O,{capture:!0,passive:!0}),()=>N.removeEventListener("wheel",O,{capture:!0})},[s]);const D=r&&r>0?{maxHeight:`${r*vn}px`}:void 0;return t.jsxs("div",{className:a??"flex flex-col h-full w-full min-h-0 bg-term",children:[(T||L)&&t.jsx("div",{className:"border-b border-accent/25 bg-accent-soft px-3 py-1 font-mono text-xs text-accent",children:L?m.terminal.sessionEnded:T}),t.jsx("div",{className:"flex flex-1 min-h-0 px-2 py-1.5",style:D,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(Br,{agentId:e})}),t.jsx($r,{className:"flex items-center justify-center gap-1",onKey:N=>{var B,ue;const O=!!((ue=(B=p.current)==null?void 0:B.modes)!=null&&ue.applicationCursorKeysMode);xe(Fr(N,O))},onEscape:()=>xe("\x1B")})]})]})}function cs(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 Vr(e){return cs(Yn(),e)}function tn(e,n){return e.reason==="bootstrap-marker-clear-failed"||e.reason==="dispatch-failed:ack_unknown"&&n!=="review"?e.recommendedActions.filter(s=>s!=="advance"):e.recommendedActions}function ds(e,n,s){const{reason:r}=n,a=tn(n,s),l={"dirty-workdir":{title:e.taskDetail.attentionDirtyWorkdirTitle,guidance:e.taskDetail.attentionDirtyWorkdirGuidance},"checkout-preparation-failed":{title:e.taskDetail.attentionCheckoutTitle,guidance:e.taskDetail.attentionCheckoutGuidance},"restart-redispatch-failed":{title:e.taskDetail.attentionReplayTitle,guidance:e.taskDetail.attentionReplayGuidance},"bootstrap-marker-clear-failed":{title:e.taskDetail.attentionBootstrapDeliveredTitle,guidance:e.taskDetail.attentionBootstrapDeliveredGuidance},"dispatch-failed:ack_unknown":{title:e.taskDetail.attentionDeliveryUnknownTitle,guidance:e.taskDetail.attentionDeliveryUnknownGuidance}}[r],c=(l==null?void 0:l.title)??(/confirm-merge|post-approve|merge/.test(r)?e.taskDetail.attentionMergeTitle:/review|verdict/.test(r)?e.taskDetail.attentionReviewTitle:/runtime|session|recovery|tmux|repl/.test(r)?e.taskDetail.attentionAgentTitle:/dispatch|delivery|pr-created/.test(r)?e.taskDetail.attentionHandoffTitle:e.taskDetail.attentionDefaultTitle),m=a.includes("verdict")?e.taskDetail.attentionVerdictGuidance:a.includes("advance")?e.taskDetail.attentionAdvanceGuidance:a.includes("retry")?e.taskDetail.attentionRetryGuidance:e.taskDetail.attentionCancelGuidance;return{title:c,guidance:l?`${l.guidance} ${m}`:m,...l?{expandDetails:!0}:{}}}const Kr={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 nn({task:e,className:n=""}){const s=U(),r=cs(s,e);return t.jsx("span",{className:`${Kr[e.status]??"pill"} ${n}`,title:r,"data-status":e.status,children:r})}function sn(e){if(!e)return"";const n=e.match(/^task-(\d+)$/);return n?n[1]:e}function Et(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 De(e,n){return`/project/${encodeURIComponent(e)}/task/${encodeURIComponent(n)}`}const $t={unknown:"pill pill-idle",idle:"pill pill-idle",pending:"pill pill-warn",working:"pill pill-live",waiting:"pill pill-review",error:"pill pill-warn"};function Qr(e,n,s,r=s!==void 0){const a=s!==void 0?Kt.has(s.status):r;return e==="greeting_failed"?"restart-runtime":e==="agent_dialog_pending"?"terminal":e==="bootstrap-marker-clear-failed"?(s==null?void 0:s.status)==="in_progress"||!s&&r?"task":"resume":e==="restart-redispatch-failed"?(s?["in_progress","fixing","approved"].includes(s.status):r)?"task":"resume":a&&(e==="agent_dialog_resolved_runtime"||e!=null&&e.startsWith("signal-arm-failed"))?"task":e==="dispatch-failed:ack_unknown"&&n==="dev"&&s&&["spec-ready","review","merge-ready","max_rounds"].includes(s.status)?"resume":a&&(e==="dispatch-failed:ack_unknown"||e==="dev-wait-gate-failed-after-qa-started")||a&&(s==null?void 0:s.status)!=="spec-ready"&&(s==null?void 0:s.status)!=="max_rounds"&&(e==="dirty-workdir"||e==="checkout-preparation-failed")&&n==="dev"?"task":"resume"}function us(e){var n;return!!((n=e.binding)!=null&&n.creationToken)&&!e.binding.paneId&&e.binding.status!=="awaiting_human"&&e.reason!=="PENDING_HUMAN"}function Yr(e,n){var s,r,a;return e.tmuxSessionStatus==="unreachable"?{kind:"alert",label:n.sessionStatus.unreachable,cls:"pill pill-danger"}:us(e)?{kind:"runtime",label:n.bootstrappingBadge,cls:"pill pill-review"}:Fn(e)?{kind:"runtime",label:n.dispatchingBadge,cls:"pill pill-review",title:n.dispatchingTitle}:e.tmuxSessionStatus==="absent"?{kind:"alert",label:n.sessionStatus.absent,cls:"pill pill-warn"}:e.runtimeStatus==="error"?{kind:"alert",label:n.runtimeStatus.error,cls:$t.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:$t.pending}:{kind:"runtime",label:n.runtimeStatus[e.runtimeStatus],cls:$t[e.runtimeStatus]}}function Jr(e,n){const s=Yr(e,n);if(!e.stale)return{...s,stale:!1};const r=n.staleTitle(e.observedAt?new Date(e.observedAt).toLocaleString():void 0);return{...s,stale:!0,title:s.title?`${s.title} · ${r}`:r}}function ms({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:p,onActivate:g,task:u}){var Z,z,ee,we,Ee,Fe,Te,Ne;const d=U(),[x,b]=o.useState(!1),[y,S]=o.useState(null),{show:A}=je(),R=en(),{compact:w,clear:k,remove:T,compacting:v,clearing:L,deleting:$,deleteError:H,busy:F}=ns(n,[e.id],i),[Q,P]=o.useState(!1),[G,te]=o.useState(!1),V=(Z=e.binding)==null?void 0:Z.taskId,Y=(u==null?void 0:u.id)===V?u:void 0,W=((z=e.binding)==null?void 0:z.status)==="awaiting_human",se=(we=(ee=e.binding)==null?void 0:ee.needInput)==null?void 0:we.at,J=W&&((Ee=e.binding)==null?void 0:Ee.awaitingPhase)==="greeting_failed",X=Qr((Fe=e.binding)==null?void 0:Fe.awaitingPhase,s,Y,!!V),oe=us(e),ge=oe&&e.tmuxSessionStatus!=="present",q=Jr(e,d.agents),he=h==="activity-preview"&&!ge&&(e.runtimeStatus==="working"||e.runtimeStatus==="pending"),de=h==="embedded-full",fe=de&&typeof g=="function",ye=fe&&p===!0,j=c||l||ge,xe=c?d.agents.agentStatusLoading:l?d.agents.terminalNeedsRestart:d.agents.bootstrappingTerminalDisabled,be=_n(r,a),D=async()=>{b(!0),S(null);try{await _.agents.stop(e.id)}catch(ae){S(ae instanceof Error?ae.message:String(ae))}finally{b(!1)}},N=async()=>{te(!0);try{(await _.projects.bootstrap(n)).ok?A({kind:"success",title:d.agents.retryBootstrapSucceededTitle,body:d.agents.retryBootstrapSucceededBody}):A({kind:"warn",title:d.agents.retryBootstrapStillFailingTitle,body:d.agents.retryBootstrapStillFailingBody})}catch(ae){A({kind:"error",title:d.agents.retryBootstrapFailedTitle,body:ae instanceof Error?ae.message:String(ae)})}finally{te(!1)}},O=async()=>{if(await R({title:d.agents.resumeConfirmTitle(e.id),body:J?d.agents.resumeGreetingBody:d.agents.resumeDefaultBody,confirmLabel:d.agents.resume})){P(!0);try{if(J){e.tmuxSessionStatus==="present"?await _.projects.restartRepl(n,e.id):await _.projects.retryAgent(n,e.id),A({kind:"success",title:d.agents.regreetingStartedTitle(e.id),body:d.agents.regreetingStartedBody});return}const $e=await _.projects.resumeAgent(n,e.id);A({kind:"success",title:d.agents.resumedTitle(e.id),body:$e.releasedBinding?d.agents.resumedReleasedBody:d.agents.resumedKeptBody})}catch($e){A({kind:"error",title:d.agents.resumeFailedTitle,body:$e instanceof Error?$e.message:String($e)})}finally{P(!1)}}},B=fe&&!j&&!ye,ue=["card relative flex h-full min-w-0 flex-col overflow-visible p-4",ye?"ring-2 ring-accent":""].filter(Boolean).join(" "),re="mb-3 flex items-start justify-between gap-2",I=["mb-2 mt-3 h-80 min-h-0 overflow-hidden border border-hairline bg-surface",B?"cursor-pointer":""].filter(Boolean).join(" "),C=B?()=>g==null?void 0:g():void 0,E=B?ae=>{(ae.key==="Enter"||ae.key===" ")&&(ae.preventDefault(),g==null||g())}:void 0;return t.jsxs("div",{className:ue,"data-agent-card":fe?e.id:void 0,children:[t.jsxs("div",{className:re,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-xs text-og-1000",title:Hn(e.id,r,a),children:e.id}),be&&t.jsxs("span",{className:"hidden shrink-0 whitespace-nowrap text-xs text-og-400 sm:inline",title:be,children:["(",be,")"]})]}),t.jsx("span",{className:q.stale?`${q.cls} pill--stale shrink-0`:`${q.cls} shrink-0`,title:q.title,children:q.label}),q.stale&&t.jsx("span",{className:"sr-only",children:q.title})]}),ge&&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}),W&&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:(Te=e.binding)==null?void 0:Te.awaitingPhase}),((Ne=e.binding)==null?void 0:Ne.awaitingReason)&&t.jsxs("span",{children:[" · ",e.binding.awaitingReason]})]}),t.jsx("div",{className:"text-og-700",children:d.agents.holdRecovery[X]})]}),!oe&&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(Ae,{to:`/terminal/${e.id}`,className:"text-accent hover:text-accent-hover underline",children:d.agents.terminal}),d.agents.openTerminalSuffix]})]}),se&&t.jsxs("div",{className:"mb-2 space-y-1 rounded-md border border-accent/25 bg-accent-soft/60 px-2.5 py-2 text-xs text-accent",children:[t.jsx("div",{className:"font-medium",children:d.agents.needInputNoticeTitle}),t.jsxs("div",{children:[d.agents.needInputPrefix,t.jsx(Ae,{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:N,disabled:G,className:"btn-primary shrink-0",children:G?d.common.retrying:d.agents.retryBootstrap})]})]}),m&&V&&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:V})]}),he&&t.jsx("div",{className:"mb-2 overflow-hidden border border-hairline bg-surface",children:t.jsx(Ke,{agentId:e.id,mode:"preview",maxLines:6,interactive:!1})}),de&&t.jsx("div",{className:I,role:B?"button":void 0,tabIndex:B?0:void 0,"aria-label":B?d.agents.activateTerminal(e.id):void 0,onClick:C,onKeyDown:E,children:j?t.jsx("div",{className:"flex h-full items-center justify-center px-3 text-sm text-og-500",children:xe}):fe?ye?t.jsx(Ke,{agentId:e.id,mode:"full",interactive:!0,autoFocus:!0}):t.jsx(Ke,{agentId:e.id,mode:"preview",interactive:!1}):t.jsx(Ke,{agentId:e.id,mode:"full",interactive:!0,autoFocus:!1,deferFullUntilFocus:!0})}),l&&t.jsx("div",{className:"mb-2 rounded-md border border-accent/25 bg-accent-soft/60 px-2.5 py-1.5 text-xs text-accent",children: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:[j?t.jsx("span",{className:"shrink-0 cursor-not-allowed text-sm text-og-400",title:xe,children:d.agents.terminal}):t.jsx(Ae,{to:`/terminal/${e.id}`,className:"btn-secondary shrink-0",children:d.agents.terminal}),!l&&e.runtimeStatus==="working"&&t.jsx("button",{onClick:D,disabled:x,className:"btn-ghost shrink-0",children:x?d.agents.stopping:d.agents.stop}),W&&(X==="resume"||X==="restart-runtime")&&t.jsx("button",{type:"button",onClick:O,disabled:Q,title:J?d.agents.resumeGreetingButtonTitle:d.agents.resumeDefaultButtonTitle,className:"btn-primary shrink-0",children:Q?d.agents.resuming:X==="restart-runtime"?d.agents.restartRuntime:d.agents.resume}),W&&X==="terminal"&&t.jsx(Ae,{to:`/terminal/${e.id}`,className:"btn-primary shrink-0",children:d.agents.openTerminalAction}),W&&X==="task"&&V&&t.jsx(Ae,{to:De(n,V),className:"btn-primary shrink-0",children:d.agents.openTaskActions}),W&&X==="delete-agent"&&t.jsx("button",{type:"button",onClick:()=>void T(),disabled:$,className:"btn-primary shrink-0",children:$?d.common.deleting:d.agents.deleteToRecover})]}),t.jsx(jt,{ariaLabel:d.agents.actionsMenu(e.id),className:"shrink-0",placement:"up",autoFocusFirstItem:!0,disabled:$,children:ae=>t.jsxs(t.Fragment,{children:[t.jsx(ke,{onClick:()=>{ae(),w()},disabled:F,title:d.agents.compactMenuItemTitle,children:v?d.agents.compacting:d.agents.compact}),t.jsx(ke,{onClick:()=>{ae(),k()},disabled:F,title:d.agents.clearMenuItemTitle,children:L?d.agents.clearing:d.agents.clear}),t.jsx(ke,{onClick:()=>{ae(),T()},disabled:F,children:$?d.common.deleting:d.common.delete})]})})]}),y&&t.jsx("div",{className:"mt-1.5 break-words text-xs text-accent",children:y}),H&&t.jsx("div",{className:"mt-1.5 break-words text-xs text-accent",children:H})]})}const It="baxian:terminal-activated";function hs({coordinateAcrossInstances:e=!0}={}){const n=o.useId(),[s,r]=o.useState(null);o.useEffect(()=>{if(s===null)return;const i=m=>{m.composedPath().some(g=>g instanceof Element&&g.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(It,c),()=>{document.removeEventListener("click",i),document.removeEventListener("keydown",l),e&&document.removeEventListener(It,c)}},[s,e,n]);const a=o.useCallback(i=>{r(i),e&&document.dispatchEvent(new CustomEvent(It,{detail:{ownerId:n}}))},[e,n]);return{activeAgentId:s,activateAgentCard:a}}function fs({team:e,projectId:n,agentsById:s,agentsLoaded:r,agentsError:a=!1,tasks:i,onDeleted:l,terminalMode:c="activity-preview"}){const m=U(),h=e.find(P=>P.role==="dev")??e[0],p=i.filter(P=>ea(P,h==null?void 0:h.id)),g=h?i.filter(P=>ta(P,n,h.id)).sort((P,G)=>P.createdAt.localeCompare(G.createdAt)):[],u=e.map(P=>P.id).join(" / "),d=`Agent Team ${u}`,x=Pe(),{compact:b,clear:y,remove:S,compacting:A,clearing:R,deleting:w,deleteError:k,busy:T}=ns(n,e.map(P=>P.id),l),v=c==="embedded-full",{activeAgentId:L,activateAgentCard:$}=hs({coordinateAcrossInstances:v}),H=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",F=!!h&&g.length>0,Q=p.length===0&&!F;return t.jsxs("div",{role:"group","aria-label":d,className:"min-w-0 rounded-lg border border-og-100 bg-og-25/60 p-3",children:[t.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[t.jsx("span",{className:"shrink-0 font-display text-xs font-semibold uppercase tracking-[0.06em] text-og-500",children:"Team"}),t.jsx("span",{className:"min-w-0 truncate font-mono text-xs text-og-700",title:u,children:u}),t.jsx(jt,{ariaLabel:m.agents.teamActionsMenu(u),className:"ml-auto shrink-0",autoFocusFirstItem:!0,disabled:w,children:P=>t.jsxs(t.Fragment,{children:[t.jsx(ke,{onClick:()=>{P(),b()},disabled:T,title:m.agents.teamCompactMenuItemTitle,children:A?m.agents.compacting:m.agents.compact}),t.jsx(ke,{onClick:()=>{P(),y()},disabled:T,title:m.agents.teamClearMenuItemTitle,children:R?m.agents.clearing:m.agents.clear}),t.jsx(ke,{onClick:()=>{P(),S()},disabled:T,children:w?m.common.deleting:m.common.delete})]})})]}),k&&t.jsx("div",{className:"mb-2 break-words text-xs text-accent",children:k}),F&&h&&t.jsx(Zr,{tasks:g,devId:h.id,agentsById:s,label:d}),p.length>0&&t.jsx("div",{className:"card mb-2 max-h-28 overflow-y-auto divide-y divide-hairline",children:p.map(P=>{const G=Me(P.phase)?P.specReviewRound??0:P.reviewRound;return t.jsxs("button",{type:"button",onClick:()=>x(De(P.projectId,P.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:P.id,children:sn(P.id)}),t.jsx("span",{className:"truncate text-og-1000",children:P.title})]}),t.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[G>0&&t.jsx("span",{className:"shrink-0 text-xs text-og-500",children:m.agents.round(G)}),t.jsx(nn,{task:P,className:"shrink-0"})]})]},P.id)})}),Q&&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(d),children:m.agents.noActiveTask}),t.jsx("div",{className:`grid grid-cols-1 ${H} gap-4`,children:e.map(P=>{var Y;const G=s.get(P.id),te=G??{id:P.id,projectId:n,runtimeStatus:"unknown",tmuxSessionStatus:"unknown",stale:!0},V=((Y=te.binding)==null?void 0:Y.taskId)===void 0?void 0:i.find(W=>{var se;return W.id===((se=te.binding)==null?void 0:se.taskId)});return t.jsx(ms,{agent:te,projectId:n,role:P.role,runtime:P.runtime,model:P.model,pendingRestart:r&&!G,terminalLoading:!r&&!G&&!a,onDeleted:l,showTaskBinding:!1,terminalMode:c,task:V,...v?{active:L===P.id,onActivate:()=>$(P.id)}:{}},P.id)})})]})}function Xr(e){var n,s,r;return!!e&&e.runtimeStatus==="idle"&&((n=e.binding)==null?void 0:n.status)!=="awaiting_human"&&!((s=e.binding)!=null&&s.creationToken)&&!((r=e.binding)!=null&&r.taskId)}function Zr({tasks:e,devId:n,agentsById:s,label:r}){const a=U(),{show:i}=je(),l=Pe(),[c,m]=o.useState(null),h=async(p,g)=>{m(p);try{await _.tasks.advance(p,{executor:"dev",agentId:g}),i({kind:"success",title:a.agents.taskHandedTo(p,g)})}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(p=>{const g=p.preferredAgentId||n,u=Xr(s.get(g)),d=p.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(De(p.projectId,p.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:p.id,children:sn(p.id)}),t.jsx("span",{className:"truncate text-og-1000",title:p.title,children:p.title}),d&&t.jsx("span",{className:"pill shrink-0",children:a.agents.unassigned})]}),t.jsx("button",{type:"button",onClick:()=>void h(p.id,g),disabled:!u||x,title:u?a.agents.handToAndStart(g):a.agents.agentUnavailable(g),className:"shrink-0 text-sm font-medium text-accent transition-colors hover:text-accent-hover disabled:opacity-50 disabled:cursor-not-allowed",children:c===p.id?a.agents.starting:a.agents.start})]},p.id)})})}function ea(e,n){return!n||!Kt.has(e.status)?!1:e.devAgentId===n}function ta(e,n,s){return e.projectId!==n||e.status!=="pending"?!1:e.preferredAgentId===s||e.preferredAgentId===""}const me="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",ce="mb-1.5 block text-xs font-medium text-og-700",bt="mt-1 text-xs text-accent",He="mt-1 text-xs text-og-500",Ie="h-3.5 w-3.5 accent-accent",na=/^[a-z][a-z0-9-]{1,31}$/;function sa({open:e,onClose:n,onCreated:s}){const r=U(),[a,i]=o.useState(""),[l,c]=o.useState(""),[m,h]=o.useState(null),[p,g]=o.useState("human"),[u,d]=o.useState(!1),[x,b]=o.useState(null),[y,S]=o.useState({}),[A,R]=o.useState(new Set),w=o.useRef(0),{show:k}=je(),{flagDirty:T}=Nt();o.useEffect(()=>{if(!e)return;w.current+=1;const H=w.current;i(""),c(""),h(null),g("human"),b(null),S({}),R(new Set),_.config.get().then(F=>{H===w.current&&R(new Set(F.project.map(Q=>Q.id)))}).catch(F=>{H===w.current&&b(r.common.loadFailed(F instanceof Error?F.message:String(F)))})},[e]);const v=()=>{u||n()},L=()=>{const H={};return a?na.test(a)?A.has(a)&&(H.id=r.createProject.idTakenError):H.id=r.common.idFormatError:H.id=r.createProject.required,l.trim()||(H.repo=r.createProject.required),S(H),Object.keys(H).length===0},$=async H=>{if(H.preventDefault(),!!L()){d(!0),b(null);try{const F=await _.projects.create({id:a,repo:l.trim(),merge:m,...p?{specApproval:p}:{}});F.restartRequired&&T(),k({kind:"success",title:r.createProject.createdToastTitle(F.project.id)}),s(F.project.id)}catch(F){b(F instanceof Error?F.message:String(F))}finally{d(!1)}}};return t.jsx(Le,{open:e,onClose:v,title:r.createProject.title,size:"md",footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:v,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:$,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:ce,htmlFor:"proj-id",children:r.createProject.idLabel}),t.jsx("input",{id:"proj-id",type:"text",value:a,onChange:H=>i(H.target.value),className:me,placeholder:"baxian",disabled:u}),y.id&&t.jsx("div",{className:bt,children:y.id})]}),t.jsxs("div",{children:[t.jsx("label",{className:ce,htmlFor:"proj-repo",children:r.createProject.repoLabel}),t.jsx("input",{id:"proj-repo",type:"text",value:l,onChange:H=>c(H.target.value),className:me,placeholder:"https://github.com/baxian-ai/baxian.git",disabled:u}),y.repo&&t.jsx("div",{className:bt,children:y.repo})]}),t.jsxs("div",{children:[t.jsx("span",{className:ce,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:ce,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:p==="human",onChange:()=>g("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:p===null,onChange:()=>g(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 wn=/^[a-z][a-z0-9-]{1,31}$/,ra=500,Bt={id:"",mode:"local",host:"",runtime:"",workdir:"",yolo:!0,model:"",addDirs:""};function aa(e){return e.alias?e.alias:`${e.user?`${e.user}@`:""}${e.hostname}${e.port!=null?`:${e.port}`:""}`}function ps({open:e,onClose:n,projectId:s,onCreated:r}){var D,N,O,B,ue,re;const a=U(),[i,l]=o.useState(Bt),[c,m]=o.useState(null),[h,p]=o.useState([]),[g,u]=o.useState(new Set),[d,x]=o.useState(null),[b,y]=o.useState(!1),[S,A]=o.useState(!1),[R,w]=o.useState(null),[k,T]=o.useState(!1),[v,L]=o.useState(null),[$,H]=o.useState(!1),F=o.useRef(null),Q=o.useRef(null),P=o.useRef(0),G=o.useRef(0),{show:te}=je(),{flagDirty:V}=Nt();o.useEffect(()=>{if(!e)return;G.current+=1;const I=G.current;l(Bt),m(null),p([]),u(new Set),x(null),y(!1),A(!1),w(null),P.current+=1,L(null),H(!1),_.config.get().then(C=>{if(I!==G.current)return;p(C.host??[]);const E=new Set;C.project.forEach(Z=>Z.agent.forEach(z=>z.forEach(ee=>E.add(ee.id)))),u(E)}).catch(()=>{})},[e,s]);const Y=()=>{k||n()},W=o.useCallback(()=>{F.current&&F.current.abort();const I=new AbortController;F.current=I,y(!0),L(null);const C=i.mode==="remote"?{hostId:i.host}:{};_.agents.probe(i.mode,C,{signal:I.signal}).then(E=>{I.signal.aborted||(x(E),L(null))}).catch(E=>{I.signal.aborted||(x(null),L(E instanceof Error?E.message:String(E)))}).finally(()=>{F.current===I&&y(!1)})},[i.mode,i.host]);o.useEffect(()=>{if(e&&(x(null),w(null),A(!1),P.current+=1,F.current&&F.current.abort(),!(i.mode==="remote"&&!i.host)))return Q.current&&clearTimeout(Q.current),Q.current=setTimeout(W,ra),()=>{Q.current&&clearTimeout(Q.current)}},[e,i.mode,i.host,c,W]),o.useEffect(()=>{e||F.current&&F.current.abort()},[e]),o.useEffect(()=>()=>{F.current&&F.current.abort(),Q.current&&clearTimeout(Q.current)},[]);const se=()=>{if(S)return;const I=P.current;A(!0),w(null);const C=i.mode==="remote"?{hostId:i.host}:{};_.agents.installTmux(i.mode,C).then(E=>{P.current===I&&(w({ok:E.ok,message:E.message}),A(!1),E.ok&&W())}).catch(E=>{P.current===I&&(w({ok:!1,message:E instanceof Error?E.message:String(E)}),A(!1))})},J=c?"qa":"dev",X=wn.test(i.id)&&!g.has(i.id)&&i.id!==(c==null?void 0:c.agent.id),oe=i.mode==="local"||i.mode==="remote"&&i.host!=="",ge=i.runtime!==""&&!!((D=d==null?void 0:d.runtimes[i.runtime])!=null&&D.ok),q=!!(d!=null&&d.tmux.ok),he=i.mode==="local"||!!((N=d==null?void 0:d.ssh)!=null&&N.ok),de=!k&&X&&oe&&ge&&q&&he,fe=async I=>{var Z,z;if(I.preventDefault(),!de)return;L(null);const C=i.addDirs.split(`
11
+ `).map(ee=>ee.trim()).filter(ee=>ee.length>0),E={id:i.id,role:J,runtime:i.runtime,mode:i.mode,...i.mode==="remote"?{host:i.host}:{},...i.workdir?{workdir:i.workdir}:{},yolo:i.yolo,...i.model.trim()?{model:i.model.trim()}:{},...C.length>0?{addDirs:C}:{}};if(!c){m({agent:E,form:i}),l(Bt),x(null),w(null),H(!1);return}T(!0);try{const ee=await _.projects.addAgentTeam(s,{agents:[c.agent,E]});ee.restartRequired&&V(),te({kind:(Z=ee.warnings)!=null&&Z.length?"warn":"success",title:a.createAgent.addedToastTitle(ee.agents.find(we=>we.role==="dev").id,ee.agents.find(we=>we.role==="qa").id,s),...(z=ee.warnings)!=null&&z.length?{body:ee.warnings.join(`
12
+ `)}:{}}),r(),n()}catch(ee){L(ee instanceof Error?ee.message:String(ee))}finally{T(!1)}},ye=()=>{!c||k||(l(c.form),m(null),x(null),w(null),H(!1))},j=({rt:I})=>{if(i.mode==="remote"&&!i.host)return t.jsx("span",{className:"ml-2 text-xs text-og-400",children:a.createAgent.selectHostFirstHint});if(b)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 E=d.runtimes[I];return E?E.ok?t.jsxs("span",{className:"ml-2 text-xs text-probe-ok",children:["✓ ",E.path??""]}):t.jsxs("span",{className:"ml-2 text-xs text-accent",title:E.message,children:["⨯ ",E.message]}):t.jsx("span",{className:"ml-2 text-xs text-og-400",children:"?"})},xe=()=>{var C;if(i.mode==="remote"&&!i.host)return null;if(b&&!S)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=i.mode==="local"||!!((C=d.ssh)!=null&&C.ok);return t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"text-xs text-accent",children:["tmux: ⨯ ",d.tmux.message,I&&t.jsx("button",{type:"button",onClick:se,className:"ml-2 text-accent underline transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",disabled:S||k,children:S?a.common.installing:a.common.oneClickInstall})]}),S&&t.jsx("div",{className:"text-xs text-og-500",children:a.common.installingTmuxNotice}),!S&&R&&t.jsxs("div",{className:`break-all text-xs ${R.ok?"text-probe-ok":"text-accent"}`,children:[R.ok?"✓ ":"⨯ ",R.message]})]})},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(Le,{open:e,onClose:Y,title:a.createAgent.modalTitle(s),size:"lg",footer:t.jsxs(t.Fragment,{children:[c&&t.jsx("button",{type:"button",onClick:ye,disabled:k,className:"btn-secondary",children:a.common.back}),t.jsx("button",{type:"button",onClick:Y,disabled:k,className:"btn-secondary",children:a.common.cancel}),t.jsx("button",{type:"submit",form:"create-agent-form",disabled:!de,className:"btn-primary",children:k?a.createAgent.submitting:c?a.createAgent.submitLabel:a.createAgent.continueLabel})]}),children:t.jsxs("form",{id:"create-agent-form",onSubmit:fe,className:"space-y-3",children:[v&&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:v}),t.jsxs("div",{children:[t.jsx("label",{className:ce,htmlFor:"agent-id",children:"Agent ID"}),t.jsx("input",{id:"agent-id",type:"text",value:i.id,onChange:I=>l({...i,id:I.target.value}),className:me,placeholder:a.createAgent.idPlaceholder(s,J),disabled:k}),i.id&&!wn.test(i.id)&&t.jsx("div",{className:bt,children:a.common.idFormatError}),i.id&&(g.has(i.id)||i.id===(c==null?void 0:c.agent.id))&&t.jsx("div",{className:bt,children:a.createAgent.idTakenGlobalError})]}),t.jsxs("div",{children:[t.jsx("span",{className:ce,children:a.createAgent.roleLabel}),t.jsx("div",{className:"text-sm text-og-800",children:J==="dev"?a.createAgent.devStepLabel:a.createAgent.qaStepLabel}),c&&t.jsx("div",{className:He,children:a.createAgent.teamDevLabel(c.agent.id)})]}),t.jsxs("div",{children:[t.jsx("span",{className:ce,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:Ie,onChange:()=>l({...i,mode:"local",host:""}),disabled:k}),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:Ie,onChange:()=>l({...i,mode:"remote"}),disabled:k}),t.jsx("span",{className:"text-sm text-og-800",children:a.createAgent.remoteModeLabel})]})]}),i.mode==="remote"&&t.jsxs("div",{children:[t.jsx("label",{className:ce,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:I=>l({...i,host:I.target.value}),className:me,disabled:k,children:[t.jsx("option",{value:"",children:a.createAgent.selectHostPlaceholder}),h.map(I=>t.jsx("option",{value:I.id,children:aa(I)},I.id))]}),t.jsx("div",{className:He,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:W,className:"text-xs text-accent transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",disabled:k||b||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:Ie,onChange:()=>l({...i,runtime:"claude-code"}),disabled:k||(d?!((O=d.runtimes["claude-code"])!=null&&O.ok):!1)}),t.jsx("span",{className:"text-sm text-og-800",children:"Claude Code"}),t.jsx(j,{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:Ie,onChange:()=>l({...i,runtime:"codex"}),disabled:k||(d?!((B=d.runtimes.codex)!=null&&B.ok):!1)}),t.jsx("span",{className:"text-sm text-og-800",children:"Codex"}),t.jsx(j,{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:Ie,onChange:()=>l({...i,runtime:"opencode"}),disabled:k||(d?!((ue=d.runtimes.opencode)!=null&&ue.ok):!1)}),t.jsx("span",{className:"text-sm text-og-800",children:"OpenCode"}),t.jsx(j,{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:Ie,onChange:()=>l({...i,runtime:"qodercli"}),disabled:k||(d?!((re=d.runtimes.qodercli)!=null&&re.ok):!1)}),t.jsx("span",{className:"text-sm text-og-800",children:"Qoder CLI"}),t.jsx(j,{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:()=>H(I=>!I),"aria-expanded":$,"aria-controls":$?"advanced-options":void 0,className:"flex w-full items-center justify-between rounded-md px-1 py-1.5 text-left text-xs font-medium text-og-700 transition-colors hover:bg-og-50",children:[t.jsx("span",{children:a.createAgent.advancedOptionsLabel}),t.jsx("span",{className:"text-og-400",children:$?a.createAgent.collapseLabel:a.createAgent.expandLabel})]}),$&&t.jsxs("div",{id:"advanced-options",className:"mt-3 space-y-3",children:[t.jsxs("div",{children:[t.jsx("label",{className:ce,htmlFor:"workdir",children:a.createAgent.workdirLabel}),t.jsx("input",{id:"workdir",type:"text",value:i.workdir,onChange:I=>l({...i,workdir:I.target.value}),className:me,placeholder:a.createAgent.workdirPlaceholder,disabled:k}),t.jsx("div",{className:He,children:a.createAgent.workdirHint})]}),t.jsxs("div",{children:[t.jsx("label",{className:ce,htmlFor:"model",children:a.createAgent.modelLabel}),t.jsx("input",{id:"model",type:"text",value:i.model,onChange:I=>l({...i,model:I.target.value}),className:me,placeholder:i.runtime==="codex"?a.createAgent.modelPlaceholderCodex:a.createAgent.modelPlaceholderOther,disabled:k}),t.jsx("div",{className:He,children:a.createAgent.modelHint})]}),t.jsxs("div",{children:[t.jsx("label",{className:ce,htmlFor:"addDirs",children:a.createAgent.addDirsLabel}),t.jsx("textarea",{id:"addDirs",value:i.addDirs,onChange:I=>l({...i,addDirs:I.target.value}),className:`${me} font-mono text-xs`,rows:3,placeholder:a.createAgent.addDirsPlaceholder,disabled:k}),t.jsx("div",{className:He,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:I=>l({...i,yolo:I.target.checked}),disabled:k}),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:er[i.runtime||"claude-code"]}),a.createAgent.yoloBodyTrail]})]})]})})]})})}const kn=200,jn=16e3,ia="baxian.draft.createTask:";function Gt(e){return`${ia}${e??"*"}`}function Tn(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 oa(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 Nn(e){try{localStorage.removeItem(e)}catch{}}function la(e){const n=Gt(e),s=Tn(n);if(!e)return s;const r=Gt(void 0),a=Tn(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 Sn="mt-1 text-right text-xs text-og-400",ca=Math.floor(Tt/1024/1024);function rn(e){const n=U(),s=e.mode==="edit",{show:r}=je(),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([]),[p,g]=o.useState([]),[u,d]=o.useState(a??""),[x,b]=o.useState(c),[y,S]=o.useState(i),[A,R]=o.useState(l),[w,k]=o.useState([]),T=o.useRef(null),[v,L]=o.useState(!1),[$,H]=o.useState(null),[F,Q]=o.useState(!1),P=o.useRef(0),G=o.useRef(0),te=o.useRef(0),V=o.useRef(new Set),Y=s?null:Gt(a);o.useEffect(()=>{if(!e.open)return;P.current+=1,G.current+=1;const C=P.current;h([]),g([]),V.current=new Set;const E=Y?la(a):null;E&&V.current.add(E.projectId),d(a??(E==null?void 0:E.projectId)??""),b((E==null?void 0:E.preferredAgentId)||c),S((E==null?void 0:E.title)||i),R((E==null?void 0:E.description)||l),Q(E!==null),H(null),L(!1),k([]),Promise.all([_.projects.list(),_.agents.list()]).then(([Z,z])=>{C===P.current&&(h(Z),g(z))}).catch(Z=>{C===P.current&&H(Z instanceof Error?Z.message:String(Z))})},[e.open,a,i,l,c,Y]),o.useEffect(()=>{if(!(!e.open||!Y)){if(te.current!==G.current){te.current=G.current;return}oa(Y,{title:y,description:A,projectId:u,preferredAgentId:x})}},[e.open,Y,y,A,u,x]);const W=o.useMemo(()=>m.find(C=>C.id===u)??null,[m,u]),se=o.useMemo(()=>W?W.agent.flat().filter(C=>C.role==="dev"):[],[W]),J=o.useMemo(()=>new Set(p.map(C=>C.id)),[p]),X=o.useMemo(()=>se.filter(C=>J.has(C.id)),[se,J]),oe=o.useMemo(()=>se.filter(C=>!J.has(C.id)),[se,J]);o.useEffect(()=>{s||W!==null&&x!==""&&!X.find(C=>C.id===x)&&b("")},[W,X,x,s]),o.useEffect(()=>{if(s||!W)return;const C=X.find(E=>E.role==="dev");C&&(V.current.has(W.id)||(V.current.add(W.id),b(E=>E===""?C.id:E)))},[s,W,X]);const ge=!s||X.find(C=>C.id===x),q=s&&!ge&&!!x,he=q&&oe.some(C=>C.id===x),de=he?n.createTask.noDevPendingRestartHint(x):q?n.createTask.noDevNotInRuntimeHint(x):!u||X.length>0?null:oe.length>0?n.createTask.noDevGlobalPendingRestartHint:null,fe=y.trim(),ye=A.trim(),xe=!!u&&fe.length>0&&!v,be=()=>{v||e.onClose()},D=()=>{Y&&(Nn(Y),d(a??""),b(c),S(i),R(l),H(null),Q(!1))},N=async C=>{var E,Z;if(C.preventDefault(),!!xe){L(!0),H(null);try{if(e.mode==="edit"){const z=await _.tasks.update(e.task.id,{title:fe,description:ye,preferredAgentId:x});r({kind:"success",title:n.createTask.updatedToastTitle}),(E=e.onUpdated)==null||E.call(e,z),e.onClose()}else{const z=w.length?await Promise.all(w.map(async we=>({dataBase64:await Gn(we),filename:we.name}))):void 0,ee=await _.tasks.create({projectId:u,title:fe,description:ye,preferredAgentId:x,...z?{images:z}:{}});Y&&Nn(Y),r({kind:"success",title:n.createTask.createdToastTitle}),(Z=e.onCreated)==null||Z.call(e,ee),e.onClose()}}catch(z){H(z instanceof Error?z.message:String(z))}finally{L(!1)}}},O=C=>{const E=Array.from(C.target.files??[]);if(C.target.value="",E.length===0)return;const Z=E.filter(z=>z.size>Tt?(r({kind:"error",title:n.createTask.imageTooLargeToastTitle,body:n.createTask.imageTooLargeToastBody(z.name,ca)}),!1):!0);w.length+Z.length>ot&&r({kind:"warn",title:n.createTask.tooManyImagesToastTitle(ot)}),k(z=>[...z,...Z].slice(0,ot))},B=C=>k(E=>E.filter((Z,z)=>z!==C)),ue=s?n.createTask.titleEdit:n.createTask.titleCreate,re=s?v?n.common.saving:n.common.save:v?n.common.creating:n.common.create,I=!s&&!a;return t.jsx(Le,{open:e.open,onClose:be,title:ue,size:"md",dismissOnBackdrop:!1,footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:be,disabled:v,className:"btn-secondary",children:n.common.cancel}),t.jsx("button",{type:"submit",form:"create-task-form",disabled:!xe,className:"btn-primary",children:re})]}),children:t.jsxs("form",{id:"create-task-form",onSubmit:N,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:D,className:"shrink-0 underline hover:text-accent-hover",children:n.createTask.discardDraftButton})]}),$&&t.jsx("div",{className:"rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-sm text-accent",children:$}),I&&t.jsxs("div",{children:[t.jsx("label",{className:ce,htmlFor:"task-project",children:"Project"}),t.jsxs("select",{id:"task-project",value:u,onChange:C=>d(C.target.value),className:me,disabled:v,required:!0,children:[t.jsx("option",{value:"",disabled:!0,children:n.createTask.selectProjectPlaceholder}),m.map(C=>t.jsx("option",{value:C.id,children:C.id},C.id))]})]}),t.jsxs("div",{children:[t.jsx("label",{className:ce,htmlFor:"task-dev",children:n.createTask.targetAgentLabel}),t.jsxs("select",{id:"task-dev",value:x,onChange:C=>b(C.target.value),className:me,disabled:v,children:[t.jsx("option",{value:"",children:n.createTask.notAssignedOption}),q&&t.jsxs("option",{value:x,children:[x," ",he?n.createTask.pendingRestartSuffix:n.createTask.notInRuntimeSuffix]}),X.map(C=>t.jsx("option",{value:C.id,children:C.id},C.id))]}),de&&t.jsx("div",{className:"mt-1 text-xs text-accent",children:de})]}),t.jsxs("div",{children:[t.jsx("label",{className:ce,htmlFor:"task-title",children:"Title"}),t.jsx("input",{id:"task-title",type:"text",value:y,onChange:C=>S(C.target.value),maxLength:kn,className:me,placeholder:n.createTask.titlePlaceholder,disabled:v,required:!0}),t.jsxs("div",{className:Sn,children:[y.length," / ",kn]})]}),t.jsxs("div",{children:[t.jsx("label",{className:ce,htmlFor:"task-description",children:n.createTask.descriptionLabel}),t.jsx("textarea",{id:"task-description",value:A,onChange:C=>R(C.target.value),maxLength:jn,rows:8,className:`${me} font-mono text-xs`,placeholder:n.createTask.descriptionPlaceholder,disabled:v}),t.jsxs("div",{className:Sn,children:[A.length," / ",jn]})]}),!s&&t.jsxs("div",{children:[t.jsx("label",{className:ce,children:n.createTask.imagesLabel}),t.jsx("button",{type:"button",onClick:()=>{var C;return(C=T.current)==null?void 0:C.click()},disabled:v||w.length>=ot,className:"btn-secondary",children:n.createTask.addImagesButton}),t.jsx("input",{ref:T,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:O}),w.length>0&&t.jsx("ul",{className:"mt-2 space-y-1",children:w.map((C,E)=>t.jsxs("li",{className:"flex items-center justify-between rounded-md border border-og-100 bg-surface px-2.5 py-1.5",children:[t.jsx("span",{title:C.name,className:"truncate text-xs text-og-700",children:C.name}),t.jsx("button",{type:"button","aria-label":n.createTask.removeImageAriaLabel(C.name),onClick:()=>B(E),disabled:v,className:"ml-2 shrink-0 text-og-400 transition-colors",children:"✕"})]},`${C.name}-${E}`))})]})]})})}const Rn="***",Mt={hostname:"",port:"",alias:"",user:"",password:""};function da(e){return e.alias?e.alias:`${e.user?`${e.user}@`:""}${e.hostname}${e.port!=null?`:${e.port}`:""}`}function ua({open:e,onClose:n}){var be;const s=U(),[r,a]=o.useState([]),[i,l]=o.useState("list"),[c,m]=o.useState(null),[h,p]=o.useState(null),[g,u]=o.useState(!1),[d,x]=o.useState(!1),[b,y]=o.useState(Mt),[S,A]=o.useState(null),[R,w]=o.useState(!1),[k,T]=o.useState(!1),[v,L]=o.useState(null),[$,H]=o.useState(!1),[F,Q]=o.useState(null),P=o.useRef(0),G=o.useRef(null),{show:te}=je(),V=o.useCallback(()=>{_.hosts.list().then(a).catch(D=>A(D instanceof Error?D.message:String(D)))},[]);o.useEffect(()=>{if(!e){G.current&&G.current.abort();return}l("list"),m(null),p(null),y(Mt),A(null),V()},[e,V]),o.useEffect(()=>{P.current+=1,G.current&&G.current.abort(),T(!1),L(null),H(!1),Q(null)},[b.hostname,b.user,b.port,b.password,d,i]),o.useEffect(()=>()=>{G.current&&G.current.abort()},[]);const Y=()=>{m(null),p(null),u(!1),x(!1),y(Mt),A(null),l("form")},W=D=>{m(D.id??null),p(D),u(D.password===Rn),x(!1),y({hostname:D.hostname,port:D.port!=null?String(D.port):"",alias:D.alias??"",user:D.user??"",password:""}),A(null),l("form")},se=()=>{const D={hostname:b.hostname.trim()};return c?(D.port=b.port.trim()?Number(b.port):null,D.alias=b.alias.trim(),D.user=b.user.trim()):(b.port.trim()&&(D.port=Number(b.port)),b.alias.trim()&&(D.alias=b.alias.trim()),b.user.trim()&&(D.user=b.user.trim())),c&&d?D.password="":b.password&&(D.password=b.password),D},J=b.port.trim(),X=J===""||/^\d+$/.test(J)&&Number(J)>0&&Number(J)<=65535,oe=b.hostname.trim().length>0&&X,ge=!!h&&b.hostname.trim()===h.hostname&&b.user.trim()===(h.user??"")&&b.port.trim()===(h.port!=null?String(h.port):""),q=()=>c&&ge&&!b.password&&!d?{hostId:c}:{host:{hostname:b.hostname.trim(),...b.user.trim()?{user:b.user.trim()}:{},...J?{port:Number(J)}:{},...!d&&b.password?{password:b.password}:{}}},he=async()=>{if(!oe||k)return;G.current&&G.current.abort();const D=new AbortController;G.current=D;const N=P.current;T(!0),L(null),Q(null),A(null);try{const O=await _.agents.probe("remote",q(),{signal:D.signal});if(D.signal.aborted||P.current!==N)return;L(O)}catch(O){if(D.signal.aborted||P.current!==N)return;A(O instanceof Error?O.message:String(O))}finally{P.current===N&&T(!1)}},de=async()=>{if($)return;const D=P.current;H(!0),Q(null),A(null);try{const N=await _.agents.installTmux("remote",q());if(P.current!==D)return;Q({ok:N.ok,message:N.message}),L(O=>O&&{...O,tmux:N.tmux})}catch(N){if(P.current!==D)return;A(N instanceof Error?N.message:String(N))}finally{P.current===D&&H(!1)}},fe=async D=>{if(D.preventDefault(),!(!oe||R)){w(!0),A(null);try{if(c)await _.hosts.update(c,se()),te({kind:"success",title:s.hostMgmt.updatedToastTitle(c)});else{const N=await _.hosts.create(se());te({kind:"success",title:s.hostMgmt.createdToastTitle(N.host.id)})}V(),l("list")}catch(N){A(N instanceof Error?N.message:String(N))}finally{w(!1)}}},ye=async D=>{A(null);try{await _.hosts.delete(D.id),te({kind:"success",title:s.hostMgmt.deletedToastTitle(D.id)}),V()}catch(N){A(N instanceof Error?N.message:String(N))}},j=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:!oe||R,className:"btn-primary",children:R?s.common.saving:s.common.save})]});return t.jsxs(Le,{open:e,onClose:n,title:s.hostMgmt.title,size:"md",footer:i==="list"?j:xe,children:[S&&t.jsx("div",{className:"mb-3 whitespace-pre-line rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-sm text-accent",children:S}),i==="list"?t.jsxs("div",{className:"space-y-3",children:[r.length===0?t.jsx("p",{className:"text-sm text-og-500",children:s.hostMgmt.emptyState}):t.jsx("ul",{className:"space-y-1.5",children:r.map(D=>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:da(D)}),t.jsxs("div",{className:"truncate text-xs text-og-500",children:[(D.user?`${D.user}@`:"")+D.hostname,D.port!=null?`:${D.port}`:"",D.password===Rn?s.hostMgmt.passwordSavedIndicator:""]})]}),t.jsxs("div",{className:"flex shrink-0 gap-2",children:[t.jsx("button",{type:"button",onClick:()=>W(D),className:"text-xs text-accent transition-colors hover:text-accent-hover",children:s.common.edit}),t.jsx("button",{type:"button",onClick:()=>ye(D),className:"text-xs text-accent transition-colors hover:opacity-80",children:s.common.delete})]})]},D.id))}),t.jsx("button",{type:"button",onClick:Y,className:"btn-secondary w-full",children:s.hostMgmt.addHostButton})]}):t.jsxs("form",{id:"host-form",onSubmit:fe,className:"space-y-3",children:[t.jsxs("div",{children:[t.jsx("label",{className:ce,htmlFor:"host-hostname",children:s.hostMgmt.addressLabel}),t.jsx("input",{id:"host-hostname",type:"text",value:b.hostname,onChange:D=>y({...b,hostname:D.target.value}),className:me,placeholder:"remote.example.com",disabled:R})]}),t.jsxs("div",{children:[t.jsx("label",{className:ce,htmlFor:"host-port",children:s.hostMgmt.portLabel}),t.jsx("input",{id:"host-port",type:"text",inputMode:"numeric",value:b.port,onChange:D=>y({...b,port:D.target.value}),className:me,placeholder:"22",disabled:R}),b.port.trim()!==""&&!X&&t.jsx("div",{className:"mt-1 text-xs text-accent",children:s.hostMgmt.portRangeError})]}),t.jsxs("div",{children:[t.jsx("label",{className:ce,htmlFor:"host-alias",children:s.hostMgmt.aliasLabel}),t.jsx("input",{id:"host-alias",type:"text",value:b.alias,onChange:D=>y({...b,alias:D.target.value}),className:me,placeholder:"Prod worker",disabled:R})]}),t.jsxs("div",{children:[t.jsx("label",{className:ce,htmlFor:"host-user",children:s.hostMgmt.userLabel}),t.jsx("input",{id:"host-user",type:"text",value:b.user,onChange:D=>y({...b,user:D.target.value}),className:me,placeholder:s.hostMgmt.userPlaceholder,disabled:R})]}),t.jsxs("div",{children:[t.jsx("label",{className:ce,htmlFor:"host-password",children:s.hostMgmt.passwordLabel}),t.jsx("input",{id:"host-password",type:"password",value:d?"":b.password,onChange:D=>y({...b,password:D.target.value}),className:me,placeholder:g?s.hostMgmt.passwordPlaceholderSet:s.hostMgmt.passwordPlaceholderUnset,disabled:R||d,autoComplete:"new-password"}),c&&g&&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:D=>x(D.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:he,disabled:!oe||k||R||$,className:"text-xs text-accent transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",children:k?s.hostMgmt.testing:s.hostMgmt.testConnection}),(v==null?void 0:v.ssh)&&t.jsxs("div",{className:`text-xs ${v.ssh.ok?"text-og-800":"text-accent"}`,children:["SSH: ",v.ssh.ok?"✓":"⨯"," ",v.ssh.message]}),v&&(v.tmux.ok?t.jsxs("div",{className:"text-xs text-og-800",children:["tmux: ✓ ",v.tmux.path??""]}):t.jsxs("div",{className:"text-xs text-accent",children:["tmux: ⨯ ",v.tmux.message,((be=v.ssh)==null?void 0:be.ok)&&t.jsx("button",{type:"button",onClick:de,disabled:$||R,className:"ml-2 text-accent underline transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",children:$?s.common.installing:s.common.oneClickInstall})]})),$&&t.jsx("div",{className:"text-xs text-og-500",children:s.common.installingTmuxNotice}),!$&&F&&t.jsxs("div",{className:`break-all text-xs ${F.ok?"text-og-800":"text-accent"}`,children:[F.ok?"✓ ":"⨯ ",F.message]})]})]})]})}const an="baxian.taskNotifications.enabled";function on(){if(typeof window>"u")return null;const e=window.Notification;return typeof e=="function"?e:null}function ht(){const e=on();return e?e.permission:"unsupported"}function Ft(){try{return localStorage.getItem(an)!=="0"}catch{return!0}}function ft(e){try{localStorage.setItem(an,e?"1":"0")}catch{}}const gs=o.createContext(null);function ma({children:e}){const[n,s]=o.useState(ht),[r,a]=o.useState(Ft),[i,l]=o.useState(!1),c=o.useRef(!1),m=o.useRef(0);o.useEffect(()=>{const g=()=>{s(ht()),c.current||a(Ft())},u=d=>{if(d.key!==null&&d.key!==an)return;s(ht());const x=d.key===null?Ft():d.newValue!=="0";x||(m.current+=1),a(x)};return window.addEventListener("focus",g),window.addEventListener("storage",u),()=>{window.removeEventListener("focus",g),window.removeEventListener("storage",u)}},[]);const h=o.useCallback(()=>{a(!0);const g=on();if(!g){ft(!0);return}if(g.permission!=="default"){s(g.permission),ft(!0);return}if(c.current)return;c.current=!0,l(!0);const u=m.current;g.requestPermission().then(s).catch(d=>{console.warn("[task-notifications] permission request failed:",d),s(ht())}).finally(()=>{m.current===u&&ft(!0),c.current=!1,l(!1)})},[]),p=o.useCallback(()=>{m.current+=1,a(!1),ft(!1)},[]);return t.jsx(gs.Provider,{value:{permission:n,preferenceEnabled:r,enabled:n==="granted"&&r,requesting:i,enable:h,disable:p},children:e})}function xs(){const e=o.useContext(gs);if(!e)throw new Error("useTaskNotifications must be used inside TaskNotificationsProvider");return e}const ha=[{value:"en-US",label:"English"},{value:"zh-CN",label:"简体中文"}];function fa({open:e,onClose:n}){const s=U(),{locale:r,saving:a,setLocale:i}=Xn(),{show:l}=je(),c=async m=>{try{await i(m)}catch(h){const p=h instanceof Error?h.message:String(h);l({kind:"error",title:s.settings.languageSaveFailed(p)})}};return t.jsx(Le,{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:ce,children:s.settings.language}),t.jsx("div",{className:"flex gap-4",children:ha.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:Ie,checked:r===m.value,disabled:a,onChange:()=>void c(m.value)}),m.label]},m.value))})]}),t.jsx(pa,{})]})})}function pa(){const e=U(),{permission:n,enabled:s,requesting:r,enable:a,disable:i}=xs();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:Ie,checked:s,disabled:l||r,onChange:()=>s?i():a()}),e.settings.taskNotifications]}),t.jsx("p",{className:He,children:l?e.settings.taskNotificationsDenied:e.settings.taskNotificationsHint})]})}const bs="topbar-actions";function Cn(){return typeof document>"u"?null:document.getElementById(bs)}function vs({children:e}){const[n,s]=o.useState(Cn);return o.useEffect(()=>{n||s(Cn())},[n]),n?Ws.createPortal(e,n):null}function ga(){return is("/api/realtime")}class xa{constructor(n={}){ie(this,"wsUrl");ie(this,"wsFactory");ie(this,"tokenProvider");ie(this,"ws",null);ie(this,"topics",new Map);ie(this,"cache",new Map);ie(this,"outbox",[]);ie(this,"reconnectScheduler");ie(this,"explicitlyClosed",!1);this.wsUrl=n.wsUrl??ga(),this.wsFactory=n.wsFactory??os,this.tokenProvider=n.tokenProvider??Yt,this.reconnectScheduler=new ss({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.${as(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=i=>{r===this.ws&&(this.ws=null,!this.explicitlyClosed&&(rs(i,n,this.tokenProvider())||(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 Ot=null;function tt(){return Ot||(Ot=new xa),Ot}function ln(){const[e,n]=o.useState(null),[s,r]=o.useState(!1),[a,i]=o.useState(null);return o.useEffect(()=>tt().subscribe("agents",c=>{i(null),n(c),r(!0)},c=>i(c)),[]),{data:e,loaded:s,error:a}}function ys(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),tt().subscribe(`task:${e}`,m=>{l(null),s(m),a(!0)},m=>l(m))),[e]),{data:n,loaded:r,error:i}}function ws(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 p=tt().subscribe(`project-tasks:${e}`,g=>{c||(m=!0,l(null),s(g),a(!0))},g=>{c||(l(g),!(m||h)&&(h=!0,_.tasks.list(e).then(u=>{c||m||(s(u),a(!0))},u=>{console.warn(`[useProjectTasks] REST fallback failed for ${e}:`,u)})))});return()=>{c=!0,p()}},[e]),{data:n,loaded:r,error:i}}let vt=null,Be=null,yt=null,Qe=0;const Wt=new Set;function ks(){Wt.forEach(e=>e())}async function ba(){const e=Qe;try{const n=await _.projects.list();if(e!==Qe)return;vt=n,yt=null}catch(n){if(e!==Qe)return;yt=n instanceof Error?n.message:String(n)}finally{e===Qe&&(Be=null,ks())}}function zt(){return Be||(Be=ba(),Be)}function va(){Qe+=1,vt=null,Be=null,yt=null,ks()}typeof window<"u"&&window.addEventListener(Ye,va);async function ya(){const e=Be!==null;await zt(),e&&await zt()}function nt(){const[,e]=o.useState(0);return o.useEffect(()=>{const n=()=>e(s=>s+1);return Wt.add(n),vt===null&&!Be&&zt(),()=>{Wt.delete(n)}},[]),{projects:vt,error:yt,refresh:ya}}function wa(){const e=U(),n=Pe(),{projects:s,error:r,refresh:a}=nt(),i=s??[],l=s!==null,[c,m]=o.useState(!1),[h,p]=o.useState(!1),[g,u]=o.useState(!1),[d,x]=o.useState(!1),[b,y]=o.useState({kind:"closed"}),{data:S,loaded:A,error:R}=ln(),w=(R==null?void 0:R.message)??null,k=new Map((S??[]).map($=>[$.id,$])),T=r??w,v=i.length===0,L=t.jsx("button",{type:"button",onClick:()=>p(!0),disabled:v,"aria-describedby":v?"create-task-hint":void 0,className:"btn-ghost",children:e.dashboard.newTask});return t.jsxs("div",{children:[t.jsxs(vs,{children:[v?t.jsx("span",{className:"inline-flex",title:e.dashboard.createProjectFirst,children:L}):L,v&&t.jsx("span",{id:"create-task-hint",className:"sr-only",children:e.dashboard.createProjectFirst}),t.jsx(jt,{ariaLabel:e.dashboard.moreActions,children:$=>t.jsxs(t.Fragment,{children:[t.jsx(ke,{onClick:()=>{$(),m(!0)},children:e.dashboard.newProject}),t.jsx(ke,{onClick:()=>{$(),u(!0)},children:e.dashboard.manageHosts}),t.jsx(ke,{onClick:()=>{$(),x(!0)},children:e.settings.entry})]})})]}),t.jsx("h1",{className:"sr-only",children:"Dashboard"}),T&&t.jsx("div",{className:"mb-4 text-sm text-accent",children:e.common.loadFailed(T)}),l&&i.length===0&&!r&&t.jsx("div",{className:"rounded-lg border border-hairline bg-surface py-12 text-center text-sm text-og-500",children:e.dashboard.emptyProjects}),i.map($=>t.jsx(ka,{project:$,agentsById:k,agentsLoaded:A,agentsError:!!R,onAgentDeleted:a},$.id)),t.jsx(sa,{open:c,onClose:()=>m(!1),onCreated:$=>{m(!1),a(),y({kind:"asking",projectId:$})}}),t.jsx(ua,{open:g,onClose:()=>u(!1)}),t.jsx(Le,{open:b.kind==="asking",onClose:()=>y({kind:"closed"}),title:e.dashboard.projectCreatedTitle,size:"sm",footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:()=>y({kind:"closed"}),className:"btn-secondary",children:e.dashboard.later}),t.jsx("button",{type:"button",onClick:()=>{b.kind==="asking"&&y({kind:"addingAgent",projectId:b.projectId})},className:"btn-primary",children:e.dashboard.continueAddingAgent})]}),children:t.jsx("p",{className:"text-sm text-og-700",children:e.dashboard.addAgentNowOrLater})}),b.kind==="addingAgent"&&t.jsx(ps,{open:!0,projectId:b.projectId,onClose:()=>y({kind:"closed"}),onCreated:()=>{a()}}),t.jsx(rn,{open:h,onClose:()=>p(!1),onCreated:$=>n(De($.projectId,$.id))}),t.jsx(fa,{open:d,onClose:()=>x(!1)})]})}function ka({project:e,agentsById:n,agentsLoaded:s,agentsError:r,onAgentDeleted:a}){const i=U(),{data:l,error:c}=ws(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(Ae,{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(Ae,{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((p,g)=>t.jsx(fs,{team:p,projectId:e.id,agentsById:n,agentsLoaded:s,agentsError:r,tasks:m,onDeleted:a,terminalMode:"embedded-full"},p.map(u=>u.id).join(":")||g))})]})}const js="baxian.taskPanel.doneOpen";function ja(){try{return localStorage.getItem(js)==="1"}catch{return!1}}function wt(e){const n=e.match(/^task-(\d+)$/);return n?parseInt(n[1],10):Number.NaN}function Ta(e,n){const s=wt(e.id),r=wt(n.id);return Number.isNaN(s)||Number.isNaN(r)?e.id.localeCompare(n.id):s-r}function Na(e,n){const s=(n.updatedAt??"").localeCompare(e.updatedAt??"");if(s!==0)return s;const r=wt(e.id),a=wt(n.id);return Number.isNaN(r)||Number.isNaN(a)?n.id.localeCompare(e.id):a-r}function An(e,n){const[s,r]=o.useState(At);o.useEffect(()=>r(At),[n]);const a=e.slice(0,s),i=e.length>a.length;return{items:a,hasMore:i,loadMore:()=>r(c=>c+At),total:e.length}}function Sa(e){const[n,s]=o.useState([]),[r,a]=o.useState(!1),[i,l]=o.useState(!1),[c,m]=o.useState(!1),[h,p]=o.useState(null),g=o.useRef(0),u=o.useRef(0),d=o.useCallback(x=>{const b=++g.current,y=x==="first"?0:u.current;l(!0),p(null),_.tasks.page(e,{category:"done",offset:y}).then(S=>{g.current===b&&(s(A=>x==="first"?S.tasks:[...A,...S.tasks]),a(S.hasMore),u.current=S.nextOffset,m(!0),l(!1))},S=>{g.current===b&&(p(S instanceof Error?S.message:String(S)),l(!1))})},[e]);return o.useEffect(()=>{g.current+=1,u.current=0,s([]),a(!1),m(!1),p(null),l(!1)},[e]),{items:n,hasMore:r,loading:i,loaded:c,error:h,load:d}}function Ra({projectId:e,openTasks:n,className:s=""}){const r=U(),a=o.useMemo(()=>n.filter(u=>Kt.has(u.status)).sort(Na),[n]),i=o.useMemo(()=>n.filter(u=>u.status==="pending").sort(Ta),[n]),l=An(a,e),c=An(i,e),m=Sa(e),[h,p]=o.useState(ja);o.useEffect(()=>{try{localStorage.setItem(js,h?"1":"0")}catch{}},[h]),o.useEffect(()=>{h&&m.load("first")},[h,m.load]);const g=()=>p(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(Dn,{title:r.taskPanel.inProgressTitle,section:l,emptyHint:r.taskPanel.emptyInProgress}),t.jsx(Dn,{title:r.taskPanel.pendingTitle,section:c,emptyHint:r.taskPanel.emptyPending}),t.jsxs("div",{children:[t.jsxs("button",{type:"button",onClick:g,"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(Ca,{state:m})]})]})})}function Dn({title:e,section:n,emptyHint:s}){const r=U();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(Ts,{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 Ca({state:e}){const n=U(),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(Ts,{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 Ts({task:e}){const n=U(),s=Pe(),{show:r}=je(),[a,i]=o.useState(!1),l=Me(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?ds(n,e.attention,e.status):null,p=()=>s(De(e.projectId,e.id)),g=async()=>{if(c||e.postApproveRevoked||e.status==="review"&&On(e)){p();return}i(!0);try{await _.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:p,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:sn(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(nn,{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:p,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:tn(e.attention,e.status).map(u=>t.jsx("button",{type:"button",disabled:u==="advance"&&a,onClick:()=>u==="advance"?void g():p(),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",{open:h.expandDetails,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,`
13
+ `,e.attention.runbook]})]})]})]})}const Aa=[],Ns="baxian.taskPanel.open";function Da(){try{return localStorage.getItem(Ns)!=="0"}catch{return!0}}function Pa(){const{id:e}=kt(),n=Pe(),s=U(),{show:r}=je(),{refresh:a}=nt(),[i,l]=o.useState(null),[c,m]=o.useState(null),[h,p]=o.useState(!1),[g,u]=o.useState(!1),d=o.useRef(null),[x,b]=o.useState(Da),[y,S]=o.useState(!1),[A,R]=o.useState(""),[w,k]=o.useState(!1),[T,v]=o.useState(null),L=o.useRef(0),{data:$,loaded:H,error:F}=ln(),{data:Q,error:P}=ws(e),G=(F==null?void 0:F.message)??null,te=(P==null?void 0:P.message)??null,V=Q??Aa,Y=new Map(($??[]).map(q=>[q.id,q])),W=c??G??te,se=o.useCallback(async q=>{const he=++L.current;try{const de=await _.projects.get(q);if(he!==L.current)return;l(de),m(null)}catch(de){if(he!==L.current)return;m(de instanceof Error?de.message:String(de))}},[]);o.useEffect(()=>{e&&(l(null),m(null),se(e))},[e,se]),o.useEffect(()=>{y||(R(""),v(null))},[y]),o.useEffect(()=>{try{localStorage.setItem(Ns,x?"1":"0")}catch{}},[x]);const J=(i==null?void 0:i.agent.flat().length)??0,X=J===0,oe=!!i&&A.trim()===i.id,ge=async()=>{if(!(!i||!oe||w)){k(!0),v(null);try{await _.projects.delete(i.id),await a(),r({kind:"success",title:s.projectPage.deletedToastTitle(i.id)}),S(!1),n("/")}catch(q){v(q instanceof Error?q.message:String(q))}finally{k(!1)}}};return i?t.jsxs("div",{children:[t.jsxs(vs,{children:[t.jsx("button",{type:"button",onClick:()=>u(!0),className:"btn-ghost",children:s.projectPage.newTaskButton}),t.jsx(jt,{ariaLabel:s.projectPage.menuAriaLabel(i.id),menuClassName:"min-w-[180px]",triggerRef:d,children:q=>t.jsxs(t.Fragment,{children:[!x&&t.jsx(ke,{onClick:()=>{q(),b(!0)},children:s.projectPage.showTaskPanel}),t.jsx(ke,{onClick:()=>{q(),p(!0)},children:s.projectPage.addAgent}),t.jsx("div",{role:"none",className:"my-1 border-t border-hairline"}),t.jsx(ke,{onClick:()=>{q(),S(!0)},disabled:!X,title:X?void 0:s.projectPage.deleteAgentsFirstHint(J),children:s.projectPage.deleteProjectMenuItem})]})})]}),W&&t.jsx("div",{className:"mb-4 text-sm text-accent",children:s.common.loadFailed(W)}),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((q,he)=>t.jsx(fs,{team:q,projectId:i.id,agentsById:Y,agentsLoaded:H,agentsError:!!F,tasks:V,onDeleted:()=>{se(i.id)},terminalMode:"embedded-full"},q.map(de=>de.id).join(":")||he))})]}),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 q;b(!1),(q=d.current)==null||q.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(Ra,{projectId:i.id,openTasks:V})]})]}),t.jsx(ps,{open:h,projectId:i.id,onClose:()=>p(!1),onCreated:()=>{se(i.id)}}),t.jsx(rn,{open:g,projectId:i.id,onClose:()=>u(!1),onCreated:q=>n(De(q.projectId,q.id))}),t.jsx(Le,{open:y,onClose:()=>{w||S(!1)},title:s.projectPage.deleteModalTitle,size:"sm",footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:()=>S(!1),disabled:w,className:"btn-secondary",children:s.common.cancel}),t.jsx("button",{type:"button",onClick:()=>void ge(),disabled:!oe||w,className:"btn-primary",children:w?s.common.deleting:s.projectPage.confirmDeleteButton})]}),children:t.jsxs("div",{className:"space-y-4",children:[t.jsxs("p",{className:"text-sm text-og-700",children:[s.projectPage.deleteBodyLead,t.jsx("code",{className:"font-mono text-og-1000",children:"baxian.json"}),s.projectPage.deleteBodyMid,t.jsx("span",{className:"font-mono text-og-1000",children:i.id}),s.projectPage.deleteBodySuffix]}),t.jsxs("p",{className:"text-sm text-og-700",children:[s.projectPage.confirmInputLead,t.jsx("span",{className:"font-mono text-og-1000",children:i.id}),s.projectPage.confirmInputSuffix]}),t.jsx("input",{type:"text",value:A,onChange:q=>R(q.target.value),placeholder:i.id,autoComplete:"off",autoCorrect:"off",spellCheck:!1,disabled:w,"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"}),T&&t.jsx("div",{className:"rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-xs text-accent",children:T})]})})]}):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 Ss={approve:"pill pill-live","request-changes":"pill pill-warn",comment:"pill"};function Rs(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 Ze(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 St(e){if(e.id)return e.sourceKey!==void 0?`pr-${e.kind}.${e.sourceKey}.${e.id}`:`pr-${e.kind}-${e.id}`}function Cs(e,n){return e.review?`round-${Ze(e.review,n)}`:`round-in-progress-${e.items[0]?Ze(e.items[0],n):n}`}function As(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 La=4e3,Ea=6e4;function Ds(e,n){const[s,r]=o.useState(null),[a,i]=o.useState(!1),[l,c]=o.useState(null),[m,h]=o.useState(!1),[p,g]=o.useState(null),[u,d]=o.useState(0),x=o.useRef(e),b=o.useRef(n),y=o.useRef(0),S=o.useRef(0),A=o.useRef(void 0),R=o.useRef(0),w=o.useRef(null);o.useEffect(()=>{const T=()=>{w.current!==null&&(w.current=null,h(!1),g(null))};x.current!==e&&(x.current=e,r(null),i(!1),g(null),S.current=0,T()),b.current!==n&&(b.current=n,S.current=0,T());const v=++y.current;return c(null),_.tasks.prReview(e).then(L=>{if(y.current===v)if(r(L),i(!0),L.available&&L.error&&S.current<3){S.current+=1;const $=L.rateLimited?Ea*2**(S.current-1):La*S.current;A.current=setTimeout(()=>d(H=>H+1),$)}else L.error||(S.current=0)}).catch(L=>{y.current===v&&(c(L instanceof Error?L.message:String(L)),r(null),i(!0))}),()=>{clearTimeout(A.current),A.current=void 0}},[e,n,u]);const k=o.useCallback(()=>{if(w.current!==null)return;const T=++R.current;w.current=T,h(!0),g(null),_.tasks.prReviewRefresh(x.current).then(v=>{if(w.current===T){if(v.available&&(v.error!==void 0||v.rateLimited===!0)){g(v.error??"rate limited");return}clearTimeout(A.current),A.current=void 0,y.current+=1,S.current=0,r(v),i(!0),c(null)}}).catch(v=>{w.current===T&&g(v instanceof Error?v.message:String(v))}).finally(()=>{w.current===T&&(w.current=null,h(!1))})},[]);return{data:s,loaded:a,error:l,refresh:k,refreshing:m,refreshError:p}}function $a(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 Ps({data:e,onRefresh:n,refreshing:s,refreshError:r}){const a=U(),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 g=Date.now()-m.current;c(Math.ceil((i-g%i)/1e3))};h();const p=setInterval(h,1e3);return()=>clearInterval(p)},[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($a(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 Ia({role:e,label:n,summary:s,badge:r,onClick:a}){const i=U();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 Ba(e){return{"no-pr":e.prReview.reasonNoPr,"driver-unavailable":e.prReview.reasonDriverUnavailable}}function Ma(e){return(e==null?void 0:e.trim().split(`
14
+ `,1)[0])??""}function Fa(e){if(!(e.kind!=="review-comment"||!e.path))return e.line!==void 0?`${e.path}:${e.line}`:e.path}function Oa(e,n){return n.bodyTruncated?e.prReview.truncatedSuffix:""}function _a(e,n){const s=Ma(n.body),r=Oa(e,n);if(n.kind==="review-comment"){const a=Fa(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 Ha(e,n){return n.verdict!==void 0||n.kind==="review"?e.review.reviewTurnLabel:n.kind==="review-comment"?n.inReplyTo?e.review.responseTurnLabel:e.prReview.inlineComment:e.prReview.comment}function qa(e){return e.verdict!==void 0?"qa":e.kind==="issue-comment"||e.inReplyTo?"dev":"qa"}function Ua({task:e}){const n=U(),s=Pe(),r=As(e),{data:a,loaded:i,error:l,refresh:c,refreshing:m,refreshError:h}=Ds(e.id,r),p=Me(e.phase)?n.prReview.specReviewHeading:n.prReview.codeReviewHeading;function g(x){s(`/tasks/${encodeURIComponent(e.id)}/pr-review${x?`#${x}`:""}`)}if(l)return t.jsx(Ve,{title:p,children:t.jsx("div",{className:"text-sm text-accent",children:n.review.loadFailed(l)})});if(!i)return t.jsx(Ve,{title:p,children:t.jsx("div",{className:"text-sm text-og-400",children:n.review.loadingRecords})});if(!(a!=null&&a.available)){const x=Ba(n);return t.jsx(Ve,{title:p,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(Ps,{data:a,onRefresh:c,refreshing:m,refreshError:h});if(a.items.length===0)return t.jsxs(Ve,{title:p,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=Rs(a.items);return t.jsxs(Ve,{title:p,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,b)=>t.jsx(Ga,{round:x,index:b,onOpen:g},Cs(x,String(b))))]})}function Ve({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 Ga({round:e,index:n,onOpen:s}){const r=U(),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(Pn,{item:i,onOpen:s},Ze(i,`${n}-${l}`))),e.review&&t.jsx(Pn,{item:e.review,onOpen:s})]})]})}function Pn({item:e,onOpen:n}){const s=U(),r=e.verdict,a=r?t.jsx("span",{className:Ss[r],children:r}):e.kind==="review"&&e.reviewState?t.jsx("span",{className:"pill",children:e.reviewState}):void 0;return t.jsx(Ia,{role:qa(e),label:Ha(s,e),badge:a,summary:_a(s,e),onClick:()=>n(St(e))})}function Wa({task:e}){const n=U();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(Ua,{task:e})]})}const za=qn;function Va(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 Ln(e){if(!/^[1-9]\d*$/.test(e.trim()))return;const n=Number(e);return Number.isSafeInteger(n)?n:void 0}function Ka(e){return e.status==="review"&&!Me(e.phase)}function pt({children:e,open:n}){const s=U();return t.jsxs("details",{open:n,className:"mt-2 text-xs text-og-500",children:[t.jsx("summary",{className:"cursor-pointer select-none text-accent",children:s.common.technicalDetails}),t.jsx("div",{className:"mt-1 whitespace-pre-wrap break-words font-mono",children:e})]})}function Qa(){const{taskId:e=""}=kt();return t.jsx(Ya,{taskId:e},e)}function Ya({taskId:e}){var un;const n=Pe(),s=U(),{show:r}=je(),a=en(),[i,l]=o.useState(!1),[c,m]=o.useState(!1),[h,p]=o.useState(!1),[g,u]=o.useState(!1),[d,x]=o.useState(!1),[b,y]=o.useState("spec"),[S,A]=o.useState(""),[R,w]=o.useState(!1),[k,T]=o.useState(!1),[v,L]=o.useState(!1),[$,H]=o.useState(""),[F,Q]=o.useState(!1),[P,G]=o.useState(""),[te,V]=o.useState(!1),[Y,W]=o.useState(null),{data:se,loaded:J,error:X}=ys(e),{projects:oe,error:ge}=nt(),{data:q,loaded:he,error:de}=ln(),{activeAgentId:fe,activateAgentCard:ye}=hs(),j=Y??se,xe=j!==null&&Ka(j),be=xe&&(te||((un=j==null?void 0:j.attention)==null?void 0:un.recommendedActions.includes("verdict"))===!0),D=(X==null?void 0:X.message)??null,N=j?oe==null?void 0:oe.find(f=>f.id===j.projectId):void 0,O=N===void 0?"unknown":N.merge==="auto"?"auto":"manual",B=oe===null&&ge===null,ue=o.useMemo(()=>new Map((q??[]).map(f=>[f.id,f])),[q]);o.useEffect(()=>{Y&&se&&se.updatedAt>=Y.updatedAt&&W(null)},[Y,se]),o.useEffect(()=>{V(!1)},[j==null?void 0:j.status,j==null?void 0:j.reviewRound]);const re=f=>{W(f)},I=f=>({body:s.taskDetail.actionFailedBody,details:f instanceof Error?f.message:String(f)}),C=(f,M)=>{const K=M??(f.status==="review"?"qa":"dev");return f.status==="pending"?f.preferredAgentId===""?s.taskDetail.editTask:s.taskDetail.startTask:K==="qa"&&f.status!=="review"?s.taskDetail.startReview:f.status==="review"?s.taskDetail.restartReview:f.status==="approved"?s.taskDetail.retryPreMergeCheck:s.taskDetail.retryCurrentStep},E=()=>B?s.taskDetail.loadingMergeSetting:O==="auto"?s.taskDetail.confirmAndMerge:O==="manual"?s.taskDetail.confirmComplete:s.taskDetail.confirmResult,Z=async()=>{if(!j)return;const f=qn.has(j.status);if(await a({title:s.taskDetail.cancelConfirmTitle(j.id),body:f?s.taskDetail.cancelConfirmBodyTerminal:s.taskDetail.cancelConfirmBodyActive,confirmLabel:s.taskDetail.cancelConfirmLabel,cancelLabel:s.common.backText})){m(!0);try{const K=await _.tasks.update(j.id,{status:"cancelled"});re(K),r({kind:"success",title:K.status==="cancelled"?s.taskDetail.cancelledToastTitle:s.taskDetail.cancelCleanupToastTitle})}catch(K){r({kind:"error",title:s.taskDetail.cancelFailedTitle,...I(K)})}finally{m(!1)}}},z=async(f,M,K)=>{u(!0);try{const le=await _.tasks.advance(f.id,{executor:M,...f.status==="pending"&&f.preferredAgentId?{agentId:f.preferredAgentId}:{},...K??{}});re(le),x(!1),r({kind:"success",title:s.taskDetail.advanceSucceededTitle})}catch(le){r({kind:"error",title:s.taskDetail.advanceFailedTitle,...I(le)})}finally{u(!1)}},ee=async f=>{var ve;if(!j)return;if(j.status==="pending"&&j.preferredAgentId===""){l(!0);return}const M=f??(j.status==="review"?"qa":"dev"),K=C(j,M);if(M==="qa"&&On(j)){y(j.phase??"spec"),A(((ve=j.prNumber)==null?void 0:ve.toString())??""),x(!0);return}if(j.postApproveRevoked){if(!await a({title:s.taskDetail.advanceRevokedConfirmTitle,body:j.postApproveRevoked.reason==="request-changes"?s.taskDetail.advanceRevokedRequestChangesBody:s.taskDetail.advanceRevokedRetryLimitBody,confirmLabel:K}))return;await z(j,M,{confirmRevoked:!0});return}await a({title:s.taskDetail.advanceConfirmTitle(K),body:j.status==="pending"?s.taskDetail.startTaskConfirmBody(j.id,j.preferredAgentId):M==="qa"&&j.status==="review"?s.taskDetail.restartReviewConfirmBody(j.id):M==="qa"?s.taskDetail.startReviewConfirmBody(j.id):j.status==="approved"?s.taskDetail.retryPreMergeConfirmBody:s.taskDetail.retryCurrentStepConfirmBody(j.id),confirmLabel:K})&&await z(j,M)},we=async()=>{if(!(!j||!await a({title:s.taskDetail.retryConfirmTitle(j.id),body:j.status==="merged"?s.taskDetail.retryConfirmBodyMerged:s.taskDetail.retryConfirmBodyDefault,confirmLabel:s.taskDetail.retryTask}))){p(!0);try{const M=await _.tasks.retry(j.id);r({kind:"success",title:s.taskDetail.retryCreatedToastTitle(M.id)}),n(De(M.projectId,M.id))}catch(M){r({kind:"error",title:s.taskDetail.retryFailedTitle,...I(M)})}finally{p(!1)}}},Ee=async()=>{if(j&&await a({title:s.taskDetail.markCompleteConfirmTitle,body:s.taskDetail.markCompleteConfirmBody(j.prNumber??0),confirmLabel:s.taskDetail.verdictComplete})){w(!0);try{const f=await _.tasks.verdict(j.id,{action:"complete"});re(f),r({kind:"success",title:s.taskDetail.markCompleteToastTitle})}catch(f){r({kind:"error",title:s.taskDetail.markCompleteFailedTitle,...I(f)})}finally{w(!1)}}},Fe=async()=>{if(j&&await a({title:s.taskDetail.continueConfirmTitle,body:s.taskDetail.continueConfirmBody(j.reviewRound+1),confirmLabel:s.taskDetail.verdictContinue})){T(!0);try{const f=await _.tasks.verdict(j.id,{action:"continue"});re(f),r({kind:"success",title:s.taskDetail.continuedToastTitle(f.reviewRound)})}catch(f){r({kind:"error",title:s.taskDetail.continueFailedTitle,...I(f)})}finally{T(!1)}}},Te=async(f,M)=>{if(j){L(!0);try{const K=await _.tasks.verdict(j.id,{action:f.verdict,...f.comments!==void 0?{comments:f.comments}:{}});re(K),H(""),r({kind:"success",title:M.success})}catch(K){r({kind:"error",title:M.failure,...I(K)})}finally{L(!1)}}},Ne=async()=>{j&&await a({title:s.taskDetail.specApproveConfirmTitle,body:s.taskDetail.specApproveConfirmBody(j.id),confirmLabel:s.taskDetail.specApprove})&&await Te({verdict:"approve"},{success:s.taskDetail.specApprovedToastTitle,failure:s.taskDetail.specApproveFailedTitle})},ae=async()=>{const f=$.trim();f&&await Te({verdict:"request-changes",comments:f},{success:s.taskDetail.specRejectedToastTitle,failure:s.taskDetail.specRejectFailedTitle})},$e=async f=>{if(!j)return;const M=P.trim();if(!(f==="request-changes"&&!M||!await a({title:f==="pass"?s.taskDetail.codePassConfirmTitle:s.taskDetail.codeRejectConfirmTitle,body:s.taskDetail.codeVerdictConfirmBody,confirmLabel:f==="pass"?s.taskDetail.codePass:s.taskDetail.codeRequestChanges}))){Q(!0);try{const le=await _.tasks.verdict(j.id,{action:f,...M?{comments:M}:{}});re(le),G(""),r({kind:"success",title:s.taskDetail.codeVerdictSubmittedTitle})}catch(le){r({kind:"error",title:s.taskDetail.codeVerdictFailedTitle,...I(le)})}finally{Q(!1)}}},Bs=()=>{var f;(f=document.getElementById("task-verdict-controls"))==null||f.scrollIntoView({behavior:"smooth",block:"center"})},Ms=async()=>{if(!j||B)return;const f=j.prNumber??0,M=O==="auto"?s.taskDetail.confirmAutoMergeTitle(f):O==="manual"?s.taskDetail.confirmManualCompleteTitle:s.taskDetail.confirmResultTitle,K=O==="auto"?s.taskDetail.confirmAutoMergeBody(f):O==="manual"?s.taskDetail.confirmManualCompleteBody(f):s.taskDetail.confirmResultBody;if(await a({title:M,body:K,confirmLabel:E()})){w(!0);try{const le=await _.tasks.verdict(j.id,{action:"confirm-merge"});re(le),r({kind:"success",title:le.status==="merged"?s.taskDetail.confirmedMergedToastTitle:s.taskDetail.confirmedCompleteToastTitle})}catch(le){r({kind:"error",title:s.taskDetail.confirmFailedTitle,...I(le)})}finally{w(!1)}}};return t.jsxs("div",{children:[t.jsx("button",{type:"button",onClick:()=>n(-1),className:"btn-ghost mb-3",children:s.common.back}),D&&!j&&t.jsx("div",{className:"text-sm text-accent",children:s.common.loadFailed(D)}),J&&!j&&!D&&t.jsx("div",{className:"text-sm text-accent",children:s.taskDetail.taskNotFound(e)}),!j&&!D&&!J&&t.jsx("div",{className:"text-sm text-og-500",children:s.common.loading}),j&&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:j.id}),t.jsx("span",{className:"min-w-0 truncate font-display text-sm font-semibold tracking-tight text-og-1000",title:j.title,children:j.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:Fs(j)}),t.jsx("aside",{className:"min-w-0 space-y-4",children:Hs(j)})]})]}),i&&j&&t.jsx(rn,{mode:"edit",open:!0,onClose:()=>l(!1),task:j,onUpdated:re}),d&&j&&t.jsx(Le,{open:!0,title:s.taskDetail.reviewRecoveryTitle,onClose:()=>{g||x(!1)},size:"sm",dismissOnBackdrop:!g,footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",disabled:g,onClick:()=>x(!1),className:"btn-secondary",children:s.common.cancel}),t.jsx("button",{type:"submit",form:"review-recovery-form",disabled:g||j.prNumber===void 0&&Ln(S)===void 0,className:"btn-primary",children:g?s.taskDetail.advancing:s.taskDetail.reviewRecoverySubmit})]}),children:t.jsxs("form",{id:"review-recovery-form",className:"space-y-4",onSubmit:f=>{f.preventDefault();const M=j.prNumber??Ln(S);M===void 0||g||z(j,"qa",{stage:b,...j.prNumber===void 0?{prNumber:M}:{}})},children:[t.jsx("p",{className:"text-sm text-og-700",children:s.taskDetail.reviewRecoveryBody}),j.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:S,required:!0,disabled:g,onChange:f=>A(f.target.value),placeholder:s.taskDetail.reviewRecoveryPrNumberPlaceholder,className:me})]}),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:b,required:!0,disabled:g||j.phase!==void 0,onChange:f=>y(f.target.value),className:me,children:[t.jsx("option",{value:"spec",children:s.taskDetail.reviewRecoveryStageSpec}),t.jsx("option",{value:"code",children:s.taskDetail.reviewRecoveryStageCode})]})]})]})})]});function Fs(f){var at;const M=f.preferredAgentId==="",K=f.status==="approved"&&f.prNumber!==void 0,le=f.status==="merge-ready"&&f.prNumber!==void 0,ve=f.status==="spec-ready",Se=be,Rt=f.status==="max_rounds"&&!Me(f.phase),st=f.status==="max_rounds"&&Me(f.phase),Re=Un(f.prUrl),rt=Va(Re??void 0,f.branch??""),Oe=f.attention?ds(s,f.attention,f.status):null,Ct=(q??[]).some(it=>Fn(it,f.id));return t.jsxs("div",{children:[D&&t.jsx("div",{className:"mb-4 text-sm text-accent",children:s.common.loadFailed(D)}),f.branchCleanupPending&&t.jsxs("div",{className:"mb-4 rounded-md border border-accent/25 bg-accent-soft/60 px-3 py-2.5 text-xs text-accent",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.branchCleanupPendingTitle}),t.jsx("div",{className:"mt-1 text-og-700",children:s.taskDetail.branchCleanupPendingBody}),t.jsx(pt,{children:f.branchCleanupPending.reason})]}),f.branchCleanupSkipped&&t.jsxs("div",{className:"mb-4 rounded-md border border-hairline bg-og-25 px-3 py-2.5 text-xs text-og-700",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.branchCleanupSkippedTitle}),t.jsx("div",{className:"mt-1",children:s.taskDetail.branchCleanupSkippedBody}),t.jsx(pt,{children:f.branchCleanupSkipped.reason})]}),M&&t.jsx("div",{className:"mb-4 rounded-md border border-accent/25 bg-accent-soft/60 px-3 py-2.5 text-xs text-accent",children:f.status==="pending"?s.taskDetail.unassignedPendingNotice:s.taskDetail.unassignedReadonlyNotice}),t.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-3",children:[t.jsx(nn,{task:f,className:"text-sm"}),Ct&&t.jsx("span",{className:"text-sm text-og-500",title:s.taskDetail.dispatchingHint,children:s.taskDetail.dispatching}),(f.specReviewRound??0)>0&&t.jsx("span",{className:"text-sm text-og-500",children:s.taskDetail.specReviewRound(f.specReviewRound??0)}),f.reviewRound>0&&t.jsx("span",{className:"text-sm text-og-500",children:s.taskDetail.codeReviewRound(f.reviewRound)})]}),t.jsx("div",{className:"mb-4 flex flex-wrap items-center gap-2",children:qs(f)}),t.jsxs("div",{className:"mb-4 text-sm text-og-500",children:[s.taskDetail.createdAtPrefix,Et(f.createdAt,!1),s.taskDetail.updatedAtPrefix,Et(f.updatedAt,!1),f.origin&&t.jsxs(t.Fragment,{children:[s.taskDetail.originPrefix,t.jsx(Ae,{to:De(f.projectId,f.origin.taskId),className:"underline hover:text-og-700",children:f.origin.taskId})]})]}),f.attention&&Oe&&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:Oe.title}),t.jsx("div",{className:"mt-1 text-og-700",children:Oe.guidance}),t.jsx("div",{className:"mt-1 text-xs text-og-500",children:Et(f.attention.occurredAt)}),t.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:_s(f)}),t.jsx(pt,{open:Oe.expandDetails,children:`${f.attention.reason}
15
+ ${f.attention.runbook}`})]}),K&&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}),Re&&t.jsx("a",{href:Re,target:"_blank",rel:"noopener noreferrer",className:"btn-secondary mt-3",children:s.taskDetail.viewPr(f.prNumber??0)})]}),le&&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:O==="auto"?s.taskDetail.mergeReadyAutoBody(f.prNumber??0):O==="manual"?s.taskDetail.mergeReadyManualBody(f.prNumber??0):B?s.taskDetail.mergeReadyLoadingBody:s.taskDetail.mergeReadyUnknownBody}),O==="unknown"&&ge&&t.jsx(pt,{children:ge}),Re&&t.jsx("a",{href:Re,target:"_blank",rel:"noopener noreferrer",className:"btn-secondary mt-3",children:s.taskDetail.viewPr(f.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(f.specReviewRound??0)}),cn()]}),Se&&t.jsxs("div",{id:"task-verdict-controls",className:`mb-4 rounded-lg p-4 text-sm ${((at=f.attention)==null?void 0:at.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}),Os()]}),Rt&&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(f.reviewRound)}),t.jsx("div",{className:"mt-1 text-og-700",children:s.taskDetail.codeMaxRoundsBody})]}),st&&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(f.specReviewRound??0)}),t.jsx("div",{className:"mt-1 text-og-700",children:s.taskDetail.specMaxRoundsBody}),cn()]}),t.jsxs("div",{className:"card mb-4 flex flex-wrap items-center gap-x-6 gap-y-1 p-4 text-sm",children:[t.jsxs("span",{className:"text-og-500",children:["PR:"," ",f.prNumber?Re?t.jsxs("a",{href:Re,target:"_blank",rel:"noopener noreferrer",className:"text-accent hover:text-accent-hover",children:["#",f.prNumber]}):t.jsxs("span",{className:"font-mono text-og-800",children:["#",f.prNumber]}):t.jsx("span",{className:"text-og-400",children:"—"})]}),t.jsxs("span",{className:"text-og-500",children:["Branch:"," ",f.branch?rt?t.jsx("a",{href:rt,target:"_blank",rel:"noopener noreferrer",className:"font-mono text-accent hover:text-accent-hover",children:f.branch}):t.jsx("span",{className:"font-mono text-og-800",children:f.branch}):t.jsx("span",{className:"text-og-400",children:"—"})]})]}),t.jsx("pre",{className:"card mb-4 whitespace-pre-wrap p-4 text-sm text-og-800",children:f.description||t.jsx("span",{className:"text-og-400",children:s.taskDetail.noDescription})}),t.jsx(Wa,{task:f})]})}function cn(){return t.jsxs("div",{className:"mt-3 flex flex-col gap-2",children:[t.jsx("textarea",{value:$,onChange:f=>H(f.target.value),placeholder:s.taskDetail.specCommentsPlaceholder,rows:3,disabled:v,className:me}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",disabled:v,onClick:Ne,className:"btn-primary",children:v?s.taskDetail.submitting:s.taskDetail.specApproveButton}),t.jsx("button",{type:"button",disabled:v||$.trim()==="",onClick:ae,title:$.trim()===""?s.taskDetail.specRejectTitleEmpty:s.taskDetail.specRejectTitleReady,className:"btn-secondary",children:v?s.taskDetail.submitting:s.taskDetail.specReject})]})]})}function Os(){return t.jsxs("div",{className:"mt-3 flex flex-col gap-2",children:[t.jsx("textarea",{value:P,onChange:f=>G(f.target.value),placeholder:s.taskDetail.codeCommentsPlaceholder,rows:3,disabled:F,className:me}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",disabled:F,onClick:()=>void $e("pass"),className:"btn-secondary",children:F?s.taskDetail.submitting:s.taskDetail.codePass}),t.jsx("button",{type:"button",disabled:F||P.trim()==="",onClick:()=>void $e("request-changes"),className:"btn-secondary",children:F?s.taskDetail.submitting:s.taskDetail.codeRequestChanges})]})]})}function _s(f){return f.attention?tn(f.attention,f.status).map(M=>M==="advance"?t.jsx("button",{type:"button",disabled:g,onClick:()=>void ee(),className:"btn-primary",children:g?s.taskDetail.advancing:C(f)},M):M==="verdict"?t.jsx("button",{type:"button",onClick:Bs,className:"btn-primary",children:s.taskDetail.handleReview},M):M==="cancel"?t.jsx("button",{type:"button",disabled:c,onClick:Z,className:"btn-secondary",children:c?s.taskDetail.cancelling:s.taskDetail.cancelConfirmLabel},M):t.jsx("button",{type:"button",disabled:h,onClick:we,className:"btn-secondary",children:h?s.common.retrying:s.taskDetail.retryTask},M)):null}function Hs(f){if(oe===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 M=(N==null?void 0:N.agent.find(ve=>ve.some(Se=>Se.id===f.devAgentId)))??(f.qaAgentId?N==null?void 0:N.agent.find(ve=>ve.some(Se=>Se.id===f.qaAgentId)):void 0),K=M==null?void 0:M.find(ve=>ve.role==="dev"&&ve.id===f.devAgentId),le=f.qaAgentId?M==null?void 0:M.find(ve=>ve.role==="qa"&&ve.id===f.qaAgentId):void 0;return!K&&!le?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:[K?dn(f,K):t.jsx(En,{role:"dev"}),le?dn(f,le):t.jsx(En,{role:"qa"})]})}function dn(f,M){const K=ue.get(M.id),le=K??{id:M.id,projectId:f.projectId,runtimeStatus:"unknown",tmuxSessionStatus:"unknown",stale:!0};return t.jsx(ms,{agent:le,projectId:f.projectId,role:M.role,runtime:M.runtime,model:M.model,pendingRestart:he&&!K,terminalLoading:!he&&!K&&!de,showTaskBinding:!1,terminalMode:"embedded-full",active:fe===M.id,onActivate:()=>ye(M.id),task:f},M.id)}function qs(f){var it,mn;const K=f.status==="max_rounds"&&!Me(f.phase),le=f.status==="merge-ready",ve=f.status==="pending",Se=za.has(f.status),Rt=Se&&!!f.preferredAgentId,st=f.preferredAgentId==="",Re=["pending","in_progress","fixing","review","approved"].includes(f.status)&&((it=f.attention)==null?void 0:it.reason)!=="bootstrap-marker-clear-failed"&&(((mn=f.attention)==null?void 0:mn.reason)!=="dispatch-failed:ack_unknown"||f.status==="review")&&!(f.status==="pending"&&st),rt=(f.status==="in_progress"||f.status==="fixing")&&f.qaAgentId!==void 0,Oe=K&&f.prNumber!==void 0,Ct=Oe&&!!f.agentId,at=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:Z,title:s.taskDetail.cancelForceTitle,className:"btn-secondary",children:c?s.taskDetail.cancelling:s.taskDetail.cancelConfirmLabel}),Se&&f.replacementTaskId===void 0&&t.jsx("button",{type:"button",disabled:!Rt||h,onClick:we,title:st?s.taskDetail.retryDisabledUnassignedTitle:s.taskDetail.retryEnabledTitle,className:"btn-secondary",children:h?s.common.retrying:s.taskDetail.retryTask}),Re&&t.jsx("button",{type:"button",disabled:g,onClick:()=>void ee(),className:"btn-primary",children:g?s.taskDetail.advancing:C(f)}),rt&&t.jsx("button",{type:"button",disabled:g,onClick:()=>void ee("qa"),className:"btn-secondary",children:C(f,"qa")}),at&&t.jsx("button",{type:"button",onClick:()=>V(!0),className:"btn-secondary",children:s.taskDetail.handleReview}),K&&t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",disabled:!Ct||k,onClick:Fe,title:s.taskDetail.continueButtonTitle,className:"btn-secondary",children:k?s.taskDetail.continuing:s.taskDetail.verdictContinue}),t.jsx("button",{type:"button",disabled:!Oe||R,onClick:Ee,title:s.taskDetail.completeButtonTitle,className:"btn-primary",children:R?s.taskDetail.completing:s.taskDetail.verdictComplete})]}),le&&t.jsx("button",{type:"button",disabled:R||B,onClick:Ms,title:B?s.taskDetail.confirmLoadingTitle:s.taskDetail.confirmButtonTitle,className:"btn-primary",children:R?s.taskDetail.confirming:E()})]})}}function En({role:e}){const n=U();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 Ja(){const{agentId:e}=kt(),{projects:n}=nt(),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",{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:Hn(e,s),children:e})]}),t.jsx("div",{className:"min-h-0 flex-1",children:t.jsx(Ke,{agentId:e,mode:"full",interactive:!0,arrowKeys:!0})})]}):t.jsx("div",{className:"text-sm text-accent",children:"No agent specified"})}const Xa=65536,Za=8e3,ei=["text-[18px] font-bold","text-[17px] font-bold","text-[16px] font-semibold","text-[15px] font-semibold","text-[15px] font-semibold","text-[15px] font-semibold"],ti=/^(https?:\/\/|mailto:)/i,ni=/^https?:\/\//i;function si(e){try{const n=new URL(e).hostname.toLowerCase();return n==="githubusercontent.com"||n.endsWith(".githubusercontent.com")}catch{return!1}}function ri({src:e,alt:n}){const s=U(),[r,a]=o.useState(!1);if(r||si(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 $n(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 ai(e){const n=/\s/g;let s=-1,r=-2;return a=>{if(r!==-2&&a>=s&&(r===-1||a<=r))return r;s=a,n.lastIndex=a;const i=n.exec(e);return r=i?i.index:-1,r}}function In(e,n,s){const r=n+1,a=s.bracket(r);if(a===-1||e[a+1]!=="(")return null;const i=a+2,l=s.paren(i);if(l===-1||l===i)return null;const c=s.whitespace(i);return c!==-1&&c<l?null:{label:e.slice(r,a),url:e.slice(i,l),end:l+1}}class Ls extends Error{}class ii{constructor(n){ie(this,"count",0);this.max=n}charge(){if(++this.count>this.max)throw new Ls}}function qe(e,n,s){const r=[];let a="",i=0;const l={bracket:$n(e,"]"),paren:$n(e,")"),whitespace:ai(e)},c=()=>{a!==""&&(n.charge(),r.push(a),a="")},m=p=>{c(),n.charge(),r.push(p)},h=()=>`${s}-${r.length}`;for(;i<e.length;){const p=e[i];if(p==="`"){const g=e.indexOf("`",i+1);if(g!==-1){const u=e.slice(i+1,g);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=g+1;continue}}else if(p==="!"&&e[i+1]==="["){const g=In(e,i+1,l);if(g){ni.test(g.url)?m(t.jsx(ri,{src:g.url,alt:g.label},h())):a+=e.slice(i,g.end),i=g.end;continue}}else if(p==="["){const g=In(e,i,l);if(g){if(ti.test(g.url)){c(),n.charge();const u=qe(g.label,n,`${s}-a${r.length}`);r.push(t.jsx("a",{href:g.url,target:"_blank",rel:"noopener noreferrer",className:"text-accent hover:text-accent-hover",children:u},h()))}else a+=e.slice(i,g.end);i=g.end;continue}}else if(p==="*"){if(e.startsWith("***",i)){const u=e.indexOf("***",i+3);if(u>i+3){c(),n.charge(),n.charge();const d=qe(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=qe(e.slice(i+2,u),n,`${s}-b${r.length}`);r.push(t.jsx("strong",{children:d},h())),i=u+2;continue}}const g=e.indexOf("*",i+1);if(g>i+1){c(),n.charge();const u=qe(e.slice(i+1,g),n,`${s}-i${r.length}`);r.push(t.jsx("em",{children:u},h())),i=g+1;continue}}a+=p,i++}return c(),r}function oi(e,n){const s=[],r=e.split(`
16
+ `);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(...qe(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 p=l+1;for(;p<r.length&&!/^```\s*$/.test(r[p]);)h.push(r[p]),p++;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(`
17
+ `)})},`pre-${s.length}`)),l=p;continue}const m=/^(#{1,6}) (.*)$/.exec(c);if(m){i(),n.charge();const h=m[1].length,p=`h${h}`;s.push(t.jsx(p,{className:ei[h-1],children:qe(c,n,`h${s.length}`)},`h-${s.length}`));continue}if(c.trim()===""){i();continue}a.push(c)}return i(),s}function li(e){if(typeof e!="string")return[];if(e.length>Xa)return null;const n=new ii(Za);try{return n.charge(),oi(e.replace(/\r\n/g,`
18
+ `),n)}catch(s){if(s instanceof Ls)return null;throw s}}function ci({text:e}){const n=o.useMemo(()=>li(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 di={approve:"approve","request-changes":"request-changes",comment:"comment"};function ui(e){return e==="no-pr"||e==="driver-unavailable"?e:void 0}function mi(e){return{"no-pr":e.prReview.reasonNoPr,"driver-unavailable":e.prReview.reasonDriverUnavailable}}function Es(e){if(!e)return"";const n=e.match(/^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2})/);return n?`${n[1]} ${n[2]}`:e}function hi(){const e=U(),{taskId:n=""}=kt(),s=Pe(),{hash:r}=Mn(),{data:a}=ys(n),i=a?As(a):void 0,{data:l,loaded:c,error:m,refresh:h,refreshing:p,refreshError:g}=Ds(n,i),[u,d]=o.useState(null),x=(l==null?void 0:l.prNumber)??(a==null?void 0:a.prNumber),b=(l==null?void 0:l.prUrl)??(a==null?void 0:a.prUrl),y=Un(b),S=l?Rs(l.items):[],A=c&&!m&&(l==null?void 0:l.available)===!0&&l.items.length>0,R=Me(a==null?void 0:a.phase)?e.prReview.specReviewHeading:e.prReview.codeReviewHeading,w=o.useRef(null),k=o.useRef(void 0);return o.useEffect(()=>()=>clearTimeout(k.current),[]),o.useEffect(()=>{let T=null;if(r)try{T=decodeURIComponent(r.slice(1))}catch{T=null}if(!T){w.current=null,d(null);return}if(w.current===T||!A||!l)return;const v=document.getElementById(T);v&&(w.current=T,v.scrollIntoView({behavior:"smooth",block:"center"}),d(T),clearTimeout(k.current),k.current=setTimeout(()=>d(null),2e3))},[A,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}),y&&x!==void 0&&t.jsx("a",{href:y,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(Ps,{data:l,onRefresh:h,refreshing:p,refreshError:g})]}),!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:mi(e)[ui(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:S.map((T,v)=>t.jsx(fi,{round:T,index:v,flashId:u},Cs(T,String(v))))})]}))]})}function fi({round:e,index:n,flashId:s}){const r=U(),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(Bn,{item:i,flashId:s},Ze(i,`${n}-${l}`)):t.jsx(pi,{item:i,flashId:s},Ze(i,`${n}-${l}`))),e.review&&t.jsx(Bn,{item:e.review,flashId:s})]})]})}function $s(e,n){const s=St(e);return`card p-3 text-sm${s&&s===n?" ring-2 ring-accent":""}`}function pi({item:e,flashId:n}){const s=U(),r=e.kind==="review-comment";return t.jsxs("div",{id:St(e),className:$s(e,n),children:[t.jsxs("div",{className:"mb-1 flex flex-wrap items-center gap-2",children:[t.jsx("span",{className:"pill shrink-0",children:r?s.prReview.inlineComment:s.prReview.comment}),e.author?t.jsx("span",{className:"font-medium text-og-700",children:e.author}):t.jsx("span",{className:"text-xs italic text-og-400",children:s.prReview.ghostAuthor}),r&&e.path&&t.jsx("span",{className:"min-w-0 break-all font-mono text-xs text-og-500",children:e.line!==void 0?`${e.path}:${e.line}`:e.path}),e.inReplyTo&&t.jsx("span",{className:"text-xs text-og-400",children:s.prReview.replyIndicator}),e.createdAt&&t.jsx("span",{className:"text-xs text-og-400",children:Es(e.createdAt)})]}),t.jsx(Is,{item:e})]})}function Bn({item:e,flashId:n}){const s=U(),r=e.verdict??"comment";return t.jsxs("div",{id:St(e),className:$s(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:Ss[r],children:di[r]}),e.reviewState&&t.jsx("span",{className:"pill shrink-0",children:e.reviewState}),e.author?t.jsx("span",{className:"text-xs text-og-400",children:e.author}):t.jsx("span",{className:"text-xs italic text-og-400",children:s.prReview.ghostAuthor}),e.commitSha&&t.jsx("span",{className:"font-mono text-xs text-og-500",children:e.commitSha.slice(0,9)}),!e.commitSha&&e.anchorSha&&t.jsx("span",{className:"font-mono text-xs text-og-500",children:e.anchorSha.slice(0,9)}),e.createdAt&&t.jsx("span",{className:"text-xs text-og-400",children:Es(e.createdAt)})]}),t.jsx(Is,{item:e,placeholder:s.prReview.noReviewBody})]})}function Is({item:e,placeholder:n}){const s=U();return t.jsxs(t.Fragment,{children:[e.body?t.jsx("div",{className:"text-og-800",children:t.jsx(ci,{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 gi(){const e=U(),[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 xi(){const[e,n]=o.useState(null),[s,r]=o.useState(!1),[a,i]=o.useState(null);return o.useEffect(()=>tt().subscribe("pollers",c=>{i(null),n(c),r(!0)},c=>i(c)),[]),{data:e,loaded:s,error:a}}function bi(e){return e.lastErrorClass==="RATE_LIMIT"&&e.rateLimitedUntil!==void 0&&Date.parse(e.rateLimitedUntil)>Date.now()}function vi(e){const n=e.find(l=>l.lastErrorClass==="ACCESS_DENIED");if(n)return{poller:n,kind:"access-denied"};const s=e.find(l=>l.health==="failed"&&l.lastErrorClass==="NOT_FOUND");if(s)return{poller:s,kind:"not-found"};const r=e.find(l=>l.health==="failed");if(r)return{poller:r,kind:"failed"};const a=e.find(bi);if(a)return{poller:a,kind:"rate-limited"};const i=e.find(l=>l.health==="degraded");return i?{poller:i,kind:"degraded"}:null}function yi(){const e=U(),{data:n}=xi();if(!n)return null;const s=vi(n);if(!s)return null;const{poller:r,kind:a}=s,i=a==="access-denied"?e.banner.platformAccessDenied(r.repo,r.lastErrorMessage):a==="not-found"?e.banner.platformRepoNotFound(r.repo):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 wi(){const e=U(),{phase:n,count:s,error:r,triggerRestart:a}=Nt();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 ki=new Set(["done","merged"]);function _t(e,n){const s=e.trim().replace(/\s+/g," ");return s.length>n?`${s.slice(0,n-1)}…`:s}function ji(e,n){return e?e.repo?`${e.id} · ${e.repo}`:e.id:n}function Ti(e){return e.title?`${e.id} · ${e.title}`:e.id}function Ni(e){return ki.has(e)}function Si(e,n,s){const r=on();if(!(!r||r.permission!=="granted"))try{const a=Yn(),i=new r(a.notification.taskDone(_t(e.title||e.id,80)),{body:[a.notification.bodyProject(_t(n,120)),a.notification.bodyTask(_t(Ti(e),120)),a.notification.bodyStatus(Vr(e.status))].join(`
19
+ `),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 Ri(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),p=o.useRef(new Map),g=o.useMemo(()=>s?(e??[]).map(u=>u.id).sort().join("\0"):"",[s,e]);o.useEffect(()=>{h.current=n},[n]),o.useEffect(()=>{p.current=new Map((e??[]).map(u=>[u.id,ji(u,u.id)]))},[e]),o.useEffect(()=>{const u=y=>{m.current.set(y,(m.current.get(y)??0)+1)};if(g===""){for(const y of c.current)u(y);c.current=new Set,r.current.clear(),i.current.clear(),l.current.clear();return}const d=g.split("\0"),x=new Set(d);for(const y of c.current)x.has(y)||u(y);c.current=x;for(const y of r.current.keys())x.has(y)||r.current.delete(y);for(const y of i.current.keys())x.has(y)||i.current.delete(y);const b=d.map(y=>tt().subscribe(`project-tasks:${y}`,S=>{const A=r.current.get(y),R=new Map(S.map(k=>[k.id,k]));r.current.set(y,R);const w=i.current.get(y)??new Set;if(i.current.set(y,w),!A){for(const k of R.keys())w.delete(k);return}for(const[k]of A)R.has(k)||a.current.has(k)||w.add(k);for(const k of[...w]){if(R.has(k)){w.delete(k);continue}const T=m.current.get(y)??0,v=`${y}:${T}:${k}`;l.current.has(v)||(l.current.add(v),_.tasks.get(k).then(L=>{if((m.current.get(y)??0)!==T)return;if(!L||L.projectId!==y||!Ni(L.status)){w.delete(k);return}w.delete(k),a.current.add(L.id);const $=p.current.get(y)??y;Si(L,$,()=>h.current(L))}).catch(L=>{console.warn(`[task-notifications] failed to confirm completed task ${k}:`,L)}).finally(()=>{l.current.delete(v)}))}},S=>{console.warn(`[task-notifications] project task stream failed for ${y}:`,S)}));return()=>{for(const y of b)y()}},[g])}function Ci(){const e=Mn(),n=Pe(),{projects:s}=nt(),{enabled:r}=xs(),a=!e.pathname.startsWith("/terminal/");return hr(),Ri(s,i=>n(De(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(Ae,{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:bs,className:"ml-auto flex min-w-0 items-center justify-end gap-2"})]}),t.jsx(wi,{}),t.jsx(yi,{}),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(Xs,{children:[t.jsx(ze,{path:"/",element:t.jsx(wa,{})}),t.jsx(ze,{path:"/project/:id",element:t.jsx(Pa,{})}),t.jsx(ze,{path:"/project/:id/task/:taskId",element:t.jsx(Qa,{})}),t.jsx(ze,{path:"/terminal/:agentId",element:t.jsx(Ja,{})}),t.jsx(ze,{path:"/tasks/:taskId/pr-review",element:t.jsx(hi,{})})]}),a&&t.jsx("footer",{className:"mt-auto flex justify-center pb-4 pt-24",children:t.jsx(gi,{})})]})]})}function Ai(){return t.jsx(Js,{children:t.jsx(ma,{children:t.jsx(Ci,{})})})}function Di({children:e}){const n=U(),[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 _.config.get();qt(c.language),r({kind:"authorized"})}catch(c){if(c instanceof Je&&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(Ye,c),()=>window.removeEventListener(Ye,c)},[]),s.kind==="authorized")return t.jsx(t.Fragment,{children:e});if(s.kind==="error")return t.jsxs(Vt,{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(Vt,{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(Pi,{message:l,onSubmit:async c=>{tr(c);try{const m=await _.config.get();qt(m.language),r({kind:"authorized"})}catch(m){if(nr(),m instanceof Je&&m.status===401){r({kind:"unauthorized",reason:"invalid"});return}r({kind:"error",message:m instanceof Error?m.message:void 0,fallback:"loginFailed"})}}})}function Vt({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 Pi({message:e,onSubmit:n}){const s=U(),[r,a]=o.useState(""),[i,l]=o.useState(!1),[c,m]=o.useState(void 0),h=async g=>{g.preventDefault();const u=r.trim();if(!u){m(s.auth.tokenRequired);return}m(void 0),l(!0);try{await n(u)}finally{l(!1)}},p=c??e;return t.jsxs(Vt,{title:s.auth.loginTitle,children:[t.jsx("p",{className:"mb-4 text-sm text-og-600",children:s.auth.loginDescription}),t.jsxs("form",{onSubmit:g=>{h(g)},children:[t.jsx("label",{className:ce,htmlFor:"baxian-token",children:s.auth.tokenLabel}),t.jsx("input",{id:"baxian-token",type:"password",autoComplete:"current-password",autoFocus:!0,value:r,onChange:g=>a(g.target.value),className:`${me} font-mono`,placeholder:s.auth.tokenPlaceholder,disabled:i}),p&&t.jsx("p",{role:"alert",className:"mt-2 text-xs text-accent",children:p}),t.jsx("button",{type:"submit",disabled:i,className:"btn-primary mt-4 w-full",children:i?s.auth.submitting:s.auth.submit})]})]})}zs.createRoot(document.getElementById("root")).render(t.jsx(o.StrictMode,{children:t.jsx(mr,{children:t.jsx(Tr,{children:t.jsx(xr,{children:t.jsx(vr,{children:t.jsx(Di,{children:t.jsx(Ai,{})})})})})})}));