baxian 1.2.47 → 1.2.49

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.
@@ -0,0 +1,11 @@
1
+ var fs=Object.defineProperty;var ps=(e,n,s)=>n in e?fs(e,n,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[n]=s;var se=(e,n,s)=>ps(e,typeof n!="symbol"?n+"":n,s);import{r as o,j as t,a as gs,c as xs}from"./react-BFCkCmbU.js";import{x as bs,a as vs}from"./xterm-D5X2JljJ.js";import{L as $e,u as be,a as We,b as Nn,B as ws,R as ys,c as De}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 xe({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 Et({ariaLabel:e,children:n,placement:s="down",autoFocusFirstItem:r=!1,menuClassName:a="min-w-[140px]",className:i,disabled:l=!1,triggerRef:d}){const[m,f]=o.useState(!1),p=o.useRef(null),u=o.useRef(null),h=o.useId(),x=o.useId();return o.useEffect(()=>{if(!m)return;const g=w=>{var P,k;const C=w.target;C&&((P=u.current)!=null&&P.contains(C)||(k=p.current)!=null&&k.contains(C)||f(!1))},y=w=>{var C;w.key==="Escape"&&(f(!1),(C=p.current)==null||C.focus())};return document.addEventListener("mousedown",g),document.addEventListener("keydown",y),()=>{document.removeEventListener("mousedown",g),document.removeEventListener("keydown",y)}},[m]),o.useEffect(()=>{var y;if(!m||!r)return;const g=(y=u.current)==null?void 0:y.querySelector('[role="menuitem"]:not([disabled])');g==null||g.focus()},[m,r]),t.jsxs("div",{className:`relative ${i??""}`,children:[t.jsx("button",{ref:g=>{p.current=g,d&&(d.current=g)},id:x,type:"button",onClick:()=>f(g=>!g),disabled:l,"aria-haspopup":"menu","aria-expanded":m,"aria-controls":m?h: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:u,id:h,role:"menu","aria-labelledby":x,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 g;f(!1),(g=p.current)==null||g.focus()})})]})}const js={"claude-code":"Claude Code",codex:"Codex"};function Tn(e){return e?js[e]:null}function Rn(e,n){const s=Tn(n);return s?`${e} (${s})`:e}const Cn=new Set(["merged","done","failed","cancelled"]),An=new Set(["in_progress","review","fixing","spec-ready","approved","merge-ready","ready","max_rounds"]),ut=20,lt=5*1024*1024,ze=4,Pn=600*1e3,ks=1536,Ss=1872,En=192,Ln=208,Fe="/api",Lt="baxian.token",et="baxian:unauthorized";function Dt(){try{return typeof localStorage<"u"?localStorage.getItem(Lt):null}catch{return null}}function Ns(e){try{localStorage.setItem(Lt,e)}catch(n){console.error("Failed to save auth token to localStorage",n)}}function Ts(){try{localStorage.removeItem(Lt)}catch(e){console.error("Failed to clear auth token from localStorage",e)}}function Ae(e){const n=Dt();return{...e??{},...n?{Authorization:`Bearer ${n}`}:{}}}class Be extends Error{constructor(n,s,r){super(s),this.status=n,this.details=r,this.name="ApiError"}}async function Pe(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),Array.isArray(a.details)&&(r=a.details)}catch{}throw e.status===401&&typeof window<"u"&&window.dispatchEvent(new CustomEvent(et)),new Be(e.status,s,r)}async function ge(e){const n=await fetch(`${Fe}${e}`,{headers:Ae()});return n.ok||await Pe(n),n.json()}async function Rs(){const e=await fetch("/health");return e.ok||await Pe(e),e.json()}async function ae(e,n,s){const r=n!==void 0,a=await fetch(`${Fe}${e}`,{method:"POST",headers:r?Ae({"Content-Type":"application/json"}):Ae(),body:r?JSON.stringify(n):void 0,signal:s==null?void 0:s.signal});return a.ok||await Pe(a),a.json()}async function mt(e,n,s){const r=await fetch(`${Fe}${e}`,{method:"PATCH",headers:Ae({"Content-Type":"application/json"}),body:n?JSON.stringify(n):void 0,signal:s==null?void 0:s.signal});if(r.ok||await Pe(r),r.status===204)return;const a=await r.text();if(a)return JSON.parse(a)}async function Cs(e,n){const s=await fetch(`${Fe}${e}`,{method:"PUT",headers:Ae({"Content-Type":"application/json"}),body:JSON.stringify(n??null)});if(s.ok||await Pe(s),s.status===204)return;const r=await s.text();if(r)return JSON.parse(r)}async function Me(e){const n=await fetch(`${Fe}${e}`,{method:"DELETE",headers:Ae()});if(n.ok||await Pe(n),n.status===204)return;const s=await n.text();if(s)return JSON.parse(s)}const Q=encodeURIComponent;function kt(e){return new Promise((n,s)=>{const r=new FileReader;r.onerror=()=>s(r.error??new Error("file read failed")),r.onload=()=>{const a=r.result;if(typeof a!="string"){s(new Error("unexpected FileReader result"));return}const i=a.indexOf(",");n(i>=0?a.slice(i+1):a)},r.readAsDataURL(e)})}const D={agents:{list:()=>ge("/agents"),get:e=>ge(`/agents/${Q(e)}`),stop:e=>Me(`/agents/${Q(e)}/session`),compact:e=>ae(`/agents/${Q(e)}/compact`),clear:e=>ae(`/agents/${Q(e)}/clear`),probe:(e,n={},s)=>ae("/agents/probe",{mode:e,host:n.host,hostId:n.hostId},s),installTmux:(e,n={})=>ae("/agents/install-tmux",{mode:e,host:n.host,hostId:n.hostId}),uploadImage:async(e,n)=>ae(`/agents/${Q(e)}/images`,{dataBase64:await kt(n)}),setPet:(e,n)=>Cs(`/agents/${Q(e)}/pet`,{petId:n})},pets:{list:()=>ge("/pets"),create:async(e,n)=>ae("/pets",{petJson:e,spritesheetBase64:await kt(n)}),remove:e=>Me(`/pets/${Q(e)}`),fetchSpritesheet:async e=>{const n=await fetch(`${Fe}/pets/${Q(e)}/spritesheet`,{headers:Ae()});return n.ok||await Pe(n),n.blob()}},tasks:{list:async e=>{const n=new Map;for(const s of["active","pending"]){let r=0;for(;;){const a=await D.tasks.page(e,{category:s,offset:r});for(const i of a.tasks)n.set(i.id,i);if(!a.hasMore||a.tasks.length===0)break;r=a.nextOffset}}return[...n.values()]},page:(e,n={})=>{const s=[`projectId=${Q(e)}`];return n.category&&s.push(`category=${n.category}`),s.push(`offset=${n.offset??0}`),ge(`/tasks?${s.join("&")}`)},get:e=>ge(`/tasks/${Q(e)}`),create:e=>ae("/tasks",e),update:(e,n)=>mt(`/tasks/${Q(e)}`,n),retry:e=>ae(`/tasks/${Q(e)}/retry`),review:e=>ae(`/tasks/${Q(e)}/review`),complete:e=>ae(`/tasks/${Q(e)}/complete`),continue:e=>ae(`/tasks/${Q(e)}/continue`),spec:(e,n)=>ae(`/tasks/${Q(e)}/spec`,n),reviews:e=>ge(`/tasks/${Q(e)}/reviews`),githubReview:e=>ge(`/tasks/${Q(e)}/github-review`),dispatch:(e,n)=>ae(`/tasks/${Q(e)}/dispatch`,n)},projects:{list:()=>ge("/projects"),get:e=>ge(`/projects/${Q(e)}`),create:e=>ae("/projects",e),delete:e=>Me(`/projects/${Q(e)}`),addAgent:(e,n)=>ae(`/projects/${Q(e)}/agents`,n),deleteAgent:(e,n)=>Me(`/projects/${Q(e)}/agents/${Q(n)}`),resumeAgent:(e,n)=>ae(`/projects/${Q(e)}/agents/${Q(n)}/resume`),restartRepl:(e,n)=>ae(`/projects/${Q(e)}/agents/${Q(n)}/restart-repl`),retryAgent:(e,n)=>ae(`/projects/${Q(e)}/agents/${Q(n)}/retry`),bootstrap:e=>ae(`/projects/${Q(e)}/bootstrap`)},hosts:{list:()=>ge("/hosts"),create:e=>ae("/hosts",e),update:(e,n)=>mt(`/hosts/${Q(e)}`,n),delete:e=>Me(`/hosts/${Q(e)}`),check:e=>ae("/hosts/check",e)},config:{get:()=>ge("/config"),patch:e=>mt("/config",e)},health:{get:Rs},server:{restart:()=>ae("/restart")}};function $t(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 As(e){return t.jsxs("svg",{...$t(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 Ps(e){return t.jsxs("svg",{...$t(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 Es(e){return t.jsxs("svg",{...$t(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 Dn={common:{cancel:"Cancel",confirm:"Confirm",close:"Close",delete:"Delete",deleting:"Deleting…",edit:"Edit",retry:"Retry",retrying:"Retrying…",back:"← Back",backText:"Back",loading:"Loading…",loadFailed:e=>`Failed to load: ${e}`,idFormatError:"Must start with a lowercase letter; only a-z, 0-9, and - allowed; length 2–32",create:"Create",creating:"Creating…",save:"Save",saving:"Saving…",oneClickInstall:"Install with one click",installing:"Installing…",installingTmuxNotice:"Installing tmux — this can take a few minutes, please keep this window open…"},status:{pending:"Pending",in_progress:"In progress",review:"In review",fixing:"Fixing","spec-ready":"Spec ready",approved:"Approved","merge-ready":"Awaiting confirm",ready:"Awaiting confirm",merged:"Merged",done:"Done",failed:"Failed",max_rounds:"Max rounds reached",cancelled:"Cancelled"},notification:{taskDone:e=>`Task completed: ${e}`,bodyProject:e=>`Project: ${e}`,bodyTask:e=>`Task: ${e}`,bodyStatus:e=>`Status: ${e}`},dashboard:{moreActions:"More actions",newProject:"New project",manageHosts:"Manage hosts",newTask:"+ New task",createProjectFirst:"Create a project first",emptyProjects:'No projects yet. Open the top-right menu and choose "New project" to start.',noAgentsYet:"No agents yet. Open Details to add one.",detailsLink:"Details →",detailsAriaLabel:e=>`Details — ${e}`,tasksLoadFailed:e=>`Failed to load tasks: ${e}`,projectCreatedTitle:"Project created",addAgentNowOrLater:"Add the first agent now, or later?",later:"Later",continueAddingAgent:"Continue adding an agent"},nav:{toggleToIcon:"Switch to logo icon",toggleToText:"Switch to logo text"},agents:{runtimeStatus:{unknown:"Unknown",idle:"Idle",pending:"Awaiting human",working:"Working",waiting:"Waiting",error:"Error"},sessionStatus:{absent:"No session",unreachable:"Host unreachable",unknown:"Session status unknown",starting:"Session starting"},bootstrappingBadge:"Starting",agentStatusLoading:"Agent status loading",bootstrappingTerminalDisabled:"Agent is starting",bootstrappingNotice:"Agent is starting; the terminal will refresh automatically once it is available.",terminalNeedsRestart:"Available after restarting the baxian server",pendingRestartNotice:"Takes effect after restarting the baxian server",heldBadge:"Held",heldDefaultReason:"Needs human attention",staleBadge:"Stale",awaitingHumanIntervention:"Awaiting human intervention",openTerminalPrefix:"Open the ",openTerminalSuffix:" to resolve it.",terminal:"Terminal",needInputBadge:"Awaiting reply",needInputTitle:e=>`Agent is waiting for your reply (${e})`,needInputNoticeTitle:"Agent is waiting for your reply",needInputPrefix:"It has a question — open the ",needInputSuffix:" to reply.",activateTerminal:e=>`Activate ${e} terminal`,actionsMenu:e=>`Agent ${e} actions menu`,taskLabel:"Task: ",stop:"Stop",stopping:"Stopping…",resume:"Resume",resuming:"Resuming…",resumeConfirmTitle:e=>`Resume agent ${e}?`,resumeGreetingBody:"The greeting capability check failed; baxian will re-run the handshake (restarts the REPL if the session is alive, or rebuilds it if lost). The hold only clears once the handshake passes.",resumeDefaultBody:"baxian will clear the awaiting_human state; the agent becomes usable again.",resumeGreetingButtonTitle:"Re-run the greeting handshake to resume (restarts the REPL if the session is alive, rebuilds it if lost; greeting_failed cannot be cleared by state alone).",resumeDefaultButtonTitle:"Clear the awaiting_human state so the agent becomes usable again.",regreetingStartedTitle:e=>`Agent ${e} is re-running the greeting handshake`,regreetingStartedBody:"Once the handshake passes, the hold clears automatically on the next refresh; if it keeps failing, fix the runtime per the hint and try again.",resumedTitle:e=>`Agent ${e} resumed`,resumedReleasedBody:"The previous task was released; the agent can take on new work.",resumedKeptBody:"The binding was kept (the previous task is still active).",resumeFailedTitle:"Resume failed",compact:"Compact context",compacting:"Compacting…",compactMenuItemTitle:"Send /compact to the agent runtime to compact context",compactSentTitle:e=>`/compact sent to agent ${e}`,compactFailedTitle:"Failed to compact context",clear:"Clear context",clearing:"Clearing…",clearMenuItemTitle:"Send /clear to the agent runtime to clear context",clearConfirmTitle:e=>`Clear the context for agent ${e}?`,clearConfirmBody:"This sends /clear; the entire session context cannot be recovered.",clearConfirmLabel:"Clear",clearSentTitle:e=>`/clear sent to agent ${e}`,clearFailedTitle:"Failed to clear context",deleteConfirmTitle:e=>`Delete agent ${e}?`,deleteConfirmBody:"This action cannot be undone.",deletedWithPairTitle:e=>`Deleted agent ${e}`,deletedWithPairBody:e=>`The paired QA agent ${e} was removed as well.`,deletedTitle:e=>`Agent ${e} deleted`,agentPetMenuItemTitle:"Configure Agent Pet (shows an animated pet in place of the status badge).",callReview:"Call review",callingReview:"Calling review…",callReviewMenuItemTitle:e=>`Have the QA agent run a review round on task ${e} right now (requires the task to already have a PR).`,confirmReReviewTitle:"Start a QA re-review?",confirmReReviewBody:e=>`QA agent will immediately start a new review round for task ${e} (reviewRound +1).`,confirmReReviewLabel:"Start re-review",reReviewStarted:e=>`QA re-review started (round ${e})`,reReviewStartFailed:"Failed to start review",retryBootstrap:"Retry bootstrap",retryBootstrapSucceededTitle:"Retry bootstrap succeeded",retryBootstrapSucceededBody:"Agent status will update on the next refresh.",retryBootstrapStillFailingTitle:"Retry bootstrap still failed",retryBootstrapStillFailingBody:"Check the latest reason on the red error card, fix it per the hint, and try again.",retryBootstrapFailedTitle:"Retry bootstrap failed",round:e=>`Round ${e}`,noActiveTask:"No active task",noActiveTaskAriaLabel:e=>`${e} no active task`,unassigned:"Unassigned",start:"Start",starting:"Starting…",startFailed:"Failed to start",taskHandedTo:(e,n)=>`Task ${e} handed to ${n}`,handToAndStart:e=>`Hand to ${e} and start immediately`,devAgentUnavailable:"Dev agent is currently unavailable"},settings:{entry:"Settings",title:"Settings",language:"Language",languageSaveFailed:e=>`Failed to save language: ${e}`,taskNotifications:"Task completion notifications",taskNotificationsDenied:"Notifications are blocked by the browser",taskNotificationsHint:"Notify via the browser when a task reaches done or merged"},auth:{checkingTitle:"Loading",checkingBody:"Checking sign-in status…",connectFailedTitle:"Cannot reach the server",connectFallback:"Cannot reach the server",loginTitle:"Sign in to baxian",loginDescription:"This server requires an access token to continue",loginFailed:"Sign-in failed",sessionExpired:"Session expired, please enter the token again",tokenInvalid:"Invalid token, please retry",tokenLabel:"Token",tokenPlaceholder:"Enter the token configured on the server",tokenRequired:"Please enter the access token",submit:"Sign in",submitting:"Signing in…"},createProject:{title:"New project",required:"Required",idLabel:"Project ID",idPlaceholder:"baxian",idTakenError:"This ID is already in use",repoLabel:"Git repository URL",repoFormatError:"Must be a Git URL (https / ssh / scp, e.g. https://gitlab.example.com/group/proj.git) or owner/repo",mergeStrategyLabel:"Merge strategy",mergeHumanLabel:"Human merge (default)",mergeAutoLabel:"Auto-merge after QA approval",specApprovalLabel:"Spec review",specApprovalHumanLabel:"Human review (default)",specApprovalAutoLabel:"Auto-start coding after QA approval",reviewModeLabel:"Review mode",reviewModeFollowGlobalLabel:"Follow global setting",createdToastTitle:e=>`Project ${e} created`},createAgent:{modalTitle:e=>`Add agent to ${e}`,submitLabel:"Add agent",submitting:"Adding…",idTakenGlobalError:"This ID is already in use (must be globally unique)",idPlaceholder:(e,n)=>`${e}-${n}`,roleLabel:"Role",createDevFirstHint:"Create a Dev agent first",pairWithLabel:"Paired Dev agent",pairWithPlaceholder:"Select one",pairOptionLabel:(e,n)=>`${e} (${n})`,modeLabel:"Run mode",localModeLabel:"Local",remoteModeLabel:"Remote (SSH)",noHostsHint:'No hosts configured yet. Add one from the "Manage hosts" menu in the top-right corner first.',selectHostPlaceholder:"Select a host",sshConfigHint:'Private keys and jump hosts can still be configured in ~/.ssh/config; port and password are set under "Manage hosts".',runtimeLabel:"Runtime",reprobeButton:"↻ Re-probe",selectHostFirstHint:"(select a host first)",probingLabel:"probing…",tmuxProbingLabel:"tmux: probing…",advancedOptionsLabel:"Advanced options",expandLabel:"Expand",collapseLabel:"Collapse",workdirLabel:"Workdir (optional)",workdirPlaceholder:"Leave blank to auto-clone into ~/.baxian/repos/<owner>/<repo>",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.:
2
+ /Users/me/shared-libs
3
+ /Users/me/extra-repo`,addDirsHint:"Passed through to --add-dir. It does not affect permission interception under the current YOLO mode; mainly used to bring extra directories into the CLI's working root.",yoloTitle:"YOLO mode (recommended)",yoloBodyLead:"Once enabled, Claude Code launches with ",yoloBodyMid:", and Codex launches with ",yoloBodyTrail:".",addedToastTitle:(e,n)=>`Agent ${e} added to ${n}`},createTask:{titleCreate:"New task",titleEdit:"Edit task",selectProjectPlaceholder:"Select a project",notAssignedOption:"Not assigned yet",pendingRestartSuffix:"(pending restart)",notInRuntimeSuffix:"(not in runtime)",titlePlaceholder:"One-sentence summary of what to do",descriptionLabel:"Description (optional)",descriptionPlaceholder:"Describe the task in detail; markdown is supported. Optional for simple tasks.",imagesLabel:"Images (optional)",addImagesButton:"Add images",removeImageAriaLabel:e=>`Remove image ${e}`,draftRestoredNotice:"Restored your last unsaved draft",discardDraftButton:"Discard",updatedToastTitle:"Task updated",createdToastTitle:"Task created",imageTooLargeToastTitle:"Image too large",imageTooLargeToastBody:(e,n)=>`${e} exceeds ${n} MiB`,tooManyImagesToastTitle:e=>`Maximum ${e} images`,noDevPendingRestartHint:e=>`Dev agent "${e}" exists in baxian.json but the runtime has not loaded it (config may have been edited by hand); restart the server to bring it up`,noDevNotInRuntimeHint:e=>`Dev agent "${e}" is not in the runtime (it may have been removed from the project config); saving may fail — confirm or choose a different Dev agent`,noDevGlobalPendingRestartHint:"baxian.json has Dev agents the runtime has not loaded (config may have been edited by hand); restart the server to apply"},hostMgmt:{title:"Manage hosts",emptyState:'No hosts configured yet. Click "Add host" below.',addHostButton:"+ Add host",passwordSavedIndicator:" · Password saved",addressLabel:"Host address",portLabel:"Port (optional)",portRangeError:"Port must be 1–65535",aliasLabel:"Alias (optional)",userLabel:"Username (optional)",userPlaceholder:"Leave blank to read the User from ~/.ssh/config",passwordLabel:"Password (optional)",passwordPlaceholderSet:"Already set; leave blank to keep it unchanged",passwordPlaceholderUnset:"Leave blank to use key-based auth",clearPasswordLabel:"Clear the saved password (switch to key-based login)",passwordHintLead:"We recommend setting up ",passwordHintStrong:"passwordless login (SSH key).",plaintextWarningLead:"Otherwise, the password you enter will be saved to baxian.json in ",plaintextWarningStrong:"plaintext",plaintextWarningTrail:".",testConnection:"Test connection",testing:"Testing…",createdToastTitle:e=>`Host ${e} added`,updatedToastTitle:e=>`Host ${e} updated`,deletedToastTitle:e=>`Host ${e} deleted`},projectPage:{newTaskButton:"+ New task",menuAriaLabel:e=>`Project ${e} actions menu`,showTaskPanel:"Show task panel",addAgent:"Add agent",deleteAgentsFirstHint:e=>`Delete the project's ${e} agent${e===1?"":"s"} first`,deleteProjectMenuItem:"Delete project…",noAgentsYet:"No agents yet. Use the menu in the top-right corner to add one.",closeTaskPanel:"Close task panel",deleteModalTitle:"Delete project",confirmDeleteButton:"Confirm delete",deleteBodyLead:"This updates ",deleteBodyMid:" to remove project ",deleteBodySuffix:". This action cannot be undone and will not delete the underlying Git repository.",confirmInputLead:"To confirm, enter the project ID below: ",confirmInputSuffix:"",confirmInputAriaLabel:"Enter the project ID to confirm deletion",deletedToastTitle:e=>`Project ${e} deleted`},taskDetail:{cancelConfirmTitle:e=>`Cancel task ${e}?`,cancelConfirmLabel:"Cancel task",cancelledToastTitle:"Task cancelled",cancelFailedTitle:"Failed to cancel",reReviewTerminalConfirmTitle:"Re-review a finished task?",reReviewTerminalConfirmBody:(e,n)=>`Task ${e} is already in status "${n}". Manually asking the QA agent to re-review runs another round, but the state machine will not feed the QA agent's result back into the main flow.`,retryConfirmTitle:e=>`Retry task ${e}?`,retryConfirmBodyMerged:"The task is merged. Retrying creates a new task from scratch with the same title/description.",retryConfirmBodyDefault:"This creates a new task from scratch; the old task is kept as history.",retryCreatedToastTitle:e=>`Created task ${e}`,retryFailedTitle:"Failed to retry",markCompleteConfirmTitle:"Mark complete and merge?",markCompleteConfirmBody:e=>`Merges PR #${e} and wraps up: deletes the local branch and compacts the agent's context.`,markComplete:"Mark complete",completing:"Completing…",markCompleteToastTitle:"Marked complete; wrapping up",markCompleteFailedTitle:"Failed to mark complete",continueConfirmTitle:"Continue another round?",continueConfirmBody:e=>`Has the Dev agent do another round of fixes (round ${e}); moves to QA review automatically once done.`,continueRound:"Continue another round",continuing:"Continuing…",continuedToastTitle:e=>`Continued to another round (round ${e})`,continueFailedTitle:"Failed to continue",specApproveConfirmTitle:"Approve Spec and start coding?",specApproveConfirmBody:e=>`Task ${e} will move into the coding phase.`,specApprove:"Approve Spec",specApprovedToastTitle:"Spec approved; coding started",specApproveFailedTitle:"Failed to approve Spec",specRejectedToastTitle:"Spec rejected; Dev agent is revising",specRejectFailedTitle:"Failed to reject Spec",confirmGateConfirmTitle:e=>`Confirm task ${e} is complete?`,confirmGateConfirmBody:"When project.merge is set to auto, baxian merges it automatically.",confirmComplete:"Confirm complete",confirmedToastTitle:e=>`Confirmed (${e})`,confirmFailedTitle:"Failed to confirm",taskNotFound:e=>`Task not found: ${e}`,legacyPendingNotice:'This task has no Dev agent assigned yet: click "Edit" to choose one, or click "Start" on any idle Dev agent card.',legacyReadonlyNotice:e=>`Legacy task with no Dev agent assigned. Current status: "${e}". Read-only.`,reviewRoundPrefix:"Review round ",reviewRoundSuffix:"",specRoundPrefix:"Spec round ",specRoundSuffix:"",createdAtPrefix:"Created ",updatedAtPrefix:" · Updated ",verdictOverdueTitle:"Review verdict overdue",verdictOverduePrefix:"QA agent claimed it at ",verdictOverdueSuffix:' with no verdict submitted after 10 minutes. Open the QA agent terminal to check, or click "Call review" to try again.',approvedBannerTitle:"QA agent approved · Confirming feedback",approvedBannerBody:"Dev agent is confirming all review feedback has been addressed; wraps up once done.",viewPr:e=>`View PR #${e}`,readyGateBannerTitle:"Review approved · Awaiting your confirmation",readyGateBannerBody:e=>`Server review approved — ${e} round${e===1?"":"s"} in total. Click "Confirm" to wrap up, or "Cancel" to discard.`,mergeReadyBannerTitle:"PR ready · Awaiting your confirmation",mergeReadyBannerBody:'Dev agent has finished its wrap-up self-check; click "Confirm" to let baxian finish up.',specReadyBannerTitle:"Spec requires human review",specReadyNotice:e=>`QA agent approved Spec round ${e} — see the full review below. Approving starts coding; comments from a rejection go to the Dev agent for revision and re-review.`,specCommentsPlaceholder:"Rejection comments (required when rejecting)",submitting:"Submitting…",specApproveButton:"Approve Spec and start coding",specRejectTitleEmpty:"Fill in rejection comments first",specRejectTitleReady:"Comments will be passed to the Dev agent as findings for revision",specReject:"Reject Spec",codeMaxRoundsTitle:e=>`Review round limit reached (round ${e})`,codeMaxRoundsBody:'You can click "Mark complete" to merge what you have, or "Continue another round" to keep revising. For anything left over, consider opening a new task — more rounds make the agent more likely to drift off-topic.',specMaxRoundsTitle:e=>`Spec review round limit reached (round ${e})`,specMaxRoundsBody:'No agreement was reached after multiple rounds; the task is paused. You can click "Retry" to start a new task from scratch, or "Cancel". We recommend reviewing the review history to find the disagreement and refining the description before retrying.',noDescription:"(No description)",noLinkedAgent:"No linked agent",cancelling:"Cancelling…",retryDisabledStatusTitle:e=>`Cannot retry in status "${e}"`,retryDisabledLegacyTitle:"Legacy task has no Dev agent assigned; cannot retry",retryEnabledTitle:"Creates a new task from scratch, discarding the current worktree/branch",reviewNoPrTitle:"This task has no PR yet; cannot start a review",reviewSpecMaxRoundsTitle:"Spec phase has reached its round limit; Call review is not supported",reviewButtonTitle:"Has the QA agent start a new review round right away (reviewRound +1)",continueButtonTitle:"Has the Dev agent do another round of fixes; moves to QA review automatically once done",completeButtonTitle:"Merges the PR and wraps up (deletes the local branch and compacts context)",confirmButtonTitle:"Confirms completion; when merge is set to auto, baxian performs the merge",confirming:"Confirming…",retryPublishButtonTitle:"Retries the push/PR steps after a failed publish",retryPublish:"Retry publish",noAgentSlot:e=>`No ${e} agent`,reviewSummaryPrefix:"Review rounds: ",reviewSummaryMid:" · Final verdict ",reviewSummaryFindingsPrefix:" · Findings: ",reviewSummaryFindingsSuffix:" total"},taskPanel:{ariaLabel:"Task panel",emptyInProgress:"No tasks in progress yet",emptyPending:"No pending tasks yet",collapse:"Collapse",view:"View",loadMore:"Load more",emptyDone:"No completed tasks yet"},review:{specDraft:"Spec draft",codeChanges:"Code changes",submitSpecDraft:"Submit Spec draft",submitCodeChanges:"Submit code changes",contentTruncated:"Content is large; showing a truncated excerpt.",noContent:"No content",qaReviewHeading:"QA review",notSubmitted:"Review not submitted yet.",noFindingsThisRound:"No findings this round.",devResponsesHeading:"Dev responses",roundNotFound:(e,n)=>`Review round not found (${e} round ${n}).`,loadFailed:e=>`Failed to load review records: ${e}`,loadingRecords:"Loading review records…",notStarted:"Review has not started",sectionTitle:"Review records",phaseLabel:{spec:"Spec review",code:"Code review"},diffLineCount:e=>`diff ${e} lines`,specDocLineCount:e=>`Spec draft ${e} lines`,findingsSummary:(e,n)=>`${e} findings${n?` (${n})`:""}`,responsesSummary:e=>`${e} responses`,reviewTurnLabel:"Review",responseTurnLabel:"Response",roleUser:"User",roleQa:"QA",roleDev:"Dev"},githubReview:{reasonServerMode:'This task uses server review mode; code review records are under "Review records" on the task detail page.',reasonServerModeEntry:"This task uses server review mode; code review records are in the server review rounds.",reasonNoPr:"This task has no PR yet; there are no code review records.",reasonNotGithub:"This task's repository is not a GitHub repository; PR review records cannot be fetched.",codeReviewHeading:"Code review",fetchFailed:e=>`Failed to fetch review records: ${e}`,partialFetchFailed:e=>`Some review records failed to fetch: ${e} (showing only what was retrieved).`,commitPill:"Commit",inlineComment:"Inline comment",comment:"Comment",replyIndicator:"↩ Reply",noReviewBody:"(No review body)",bodyTruncated:"Content is large; truncated.",truncatedSuffix:"(truncated)",noReviewBodyFallback:"No review body",commitFallback:"commit"},toast:{dismissAriaLabel:"Close notification"},banner:{restartFailed:e=>`Restart failed: ${e}`,restarting:"Restarting…",pendingNotice:e=>`${e} config change${e===1?"":"s"} pending — restart the baxian server to apply`,restartNow:"Restart now",preRestartFetchFailed:e=>`Failed to read startedAt before restart: ${e}`,restartTriggerFailed:e=>`Failed to trigger restart: ${e}`,restartTimeout:"Restart timed out (30s with no recovery). Check the logs, or run baxian start -c <path> manually."},terminal:{sessionEnded:"Session ended",keyPadAriaLabel:"Terminal keys",arrowAriaLabel:e=>`${e} arrow key`,arrowLabel:{up:"Up",down:"Down",left:"Left",right:"Right"},escKeyAriaLabel:"Esc key"},imageUpload:{tooLargeBody:e=>`A single image must not exceed ${e} MiB`,insertedTitle:"Image inserted",insertedBody:"Path pasted into the terminal input — add more detail, then press Enter",uploadFailedTitle:"Failed to upload image",uploadAriaLabel:"Upload image"},pet:{missingManifest:"pet.json not found in the file package",manifestParseFailed:"Failed to parse pet.json",missingSpritesheet:"Spritesheet (png/webp) not found in the file package",disabledTitle:"Agent Pet disabled",disableFailedTitle:"Failed to disable",selectedTitle:"Pet selected",selectFailedTitle:"Failed to select",deleteConfirmTitle:e=>`Delete Pet "${e}"?`,deleteConfirmBody:"Agents using it will fall back to the default status display.",deletedTitle:e=>`Pet "${e}" deleted`,deleteFailedTitle:"Failed to delete",uploadedTitle:"Pet uploaded",uploadFailedTitle:"Failed to upload pet",enableLabel:"Enable Agent Pet",enableHint:"Once enabled, you can upload a Codex Pet package, or pick a previously uploaded pet to replace the status display on the agent card.",uploadButton:"Upload Pet package",uploadInputAriaLabel:"Upload Codex Pet package",uploadDirHint:"Select a Codex Pet directory (containing pet.json and the spritesheet).",emptyState:"No pets uploaded yet — click the button above to upload one.",currentMarker:"(current)",deleteAriaLabel:e=>`Delete ${e}`}},Ls={common:{cancel:"取消",confirm:"确认",close:"关闭",delete:"删除",deleting:"删除中…",edit:"编辑",retry:"重试",retrying:"重试中…",back:"← 返回",backText:"返回",loading:"加载中…",loadFailed:e=>`加载失败:${e}`,idFormatError:"小写字母开头,只含 a-z 0-9 -,长度 2-32",create:"创建",creating:"创建中…",save:"保存",saving:"保存中…",oneClickInstall:"一键安装",installing:"安装中…",installingTmuxNotice:"正在安装 tmux,可能需要几分钟,请勿关闭窗口…"},status:{pending:"待处理",in_progress:"进行中",review:"评审中",fixing:"修订中","spec-ready":"Spec 待批",approved:"已通过","merge-ready":"待确认",ready:"待确认",merged:"已合并",done:"已完成",failed:"失败",max_rounds:"轮次达上限",cancelled:"已取消"},notification:{taskDone:e=>`任务完成:${e}`,bodyProject:e=>`项目:${e}`,bodyTask:e=>`任务:${e}`,bodyStatus:e=>`状态:${e}`},dashboard:{moreActions:"更多操作",newProject:"新建项目",manageHosts:"Host 管理",newTask:"+ 新建任务",createProjectFirst:"请先创建项目",emptyProjects:'还没有项目。点击右上角"更多"菜单 → "新建项目"开始。',noAgentsYet:"还没有 Agent。进入 Details 添加。",detailsLink:"详情 →",detailsAriaLabel:e=>`详情 — ${e}`,tasksLoadFailed:e=>`任务列表加载失败:${e}`,projectCreatedTitle:"项目已创建",addAgentNowOrLater:"现在添加第一个 Agent,还是稍后再加?",later:"稍后再加",continueAddingAgent:"继续添加 Agent"},nav:{toggleToIcon:"切换为 Logo 图标",toggleToText:"切换为 Logo 文字"},agents:{runtimeStatus:{unknown:"未知",idle:"空闲",pending:"待人工",working:"工作中",waiting:"等待中",error:"异常"},sessionStatus:{absent:"无会话",unreachable:"主机不可达",unknown:"会话状态未知",starting:"会话启动中"},bootstrappingBadge:"启动中",agentStatusLoading:"Agent 状态加载中",bootstrappingTerminalDisabled:"Agent 正在启动",bootstrappingNotice:"Agent 正在启动,终端可用后会自动刷新。",terminalNeedsRestart:"重启 baxian server 后可用",pendingRestartNotice:"重启 baxian server 后生效",heldBadge:"挂起",heldDefaultReason:"需人工处理",staleBadge:"失联",awaitingHumanIntervention:"等待人工介入",openTerminalPrefix:"请打开 ",openTerminalSuffix:" 处理。",terminal:"终端",needInputBadge:"等回答",needInputTitle:e=>`Agent 在等你的回答(${e})`,needInputNoticeTitle:"Agent 在等你的回答",needInputPrefix:"它提了一个问题,请打开 ",needInputSuffix:" 回复。",activateTerminal:e=>`激活 ${e} 终端`,actionsMenu:e=>`Agent ${e} 操作菜单`,taskLabel:"任务:",stop:"停止",stopping:"停止中…",resume:"恢复",resuming:"恢复中…",resumeConfirmTitle:e=>`恢复 Agent ${e}?`,resumeGreetingBody:"greeting 能力未通过,baxian 会重跑能力握手(会话存活则重启 REPL,已丢失则重建);握手通过才解除挂起。",resumeDefaultBody:"baxian 会清除 awaiting_human 状态,agent 恢复可用。",resumeGreetingButtonTitle:"重跑 greeting 能力握手以恢复(会话存活则重启 REPL,已丢失则重建;greeting_failed 无法靠清状态解除)",resumeDefaultButtonTitle:"清除 awaiting_human 状态,让 agent 恢复可用",regreetingStartedTitle:e=>`Agent ${e} 正在重跑能力握手`,regreetingStartedBody:"握手通过后 Held 会在下一次刷新自动解除,仍失败则按提示修复 runtime 后再试。",resumedTitle:e=>`Agent ${e} 已 Resume`,resumedReleasedBody:"原任务已释放,agent 可接新任务。",resumedKeptBody:"保留绑定(原任务仍 active)。",resumeFailedTitle:"Resume 失败",compact:"压缩上下文",compacting:"压缩中…",compactMenuItemTitle:"向 agent runtime 发送 /compact 压缩上下文",compactSentTitle:e=>`已向 Agent ${e} 发送 /compact`,compactFailedTitle:"压缩上下文失败",clear:"清空上下文",clearing:"清空中…",clearMenuItemTitle:"向 agent runtime 发送 /clear 清空上下文",clearConfirmTitle:e=>`清空 Agent ${e} 的上下文?`,clearConfirmBody:"将发送 /clear,整个会话上下文不可恢复。",clearConfirmLabel:"清空",clearSentTitle:e=>`已向 Agent ${e} 发送 /clear`,clearFailedTitle:"清空上下文失败",deleteConfirmTitle:e=>`删除 Agent ${e}?`,deleteConfirmBody:"此操作不可撤销。",deletedWithPairTitle:e=>`已删除 Agent ${e}`,deletedWithPairBody:e=>`配对的 QA agent ${e} 也被一并移除。`,deletedTitle:e=>`Agent ${e} 已删除`,agentPetMenuItemTitle:"配置 Agent Pet(在状态位置显示动画宠物)",callReview:"发起评审",callingReview:"发起中…",callReviewMenuItemTitle:e=>`让 QA agent 立即对任务 ${e} 跑一轮 review(需要该任务已有 PR)`,confirmReReviewTitle:"发起 QA 重审?",confirmReReviewBody:e=>`QA agent 将对任务 ${e} 立即开始新一轮 review(reviewRound +1)。`,confirmReReviewLabel:"发起重审",reReviewStarted:e=>`已发起 QA 重审(第 ${e} 轮)`,reReviewStartFailed:"发起评审失败",retryBootstrap:"重试 bootstrap",retryBootstrapSucceededTitle:"重试 bootstrap 完成",retryBootstrapSucceededBody:"agent 状态将在下一次刷新生效。",retryBootstrapStillFailingTitle:"重试 bootstrap 仍失败",retryBootstrapStillFailingBody:"看一下红色错误卡的最新原因,按提示修复后再试。",retryBootstrapFailedTitle:"重试 bootstrap 失败",round:e=>`第 ${e} 轮`,noActiveTask:"暂无任务",noActiveTaskAriaLabel:e=>`${e} 暂无任务`,unassigned:"未分配",start:"发起",starting:"发起中…",startFailed:"发起失败",taskHandedTo:(e,n)=>`任务 ${e} 已交给 ${n}`,handToAndStart:e=>`交给 ${e} 并立即开始`,devAgentUnavailable:"Dev agent 当前不可用"},settings:{entry:"系统设置",title:"系统设置",language:"语言",languageSaveFailed:e=>`语言保存失败:${e}`,taskNotifications:"任务完成通知",taskNotificationsDenied:"浏览器已拒绝通知权限",taskNotificationsHint:"任务到达已完成或已合并时通过浏览器通知"},auth:{checkingTitle:"加载中",checkingBody:"正在检查登录状态…",connectFailedTitle:"无法连接服务器",connectFallback:"无法连接服务器",loginTitle:"登录 baxian",loginDescription:"服务器开启了访问鉴权,请输入访问令牌继续。",loginFailed:"登录失败",sessionExpired:"登录已失效,请重新输入令牌",tokenInvalid:"令牌无效,请重试",tokenLabel:"令牌",tokenPlaceholder:"请输入服务器配置的 token",tokenRequired:"请输入访问令牌",submit:"登录",submitting:"登录中…"},createProject:{title:"新建项目",required:"必填",idLabel:"项目 ID",idPlaceholder:"baxian",idTakenError:"该 id 已被占用",repoLabel:"Git 仓库地址",repoFormatError:"需为 git URL(https / ssh / scp,如 https://gitlab.example.com/group/proj.git)或 owner/repo",mergeStrategyLabel:"合并策略",mergeHumanLabel:"人类合并(默认)",mergeAutoLabel:"QA Approve 后自动合并",specApprovalLabel:"Spec 审核",specApprovalHumanLabel:"人类审核(默认)",specApprovalAutoLabel:"QA Approve 后自动开始编码",reviewModeLabel:"Review 模式",reviewModeFollowGlobalLabel:"跟随全局",createdToastTitle:e=>`项目 ${e} 已创建`},createAgent:{modalTitle:e=>`添加 Agent 到 ${e}`,submitLabel:"添加 Agent",submitting:"添加中…",idTakenGlobalError:"该 id 已被占用(全局唯一)",idPlaceholder:(e,n)=>`${e}-${n}`,roleLabel:"角色",createDevFirstHint:"请先创建一个 Dev agent",pairWithLabel:"配对 Dev agent",pairWithPlaceholder:"请选择",pairOptionLabel:(e,n)=>`${e}(${n})`,modeLabel:"运行模式",localModeLabel:"本机",remoteModeLabel:"远程 (SSH)",noHostsHint:"还没有配置 Host。请先在右上角菜单的「Host 管理」中添加。",selectHostPlaceholder:"请选择 Host",sshConfigHint:"私钥/跳板机仍可在 ~/.ssh/config 配置;端口/密码在「Host 管理」里设置。",runtimeLabel:"运行时",reprobeButton:"↻ 重新探测",selectHostFirstHint:"(请先选择 Host)",probingLabel:"探测中…",tmuxProbingLabel:"tmux: 探测中…",advancedOptionsLabel:"高级选项",expandLabel:"展开",collapseLabel:"收起",workdirLabel:"Workdir(可选)",workdirPlaceholder:"留空时自动 clone 到 ~/.baxian/repos/<owner>/<repo>",modelLabel:"Model(可选)",modelPlaceholderCodex:"例: o3 / gpt-4o(留空走 default)",modelPlaceholderOther:"例: sonnet / opus / claude-sonnet-4-6(留空走 default)",modelHint:"透传到 launch 命令的 --model 参数;留空跟随 CLI 默认。",addDirsLabel:"Additional Dirs(可选)",addDirsPlaceholder:`每行一个绝对路径,例:
4
+ /Users/me/shared-libs
5
+ /Users/me/extra-repo`,addDirsHint:"透传到 --add-dir。当前 YOLO 模式下不影响权限拦截,主要用于让 CLI 把额外目录纳入工作根。",yoloTitle:"YOLO 模式(推荐开启)",yoloBodyLead:"开启后 Claude Code 以 ",yoloBodyMid:" 启动,Codex 以 ",yoloBodyTrail:" 启动。",addedToastTitle:(e,n)=>`Agent ${e} 已添加到 ${n}`},createTask:{titleCreate:"新建任务",titleEdit:"编辑任务",selectProjectPlaceholder:"选择项目",notAssignedOption:"暂不指定",pendingRestartSuffix:"(待重启)",notInRuntimeSuffix:"(不在 runtime)",titlePlaceholder:"一句话描述要做什么",descriptionLabel:"Description(可选)",descriptionPlaceholder:"详细描述任务,支持 markdown;简单任务可不填",imagesLabel:"图片(可选)",addImagesButton:"添加图片",removeImageAriaLabel:e=>`移除图片 ${e}`,draftRestoredNotice:"已恢复上次未提交的草稿",discardDraftButton:"丢弃",updatedToastTitle:"任务已更新",createdToastTitle:"任务已创建",imageTooLargeToastTitle:"图片过大",imageTooLargeToastBody:(e,n)=>`${e} 超过 ${n} MiB`,tooManyImagesToastTitle:e=>`最多 ${e} 张图片`,noDevPendingRestartHint:e=>`当前 Dev agent "${e}" 在 baxian.json 中存在但 runtime 未加载,可能是手动编辑过配置文件;重启 server 可拉起`,noDevNotInRuntimeHint:e=>`当前 Dev agent "${e}" 不在 runtime(可能已从 project 配置移除);保存可能失败,请确认或选择新 Dev agent`,noDevGlobalPendingRestartHint:"baxian.json 里有 Dev agent 但 runtime 未加载(可能是手动编辑过配置);重启 server 后生效"},hostMgmt:{title:"Host 管理",emptyState:"还没有配置 Host。点击下方「添加 Host」。",addHostButton:"+ 添加 Host",passwordSavedIndicator:" · 密码已保存",addressLabel:"Host 地址",portLabel:"端口(可选)",portRangeError:"端口需为 1–65535 的整数",aliasLabel:"别名(可选)",userLabel:"用户名(可选)",userPlaceholder:"留空则读 ~/.ssh/config 的 User",passwordLabel:"密码(可选)",passwordPlaceholderSet:"已设置,留空保持不变",passwordPlaceholderUnset:"留空使用 key 认证",clearPasswordLabel:"清除已保存的密码(改用 key 登录)",passwordHintLead:"建议为该 Host 配置好",passwordHintStrong:"免密码登入(SSH key)。",plaintextWarningLead:"否则填写的密码将以",plaintextWarningStrong:"明文",plaintextWarningTrail:"保存到 baxian.json 中。",testConnection:"测试连接",testing:"测试中…",createdToastTitle:e=>`Host ${e} 已添加`,updatedToastTitle:e=>`Host ${e} 已更新`,deletedToastTitle:e=>`Host ${e} 已删除`},projectPage:{newTaskButton:"+ 新建任务",menuAriaLabel:e=>`项目 ${e} 操作菜单`,showTaskPanel:"显示任务面板",addAgent:"添加 Agent",deleteAgentsFirstHint:e=>`请先删除项目下的 ${e} 个 Agent`,deleteProjectMenuItem:"删除项目…",noAgentsYet:"还没有 Agent,点击右上角菜单添加。",closeTaskPanel:"关闭任务面板",deleteModalTitle:"删除项目",confirmDeleteButton:"确认删除",deleteBodyLead:"将从 ",deleteBodyMid:" 中移除项目 ",deleteBodySuffix:"。此操作不可撤销,且不会删除 Git 仓库本身。",confirmInputLead:"如需确认,请在下方输入项目 ID ",confirmInputSuffix:":",confirmInputAriaLabel:"输入项目 ID 以确认删除",deletedToastTitle:e=>`项目 ${e} 已删除`},taskDetail:{cancelConfirmTitle:e=>`取消任务 ${e}?`,cancelConfirmLabel:"取消任务",cancelledToastTitle:"任务已取消",cancelFailedTitle:"取消失败",reReviewTerminalConfirmTitle:"重审已结束的任务?",reReviewTerminalConfirmBody:(e,n)=>`任务 ${e} 已是「${n}」状态。手动请 QA agent 重审会再跑一轮 review,但状态机不会把 QA agent 的结果带回主流程。`,retryConfirmTitle:e=>`重试任务 ${e}?`,retryConfirmBodyMerged:"任务已合并。重试会用同样的标题/描述新建一个任务从头跑。",retryConfirmBodyDefault:"会新建一个任务从头开始,旧任务保留为历史。",retryCreatedToastTitle:e=>`已新建任务 ${e}`,retryFailedTitle:"重试失败",markCompleteConfirmTitle:"标记完成并合并?",markCompleteConfirmBody:e=>`将合并 PR #${e} 并收尾:删本地分支、压缩 agent 上下文。`,markComplete:"标记完成",completing:"完成中…",markCompleteToastTitle:"已标记完成,开始收尾",markCompleteFailedTitle:"标记完成失败",continueConfirmTitle:"继续一轮?",continueConfirmBody:e=>`让 Dev agent 再修一轮(第 ${e} 轮),完成后自动转 QA review。`,continueRound:"继续一轮",continuing:"继续中…",continuedToastTitle:e=>`已继续一轮(第 ${e} 轮)`,continueFailedTitle:"继续一轮失败",specApproveConfirmTitle:"通过 Spec 并开始编码?",specApproveConfirmBody:e=>`任务 ${e} 将进入编码阶段。`,specApprove:"通过 Spec",specApprovedToastTitle:"Spec 已通过,已发起编码",specApproveFailedTitle:"Spec 通过失败",specRejectedToastTitle:"Spec 已打回,Dev agent 开始修订",specRejectFailedTitle:"Spec 打回失败",confirmGateConfirmTitle:e=>`确认完成任务 ${e}?`,confirmGateConfirmBody:"project.merge 为 auto 时由 baxian 自动执行合并。",confirmComplete:"确认完成",confirmedToastTitle:e=>`已确认(${e})`,confirmFailedTitle:"确认失败",taskNotFound:e=>`任务不存在:${e}`,legacyPendingNotice:"任务还没有指定 Dev agent:点「编辑」选择,或在任一空闲 Dev agent 卡片上点「发起」。",legacyReadonlyNotice:e=>`历史任务,无指定 Dev agent,当前状态「${e}」,只读。`,reviewRoundPrefix:"评审 ",reviewRoundSuffix:" 轮",specRoundPrefix:"Spec ",specRoundSuffix:" 轮",createdAtPrefix:"创建于 ",updatedAtPrefix:" · 更新于 ",verdictOverdueTitle:"评审逾期未交",verdictOverduePrefix:"QA agent 于 ",verdictOverdueSuffix:" 接单,超过 10 分钟未提交结论。可打开 QA agent 终端查看,或点「发起评审」重新发起。",approvedBannerTitle:"QA agent 已通过 · 正在核对反馈",approvedBannerBody:"Dev agent 正在确认所有评审反馈均已处理,完成后进入收尾。",viewPr:e=>`查看 PR #${e}`,readyGateBannerTitle:"评审通过 · 等你确认",readyGateBannerBody:e=>`Server 评审通过,共 ${e} 轮。点「确认」收尾,或「取消」丢弃。`,mergeReadyBannerTitle:"PR 就绪 · 等你确认",mergeReadyBannerBody:"Dev agent 已完成收尾自检,点「确认」交由 baxian 收尾。",specReadyBannerTitle:"Spec 需由人类审核",specReadyNotice:e=>`QA agent 已通过第 ${e} 轮 Spec,全文见下方评审记录。通过即开始编码;打回意见将交 Dev agent 修订后复审。`,specCommentsPlaceholder:"打回意见(打回时必填)",submitting:"提交中…",specApproveButton:"通过 Spec,开始编码",specRejectTitleEmpty:"先填写打回意见",specRejectTitleReady:"意见将作为 findings 交 Dev agent 修订",specReject:"打回 Spec",codeMaxRoundsTitle:e=>`评审已达 ${e} 轮上限`,codeMaxRoundsBody:"可「标记完成」先合并成果,或「继续一轮」再修订。剩余问题建议另开任务,轮次越多 agent 越容易偏题。",specMaxRoundsTitle:e=>`Spec 评审已达 ${e} 轮上限`,specMaxRoundsBody:"多轮未达成一致,任务已暂停。可「重试」新建任务从头跑,或「取消」。建议先看评审记录定位分歧、细化描述后再重试。",noDescription:"(无描述)",noLinkedAgent:"暂无关联 Agent",cancelling:"取消中…",retryDisabledStatusTitle:e=>`当前状态「${e}」不可重试`,retryDisabledLegacyTitle:"历史任务没有指定 Dev agent,无法重试",retryEnabledTitle:"新建一个任务从头跑,丢弃当前 worktree/branch",reviewNoPrTitle:"该任务还没有 PR,无法发起评审",reviewSpecMaxRoundsTitle:"Spec 阶段达上限不支持 Call review",reviewButtonTitle:"让 QA agent 立即开始新一轮 review(reviewRound +1)",continueButtonTitle:"让 Dev agent 再修一轮,完成后自动转 QA review",completeButtonTitle:"合并 PR 并收尾(删本地分支 + 压缩上下文)",confirmButtonTitle:"确认完成;merge:auto 时由 baxian 执行合并",confirming:"确认中…",retryPublishButtonTitle:"发布失败后重试 push/PR 步骤",retryPublish:"重试发布",noAgentSlot:e=>`暂无 ${e} agent`,reviewSummaryPrefix:"Review ",reviewSummaryMid:" 轮 · 最终 verdict ",reviewSummaryFindingsPrefix:" · findings 共 ",reviewSummaryFindingsSuffix:" 条"},taskPanel:{ariaLabel:"任务面板",emptyInProgress:"暂无正在处理的任务",emptyPending:"暂无待处理的任务",collapse:"收起",view:"查看",loadMore:"加载更多",emptyDone:"暂无已处理的任务"},review:{specDraft:"规格稿",codeChanges:"代码改动",submitSpecDraft:"提交规格稿",submitCodeChanges:"提交代码改动",contentTruncated:"内容较大,展示的是截断后的片段。",noContent:"无内容",qaReviewHeading:"QA 评审",notSubmitted:"评审尚未提交。",noFindingsThisRound:"本轮无 findings。",devResponsesHeading:"Dev 反馈",roundNotFound:(e,n)=>`未找到该轮评审(${e} 第 ${n} 轮)。`,loadFailed:e=>`加载评审记录失败:${e}`,loadingRecords:"加载评审记录…",notStarted:"评审尚未开始",sectionTitle:"评审记录",phaseLabel:{spec:"Spec 评审",code:"代码评审"},diffLineCount:e=>`diff ${e} 行`,specDocLineCount:e=>`规格稿 ${e} 行`,findingsSummary:(e,n)=>`${e} 条 findings${n?`(${n})`:""}`,responsesSummary:e=>`${e} 条反馈`,reviewTurnLabel:"评审",responseTurnLabel:"反馈",roleUser:"用户",roleQa:"QA",roleDev:"Dev"},githubReview:{reasonServerMode:"该 task 为 server 评审模式,代码评审记录见任务详情的「评审记录」。",reasonServerModeEntry:"该 task 为 server 评审模式,代码评审记录见 server 评审轮次。",reasonNoPr:"该 task 还没有 PR,暂无代码评审记录。",reasonNotGithub:"该 task 的仓库不是 GitHub 仓库,无法拉取 PR 评审记录。",codeReviewHeading:"代码评审",fetchFailed:e=>`评审记录拉取失败:${e}`,partialFetchFailed:e=>`部分评审记录拉取失败:${e}(仅展示已获取的部分)`,commitPill:"提交",inlineComment:"行内评论",comment:"评论",replyIndicator:"↩ 回复",noReviewBody:"(无评审正文)",bodyTruncated:"内容较大,已截断。",truncatedSuffix:"(已截断)",noReviewBodyFallback:"无评审正文",commitFallback:"commit"},toast:{dismissAriaLabel:"关闭通知"},banner:{restartFailed:e=>`重启失败:${e}`,restarting:"重启中…",pendingNotice:e=>`有 ${e} 项配置变更待重启 baxian server 才生效`,restartNow:"现在重启",preRestartFetchFailed:e=>`获取重启前 startedAt 失败:${e}`,restartTriggerFailed:e=>`触发重启失败:${e}`,restartTimeout:"重启超时(30s 未恢复)。请检查日志或手动 baxian start -c <path>"},terminal:{sessionEnded:"会话已结束",keyPadAriaLabel:"终端按键",arrowAriaLabel:e=>`方向键 ${e}`,arrowLabel:{up:"上",down:"下",left:"左",right:"右"},escKeyAriaLabel:"Esc 键"},imageUpload:{tooLargeBody:e=>`单张图片不能超过 ${e} MiB`,insertedTitle:"图片已插入",insertedBody:"路径已粘贴到终端输入,补充说明后回车",uploadFailedTitle:"图片上传失败",uploadAriaLabel:"上传图片"},pet:{missingManifest:"文件包中未找到 pet.json",manifestParseFailed:"pet.json 解析失败",missingSpritesheet:"文件包中未找到精灵图(png/webp)",disabledTitle:"已关闭 Agent Pet",disableFailedTitle:"关闭失败",selectedTitle:"已选择 Pet",selectFailedTitle:"选择失败",deleteConfirmTitle:e=>`删除 Pet「${e}」?`,deleteConfirmBody:"使用它的 Agent 会回到默认状态显示。",deletedTitle:e=>`Pet「${e}」已删除`,deleteFailedTitle:"删除失败",uploadedTitle:"Pet 上传成功",uploadFailedTitle:"Pet 上传失败",enableLabel:"启用 Agent Pet",enableHint:"开启后可上传 Codex Pet 文件包,或选择已上传过的 Pet 替换 Agent 卡片上的状态显示。",uploadButton:"上传 Pet 文件包",uploadInputAriaLabel:"上传 Codex Pet 文件包",uploadDirHint:"选择 Codex Pet 目录(含 pet.json 与精灵图)。",emptyState:"还没有上传过 Pet,点击上方按钮上传。",currentMarker:"(当前)",deleteAriaLabel:e=>`删除 ${e}`}},It="baxian.language",Ge="en-US",$n={"en-US":Dn,"zh-CN":Ls};function In(e){return e==="zh-CN"||e==="en-US"}function Bn(){try{const e=localStorage.getItem(It);return In(e)?e:Ge}catch{return Ge}}function Fn(e){try{localStorage.setItem(It,e)}catch{}}let Ie=Bn();const St=new Set;let tt=0,Ds=0,en=0;function Bt(e){e!==Ie&&(Ie=e,St.forEach(n=>n(e)))}function Nt(e){tt+=1;const n=e??Ge;Fn(n),Bt(n)}function $s(e){const n=e??Ge;Fn(n),Bt(n)}function Ft(){return $n[Ie]}const Mn=o.createContext({locale:Ge,messages:Dn,saving:!1,setLocale:async()=>{throw new Error("setLocale requires I18nProvider")}});function Is({children:e}){const[n,s]=o.useState(Ie),[r,a]=o.useState(!1);o.useEffect(()=>{const l=d=>s(d);return St.add(l),s(Ie),()=>{St.delete(l)}},[]),o.useEffect(()=>{document.documentElement.lang=n==="zh-CN"?"zh-CN":"en"},[n]),o.useEffect(()=>{const l=d=>{if(d.key!==null&&d.key!==It)return;const m=d.key===null?Bn():d.newValue;In(m)&&(tt+=1,Bt(m))};return window.addEventListener("storage",l),()=>window.removeEventListener("storage",l)},[]);const i=async l=>{if(l!==Ie){a(!0);try{await D.config.patch({language:l}),Nt(l)}finally{a(!1)}}};return t.jsx(Mn.Provider,{value:{locale:n,messages:$n[n],saving:r,setLocale:i},children:e})}function On(){return o.useContext(Mn)}function F(){return On().messages}function Bs(){o.useEffect(()=>{const e=()=>{const s=tt,r=++Ds;D.config.get().then(a=>{s===tt&&(r<=en||(en=r,$s(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 Hn=o.createContext(null),Fs={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"},Ms={success:As,warn:Ps,error:Es};let Os=1;function Hs({children:e}){const n=F(),[s,r]=o.useState([]),a=o.useRef(new Map),i=o.useRef(new Map);o.useEffect(()=>{const h=a.current,x=i.current;return()=>{for(const g of h.values())clearTimeout(g);h.clear(),x.clear()}},[]);const l=o.useCallback(h=>{const x=a.current.get(h);x&&clearTimeout(x),a.current.delete(h)},[]),d=o.useCallback(h=>{l(h),i.current.delete(h),r(x=>x.filter(g=>g.id!==h))},[l]),m=o.useCallback((h,x)=>{l(h),a.current.set(h,setTimeout(()=>d(h),x))},[l,d]),f=o.useCallback((h,x)=>{const g=i.current.get(h)??new Set;g.add(x),i.current.set(h,g),l(h)},[l]),p=o.useCallback((h,x,g)=>{const y=i.current.get(h);y==null||y.delete(x),(!y||y.size===0)&&m(h,g)},[m]),u=o.useCallback(h=>{const x=Os++,g=h.durationMs??3e3;r(y=>[...y,{...h,id:x,durationMs:g}]),m(x,g)},[m]);return t.jsxs(Hn.Provider,{value:{show:u},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(h=>t.jsx("div",{className:`pointer-events-auto w-full max-w-xs rounded-lg border px-4 py-3 shadow-toast ${Fs[h.kind]}`,role:"status",onMouseEnter:()=>f(h.id,"hover"),onMouseLeave:()=>p(h.id,"hover",h.durationMs),onFocus:()=>f(h.id,"focus"),onBlur:x=>{x.currentTarget.contains(x.relatedTarget)||p(h.id,"focus",h.durationMs)},children:t.jsxs("div",{className:"flex items-start gap-2",children:[(()=>{const x=Ms[h.kind];return t.jsx(x,{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:h.title}),h.body&&t.jsx("div",{className:"mt-1 whitespace-pre-line text-xs text-og-700",children:h.body})]}),t.jsx("button",{type:"button",onClick:()=>d(h.id),className:"text-current opacity-50 transition-opacity hover:opacity-100","aria-label":n.toast.dismissAriaLabel,children:"✕"})]})},h.id))})]})}function ve(){const e=o.useContext(Hn);if(!e)throw new Error("useToast must be inside <ToastProvider>");return e}const _s={sm:"max-w-md",md:"max-w-lg",lg:"max-w-2xl"},tn='input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), [href], [tabindex]:not([tabindex="-1"])',Ce=[];function ke({open:e,onClose:n,title:s,titleContent:r,children:a,footer:i,size:l="md",dismissOnBackdrop:d=!0}){const m=F(),f=o.useRef(null),p=o.useRef();p.current||(p.current=Symbol("modal"));const u=o.useRef(null),h=o.useRef(!1),x=o.useRef(n);return o.useEffect(()=>{x.current=n},[n]),o.useEffect(()=>{if(!e)return;const g=p.current;Ce.push(g);const y=()=>Ce[Ce.length-1]===g;u.current=document.activeElement;const w=k=>{if(!y())return;if(k.key==="Escape"){x.current();return}if(k.key!=="Tab")return;const N=f.current;if(!N)return;const b=Array.from(N.querySelectorAll(tn)).filter(I=>I.offsetParent!==null||I===document.activeElement);if(b.length===0){k.preventDefault();return}const T=b[0],j=b[b.length-1],B=document.activeElement;k.shiftKey&&(B===T||!N.contains(B))?(k.preventDefault(),j.focus()):!k.shiftKey&&(B===j||!N.contains(B))&&(k.preventDefault(),T.focus())};document.addEventListener("keydown",w);const C=document.body.style.overflow;document.body.style.overflow="hidden";const P=f.current;if(P){const k=P.querySelector(tn);k==null||k.focus()}return()=>{var N,b;const k=Ce.indexOf(g);k>=0&&Ce.splice(k,1),document.removeEventListener("keydown",w),document.body.style.overflow=C,(b=(N=u.current)==null?void 0:N.focus)==null||b.call(N)}},[e]),e?t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-og-1000/45 px-3 sm:px-4",onMouseDown:d?g=>{h.current=g.target===g.currentTarget&&Ce[Ce.length-1]===p.current}:void 0,onClick:d?g=>{g.target===g.currentTarget&&h.current&&x.current()}:void 0,role:"presentation",children:t.jsxs("div",{ref:f,className:`flex w-full ${_s[l]} max-h-[90dvh] flex-col overflow-hidden rounded-lg border border-og-100 bg-surface shadow-modal`,onClick:g=>g.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:()=>x.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 _n=o.createContext(null);function Us({children:e}){const n=F(),[s,r]=o.useState(null),a=o.useRef(null),i=o.useCallback(d=>new Promise(m=>{var p;(p=a.current)==null||p.resolve(!1);const f={...d,resolve:m};a.current=f,r(f)}),[]),l=o.useCallback(d=>{const m=a.current;m&&(a.current=null,r(null),m.resolve(d))},[]);return t.jsxs(_n.Provider,{value:i,children:[e,s&&t.jsx(ke,{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 Mt(){const e=o.useContext(_n);if(!e)throw new Error("useConfirm must be inside <ConfirmProvider>");return e}const nt="baxian.pendingRestart",Gs=500,Ws=3e4,Un=o.createContext(null);function qs(){try{const e=localStorage.getItem(nt);if(!e)return{count:0,baselineStartedAt:null};const n=JSON.parse(e);return{count:typeof n.count=="number"?n.count:0,baselineStartedAt:typeof n.baselineStartedAt=="string"?n.baselineStartedAt:null}}catch{return{count:0,baselineStartedAt:null}}}function zs(e){try{e.count<=0?localStorage.removeItem(nt):localStorage.setItem(nt,JSON.stringify(e))}catch{}}function Qs({children:e}){const n=F(),s=qs(),[r,a]=o.useState(s.count),[i,l]=o.useState(s.baselineStartedAt),[d,m]=o.useState(s.count>0?"pending":"idle"),[f,p]=o.useState(),u=o.useRef(s.count),h=o.useRef(s.count>0?"pending":"idle"),x=o.useRef(0),g=o.useCallback(N=>{u.current=N,a(N)},[]),y=o.useCallback(N=>{a(b=>{const T=N(b);return u.current=T,T})},[]),w=o.useCallback(N=>{h.current=N,m(N)},[]);o.useEffect(()=>{zs({count:r,baselineStartedAt:i})},[r,i]),o.useEffect(()=>{let N=!1;(async()=>{try{const T=await D.health.get();if(N)return;l(j=>j!==null&&T.startedAt!==j?(g(0),w("idle"),null):j)}catch{}})();const b=T=>{if(T.key===nt){if(T.newValue===null){if(h.current==="restarting"&&x.current>0){g(x.current),l(null);return}g(0),l(null),h.current!=="restarting"&&w("idle");return}try{const j=JSON.parse(T.newValue);typeof j.count=="number"&&(h.current==="restarting"&&j.count>u.current&&(x.current+=j.count-u.current),g(j.count),h.current!=="restarting"&&w(j.count>0?"pending":"idle")),typeof j.baselineStartedAt=="string"?l(j.baselineStartedAt):j.baselineStartedAt===null&&l(null)}catch{}}};return window.addEventListener("storage",b),()=>{N=!0,window.removeEventListener("storage",b)}},[g,w]);const C=o.useRef(!1),P=o.useCallback(()=>{y(N=>N+1),h.current==="restarting"?x.current+=1:w("pending"),l(N=>(N!==null||C.current||(C.current=!0,(async()=>{try{const b=await D.health.get();l(T=>T??b.startedAt)}catch{}finally{C.current=!1}})()),N))},[w,y]),k=o.useCallback(async()=>{x.current=0,p(void 0),w("restarting");let N;try{N=(await D.health.get()).startedAt}catch(T){w("failed"),p(n.banner.preRestartFetchFailed(T instanceof Error?T.message:String(T)));return}try{await D.server.restart()}catch(T){if(!(T instanceof Be&&T.status===409)){w("failed"),p(n.banner.restartTriggerFailed(T instanceof Error?T.message:String(T)));return}}const b=Date.now();for(;Date.now()-b<Ws;){await new Promise(T=>setTimeout(T,Gs));try{const T=await D.health.get();if(T.startedAt!==N){const j=x.current;x.current=0,l(j>0?T.startedAt:null),g(j),w(j>0?"pending":"idle");return}}catch{}}w("failed"),p(n.banner.restartTimeout)},[g,w,n]);return t.jsx(Un.Provider,{value:{phase:d,count:r,error:f,flagDirty:P,triggerRestart:k},children:e})}function ct(){const e=o.useContext(Un);if(!e)throw new Error("usePendingRestart must be used inside PendingRestartProvider");return e}const Ks=[500,1e3,2e3,4e3,8e3,15e3,3e4];class Gn{constructor(n){se(this,"attempts",0);se(this,"timer",null);se(this,"delaysMs");this.opts=n,this.delaysMs=n.delaysMs??Ks}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}}let nn=0;function Vs(){nn++;const e=Math.random().toString(36).slice(2,8);return`sub-${Date.now().toString(36)}-${nn}-${e}`}function Ys(e){return Array.from(new TextEncoder().encode(e)).map(n=>n.toString(16).padStart(2,"0")).join("")}function Js(){return`${location.protocol==="https:"?"wss":"ws"}://${location.host}/api/stream`}const Xs=(e,n)=>n&&n.length>0?new WebSocket(e,n):new WebSocket(e);class Zs{constructor(n={}){se(this,"wsUrl");se(this,"wsFactory");se(this,"tokenProvider");se(this,"ws",null);se(this,"subs",new Map);se(this,"snapshotPending",new Set);se(this,"preSubscribeQueue",new Map);se(this,"outbox",[]);se(this,"reconnectScheduler");se(this,"explicitlyClosed",!1);this.wsUrl=n.wsUrl??Js(),this.wsFactory=n.wsFactory??Xs,this.tokenProvider=n.tokenProvider??Dt,this.reconnectScheduler=new Gn({reconnect:()=>this.openSocket(),shouldReconnect:()=>!this.explicitlyClosed&&this.subs.size>0})}subscribe(n){const s=Vs(),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.${Ys(n)}`]:void 0;let r;try{r=this.wsFactory(this.wsUrl,s)}catch(a){console.warn("[pane-stream] WebSocket constructor threw:",a),this.scheduleReconnect();return}this.ws=r,r.onopen=()=>{if(r!==this.ws)return;this.reconnectScheduler.reset();for(const i of this.subs.values()){this.snapshotPending.add(i.subscriberId),this.preSubscribeQueue.set(i.subscriberId,[]),i.snapshotSeq=void 0;try{r.send(JSON.stringify({op:"subscribe",subscriberId:i.subscriberId,agentId:i.agentId,mode:i.mode}))}catch(l){console.warn("[pane-stream] resubscribe send failed:",l)}}const a=this.outbox;this.outbox=[];for(const i of a)if(i.op!=="subscribe"){if("subscriberId"in i&&i.subscriberId){if(!this.subs.has(i.subscriberId))continue;if(this.snapshotPending.has(i.subscriberId)&&i.op!=="unsubscribe"){this.outbox.push(i);continue}}try{r.send(JSON.stringify(i))}catch(l){console.warn("[pane-stream] outbox flush failed:",l)}}},r.onmessage=a=>{if(r!==this.ws)return;let i;try{const l=typeof a.data=="string"?a.data:String(a.data);i=JSON.parse(l)}catch{return}this.handleMessage(i)},r.onclose=()=>{r===this.ws&&(this.ws=null,!this.explicitlyClosed&&this.subs.size!==0&&this.scheduleReconnect())},r.onerror=()=>{}}scheduleReconnect(){this.reconnectScheduler.schedule()}wsSendOrQueue(n){if(this.ws&&this.ws.readyState===WebSocket.OPEN)try{this.ws.send(JSON.stringify(n));return}catch(s){console.warn("[pane-stream] send failed, will queue:",s)}this.outbox.push(n)}handleMessage(n){var s,r;switch(n.type){case"snapshot":this.handleSnapshot(n);break;case"subscribed":this.handleSubscribed(n);break;case"data":this.dispatch(n);break;case"session_gone":for(const a of[...this.subs.values()])a.agentId===n.agentId&&((s=a.onSessionGone)==null||s.call(a));break;case"error":{if(n.subscriberId){const a=this.subs.get(n.subscriberId);(r=a==null?void 0:a.onError)==null||r.call(a,{code:n.code,message:n.message})}else console.warn("[pane-stream] connection-level error:",n.code,n.message);break}}}handleSnapshot(n){const s=this.subs.get(n.subscriberId);s&&s.onSnapshot({cols:n.cols,rows:n.rows,data:n.data})}handleSubscribed(n){const s=this.subs.get(n.subscriberId);if(!s)return;s.snapshotSeq=n.snapshotSeq,s.lastSize||(s.lastSize={cols:n.cols,rows:n.rows}),this.snapshotPending.delete(n.subscriberId);const r=this.preSubscribeQueue.get(n.subscriberId);if(this.preSubscribeQueue.delete(n.subscriberId),r)for(const a of r)a.seq>n.snapshotSeq&&s.onData(a.data);s.mode==="full"&&s.lastSize&&this.wsSendOrQueue({op:"resize",subscriberId:s.subscriberId,cols:s.lastSize.cols,rows:s.lastSize.rows}),this.flushOutboxForSub(n.subscriberId)}flushOutboxForSub(n){if(this.outbox.length===0||!this.ws||this.ws.readyState!==WebSocket.OPEN)return;const s=[];for(const r of this.outbox)if("subscriberId"in r&&r.subscriberId===n&&r.op!=="subscribe")try{this.ws.send(JSON.stringify(r))}catch(a){console.warn("[pane-stream] flushOutboxForSub send failed:",a)}else s.push(r);this.outbox=s}dispatch(n){for(const s of this.subs.values())if(s.agentId===n.agentId)if(this.snapshotPending.has(s.subscriberId)){const r=this.preSubscribeQueue.get(s.subscriberId);r&&r.push({seq:n.seq,data:n.data})}else s.onData(n.data)}}let ht=null;function ft(){return ht||(ht=new Zs),ht}function er(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=ft().subscribe({agentId:n,mode:s,onSnapshot:f=>a.current.onSnapshot(f),onData:f=>a.current.onData(f),onError:f=>{var p,u;return(u=(p=a.current).onError)==null?void 0:u.call(p,f)},onSessionGone:()=>{var f,p;return(p=(f=a.current).onSessionGone)==null?void 0:p.call(f)}});return r.current=m.subscriberId,()=>{r.current=null,m.unsubscribe()}},[n,s]);const i=o.useCallback(d=>{const m=r.current;m&&ft().send(m,d)},[]),l=o.useCallback((d,m)=>{const f=r.current;f&&ft().resize(f,d,m)},[]);return{send:i,resize:l}}const tr=[{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"}],Qe=Object.fromEntries(tr.map(e=>[e.key,e]));function Ke({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 nr({onKey:e,onEscape:n,className:s}){const r=F();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(Ke,{arrow:Qe.left,ariaLabel:r.terminal.arrowAriaLabel(r.terminal.arrowLabel.left),onPress:e}),t.jsx(Ke,{arrow:Qe.up,ariaLabel:r.terminal.arrowAriaLabel(r.terminal.arrowLabel.up),onPress:e}),t.jsx(Ke,{arrow:Qe.down,ariaLabel:r.terminal.arrowAriaLabel(r.terminal.arrowLabel.down),onPress:e}),t.jsx(Ke,{arrow:Qe.right,ariaLabel:r.terminal.arrowAriaLabel(r.terminal.arrowLabel.right),onPress:e})]})}const sr=Math.floor(lt/1024/1024);function rr({agentId:e,className:n}){const s=F(),r=o.useRef(null),[a,i]=o.useState(!1),{show:l}=ve(),d=async m=>{var p;const f=(p=m.target.files)==null?void 0:p[0];if(m.target.value="",!!f){if(f.size>lt){l({kind:"error",title:s.createTask.imageTooLargeToastTitle,body:s.imageUpload.tooLargeBody(sr)});return}i(!0);try{await D.agents.uploadImage(e,f),l({kind:"success",title:s.imageUpload.insertedTitle,body:s.imageUpload.insertedBody})}catch(u){const h=u instanceof Be||u instanceof Error?u.message:String(u);l({kind:"error",title:s.imageUpload.uploadFailedTitle,body:h})}finally{i(!1)}}};return t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button","aria-label":s.imageUpload.uploadAriaLabel,disabled:a,onMouseDown:m=>m.preventDefault(),onClick:()=>{var m;return(m=r.current)==null?void 0:m.click()},className:n??"flex h-8 w-8 items-center justify-center rounded border border-hairline bg-surface text-og-700 transition-colors hover:bg-og-50 hover:text-og-1000 active:bg-og-200 disabled:cursor-not-allowed disabled:opacity-50",children:t.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[t.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),t.jsx("circle",{cx:"9",cy:"9",r:"2"}),t.jsx("path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"})]})}),t.jsx("input",{ref:r,type:"file",accept:"image/*",className:"hidden",onChange:d})]})}const ar={up:"A",down:"B",right:"C",left:"D"};function ir(e,n){return(n?"\x1BO":"\x1B[")+ar[e]}const sn=18,or=250,lr=256*1024,rn="#fdfdfd",cr='ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',dr={background:rn,foreground:"#474c55",cursor:"#1348dc",cursorAccent:rn,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 mr(e){return e.replace(ur,"")}const hr=1024*1024;function fr(e){const n=e.indexOf(";");if(n===-1)return null;const s=e.slice(n+1);if(s.length===0||s==="?"||s.length>hr)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 He({agentId:e,mode:n,interactive:s=!1,maxLines:r,className:a,autoFocus:i=!0,deferFullUntilFocus:l=!1,arrowKeys:d=!1}){const m=F(),f=o.useRef(null),p=o.useRef(null),u=o.useRef(null),h=o.useRef(null),x=o.useRef(!1),g=o.useRef(""),y=o.useRef([]),w=o.useRef(0),C=o.useRef(null),P=o.useRef(null),k=o.useRef(null),N=o.useRef(Promise.resolve()),b=o.useRef(0),[T,j]=o.useState(null),[B,I]=o.useState(!1),L=`${e}\0${n}\0${l?"1":"0"}`,[U,H]=o.useState({key:L,active:!1}),M=U.key===L&&U.active,K=n==="full"&&l,ee=K&&!M?"preview":n,E=s&&ee==="full",ne=(c,v)=>v.length===0?Promise.resolve():new Promise(S=>{try{c.write(v,()=>S())}catch($){console.warn("[pane-terminal] write failed:",$),S()}}),q=ee==="preview",J=()=>{if(!q)return;const c=f.current,v=p.current;if(!c||!v||c.clientHeight<=0)return;const $=(v.buffer.active.cursorY+1)*sn;c.scrollTop=Math.max(0,$-c.clientHeight)},W=()=>{if(!q||k.current!==null)return;let c=!1;const v=requestAnimationFrame(()=>{c=!0,k.current=null,J()});c||(k.current=v)},V=(c,v)=>{N.current=N.current.then(async()=>{const S=p.current;if(!(!S||v!==b.current))try{await c(S),E&&S.scrollToBottom(),W()}catch($){console.warn("[pane-terminal] terminal task failed:",$)}}).catch(S=>{console.warn("[pane-terminal] write chain failed:",S)})},ce=(c,v)=>{V(S=>ne(S,c),v)},de=()=>{C.current!==null&&(cancelAnimationFrame(C.current),C.current=null),P.current!==null&&(clearTimeout(P.current),P.current=null)},_=()=>{de(),y.current=[],w.current=0},ie=()=>{de();const c=y.current;c.length!==0&&(y.current=[],w.current=0,ce(c.join(""),b.current))},re=c=>{if(c.length!==0){if(y.current.push(c),w.current+=c.length,w.current>=lr){ie();return}C.current===null&&(C.current=requestAnimationFrame(ie)),P.current===null&&(P.current=setTimeout(ie,or))}},{send:ue,resize:he}=er({agentId:e,mode:ee,onSnapshot:({cols:c,rows:v,data:S})=>{if(p.current)try{const Y=b.current+1;b.current=Y,_(),V(async X=>{var R;X.reset(),E?((R=h.current)==null||R.call(h),await ne(X,S)):(c>0&&v>0&&X.resize(c,v),await ne(X,S))},Y)}catch(Y){console.warn("[pane-terminal] snapshot write failed:",Y)}},onData:c=>{re(c)},onError:c=>j(`${c.code}: ${c.message}`),onSessionGone:()=>I(!0)});o.useEffect(()=>{j(null),I(!1)},[e,ee]),o.useEffect(()=>{g.current=""},[L]),o.useEffect(()=>{if(ee!=="full")return;const c=g.current;c.length!==0&&(g.current="",ue(c))},[ue,ee]);const pe=o.useCallback(()=>{!s||!K||M||(x.current=!0,H({key:L,active:!0}))},[L,M,s,K]),oe=o.useCallback(c=>{const v=mr(c);if(v.length!==0){if(K&&(!M||g.current.length>0)){g.current+=v,pe();return}ue(v)}},[pe,M,ue,K]);o.useEffect(()=>{const c=f.current;if(!c)return;let v=!1;const S=new bs.Terminal({cursorBlink:s,disableStdin:!s,theme:dr,fontFamily:cr,fontSize:13,lineHeight:1.4,scrollback:ee==="full"?5e3:1e3}),$=new vs.FitAddon;S.loadAddon($),S.open(c),p.current=S,u.current=$;const Y=q?S.onRender(()=>W()):null;if(s&&(i||x.current)){x.current=!1;try{S.focus()}catch{}}s&&(S.onData(oe),ee==="full"&&S.parser.registerOscHandler(52,je=>{var Re;const Se=fr(je);return Se!==null&&((Re=navigator.clipboard)==null||Re.writeText(Se).catch(()=>{})),!0}));const X=()=>c.clientWidth>0&&c.clientHeight>0,R=(je=!1)=>{if(!X())return!1;const Se=S.cols,Re=S.rows;try{$.fit()}catch{return!1}return E&&S.scrollToBottom(),S.cols>0&&S.rows>0&&(je||S.cols!==Se||S.rows!==Re)&&he(S.cols,S.rows),!0};h.current=E?()=>R(!0):null;let O=null,Z=null,z=null,ye=0;const we=()=>{O||(O=new ResizeObserver(()=>{Z&&clearTimeout(Z),Z=setTimeout(()=>{Z=null,E?R():q&&W()},100)}),O.observe(c))},Le=()=>{z=requestAnimationFrame(()=>{if(z=null,!v){if(!E){q&&(we(),W());return}if(R(!0)){we();return}if(ye++<5){Le();return}we()}})};return Le(),()=>{v=!0,z!==null&&cancelAnimationFrame(z),C.current!==null&&(cancelAnimationFrame(C.current),C.current=null),P.current!==null&&(clearTimeout(P.current),P.current=null),k.current!==null&&(cancelAnimationFrame(k.current),k.current=null),b.current++,y.current=[],w.current=0,N.current=Promise.resolve(),Z&&clearTimeout(Z),O==null||O.disconnect(),Y==null||Y.dispose(),p.current=null,u.current=null,h.current=null;try{S.dispose()}catch(je){console.warn("[pane-terminal] dispose failed:",je)}}},[e,i,E,oe,s,ee,he]);const me=()=>{var c;if(s){pe();try{(c=p.current)==null||c.focus()}catch{}}};o.useEffect(()=>{if(s)return;const c=f.current;if(!c)return;const v=S=>{S.stopPropagation()};return c.addEventListener("wheel",v,{capture:!0,passive:!0}),()=>c.removeEventListener("wheel",v,{capture:!0})},[s]);const A=r&&r>0?{maxHeight:`${r*sn}px`}:void 0;return t.jsxs("div",{className:a??"flex flex-col h-full w-full min-h-0 bg-term",children:[(T||B)&&t.jsx("div",{className:"border-b border-accent/25 bg-accent-soft px-3 py-1 font-mono text-xs text-accent",children:B?m.terminal.sessionEnded:T}),t.jsx("div",{className:"flex flex-1 min-h-0 px-2 py-1.5",style:A,children:t.jsx("div",{ref:f,className:"flex-1 min-h-0 overflow-hidden",onMouseDown:me})}),s&&d&&t.jsxs("div",{className:"grid grid-cols-[1fr_auto_1fr] gap-2 flex-none items-center border-t border-hairline bg-page px-3 py-2",children:[t.jsx("div",{className:"flex items-center",children:t.jsx(rr,{agentId:e})}),t.jsx(nr,{className:"flex items-center justify-center gap-1",onKey:c=>{var S,$;const v=!!(($=(S=p.current)==null?void 0:S.modes)!=null&&$.applicationCursorKeysMode);oe(ir(c,v))},onEscape:()=>oe("\x1B")})]})]})}function pr(){const[e,n]=o.useState([]),[s,r]=o.useState(!0),[a,i]=o.useState(null),l=o.useCallback(async()=>{r(!0);try{n(await D.pets.list()),i(null)}catch(d){i(d instanceof Error?d.message:String(d))}finally{r(!1)}},[]);return o.useEffect(()=>{l()},[l]),{pets:e,loading:s,error:a,refresh:l}}const pt=new Map,gt=new Map;function gr(e){const[n,s]=o.useState(()=>e?gt.get(e)??null:null);return o.useEffect(()=>{if(!e){s(null);return}const r=gt.get(e);if(s(r??null),r)return;let a=!1,i=pt.get(e);return i||(i=D.pets.fetchSpritesheet(e).then(l=>{const d=URL.createObjectURL(l);return gt.set(e,d),d}),pt.set(e,i)),i.then(l=>{a||s(l)},()=>{a||s(null),pt.delete(e)}),()=>{a=!0}},[e]),n}const xr=[{state:"idle",row:0,durations:[280,110,110,140,140,320]},{state:"running-right",row:1,durations:[120,120,120,120,120,120,120,220]},{state:"running-left",row:2,durations:[120,120,120,120,120,120,120,220]},{state:"waving",row:3,durations:[140,140,140,280]},{state:"jumping",row:4,durations:[140,140,140,140,280]},{state:"failed",row:5,durations:[140,140,140,140,140,140,140,240]},{state:"waiting",row:6,durations:[150,150,150,150,150,260]},{state:"running",row:7,durations:[120,120,120,120,120,220]},{state:"review",row:8,durations:[150,150,150,150,150,280]}];function br(e,n){if(n)return 3;switch(e){case"working":return 7;case"waiting":return 6;case"pending":return 6;case"error":return 5;case"idle":return 0;case"unknown":return 0;default:return 0}}const Ot=36,vr=Ot/Ln,wr=En*vr;function yr(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Wn({petId:e,status:n,bootstrapping:s=!1,label:r,displayHeight:a=Ot,className:i}){const l=gr(e),d=br(n,s),m=xr[d],f=m.durations.length,[p,u]=o.useState(0),h=a/Ln,x=En*h;return o.useEffect(()=>{if(u(0),!l||f<=1||yr())return;let g,y=0;const w=()=>{y=(y+1)%f,u(y),g=setTimeout(w,m.durations[y])};return g=setTimeout(w,m.durations[0]),()=>clearTimeout(g)},[l,d,f,m]),l?t.jsx("span",{role:"img","aria-label":r,title:r,"data-pet-row":d,"data-pet-col":p,className:["inline-block shrink-0",i].filter(Boolean).join(" "),style:{width:`${x}px`,height:`${a}px`,backgroundImage:`url(${l})`,backgroundRepeat:"no-repeat",backgroundSize:`${ks*h}px ${Ss*h}px`,backgroundPositionX:`${-(p*x)}px`,backgroundPositionY:`${-(d*a)}px`,imageRendering:"pixelated"}}):t.jsx("span",{className:"pill pill-idle",title:r,children:r})}class Xe extends Error{constructor(n){super(n),this.name="PetPackageError"}}const Ve=e=>e.split("/").pop()??e;function jr(e){return typeof e.text=="function"?e.text():new Promise((n,s)=>{const r=new FileReader;r.onerror=()=>s(r.error??new Error("file read failed")),r.onload=()=>n(typeof r.result=="string"?r.result:""),r.readAsText(e)})}async function kr(e){const n=Ft(),s=e.find(d=>Ve(d.name)==="pet.json"||Ve(d.webkitRelativePath||"")==="pet.json");if(!s)throw new Xe(n.pet.missingManifest);let r;try{r=JSON.parse(await jr(s))}catch{throw new Xe(n.pet.manifestParseFailed)}const a=r&&typeof r=="object"&&typeof r.spritesheetPath=="string"?r.spritesheetPath:"",i=a?Ve(a):"",l=(i?e.find(d=>Ve(d.name)===i):void 0)??e.find(d=>/\.(png|webp)$/i.test(d.name));if(!l)throw new Xe(n.pet.missingSpritesheet);return{manifest:r,spritesheet:l}}function Sr({children:e,style:n}){const s=o.useRef(null),[r,a]=o.useState(typeof IntersectionObserver>"u");return o.useEffect(()=>{if(r||typeof IntersectionObserver>"u")return;const i=s.current;if(!i)return;const l=new IntersectionObserver(d=>{d.some(m=>m.isIntersecting)&&(a(!0),l.disconnect())});return l.observe(i),()=>l.disconnect()},[r]),t.jsx("span",{ref:s,className:"inline-block shrink-0",style:n,children:r?e:null})}function Nr({agentId:e,currentPetId:n,onClose:s}){const r=F(),{show:a}=ve(),i=Mt(),{pets:l,loading:d,refresh:m}=pr(),[f,p]=o.useState(!!n),[u,h]=o.useState(n),[x,g]=o.useState(!1),y=o.useRef(null);o.useEffect(()=>{h(n)},[n]),o.useEffect(()=>{const b=y.current;b&&(b.setAttribute("webkitdirectory",""),b.setAttribute("directory",""))},[f]);const w=b=>b instanceof Be||b instanceof Error?b.message:String(b),C=async b=>{if(p(b),!b&&u){g(!0);try{await D.agents.setPet(e,null),h(null),a({kind:"success",title:r.pet.disabledTitle})}catch(T){a({kind:"error",title:r.pet.disableFailedTitle,body:w(T)}),p(!0)}finally{g(!1)}}},P=async b=>{g(!0);try{await D.agents.setPet(e,b),h(b),a({kind:"success",title:r.pet.selectedTitle})}catch(T){a({kind:"error",title:r.pet.selectFailedTitle,body:w(T)})}finally{g(!1)}},k=async(b,T)=>{if(await i({title:r.pet.deleteConfirmTitle(T),body:r.pet.deleteConfirmBody,confirmLabel:r.common.delete})){g(!0);try{await D.pets.remove(b),await m(),a({kind:"success",title:r.pet.deletedTitle(T)})}catch(j){a({kind:"error",title:r.pet.deleteFailedTitle,body:w(j)})}finally{g(!1)}}},N=async b=>{const T=b.target.files?Array.from(b.target.files):[];if(b.target.value="",!!T.length){g(!0);try{const{manifest:j,spritesheet:B}=await kr(T);await D.pets.create(j,B),await m(),a({kind:"success",title:r.pet.uploadedTitle})}catch(j){const B=j instanceof Xe?j.message:w(j);a({kind:"error",title:r.pet.uploadFailedTitle,body:B})}finally{g(!1)}}};return t.jsx(ke,{open:!0,onClose:s,title:"Agent Pet",size:"md",children:t.jsxs("div",{className:"space-y-4",children:[t.jsxs("label",{className:"flex items-center gap-2 text-sm text-og-1000",children:[t.jsx("input",{type:"checkbox",checked:f,disabled:x,onChange:b=>void C(b.target.checked)}),r.pet.enableLabel]}),f?t.jsxs(t.Fragment,{children:[t.jsxs("div",{children:[t.jsx("button",{type:"button",onClick:()=>{var b;return(b=y.current)==null?void 0:b.click()},disabled:x,className:"btn-secondary",children:r.pet.uploadButton}),t.jsx("input",{ref:y,type:"file","aria-label":r.pet.uploadInputAriaLabel,className:"hidden",onChange:b=>void N(b)}),t.jsx("p",{className:"mt-1 text-xs text-og-400",children:r.pet.uploadDirHint})]}),d?t.jsx("p",{className:"text-sm text-og-500",children:r.common.loading}):l.length===0?t.jsx("p",{className:"text-sm text-og-500",children:r.pet.emptyState}):t.jsx("ul",{className:"grid grid-cols-2 gap-2",children:l.map(b=>{const T=b.id===u;return t.jsxs("li",{className:`flex items-center gap-2 rounded-md border p-2 ${T?"border-accent bg-accent-soft/40":"border-hairline"}`,children:[t.jsx(Sr,{style:{width:`${wr}px`,height:`${Ot}px`},children:t.jsx(Wn,{petId:b.id,status:"idle",label:b.displayName})}),t.jsxs("button",{type:"button",onClick:()=>void P(b.id),disabled:x||T,title:b.description||b.displayName,className:"min-w-0 flex-1 truncate text-left text-sm text-og-1000 hover:text-accent-hover disabled:cursor-default",children:[b.displayName,T&&t.jsx("span",{className:"ml-1 text-xs text-accent",children:r.pet.currentMarker})]}),t.jsx("button",{type:"button","aria-label":r.pet.deleteAriaLabel(b.displayName),onClick:()=>void k(b.id,b.displayName),disabled:x,className:"shrink-0 text-xs text-accent hover:underline disabled:opacity-50",children:r.common.delete})]},b.id)})})]}):t.jsx("p",{className:"text-xs text-og-500",children:r.pet.enableHint})]})})}const Tr={unknown:"pill pill-idle",idle:"pill pill-idle",pending:"pill pill-warn",working:"pill pill-live",waiting:"pill pill-review",error:"pill pill-warn"},Rr=72,Cr={absent:"status-dot--warn",unreachable:"status-dot--danger",unknown:"status-dot--warn",starting:"status-dot--info"};function Ar({state:e}){const n=F();if(e==="present")return null;const s=n.agents.sessionStatus[e],r=Cr[e];return t.jsx("span",{role:"img","aria-label":s,title:s,className:`status-dot ml-2 ${r}`})}function qn({agent:e,projectId:n,role:s,runtime:r,onDeleted:a,pendingRestart:i=!1,terminalLoading:l=!1,showTaskBinding:d=!0,terminalMode:m="activity-preview",active:f,onActivate:p}){var Re,zt,Qt,Kt,Vt,Yt,Jt,Xt,Zt;const u=F(),[h,x]=o.useState(!1),[g,y]=o.useState(null),{show:w}=ve(),C=Mt(),{flagDirty:P}=ct(),[k,N]=o.useState(!1),[b,T]=o.useState(null),[j,B]=o.useState(!1),[I,L]=o.useState(!1),[U,H]=o.useState(!1),[M,K]=o.useState(!1),[ee,E]=o.useState(!1),[ne,q]=o.useState(!1),J=(Re=e.binding)==null?void 0:Re.taskId,W=((zt=e.binding)==null?void 0:zt.status)==="awaiting_human",V=(Qt=e.binding)==null?void 0:Qt.needInputAt,ce=V?u.agents.needInputTitle(new Date(V).toLocaleString()):void 0,de=W&&((Kt=e.binding)==null?void 0:Kt.awaitingPhase)==="greeting_failed",_=!!((Vt=e.binding)!=null&&Vt.creationToken)&&!((Yt=e.binding)!=null&&Yt.paneId)&&!W&&e.reason!=="PENDING_HUMAN",ie=_&&e.tmuxSessionStatus!=="present",re=_?{label:u.agents.bootstrappingBadge,cls:"pill pill-review"}:{label:u.agents.runtimeStatus[e.runtimeStatus],cls:Tr[e.runtimeStatus]},ue=_?"starting":e.tmuxSessionStatus,he=m==="activity-preview"&&!ie&&(e.runtimeStatus==="working"||e.runtimeStatus==="pending"),pe=m==="embedded-full",oe=pe&&typeof p=="function",me=oe&&f===!0,A=l||i||ie,c=l?u.agents.agentStatusLoading:i?u.agents.terminalNeedsRestart:u.agents.bootstrappingTerminalDisabled,v=Tn(r),S=async()=>{x(!0),y(null);try{await D.agents.stop(e.id)}catch(G){y(G instanceof Error?G.message:String(G))}finally{x(!1)}},$=async()=>{if(!(!J||!await C({title:u.agents.confirmReReviewTitle,body:u.agents.confirmReReviewBody(J),confirmLabel:u.agents.confirmReReviewLabel}))){H(!0);try{const fe=await D.tasks.review(J);w({kind:"success",title:u.agents.reReviewStarted(fe.reviewRound)})}catch(fe){w({kind:"error",title:u.agents.reReviewStartFailed,body:fe instanceof Error?fe.message:String(fe)})}finally{H(!1)}}},Y=async()=>{E(!0);try{(await D.projects.bootstrap(n)).ok?w({kind:"success",title:u.agents.retryBootstrapSucceededTitle,body:u.agents.retryBootstrapSucceededBody}):w({kind:"warn",title:u.agents.retryBootstrapStillFailingTitle,body:u.agents.retryBootstrapStillFailingBody})}catch(G){w({kind:"error",title:u.agents.retryBootstrapFailedTitle,body:G instanceof Error?G.message:String(G)})}finally{E(!1)}},X=async()=>{if(await C({title:u.agents.resumeConfirmTitle(e.id),body:de?u.agents.resumeGreetingBody:u.agents.resumeDefaultBody,confirmLabel:u.agents.resume})){K(!0);try{if(de){e.tmuxSessionStatus==="present"?await D.projects.restartRepl(n,e.id):await D.projects.retryAgent(n,e.id),w({kind:"success",title:u.agents.regreetingStartedTitle(e.id),body:u.agents.regreetingStartedBody});return}const fe=await D.projects.resumeAgent(n,e.id);w({kind:"success",title:u.agents.resumedTitle(e.id),body:fe.releasedBinding?u.agents.resumedReleasedBody:u.agents.resumedKeptBody})}catch(fe){w({kind:"error",title:u.agents.resumeFailedTitle,body:fe instanceof Error?fe.message:String(fe)})}finally{K(!1)}}},R=async()=>{B(!0);try{await D.agents.compact(e.id),w({kind:"success",title:u.agents.compactSentTitle(e.id)})}catch(G){w({kind:"error",title:u.agents.compactFailedTitle,body:G instanceof Error?G.message:String(G)})}finally{B(!1)}},O=async()=>{if(await C({title:u.agents.clearConfirmTitle(e.id),body:u.agents.clearConfirmBody,confirmLabel:u.agents.clearConfirmLabel})){L(!0);try{await D.agents.clear(e.id),w({kind:"success",title:u.agents.clearSentTitle(e.id)})}catch(G){w({kind:"error",title:u.agents.clearFailedTitle,body:G instanceof Error?G.message:String(G)})}finally{L(!1)}}},Z=async()=>{if(await C({title:u.agents.deleteConfirmTitle(e.id),body:u.agents.deleteConfirmBody,confirmLabel:u.common.delete})){N(!0),T(null);try{const G=await D.projects.deleteAgent(n,e.id);G!=null&&G.restartRequired&&P();const fe=(G==null?void 0:G.removed)??[e.id];if(fe.length>1){const ms=fe.filter(hs=>hs!==e.id).join(", ");w({kind:"warn",title:u.agents.deletedWithPairTitle(e.id),body:u.agents.deletedWithPairBody(ms)})}else w({kind:"success",title:u.agents.deletedTitle(e.id)});a==null||a()}catch(G){T(G instanceof Error?G.message:String(G))}finally{N(!1)}}},z=oe&&!A&&!me,ye=["card relative flex h-full min-w-0 flex-col overflow-visible p-4",me?"ring-2 ring-accent":""].filter(Boolean).join(" "),we=["mb-3 flex items-start justify-between gap-2",e.petId?"pr-28":""].filter(Boolean).join(" "),Le=["mb-2 mt-3 h-80 min-h-0 overflow-hidden border border-hairline bg-surface",z?"cursor-pointer":""].filter(Boolean).join(" "),je=z?()=>p==null?void 0:p():void 0,Se=z?G=>{(G.key==="Enter"||G.key===" ")&&(G.preventDefault(),p==null||p())}:void 0;return t.jsxs("div",{className:ye,"data-agent-card":oe?e.id:void 0,children:[e.petId&&t.jsx("div",{className:"absolute -top-4 right-7 z-10",children:t.jsx(Wn,{petId:e.petId,status:e.runtimeStatus,bootstrapping:_,label:re.label,displayHeight:Rr})}),t.jsxs("div",{className:we,children:[t.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[t.jsx("span",{className:"shrink-0 font-mono text-xs font-medium tracking-[0.05em] text-og-500",children:s==="qa"?"QA":"Dev"}),t.jsx("span",{className:"min-w-0 truncate whitespace-nowrap font-display text-sm font-semibold text-og-1000",title:Rn(e.id,r),children:e.id}),v&&t.jsxs("span",{className:"hidden shrink-0 whitespace-nowrap text-xs text-og-400 sm:inline",title:v,children:["(",v,")"]})]}),t.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-1",children:[W&&t.jsx("span",{className:"pill pill-warn",title:((Jt=e.binding)==null?void 0:Jt.awaitingReason)??u.agents.heldDefaultReason,children:u.agents.heldBadge}),V&&t.jsx("span",{className:"pill pill-warn",title:ce,children:u.agents.needInputBadge}),!e.petId&&t.jsx("span",{className:re.cls,children:re.label}),e.stale&&t.jsx("span",{className:"pill pill-warn",title:e.observedAt?`Last observed at ${e.observedAt}`:void 0,children:u.agents.staleBadge}),t.jsx(Ar,{state:ue})]})]}),ie&&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:u.agents.bootstrappingNotice}),W&&t.jsxs("div",{className:"mb-2 rounded-md border border-accent/25 bg-accent-soft/60 px-2.5 py-2 text-xs text-accent",children:[t.jsx("span",{className:"font-mono",children:(Xt=e.binding)==null?void 0:Xt.awaitingPhase}),((Zt=e.binding)==null?void 0:Zt.awaitingReason)&&t.jsxs("span",{children:[" · ",e.binding.awaitingReason]})]}),!_&&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:u.agents.awaitingHumanIntervention}),t.jsxs("div",{children:[u.agents.openTerminalPrefix,t.jsx($e,{to:`/terminal/${e.id}`,className:"text-accent hover:text-accent-hover underline",children:u.agents.terminal}),u.agents.openTerminalSuffix]})]}),V&&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:u.agents.needInputNoticeTitle}),t.jsxs("div",{children:[u.agents.needInputPrefix,t.jsx($e,{to:`/terminal/${e.id}`,className:"text-accent hover:text-accent-hover underline",children:u.agents.terminal}),u.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:Y,disabled:ee,className:"btn-primary shrink-0",children:ee?u.common.retrying:u.agents.retryBootstrap})]})]}),d&&J&&t.jsxs("div",{className:"mb-2 text-xs text-og-500",children:[u.agents.taskLabel,t.jsx("span",{className:"font-mono text-og-700",children:J})]}),he&&t.jsx("div",{className:"mb-2 overflow-hidden border border-hairline bg-surface",children:t.jsx(He,{agentId:e.id,mode:"preview",maxLines:6,interactive:!1})}),pe&&t.jsx("div",{className:Le,role:z?"button":void 0,tabIndex:z?0:void 0,"aria-label":z?u.agents.activateTerminal(e.id):void 0,onClick:je,onKeyDown:Se,children:A?t.jsx("div",{className:"flex h-full items-center justify-center px-3 text-sm text-og-500",children:c}):oe?me?t.jsx(He,{agentId:e.id,mode:"full",interactive:!0,autoFocus:!0}):t.jsx(He,{agentId:e.id,mode:"preview",interactive:!1}):t.jsx(He,{agentId:e.id,mode:"full",interactive:!0,autoFocus:!1,deferFullUntilFocus:!0})}),i&&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:u.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:[A?t.jsx("span",{className:"shrink-0 cursor-not-allowed text-sm text-og-400",title:c,children:u.agents.terminal}):t.jsx($e,{to:`/terminal/${e.id}`,className:"btn-secondary shrink-0",children:u.agents.terminal}),!i&&e.runtimeStatus==="working"&&t.jsx("button",{onClick:S,disabled:h,className:"btn-ghost shrink-0",children:h?u.agents.stopping:u.agents.stop}),W&&t.jsx("button",{type:"button",onClick:X,disabled:M,title:de?u.agents.resumeGreetingButtonTitle:u.agents.resumeDefaultButtonTitle,className:"btn-primary shrink-0",children:M?u.agents.resuming:u.agents.resume})]}),t.jsx(Et,{ariaLabel:u.agents.actionsMenu(e.id),className:"shrink-0",placement:"up",autoFocusFirstItem:!0,disabled:k,children:G=>t.jsxs(t.Fragment,{children:[t.jsx(xe,{onClick:()=>{G(),q(!0)},disabled:j||I||k,title:u.agents.agentPetMenuItemTitle,children:"Agent Pet"}),t.jsx(xe,{onClick:()=>{G(),R()},disabled:j||I||k,title:u.agents.compactMenuItemTitle,children:j?u.agents.compacting:u.agents.compact}),t.jsx(xe,{onClick:()=>{G(),O()},disabled:I||j||k,title:u.agents.clearMenuItemTitle,children:I?u.agents.clearing:u.agents.clear}),!i&&J&&s==="dev"&&t.jsx(xe,{onClick:()=>{G(),$()},disabled:U||k,title:u.agents.callReviewMenuItemTitle(J),children:U?u.agents.callingReview:u.agents.callReview}),t.jsx(xe,{onClick:()=>{G(),Z()},disabled:k||j||I,children:k?u.common.deleting:u.common.delete})]})})]}),g&&t.jsx("div",{className:"mt-1.5 break-words text-xs text-accent",children:g}),b&&t.jsx("div",{className:"mt-1.5 break-words text-xs text-accent",children:b}),ne&&t.jsx(Nr,{agentId:e.id,currentPetId:e.petId??null,onClose:()=>q(!1)})]})}const xt="baxian:terminal-activated";function zn({coordinateAcrossInstances:e=!0}={}){const n=o.useId(),[s,r]=o.useState(null);o.useEffect(()=>{if(s===null)return;const i=m=>{m.composedPath().some(u=>u instanceof Element&&u.hasAttribute("data-agent-card"))||r(null)},l=m=>{if(m.key!=="Escape")return;const f=document.activeElement;f instanceof Element&&f.closest("[data-agent-card]")||r(null)},d=m=>{const f=m.detail;(f==null?void 0:f.ownerId)!==n&&r(null)};return document.addEventListener("click",i),document.addEventListener("keydown",l),e&&document.addEventListener(xt,d),()=>{document.removeEventListener("click",i),document.removeEventListener("keydown",l),e&&document.removeEventListener(xt,d)}},[s,e,n]);const a=o.useCallback(i=>{r(i),e&&document.dispatchEvent(new CustomEvent(xt,{detail:{ownerId:n}}))},[e,n]);return{activeAgentId:s,activateAgentCard:a}}function Pr(e){return Ft().status[e]??e}const Qn={pending:"pill",in_progress:"pill pill-live",review:"pill pill-review",fixing:"pill pill-warn","spec-ready":"pill pill-warn",approved:"pill pill-live","merge-ready":"pill pill-warn",ready:"pill pill-warn",merged:"pill pill-live",done:"pill pill-live",failed:"pill pill-danger",max_rounds:"pill pill-warn",cancelled:"pill"},Er={pending:"bg-og-300",in_progress:"bg-success",review:"bg-accent",fixing:"bg-warn","spec-ready":"bg-warn",approved:"bg-success","merge-ready":"bg-warn",ready:"bg-warn",merged:"bg-success",done:"bg-success",failed:"bg-danger",max_rounds:"bg-warn",cancelled:"bg-og-300"};function Lr({status:e}){return t.jsx("span",{role:"img","aria-label":e,title:e,className:`inline-block h-2 w-2 shrink-0 rounded-full ${Er[e]??"bg-og-300"}`})}function Ht(e){if(!e)return"";const n=e.match(/^task-(\d+)$/);return n?n[1]:e}function bt(e,n=!0){if(e==null)return"";const s=String(e).trim();if(!s)return"";const r=new Date(s.replace(/^(\d{4}-\d{2}-\d{2}) /,"$1T"));if(Number.isNaN(r.getTime()))return s;const a=d=>String(d).padStart(2,"0"),i=`${r.getFullYear()}-${a(r.getMonth()+1)}-${a(r.getDate())}`,l=`${a(r.getHours())}:${a(r.getMinutes())}`;return n?`${i} ${l}:${a(r.getSeconds())}`:`${i} ${l}`}function Ee(e,n){return`/project/${encodeURIComponent(e)}/task/${encodeURIComponent(n)}`}function Kn({group:e,projectId:n,agentsById:s,agentsLoaded:r,agentsError:a=!1,tasks:i,onDeleted:l,terminalMode:d="activity-preview"}){var j,B,I;const m=F(),f=e.find(L=>L.role==="dev")??e[0],p=e.find(L=>L.role==="qa"),u=i.filter(L=>$r(L,f==null?void 0:f.id,p==null?void 0:p.id)),h=f?i.filter(L=>Ir(L,n,f.id)).sort((L,U)=>L.createdAt.localeCompare(U.createdAt)):[],x=f?s.get(f.id):void 0,g=!!x&&x.runtimeStatus==="idle"&&((j=x.binding)==null?void 0:j.status)!=="awaiting_human"&&!((B=x.binding)!=null&&B.creationToken)&&!((I=x.binding)!=null&&I.taskId),y=`Agent group ${e.map(L=>L.id).join(" / ")}`,w=be(),C=d==="embedded-full",{activeAgentId:P,activateAgentCard:k}=zn({coordinateAcrossInstances:C}),N=d==="embedded-full"?e.length<=1?"lg:grid-cols-1":e.length===2?"lg:grid-cols-2":e.length===3?"lg:grid-cols-3":"lg:grid-cols-4":"sm:grid-cols-2",b=!!f&&h.length>0,T=u.length===0&&!b;return t.jsxs("div",{role:"group","aria-label":y,className:"min-w-0",children:[b&&f&&t.jsx(Dr,{tasks:h,devId:f.id,dispatchReady:g,label:y}),u.length>0&&t.jsx("div",{className:"card mb-2 max-h-28 overflow-y-auto divide-y divide-hairline",children:u.map(L=>{const U=L.phase==="spec"?L.specReviewRound??0:L.reviewRound;return t.jsxs("button",{type:"button",onClick:()=>w(Ee(L.projectId,L.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:L.id,children:Ht(L.id)}),t.jsx("span",{className:"truncate text-og-1000",children:L.title})]}),t.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[t.jsx("span",{className:"shrink-0 text-xs text-og-500",children:m.agents.round(U)}),t.jsx("span",{className:`${Qn[L.status]} shrink-0`,title:L.status,children:m.status[L.status]??L.status})]})]},L.id)})}),T&&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(y),children:m.agents.noActiveTask}),t.jsx("div",{className:`grid grid-cols-1 ${N} gap-4`,children:e.map(L=>{const U=s.get(L.id),H=U??{id:L.id,projectId:n,runtimeStatus:"unknown",tmuxSessionStatus:"unknown",stale:!0};return t.jsx(qn,{agent:H,projectId:n,role:L.role,runtime:L.runtime,pendingRestart:r&&!U,terminalLoading:!r&&!U&&!a,onDeleted:l,showTaskBinding:!1,terminalMode:d,...C?{active:P===L.id,onActivate:()=>k(L.id)}:{}},L.id)})})]})}function Dr({tasks:e,devId:n,dispatchReady:s,label:r}){const a=F(),{show:i}=ve(),l=be(),[d,m]=o.useState(null),f=async p=>{m(p);try{await D.tasks.dispatch(p,{agentId:n}),i({kind:"success",title:a.agents.taskHandedTo(p,n)})}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 u=p.preferredAgentId==="",h=d!==null;return t.jsxs("div",{className:"flex items-center gap-3 px-3 py-2 text-sm",children:[t.jsxs("button",{type:"button",onClick:()=>l(Ee(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:Ht(p.id)}),t.jsx("span",{className:"truncate text-og-1000",title:p.title,children:p.title}),u&&t.jsx("span",{className:"pill shrink-0",children:a.agents.unassigned})]}),t.jsx("button",{type:"button",onClick:()=>void f(p.id),disabled:!s||h,title:s?a.agents.handToAndStart(n):a.agents.devAgentUnavailable,className:"shrink-0 text-sm font-medium text-accent transition-colors hover:text-accent-hover disabled:opacity-50 disabled:cursor-not-allowed",children:d===p.id?a.agents.starting:a.agents.start})]},p.id)})})}function $r(e,n,s){return!(!n||!An.has(e.status)||!(e.agentId===n||e.preferredAgentId===n)||s&&e.qaAgentId&&e.qaAgentId!==s)}function Ir(e,n,s){return e.projectId!==n||e.status!=="pending"?!1:e.preferredAgentId===s||e.preferredAgentId===""}const le="w-full rounded-md border border-og-100 bg-surface px-2.5 py-1.5 text-sm text-og-800 placeholder:text-og-400 focus:border-accent focus:outline-none focus:ring-[3px] focus:ring-accent-soft disabled:cursor-not-allowed disabled:opacity-50",te="mb-1.5 block text-xs font-medium text-og-700",st="mt-1 text-xs text-accent",Ze="mt-1 text-xs text-og-500",Ne="h-3.5 w-3.5 accent-accent",Br=/^[a-z][a-z0-9-]{1,31}$/,Fr=[/^https?:\/\/[^/\s]+\/[^\s]+$/,/^ssh:\/\/[^/\s]+\/[^\s]+$/,/^[^@/\s]+@[^:/\s]+:[^\s]+$/,/^[^/\s:@]+\/[^/\s]+$/];function Mr({open:e,onClose:n,onCreated:s}){const r=F(),[a,i]=o.useState(""),[l,d]=o.useState(""),[m,f]=o.useState(null),[p,u]=o.useState("human"),[h,x]=o.useState(""),[g,y]=o.useState(!1),[w,C]=o.useState(null),[P,k]=o.useState({}),[N,b]=o.useState(new Set),T=o.useRef(0),{show:j}=ve(),{flagDirty:B}=ct();o.useEffect(()=>{if(!e)return;T.current+=1;const H=T.current;i(""),d(""),f(null),u("human"),x(""),C(null),k({}),b(new Set),D.config.get().then(M=>{H===T.current&&b(new Set(M.project.map(K=>K.id)))}).catch(()=>{})},[e]);const I=()=>{g||n()},L=()=>{const H={};return a?Br.test(a)?N.has(a)&&(H.id=r.createProject.idTakenError):H.id=r.common.idFormatError:H.id=r.createProject.required,l?Fr.some(M=>M.test(l.trim()))||(H.repo=r.createProject.repoFormatError):H.repo=r.createProject.required,k(H),Object.keys(H).length===0},U=async H=>{if(H.preventDefault(),!!L()){y(!0),C(null);try{const M=await D.projects.create({id:a,repo:l.trim(),merge:m,...p?{specApproval:p}:{},...h?{review:{mode:h}}:{}});M.restartRequired&&B(),j({kind:"success",title:r.createProject.createdToastTitle(M.project.id)}),s(M.project.id)}catch(M){C(M instanceof Error?M.message:String(M))}finally{y(!1)}}};return t.jsx(ke,{open:e,onClose:I,title:r.createProject.title,size:"md",footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:I,disabled:g,className:"btn-secondary",children:r.common.cancel}),t.jsx("button",{type:"submit",form:"create-project-form",disabled:g,className:"btn-primary",children:g?r.common.creating:r.common.create})]}),children:t.jsxs("form",{id:"create-project-form",onSubmit:U,className:"space-y-3",children:[w&&t.jsx("div",{className:"rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-sm text-accent",children:w}),t.jsxs("div",{children:[t.jsx("label",{className:te,htmlFor:"proj-id",children:r.createProject.idLabel}),t.jsx("input",{id:"proj-id",type:"text",value:a,onChange:H=>i(H.target.value),className:le,placeholder:"baxian",disabled:g}),P.id&&t.jsx("div",{className:st,children:P.id})]}),t.jsxs("div",{children:[t.jsx("label",{className:te,htmlFor:"proj-repo",children:r.createProject.repoLabel}),t.jsx("input",{id:"proj-repo",type:"text",value:l,onChange:H=>d(H.target.value),className:le,placeholder:"https://github.com/baxian-ai/baxian.git",disabled:g}),P.repo&&t.jsx("div",{className:st,children:P.repo})]}),t.jsxs("div",{children:[t.jsx("span",{className:te,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:()=>f(null),disabled:g,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:()=>f("auto"),disabled:g,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:te,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:()=>u("human"),disabled:g,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:()=>u(null),disabled:g,className:"h-3.5 w-3.5 accent-accent"}),t.jsx("span",{className:"text-sm text-og-800",children:r.createProject.specApprovalAutoLabel})]})]}),t.jsxs("div",{children:[t.jsx("span",{className:te,children:r.createProject.reviewModeLabel}),t.jsxs("label",{className:"mb-1 flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"review-mode",checked:h==="",onChange:()=>x(""),disabled:g,className:"h-3.5 w-3.5 accent-accent"}),t.jsx("span",{className:"text-sm text-og-800",children:r.createProject.reviewModeFollowGlobalLabel})]}),t.jsxs("label",{className:"mb-1 flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"review-mode",checked:h==="github",onChange:()=>x("github"),disabled:g,className:"h-3.5 w-3.5 accent-accent"}),t.jsx("span",{className:"text-sm text-og-800",children:"GitHub PR"})]}),t.jsxs("label",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"review-mode",checked:h==="server",onChange:()=>x("server"),disabled:g,className:"h-3.5 w-3.5 accent-accent"}),t.jsx("span",{className:"text-sm text-og-800",children:"Server"})]})]})]})})}const an=/^[a-z][a-z0-9-]{1,31}$/,Or=500,on={id:"",role:"dev",pairWith:"",mode:"local",host:"",runtime:"",workdir:"",yolo:!0,model:"",addDirs:""};function Hr(e){return e.alias?e.alias:`${e.user?`${e.user}@`:""}${e.hostname}${e.port!=null?`:${e.port}`:""}`}function Vn({open:e,onClose:n,projectId:s,onCreated:r}){var c;const a=F(),[i,l]=o.useState(on),[d,m]=o.useState(null),[f,p]=o.useState([]),[u,h]=o.useState(new Set),[x,g]=o.useState(null),[y,w]=o.useState(!1),[C,P]=o.useState(!1),[k,N]=o.useState(null),[b,T]=o.useState(!1),[j,B]=o.useState(null),[I,L]=o.useState(!1),U=o.useRef(null),H=o.useRef(null),M=o.useRef(0),K=o.useRef(0),{show:ee}=ve(),{flagDirty:E}=ct();o.useEffect(()=>{if(!e)return;K.current+=1;const v=K.current;l(on),m(null),p([]),h(new Set),g(null),w(!1),P(!1),N(null),M.current+=1,B(null),L(!1),D.config.get().then(S=>{if(v!==K.current)return;const $=S.project.find(X=>X.id===s)??null;m($),p(S.host??[]);const Y=new Set;S.project.forEach(X=>X.agent.forEach(R=>R.forEach(O=>Y.add(O.id)))),h(Y)}).catch(()=>{})},[e,s]);const ne=()=>{b||n()},q=o.useCallback(()=>{U.current&&U.current.abort();const v=new AbortController;U.current=v,w(!0),B(null);const S=i.mode==="remote"?{hostId:i.host}:{};D.agents.probe(i.mode,S,{signal:v.signal}).then($=>{v.signal.aborted||(g($),B(null))}).catch($=>{v.signal.aborted||(g(null),B($ instanceof Error?$.message:String($)))}).finally(()=>{U.current===v&&w(!1)})},[i.mode,i.host]);o.useEffect(()=>{if(e&&(g(null),N(null),P(!1),M.current+=1,U.current&&U.current.abort(),!(i.mode==="remote"&&!i.host)))return H.current&&clearTimeout(H.current),H.current=setTimeout(q,Or),()=>{H.current&&clearTimeout(H.current)}},[e,i.mode,i.host,q]),o.useEffect(()=>{e||U.current&&U.current.abort()},[e]),o.useEffect(()=>()=>{U.current&&U.current.abort(),H.current&&clearTimeout(H.current)},[]);const J=()=>{if(C)return;const v=M.current;P(!0),N(null);const S=i.mode==="remote"?{hostId:i.host}:{};D.agents.installTmux(i.mode,S).then($=>{M.current===v&&(N({ok:$.ok,message:$.message}),P(!1),$.ok&&q())}).catch($=>{M.current===v&&(N({ok:!1,message:$ instanceof Error?$.message:String($)}),P(!1))})},W=(d==null?void 0:d.agent.filter(v=>v.length===1&&v[0].role==="dev").map(v=>v[0]))??[],V=W.length>0,ce=an.test(i.id)&&!u.has(i.id),de=i.mode==="local"||i.mode==="remote"&&i.host!=="",_=i.runtime!==""&&(i.runtime==="claude-code"?!!(x!=null&&x.runtimes["claude-code"].ok):!!(x!=null&&x.runtimes.codex.ok)),ie=!!(x!=null&&x.tmux.ok),re=i.mode==="local"||!!((c=x==null?void 0:x.ssh)!=null&&c.ok),ue=i.role==="dev"||i.role==="qa"&&i.pairWith!=="",he=!b&&ce&&de&&ue&&_&&ie&&re,pe=async v=>{if(v.preventDefault(),!!he){T(!0),B(null);try{const S=i.addDirs.split(`
6
+ `).map(X=>X.trim()).filter(X=>X.length>0),$={id:i.id,role:i.role,runtime:i.runtime,mode:i.mode,...i.mode==="remote"?{host:i.host}:{},...i.workdir?{workdir:i.workdir}:{},yolo:i.yolo,...i.model.trim()?{model:i.model.trim()}:{},...S.length>0?{addDirs:S}:{},...i.role==="qa"?{pairWith:i.pairWith}:{}},Y=await D.projects.addAgent(s,$);Y.restartRequired&&E(),ee({kind:"success",title:a.createAgent.addedToastTitle(Y.agent.id,s)}),r(),n()}catch(S){B(S instanceof Error?S.message:String(S))}finally{T(!1)}}},oe=({rt:v})=>{if(i.mode==="remote"&&!i.host)return t.jsx("span",{className:"ml-2 text-xs text-og-400",children:a.createAgent.selectHostFirstHint});if(y)return t.jsx("span",{className:"ml-2 text-xs text-og-400",children:a.createAgent.probingLabel});if(!x)return t.jsx("span",{className:"ml-2 text-xs text-og-400",children:"?"});const $=x.runtimes[v];return $.ok?t.jsxs("span",{className:"ml-2 text-xs text-probe-ok",children:["✓ ",$.path??""]}):t.jsxs("span",{className:"ml-2 text-xs text-accent",title:$.message,children:["⨯ ",$.message]})},me=()=>{var S;if(i.mode==="remote"&&!i.host)return null;if(y&&!C)return t.jsx("div",{className:"text-xs text-og-400",children:a.createAgent.tmuxProbingLabel});if(!x)return null;if(x.tmux.ok)return t.jsxs("div",{className:"text-xs text-probe-ok",children:["tmux: ✓ ",x.tmux.path??""]});const v=i.mode==="local"||!!((S=x.ssh)!=null&&S.ok);return t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"text-xs text-accent",children:["tmux: ⨯ ",x.tmux.message,v&&t.jsx("button",{type:"button",onClick:J,className:"ml-2 text-accent underline transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",disabled:C||b,children:C?a.common.installing:a.common.oneClickInstall})]}),C&&t.jsx("div",{className:"text-xs text-og-500",children:a.common.installingTmuxNotice}),!C&&k&&t.jsxs("div",{className:`break-all text-xs ${k.ok?"text-probe-ok":"text-accent"}`,children:[k.ok?"✓ ":"⨯ ",k.message]})]})},A=()=>i.mode!=="remote"||!i.host||!(x!=null&&x.ssh)?null:x.ssh.ok?t.jsxs("div",{className:"text-xs text-probe-ok",children:["SSH: ✓ ",x.ssh.message]}):t.jsxs("div",{className:"text-xs text-accent",children:["SSH: ⨯ ",x.ssh.message]});return t.jsx(ke,{open:e,onClose:ne,title:a.createAgent.modalTitle(s),size:"lg",footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:ne,disabled:b,className:"btn-secondary",children:a.common.cancel}),t.jsx("button",{type:"submit",form:"create-agent-form",disabled:!he,className:"btn-primary",children:b?a.createAgent.submitting:a.createAgent.submitLabel})]}),children:t.jsxs("form",{id:"create-agent-form",onSubmit:pe,className:"space-y-3",children:[j&&t.jsx("div",{className:"rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-sm text-accent",children:j}),t.jsxs("div",{children:[t.jsx("label",{className:te,htmlFor:"agent-id",children:"Agent ID"}),t.jsx("input",{id:"agent-id",type:"text",value:i.id,onChange:v=>l({...i,id:v.target.value}),className:le,placeholder:a.createAgent.idPlaceholder(s,i.role),disabled:b}),i.id&&!an.test(i.id)&&t.jsx("div",{className:st,children:a.common.idFormatError}),i.id&&u.has(i.id)&&t.jsx("div",{className:st,children:a.createAgent.idTakenGlobalError})]}),t.jsxs("div",{children:[t.jsx("span",{className:te,children:a.createAgent.roleLabel}),t.jsxs("label",{className:"mr-4 inline-flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"role",checked:i.role==="dev",className:Ne,onChange:()=>l({...i,role:"dev",pairWith:""}),disabled:b}),t.jsx("span",{className:"text-sm text-og-800",children:"Dev agent"})]}),t.jsxs("label",{className:"inline-flex items-center gap-2",title:V?"":a.createAgent.createDevFirstHint,children:[t.jsx("input",{type:"radio",name:"role",checked:i.role==="qa",className:Ne,onChange:()=>l({...i,role:"qa"}),disabled:b||!V}),t.jsx("span",{className:`text-sm ${V?"text-og-800":"text-og-400"}`,children:"QA agent"})]})]}),i.role==="qa"&&t.jsxs("div",{children:[t.jsx("label",{className:te,htmlFor:"pair-with",children:a.createAgent.pairWithLabel}),t.jsxs("select",{id:"pair-with",value:i.pairWith,onChange:v=>l({...i,pairWith:v.target.value}),className:le,disabled:b,children:[t.jsx("option",{value:"",children:a.createAgent.pairWithPlaceholder}),W.map(v=>t.jsx("option",{value:v.id,children:a.createAgent.pairOptionLabel(v.id,v.mode)},v.id))]})]}),t.jsxs("div",{children:[t.jsx("span",{className:te,children:a.createAgent.modeLabel}),t.jsxs("label",{className:"mr-4 inline-flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"mode",checked:i.mode==="local",className:Ne,onChange:()=>l({...i,mode:"local",host:""}),disabled:b}),t.jsx("span",{className:"text-sm text-og-800",children:a.createAgent.localModeLabel})]}),t.jsxs("label",{className:"inline-flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"mode",checked:i.mode==="remote",className:Ne,onChange:()=>l({...i,mode:"remote"}),disabled:b}),t.jsx("span",{className:"text-sm text-og-800",children:a.createAgent.remoteModeLabel})]})]}),i.mode==="remote"&&t.jsxs("div",{children:[t.jsx("label",{className:te,htmlFor:"host",children:"Host"}),f.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:v=>l({...i,host:v.target.value}),className:le,disabled:b,children:[t.jsx("option",{value:"",children:a.createAgent.selectHostPlaceholder}),f.map(v=>t.jsx("option",{value:v.id,children:Hr(v)},v.id))]}),t.jsx("div",{className:Ze,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:q,className:"text-xs text-accent transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",disabled:b||y||i.mode==="remote"&&!i.host,children:a.createAgent.reprobeButton})]}),t.jsxs("label",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"runtime",checked:i.runtime==="claude-code",className:Ne,onChange:()=>l({...i,runtime:"claude-code"}),disabled:b||(x?!x.runtimes["claude-code"].ok:!1)}),t.jsx("span",{className:"text-sm text-og-800",children:"Claude Code"}),t.jsx(oe,{rt:"claude-code"})]}),t.jsxs("label",{className:"mt-1 flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"runtime",checked:i.runtime==="codex",className:Ne,onChange:()=>l({...i,runtime:"codex"}),disabled:b||(x?!x.runtimes.codex.ok:!1)}),t.jsx("span",{className:"text-sm text-og-800",children:"Codex"}),t.jsx(oe,{rt:"codex"})]}),t.jsx("div",{className:"mt-2",children:t.jsx(me,{})}),t.jsx("div",{children:t.jsx(A,{})})]}),t.jsxs("div",{children:[t.jsxs("button",{type:"button",onClick:()=>L(v=>!v),"aria-expanded":I,"aria-controls":I?"advanced-options":void 0,className:"flex w-full items-center justify-between rounded-md px-1 py-1.5 text-left text-xs font-medium text-og-700 transition-colors hover:bg-og-50",children:[t.jsx("span",{children:a.createAgent.advancedOptionsLabel}),t.jsx("span",{className:"text-og-400",children:I?a.createAgent.collapseLabel:a.createAgent.expandLabel})]}),I&&t.jsxs("div",{id:"advanced-options",className:"mt-3 space-y-3",children:[t.jsxs("div",{children:[t.jsx("label",{className:te,htmlFor:"workdir",children:a.createAgent.workdirLabel}),t.jsx("input",{id:"workdir",type:"text",value:i.workdir,onChange:v=>l({...i,workdir:v.target.value}),className:le,placeholder:a.createAgent.workdirPlaceholder,disabled:b})]}),t.jsxs("div",{children:[t.jsx("label",{className:te,htmlFor:"model",children:a.createAgent.modelLabel}),t.jsx("input",{id:"model",type:"text",value:i.model,onChange:v=>l({...i,model:v.target.value}),className:le,placeholder:i.runtime==="codex"?a.createAgent.modelPlaceholderCodex:a.createAgent.modelPlaceholderOther,disabled:b}),t.jsx("div",{className:Ze,children:a.createAgent.modelHint})]}),t.jsxs("div",{children:[t.jsx("label",{className:te,htmlFor:"addDirs",children:a.createAgent.addDirsLabel}),t.jsx("textarea",{id:"addDirs",value:i.addDirs,onChange:v=>l({...i,addDirs:v.target.value}),className:`${le} font-mono text-xs`,rows:3,placeholder:a.createAgent.addDirsPlaceholder,disabled:b}),t.jsx("div",{className:Ze,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:v=>l({...i,yolo:v.target.checked}),disabled:b}),t.jsxs("div",{className:"text-sm text-og-800",children:[t.jsx("div",{className:"font-medium",children:a.createAgent.yoloTitle}),t.jsxs("div",{className:"mt-1 text-xs text-accent",children:[a.createAgent.yoloBodyLead,t.jsx("code",{children:"--permission-mode bypassPermissions"}),a.createAgent.yoloBodyMid,t.jsx("code",{children:"--dangerously-bypass-approvals-and-sandbox"}),a.createAgent.yoloBodyTrail]})]})]})})]})})}const ln=200,cn=16e3,_r="baxian.draft.createTask:";function Tt(e){return`${_r}${e??"*"}`}function dn(e){try{const n=localStorage.getItem(e);if(!n)return null;const s=JSON.parse(n);if(!s||typeof s!="object")return null;const r=s,a=typeof r.title=="string"?r.title:"",i=typeof r.description=="string"?r.description:"",l=typeof r.projectId=="string"?r.projectId:"",d=typeof r.preferredAgentId=="string"?r.preferredAgentId:"",m=typeof r.updatedAt=="number"?r.updatedAt:void 0;return!a.trim()&&!i.trim()?null:{title:a,description:i,projectId:l,preferredAgentId:d,updatedAt:m}}catch{return null}}function Ur(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 un(e){try{localStorage.removeItem(e)}catch{}}function Gr(e){const n=Tt(e),s=dn(n);if(!e)return s;const r=Tt(void 0),a=dn(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 mn="mt-1 text-right text-xs text-og-400",Wr=Math.floor(lt/1024/1024);function _t(e){const n=F(),s=e.mode==="edit",{show:r}=ve(),a=s?e.task.projectId:e.projectId,i=s?e.task.title:"",l=s?e.task.description:"",d=s?e.task.preferredAgentId:"",[m,f]=o.useState([]),[p,u]=o.useState([]),[h,x]=o.useState(a??""),[g,y]=o.useState(d),[w,C]=o.useState(i),[P,k]=o.useState(l),[N,b]=o.useState([]),T=o.useRef(null),[j,B]=o.useState(!1),[I,L]=o.useState(null),[U,H]=o.useState(!1),M=o.useRef(0),K=o.useRef(0),ee=o.useRef(0),E=o.useRef(new Set),ne=s?null:Tt(a);o.useEffect(()=>{if(!e.open)return;M.current+=1,K.current+=1;const R=M.current;f([]),u([]),E.current=new Set;const O=ne?Gr(a):null;O&&E.current.add(O.projectId),x(a??(O==null?void 0:O.projectId)??""),y((O==null?void 0:O.preferredAgentId)||d),C((O==null?void 0:O.title)||i),k((O==null?void 0:O.description)||l),H(O!==null),L(null),B(!1),b([]),Promise.all([D.projects.list(),D.agents.list()]).then(([Z,z])=>{R===M.current&&(f(Z),u(z))}).catch(Z=>{R===M.current&&L(Z instanceof Error?Z.message:String(Z))})},[e.open,a,i,l,d,ne]),o.useEffect(()=>{if(!(!e.open||!ne)){if(ee.current!==K.current){ee.current=K.current;return}Ur(ne,{title:w,description:P,projectId:h,preferredAgentId:g})}},[e.open,ne,w,P,h,g]);const q=o.useMemo(()=>m.find(R=>R.id===h)??null,[m,h]),J=o.useMemo(()=>q?q.agent.flat().filter(R=>R.role==="dev"):[],[q]),W=o.useMemo(()=>new Set(p.map(R=>R.id)),[p]),V=o.useMemo(()=>J.filter(R=>W.has(R.id)),[J,W]),ce=o.useMemo(()=>J.filter(R=>!W.has(R.id)),[J,W]);o.useEffect(()=>{s||q!==null&&g!==""&&!V.find(R=>R.id===g)&&y("")},[q,V,g,s]),o.useEffect(()=>{s||q&&V.length!==0&&(E.current.has(q.id)||(E.current.add(q.id),y(R=>R===""?V[0].id:R)))},[s,q,V]);const de=!s||V.find(R=>R.id===g),_=s&&!de&&!!g,ie=_&&ce.some(R=>R.id===g),re=ie?n.createTask.noDevPendingRestartHint(g):_?n.createTask.noDevNotInRuntimeHint(g):!h||V.length>0?null:ce.length>0?n.createTask.noDevGlobalPendingRestartHint:null,ue=w.trim(),he=P.trim(),oe=!!h&&ue.length>0&&!j,me=()=>{j||e.onClose()},A=()=>{ne&&(un(ne),x(a??""),y(d),C(i),k(l),L(null),H(!1))},c=async R=>{var O,Z;if(R.preventDefault(),!!oe){B(!0),L(null);try{if(e.mode==="edit"){const z=await D.tasks.update(e.task.id,{title:ue,description:he,preferredAgentId:g});r({kind:"success",title:n.createTask.updatedToastTitle}),(O=e.onUpdated)==null||O.call(e,z),e.onClose()}else{const z=N.length?await Promise.all(N.map(async we=>({dataBase64:await kt(we),filename:we.name}))):void 0,ye=await D.tasks.create({projectId:h,title:ue,description:he,preferredAgentId:g,...z?{images:z}:{}});ne&&un(ne),r({kind:"success",title:n.createTask.createdToastTitle}),(Z=e.onCreated)==null||Z.call(e,ye),e.onClose()}}catch(z){L(z instanceof Error?z.message:String(z))}finally{B(!1)}}},v=R=>{const O=Array.from(R.target.files??[]);if(R.target.value="",O.length===0)return;const Z=O.filter(z=>z.size>lt?(r({kind:"error",title:n.createTask.imageTooLargeToastTitle,body:n.createTask.imageTooLargeToastBody(z.name,Wr)}),!1):!0);b(z=>(z.length+Z.length>ze&&r({kind:"warn",title:n.createTask.tooManyImagesToastTitle(ze)}),[...z,...Z].slice(0,ze)))},S=R=>b(O=>O.filter((Z,z)=>z!==R)),$=s?n.createTask.titleEdit:n.createTask.titleCreate,Y=s?j?n.common.saving:n.common.save:j?n.common.creating:n.common.create,X=!s&&!a;return t.jsx(ke,{open:e.open,onClose:me,title:$,size:"md",dismissOnBackdrop:!1,footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:me,disabled:j,className:"btn-secondary",children:n.common.cancel}),t.jsx("button",{type:"submit",form:"create-task-form",disabled:!oe,className:"btn-primary",children:Y})]}),children:t.jsxs("form",{id:"create-task-form",onSubmit:c,className:"space-y-3",children:[!s&&U&&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:A,className:"shrink-0 underline hover:text-accent-hover",children:n.createTask.discardDraftButton})]}),I&&t.jsx("div",{className:"rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-sm text-accent",children:I}),X&&t.jsxs("div",{children:[t.jsx("label",{className:te,htmlFor:"task-project",children:"Project"}),t.jsxs("select",{id:"task-project",value:h,onChange:R=>x(R.target.value),className:le,disabled:j,required:!0,children:[t.jsx("option",{value:"",disabled:!0,children:n.createTask.selectProjectPlaceholder}),m.map(R=>t.jsx("option",{value:R.id,children:R.id},R.id))]})]}),t.jsxs("div",{children:[t.jsx("label",{className:te,htmlFor:"task-dev",children:"Dev agent"}),t.jsxs("select",{id:"task-dev",value:g,onChange:R=>y(R.target.value),className:le,disabled:j,children:[t.jsx("option",{value:"",children:n.createTask.notAssignedOption}),_&&t.jsxs("option",{value:g,children:[g," ",ie?n.createTask.pendingRestartSuffix:n.createTask.notInRuntimeSuffix]}),V.map(R=>t.jsx("option",{value:R.id,children:R.id},R.id))]}),re&&t.jsx("div",{className:"mt-1 text-xs text-accent",children:re})]}),t.jsxs("div",{children:[t.jsx("label",{className:te,htmlFor:"task-title",children:"Title"}),t.jsx("input",{id:"task-title",type:"text",value:w,onChange:R=>C(R.target.value),maxLength:ln,className:le,placeholder:n.createTask.titlePlaceholder,disabled:j,required:!0}),t.jsxs("div",{className:mn,children:[w.length," / ",ln]})]}),t.jsxs("div",{children:[t.jsx("label",{className:te,htmlFor:"task-description",children:n.createTask.descriptionLabel}),t.jsx("textarea",{id:"task-description",value:P,onChange:R=>k(R.target.value),maxLength:cn,rows:8,className:`${le} font-mono text-xs`,placeholder:n.createTask.descriptionPlaceholder,disabled:j}),t.jsxs("div",{className:mn,children:[P.length," / ",cn]})]}),!s&&t.jsxs("div",{children:[t.jsx("label",{className:te,children:n.createTask.imagesLabel}),t.jsx("button",{type:"button",onClick:()=>{var R;return(R=T.current)==null?void 0:R.click()},disabled:j||N.length>=ze,className:"btn-secondary",children:n.createTask.addImagesButton}),t.jsx("input",{ref:T,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:v}),N.length>0&&t.jsx("ul",{className:"mt-2 space-y-1",children:N.map((R,O)=>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:R.name,className:"truncate text-xs text-og-700",children:R.name}),t.jsx("button",{type:"button","aria-label":n.createTask.removeImageAriaLabel(R.name),onClick:()=>S(O),disabled:j,className:"ml-2 shrink-0 text-og-400 transition-colors",children:"✕"})]},`${R.name}-${O}`))})]})]})})}const hn="***",vt={hostname:"",port:"",alias:"",user:"",password:""};function qr(e){return e.alias?e.alias:`${e.user?`${e.user}@`:""}${e.hostname}${e.port!=null?`:${e.port}`:""}`}function zr({open:e,onClose:n}){var me;const s=F(),[r,a]=o.useState([]),[i,l]=o.useState("list"),[d,m]=o.useState(null),[f,p]=o.useState(null),[u,h]=o.useState(!1),[x,g]=o.useState(!1),[y,w]=o.useState(vt),[C,P]=o.useState(null),[k,N]=o.useState(!1),[b,T]=o.useState(!1),[j,B]=o.useState(null),[I,L]=o.useState(!1),[U,H]=o.useState(null),M=o.useRef(0),K=o.useRef(null),{show:ee}=ve(),E=o.useCallback(()=>{D.hosts.list().then(a).catch(A=>P(A instanceof Error?A.message:String(A)))},[]);o.useEffect(()=>{if(!e){K.current&&K.current.abort();return}l("list"),m(null),p(null),w(vt),P(null),E()},[e,E]),o.useEffect(()=>{M.current+=1,K.current&&K.current.abort(),T(!1),B(null),L(!1),H(null)},[y.hostname,y.user,y.port,y.password,x,i]),o.useEffect(()=>()=>{K.current&&K.current.abort()},[]);const ne=()=>{m(null),p(null),h(!1),g(!1),w(vt),P(null),l("form")},q=A=>{m(A.id??null),p(A),h(A.password===hn),g(!1),w({hostname:A.hostname,port:A.port!=null?String(A.port):"",alias:A.alias??"",user:A.user??"",password:""}),P(null),l("form")},J=()=>{const A={hostname:y.hostname.trim()};return d?(A.port=y.port.trim()?Number(y.port):null,A.alias=y.alias.trim(),A.user=y.user.trim()):(y.port.trim()&&(A.port=Number(y.port)),y.alias.trim()&&(A.alias=y.alias.trim()),y.user.trim()&&(A.user=y.user.trim())),d&&x?A.password="":y.password&&(A.password=y.password),A},W=y.port.trim(),V=W===""||/^\d+$/.test(W)&&Number(W)>0&&Number(W)<=65535,ce=y.hostname.trim().length>0&&V,de=!!f&&y.hostname.trim()===f.hostname&&y.user.trim()===(f.user??"")&&y.port.trim()===(f.port!=null?String(f.port):""),_=()=>d&&de&&!y.password&&!x?{hostId:d}:{host:{hostname:y.hostname.trim(),...y.user.trim()?{user:y.user.trim()}:{},...W?{port:Number(W)}:{},...!x&&y.password?{password:y.password}:{}}},ie=async()=>{if(!ce||b)return;K.current&&K.current.abort();const A=new AbortController;K.current=A;const c=M.current;T(!0),B(null),H(null),P(null);try{const v=await D.agents.probe("remote",_(),{signal:A.signal});if(A.signal.aborted||M.current!==c)return;B(v)}catch(v){if(A.signal.aborted||M.current!==c)return;P(v instanceof Error?v.message:String(v))}finally{M.current===c&&T(!1)}},re=async()=>{if(I)return;const A=M.current;L(!0),H(null),P(null);try{const c=await D.agents.installTmux("remote",_());if(M.current!==A)return;H({ok:c.ok,message:c.message}),B(v=>v&&{...v,tmux:c.tmux})}catch(c){if(M.current!==A)return;P(c instanceof Error?c.message:String(c))}finally{M.current===A&&L(!1)}},ue=async A=>{if(A.preventDefault(),!(!ce||k)){N(!0),P(null);try{if(d)await D.hosts.update(d,J()),ee({kind:"success",title:s.hostMgmt.updatedToastTitle(d)});else{const c=await D.hosts.create(J());ee({kind:"success",title:s.hostMgmt.createdToastTitle(c.host.id)})}E(),l("list")}catch(c){P(c instanceof Error?c.message:String(c))}finally{N(!1)}}},he=async A=>{P(null);try{await D.hosts.delete(A.id),ee({kind:"success",title:s.hostMgmt.deletedToastTitle(A.id)}),E()}catch(c){P(c instanceof Error?c.message:String(c))}},pe=t.jsx("button",{type:"button",onClick:n,className:"btn-secondary",children:s.common.close}),oe=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:()=>l("list"),disabled:k,className:"btn-secondary",children:s.common.backText}),t.jsx("button",{type:"submit",form:"host-form",disabled:!ce||k,className:"btn-primary",children:k?s.common.saving:s.common.save})]});return t.jsxs(ke,{open:e,onClose:n,title:s.hostMgmt.title,size:"md",footer:i==="list"?pe:oe,children:[C&&t.jsx("div",{className:"mb-3 rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-sm text-accent",children:C}),i==="list"?t.jsxs("div",{className:"space-y-3",children:[r.length===0?t.jsx("p",{className:"text-sm text-og-500",children:s.hostMgmt.emptyState}):t.jsx("ul",{className:"space-y-1.5",children:r.map(A=>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:qr(A)}),t.jsxs("div",{className:"truncate text-xs text-og-500",children:[(A.user?`${A.user}@`:"")+A.hostname,A.port!=null?`:${A.port}`:"",A.password===hn?s.hostMgmt.passwordSavedIndicator:""]})]}),t.jsxs("div",{className:"flex shrink-0 gap-2",children:[t.jsx("button",{type:"button",onClick:()=>q(A),className:"text-xs text-accent transition-colors hover:text-accent-hover",children:s.common.edit}),t.jsx("button",{type:"button",onClick:()=>he(A),className:"text-xs text-accent transition-colors hover:opacity-80",children:s.common.delete})]})]},A.id))}),t.jsx("button",{type:"button",onClick:ne,className:"btn-secondary w-full",children:s.hostMgmt.addHostButton})]}):t.jsxs("form",{id:"host-form",onSubmit:ue,className:"space-y-3",children:[t.jsxs("div",{children:[t.jsx("label",{className:te,htmlFor:"host-hostname",children:s.hostMgmt.addressLabel}),t.jsx("input",{id:"host-hostname",type:"text",value:y.hostname,onChange:A=>w({...y,hostname:A.target.value}),className:le,placeholder:"remote.example.com",disabled:k})]}),t.jsxs("div",{children:[t.jsx("label",{className:te,htmlFor:"host-port",children:s.hostMgmt.portLabel}),t.jsx("input",{id:"host-port",type:"text",inputMode:"numeric",value:y.port,onChange:A=>w({...y,port:A.target.value}),className:le,placeholder:"22",disabled:k}),y.port.trim()!==""&&!V&&t.jsx("div",{className:"mt-1 text-xs text-accent",children:s.hostMgmt.portRangeError})]}),t.jsxs("div",{children:[t.jsx("label",{className:te,htmlFor:"host-alias",children:s.hostMgmt.aliasLabel}),t.jsx("input",{id:"host-alias",type:"text",value:y.alias,onChange:A=>w({...y,alias:A.target.value}),className:le,placeholder:"Prod worker",disabled:k})]}),t.jsxs("div",{children:[t.jsx("label",{className:te,htmlFor:"host-user",children:s.hostMgmt.userLabel}),t.jsx("input",{id:"host-user",type:"text",value:y.user,onChange:A=>w({...y,user:A.target.value}),className:le,placeholder:s.hostMgmt.userPlaceholder,disabled:k})]}),t.jsxs("div",{children:[t.jsx("label",{className:te,htmlFor:"host-password",children:s.hostMgmt.passwordLabel}),t.jsx("input",{id:"host-password",type:"password",value:x?"":y.password,onChange:A=>w({...y,password:A.target.value}),className:le,placeholder:u?s.hostMgmt.passwordPlaceholderSet:s.hostMgmt.passwordPlaceholderUnset,disabled:k||x,autoComplete:"new-password"}),d&&u&&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:x,onChange:A=>g(A.target.checked),disabled:k}),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:ie,disabled:!ce||b||k||I,className:"text-xs text-accent transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",children:b?s.hostMgmt.testing:s.hostMgmt.testConnection}),(j==null?void 0:j.ssh)&&t.jsxs("div",{className:`text-xs ${j.ssh.ok?"text-og-800":"text-accent"}`,children:["SSH: ",j.ssh.ok?"✓":"⨯"," ",j.ssh.message]}),j&&(j.tmux.ok?t.jsxs("div",{className:"text-xs text-og-800",children:["tmux: ✓ ",j.tmux.path??""]}):t.jsxs("div",{className:"text-xs text-accent",children:["tmux: ⨯ ",j.tmux.message,((me=j.ssh)==null?void 0:me.ok)&&t.jsx("button",{type:"button",onClick:re,disabled:I||k,className:"ml-2 text-accent underline transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",children:I?s.common.installing:s.common.oneClickInstall})]})),I&&t.jsx("div",{className:"text-xs text-og-500",children:s.common.installingTmuxNotice}),!I&&U&&t.jsxs("div",{className:`break-all text-xs ${U.ok?"text-og-800":"text-accent"}`,children:[U.ok?"✓ ":"⨯ ",U.message]})]})]})]})}const Ut="baxian.taskNotifications.enabled";function Gt(){if(typeof window>"u")return null;const e=window.Notification;return typeof e=="function"?e:null}function Ye(){const e=Gt();return e?e.permission:"unsupported"}function wt(){try{return localStorage.getItem(Ut)!=="0"}catch{return!0}}function Je(e){try{localStorage.setItem(Ut,e?"1":"0")}catch{}}const Yn=o.createContext(null);function Qr({children:e}){const[n,s]=o.useState(Ye),[r,a]=o.useState(wt),[i,l]=o.useState(!1),d=o.useRef(!1),m=o.useRef(0);o.useEffect(()=>{const u=()=>{s(Ye()),d.current||a(wt())},h=x=>{if(x.key!==null&&x.key!==Ut)return;s(Ye());const g=x.key===null?wt():x.newValue!=="0";g||(m.current+=1),a(g)};return window.addEventListener("focus",u),window.addEventListener("storage",h),()=>{window.removeEventListener("focus",u),window.removeEventListener("storage",h)}},[]);const f=o.useCallback(()=>{a(!0);const u=Gt();if(!u){Je(!0);return}if(u.permission!=="default"){s(u.permission),Je(!0);return}if(d.current)return;d.current=!0,l(!0);const h=m.current;u.requestPermission().then(s).catch(x=>{console.warn("[task-notifications] permission request failed:",x),s(Ye())}).finally(()=>{m.current===h&&Je(!0),d.current=!1,l(!1)})},[]),p=o.useCallback(()=>{m.current+=1,a(!1),Je(!1)},[]);return t.jsx(Yn.Provider,{value:{permission:n,preferenceEnabled:r,enabled:n==="granted"&&r,requesting:i,enable:f,disable:p},children:e})}function Jn(){const e=o.useContext(Yn);if(!e)throw new Error("useTaskNotifications must be used inside TaskNotificationsProvider");return e}const Kr=[{value:"en-US",label:"English"},{value:"zh-CN",label:"简体中文"}];function Vr({open:e,onClose:n}){const s=F(),{locale:r,saving:a,setLocale:i}=On(),{show:l}=ve(),d=async m=>{try{await i(m)}catch(f){const p=f instanceof Error?f.message:String(f);l({kind:"error",title:s.settings.languageSaveFailed(p)})}};return t.jsx(ke,{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:te,children:s.settings.language}),t.jsx("div",{className:"flex gap-4",children:Kr.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:Ne,checked:r===m.value,disabled:a,onChange:()=>void d(m.value)}),m.label]},m.value))})]}),t.jsx(Yr,{})]})})}function Yr(){const e=F(),{permission:n,enabled:s,requesting:r,enable:a,disable:i}=Jn();if(n==="unsupported")return null;const l=n==="denied";return t.jsxs("div",{children:[t.jsxs("label",{className:"inline-flex items-center gap-2 text-sm text-og-800",children:[t.jsx("input",{type:"checkbox",className:Ne,checked:s,disabled:l||r,onChange:()=>s?i():a()}),e.settings.taskNotifications]}),t.jsx("p",{className:Ze,children:l?e.settings.taskNotificationsDenied:e.settings.taskNotificationsHint})]})}const Xn="topbar-actions";function fn(){return typeof document>"u"?null:document.getElementById(Xn)}function Zn({children:e}){const[n,s]=o.useState(fn);return o.useEffect(()=>{n||s(fn())},[n]),n?gs.createPortal(e,n):null}function Jr(e){return Array.from(new TextEncoder().encode(e)).map(n=>n.toString(16).padStart(2,"0")).join("")}function Xr(){return`${location.protocol==="https:"?"wss":"ws"}://${location.host}/api/realtime`}const Zr=(e,n)=>n&&n.length>0?new WebSocket(e,n):new WebSocket(e);class ea{constructor(n={}){se(this,"wsUrl");se(this,"wsFactory");se(this,"tokenProvider");se(this,"ws",null);se(this,"topics",new Map);se(this,"cache",new Map);se(this,"outbox",[]);se(this,"reconnectScheduler");se(this,"explicitlyClosed",!1);this.wsUrl=n.wsUrl??Xr(),this.wsFactory=n.wsFactory??Zr,this.tokenProvider=n.tokenProvider??Dt,this.reconnectScheduler=new Gn({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.${Jr(n)}`]:void 0;let r;try{r=this.wsFactory(this.wsUrl,s)}catch(i){console.warn("[events-client] WebSocket constructor threw:",i),this.broadcastConnectionError({code:"connection_failed",message:i instanceof Error?i.message:"WebSocket constructor threw"}),this.scheduleReconnect();return}this.ws=r;let a=!1;r.onopen=()=>{if(r!==this.ws)return;a=!0,this.reconnectScheduler.reset();for(const l of this.topics.keys())try{r.send(JSON.stringify({op:"subscribe",topic:l}))}catch(d){console.warn("[events-client] resubscribe send failed:",d)}const i=this.outbox;this.outbox=[];for(const l of i)if(!(l.op==="subscribe"||l.op==="unsubscribe"))try{r.send(JSON.stringify(l))}catch(d){console.warn("[events-client] outbox flush failed:",d)}},r.onmessage=i=>{if(r!==this.ws)return;let l;try{const d=typeof i.data=="string"?i.data:String(i.data);l=JSON.parse(d)}catch{return}this.handleMessage(l)},r.onclose=()=>{r===this.ws&&(this.ws=null,!this.explicitlyClosed&&(a||this.broadcastConnectionError({code:"connection_failed",message:"WebSocket failed to connect (auth, network, or proxy issue)"}),this.topics.size!==0&&this.scheduleReconnect()))},r.onerror=()=>{}}scheduleReconnect(){this.reconnectScheduler.schedule()}broadcastConnectionError(n){for(const s of this.topics.values())for(const r of[...s.error])try{r(n)}catch(a){console.error("[events-client] error handler threw on connection error:",a)}}wsSendOrQueue(n){if(this.ws&&this.ws.readyState===WebSocket.OPEN)try{this.ws.send(JSON.stringify(n));return}catch(s){console.warn("[events-client] send failed, will queue:",s)}this.outbox.push(n)}handleMessage(n){switch(n.type){case"data":{const s=this.topics.get(n.topic);if(this.cache.set(n.topic,n.data),!s)return;for(const r of[...s.data])try{r(n.data)}catch(a){console.error(`[events-client] handler threw on ${n.topic}:`,a)}break}case"error":{const s={code:n.code,message:n.message};if(n.topic){const r=this.topics.get(n.topic);if(r)for(const a of[...r.error])try{a(s)}catch(i){console.error(`[events-client] error handler threw on ${n.topic}:`,i)}}else console.warn("[events-client] connection-level error:",n.code,n.message);break}}}}let yt=null;function dt(){return yt||(yt=new ea),yt}function Wt(){const[e,n]=o.useState(null),[s,r]=o.useState(!1),[a,i]=o.useState(null);return o.useEffect(()=>dt().subscribe("agents",d=>{i(null),n(d),r(!0)},d=>i(d)),[]),{data:e,loaded:s,error:a}}function qt(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),dt().subscribe(`task:${e}`,m=>{l(null),s(m),a(!0)},m=>l(m))),[e]),{data:n,loaded:r,error:i}}function es(e){const[n,s]=o.useState(null),[r,a]=o.useState(!1),[i,l]=o.useState(null);return o.useEffect(()=>{if(!e){s(null),a(!1),l(null);return}s(null),a(!1),l(null);let d=!1,m=!1,f=!1;const p=dt().subscribe(`project-tasks:${e}`,u=>{d||(m=!0,l(null),s(u),a(!0))},u=>{d||(l(u),!(m||f)&&(f=!0,D.tasks.list(e).then(h=>{d||m||(s(h),a(!0))},h=>{console.warn(`[useProjectTasks] REST fallback failed for ${e}:`,h)})))});return()=>{d=!0,p()}},[e]),{data:n,loaded:r,error:i}}let rt=null,Te=null,at=null,_e=0;const Rt=new Set;function ts(){Rt.forEach(e=>e())}async function ta(){const e=_e;try{const n=await D.projects.list();if(e!==_e)return;rt=n,at=null}catch(n){if(e!==_e)return;at=n instanceof Error?n.message:String(n)}finally{e===_e&&(Te=null,ts())}}function Ct(){return Te||(Te=ta(),Te)}function na(){_e+=1,rt=null,Te=null,at=null,ts()}typeof window<"u"&&window.addEventListener(et,na);async function sa(){const e=Te!==null;await Ct(),e&&await Ct()}function qe(){const[,e]=o.useState(0);return o.useEffect(()=>{const n=()=>e(s=>s+1);return Rt.add(n),rt===null&&!Te&&Ct(),()=>{Rt.delete(n)}},[]),{projects:rt,error:at,refresh:sa}}function ra(){const e=F(),n=be(),{projects:s,error:r,refresh:a}=qe(),i=s??[],l=s!==null,[d,m]=o.useState(!1),[f,p]=o.useState(!1),[u,h]=o.useState(!1),[x,g]=o.useState(!1),[y,w]=o.useState({kind:"closed"}),{data:C,loaded:P,error:k}=Wt(),N=(k==null?void 0:k.message)??null,b=new Map((C??[]).map(I=>[I.id,I])),T=r??N,j=i.length===0,B=t.jsx("button",{type:"button",onClick:()=>p(!0),disabled:j,"aria-describedby":j?"create-task-hint":void 0,className:"btn-ghost",children:e.dashboard.newTask});return t.jsxs("div",{children:[t.jsxs(Zn,{children:[j?t.jsx("span",{className:"inline-flex",title:e.dashboard.createProjectFirst,children:B}):B,j&&t.jsx("span",{id:"create-task-hint",className:"sr-only",children:e.dashboard.createProjectFirst}),t.jsx(Et,{ariaLabel:e.dashboard.moreActions,children:I=>t.jsxs(t.Fragment,{children:[t.jsx(xe,{onClick:()=>{I(),m(!0)},children:e.dashboard.newProject}),t.jsx(xe,{onClick:()=>{I(),h(!0)},children:e.dashboard.manageHosts}),t.jsx(xe,{onClick:()=>{I(),g(!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(I=>t.jsx(aa,{project:I,agentsById:b,agentsLoaded:P,agentsError:!!k,onAgentDeleted:a},I.id)),t.jsx(Mr,{open:d,onClose:()=>m(!1),onCreated:I=>{m(!1),a(),w({kind:"asking",projectId:I})}}),t.jsx(zr,{open:u,onClose:()=>h(!1)}),t.jsx(ke,{open:y.kind==="asking",onClose:()=>w({kind:"closed"}),title:e.dashboard.projectCreatedTitle,size:"sm",footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:()=>w({kind:"closed"}),className:"btn-secondary",children:e.dashboard.later}),t.jsx("button",{type:"button",onClick:()=>{y.kind==="asking"&&w({kind:"addingAgent",projectId:y.projectId})},className:"btn-primary",children:e.dashboard.continueAddingAgent})]}),children:t.jsx("p",{className:"text-sm text-og-700",children:e.dashboard.addAgentNowOrLater})}),y.kind==="addingAgent"&&t.jsx(Vn,{open:!0,projectId:y.projectId,onClose:()=>w({kind:"closed"}),onCreated:()=>{a()}}),t.jsx(_t,{open:f,onClose:()=>p(!1),onCreated:I=>n(Ee(I.projectId,I.id))}),t.jsx(Vr,{open:x,onClose:()=>g(!1)})]})}function aa({project:e,agentsById:n,agentsLoaded:s,agentsError:r,onAgentDeleted:a}){const i=F(),{data:l,error:d}=es(e.id),m=l??[],f=(d==null?void 0:d.message)??null;return t.jsxs("div",{className:"mb-10",children:[t.jsxs("div",{className:"mb-3 -mx-2 flex items-baseline gap-x-3 gap-y-1 px-2 py-1",children:[t.jsx("h2",{className:"min-w-0 truncate font-display text-sm font-semibold tracking-tight text-og-1000",title:e.id,children:t.jsx($e,{to:`/project/${e.id}`,className:"hover:text-accent-hover",children:e.id})}),t.jsx("span",{className:"hidden min-w-0 truncate font-mono text-xs text-og-500 sm:inline-block",title:e.repo,children:e.repo}),t.jsx($e,{to:`/project/${e.id}`,className:"ml-auto text-sm text-accent hover:text-accent-hover","aria-label":i.dashboard.detailsAriaLabel(e.id),children:i.dashboard.detailsLink})]}),f&&t.jsx("div",{className:"mb-2 text-xs text-accent",children:i.dashboard.tasksLoadFailed(f)}),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,u)=>t.jsx(Kn,{group:p,projectId:e.id,agentsById:n,agentsLoaded:s,agentsError:r,tasks:m,onDeleted:a,terminalMode:"embedded-full"},p.map(h=>h.id).join(":")||u))})]})}const ns="baxian.taskPanel.doneOpen";function ia(){try{return localStorage.getItem(ns)==="1"}catch{return!1}}function it(e){const n=e.match(/^task-(\d+)$/);return n?parseInt(n[1],10):Number.NaN}function oa(e,n){const s=it(e.id),r=it(n.id);return Number.isNaN(s)||Number.isNaN(r)?e.id.localeCompare(n.id):s-r}function la(e,n){const s=(n.updatedAt??"").localeCompare(e.updatedAt??"");if(s!==0)return s;const r=it(e.id),a=it(n.id);return Number.isNaN(r)||Number.isNaN(a)?n.id.localeCompare(e.id):a-r}function pn(e,n){const[s,r]=o.useState(ut);o.useEffect(()=>r(ut),[n]);const a=e.slice(0,s),i=e.length>a.length;return{items:a,hasMore:i,loadMore:()=>r(d=>d+ut),total:e.length}}function ca(e){const[n,s]=o.useState([]),[r,a]=o.useState(!1),[i,l]=o.useState(!1),[d,m]=o.useState(!1),[f,p]=o.useState(null),u=o.useRef(0),h=o.useRef(0),x=o.useCallback(g=>{const y=++u.current,w=g==="first"?0:h.current;l(!0),p(null),D.tasks.page(e,{category:"done",offset:w}).then(C=>{u.current===y&&(s(P=>g==="first"?C.tasks:[...P,...C.tasks]),a(C.hasMore),h.current=C.nextOffset,m(!0),l(!1))},C=>{u.current===y&&(p(C instanceof Error?C.message:String(C)),l(!1))})},[e]);return o.useEffect(()=>{u.current+=1,h.current=0,s([]),a(!1),m(!1),p(null),l(!1)},[e]),{items:n,hasMore:r,loading:i,loaded:d,error:f,load:x}}function da({projectId:e,openTasks:n,className:s=""}){const r=F(),a=o.useMemo(()=>n.filter(h=>An.has(h.status)).sort(la),[n]),i=o.useMemo(()=>n.filter(h=>h.status==="pending").sort(oa),[n]),l=pn(a,e),d=pn(i,e),m=ca(e),[f,p]=o.useState(ia);o.useEffect(()=>{try{localStorage.setItem(ns,f?"1":"0")}catch{}},[f]),o.useEffect(()=>{f&&m.load("first")},[f,m.load]);const u=()=>p(h=>!h);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(gn,{title:"IN PROGRESS",section:l,emptyHint:r.taskPanel.emptyInProgress}),t.jsx(gn,{title:"PENDING",section:d,emptyHint:r.taskPanel.emptyPending}),t.jsxs("div",{children:[t.jsxs("button",{type:"button",onClick:u,"aria-expanded":f,className:"flex w-full items-center justify-between px-3 py-2 text-left text-xs font-normal uppercase tracking-[0.05em] text-og-500 transition-colors hover:bg-og-50/40",children:[t.jsx("span",{children:"DONE"}),t.jsx("span",{className:"font-normal normal-case text-accent",children:f?r.taskPanel.collapse:r.taskPanel.view})]}),f&&t.jsx(ua,{state:m})]})]})})}function gn({title:e,section:n,emptyHint:s}){const r=F();return t.jsxs("section",{"aria-label":e,className:"border-b border-hairline",children:[t.jsxs("div",{className:"px-3 py-2 text-xs font-normal uppercase tracking-[0.05em] text-og-500",children:[e," ",t.jsxs("span",{className:"text-og-400",children:["(",n.total,")"]})]}),n.items.length===0?t.jsx("div",{className:"px-3 pb-3 text-xs text-og-400",children:s}):t.jsxs("div",{className:"divide-y divide-hairline",children:[n.items.map(a=>t.jsx(ss,{task:a},a.id)),n.hasMore&&t.jsx("button",{type:"button",onClick:n.loadMore,className:"w-full px-3 py-2 text-center text-xs text-accent transition-colors hover:bg-og-50/40",children:r.taskPanel.loadMore})]})]})}function ua({state:e}){const n=F(),s=e.loaded&&!e.error&&e.items.length===0;return t.jsxs("div",{className:"divide-y divide-hairline",children:[e.items.map(r=>t.jsx(ss,{task:r},r.id)),e.error&&t.jsx("div",{className:"px-3 py-2 text-xs text-accent",children:n.common.loadFailed(e.error)}),s&&t.jsx("div",{className:"px-3 pb-3 pt-1 text-xs text-og-400",children:n.taskPanel.emptyDone}),e.loading&&e.items.length===0&&t.jsx("div",{className:"px-3 py-3 text-center text-xs text-og-400",children:n.common.loading}),e.hasMore&&t.jsx("button",{type:"button",onClick:()=>e.load("more"),disabled:e.loading,className:"w-full px-3 py-2 text-center text-xs text-accent transition-colors hover:bg-og-50/40 disabled:opacity-50",children:e.loading?n.common.loading:n.taskPanel.loadMore})]})}function ma(e){const[n,s]=o.useState(!1);return o.useEffect(()=>{function r(){if(e.status!=="review"||!e.reviewDispatchedAt||!e.qaAgentId){s(!1);return}s(Date.now()-Date.parse(e.reviewDispatchedAt)>=Pn)}r();const a=setInterval(r,3e4);return()=>clearInterval(a)},[e.status,e.reviewDispatchedAt,e.qaAgentId]),n}function ss({task:e}){const n=F(),s=be(),r=e.phase==="spec"?e.specReviewRound??0:e.reviewRound,a=ma(e);return t.jsxs("button",{type:"button",onClick:()=>s(Ee(e.projectId,e.id)),className:"flex w-full items-center gap-2 px-3 py-2 text-left text-sm transition-colors hover:bg-og-50/60",children:[t.jsx("span",{className:"shrink-0 font-mono text-xs text-og-500",title:e.id,children:Ht(e.id)}),t.jsx("span",{className:"min-w-0 flex-1 truncate text-og-1000",title:e.title,children:e.title}),e.phase==="spec"&&t.jsx("span",{className:"pill pill-review shrink-0",children:"spec"}),a&&t.jsx("span",{className:"pill pill-warn shrink-0",title:"Review verdict missing",children:"!"}),t.jsxs("span",{"aria-label":n.agents.round(r),className:"shrink-0 text-xs text-og-400",children:["R",r]}),t.jsx(Lr,{status:e.status})]})}const ha=[],rs="baxian.taskPanel.open";function fa(){try{return localStorage.getItem(rs)!=="0"}catch{return!0}}function pa(){const{id:e}=We(),n=be(),s=F(),{show:r}=ve(),{refresh:a}=qe(),[i,l]=o.useState(null),[d,m]=o.useState(null),[f,p]=o.useState(!1),[u,h]=o.useState(!1),x=o.useRef(null),[g,y]=o.useState(fa),[w,C]=o.useState(!1),[P,k]=o.useState(""),[N,b]=o.useState(!1),[T,j]=o.useState(null),B=o.useRef(0),{data:I,loaded:L,error:U}=Wt(),{data:H,error:M}=es(e),K=(U==null?void 0:U.message)??null,ee=(M==null?void 0:M.message)??null,E=H??ha,ne=new Map((I??[]).map(_=>[_.id,_])),q=d??K??ee,J=o.useCallback(async _=>{const ie=++B.current;try{const re=await D.projects.get(_);if(ie!==B.current)return;l(re),m(null)}catch(re){if(ie!==B.current)return;m(re instanceof Error?re.message:String(re))}},[]);o.useEffect(()=>{e&&(l(null),m(null),J(e))},[e,J]),o.useEffect(()=>{w||(k(""),j(null))},[w]),o.useEffect(()=>{try{localStorage.setItem(rs,g?"1":"0")}catch{}},[g]);const W=(i==null?void 0:i.agent.flat().length)??0,V=W===0,ce=!!i&&P.trim()===i.id,de=async()=>{if(!(!i||!ce||N)){b(!0),j(null);try{await D.projects.delete(i.id),await a(),r({kind:"success",title:s.projectPage.deletedToastTitle(i.id)}),C(!1),n("/")}catch(_){j(_ instanceof Error?_.message:String(_))}finally{b(!1)}}};return i?t.jsxs("div",{children:[t.jsxs(Zn,{children:[t.jsx("button",{type:"button",onClick:()=>h(!0),className:"btn-ghost",children:s.projectPage.newTaskButton}),t.jsx(Et,{ariaLabel:s.projectPage.menuAriaLabel(i.id),menuClassName:"min-w-[180px]",triggerRef:x,children:_=>t.jsxs(t.Fragment,{children:[!g&&t.jsx(xe,{onClick:()=>{_(),y(!0)},children:s.projectPage.showTaskPanel}),t.jsx(xe,{onClick:()=>{_(),p(!0)},children:s.projectPage.addAgent}),t.jsx("div",{role:"none",className:"my-1 border-t border-hairline"}),t.jsx(xe,{onClick:()=>{_(),C(!0)},disabled:!V,title:V?void 0:s.projectPage.deleteAgentsFirstHint(W),children:s.projectPage.deleteProjectMenuItem})]})})]}),q&&t.jsx("div",{className:"mb-4 text-sm text-accent",children:s.common.loadFailed(q)}),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((_,ie)=>t.jsx(Kn,{group:_,projectId:i.id,agentsById:ne,agentsLoaded:L,agentsError:!!U,tasks:E,onDeleted:()=>{J(i.id)},terminalMode:"embedded-full"},_.map(re=>re.id).join(":")||ie))})]}),g&&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 _;y(!1),(_=x.current)==null||_.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(da,{projectId:i.id,openTasks:E})]})]}),t.jsx(Vn,{open:f,projectId:i.id,onClose:()=>p(!1),onCreated:()=>{J(i.id)}}),t.jsx(_t,{open:u,projectId:i.id,onClose:()=>h(!1),onCreated:_=>n(Ee(_.projectId,_.id))}),t.jsx(ke,{open:w,onClose:()=>{N||C(!1)},title:s.projectPage.deleteModalTitle,size:"sm",footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:()=>C(!1),disabled:N,className:"btn-secondary",children:s.common.cancel}),t.jsx("button",{type:"button",onClick:()=>void de(),disabled:!ce||N,className:"btn-primary",children:N?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:P,onChange:_=>k(_.target.value),placeholder:i.id,autoComplete:"off",autoCorrect:"off",spellCheck:!1,disabled:N,"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})]})})]}):d?t.jsx("div",{className:"text-sm text-accent",children:s.common.loadFailed(d)}):t.jsx("div",{className:"text-sm text-og-500",children:s.common.loading})}function as(e,n){const[s,r]=o.useState(null),[a,i]=o.useState(!1),[l,d]=o.useState(null),m=o.useRef(e);return o.useEffect(()=>{let f=!0;return m.current!==e&&(m.current=e,r(null),i(!1)),d(null),D.tasks.reviews(e).then(p=>{f&&(r(p),i(!0))}).catch(p=>{f&&(d(p instanceof Error?p.message:String(p)),r([]),i(!0))}),()=>{f=!1}},[e,n]),{rounds:s,loaded:a,error:l}}const is={approve:"pill pill-live","request-changes":"pill pill-warn",comment:"pill"};function os(e){const n=[];let s=[];for(const r of e)r.kind==="review"?(n.push({items:s,review:r}),s=[]):s.push(r);return s.length>0&&n.push({items:s}),n}function ot(e,n){return`${e.kind}-${e.id||e.commitSha||e.createdAt||e.body||n}`}function ls(e,n){return e.review?`round-${ot(e.review,n)}`:`round-in-progress-${e.items[0]?ot(e.items[0],n):n}`}function cs(e){return`${e.reviewRound}:${e.latestHeadSha??""}:${e.status}:${e.reviewDispatchedAt??""}:${e.prFeedbackReceivedAt??""}`}function ds(e,n){const[s,r]=o.useState(null),[a,i]=o.useState(!1),[l,d]=o.useState(null),m=o.useRef(e),f=o.useRef(n),p=o.useRef(0),u=o.useRef(!1);return o.useEffect(()=>{if(m.current!==e)m.current=e,u.current=!1,r(null),i(!1);else if(f.current===void 0&&n!==void 0&&u.current){f.current=n;return}f.current=n;const x=++p.current;d(null),D.tasks.githubReview(e).then(g=>{p.current===x&&(u.current=g.available===!0&&!g.error,r(g),i(!0))}).catch(g=>{p.current===x&&(u.current=!1,d(g instanceof Error?g.message:String(g)),r(null),i(!0))})},[e,n]),{data:s,loaded:a,error:l}}function Ue({role:e,label:n,summary:s,badge:r,onClick:a}){const i=F();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 ga(e){return{"server-mode":e.githubReview.reasonServerModeEntry,"no-pr":e.githubReview.reasonNoPr,"not-github":e.githubReview.reasonNotGithub}}function xa(e){return(e==null?void 0:e.trim().split(`
7
+ `,1)[0])??""}function ba(e){var n;return(n=e.commitSha)==null?void 0:n.slice(0,9)}function va(e){if(!(e.kind!=="review-comment"||!e.path))return e.line!==void 0?`${e.path}:${e.line}`:e.path}function wa(e,n){return n.bodyTruncated?e.githubReview.truncatedSuffix:""}function ya(e,n){const s=xa(n.body),r=wa(e,n);if(n.kind==="commit"){const a=ba(n);return a&&s?`${a} ${s}${r}`:`${s||a||e.githubReview.commitFallback}${r}`}if(n.kind==="review-comment"){const a=va(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.githubReview.inlineComment}${r}`}return n.kind==="issue-comment"?n.author&&s?`${n.author} · ${s}${r}`:`${s||n.author||e.githubReview.comment}${r}`:`${s||e.githubReview.noReviewBodyFallback}${r}`}function ja(e,n){return n.kind==="commit"?e.review.submitCodeChanges:n.kind==="review"?e.review.reviewTurnLabel:n.kind==="review-comment"?n.inReplyTo?e.review.responseTurnLabel:e.githubReview.inlineComment:e.githubReview.comment}function ka(e){return e.kind==="commit"||e.kind==="issue-comment"||e.inReplyTo?"dev":"qa"}function Sa({task:e}){const n=F(),s=be(),r=cs(e),{data:a,loaded:i,error:l}=ds(e.id,r);function d(){s(`/tasks/${encodeURIComponent(e.id)}/github-review`)}if(l)return t.jsx(Oe,{children:t.jsx("div",{className:"text-sm text-accent",children:n.review.loadFailed(l)})});if(!i)return t.jsx(Oe,{children:t.jsx("div",{className:"text-sm text-og-400",children:n.review.loadingRecords})});if(!(a!=null&&a.available)){const f=ga(n);return t.jsx(Oe,{children:t.jsx("div",{className:"text-sm text-og-400",children:f[(a==null?void 0:a.reason)??"no-pr"]??f["no-pr"]})})}if(a.items.length===0)return t.jsx(Oe,{children:a.error?t.jsx("div",{className:"text-sm text-accent",children:n.githubReview.fetchFailed(a.error)}):t.jsx("div",{className:"text-sm text-og-400",children:n.review.notStarted})});const m=os(a.items);return t.jsxs(Oe,{children:[a.error&&t.jsx("div",{className:"text-xs text-accent",children:n.githubReview.partialFetchFailed(a.error)}),m.map((f,p)=>t.jsx(Na,{round:f,index:p,onOpen:d},ls(f,String(p))))]})}function Oe({children:e}){const n=F();return t.jsxs("div",{children:[t.jsx("div",{className:"mb-1.5 text-xs text-og-700",children:n.githubReview.codeReviewHeading}),t.jsx("div",{className:"space-y-3",children:e})]})}function Na({round:e,index:n,onOpen:s}){const r=F(),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(xn,{item:i,onOpen:s},ot(i,`${n}-${l}`))),e.review&&t.jsx(xn,{item:e.review,onOpen:s})]})]})}function xn({item:e,onOpen:n}){const s=F(),r=e.kind==="review"?e.verdict:void 0;return t.jsx(Ue,{role:ka(e),label:ja(s,e),badge:r?t.jsx("span",{className:is[r],children:r}):void 0,summary:ya(s,e),onClick:n})}const bn={approve:"pill pill-live","request-changes":"pill pill-warn"};function vn(e){if(!e)return 0;const n=e.endsWith(`
8
+ `)?e.slice(0,-1):e;return n===""?0:n.split(`
9
+ `).length}function Ta(e,n){return n.phase==="code"?(n.diffstat??"").split(`
10
+ `).map(r=>r.trim()).filter(Boolean).pop()??e.review.diffLineCount(vn(n.content)):e.review.specDocLineCount(vn(n.content))}function Ra(e,n){const s={critical:0,major:0,minor:0};for(const i of n.findings)i.severity in s&&s[i.severity]++;const r=[];s.critical&&r.push(`${s.critical} critical`),s.major&&r.push(`${s.major} major`),s.minor&&r.push(`${s.minor} minor`);const a=n.findings.length;return e.review.findingsSummary(a,r.join(", "))}function Ca(e,n){const s={fix:0,reject:0,"out-of-scope":0};for(const a of n.responses)a.action in s&&s[a.action]++;const r=[];return s.fix&&r.push(`${s.fix} fixed`),s.reject&&r.push(`${s.reject} rejected`),s["out-of-scope"]&&r.push(`${s["out-of-scope"]} out-of-scope`),r.join(" · ")||e.review.responsesSummary(n.responses.length)}function Aa({task:e}){const n=F(),s=e.reviewMode==="server"||(e.specReviewRound??0)>0,r=e.reviewMode!=="server"&&e.prNumber!==void 0;return!s&&!r?null:t.jsxs("section",{className:"mt-4","aria-label":n.review.sectionTitle,children:[t.jsx("div",{className:"mb-2 text-sm text-og-700",children:n.review.sectionTitle}),t.jsxs("div",{className:"space-y-4",children:[s&&t.jsx(Pa,{task:e}),r&&t.jsx(Sa,{task:e})]})]})}function Pa({task:e}){const n=F(),s=be(),r=`${e.specReviewRound??0}:${e.reviewRound}:${e.status}:${e.phase??"code"}`,{rounds:a,loaded:i,error:l}=as(e.id,r);function d(m,f,p){s(`/tasks/${encodeURIComponent(e.id)}/rounds/${m}/${f}${p}`)}return l?t.jsx("div",{className:"text-sm text-accent",children:n.review.loadFailed(l)}):i?((a==null?void 0:a.length)??0)===0?t.jsx("div",{className:"text-sm text-og-400",children:n.review.notStarted}):t.jsx(t.Fragment,{children:["spec","code"].map(m=>{const f=(a??[]).filter(p=>p.phase===m).sort((p,u)=>p.round-u.round);return f.length===0?null:t.jsx(Ea,{title:n.review.phaseLabel[m],children:f.map(p=>t.jsx(La,{round:p,onOpen:d},`${m}-${p.round}`))},m)})}):t.jsx("div",{className:"text-sm text-og-400",children:n.review.loadingRecords})}function Ea({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 La({round:e,onOpen:n}){const s=F(),r=e.phase==="spec";return t.jsxs("div",{children:[t.jsx("div",{className:"mb-1 text-xs text-og-400",children:s.agents.round(e.round)}),t.jsxs("div",{className:"space-y-1.5",children:[t.jsx(Ue,{role:"dev",label:r?s.review.submitSpecDraft:s.review.submitCodeChanges,summary:Ta(s,e),onClick:()=>n(e.phase,e.round,"")}),e.findings&&t.jsx(Ue,{role:"qa",label:s.review.reviewTurnLabel,badge:t.jsx("span",{className:bn[e.findings.verdict],children:e.findings.verdict}),summary:Ra(s,e.findings),onClick:()=>n(e.phase,e.round,"#review")}),e.response&&t.jsx(Ue,{role:"dev",label:s.review.responseTurnLabel,summary:Ca(s,e.response),onClick:()=>n(e.phase,e.round,"#response")}),e.userDecision&&t.jsx(Ue,{role:"user",label:e.userDecision.verdict==="approve"?s.taskDetail.specApprove:s.taskDetail.specReject,badge:t.jsx("span",{className:bn[e.userDecision.verdict],children:e.userDecision.verdict}),summary:e.userDecision.comments??"",onClick:()=>n(e.phase,e.round,"#review")})]})]})}const wn=Cn;function Da(e){const[n,s]=o.useState(!1);return o.useEffect(()=>{function r(){if(!e||e.status!=="review"||!e.reviewDispatchedAt||!e.qaAgentId){s(!1);return}const i=Date.now()-Date.parse(e.reviewDispatchedAt);s(i>=Pn)}r();const a=setInterval(r,3e4);return()=>clearInterval(a)},[e==null?void 0:e.status,e==null?void 0:e.reviewDispatchedAt,e==null?void 0:e.qaAgentId]),n}function $a(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 Ia(){const{taskId:e=""}=We();return t.jsx(Ba,{taskId:e},e)}function Ba({taskId:e}){const n=be(),s=F(),{show:r}=ve(),a=Mt(),[i,l]=o.useState(!1),[d,m]=o.useState(!1),[f,p]=o.useState(!1),[u,h]=o.useState(!1),[x,g]=o.useState(!1),[y,w]=o.useState(!1),[C,P]=o.useState(!1),[k,N]=o.useState(""),[b,T]=o.useState(null),{data:j,loaded:B,error:I}=qt(e),{projects:L}=qe(),{data:U,loaded:H,error:M}=Wt(),{activeAgentId:K,activateAgentCard:ee}=zn(),E=b??j,ne=Da(E),q=(I==null?void 0:I.message)??null,J=o.useMemo(()=>new Map((U??[]).map(c=>[c.id,c])),[U]);o.useEffect(()=>{b&&j&&j.updatedAt>=b.updatedAt&&T(null)},[b,j]);const W=c=>{T(c)},V=async()=>{if(E&&await a({title:s.taskDetail.cancelConfirmTitle(E.id),confirmLabel:s.taskDetail.cancelConfirmLabel,cancelLabel:s.common.backText})){m(!0);try{const c=await D.tasks.update(E.id,{status:"cancelled"});W(c),r({kind:"success",title:s.taskDetail.cancelledToastTitle})}catch(c){r({kind:"error",title:s.taskDetail.cancelFailedTitle,body:c instanceof Error?c.message:String(c)})}finally{m(!1)}}},ce=async()=>{if(!E)return;const c=Cn.has(E.status);if(await a(c?{title:s.taskDetail.reReviewTerminalConfirmTitle,body:s.taskDetail.reReviewTerminalConfirmBody(E.id,s.status[E.status]??E.status),confirmLabel:s.agents.confirmReReviewLabel}:{title:s.agents.confirmReReviewTitle,body:s.agents.confirmReReviewBody(E.id),confirmLabel:s.agents.confirmReReviewLabel})){h(!0);try{const S=await D.tasks.review(E.id);W(S),r({kind:"success",title:s.agents.reReviewStarted(S.reviewRound)})}catch(S){r({kind:"error",title:s.agents.reReviewStartFailed,body:S instanceof Error?S.message:String(S)})}finally{h(!1)}}},de=async()=>{if(!(!E||!await a({title:s.taskDetail.retryConfirmTitle(E.id),body:E.status==="merged"?s.taskDetail.retryConfirmBodyMerged:s.taskDetail.retryConfirmBodyDefault,confirmLabel:s.common.retry}))){p(!0);try{const v=await D.tasks.retry(E.id);r({kind:"success",title:s.taskDetail.retryCreatedToastTitle(v.id)}),n(Ee(v.projectId,v.id))}catch(v){r({kind:"error",title:s.taskDetail.retryFailedTitle,body:v instanceof Error?v.message:String(v)})}finally{p(!1)}}},_=async()=>{if(E&&await a({title:s.taskDetail.markCompleteConfirmTitle,body:s.taskDetail.markCompleteConfirmBody(E.prNumber??0),confirmLabel:s.taskDetail.markComplete})){g(!0);try{const c=await D.tasks.complete(E.id);W(c),r({kind:"success",title:s.taskDetail.markCompleteToastTitle})}catch(c){r({kind:"error",title:s.taskDetail.markCompleteFailedTitle,body:c instanceof Error?c.message:String(c)})}finally{g(!1)}}},ie=async()=>{if(E&&await a({title:s.taskDetail.continueConfirmTitle,body:s.taskDetail.continueConfirmBody(E.reviewRound+1),confirmLabel:s.taskDetail.continueRound})){w(!0);try{const c=await D.tasks.continue(E.id);W(c),r({kind:"success",title:s.taskDetail.continuedToastTitle(c.reviewRound)})}catch(c){r({kind:"error",title:s.taskDetail.continueFailedTitle,body:c instanceof Error?c.message:String(c)})}finally{w(!1)}}},re=async()=>{if(E&&await a({title:s.taskDetail.specApproveConfirmTitle,body:s.taskDetail.specApproveConfirmBody(E.id),confirmLabel:s.taskDetail.specApprove})){P(!0);try{const c=await D.tasks.spec(E.id,{verdict:"approve"});W(c),N(""),r({kind:"success",title:s.taskDetail.specApprovedToastTitle})}catch(c){r({kind:"error",title:s.taskDetail.specApproveFailedTitle,body:c instanceof Error?c.message:String(c)})}finally{P(!1)}}},ue=async()=>{if(!E)return;const c=k.trim();if(c){P(!0);try{const v=await D.tasks.spec(E.id,{verdict:"request-changes",comments:c});W(v),N(""),r({kind:"success",title:s.taskDetail.specRejectedToastTitle})}catch(v){r({kind:"error",title:s.taskDetail.specRejectFailedTitle,body:v instanceof Error?v.message:String(v)})}finally{P(!1)}}},he=async()=>{if(E&&await a({title:s.taskDetail.confirmGateConfirmTitle(E.id),body:s.taskDetail.confirmGateConfirmBody,confirmLabel:s.taskDetail.confirmComplete})){g(!0);try{const c=await D.tasks.complete(E.id);W(c),r({kind:"success",title:s.taskDetail.confirmedToastTitle(c.status)})}catch(c){r({kind:"error",title:s.taskDetail.confirmFailedTitle,body:c instanceof Error?c.message:String(c)})}finally{g(!1)}}};return t.jsxs("div",{children:[t.jsx("button",{type:"button",onClick:()=>n(-1),className:"btn-ghost mb-3",children:s.common.back}),q&&!E&&t.jsx("div",{className:"text-sm text-accent",children:s.common.loadFailed(q)}),B&&!E&&!q&&t.jsx("div",{className:"text-sm text-accent",children:s.taskDetail.taskNotFound(e)}),!E&&!q&&!B&&t.jsx("div",{className:"text-sm text-og-500",children:s.common.loading}),E&&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:E.id}),t.jsx("span",{className:"min-w-0 truncate font-display text-sm font-semibold tracking-tight text-og-1000",title:E.title,children:E.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:pe(E)}),t.jsx("aside",{className:"min-w-0 space-y-4",children:oe(E)})]})]}),i&&E&&t.jsx(_t,{mode:"edit",open:!0,onClose:()=>l(!1),task:E,onUpdated:W})]});function pe(c){const v=c.preferredAgentId==="",S=c.status==="approved"&&c.prNumber!==void 0,$=c.status==="merge-ready"&&c.prNumber!==void 0,Y=c.status==="spec-ready",X=c.status==="ready",R=c.status==="max_rounds"&&c.phase!=="spec",O=c.status==="max_rounds"&&c.phase==="spec",Z=$a(c.prUrl,c.branch??"");return t.jsxs("div",{children:[q&&t.jsx("div",{className:"mb-4 text-sm text-accent",children:s.common.loadFailed(q)}),v&&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:c.status==="pending"?s.taskDetail.legacyPendingNotice:s.taskDetail.legacyReadonlyNotice(s.status[c.status]??c.status)}),t.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-3",children:[t.jsx("span",{className:`${Qn[c.status]} text-sm`,title:c.status,children:s.status[c.status]??c.status}),t.jsxs("span",{className:"text-sm text-og-500",children:[s.taskDetail.reviewRoundPrefix,t.jsx("span",{className:"text-og-800",children:c.reviewRound}),s.taskDetail.reviewRoundSuffix]}),t.jsxs("span",{className:"text-sm text-og-500",children:[s.taskDetail.specRoundPrefix,t.jsx("span",{className:"text-og-800",children:c.specReviewRound??0}),s.taskDetail.specRoundSuffix]})]}),t.jsx("div",{className:"mb-4 flex flex-wrap items-center gap-2",children:A(c)}),t.jsxs("div",{className:"mb-4 text-sm text-og-500",children:[s.taskDetail.createdAtPrefix,bt(c.createdAt,!1),s.taskDetail.updatedAtPrefix,bt(c.updatedAt,!1)]}),ne&&t.jsxs("div",{className:"mb-4 rounded-lg border border-accent/25 bg-accent-soft p-4 text-sm text-accent",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.verdictOverdueTitle}),t.jsxs("div",{className:"mt-1 text-og-700",children:[s.taskDetail.verdictOverduePrefix,bt(c.reviewDispatchedAt),s.taskDetail.verdictOverdueSuffix]})]}),S&&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}),c.prUrl&&t.jsx("a",{href:c.prUrl,target:"_blank",rel:"noopener noreferrer",className:"btn-secondary mt-3",children:s.taskDetail.viewPr(c.prNumber??0)})]}),X&&t.jsxs("div",{className:"mb-4 rounded-lg border border-accent/25 bg-accent-soft p-4 text-sm text-accent",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.readyGateBannerTitle}),t.jsx("div",{className:"mt-1 text-og-700",children:s.taskDetail.readyGateBannerBody(c.reviewRound)}),t.jsx(jn,{taskId:c.id}),c.prUrl&&t.jsx("a",{href:c.prUrl,target:"_blank",rel:"noopener noreferrer",className:"btn-secondary mt-3",children:s.taskDetail.viewPr(c.prNumber??0)})]}),$&&t.jsxs("div",{className:"mb-4 rounded-lg border border-accent/25 bg-accent-soft p-4 text-sm text-accent",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.mergeReadyBannerTitle}),t.jsx("div",{className:"mt-1 text-og-700",children:s.taskDetail.mergeReadyBannerBody}),c.prUrl&&t.jsx("a",{href:c.prUrl,target:"_blank",rel:"noopener noreferrer",className:"btn-secondary mt-3",children:s.taskDetail.viewPr(c.prNumber??0)})]}),Y&&t.jsxs("div",{className:"mb-4 rounded-lg border border-accent-soft bg-accent-soft/40 p-4 text-sm text-accent",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.specReadyBannerTitle}),t.jsx("div",{className:"mt-1 text-og-700",children:s.taskDetail.specReadyNotice(c.specReviewRound??0)}),t.jsxs("div",{className:"mt-3 flex flex-col gap-2",children:[t.jsx("textarea",{value:k,onChange:z=>N(z.target.value),placeholder:s.taskDetail.specCommentsPlaceholder,rows:3,disabled:C,className:le}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",disabled:C,onClick:re,className:"btn-primary",children:C?s.taskDetail.submitting:s.taskDetail.specApproveButton}),t.jsx("button",{type:"button",disabled:C||k.trim()==="",onClick:ue,title:k.trim()===""?s.taskDetail.specRejectTitleEmpty:s.taskDetail.specRejectTitleReady,className:"btn-secondary",children:C?s.taskDetail.submitting:s.taskDetail.specReject})]})]})]}),R&&t.jsxs("div",{className:"mb-4 rounded-lg border border-accent/25 bg-accent-soft/60 p-4 text-sm text-accent",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.codeMaxRoundsTitle(c.reviewRound)}),t.jsx("div",{className:"mt-1 text-og-700",children:s.taskDetail.codeMaxRoundsBody})]}),O&&t.jsxs("div",{className:"mb-4 rounded-lg border border-accent/25 bg-accent-soft/60 p-4 text-sm text-accent",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.specMaxRoundsTitle(c.specReviewRound??0)}),t.jsx("div",{className:"mt-1 text-og-700",children:s.taskDetail.specMaxRoundsBody}),t.jsx(jn,{taskId:c.id})]}),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:"," ",c.prNumber?c.prUrl?t.jsxs("a",{href:c.prUrl,target:"_blank",rel:"noopener noreferrer",className:"text-accent hover:text-accent-hover",children:["#",c.prNumber]}):t.jsxs("span",{className:"font-mono text-og-800",children:["#",c.prNumber]}):t.jsx("span",{className:"text-og-400",children:"—"})]}),t.jsxs("span",{className:"text-og-500",children:["Branch:"," ",c.branch?Z?t.jsx("a",{href:Z,target:"_blank",rel:"noopener noreferrer",className:"font-mono text-accent hover:text-accent-hover",children:c.branch}):t.jsx("span",{className:"font-mono text-og-800",children:c.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:c.description||t.jsx("span",{className:"text-og-400",children:s.taskDetail.noDescription})}),t.jsx(Aa,{task:c})]})}function oe(c){if(L===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 v=L.find(R=>R.id===c.projectId),S=c.agentId||c.preferredAgentId,$=(v==null?void 0:v.agent.find(R=>R.some(O=>O.id===S)))??(c.qaAgentId?v==null?void 0:v.agent.find(R=>R.some(O=>O.id===c.qaAgentId)):void 0),Y=$==null?void 0:$.find(R=>R.role==="dev"),X=$==null?void 0:$.find(R=>R.role==="qa");return!Y&&!X?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:[Y?me(c,Y):t.jsx(yn,{role:"dev"}),X?me(c,X):t.jsx(yn,{role:"qa"})]})}function me(c,v){const S=J.get(v.id),$=S??{id:v.id,projectId:c.projectId,runtimeStatus:"unknown",tmuxSessionStatus:"unknown",stale:!0};return t.jsx(qn,{agent:$,projectId:c.projectId,role:v.role,runtime:v.runtime,pendingRestart:H&&!S,terminalLoading:!H&&!S&&!M,showTaskBinding:!1,terminalMode:"embedded-full",active:K===v.id,onActivate:()=>ee(v.id)},v.id)}function A(c){const v=c.status==="max_rounds",S=v&&c.phase!=="spec",$=v&&c.phase==="spec",Y=c.status==="ready"||c.status==="merge-ready",X=c.reviewMode==="server"&&c.status==="approved",R=c.status==="pending",O=c.status==="pending"||c.status==="in_progress"||c.status==="spec-ready"||v||Y||X,Z=(wn.has(c.status)||$)&&!!c.preferredAgentId,z=!!c.prNumber&&!$&&c.reviewMode!=="server",ye=c.reviewMode==="server",we=S&&(!!c.prNumber||ye),Le=S&&(!!c.prNumber||ye)&&!!c.agentId,je=ye&&c.status==="approved",Se=c.preferredAgentId==="";return t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",disabled:!R,onClick:()=>l(!0),className:"btn-secondary",children:s.common.edit}),t.jsx("button",{type:"button",disabled:!O||d,onClick:V,className:"btn-secondary",children:d?s.taskDetail.cancelling:s.common.cancel}),!S&&t.jsx("button",{type:"button",disabled:!Z||f,onClick:de,title:wn.has(c.status)||$?Se?s.taskDetail.retryDisabledLegacyTitle:s.taskDetail.retryEnabledTitle:s.taskDetail.retryDisabledStatusTitle(s.status[c.status]??c.status),className:"btn-secondary",children:f?s.common.retrying:s.common.retry}),t.jsx("button",{type:"button",disabled:!z||u,onClick:ce,title:c.prNumber?$?s.taskDetail.reviewSpecMaxRoundsTitle:s.taskDetail.reviewButtonTitle:s.taskDetail.reviewNoPrTitle,className:"btn-secondary",children:u?s.agents.callingReview:s.agents.callReview}),S&&t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",disabled:!Le||y,onClick:ie,title:s.taskDetail.continueButtonTitle,className:"btn-secondary",children:y?s.taskDetail.continuing:s.taskDetail.continueRound}),t.jsx("button",{type:"button",disabled:!we||x,onClick:_,title:s.taskDetail.completeButtonTitle,className:"btn-primary",children:x?s.taskDetail.completing:s.taskDetail.markComplete})]}),Y&&t.jsx("button",{type:"button",disabled:x,onClick:he,title:s.taskDetail.confirmButtonTitle,className:"btn-primary",children:x?s.taskDetail.confirming:s.common.confirm}),je&&t.jsx("button",{type:"button",disabled:x,onClick:he,title:s.taskDetail.retryPublishButtonTitle,className:"btn-primary",children:x?s.common.retrying:s.taskDetail.retryPublish})]})}}function yn({role:e}){const n=F();return t.jsx("div",{className:"rounded-lg border border-hairline bg-surface px-3 py-6 text-center text-sm text-og-400",children:n.taskDetail.noAgentSlot(e==="dev"?"Dev":"QA")})}function jn({taskId:e}){var l;const n=F(),[s,r]=o.useState(null);if(o.useEffect(()=>{let d=!0;return D.tasks.reviews(e).then(m=>{d&&r(m)}).catch(()=>{d&&r([])}),()=>{d=!1}},[e]),!s||s.length===0)return null;const a=s[s.length-1],i=s.reduce((d,m)=>{var f;return d+(((f=m.findings)==null?void 0:f.findings.length)??0)},0);return t.jsxs("div",{className:"mt-2 text-xs text-og-700",children:[n.taskDetail.reviewSummaryPrefix,s.length,n.taskDetail.reviewSummaryMid,t.jsx("span",{className:"font-mono",children:((l=a.findings)==null?void 0:l.verdict)??"—"}),n.taskDetail.reviewSummaryFindingsPrefix,i,n.taskDetail.reviewSummaryFindingsSuffix]})}function Fa(){const{agentId:e}=We(),{projects:n}=qe(),s=o.useMemo(()=>{if(e)for(const r of n??[])for(const a of r.agent){const i=a.find(l=>l.id===e);if(i)return i.runtime}},[e,n]);return e?t.jsxs("div",{"data-testid":"terminal-page-container",className:"flex min-h-0 flex-1 flex-col overflow-hidden border border-hairline bg-surface",children:[t.jsxs("div",{className:"flex h-8 flex-none select-none items-center gap-3 border-b border-hairline bg-page px-3 font-mono text-xs text-og-500",children:[t.jsx("span",{"aria-hidden":!0,className:"block h-1.5 w-1.5 rounded-full bg-og-1000"}),t.jsx("span",{className:"text-og-700",title:Rn(e,s),children:e})]}),t.jsx("div",{className:"min-h-0 flex-1",children:t.jsx(He,{agentId:e,mode:"full",interactive:!0,arrowKeys:!0})})]}):t.jsx("div",{className:"text-sm text-accent",children:"No agent specified"})}function Ma(e){return e.startsWith("diff --git")||e.startsWith("index ")||e.startsWith("--- ")||e.startsWith("+++ ")||e.startsWith("new file")||e.startsWith("deleted file")||e.startsWith("rename ")||e.startsWith("similarity ")||e.startsWith("old mode")||e.startsWith("new mode")}function Oa(e){if(!e)return[];const n=[];let s=!1;for(const r of e.split(/\r?\n/)){let a;r.startsWith("@@")?(a="hunk",s=!0):r.startsWith("diff --git")?(a="file",s=!1):r.startsWith("\\")?a="meta":s?a=r.startsWith("+")?"add":r.startsWith("-")?"del":"context":Ma(r)?a="file":a="context",n.push({type:a,text:r})}return n}const Ha={file:"bg-og-50 font-semibold text-og-700",hunk:"bg-accent-soft text-accent",add:"bg-diff-add text-diff-add-ink",del:"bg-diff-del text-diff-del-ink",context:"text-og-700",meta:"text-og-400"};function _a({content:e,diffstat:n}){const s=F(),r=Oa(e);return r.length===0?t.jsx("div",{className:"text-sm text-og-400",children:s.review.noContent}):t.jsxs("div",{children:[n&&t.jsx("pre",{className:"mb-2 overflow-x-auto rounded-md border border-hairline bg-og-50 p-3 font-mono text-xs text-og-700",children:n.trimEnd()}),t.jsx("div",{className:"overflow-auto rounded-md border border-hairline bg-surface font-mono text-xs leading-[1.5] [max-height:70vh]",children:r.map((a,i)=>t.jsx("div",{className:`whitespace-pre px-3 ${Ha[a.type]}`,children:a.text===""?" ":a.text},i))})]})}const Ua={critical:"pill pill-danger font-semibold",major:"pill pill-warn",minor:"pill"},Ga={fix:"pill pill-live",reject:"pill pill-warn","out-of-scope":"pill"};function kn(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 Sn(e){return e.file?e.line?`${e.file}:${e.line}`:e.file:e.location??""}function Wa(){const e=F(),{taskId:n="",phase:s="",round:r=""}=We(),a=be(),{hash:i}=Nn(),{data:l}=qt(n),d=l?`${l.specReviewRound??0}:${l.reviewRound}:${l.status}:${l.phase??"code"}`:void 0,{rounds:m,loaded:f,error:p}=as(n,d),u=Number(r),h=(m??[]).find(x=>x.phase===s&&x.round===u)??null;return o.useEffect(()=>{if(!h||!i)return;const x=document.getElementById(i.replace("#",""));x==null||x.scrollIntoView({behavior:"smooth",block:"start"})},[h,i]),t.jsxs("div",{className:"mx-auto w-full max-w-5xl",children:[t.jsx("button",{type:"button",onClick:()=>a(-1),className:"btn-ghost mb-3",children:e.common.back}),t.jsxs("div",{className:"mb-1 flex flex-wrap items-baseline gap-2",children:[t.jsx("span",{className:"font-mono text-og-400",children:n}),t.jsx("span",{className:"text-sm font-semibold text-og-1000",children:(l==null?void 0:l.title)??""})]}),t.jsxs("div",{className:"mb-4 flex flex-wrap items-center gap-2 text-xs text-og-500",children:[t.jsx("span",{className:"pill",children:s}),t.jsx("span",{children:e.agents.round(u)}),(h==null?void 0:h.findings)&&t.jsx("span",{className:h.findings.verdict==="approve"?"pill pill-live":"pill pill-warn",children:h.findings.verdict}),h&&t.jsxs("span",{className:"text-og-400",children:[kn(h.startedAt),h.completedAt?` → ${kn(h.completedAt)}`:""]})]}),!f&&t.jsx("div",{className:"text-sm text-og-500",children:e.common.loading}),f&&p&&t.jsx("div",{className:"text-sm text-accent",children:e.review.loadFailed(p)}),f&&!p&&!h&&t.jsx("div",{className:"text-sm text-accent",children:e.review.roundNotFound(s,r)}),h&&t.jsx(qa,{round:h})]})}function qa({round:e}){var i,l;const n=F(),s=((i=e.findings)==null?void 0:i.findings)??[],r=((l=e.response)==null?void 0:l.responses)??[],a=new Map(s.map(d=>[d.id,d]));return t.jsxs("div",{className:"space-y-6",children:[t.jsxs("section",{id:"diff",children:[t.jsx("h2",{className:"mb-2 text-sm font-semibold text-og-800",children:e.phase==="spec"?n.review.specDraft:n.review.codeChanges}),e.contentTruncated&&t.jsx("div",{className:"mb-2 text-xs text-accent",children:n.review.contentTruncated}),e.content?e.phase==="spec"?t.jsx("pre",{className:"card whitespace-pre-wrap break-words p-4 text-sm text-og-800",children:e.content}):t.jsx(_a,{content:e.content,diffstat:e.diffstat}):t.jsx("div",{className:"text-sm text-og-400",children:n.review.noContent})]}),t.jsxs("section",{id:"review",children:[t.jsx("h2",{className:"mb-2 text-sm font-semibold text-og-800",children:n.review.qaReviewHeading}),e.findings===void 0?t.jsx("div",{className:"text-sm text-og-400",children:n.review.notSubmitted}):s.length===0?t.jsx("div",{className:"text-sm text-og-400",children:n.review.noFindingsThisRound}):t.jsx("div",{className:"space-y-2",children:s.map(d=>t.jsxs("div",{className:"card p-3 text-sm",children:[t.jsxs("div",{className:"mb-1 flex flex-wrap items-center gap-2",children:[t.jsx("span",{className:"font-mono text-og-400",children:d.id}),t.jsx("span",{className:Ua[d.severity],children:d.severity}),Sn(d)&&t.jsx("span",{className:"min-w-0 break-all font-mono text-xs text-og-500",children:Sn(d)})]}),t.jsx("div",{className:"whitespace-pre-wrap break-words text-og-800",children:d.message})]},d.id))})]}),r.length>0&&t.jsxs("section",{id:"response",children:[t.jsx("h2",{className:"mb-2 text-sm font-semibold text-og-800",children:n.review.devResponsesHeading}),t.jsx("div",{className:"space-y-2",children:r.map(d=>{const m=a.get(d.findingId);return t.jsxs("div",{className:"card p-3 text-sm",children:[t.jsxs("div",{className:"mb-1 flex flex-wrap items-center gap-2",children:[t.jsx("span",{className:"font-mono text-og-400",children:d.findingId}),t.jsx("span",{className:Ga[d.action],children:d.action}),d.commitSha&&t.jsx("span",{className:"font-mono text-xs text-og-500",children:d.commitSha.slice(0,9)})]}),m&&t.jsxs("div",{className:"mb-1 break-words text-xs text-og-500",children:["↳ ",m.message]}),t.jsx("div",{className:"whitespace-pre-wrap break-words text-og-800",children:d.rationale})]},d.findingId)})})]})]})}const za={approve:"approve","request-changes":"request-changes",comment:"comment"};function Qa(e){return e==="server-mode"||e==="no-pr"||e==="not-github"?e:void 0}function Ka(e){return{"server-mode":e.githubReview.reasonServerMode,"no-pr":e.githubReview.reasonNoPr,"not-github":e.githubReview.reasonNotGithub}}function At(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 Va(){const e=F(),{taskId:n=""}=We(),s=be(),{data:r}=qt(n),a=r?cs(r):void 0,{data:i,loaded:l,error:d}=ds(n,a),m=(i==null?void 0:i.prNumber)??(r==null?void 0:r.prNumber),f=(i==null?void 0:i.prUrl)??(r==null?void 0:r.prUrl),p=i?os(i.items):[];return 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:(r==null?void 0:r.title)??""})]}),t.jsxs("div",{className:"mb-4 flex flex-wrap items-center gap-2 text-xs text-og-500",children:[t.jsx("span",{className:"pill",children:e.githubReview.codeReviewHeading}),f&&m!==void 0&&t.jsx("a",{href:f,target:"_blank",rel:"noopener noreferrer",className:"text-accent hover:text-accent-hover",children:e.taskDetail.viewPr(m)})]}),!l&&t.jsx("div",{className:"text-sm text-og-500",children:e.common.loading}),l&&d&&t.jsx("div",{className:"text-sm text-accent",children:e.review.loadFailed(d)}),l&&!d&&i&&!i.available&&t.jsx("div",{className:"text-sm text-og-500",children:Ka(e)[Qa(i.reason)??"no-pr"]}),l&&!d&&(i==null?void 0:i.available)&&(i.items.length===0?i.error?t.jsx("div",{className:"text-sm text-accent",children:e.githubReview.fetchFailed(i.error)}):t.jsx("div",{className:"text-sm text-og-400",children:e.review.notStarted}):t.jsxs(t.Fragment,{children:[i.error&&t.jsx("div",{className:"mb-3 text-xs text-accent",children:e.githubReview.partialFetchFailed(i.error)}),t.jsx("div",{className:"space-y-5",children:p.map((u,h)=>t.jsx(Ya,{round:u,index:h},ls(u,String(h))))})]}))]})}function Ya({round:e,index:n}){const s=F(),r=e.review?s.agents.round(n+1):s.status.in_progress;return t.jsxs("div",{children:[t.jsx("div",{className:"mb-1.5 text-xs font-medium text-og-700",children:r}),t.jsxs("div",{className:"space-y-2",children:[e.items.map((a,i)=>t.jsx(Ja,{item:a},ot(a,`${n}-${i}`))),e.review&&t.jsx(Xa,{item:e.review})]})]})}function Ja({item:e}){const n=F();if(e.kind==="commit")return t.jsxs("div",{className:"card p-3 text-sm",children:[t.jsxs("div",{className:"mb-1 flex flex-wrap items-center gap-2",children:[t.jsx("span",{className:"pill shrink-0",children:n.githubReview.commitPill}),e.commitSha&&t.jsx("span",{className:"font-mono text-xs text-og-500",children:e.commitSha.slice(0,9)}),e.author&&t.jsx("span",{className:"text-xs text-og-400",children:e.author}),e.createdAt&&t.jsx("span",{className:"text-xs text-og-400",children:At(e.createdAt)})]}),e.body&&t.jsx("div",{className:"whitespace-pre-wrap break-words text-og-800",children:e.body})]});const s=e.kind==="review-comment";return t.jsxs("div",{className:"card p-3 text-sm",children:[t.jsxs("div",{className:"mb-1 flex flex-wrap items-center gap-2",children:[t.jsx("span",{className:"pill shrink-0",children:s?n.githubReview.inlineComment:n.githubReview.comment}),e.author&&t.jsx("span",{className:"font-medium text-og-700",children:e.author}),s&&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:n.githubReview.replyIndicator}),e.createdAt&&t.jsx("span",{className:"text-xs text-og-400",children:At(e.createdAt)})]}),t.jsx(us,{item:e})]})}function Xa({item:e}){const n=F(),s=e.verdict??"comment";return t.jsxs("div",{className:"card p-3 text-sm",children:[t.jsxs("div",{className:"mb-1 flex flex-wrap items-center gap-2",children:[t.jsx("span",{className:"shrink-0 min-w-[1.75rem] text-xs font-semibold tracking-wide text-og-600",children:n.review.roleQa}),t.jsx("span",{className:is[s],children:za[s]}),e.author&&t.jsx("span",{className:"text-xs text-og-400",children:e.author}),e.commitSha&&t.jsx("span",{className:"font-mono text-xs text-og-500",children:e.commitSha.slice(0,9)}),e.createdAt&&t.jsx("span",{className:"text-xs text-og-400",children:At(e.createdAt)})]}),t.jsx(us,{item:e,placeholder:n.githubReview.noReviewBody})]})}function us({item:e,placeholder:n}){const s=F();return t.jsxs(t.Fragment,{children:[e.body?t.jsx("div",{className:"whitespace-pre-wrap break-words text-og-800",children: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.githubReview.bodyTruncated})]})}function Za(){const e=F(),[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 ei(){const e=F(),{phase:n,count:s,error:r,triggerRestart:a}=ct();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 ti=new Set(["done","merged"]);function jt(e,n){const s=e.trim().replace(/\s+/g," ");return s.length>n?`${s.slice(0,n-1)}…`:s}function ni(e,n){return e?e.repo?`${e.id} · ${e.repo}`:e.id:n}function si(e){return e.title?`${e.id} · ${e.title}`:e.id}function ri(e){return ti.has(e)}function ai(e,n,s){const r=Gt();if(!(!r||r.permission!=="granted"))try{const a=Ft(),i=new r(a.notification.taskDone(jt(e.title||e.id,80)),{body:[a.notification.bodyProject(jt(n,120)),a.notification.bodyTask(jt(si(e),120)),a.notification.bodyStatus(Pr(e.status))].join(`
11
+ `),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 ii(e,n,s){const r=o.useRef(new Map),a=o.useRef(new Set),i=o.useRef(new Map),l=o.useRef(new Set),d=o.useRef(new Set),m=o.useRef(new Map),f=o.useRef(n),p=o.useRef(new Map),u=o.useMemo(()=>s?(e??[]).map(h=>h.id).sort().join("\0"):"",[s,e]);o.useEffect(()=>{f.current=n},[n]),o.useEffect(()=>{p.current=new Map((e??[]).map(h=>[h.id,ni(h,h.id)]))},[e]),o.useEffect(()=>{const h=w=>{m.current.set(w,(m.current.get(w)??0)+1)};if(u===""){for(const w of d.current)h(w);d.current=new Set,r.current.clear(),i.current.clear(),l.current.clear();return}const x=u.split("\0"),g=new Set(x);for(const w of d.current)g.has(w)||h(w);d.current=g;for(const w of r.current.keys())g.has(w)||r.current.delete(w);for(const w of i.current.keys())g.has(w)||i.current.delete(w);const y=x.map(w=>dt().subscribe(`project-tasks:${w}`,C=>{const P=r.current.get(w),k=new Map(C.map(b=>[b.id,b]));r.current.set(w,k);const N=i.current.get(w)??new Set;if(i.current.set(w,N),!P){for(const b of k.keys())N.delete(b);return}for(const[b]of P)k.has(b)||a.current.has(b)||N.add(b);for(const b of[...N]){if(k.has(b)){N.delete(b);continue}const T=m.current.get(w)??0,j=`${w}:${T}:${b}`;l.current.has(j)||(l.current.add(j),D.tasks.get(b).then(B=>{if((m.current.get(w)??0)!==T)return;if(!B||B.projectId!==w||!ri(B.status)){N.delete(b);return}N.delete(b),a.current.add(B.id);const I=p.current.get(w)??w;ai(B,I,()=>f.current(B))}).catch(B=>{console.warn(`[task-notifications] failed to confirm completed task ${b}:`,B)}).finally(()=>{l.current.delete(j)}))}},C=>{console.warn(`[task-notifications] project task stream failed for ${w}:`,C)}));return()=>{for(const w of y)w()}},[u])}function oi(){const e=Nn(),n=be(),{projects:s}=qe(),{enabled:r}=Jn(),a=!e.pathname.startsWith("/terminal/");return Bs(),ii(s,i=>n(Ee(i.projectId,i.id)),r),t.jsxs("div",{className:"flex h-dvh flex-col bg-page",children:[t.jsxs("nav",{className:"flex h-12 flex-none items-center border-b border-hairline bg-surface px-3 sm:px-6",children:[t.jsxs($e,{to:"/",className:"flex shrink-0 items-center gap-2 font-display text-sm font-semibold tracking-tight text-og-1000",children:[t.jsx("span",{"aria-hidden":!0,className:"block h-2.5 w-2.5 rounded-full bg-accent"}),"baxian"]}),t.jsx("div",{id:Xn,className:"ml-auto flex min-w-0 items-center justify-end gap-2"})]}),t.jsx(ei,{}),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(ys,{children:[t.jsx(De,{path:"/",element:t.jsx(ra,{})}),t.jsx(De,{path:"/project/:id",element:t.jsx(pa,{})}),t.jsx(De,{path:"/project/:id/task/:taskId",element:t.jsx(Ia,{})}),t.jsx(De,{path:"/terminal/:agentId",element:t.jsx(Fa,{})}),t.jsx(De,{path:"/tasks/:taskId/rounds/:phase/:round",element:t.jsx(Wa,{})}),t.jsx(De,{path:"/tasks/:taskId/github-review",element:t.jsx(Va,{})})]}),a&&t.jsx("footer",{className:"mt-auto flex justify-center pb-4 pt-24",children:t.jsx(Za,{})})]})]})}function li(){return t.jsx(ws,{children:t.jsx(Qr,{children:t.jsx(oi,{})})})}function ci({children:e}){const n=F(),[s,r]=o.useState({kind:"probing"}),a=o.useRef(s);o.useEffect(()=>{a.current=s},[s]);const i=o.useCallback(async()=>{r({kind:"probing"});try{const d=await D.config.get();Nt(d.language),r({kind:"authorized"})}catch(d){if(d instanceof Be&&d.status===401){r({kind:"unauthorized"});return}r({kind:"error",message:d instanceof Error?d.message:void 0,fallback:"connectFallback"})}},[]);if(o.useEffect(()=>{i()},[i]),o.useEffect(()=>{const d=()=>{a.current.kind!=="probing"&&r({kind:"unauthorized",reason:"expired"})};return window.addEventListener(et,d),()=>window.removeEventListener(et,d)},[]),s.kind==="authorized")return t.jsx(t.Fragment,{children:e});if(s.kind==="error")return t.jsxs(Pt,{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(Pt,{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(di,{message:l,onSubmit:async d=>{Ns(d);try{const m=await D.config.get();Nt(m.language),r({kind:"authorized"})}catch(m){if(Ts(),m instanceof Be&&m.status===401){r({kind:"unauthorized",reason:"invalid"});return}r({kind:"error",message:m instanceof Error?m.message:void 0,fallback:"loginFailed"})}}})}function Pt({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 di({message:e,onSubmit:n}){const s=F(),[r,a]=o.useState(""),[i,l]=o.useState(!1),[d,m]=o.useState(void 0),f=async u=>{u.preventDefault();const h=r.trim();if(!h){m(s.auth.tokenRequired);return}m(void 0),l(!0);try{await n(h)}finally{l(!1)}},p=d??e;return t.jsxs(Pt,{title:s.auth.loginTitle,children:[t.jsx("p",{className:"mb-4 text-sm text-og-600",children:s.auth.loginDescription}),t.jsxs("form",{onSubmit:u=>{f(u)},children:[t.jsx("label",{className:te,htmlFor:"baxian-token",children:s.auth.tokenLabel}),t.jsx("input",{id:"baxian-token",type:"password",autoComplete:"current-password",autoFocus:!0,value:r,onChange:u=>a(u.target.value),className:`${le} 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})]})]})}xs.createRoot(document.getElementById("root")).render(t.jsx(o.StrictMode,{children:t.jsx(Is,{children:t.jsx(Qs,{children:t.jsx(Hs,{children:t.jsx(Us,{children:t.jsx(ci,{children:t.jsx(li,{})})})})})})}));
@@ -6,7 +6,7 @@
6
6
  <link rel="icon" type="image/png" href="/baxian-logo.png" />
7
7
  <link rel="apple-touch-icon" href="/baxian-logo.png" />
8
8
  <title>baxian</title>
9
- <script type="module" crossorigin src="/assets/index-wY1NEceI.js"></script>
9
+ <script type="module" crossorigin src="/assets/index-Bc2bgdOQ.js"></script>
10
10
  <link rel="modulepreload" crossorigin href="/assets/react-BFCkCmbU.js">
11
11
  <link rel="modulepreload" crossorigin href="/assets/xterm-D5X2JljJ.js">
12
12
  <link rel="modulepreload" crossorigin href="/assets/router-BgSDZqI0.js">
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "baxian",
3
- "version": "1.2.47",
3
+ "version": "1.2.49",
4
4
  "description": "AI agent orchestration",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {