baxian 2.1.2 → 2.1.3

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,19 @@
1
+ var Us=Object.defineProperty;var Gs=(e,n,s)=>n in e?Us(e,n,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[n]=s;var ce=(e,n,s)=>Gs(e,typeof n!="symbol"?n+"":n,s);import{r as o,j as t,a as Ws,c as zs}from"./react-BFCkCmbU.js";import{a as Ks,b as Vs,x as Qs,c as Ys}from"./xterm-DYzQPKhn.js";import{L as Ne,u as Le,a as At,b as Un,B as Js,R as Xs,c as Ye}from"./router-BgSDZqI0.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))r(a);new MutationObserver(a=>{for(const i of a)if(i.type==="childList")for(const l of i.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&r(l)}).observe(document,{childList:!0,subtree:!0});function s(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerPolicy&&(i.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?i.credentials="include":a.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(a){if(a.ep)return;a.ep=!0;const i=s(a);fetch(a.href,i)}})();function ke({className:e,...n}){return t.jsx("button",{type:"button",role:"menuitem",className:`block w-full px-3 py-1.5 text-left text-sm text-og-1000 hover:bg-og-50 disabled:opacity-50 disabled:cursor-not-allowed ${e??""}`,...n})}function Dt({ariaLabel:e,children:n,placement:s="down",autoFocusFirstItem:r=!1,menuClassName:a="min-w-[140px]",className:i,disabled:l=!1,triggerRef:c}){const[m,h]=o.useState(!1),f=o.useRef(null),p=o.useRef(null),u=o.useId(),d=o.useId();return o.useEffect(()=>{if(!m)return;const x=y=>{var R,A;const T=y.target;T&&((R=p.current)!=null&&R.contains(T)||(A=f.current)!=null&&A.contains(T)||h(!1))},b=y=>{var T;y.key==="Escape"&&(h(!1),(T=f.current)==null||T.focus())};return document.addEventListener("mousedown",x),document.addEventListener("keydown",b),()=>{document.removeEventListener("mousedown",x),document.removeEventListener("keydown",b)}},[m]),o.useEffect(()=>{var b;if(!m||!r)return;const x=(b=p.current)==null?void 0:b.querySelector('[role="menuitem"]:not([disabled])');x==null||x.focus()},[m,r]),t.jsxs("div",{className:`relative ${i??""}`,children:[t.jsx("button",{ref:x=>{f.current=x,c&&(c.current=x)},id:d,type:"button",onClick:()=>h(x=>!x),disabled:l,"aria-haspopup":"menu","aria-expanded":m,"aria-controls":m?u:void 0,"aria-label":e,className:"flex h-8 w-8 items-center justify-center rounded text-og-500 transition-colors hover:bg-og-50 hover:text-og-1000 disabled:cursor-not-allowed disabled:opacity-50",children:t.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[t.jsx("circle",{cx:"12",cy:"12",r:"1"}),t.jsx("circle",{cx:"12",cy:"5",r:"1"}),t.jsx("circle",{cx:"12",cy:"19",r:"1"})]})}),m&&t.jsx("div",{ref:p,id:u,role:"menu","aria-labelledby":d,className:`absolute right-0 z-10 rounded-md border border-hairline bg-surface py-1 shadow-md ${s==="up"?"bottom-full mb-1":"top-full mt-1"} ${a}`,children:n(()=>{var x;h(!1),(x=f.current)==null||x.focus()})})]})}function Fe(e){return e==="spec"}function Gn(e,n){var r;const s=e.binding;return(s==null?void 0:s.bootstrappingTaskId)!==void 0&&s.bootstrappingTaskId===s.taskId&&(n===void 0||s.taskId===n)&&s.status!=="awaiting_human"&&((r=s.needInput)==null?void 0:r.at)===void 0}function Wn(e){var n;return e.prNumber===void 0||e.phase===void 0||((n=e.deliveryConfirmation)==null?void 0:n.phase)!==e.phase}const Zs={"claude-code":"Claude Code",codex:"Codex",opencode:"OpenCode",qodercli:"Qoder CLI"};function zn(e,n){const s=[e?Zs[e]:null,n||null].filter(Boolean);return s.length>0?s.join(" · "):null}function Kn(e,n,s){const r=zn(n,s);return r?`${e} (${r})`:e}const Vn=new Set(["merged","done","failed","cancelled"]),tn=new Set(["in_progress","review","fixing","spec-ready","approved","merge-ready","max_rounds"]),Bt=20,Pt=5*1024*1024,ft=4;function Qn(e){if(!e)return null;try{const n=new URL(e);return n.protocol==="http:"||n.protocol==="https:"?n.href:null}catch{return null}}const st="/api",nn="baxian.token",et="baxian:unauthorized";function sn(){try{return typeof localStorage<"u"?localStorage.getItem(nn):null}catch{return null}}function er(e){try{localStorage.setItem(nn,e)}catch(n){console.error("Failed to save auth token to localStorage",n)}}function tr(){try{localStorage.removeItem(nn)}catch(e){console.error("Failed to clear auth token from localStorage",e)}}function We(e){const n=sn();return{...e??{},...n?{Authorization:`Bearer ${n}`}:{}}}class ze extends Error{constructor(n,s,r){super(s),this.status=n,this.details=r,this.name="ApiError"}}function nr(e){if(!Array.isArray(e))return;const n=e.filter(s=>typeof s=="object"&&s!==null&&typeof s.path=="string"&&typeof s.message=="string");return n.length>0?n:void 0}async function Ke(e){const n=await e.text();let s=n||`HTTP ${e.status}`,r;try{const a=JSON.parse(n);typeof a.error=="string"&&(s=a.error),r=nr(a.details)}catch{}throw r!==void 0&&(s=`${s}
2
+ ${r.map(a=>`${a.path}: ${a.message}`).join(`
3
+ `)}`),e.status===401&&typeof window<"u"&&window.dispatchEvent(new CustomEvent(et)),new ze(e.status,s,r)}async function Se(e){const n=await fetch(`${st}${e}`,{headers:We()});return n.ok||await Ke(n),n.json()}async function sr(){const e=await fetch("/health");return e.ok||await Ke(e),e.json()}async function fe(e,n,s){const r=n!==void 0,a=await fetch(`${st}${e}`,{method:"POST",headers:r?We({"Content-Type":"application/json"}):We(),body:r?JSON.stringify(n):void 0,signal:s==null?void 0:s.signal});return a.ok||await Ke(a),a.json()}async function Ft(e,n,s){const r=await fetch(`${st}${e}`,{method:"PATCH",headers:We({"Content-Type":"application/json"}),body:n?JSON.stringify(n):void 0,signal:s==null?void 0:s.signal});if(r.ok||await Ke(r),r.status===204)return;const a=await r.text();if(a)return JSON.parse(a)}async function rr(e,n){const s=await fetch(`${st}${e}`,{method:"PUT",headers:We({"Content-Type":"application/json"}),body:JSON.stringify(n??null)});if(s.ok||await Ke(s),s.status===204)return;const r=await s.text();if(r)return JSON.parse(r)}async function pt(e){const n=await fetch(`${st}${e}`,{method:"DELETE",headers:We()});if(n.ok||await Ke(n),n.status===204)return;const s=await n.text();if(s)return JSON.parse(s)}const Q=encodeURIComponent;function Yn(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 M={agents:{list:()=>Se("/agents"),get:e=>Se(`/agents/${Q(e)}`),stop:e=>pt(`/agents/${Q(e)}/session`),compact:e=>fe(`/agents/${Q(e)}/compact`),clear:e=>fe(`/agents/${Q(e)}/clear`),probe:(e,n={},s)=>fe("/agents/probe",{mode:e,host:n.host,hostId:n.hostId},s),installTmux:(e,n={})=>fe("/agents/install-tmux",{mode:e,host:n.host,hostId:n.hostId}),uploadImage:async(e,n)=>fe(`/agents/${Q(e)}/images`,{dataBase64:await Yn(n)})},tasks:{untrackedFiles:(e,n)=>Se(`/tasks/${Q(e)}/agents/${Q(n)}/untracked-files`),resolveUntrackedFiles:(e,n,s)=>fe(`/tasks/${Q(e)}/agents/${Q(n)}/untracked-files`,s),list:async e=>{const n=new Map;for(const s of["active","pending"]){let r=0;for(;;){const a=await M.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}`),Se(`/tasks?${s.join("&")}`)},get:e=>Se(`/tasks/${Q(e)}`),create:e=>fe("/tasks",e),update:(e,n)=>Ft(`/tasks/${Q(e)}`,n),retry:e=>fe(`/tasks/${Q(e)}/retry`),advance:(e,n)=>fe(`/tasks/${Q(e)}/advance`,n),verdict:(e,n)=>fe(`/tasks/${Q(e)}/verdict`,n),prReview:e=>Se(`/tasks/${Q(e)}/pr-review`),prReviewRefresh:e=>fe(`/tasks/${Q(e)}/pr-review/refresh`)},projects:{list:()=>Se("/projects"),get:e=>Se(`/projects/${Q(e)}`),create:e=>fe("/projects",e),delete:e=>pt(`/projects/${Q(e)}`),addAgentTeam:(e,n)=>fe(`/projects/${Q(e)}/agents`,n),replaceAgent:(e,n,s)=>rr(`/projects/${Q(e)}/agents/${Q(n)}`,s),deleteAgent:(e,n)=>pt(`/projects/${Q(e)}/agents/${Q(n)}`),resumeAgent:(e,n)=>fe(`/projects/${Q(e)}/agents/${Q(n)}/resume`),restartRepl:(e,n)=>fe(`/projects/${Q(e)}/agents/${Q(n)}/restart-repl`),retryAgent:(e,n)=>fe(`/projects/${Q(e)}/agents/${Q(n)}/retry`),bootstrap:e=>fe(`/projects/${Q(e)}/bootstrap`)},hosts:{list:()=>Se("/hosts"),create:e=>fe("/hosts",e),update:(e,n)=>Ft(`/hosts/${Q(e)}`,n),delete:e=>pt(`/hosts/${Q(e)}`),check:e=>fe("/hosts/check",e)},config:{get:()=>Se("/config"),patch:e=>Ft("/config",e)},health:{get:sr},server:{restart:()=>fe("/restart")}};function rn(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 ar(e){return t.jsxs("svg",{...rn(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 ir(e){return t.jsxs("svg",{...rn(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 or(e){return t.jsxs("svg",{...rn(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 Jn={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",installing:"Installing…",installingTmuxNotice:"Installing tmux. Keep this window open…",technicalDetails:"Technical details"},status:{pending:"Waiting to start",in_progress:"In progress",review:"In review",fixing:"Revising","spec-ready":"Plan ready",approved:"Running pre-merge checks","merge-ready":"Merge ready",merged:"PR merged",done:"Complete",failed:"Failed",max_rounds:"Review needs a decision",cancelled:"Cancelled"},statusContext:{pendingUnassigned:"Unassigned",inProgressSpec:"Drafting plan",inProgressCode:"Coding",reviewSpec:"Reviewing",reviewCode:"Reviewing",fixingSpec:"Fixing",fixingCode:"Fixing",maxRoundsSpec:"Plan review needs a decision",maxRoundsCode:"Code review needs a decision"},notification:{taskDone:e=>`Task completed: ${e}`,bodyProject:e=>`Project: ${e}`,bodyTask:e=>`Task: ${e}`,bodyStatus:e=>`Status: ${e}`},dashboard:{moreActions:"More actions",newProject:"New project",manageHosts:"Manage hosts",newTask:"+ New task",createProjectFirst:"Create a project first",emptyProjects:"No projects yet. Choose “New project” in the top-right menu.",noAgentsYet:"No Agent Teams yet. Add one in project details.",detailsLink:"Details →",detailsAriaLabel:e=>`Details — ${e}`,tasksLoadFailed:e=>`Failed to load tasks: ${e}`,projectCreatedTitle:"Project created",addAgentNowOrLater:"Add an Agent Team now?",later:"Later",continueAddingAgent:"Add Agent Team",title:"Projects"},nav:{toggleToIcon:"Switch to logo icon",toggleToText:"Switch to logo text"},agents:{runtimeStatus:{unknown:"Unknown",idle:"Idle",pending:"Needs attention",working:"Working",waiting:"Waiting",error:"Error"},sessionStatus:{absent:"Not running",unreachable:"Host unreachable"},bootstrappingBadge:"Starting",dispatchingBadge:"Preparing",dispatchingTitle:"Preparing the working directory and sending the task",agentStatusLoading:"Agent status loading",bootstrappingTerminalDisabled:"Agent is starting",bootstrappingNotice:"Agent is starting. The terminal will connect automatically.",terminalNeedsRestart:"Restart baxian to use the terminal",pendingRestartNotice:"Restart baxian to apply",heldBadge:"Paused",heldDefaultReason:"Needs human attention",staleTitle:e=>e?`Status may be outdated. Last checked at ${e}`:"Status may be outdated",awaitingHumanIntervention:"Needs your attention",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:"Open the ",needInputSuffix:" to reply.",activateTerminal:e=>`Activate ${e} terminal`,actionsMenu:e=>`Agent ${e} actions menu`,taskLabel:"Task: ",stop:"Cancel task",stopping:"Cancelling…",restartRuntime:"Restart Agent",openTerminalAction:"Open terminal",openTaskActions:"View task",deleteToRecover:"Delete Agent",holdRecovery:{resume:"Resolve the problem, then resume the Agent.","restart-runtime":"Restart the Agent to check that it is ready.",terminal:"Handle the startup prompt in the terminal. The Agent resumes automatically.",task:"Open the task to retry, handle the review, or cancel.","delete-agent":"Cancel the task or delete and recreate the Agent. It cannot resume in this state."},resume:"Resume",resuming:"Resuming…",resumeConfirmTitle:e=>`Resume Agent ${e}?`,resumeGreetingBody:"The Agent failed its startup check. It will restart and resume once the check passes.",resumeDefaultBody:"Unpause the Agent so it is available again.",resumeGreetingButtonTitle:"Restart the Agent and check that it is ready",resumeDefaultButtonTitle:"Unpause the Agent",regreetingStartedTitle:e=>`Checking Agent ${e} again`,regreetingStartedBody:"The Agent will resume after the check passes. If it fails, follow the error instructions and retry.",resumedTitle:e=>`Agent ${e} resumed`,resumedReleasedBody:"The Agent can take new tasks.",resumedKeptBody:"The Agent is still assigned to its previous task.",resumeFailedTitle:"Resume failed",compact:"Summarize conversation",compacting:"Summarizing…",compactMenuItemTitle:"Shorten the conversation while keeping key information",compactSentTitle:e=>`Asked ${e} to summarize the conversation`,compactFailedTitle:"Could not summarize conversation",clear:"Clear conversation",clearing:"Clearing…",clearMenuItemTitle:"Clear the Agent’s conversation",clearConfirmTitle:e=>`Clear the conversation for ${e}?`,clearConfirmBody:"The conversation will be cleared and cannot be recovered.",clearConfirmLabel:"Clear",clearSentTitle:e=>`Asked ${e} to clear the conversation`,clearFailedTitle:"Could not clear conversation",teamHeading:"Agent Team",teamLabel:e=>`Agent Team ${e}`,claimableTasksLabel:(e,n)=>`${e}: tasks available for ${n}`,teamActionsMenu:e=>`Agent Team ${e} actions menu`,teamCompactMenuItemTitle:"Summarize conversations for every Agent in the Agent Team",teamClearMenuItemTitle:"Clear conversations for every Agent in the Agent Team",teamCompactSentTitle:e=>`Asked Agent Team ${e} to summarize conversations`,teamClearConfirmTitle:e=>`Clear conversations for Agent Team ${e}?`,teamClearConfirmBody:"Conversations for all Agents in this Agent Team will be cleared and cannot be recovered.",teamClearSentTitle:e=>`Asked Agent Team ${e} to clear conversations`,teamDeleteConfirmTitle:e=>`Delete Agent Team ${e}?`,teamDeletedTitle:e=>`Agent Team ${e} deleted`,deleteConfirmTitle:e=>`Delete the Agent Team containing ${e}?`,deleteConfirmBody:"All Agents in this Agent Team will be removed. This action cannot be undone.",deletedWithTeamTitle:e=>`Deleted the Agent Team containing ${e}`,deletedWithTeamBody:e=>`${e} was removed from the same Agent Team.`,deletedTitle:e=>`Agent ${e} deleted`,retryBootstrap:"Retry setup",retrySession:"Retry startup",retrySessionReady:"Agent is ready",retrySessionPending:"Open the terminal to handle the startup dialog",retrySessionFailed:"Agent startup failed",retryBootstrapSucceededTitle:"Setup complete",retryBootstrapSucceededBody:"Agent status will update automatically.",retryBootstrapStillFailingTitle:"Setup still failed",retryBootstrapStillFailingBody:"Follow the latest error instructions, then retry.",retryBootstrapFailedTitle:"Setup failed",round:e=>`Round ${e}`,noActiveTask:"No active task",noActiveTaskAriaLabel:e=>`${e} no active task`,unassigned:"Unassigned",start:"Start",starting:"Starting…",startFailed:"Failed to start",taskHandedTo:(e,n)=>`Task ${e} handed to ${n}`,handToAndStart:e=>`Hand to ${e} and start immediately`,agentUnavailable:e=>`Agent ${e} is currently unavailable`,devRole:"Dev agent",qaRole:"QA agent"},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 when a task finishes or its PR is 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:"Enter your access token.",loginFailed:"Sign-in failed",sessionExpired:"Session expired, please enter the token again",tokenInvalid:"Invalid token, please retry",tokenLabel:"Access token",tokenPlaceholder:"Enter the server’s access token",tokenRequired:"Please enter the access token",submit:"Sign in",submitting:"Signing in…"},createProject:{title:"New project",required:"Required",idLabel:"Project ID",idPlaceholder:"baxian",idTakenError:"This ID is already in use",repoLabel:"Git repository URL",mergeStrategyLabel:"Merge method",mergeHumanLabel:"Merge manually (default)",mergeAutoLabel:"Merge automatically after confirmation",specApprovalLabel:"Plan approval",specApprovalHumanLabel:"Require your approval (default)",specApprovalAutoLabel:"Start development automatically after plan review",createdToastTitle:e=>`Project ${e} created`},createAgent:{modalTitle:e=>`Add Agent Team to ${e}`,submitLabel:"Add Agent Team",continueLabel:"Next: QA agent",submitting:"Adding Agent Team…",idTakenGlobalError:"Another Agent already uses this ID",idPlaceholder:(e,n)=>`${e}-${n}`,roleLabel:"Role",devStepLabel:"Dev agent (1/2)",qaStepLabel:"QA agent (2/2)",teamDevLabel:e=>`Teamed with Dev agent ${e}`,modeLabel:"Run on",localModeLabel:"Local",remoteModeLabel:"Remote (SSH)",noHostsHint:"Add a host in “Manage hosts” in the top-right menu first.",selectHostPlaceholder:"Select a host",sshConfigHint:"Set keys and jump hosts in ~/.ssh/config; set port and password in “Manage hosts”.",runtimeLabel:"AI tool",reprobeButton:"↻ Check again",selectHostFirstHint:"(select a host first)",probingLabel:"Checking…",tmuxProbingLabel:"tmux: checking…",advancedOptionsLabel:"Advanced options",expandLabel:"Expand",collapseLabel:"Collapse",workdirLabel:"Working directory (optional)",workdirPlaceholder:"Leave blank to create automatically",workdirHint:"Each Agent needs its own directory. Do not share it between Agents.",modelLabel:"Model (optional)",modelPlaceholderCodex:"Enter a model name",modelPlaceholderOther:"For example, sonnet or opus",modelHint:"Leave blank to use the AI tool’s default model.",addDirsLabel:"Extra directories (optional)",addDirsPlaceholder:`One absolute path per line, e.g.:
4
+ /Users/me/shared-libs
5
+ /Users/me/extra-repo`,addDirsHint:"Allow the Agent to access these directories.",yoloTitle:"Automatic permissions (recommended)",addedToastTitle:(e,n,s)=>`Agent Team ${e} + ${n} added to ${s}`,idLabel:"Agent ID",hostLabel:"Host",yoloBody:"Let the Agent act without asking for approval. When off, you may need to approve actions in the terminal.",yoloCodexBody:"Skip approvals and turn off the sandbox that limits file access and command execution. When off, you may need to approve actions in the terminal."},createTask:{titleCreate:"New task",titleEdit:"Edit task",selectProjectPlaceholder:"Select a project",targetAgentLabel:"Dev agent",notAssignedOption:"Not assigned yet",pendingRestartSuffix:"(pending restart)",notInRuntimeSuffix:"(unavailable)",titlePlaceholder:"One-sentence summary of what to do",descriptionLabel:"Description (optional)",descriptionPlaceholder:"Add requirements; Markdown supported",imagesLabel:"Images (optional)",addImagesButton:"Add images",removeImageAriaLabel:e=>`Remove image ${e}`,draftRestoredNotice:"Restored your last unsaved draft",discardDraftButton:"Discard draft",updatedToastTitle:"Task updated",createdToastTitle:"Task created",imageTooLargeToastTitle:"Image too large",imageTooLargeToastBody:(e,n)=>`${e} exceeds ${n} MiB`,tooManyImagesToastTitle:e=>`Maximum ${e} images`,noDevPendingRestartHint:e=>`Agent ${e} has not started. Restart baxian.`,noDevNotInRuntimeHint:e=>`Agent ${e} is unavailable, so saving may fail. Check its settings or choose another Agent.`,noDevGlobalPendingRestartHint:"Dev agents have not started. Restart baxian.",projectLabel:"Project",titleLabel:"Title"},hostMgmt:{title:"Manage hosts",emptyState:"No hosts yet.",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 use your SSH username",passwordLabel:"Password (optional)",passwordPlaceholderSet:"Already set; leave blank to keep it unchanged",passwordPlaceholderUnset:"Leave blank to use an SSH key",clearPasswordLabel:"Clear password and use an SSH key",passwordHintLead:"We recommend ",passwordHintStrong:"SSH key login.",plaintextWarningLead:"Passwords are stored in the configuration file as ",plaintextWarningStrong:"plaintext",plaintextWarningTrail:".",testConnection:"Test connection",testing:"Testing…",createdToastTitle:e=>`Host ${e} added`,updatedToastTitle:e=>`Host ${e} updated`,deletedToastTitle:e=>`Host ${e} deleted`,aliasPlaceholder:"For example, development server"},projectPage:{newTaskButton:"+ New task",menuAriaLabel:e=>`Project ${e} actions menu`,showTaskPanel:"Show task panel",addAgent:"Add Agent Team",deleteAgentsFirstHint:e=>`Delete the project's ${e} Agent${e===1?"":"s"} first`,deleteProjectMenuItem:"Delete project…",noAgentsYet:"No Agent Teams yet. Use the menu in the top-right corner to add one.",closeTaskPanel:"Close task panel",deleteModalTitle:"Delete project",confirmDeleteButton:"Confirm delete",deleteBodyLead:"Delete project ",deleteBodySuffix:". This cannot be undone. The Git repository will be kept.",confirmInputLead:"Enter project ID ",confirmInputSuffix:" to confirm:",confirmInputAriaLabel:"Enter the project ID to confirm deletion",deletedToastTitle:e=>`Project ${e} deleted`,agentsHeading:"Agent Team",tasksHeading:"Tasks"},taskDetail:{cancelConfirmTitle:e=>`Cancel task ${e}?`,cancelConfirmLabel:"Cancel task",cancelledToastTitle:"Task cancelled",cancelFailedTitle:"Couldn’t cancel the task",cancelForceTitle:"Stop the task and free its Agents for new work",cancelConfirmBodyActive:"Stops the task, closes its PR, and cleans up its branches. Agents can take new tasks. You can run this task again later.",cancelConfirmBodyTerminal:"The task has ended; its status stays the same. Its Agents will be freed for new work.",cancelCleanupToastTitle:"Agents are available for new work",retryTask:"Run task again",retryConfirmTitle:e=>`Run task ${e} again?`,retryConfirmBodyMerged:"The PR is merged. A new task with the same content will start from the beginning.",retryConfirmBodyDefault:"A new task with the same content will start from the beginning. This task stays in the history.",retryCreatedToastTitle:e=>`Created task ${e}`,retryFailedTitle:"Couldn’t start the new task",markCompleteConfirmTitle:"Accept the current version and merge?",markCompleteConfirmBody:e=>`Merge PR #${e} as it is and finish the task. Remaining review concerns will not be revised.`,completing:"Finishing…",markCompleteToastTitle:"Accepted the current version; merging the PR",markCompleteFailedTitle:"Couldn’t accept and merge the current version",branchCleanupPendingTitle:"The local task branch was kept for now",branchCleanupPendingBody:"The local task branch was kept to avoid losing changes.",branchCleanupSkippedTitle:"The local task branch was kept",branchCleanupSkippedBody:"The local task branch was kept. You can check or delete it later.",continueConfirmTitle:"Continue revising?",continueConfirmBody:e=>`Start revision round ${e}, then review the changes again.`,continuing:"Starting revisions…",continuedToastTitle:e=>`Started revision round ${e}`,continueFailedTitle:"Couldn’t start another revision",specApproveConfirmTitle:"Approve the plan and start development?",specApproveConfirmBody:e=>`Task ${e} will start development using this plan.`,specApprove:"Approve plan",specApprovedToastTitle:"Plan approved; development started",specApproveFailedTitle:"Couldn’t approve the plan",specRejectedToastTitle:"Change request sent; the Dev agent is revising the plan",specRejectFailedTitle:"Couldn’t request plan changes",confirmAndMerge:"Confirm and merge",confirmComplete:"Confirm complete",confirmResult:"Confirm result",confirmAutoMergeTitle:e=>`Confirm and merge PR #${e}?`,confirmAutoMergeBody:e=>`Merge PR #${e} and finish the task. Agents can take new work.`,confirmManualCompleteTitle:"Confirm this result is complete?",confirmManualCompleteBody:e=>`Finish the task and free its Agents. You still need to merge PR #${e} manually.`,confirmResultTitle:"Confirm this result?",confirmResultBody:"Merge settings are unavailable. Confirming may merge the PR immediately and finish the task, freeing its Agents. Check the PR first.",confirmedMergedToastTitle:"PR merged; task complete",confirmedCompleteToastTitle:"Task marked complete",confirmFailedTitle:"Couldn’t confirm the result",taskNotFound:e=>`Task not found: ${e}`,unassignedPendingNotice:"Choose a Dev agent in “Edit task”, or start from an idle Agent’s card.",unassignedReadonlyNotice:"No Dev agent assigned. This task is view-only.",specReviewRound:e=>`Plan review · round ${e}`,codeReviewRound:e=>`Code review · round ${e}`,dispatching:"Preparing task…",dispatchingHint:"Preparing the working directory and sending the task. Please wait.",createdAtPrefix:"Created ",updatedAtPrefix:" · Updated ",originPrefix:" · From ",editTask:"Edit task",startTask:"Start task",startReview:"Start review",restartReview:"Restart review",retryCurrentStep:"Retry current step",retryPreMergeCheck:"Retry pre-merge checks",advancing:"Starting…",advanceSucceededTitle:"Current step started",advanceFailedTitle:"Couldn’t start this step",advanceConfirmTitle:e=>`${e}?`,startTaskConfirmBody:(e,n)=>`Task ${e} will start with Dev agent ${n}.`,startReviewConfirmBody:e=>`The current result for task ${e} will be sent to the QA agent. Existing work is kept.`,restartReviewConfirmBody:e=>`The current review for task ${e} will be sent to the QA agent again. Existing review records are kept.`,retryCurrentStepConfirmBody:e=>`The current step for task ${e} will be sent to the Dev agent again. Existing work and review records are kept.`,retryPreMergeConfirmBody:"Check the PR and its review again before continuing.",advanceRevokedConfirmTitle:"Check the PR again and continue finishing?",advanceRevokedRequestChangesBody:"New feedback arrived after approval. Work continues once it is resolved and the approval is still valid.",advanceRevokedRetryLimitBody:"Checks failed after several attempts. The PR and open feedback will be checked before retrying.",handleReview:"Handle review",verdictContinue:"Continue revising",verdictComplete:"Accept current version and merge",codeVerdictTitle:"Code review needs your decision",codeVerdictBody:"Automatic review has not produced a usable result. Review the PR, then confirm it or describe what needs to change.",codeCommentsPlaceholder:"What needs to change? Required when requesting changes; optional when confirming",codePass:"Confirm pass",codeRequestChanges:"Request changes",codePassConfirmTitle:"Confirm this code review passed?",codeRejectConfirmTitle:"Send this change request?",codeVerdictConfirmBody:"Your decision will be recorded on the PR so the task can continue.",codeVerdictSubmittedTitle:"Review decision saved to the PR",codeVerdictFailedTitle:"Couldn’t save the review decision",approvedBannerTitle:"Review passed · Final checks",approvedBannerBody:"Checking review feedback. You can confirm the result once checks finish.",viewPr:e=>`View PR #${e}`,mergeReadyBannerTitle:"Confirm the review result",mergeReadyAutoBody:e=>`Check PR #${e}. Confirming will merge it and finish the task.`,mergeReadyManualBody:e=>`Confirming will finish the task. You still need to merge PR #${e} manually.`,mergeReadyLoadingBody:"Loading merge settings. Please wait.",mergeReadyUnknownBody:"Merge settings are unavailable. Confirming may merge the PR immediately. Check it first.",specReadyBannerTitle:"Plan ready for your approval",specReadyNotice:e=>`Plan round ${e} passed review. Read it below, then approve to start development or request changes.`,specCommentsPlaceholder:"What needs to change? Required when requesting changes",submitting:"Submitting…",specApproveButton:"Approve plan and start development",specRejectTitleEmpty:"Describe what needs to change first",specRejectTitleReady:"The Dev agent will revise the plan using these comments",specReject:"Request plan changes",codeMaxRoundsTitle:e=>`Code review still has open questions after ${e} rounds`,codeMaxRoundsBody:"Continue revising, or accept the current version and merge the PR. Create a separate task for work outside the original scope.",specMaxRoundsTitle:e=>`Plan review still has open questions after ${e} rounds`,specMaxRoundsBody:"Read the discussion, then approve the plan or request changes. You can also cancel or restart the task.",noDescription:"(No description)",noLinkedAgent:"No linked Agent",cancelling:"Cancelling…",retryDisabledUnassignedTitle:"Choose a Dev agent before running this task again",retryEnabledTitle:"Creates a new task with the same content and starts it from the beginning",reviewRecoveryTitle:"Restore PR review",reviewRecoveryBody:"If a PR is published but review has not started, add its details here.",reviewRecoveryPrNumberLabel:"PR number (required)",reviewRecoveryPrNumberPlaceholder:"For example, 601",reviewRecoveryStageLabel:"PR contains (required)",reviewRecoveryStageSpec:"Plan",reviewRecoveryStageCode:"Code",reviewRecoverySubmit:"Save and start review",continueButtonTitle:"Starts another revision and sends the result back for review",completeButtonTitle:"Accepts the current version and merges the PR without another revision",confirmButtonTitle:"Review the PR before confirming the result",confirmLoadingTitle:"Wait for the project merge setting before confirming",loadingMergeSetting:"Loading merge setting…",confirming:"Confirming…",actionFailedBody:"Refresh the page to confirm the current task status before trying again.",attentionReviewTitle:"Review needs your attention",attentionMergeTitle:"The final checks could not finish",attentionAgentTitle:"The linked Agent was interrupted",attentionHandoffTitle:"The next step did not start",attentionDefaultTitle:"This task needs your attention",attentionDirtyWorkdirTitle:"The working directory has uncommitted changes",attentionDirtyWorkdirGuidance:"Commit or stash changes in the Agent’s working directory before continuing.",attentionCheckoutTitle:"The task working directory could not be prepared",attentionCheckoutGuidance:"Inspect the working directory or branch error below and resolve its cause.",attentionReplayTitle:"The task prompt could not be resent",attentionReplayGuidance:"Resolve the delivery error below. Resuming the Agent does not resend the task.",attentionBootstrapDeliveredTitle:"The initial prompt was already sent",attentionDeliveryUnknownTitle:"Prompt delivery is unconfirmed",attentionDeliveryUnknownGuidance:"The task may already be running. Check the Agent’s terminal first.",attentionBootstrapDeliveredGuidance:"Check the Agent’s terminal. Sending again could run the task twice.",attentionVerdictGuidance:"Review the PR and the discussion below, then confirm the result or request changes.",attentionAdvanceGuidance:"Check that the linked Agent and code platform are available, then retry the current step.",attentionRetryGuidance:"This task cannot continue. You can run it again from the beginning.",attentionCancelGuidance:"Review the task details, then cancel it if you no longer want it to continue.",noAgentSlot:e=>e==="dev"?"No Dev agent":"No QA agent"},untrackedFiles:{heading:"Working directory files",title:e=>e===1?"1 file has not been added to Git":`${e} files have not been added to Git`,unavailable:"File handling is temporarily unavailable.",conflicts:"Switching branches would overwrite these files. Move or rename them in the terminal, or discard listed files you no longer need.",manualCleanup:"Some files are ignored by Git or were previously kept. Handle them in the terminal, then refresh.",keepLimit:"Keeping these files would exceed 1000 paths or 64 KiB per task. Reduce the list and retry.",guidance:"Keep or discard these files to continue. Keeping does not commit them; this task remembers your choice for these paths.",keep:"Keep files and continue",discard:"Discard files and continue",readyToContinue:"Files are handled. You can continue; previously kept files stay unchanged.",continue:"Continue task",confirmTitle:"Discard these files?",confirmBody:"The listed files will be permanently deleted. This cannot be undone through Git.",refresh:"Refresh file list",loading:"Checking files…",working:"Handling files…",trackedChanges:"Files already in Git also have changes. Commit or stash them first.",directory:"Nested directories must be kept or handled in the terminal.",host:"Machine",workdir:"Working directory",agent:"Agent"},taskPanel:{ariaLabel:"Task panel",inProgressTitle:"In progress",pendingTitle:"Waiting to start",doneTitle:"Finished",round:e=>`Round ${e}`,emptyInProgress:"No tasks in progress yet",emptyPending:"No pending tasks yet",collapse:"Collapse",view:"View",loadMore:"Load more",emptyDone:"No completed tasks yet"},review:{loadExternalImage:"Load external image",loadFailed:e=>`Failed to load review records: ${e}`,loadingRecords:"Loading review records…",notStarted:"Review has not started",sectionTitle:"Review records",phaseLabel:{spec:"Plan review",code:"Code review"},reviewTurnLabel:"Review",responseTurnLabel:"Response",roleUser:"User",roleQa:"QA agent",roleDev:"Dev agent"},prReview:{reasonNoPr:"Review records will appear once the PR is created.",reasonDriverUnavailable:"PR review records are unavailable. Check the project’s code-platform configuration.",specReviewHeading:"Plan review",codeReviewHeading:"Code review",fetchFailed:e=>`Failed to fetch review records: ${e}`,partialFetchFailed:e=>`Some review records failed to fetch: ${e} (showing only what was retrieved).`,inlineComment:"Inline comment",comment:"Comment",replyIndicator:"↩ Reply",noReviewBody:"(No review body)",bodyTruncated:"Only part of this long content is shown.",truncatedSuffix:"(partial)",noReviewBodyFallback:"No review body",ghostAuthor:"Deleted account",listTruncated:"This PR has too many comments; only the earliest part is shown.",fetchedAtLabel:e=>`Refreshed ${e}`,nextCheck:e=>`Check again within ${e}s`,autoRefreshStopped:"Auto-refresh stopped",refresh:"Refresh",refreshing:"Refreshing…",refreshFailed:e=>`Refresh failed: ${e}`},toast:{dismissAriaLabel:"Close notification"},banner:{restartFailed:e=>`Restart failed: ${e}`,restarting:"Restarting…",pendingNotice:e=>`Restart baxian to apply ${e} setting change${e===1?"":"s"}.`,restartNow:"Restart now",preRestartFetchFailed:e=>`Could not check server status: ${e}`,restartTriggerFailed:e=>`Could not restart: ${e}`,restartTimeout:"Restart did not finish within 30 seconds. Check the logs or restart baxian manually.",platformDegraded:e=>`${e}: Connection unstable. Reviews and PR updates may be delayed; updates resume when connected.`,platformUnreachable:e=>`${e}: Cannot connect. Tasks are paused and will resume when connected.`,platformAccessDenied:(e,n)=>`${e}: Access denied. Tasks are paused. Check your login and permissions.${n?` ${n}`:""}`,platformRepoNotFound:e=>`${e}: Repository or requested content not found. Tasks are paused. Check the address, content, and access permissions.`,platformRateLimited:(e,n)=>`${e}: Too many requests. Updates will retry after ${new Date(n).toLocaleTimeString()}.`},terminal:{sessionEnded:"The terminal has not started or has ended.",sessionRecovery:"Retry Agent startup on the project page. For assigned tasks, follow the task page instructions. Reconnect once ready.",reconnect:"Reconnect",backToProject:"Back to project",keyPadAriaLabel:"Terminal keys",arrowAriaLabel:e=>`${e} arrow key`,arrowLabel:{up:"Up",down:"Down",left:"Left",right:"Right"},escKeyAriaLabel:"Esc key",noAgent:"No Agent selected"},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"}},lr={common:{cancel:"取消",confirm:"确认",close:"关闭",delete:"删除",deleting:"删除中…",edit:"编辑",retry:"重试",retrying:"重试中…",back:"← 返回",backText:"返回",loading:"加载中…",loadFailed:e=>`加载失败:${e}`,idFormatError:"2–32 个字符,以小写字母开头,可用小写字母、数字和连字符",create:"创建",creating:"创建中…",save:"保存",saving:"保存中…",oneClickInstall:"安装",installing:"安装中…",installingTmuxNotice:"正在安装 tmux,请保持窗口打开…",technicalDetails:"技术详情"},status:{pending:"待开始",in_progress:"处理中",review:"评审中",fixing:"修改中","spec-ready":"方案待确认",approved:"合并前检查中","merge-ready":"结果待确认",merged:"PR 已合并",done:"已完成",failed:"未能完成",max_rounds:"评审待决定",cancelled:"已取消"},statusContext:{pendingUnassigned:"待分配",inProgressSpec:"方案编写中",inProgressCode:"开发中",reviewSpec:"方案评审中",reviewCode:"代码评审中",fixingSpec:"方案修改中",fixingCode:"代码修改中",maxRoundsSpec:"方案评审待决定",maxRoundsCode:"代码评审待决定"},notification:{taskDone:e=>`任务完成:${e}`,bodyProject:e=>`项目:${e}`,bodyTask:e=>`任务:${e}`,bodyStatus:e=>`状态:${e}`},dashboard:{moreActions:"更多操作",newProject:"新建项目",manageHosts:"主机管理",newTask:"+ 新建任务",createProjectFirst:"请先创建项目",emptyProjects:"暂无项目。可在右上角菜单新建。",noAgentsYet:"暂无 Agent Team,请在项目详情中添加。",detailsLink:"详情 →",detailsAriaLabel:e=>`详情 — ${e}`,tasksLoadFailed:e=>`任务列表加载失败:${e}`,projectCreatedTitle:"项目已创建",addAgentNowOrLater:"现在添加 Agent Team?",later:"稍后再加",continueAddingAgent:"添加 Agent Team",title:"项目总览"},nav:{toggleToIcon:"切换为标志图标",toggleToText:"切换为标志文字"},agents:{runtimeStatus:{unknown:"未知",idle:"空闲",pending:"等待处理",working:"工作中",waiting:"等待中",error:"异常"},sessionStatus:{absent:"未运行",unreachable:"无法连接主机"},bootstrappingBadge:"启动中",dispatchingBadge:"准备中",dispatchingTitle:"正在准备工作目录并发送任务",agentStatusLoading:"Agent 状态加载中",bootstrappingTerminalDisabled:"Agent 正在启动",bootstrappingNotice:"Agent 正在启动,终端将自动连接。",terminalNeedsRestart:"重启 baxian 后可用",pendingRestartNotice:"重启 baxian 后生效",heldBadge:"已暂停",heldDefaultReason:"需要你处理",staleTitle:e=>e?`状态可能已过期,上次检查于 ${e}`:"状态可能已过期",awaitingHumanIntervention:"需要你处理",openTerminalPrefix:"请打开 ",openTerminalSuffix:" 处理。",terminal:"终端",needInputBadge:"等待回答",needInputTitle:e=>`Agent 在等你的回答(${e})`,needInputNoticeTitle:"Agent 在等你的回答",needInputPrefix:"请打开 ",needInputSuffix:" 回复。",activateTerminal:e=>`激活 ${e} 终端`,actionsMenu:e=>`Agent ${e} 操作菜单`,taskLabel:"任务:",stop:"取消任务",stopping:"取消中…",restartRuntime:"重启 Agent",openTerminalAction:"打开终端处理",openTaskActions:"查看任务",deleteToRecover:"删除 Agent",holdRecovery:{resume:"处理问题后,点击「恢复」。","restart-runtime":"请重启 Agent,重新检查是否可用。",terminal:"请在终端处理启动提示,完成后会自动恢复。",task:"请在任务页重试、处理评审或取消任务。","delete-agent":"请取消任务,或删除 Agent 后重建。此状态无法直接恢复。"},resume:"恢复",resuming:"恢复中…",resumeConfirmTitle:e=>`恢复 Agent ${e}?`,resumeGreetingBody:"Agent 未通过启动检查,将重新启动。检查通过后会自动恢复。",resumeDefaultBody:"解除暂停,让 Agent 恢复可用。",resumeGreetingButtonTitle:"重新启动并检查 Agent",resumeDefaultButtonTitle:"解除暂停,让 Agent 恢复可用",regreetingStartedTitle:e=>`Agent ${e} 正在重新检查`,regreetingStartedBody:"检查通过后会自动恢复。若仍失败,请按错误提示处理后重试。",resumedTitle:e=>`Agent ${e} 已恢复`,resumedReleasedBody:"Agent 可以接新任务了。",resumedKeptBody:"Agent 仍负责原任务。",resumeFailedTitle:"恢复失败",compact:"压缩对话",compacting:"压缩中…",compactMenuItemTitle:"精简对话,保留关键信息",compactSentTitle:e=>`已请求 ${e} 压缩对话`,compactFailedTitle:"压缩对话失败",clear:"清空对话",clearing:"清空中…",clearMenuItemTitle:"清除 Agent 的对话内容",clearConfirmTitle:e=>`清空 Agent ${e} 的对话?`,clearConfirmBody:"对话内容将被清空,无法恢复。",clearConfirmLabel:"清空",clearSentTitle:e=>`已请求 ${e} 清空对话`,clearFailedTitle:"清空对话失败",teamHeading:"Agent Team",teamLabel:e=>`Agent Team ${e}`,claimableTasksLabel:(e,n)=>`${e} 中可交给 ${n} 的任务`,teamActionsMenu:e=>`Agent Team ${e} 操作菜单`,teamCompactMenuItemTitle:"压缩 Agent Team 中所有 Agent 的对话",teamClearMenuItemTitle:"清空 Agent Team 中所有 Agent 的对话",teamCompactSentTitle:e=>`已请求 Agent Team ${e} 压缩对话`,teamClearConfirmTitle:e=>`清空 Agent Team ${e} 的对话?`,teamClearConfirmBody:"Agent Team 中所有 Agent 的对话都将被清空,无法恢复。",teamClearSentTitle:e=>`已请求 Agent Team ${e} 清空对话`,teamDeleteConfirmTitle:e=>`删除 Agent Team ${e}?`,teamDeletedTitle:e=>`已删除 Agent Team ${e}`,deleteConfirmTitle:e=>`删除包含 Agent ${e} 的 Agent Team?`,deleteConfirmBody:"Agent Team 中的所有 Agent 都会被移除,此操作不可撤销。",deletedWithTeamTitle:e=>`已删除包含 Agent ${e} 的 Agent Team`,deletedWithTeamBody:e=>`同一 Agent Team 的 Agent ${e} 也被一并移除。`,deletedTitle:e=>`Agent ${e} 已删除`,retryBootstrap:"重试准备环境",retrySession:"重试启动",retrySessionReady:"Agent 已就绪",retrySessionPending:"请打开终端处理启动弹窗",retrySessionFailed:"Agent 启动失败",retryBootstrapSucceededTitle:"环境已准备好",retryBootstrapSucceededBody:"Agent 状态将自动更新。",retryBootstrapStillFailingTitle:"环境准备仍失败",retryBootstrapStillFailingBody:"请按最新错误提示处理后重试。",retryBootstrapFailedTitle:"环境准备失败",round:e=>`第 ${e} 轮`,noActiveTask:"暂无任务",noActiveTaskAriaLabel:e=>`${e} 暂无任务`,unassigned:"未分配",start:"开始",starting:"开始中…",startFailed:"启动失败",taskHandedTo:(e,n)=>`任务 ${e} 已交给 ${n}`,handToAndStart:e=>`交给 ${e} 并立即开始`,agentUnavailable:e=>`Agent ${e} 当前不可用`,devRole:"Dev agent",qaRole:"QA agent"},settings:{entry:"系统设置",title:"系统设置",language:"语言",languageSaveFailed:e=>`语言保存失败:${e}`,taskNotifications:"任务完成通知",taskNotificationsDenied:"浏览器已拒绝通知权限",taskNotificationsHint:"任务完成或 PR 合并时通知你"},auth:{checkingTitle:"加载中",checkingBody:"正在检查登录状态…",connectFailedTitle:"无法连接服务器",connectFallback:"无法连接服务器",loginTitle:"登录 baxian",loginDescription:"请输入访问令牌。",loginFailed:"登录失败",sessionExpired:"登录已失效,请重新输入令牌",tokenInvalid:"令牌无效,请重试",tokenLabel:"访问令牌",tokenPlaceholder:"输入服务器的访问令牌",tokenRequired:"请输入访问令牌",submit:"登录",submitting:"登录中…"},createProject:{title:"新建项目",required:"必填",idLabel:"项目标识",idPlaceholder:"baxian",idTakenError:"该标识已被使用",repoLabel:"Git 仓库地址",mergeStrategyLabel:"合并方式",mergeHumanLabel:"手动合并(默认)",mergeAutoLabel:"确认结果后自动合并",specApprovalLabel:"方案确认",specApprovalHumanLabel:"需要你确认(默认)",specApprovalAutoLabel:"方案评审通过后自动开始开发",createdToastTitle:e=>`项目 ${e} 已创建`},createAgent:{modalTitle:e=>`添加 Agent Team 到 ${e}`,submitLabel:"添加 Agent Team",continueLabel:"下一步:配置 QA agent",submitting:"添加 Agent Team 中…",idTakenGlobalError:"该标识已被其他 Agent 使用",idPlaceholder:(e,n)=>`${e}-${n}`,roleLabel:"角色",devStepLabel:"Dev agent(1/2)",qaStepLabel:"QA agent(2/2)",teamDevLabel:e=>`与 Dev agent ${e} 组队`,modeLabel:"运行位置",localModeLabel:"本机",remoteModeLabel:"远程 (SSH)",noHostsHint:"请先在右上角的「主机管理」中添加主机。",selectHostPlaceholder:"请选择主机",sshConfigHint:"密钥和跳板机在 ~/.ssh/config 中配置;端口和密码在「主机管理」中设置。",runtimeLabel:"AI 工具",reprobeButton:"↻ 重新检测",selectHostFirstHint:"(请先选择主机)",probingLabel:"检测中…",tmuxProbingLabel:"tmux:检测中…",advancedOptionsLabel:"高级选项",expandLabel:"展开",collapseLabel:"收起",workdirLabel:"工作目录(可选)",workdirPlaceholder:"留空自动创建",workdirHint:"每个 Agent 需使用独立目录,不能共用。",modelLabel:"模型(可选)",modelPlaceholderCodex:"输入模型名称",modelPlaceholderOther:"例如 sonnet、opus",modelHint:"留空使用所选 AI 工具的默认模型。",addDirsLabel:"额外目录(可选)",addDirsPlaceholder:`每行一个绝对路径,例:
6
+ /Users/me/shared-libs
7
+ /Users/me/extra-repo`,addDirsHint:"允许 Agent 访问这些目录。",yoloTitle:"自动授权(推荐)",addedToastTitle:(e,n,s)=>`Agent Team ${e} + ${n} 已添加到 ${s}`,idLabel:"Agent 标识",hostLabel:"主机",yoloBody:"允许 Agent 直接执行操作,无需逐次确认。关闭后,可能需要在终端确认权限。",yoloCodexBody:"无需逐次确认,并关闭限制文件访问和命令执行的沙箱。关闭后,可能需要在终端确认权限。"},createTask:{titleCreate:"新建任务",titleEdit:"编辑任务",selectProjectPlaceholder:"选择项目",targetAgentLabel:"Dev agent",notAssignedOption:"暂不指定",pendingRestartSuffix:"(待重启)",notInRuntimeSuffix:"(不可用)",titlePlaceholder:"一句话描述要做什么",descriptionLabel:"任务说明(可选)",descriptionPlaceholder:"补充要求,支持 Markdown",imagesLabel:"图片(可选)",addImagesButton:"添加图片",removeImageAriaLabel:e=>`移除图片 ${e}`,draftRestoredNotice:"已恢复上次未提交的草稿",discardDraftButton:"丢弃草稿",updatedToastTitle:"任务已更新",createdToastTitle:"任务已创建",imageTooLargeToastTitle:"图片过大",imageTooLargeToastBody:(e,n)=>`${e} 超过 ${n} MiB`,tooManyImagesToastTitle:e=>`最多 ${e} 张图片`,noDevPendingRestartHint:e=>`Agent ${e} 尚未启动,请重启 baxian。`,noDevNotInRuntimeHint:e=>`Agent ${e} 不可用,保存可能失败。请检查配置或选择其他 Agent。`,noDevGlobalPendingRestartHint:"Dev agent 尚未启动,请重启 baxian。",projectLabel:"项目",titleLabel:"任务标题"},hostMgmt:{title:"主机管理",emptyState:"暂无主机。",addHostButton:"+ 添加主机",passwordSavedIndicator:" · 密码已保存",addressLabel:"主机地址",portLabel:"端口(可选)",portRangeError:"端口需为 1–65535 的整数",aliasLabel:"别名(可选)",userLabel:"用户名(可选)",userPlaceholder:"留空使用 SSH 配置中的用户名",passwordLabel:"密码(可选)",passwordPlaceholderSet:"已设置,留空保持不变",passwordPlaceholderUnset:"留空使用密钥登录",clearPasswordLabel:"清除密码,改用密钥登录",passwordHintLead:"建议使用 ",passwordHintStrong:"SSH 密钥登录。",plaintextWarningLead:"填写的密码将以",plaintextWarningStrong:"明文",plaintextWarningTrail:"保存在配置文件中。",testConnection:"测试连接",testing:"测试中…",createdToastTitle:e=>`主机 ${e} 已添加`,updatedToastTitle:e=>`主机 ${e} 已更新`,deletedToastTitle:e=>`主机 ${e} 已删除`,aliasPlaceholder:"例如:开发服务器"},projectPage:{newTaskButton:"+ 新建任务",menuAriaLabel:e=>`项目 ${e} 操作菜单`,showTaskPanel:"显示任务面板",addAgent:"添加 Agent Team",deleteAgentsFirstHint:e=>`请先删除项目下的 ${e} 个 Agent`,deleteProjectMenuItem:"删除项目…",noAgentsYet:"还没有 Agent Team,点击右上角菜单添加。",closeTaskPanel:"关闭任务面板",deleteModalTitle:"删除项目",confirmDeleteButton:"确认删除",deleteBodyLead:"将删除项目 ",deleteBodySuffix:"。此操作无法撤销,Git 仓库会保留。",confirmInputLead:"输入项目标识 ",confirmInputSuffix:" 以确认删除:",confirmInputAriaLabel:"输入项目标识以确认删除",deletedToastTitle:e=>`项目 ${e} 已删除`,agentsHeading:"Agent Team",tasksHeading:"任务"},taskDetail:{cancelConfirmTitle:e=>`取消任务 ${e}?`,cancelConfirmLabel:"取消任务",cancelledToastTitle:"任务已取消",cancelFailedTitle:"未能取消任务",cancelForceTitle:"停止任务,让 Agent 可以接新任务",cancelConfirmBodyActive:"将停止任务,关闭已发布的 PR 并清理任务分支。Agent 可接新任务;你也可以重新执行此任务。",cancelConfirmBodyTerminal:"任务已结束,状态不变。关联 Agent 将可接新任务。",cancelCleanupToastTitle:"Agent 已可接新任务",retryTask:"重新执行任务",retryConfirmTitle:e=>`重新执行任务 ${e}?`,retryConfirmBodyMerged:"PR 已合并。将以相同内容新建任务,从头执行。",retryConfirmBodyDefault:"将以相同内容新建任务,从头执行。当前任务保留在历史记录中。",retryCreatedToastTitle:e=>`已新建任务 ${e}`,retryFailedTitle:"未能启动新任务",markCompleteConfirmTitle:"接受当前版本并合并?",markCompleteConfirmBody:e=>`将直接合并 PR #${e} 并结束任务,未解决的评审意见不再修改。`,completing:"收尾中…",markCompleteToastTitle:"已接受当前版本,正在合并 PR",markCompleteFailedTitle:"未能接受并合并当前版本",branchCleanupPendingTitle:"本地任务分支暂时保留",branchCleanupPendingBody:"为避免丢失改动,暂时保留本地任务分支。",branchCleanupSkippedTitle:"本地任务分支已保留",branchCleanupSkippedBody:"本地任务分支已保留,可稍后检查或手动删除。",continueConfirmTitle:"继续修改?",continueConfirmBody:e=>`将开始第 ${e} 轮修改,完成后重新评审。`,continuing:"正在开始修改…",continuedToastTitle:e=>`已开始第 ${e} 轮修改`,continueFailedTitle:"未能开始新一轮修改",specApproveConfirmTitle:"批准方案并开始开发?",specApproveConfirmBody:e=>`任务 ${e} 将按当前方案开始开发。`,specApprove:"批准方案",specApprovedToastTitle:"方案已批准,开发已开始",specApproveFailedTitle:"未能批准方案",specRejectedToastTitle:"修改要求已发送,Dev agent 正在修改方案",specRejectFailedTitle:"未能提交方案修改要求",confirmAndMerge:"确认并合并",confirmComplete:"确认完成",confirmResult:"确认结果",confirmAutoMergeTitle:e=>`确认并合并 PR #${e}?`,confirmAutoMergeBody:e=>`将合并 PR #${e} 并结束任务,Agent 可接新任务。`,confirmManualCompleteTitle:"确认当前结果已完成?",confirmManualCompleteBody:e=>`将结束任务,Agent 可接新任务。PR #${e} 仍需你手动合并。`,confirmResultTitle:"确认当前结果?",confirmResultBody:"无法读取合并设置。确认后可能立即合并 PR 并结束任务,Agent 可接新任务。请先检查 PR。",confirmedMergedToastTitle:"PR 已合并,任务已完成",confirmedCompleteToastTitle:"任务已确认完成",confirmFailedTitle:"未能确认结果",taskNotFound:e=>`任务不存在:${e}`,unassignedPendingNotice:"请编辑任务选择 Dev agent,或从空闲 Agent 的卡片开始任务。",unassignedReadonlyNotice:"未分配 Dev agent,当前只能查看。",specReviewRound:e=>`方案评审 · 第 ${e} 轮`,codeReviewRound:e=>`代码评审 · 第 ${e} 轮`,dispatching:"正在准备任务…",dispatchingHint:"正在准备工作目录并发送任务,请稍候。",createdAtPrefix:"创建于 ",updatedAtPrefix:" · 更新于 ",originPrefix:" · 来自 ",editTask:"编辑任务",startTask:"开始任务",startReview:"开始评审",restartReview:"重新发起评审",retryCurrentStep:"重试当前步骤",retryPreMergeCheck:"重试合并前检查",advancing:"正在开始…",advanceSucceededTitle:"当前步骤已开始",advanceFailedTitle:"未能开始当前步骤",advanceConfirmTitle:e=>`${e}?`,startTaskConfirmBody:(e,n)=>`任务 ${e} 将交给 Dev agent ${n} 开始处理。`,startReviewConfirmBody:e=>`任务 ${e} 的当前结果将交给 QA agent,已有改动会保留。`,restartReviewConfirmBody:e=>`任务 ${e} 的当前评审会重新交给 QA agent,已有评审记录会保留。`,retryCurrentStepConfirmBody:e=>`任务 ${e} 的当前步骤会重新交给 Dev agent,已有改动和评审记录会保留。`,retryPreMergeConfirmBody:"将重新检查 PR 和评审结果,通过后继续。",advanceRevokedConfirmTitle:"重新检查 PR 并继续收尾?",advanceRevokedRequestChangesBody:"评审通过后有新反馈。处理完反馈且评审仍有效,才能继续。",advanceRevokedRetryLimitBody:"多次检查仍未完成。将检查 PR 和未处理的反馈后重试。",handleReview:"处理评审",verdictContinue:"继续修改",verdictComplete:"接受当前版本并合并",codeVerdictTitle:"代码评审需要你决定",codeVerdictBody:"自动评审暂未给出可用结果。请先查看 PR,再确认通过或填写修改要求。",codeCommentsPlaceholder:"需要修改什么?要求修改时必填,确认通过时可选",codePass:"确认通过",codeRequestChanges:"要求修改",codePassConfirmTitle:"确认代码评审通过?",codeRejectConfirmTitle:"发送这些修改要求?",codeVerdictConfirmBody:"你的决定会记录到 PR,任务随后继续。",codeVerdictSubmittedTitle:"评审决定已保存到 PR",codeVerdictFailedTitle:"未能保存评审决定",approvedBannerTitle:"评审已通过,正在最终检查",approvedBannerBody:"正在核对评审意见,完成后请你确认结果。",viewPr:e=>`查看 PR #${e}`,mergeReadyBannerTitle:"请确认评审结果",mergeReadyAutoBody:e=>`请检查 PR #${e},确认后将合并并结束任务。`,mergeReadyManualBody:e=>`确认后将结束任务,PR #${e} 仍需你手动合并。`,mergeReadyLoadingBody:"正在读取合并设置,请稍候。",mergeReadyUnknownBody:"无法读取合并设置。确认后可能立即合并,请先检查 PR。",specReadyBannerTitle:"请确认方案",specReadyNotice:e=>`方案已通过第 ${e} 轮评审。请查看下方内容,批准后开始开发,也可提出修改要求。`,specCommentsPlaceholder:"需要修改什么?要求修改时必填",submitting:"提交中…",specApproveButton:"批准方案并开始开发",specRejectTitleEmpty:"请先填写需要修改的内容",specRejectTitleReady:"Dev agent 会根据这些意见修改方案",specReject:"要求修改方案",codeMaxRoundsTitle:e=>`代码评审经过 ${e} 轮仍有待确认问题`,codeMaxRoundsBody:"可继续修改,或接受当前版本并合并 PR。超出任务范围的工作可另建任务。",specMaxRoundsTitle:e=>`方案评审经过 ${e} 轮仍有待确认问题`,specMaxRoundsBody:"请查看下方讨论,批准方案或提出修改要求。也可取消或重新执行任务。",noDescription:"(无描述)",noLinkedAgent:"暂无关联 Agent",cancelling:"取消中…",retryDisabledUnassignedTitle:"重新执行前,请先选择 Dev agent",retryEnabledTitle:"使用相同内容新建任务并从头开始处理",reviewRecoveryTitle:"恢复 PR 评审",reviewRecoveryBody:"已发布 PR 但未开始评审时,可在此填写 PR 信息。",reviewRecoveryPrNumberLabel:"PR 号(必填)",reviewRecoveryPrNumberPlaceholder:"例如 601",reviewRecoveryStageLabel:"PR 内容(必填)",reviewRecoveryStageSpec:"方案",reviewRecoveryStageCode:"代码",reviewRecoverySubmit:"保存并开始评审",continueButtonTitle:"开始新一轮修改,完成后重新评审",completeButtonTitle:"不再修改,接受当前版本并合并 PR",confirmButtonTitle:"确认结果前请先检查 PR",confirmLoadingTitle:"请等待项目合并设置加载完成",loadingMergeSetting:"正在加载合并设置…",confirming:"确认中…",actionFailedBody:"请刷新页面确认任务当前状态,再决定是否重试。",attentionReviewTitle:"评审需要你处理",attentionMergeTitle:"最终检查未能完成",attentionAgentTitle:"关联 Agent 的处理已中断",attentionHandoffTitle:"下一步骤未能开始",attentionDefaultTitle:"任务需要你处理",attentionDirtyWorkdirTitle:"工作目录有未提交改动",attentionDirtyWorkdirGuidance:"请先在 Agent 的工作目录中提交或暂存改动,再继续。",attentionCheckoutTitle:"任务工作目录准备失败",attentionCheckoutGuidance:"请检查并处理下方工作目录或分支错误。",attentionReplayTitle:"任务指令未能重新发送",attentionReplayGuidance:"请处理下方发送错误。恢复 Agent 不会重新发送任务。",attentionBootstrapDeliveredTitle:"初始任务指令已经发送",attentionDeliveryUnknownTitle:"任务指令的发送结果尚未确认",attentionDeliveryUnknownGuidance:"任务可能已在执行,请先到 Agent 终端核实。",attentionBootstrapDeliveredGuidance:"请到 Agent 终端核实结果,重复发送可能导致任务执行两次。",attentionVerdictGuidance:"请查看 PR 和下方评审记录,然后确认结果或提出修改要求。",attentionAdvanceGuidance:"请确认关联 Agent 和代码平台可用,然后重试当前步骤。",attentionRetryGuidance:"任务无法继续,可从头重新执行。",attentionCancelGuidance:"请先检查任务详情;如果不再需要继续,可以取消任务。",noAgentSlot:e=>e==="dev"?"暂无 Dev agent":"暂无 QA agent"},untrackedFiles:{heading:"工作目录文件",unavailable:"当前暂时无法处理文件。",conflicts:"切换分支会覆盖下列文件。请在终端移动或重命名,也可丢弃清单中不需要的文件。",manualCleanup:"部分文件被 Git 忽略或此前已保留,请在终端处理后刷新。",keepLimit:"保留后将超出每个任务的上限(1000 个路径或 64 KiB)。请减少文件后重试。",title:e=>`有 ${e} 个文件尚未加入 Git`,guidance:"保留或丢弃这些文件后可继续。保留不会自动提交,本任务不会重复询问同一批文件。",keep:"保留文件并继续",discard:"丢弃文件并继续",readyToContinue:"文件已处理,可以继续任务。此前保留的文件不变。",continue:"继续任务",confirmTitle:"丢弃这些文件?",confirmBody:"清单中的文件将被永久删除,无法通过 Git 撤销。",refresh:"刷新文件清单",loading:"正在检查文件…",working:"正在处理…",trackedChanges:"Git 中已有的文件也被修改,请先提交或暂存改动。",directory:"清单中有嵌套目录,只能保留或在终端处理。",host:"所在机器",workdir:"工作目录",agent:"Agent"},taskPanel:{ariaLabel:"任务面板",inProgressTitle:"处理中",pendingTitle:"待开始",doneTitle:"已结束",round:e=>`第 ${e} 轮`,emptyInProgress:"暂无正在处理的任务",emptyPending:"暂无待处理的任务",collapse:"收起",view:"查看",loadMore:"加载更多",emptyDone:"暂无已处理的任务"},review:{loadExternalImage:"加载外部图片",loadFailed:e=>`加载评审记录失败:${e}`,loadingRecords:"加载评审记录…",notStarted:"评审尚未开始",sectionTitle:"评审记录",phaseLabel:{spec:"方案评审",code:"代码评审"},reviewTurnLabel:"评审",responseTurnLabel:"反馈",roleUser:"用户",roleQa:"QA agent",roleDev:"Dev agent"},prReview:{reasonNoPr:"创建 PR 后,这里会显示评审记录。",reasonDriverUnavailable:"暂时无法读取 PR 评审记录,请检查项目的代码平台配置。",specReviewHeading:"方案评审",codeReviewHeading:"代码评审",fetchFailed:e=>`评审记录拉取失败:${e}`,partialFetchFailed:e=>`部分评审记录拉取失败:${e}(仅展示已获取的部分)`,inlineComment:"行内评论",comment:"评论",replyIndicator:"↩ 回复",noReviewBody:"(无评审正文)",bodyTruncated:"内容过长,仅显示部分。",truncatedSuffix:"(部分内容)",noReviewBodyFallback:"无评审正文",ghostAuthor:"已注销的账号",listTruncated:"该 PR 评论过多,仅展示靠前的一部分。",fetchedAtLabel:e=>`刷新于 ${e}`,nextCheck:e=>`${e} 秒内再次检查`,autoRefreshStopped:"已停止自动更新",refresh:"刷新",refreshing:"刷新中…",refreshFailed:e=>`刷新失败:${e}`},toast:{dismissAriaLabel:"关闭通知"},banner:{restartFailed:e=>`重启失败:${e}`,restarting:"重启中…",pendingNotice:e=>`${e} 项设置待生效,请重启 baxian。`,restartNow:"现在重启",preRestartFetchFailed:e=>`无法读取服务状态:${e}`,restartTriggerFailed:e=>`无法重启:${e}`,restartTimeout:"30 秒内未完成重启,请检查日志或手动重启 baxian。",platformDegraded:e=>`${e}:连接不稳定,评审和 PR 更新可能延迟。恢复连接后会自动更新。`,platformUnreachable:e=>`${e}:无法连接,任务已暂停。恢复连接后会自动继续。`,platformAccessDenied:(e,n)=>`${e}:无权访问,任务已暂停。请检查登录状态和访问权限。${n?` ${n}`:""}`,platformRepoNotFound:e=>`${e}:找不到仓库或所需内容,任务已暂停。请检查地址、内容是否存在及访问权限。`,platformRateLimited:(e,n)=>`${e}:请求过于频繁,将于 ${new Date(n).toLocaleTimeString()} 后自动重试。`},terminal:{sessionEnded:"终端未启动或已结束。",sessionRecovery:"请在项目页重试启动 Agent;如有任务,按任务页提示处理。启动后可重新连接。",reconnect:"重新连接",backToProject:"返回项目",keyPadAriaLabel:"终端按键",arrowAriaLabel:e=>`方向键 ${e}`,arrowLabel:{up:"上",down:"下",left:"左",right:"右"},escKeyAriaLabel:"Esc 键",noAgent:"未选择 Agent"},imageUpload:{tooLargeBody:e=>`单张图片不能超过 ${e} MiB`,insertedTitle:"图片已插入",insertedBody:"路径已粘贴到终端输入,补充说明后回车",uploadFailedTitle:"图片上传失败",uploadAriaLabel:"上传图片"}},an="baxian.language",tt="en-US",Xn={"en-US":Jn,"zh-CN":lr};function Zn(e){return e==="zh-CN"||e==="en-US"}function es(){try{const e=localStorage.getItem(an);return Zn(e)?e:tt}catch{return tt}}function ts(e){try{localStorage.setItem(an,e)}catch{}}let Ge=es();const Vt=new Set;let jt=0,cr=0,vn=0;function on(e){e!==Ge&&(Ge=e,Vt.forEach(n=>n(e)))}function Qt(e){jt+=1;const n=e??tt;ts(n),on(n)}function dr(e){const n=e??tt;ts(n),on(n)}function ns(){return Xn[Ge]}const ss=o.createContext({locale:tt,messages:Jn,saving:!1,setLocale:async()=>{throw new Error("setLocale requires I18nProvider")}});function ur({children:e}){const[n,s]=o.useState(Ge),[r,a]=o.useState(!1);o.useEffect(()=>{const l=c=>s(c);return Vt.add(l),s(Ge),()=>{Vt.delete(l)}},[]),o.useEffect(()=>{document.documentElement.lang=n==="zh-CN"?"zh-CN":"en"},[n]),o.useEffect(()=>{const l=c=>{if(c.key!==null&&c.key!==an)return;const m=c.key===null?es():c.newValue;Zn(m)&&(jt+=1,on(m))};return window.addEventListener("storage",l),()=>window.removeEventListener("storage",l)},[]);const i=async l=>{if(l!==Ge){a(!0);try{await M.config.patch({language:l}),Qt(l)}finally{a(!1)}}};return t.jsx(ss.Provider,{value:{locale:n,messages:Xn[n],saving:r,setLocale:i},children:e})}function rs(){return o.useContext(ss)}function H(){return rs().messages}function mr(){o.useEffect(()=>{const e=()=>{const s=jt,r=++cr;M.config.get().then(a=>{s===jt&&(r<=vn||(vn=r,dr(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 as=o.createContext(null),hr={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"},fr={success:ar,warn:ir,error:or};let pr=1;function gr({children:e}){const n=H(),[s,r]=o.useState([]),a=o.useRef(new Map),i=o.useRef(new Map);o.useEffect(()=>{const u=a.current,d=i.current;return()=>{for(const x of u.values())clearTimeout(x);u.clear(),d.clear()}},[]);const l=o.useCallback(u=>{const d=a.current.get(u);d&&clearTimeout(d),a.current.delete(u)},[]),c=o.useCallback(u=>{l(u),i.current.delete(u),r(d=>d.filter(x=>x.id!==u))},[l]),m=o.useCallback((u,d)=>{l(u),a.current.set(u,setTimeout(()=>c(u),d))},[l,c]),h=o.useCallback((u,d)=>{const x=i.current.get(u)??new Set;x.add(d),i.current.set(u,x),l(u)},[l]),f=o.useCallback((u,d,x)=>{const b=i.current.get(u);b==null||b.delete(d),(!b||b.size===0)&&m(u,x)},[m]),p=o.useCallback(u=>{const d=pr++,x=u.durationMs??3e3;r(b=>[...b,{...u,id:d,durationMs:x}]),m(d,x)},[m]);return t.jsxs(as.Provider,{value:{show:p},children:[e,t.jsx("div",{className:"pointer-events-none fixed inset-x-4 top-4 z-[60] flex flex-col items-end gap-2",children:s.map(u=>t.jsx("div",{className:`pointer-events-auto w-full max-w-xs rounded-lg border px-4 py-3 shadow-toast ${hr[u.kind]}`,role:"status",onMouseEnter:()=>h(u.id,"hover"),onMouseLeave:()=>f(u.id,"hover",u.durationMs),onFocus:()=>h(u.id,"focus"),onBlur:d=>{d.currentTarget.contains(d.relatedTarget)||f(u.id,"focus",u.durationMs)},children:t.jsxs("div",{className:"flex items-start gap-2",children:[(()=>{const d=fr[u.kind];return t.jsx(d,{className:"mt-0.5 shrink-0",width:14,height:14})})(),t.jsxs("div",{className:"flex-1",children:[t.jsx("div",{className:"text-sm font-semibold",children:u.title}),u.body&&t.jsx("div",{className:"mt-1 whitespace-pre-line text-xs text-og-700",children:u.body}),u.details&&t.jsxs("details",{className:"mt-1 text-xs text-og-500",children:[t.jsx("summary",{className:"cursor-pointer select-none text-accent",children:n.common.technicalDetails}),t.jsx("div",{className:"mt-1 whitespace-pre-wrap break-words font-mono",children:u.details})]})]}),t.jsx("button",{type:"button",onClick:()=>c(u.id),className:"text-current opacity-50 transition-opacity hover:opacity-100","aria-label":n.toast.dismissAriaLabel,children:"✕"})]})},u.id))})]})}function je(){const e=o.useContext(as);if(!e)throw new Error("useToast must be inside <ToastProvider>");return e}const xr={sm:"max-w-md",md:"max-w-lg",lg:"max-w-2xl"},yn='input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), [href], [tabindex]:not([tabindex="-1"])',He=[];function Ce({open:e,onClose:n,title:s,titleContent:r,children:a,footer:i,size:l="md",dismissOnBackdrop:c=!0}){const m=H(),h=o.useRef(null),f=o.useRef();f.current||(f.current=Symbol("modal"));const p=o.useRef(null),u=o.useRef(!1),d=o.useRef(n);return o.useEffect(()=>{d.current=n},[n]),o.useEffect(()=>{if(!e)return;const x=f.current;He.push(x);const b=()=>He[He.length-1]===x;p.current=document.activeElement;const y=A=>{if(!b())return;if(A.key==="Escape"){d.current();return}if(A.key!=="Tab")return;const w=h.current;if(!w)return;const k=Array.from(w.querySelectorAll(yn)).filter(P=>P.offsetParent!==null||P===document.activeElement);if(k.length===0){A.preventDefault();return}const j=k[0],v=k[k.length-1],D=document.activeElement;A.shiftKey&&(D===j||!w.contains(D))?(A.preventDefault(),v.focus()):!A.shiftKey&&(D===v||!w.contains(D))&&(A.preventDefault(),j.focus())};document.addEventListener("keydown",y);const T=document.body.style.overflow;document.body.style.overflow="hidden";const R=h.current;if(R){const A=R.querySelector(yn);A==null||A.focus()}return()=>{var w,k;const A=He.indexOf(x);A>=0&&He.splice(A,1),document.removeEventListener("keydown",y),document.body.style.overflow=T,(k=(w=p.current)==null?void 0:w.focus)==null||k.call(w)}},[e]),e?t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-og-1000/45 px-3 sm:px-4",onMouseDown:c?x=>{u.current=x.target===x.currentTarget&&He[He.length-1]===f.current}:void 0,onClick:c?x=>{x.target===x.currentTarget&&u.current&&d.current()}:void 0,role:"presentation",children:t.jsxs("div",{ref:h,className:`flex w-full ${xr[l]} max-h-[90dvh] flex-col overflow-hidden rounded-lg border border-og-100 bg-surface shadow-modal`,onClick:x=>x.stopPropagation(),role:"dialog","aria-modal":"true","aria-label":s,children:[t.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-hairline px-5 py-3",children:[t.jsx("h2",{title:s,className:"min-w-0 truncate font-display text-sm font-semibold tracking-tight text-og-1000",children:r??s}),t.jsx("button",{type:"button",onClick:()=>d.current(),className:"-mr-1 flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-og-400 transition-colors hover:bg-og-50 hover:text-og-800","aria-label":m.common.close,children:"✕"})]}),t.jsx("div",{className:"min-h-0 flex-1 overflow-auto px-5 py-4",children:a}),i&&t.jsx("div",{className:"flex shrink-0 flex-wrap items-center justify-end gap-2 border-t border-hairline px-5 py-3",children:i})]})}):null}const is=o.createContext(null);function br({children:e}){const n=H(),[s,r]=o.useState(null),a=o.useRef(null),i=o.useCallback(c=>new Promise(m=>{var f;(f=a.current)==null||f.resolve(!1);const h={...c,resolve:m};a.current=h,r(h)}),[]),l=o.useCallback(c=>{const m=a.current;m&&(a.current=null,r(null),m.resolve(c))},[]);return t.jsxs(is.Provider,{value:i,children:[e,s&&t.jsx(Ce,{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 ln(){const e=o.useContext(is);if(!e)throw new Error("useConfirm must be inside <ConfirmProvider>");return e}const Tt="baxian.pendingRestart",vr=500,yr=3e4,os=o.createContext(null);function wr(){try{const e=localStorage.getItem(Tt);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 kr(e){try{e.count<=0?localStorage.removeItem(Tt):localStorage.setItem(Tt,JSON.stringify(e))}catch{}}function jr({children:e}){const n=H(),s=wr(),[r,a]=o.useState(s.count),[i,l]=o.useState(s.baselineStartedAt),[c,m]=o.useState(s.count>0?"pending":"idle"),[h,f]=o.useState(),p=o.useRef(s.count),u=o.useRef(s.count>0?"pending":"idle"),d=o.useRef(0),x=o.useCallback(w=>{p.current=w,a(w)},[]),b=o.useCallback(w=>{a(k=>{const j=w(k);return p.current=j,j})},[]),y=o.useCallback(w=>{u.current=w,m(w)},[]);o.useEffect(()=>{kr({count:r,baselineStartedAt:i})},[r,i]),o.useEffect(()=>{let w=!1;(async()=>{try{const j=await M.health.get();if(w)return;l(v=>v!==null&&j.startedAt!==v?(x(0),y("idle"),null):v)}catch{}})();const k=j=>{if(j.key===Tt){if(j.newValue===null){if(u.current==="restarting"&&d.current>0){x(d.current),l(null);return}x(0),l(null),u.current!=="restarting"&&y("idle");return}try{const v=JSON.parse(j.newValue);typeof v.count=="number"&&(u.current==="restarting"&&v.count>p.current&&(d.current+=v.count-p.current),x(v.count),u.current!=="restarting"&&y(v.count>0?"pending":"idle")),typeof v.baselineStartedAt=="string"?l(v.baselineStartedAt):v.baselineStartedAt===null&&l(null)}catch{}}};return window.addEventListener("storage",k),()=>{w=!0,window.removeEventListener("storage",k)}},[x,y]);const T=o.useRef(!1),R=o.useCallback(()=>{b(w=>w+1),u.current==="restarting"?d.current+=1:y("pending"),l(w=>(w!==null||T.current||(T.current=!0,(async()=>{try{const k=await M.health.get();l(j=>j??k.startedAt)}catch{}finally{T.current=!1}})()),w))},[y,b]),A=o.useCallback(async()=>{d.current=0,f(void 0),y("restarting");let w;try{w=(await M.health.get()).startedAt}catch(j){y("failed"),f(n.banner.preRestartFetchFailed(j instanceof Error?j.message:String(j)));return}try{await M.server.restart()}catch(j){if(!(j instanceof ze&&j.status===409)){y("failed"),f(n.banner.restartTriggerFailed(j instanceof Error?j.message:String(j)));return}}const k=Date.now();for(;Date.now()-k<yr;){await new Promise(j=>setTimeout(j,vr));try{const j=await M.health.get();if(j.startedAt!==w){const v=d.current;d.current=0,l(v>0?j.startedAt:null),x(v),y(v>0?"pending":"idle");return}}catch{}}y("failed"),f(n.banner.restartTimeout)},[x,y,n]);return t.jsx(os.Provider,{value:{phase:c,count:r,error:h,flagDirty:R,triggerRestart:A},children:e})}function Lt(){const e=o.useContext(os);if(!e)throw new Error("usePendingRestart must be used inside PendingRestartProvider");return e}function wn(e){return e instanceof Error?e.message:String(e)}function ls(e,n,s){const r=H(),{show:a}=je(),i=ln(),{flagDirty:l}=Lt(),[c,m]=o.useState(!1),[h,f]=o.useState(!1),[p,u]=o.useState(!1),[d,x]=o.useState(null),b=n[0]??"",y=n.join(" / "),T=n.length>1,R=async j=>(await Promise.allSettled(n.map(D=>j(D)))).flatMap((D,P)=>D.status==="rejected"?[`${n[P]}: ${wn(D.reason)}`]:[]);return{compact:async()=>{m(!0);try{const j=await R(v=>M.agents.compact(v));if(j.length>0){a({kind:"error",title:r.agents.compactFailedTitle,body:j.join(`
8
+ `)});return}a({kind:"success",title:T?r.agents.teamCompactSentTitle(y):r.agents.compactSentTitle(b)})}finally{m(!1)}},clear:async()=>{if(await i({title:T?r.agents.teamClearConfirmTitle(y):r.agents.clearConfirmTitle(b),body:T?r.agents.teamClearConfirmBody:r.agents.clearConfirmBody,confirmLabel:r.agents.clearConfirmLabel})){f(!0);try{const v=await R(D=>M.agents.clear(D));if(v.length>0){a({kind:"error",title:r.agents.clearFailedTitle,body:v.join(`
9
+ `)});return}a({kind:"success",title:T?r.agents.teamClearSentTitle(y):r.agents.clearSentTitle(b)})}finally{f(!1)}}},remove:async()=>{if(await i({title:T?r.agents.teamDeleteConfirmTitle(y):r.agents.deleteConfirmTitle(b),body:r.agents.deleteConfirmBody,confirmLabel:r.common.delete})){u(!0),x(null);try{const v=await M.projects.deleteAgent(e,b);v!=null&&v.restartRequired&&l();const D=(v==null?void 0:v.removed)??[b],P=[...(v==null?void 0:v.warnings)??[]],I=T?[]:D.filter(J=>J!==b);I.length>0&&P.unshift(r.agents.deletedWithTeamBody(I.join(", ")));const O=T?r.agents.teamDeletedTitle(y):I.length>0?r.agents.deletedWithTeamTitle(b):r.agents.deletedTitle(b);a(P.length>0?{kind:"warn",title:O,body:P.join(`
10
+ `)}:{kind:"success",title:O}),s==null||s()}catch(v){x(wn(v))}finally{u(!1)}}},compacting:c,clearing:h,deleting:p,deleteError:d,busy:c||h||p}}const Tr=[500,1e3,2e3,4e3,8e3,15e3,3e4];class cs{constructor(n){ce(this,"attempts",0);ce(this,"timer",null);ce(this,"delaysMs");this.opts=n,this.delaysMs=n.delaysMs??Tr}schedule(){if(this.timer||!this.shouldReconnect())return;const n=this.delaysMs[Math.min(this.attempts,this.delaysMs.length-1)];this.attempts+=1,this.timer=setTimeout(()=>{this.timer=null,this.shouldReconnect()&&this.opts.reconnect()},n)}cancel(){this.timer&&(clearTimeout(this.timer),this.timer=null)}reset(){this.attempts=0}shouldReconnect(){return this.opts.shouldReconnect?this.opts.shouldReconnect():!0}}function ds(e,n,s){return(e==null?void 0:e.code)!==4401||n!==s?!1:(window.dispatchEvent(new CustomEvent(et)),!0)}function us(e){return Array.from(new TextEncoder().encode(e)).map(n=>n.toString(16).padStart(2,"0")).join("")}function ms(e){return`${location.protocol==="https:"?"wss":"ws"}://${location.host}${e}`}const hs=(e,n)=>n&&n.length>0?new WebSocket(e,n):new WebSocket(e);let kn=0;function Sr(){kn++;const e=Math.random().toString(36).slice(2,8);return`sub-${Date.now().toString(36)}-${kn}-${e}`}function Nr(){return ms("/api/stream")}class Cr{constructor(n={}){ce(this,"wsUrl");ce(this,"wsFactory");ce(this,"tokenProvider");ce(this,"ws",null);ce(this,"subs",new Map);ce(this,"snapshotPending",new Set);ce(this,"preSubscribeQueue",new Map);ce(this,"outbox",[]);ce(this,"reconnectScheduler");ce(this,"explicitlyClosed",!1);this.wsUrl=n.wsUrl??Nr(),this.wsFactory=n.wsFactory??hs,this.tokenProvider=n.tokenProvider??sn,this.reconnectScheduler=new cs({reconnect:()=>this.openSocket(),shouldReconnect:()=>!this.explicitlyClosed&&this.subs.size>0})}subscribe(n){const s=Sr(),r={subscriberId:s,agentId:n.agentId,mode:n.mode,onSnapshot:n.onSnapshot,onData:n.onData,onError:n.onError,onSessionGone:n.onSessionGone};return this.subs.set(s,r),this.snapshotPending.add(s),this.preSubscribeQueue.set(s,[]),this.ensureSocket(),this.wsSendOrQueue({op:"subscribe",subscriberId:s,agentId:n.agentId,mode:n.mode}),{subscriberId:s,unsubscribe:()=>this.unsubscribe(s)}}send(n,s){if(this.subs.has(n)){if(this.snapshotPending.has(n)){this.outbox.push({op:"input",subscriberId:n,data:s});return}this.wsSendOrQueue({op:"input",subscriberId:n,data:s})}}resize(n,s,r){const a=this.subs.get(n);a&&(a.lastSize={cols:s,rows:r},!this.snapshotPending.has(n)&&this.wsSendOrQueue({op:"resize",subscriberId:n,cols:s,rows:r}))}ping(){this.wsSendOrQueue({op:"ping"})}close(){if(this.explicitlyClosed=!0,this.reconnectScheduler.cancel(),this.reconnectScheduler.reset(),this.ws){try{this.ws.close()}catch{}this.ws=null}this.subs.clear(),this.snapshotPending.clear(),this.preSubscribeQueue.clear(),this.outbox=[]}unsubscribe(n){this.subs.has(n)&&(this.subs.delete(n),this.snapshotPending.delete(n),this.preSubscribeQueue.delete(n),this.wsSendOrQueue({op:"unsubscribe",subscriberId:n}),this.subs.size===0&&this.teardownSocket())}teardownSocket(){if(this.reconnectScheduler.cancel(),this.reconnectScheduler.reset(),this.outbox=[],this.ws){try{this.ws.close()}catch{}this.ws=null}}ensureSocket(){this.explicitlyClosed||this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING)||this.openSocket()}openSocket(){if(this.explicitlyClosed)return;this.reconnectScheduler.cancel();const n=this.tokenProvider(),s=n?[`baxian.token.${us(n)}`]:void 0;let r;try{r=this.wsFactory(this.wsUrl,s)}catch(a){console.warn("[pane-stream] WebSocket constructor threw:",a),this.scheduleReconnect();return}this.ws=r,r.onopen=()=>{if(r!==this.ws)return;this.reconnectScheduler.reset();for(const i of this.subs.values()){this.snapshotPending.add(i.subscriberId),this.preSubscribeQueue.set(i.subscriberId,[]),i.snapshotSeq=void 0;try{r.send(JSON.stringify({op:"subscribe",subscriberId:i.subscriberId,agentId:i.agentId,mode:i.mode}))}catch(l){console.warn("[pane-stream] resubscribe send failed:",l)}}const a=this.outbox;this.outbox=[];for(const i of a)if(i.op!=="subscribe"){if("subscriberId"in i&&i.subscriberId){if(!this.subs.has(i.subscriberId))continue;if(this.snapshotPending.has(i.subscriberId)&&i.op!=="unsubscribe"){this.outbox.push(i);continue}}try{r.send(JSON.stringify(i))}catch(l){console.warn("[pane-stream] outbox flush failed:",l)}}},r.onmessage=a=>{if(r!==this.ws)return;let i;try{const l=typeof a.data=="string"?a.data:String(a.data);i=JSON.parse(l)}catch{return}this.handleMessage(i)},r.onclose=a=>{r===this.ws&&(this.ws=null,!this.explicitlyClosed&&(ds(a,n,this.tokenProvider())||this.subs.size!==0&&this.scheduleReconnect()))},r.onerror=()=>{}}scheduleReconnect(){this.reconnectScheduler.schedule()}wsSendOrQueue(n){if(this.ws&&this.ws.readyState===WebSocket.OPEN)try{this.ws.send(JSON.stringify(n));return}catch(s){console.warn("[pane-stream] send failed, will queue:",s)}this.outbox.push(n)}handleMessage(n){var s,r;switch(n.type){case"snapshot":this.handleSnapshot(n);break;case"subscribed":this.handleSubscribed(n);break;case"data":this.dispatch(n);break;case"session_gone":for(const a of[...this.subs.values()])a.agentId===n.agentId&&((s=a.onSessionGone)==null||s.call(a));break;case"error":{if(n.subscriberId){const a=this.subs.get(n.subscriberId);(r=a==null?void 0:a.onError)==null||r.call(a,{code:n.code,message:n.message})}else console.warn("[pane-stream] connection-level error:",n.code,n.message);break}}}handleSnapshot(n){const s=this.subs.get(n.subscriberId);s&&s.onSnapshot({cols:n.cols,rows:n.rows,data:n.data})}handleSubscribed(n){const s=this.subs.get(n.subscriberId);if(!s)return;s.snapshotSeq=n.snapshotSeq,s.lastSize||(s.lastSize={cols:n.cols,rows:n.rows}),this.snapshotPending.delete(n.subscriberId);const r=this.preSubscribeQueue.get(n.subscriberId);if(this.preSubscribeQueue.delete(n.subscriberId),r)for(const a of r)a.seq>n.snapshotSeq&&s.onData(a.data);s.mode==="full"&&s.lastSize&&this.wsSendOrQueue({op:"resize",subscriberId:s.subscriberId,cols:s.lastSize.cols,rows:s.lastSize.rows}),this.flushOutboxForSub(n.subscriberId)}flushOutboxForSub(n){if(this.outbox.length===0||!this.ws||this.ws.readyState!==WebSocket.OPEN)return;const s=[];for(const r of this.outbox)if("subscriberId"in r&&r.subscriberId===n&&r.op!=="subscribe")try{this.ws.send(JSON.stringify(r))}catch(a){console.warn("[pane-stream] flushOutboxForSub send failed:",a)}else s.push(r);this.outbox=s}dispatch(n){for(const s of this.subs.values())if(s.agentId===n.agentId)if(this.snapshotPending.has(s.subscriberId)){const r=this.preSubscribeQueue.get(s.subscriberId);r&&r.push({seq:n.seq,data:n.data})}else s.onData(n.data)}}let Mt=null;function Ot(){return Mt||(Mt=new Cr),Mt}function Rr(e){const{agentId:n,mode:s}=e,r=o.useRef(null),[a,i]=o.useState(0),l=o.useRef({onSnapshot:e.onSnapshot,onData:e.onData,onError:e.onError,onSessionGone:e.onSessionGone});l.current={onSnapshot:e.onSnapshot,onData:e.onData,onError:e.onError,onSessionGone:e.onSessionGone},o.useEffect(()=>{const p=Ot().subscribe({agentId:n,mode:s,onSnapshot:u=>l.current.onSnapshot(u),onData:u=>l.current.onData(u),onError:u=>{var d,x;return(x=(d=l.current).onError)==null?void 0:x.call(d,u)},onSessionGone:()=>{var u,d;return(d=(u=l.current).onSessionGone)==null?void 0:d.call(u)}});return r.current=p.subscriberId,()=>{r.current=null,p.unsubscribe()}},[n,s,a]);const c=o.useCallback(f=>{const p=r.current;p&&Ot().send(p,f)},[]),m=o.useCallback((f,p)=>{const u=r.current;u&&Ot().resize(u,f,p)},[]),h=o.useCallback(()=>i(f=>f+1),[]);return{send:c,resize:m,reconnect:h}}const Ar=8;let gt=0,xt,jn=!0;function fs(e){var n;return Array.from(((n=e.element)==null?void 0:n.querySelectorAll("canvas"))??[])}function Tn(e){for(const n of fs(e)){const s=n.getContext("webgl2");if(s)return s}return null}function Yt(e){var n;(n=e==null?void 0:e.getExtension("WEBGL_lose_context"))==null||n.loseContext()}function Dr(){const e=document.createElement("canvas").getContext("webgl2");return e?(Yt(e),!0):!1}function Pr(e,n){let s=null,r=!1;const a=()=>{if(r||!jn)return;const h=new Vs.CanvasAddon;try{e.loadAddon(h),s={kind:"canvas",addon:h}}catch(f){jn=!1,console.warn("[terminal-renderer] canvas renderer unavailable, using dom renderer:",f),h.dispose()}},i=()=>{if(!s)return;const{kind:h,addon:f}=s;s=null;const p=h==="webgl"?Tn(e):null;f.dispose(),h==="webgl"&&(gt--,Yt(p))},l=()=>{if(xt===void 0&&(xt=Dr()),!xt||gt>=Ar)return!1;let h=null;try{return h=new Ks.WebglAddon,h.onContextLoss(()=>{i(),a()}),e.loadAddon(h),gt++,s={kind:"webgl",addon:h},!0}catch(f){xt=!1,console.warn("[terminal-renderer] webgl renderer unavailable, using canvas from now on:",f),h==null||h.dispose();for(const p of fs(e))p.remove();return!1}},c=()=>{r||s||l()||a()},m=typeof IntersectionObserver=="function"?new IntersectionObserver(h=>{if(r)return;const f=h[h.length-1];f!=null&&f.isIntersecting?c():i()}):null;return m?m.observe(n):c(),{get kind(){return(s==null?void 0:s.kind)??"dom"},dispose(){if(r)return;r=!0,m==null||m.disconnect();const h=s;s=null;const f=(h==null?void 0:h.kind)==="webgl"?Tn(e):null;try{e.dispose()}catch(p){console.warn("[terminal-renderer] dispose failed:",p)}(h==null?void 0:h.kind)==="webgl"&&(gt--,Yt(f))}}}const Lr=[{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"}],bt=Object.fromEntries(Lr.map(e=>[e.key,e]));function vt({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 Er({onKey:e,onEscape:n,className:s}){const r=H();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(vt,{arrow:bt.left,ariaLabel:r.terminal.arrowAriaLabel(r.terminal.arrowLabel.left),onPress:e}),t.jsx(vt,{arrow:bt.up,ariaLabel:r.terminal.arrowAriaLabel(r.terminal.arrowLabel.up),onPress:e}),t.jsx(vt,{arrow:bt.down,ariaLabel:r.terminal.arrowAriaLabel(r.terminal.arrowLabel.down),onPress:e}),t.jsx(vt,{arrow:bt.right,ariaLabel:r.terminal.arrowAriaLabel(r.terminal.arrowLabel.right),onPress:e})]})}const $r=Math.floor(Pt/1024/1024);function Ir({agentId:e,className:n}){const s=H(),r=o.useRef(null),[a,i]=o.useState(!1),{show:l}=je(),c=async m=>{var f;const h=(f=m.target.files)==null?void 0:f[0];if(m.target.value="",!!h){if(h.size>Pt){l({kind:"error",title:s.createTask.imageTooLargeToastTitle,body:s.imageUpload.tooLargeBody($r)});return}i(!0);try{await M.agents.uploadImage(e,h),l({kind:"success",title:s.imageUpload.insertedTitle,body:s.imageUpload.insertedBody})}catch(p){const u=p instanceof ze||p instanceof Error?p.message:String(p);l({kind:"error",title:s.imageUpload.uploadFailedTitle,body:u})}finally{i(!1)}}};return t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button","aria-label":s.imageUpload.uploadAriaLabel,disabled:a,onMouseDown:m=>m.preventDefault(),onClick:()=>{var m;return(m=r.current)==null?void 0:m.click()},className:n??"flex h-8 w-8 items-center justify-center rounded border border-hairline bg-surface text-og-700 transition-colors hover:bg-og-50 hover:text-og-1000 active:bg-og-200 disabled:cursor-not-allowed disabled:opacity-50",children:t.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[t.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),t.jsx("circle",{cx:"9",cy:"9",r:"2"}),t.jsx("path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"})]})}),t.jsx("input",{ref:r,type:"file",accept:"image/*",className:"hidden",onChange:c})]})}const Br={up:"A",down:"B",right:"C",left:"D"};function Fr(e,n){return(n?"\x1BO":"\x1B[")+Br[e]}const Sn=18,Mr=250,Or=256*1024,Nn="#fdfdfd",_r=4.5,Hr='ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',qr={background:Nn,foreground:"#474c55",cursor:"#1348dc",cursorAccent:Nn,selectionBackground:"#eaf0ff",black:"#0d0d0f",red:"#b91c1c",green:"#15803d",yellow:"#b45309",blue:"#1348dc",magenta:"#9333ea",cyan:"#0e7490",white:"#474c55",brightBlack:"#878e9b",brightRed:"#dc2626",brightGreen:"#16a34a",brightYellow:"#d97706",brightBlue:"#3080ff",brightMagenta:"#a855f7",brightCyan:"#0891b2",brightWhite:"#0d0d0f"},Ur=/\x1b\[(?:\?[\d;]*c|>[\d;]*c|\??\d+;\d+R|\d+n)/g;function Gr(e){return e.replace(Ur,"")}const Wr=1024*1024;function zr(e){const n=e.indexOf(";");if(n===-1)return null;const s=e.slice(n+1);if(s.length===0||s==="?"||s.length>Wr)return null;try{const r=atob(s),a=new Uint8Array(r.length);for(let i=0;i<r.length;i++)a[i]=r.charCodeAt(i);return new TextDecoder().decode(a)}catch{return null}}function Xe({agentId:e,mode:n,interactive:s=!1,maxLines:r,className:a,autoFocus:i=!0,deferFullUntilFocus:l=!1,arrowKeys:c=!1}){const m=H(),h=o.useRef(null),f=o.useRef(null),p=o.useRef(null),u=o.useRef(null),d=o.useRef(!1),x=o.useRef(""),b=o.useRef([]),y=o.useRef(0),T=o.useRef(null),R=o.useRef(null),A=o.useRef(null),w=o.useRef(Promise.resolve()),k=o.useRef(0),[j,v]=o.useState(null),[D,P]=o.useState(!1),I=`${e}\0${n}\0${l?"1":"0"}`,[O,J]=o.useState({key:I,active:!1}),E=O.key===I&&O.active,W=n==="full"&&l,re=W&&!E?"preview":n,te=s&&re==="full",X=(N,U)=>U.length===0?Promise.resolve():new Promise(_=>{try{N.write(U,()=>_())}catch(se){console.warn("[pane-terminal] write failed:",se),_()}}),V=re==="preview",ae=()=>{var C;if(!V)return;const N=h.current,U=f.current;if(!N||!U||N.clientHeight<=0)return;const _=((C=N.querySelector(".xterm-screen"))==null?void 0:C.getBoundingClientRect().height)??0,se=_>0&&U.rows>0?_/U.rows:Sn,B=(U.buffer.active.cursorY+1)*se;N.scrollTop=Math.max(0,B-N.clientHeight)},z=()=>{if(!V||A.current!==null)return;let N=!1;const U=requestAnimationFrame(()=>{N=!0,A.current=null,ae()});N||(A.current=U)},le=(N,U)=>{w.current=w.current.then(async()=>{const _=f.current;if(!(!_||U!==k.current))try{await N(_),te&&_.scrollToBottom(),z()}catch(se){console.warn("[pane-terminal] terminal task failed:",se)}}).catch(_=>{console.warn("[pane-terminal] write chain failed:",_)})},ne=(N,U)=>{le(_=>X(_,N),U)},ge=()=>{T.current!==null&&(cancelAnimationFrame(T.current),T.current=null),R.current!==null&&(clearTimeout(R.current),R.current=null)},q=()=>{ge(),b.current=[],y.current=0},ie=()=>{ge();const N=b.current;N.length!==0&&(b.current=[],y.current=0,ne(N.join(""),k.current))},me=N=>{if(N.length!==0){if(b.current.push(N),y.current+=N.length,y.current>=Or){ie();return}T.current===null&&(T.current=requestAnimationFrame(ie)),R.current===null&&(R.current=setTimeout(ie,Mr))}},{send:xe,resize:ye,reconnect:S}=Rr({agentId:e,mode:re,onSnapshot:({cols:N,rows:U,data:_})=>{if(v(null),P(!1),!!f.current)try{const B=k.current+1;k.current=B,q(),le(async C=>{var $;C.reset(),te?(($=u.current)==null||$.call(u),await X(C,_)):(N>0&&U>0&&C.resize(N,U),await X(C,_))},B)}catch(B){console.warn("[pane-terminal] snapshot write failed:",B)}},onData:N=>{me(N)},onError:N=>{P(N.code==="session_not_found"),v(N.code==="session_not_found"?null:`${N.code}: ${N.message}`)},onSessionGone:()=>P(!0)});o.useEffect(()=>{v(null),P(!1)},[e,re]),o.useEffect(()=>{x.current=""},[I]),o.useEffect(()=>{if(re!=="full")return;const N=x.current;N.length!==0&&(x.current="",xe(N))},[xe,re]);const we=o.useCallback(()=>{!s||!W||E||(d.current=!0,J({key:I,active:!0}))},[I,E,s,W]),pe=o.useCallback(N=>{const U=Gr(N);if(U.length!==0){if(W&&(!E||x.current.length>0)){x.current+=U,we();return}xe(U)}},[we,E,xe,W]);o.useEffect(()=>{const N=h.current;if(!N)return;let U=!1;const _=new Qs.Terminal({cursorBlink:s,disableStdin:!s,theme:qr,minimumContrastRatio:_r,fontFamily:Hr,fontSize:13,lineHeight:1.4,scrollback:re==="full"?5e3:1e3}),se=new Ys.FitAddon;_.loadAddon(se),_.open(N);const B=Pr(_,N);f.current=_,p.current=se;const C=V?_.onRender(()=>z()):null;if(s&&(i||d.current)){d.current=!1;try{_.focus()}catch{}}s&&(_.onData(pe),re==="full"&&_.parser.registerOscHandler(52,$e=>{var Te;const Re=zr($e);return Re!==null&&((Te=navigator.clipboard)==null||Te.writeText(Re).catch(()=>{})),!0}));const $=()=>N.clientWidth>0&&N.clientHeight>0,Z=($e=!1)=>{if(!$())return!1;const Re=_.cols,Te=_.rows;try{se.fit()}catch{return!1}return te&&_.scrollToBottom(),_.cols>0&&_.rows>0&&($e||_.cols!==Re||_.rows!==Te)&&ye(_.cols,_.rows),!0};u.current=te?()=>Z(!0):null;let K=null,ee=null,be=null,Ve=0;const Me=()=>{K||(K=new ResizeObserver(()=>{ee&&clearTimeout(ee),ee=setTimeout(()=>{ee=null,te?Z():V&&z()},100)}),K.observe(N))},Ee=()=>{be=requestAnimationFrame(()=>{if(be=null,!U){if(!te){V&&(Me(),z());return}if(Z(!0)){Me();return}if(Ve++<5){Ee();return}Me()}})};return Ee(),()=>{U=!0,be!==null&&cancelAnimationFrame(be),T.current!==null&&(cancelAnimationFrame(T.current),T.current=null),R.current!==null&&(clearTimeout(R.current),R.current=null),A.current!==null&&(cancelAnimationFrame(A.current),A.current=null),k.current++,b.current=[],y.current=0,w.current=Promise.resolve(),ee&&clearTimeout(ee),K==null||K.disconnect(),C==null||C.dispose(),f.current=null,p.current=null,u.current=null,B.dispose()}},[e,i,te,pe,s,re,ye]);const L=()=>{var N;if(s){we();try{(N=f.current)==null||N.focus()}catch{}}};o.useEffect(()=>{if(s)return;const N=h.current;if(!N)return;const U=_=>{_.stopPropagation()};return N.addEventListener("wheel",U,{capture:!0,passive:!0}),()=>N.removeEventListener("wheel",U,{capture:!0})},[s]);const G=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:[(j||D)&&t.jsxs("div",{role:"alert",className:"border-b border-accent/25 bg-accent-soft px-3 py-1 text-xs text-accent",children:[t.jsx("div",{children:D?m.terminal.sessionEnded:j}),D&&t.jsx("div",{children:m.terminal.sessionRecovery}),t.jsx("button",{type:"button",className:"btn-secondary mt-1",onKeyDown:N=>N.stopPropagation(),onClick:N=>{N.stopPropagation(),S()},children:m.terminal.reconnect})]}),t.jsx("div",{className:"flex flex-1 min-h-0 px-2 py-1.5",style:G,children:t.jsx("div",{ref:h,className:"flex-1 min-h-0 overflow-hidden",onMouseDown:L})}),s&&c&&t.jsxs("div",{className:"grid grid-cols-[1fr_auto_1fr] gap-2 flex-none items-center border-t border-hairline bg-page px-3 py-2",children:[t.jsx("div",{className:"flex items-center",children:t.jsx(Ir,{agentId:e})}),t.jsx(Er,{className:"flex items-center justify-center gap-1",onKey:N=>{var _,se;const U=!!((se=(_=f.current)==null?void 0:_.modes)!=null&&se.applicationCursorKeysMode);pe(Fr(N,U))},onEscape:()=>pe("\x1B")})]})]})}function ps(e,n){const s=typeof n=="string"?{status:n}:n,{status:r,phase:a}=s;if(r==="pending"&&s.preferredAgentId==="")return e.statusContext.pendingUnassigned;if(r==="in_progress"){if(a==="spec")return e.statusContext.inProgressSpec;if(a==="code")return e.statusContext.inProgressCode}if(r==="review"){if(a==="spec")return e.statusContext.reviewSpec;if(a==="code")return e.statusContext.reviewCode}if(r==="fixing"){if(a==="spec")return e.statusContext.fixingSpec;if(a==="code")return e.statusContext.fixingCode}if(r==="max_rounds"){if(a==="spec")return e.statusContext.maxRoundsSpec;if(a==="code")return e.statusContext.maxRoundsCode}return e.status[r]??r}function Kr(e){return ps(ns(),e)}function cn(e,n){return e.reason==="bootstrap-marker-clear-failed"||e.reason==="dispatch-failed:ack_unknown"&&n!=="review"?e.recommendedActions.filter(s=>s!=="advance"):e.recommendedActions}function gs(e,n,s){const{reason:r}=n,a=cn(n,s),l={"dirty-workdir":{title:e.taskDetail.attentionDirtyWorkdirTitle,guidance:e.taskDetail.attentionDirtyWorkdirGuidance},"checkout-preparation-failed":{title:e.taskDetail.attentionCheckoutTitle,guidance:e.taskDetail.attentionCheckoutGuidance},"restart-redispatch-failed":{title:e.taskDetail.attentionReplayTitle,guidance:e.taskDetail.attentionReplayGuidance},"bootstrap-marker-clear-failed":{title:e.taskDetail.attentionBootstrapDeliveredTitle,guidance:e.taskDetail.attentionBootstrapDeliveredGuidance},"dispatch-failed:ack_unknown":{title:e.taskDetail.attentionDeliveryUnknownTitle,guidance:e.taskDetail.attentionDeliveryUnknownGuidance}}[r],c=(l==null?void 0:l.title)??(/confirm-merge|post-approve|merge/.test(r)?e.taskDetail.attentionMergeTitle:/review|verdict/.test(r)?e.taskDetail.attentionReviewTitle:/runtime|session|recovery|tmux|repl/.test(r)?e.taskDetail.attentionAgentTitle:/dispatch|delivery|pr-created/.test(r)?e.taskDetail.attentionHandoffTitle:e.taskDetail.attentionDefaultTitle),m=a.includes("verdict")?e.taskDetail.attentionVerdictGuidance:a.includes("advance")?e.taskDetail.attentionAdvanceGuidance:a.includes("retry")?e.taskDetail.attentionRetryGuidance:e.taskDetail.attentionCancelGuidance;return{title:c,guidance:l?`${l.guidance} ${m}`:m,...l?{expandDetails:!0}:{}}}const Vr={pending:"pill",in_progress:"pill pill-live",review:"pill pill-review",fixing:"pill pill-warn","spec-ready":"pill pill-warn",approved:"pill pill-live","merge-ready":"pill pill-warn",merged:"pill pill-live",done:"pill pill-live",failed:"pill pill-danger",max_rounds:"pill pill-warn",cancelled:"pill"};function dn({task:e,className:n=""}){const s=H(),r=ps(s,e);return t.jsx("span",{className:`${Vr[e.status]??"pill"} ${n}`,title:r,"data-status":e.status,children:r})}function un(e){if(!e)return"";const n=e.match(/^task-(\d+)$/);return n?n[1]:e}function _t(e,n=!0){if(e==null)return"";const s=String(e).trim();if(!s)return"";const r=new Date(s.replace(/^(\d{4}-\d{2}-\d{2}) /,"$1T"));if(Number.isNaN(r.getTime()))return s;const a=c=>String(c).padStart(2,"0"),i=`${r.getFullYear()}-${a(r.getMonth()+1)}-${a(r.getDate())}`,l=`${a(r.getHours())}:${a(r.getMinutes())}`;return n?`${i} ${l}:${a(r.getSeconds())}`:`${i} ${l}`}function Pe(e,n){return`/project/${encodeURIComponent(e)}/task/${encodeURIComponent(n)}`}function Qr(e){return e>=1048576?`${(e/1048576).toFixed(1)} MiB`:e>=1024?`${(e/1024).toFixed(1)} KiB`:`${e} B`}function Yr({taskId:e,agentId:n,onPendingChange:s}){var v;const r=H(),[a,i]=o.useState(null),[l,c]=o.useState(null),[m,h]=o.useState(!0),[f,p]=o.useState(!1),[u,d]=o.useState(""),[x,b]=o.useState(""),y=o.useRef(!1),T=o.useRef(0);o.useEffect(()=>(s==null||s(!!a),()=>s==null?void 0:s(!1)),[a,s]);const R=o.useCallback(async()=>{const D=++T.current;h(!0),b("");try{const P=await M.tasks.untrackedFiles(e,n);D===T.current&&i(P)}catch(P){D===T.current&&(i(null),P instanceof ze&&P.status===409?b(P.message):d(P instanceof Error?P.message:String(P)))}finally{D===T.current&&h(!1)}},[e,n]);o.useEffect(()=>(i(null),c(null),d(""),R(),()=>{T.current+=1}),[R]);const A=async(D,P)=>{if(!y.current){y.current=!0,p(!0),d(""),c(null);try{await M.tasks.resolveUntrackedFiles(e,n,{action:D,token:P.token}),T.current+=1,i(null)}catch(I){d(I instanceof Error?I.message:String(I)),await R()}finally{y.current=!1,p(!1)}}},w=D=>t.jsx("ul",{className:"my-2 max-h-48 overflow-auto rounded bg-og-25 p-2 font-mono text-xs",children:D.map(P=>t.jsxs("li",{className:"flex justify-between gap-3",children:[t.jsx("span",{className:"whitespace-pre-wrap break-all",children:P.path}),t.jsx("span",{className:"shrink-0 text-og-500",children:Qr(P.size)})]},P.pathBase64??P.path))}),k=!!(a!=null&&a.files.length),j=!!((v=a==null?void 0:a.conflicts)!=null&&v.length);return!m&&!f&&!u&&!x&&!a?null:t.jsxs("section",{className:"mb-2 rounded-md border border-accent/25 bg-accent-soft/60 p-3 text-sm","aria-label":r.untrackedFiles.heading,children:[(m||f)&&t.jsx("p",{role:"status",children:f?r.untrackedFiles.working:r.untrackedFiles.loading}),x&&t.jsxs("p",{role:"status",children:[r.untrackedFiles.unavailable," ",x]}),u&&t.jsx("p",{role:"alert",className:"whitespace-pre-wrap break-words text-red-600",children:u}),a&&t.jsxs(t.Fragment,{children:[k&&t.jsxs(t.Fragment,{children:[t.jsx("h3",{className:"font-semibold",children:r.untrackedFiles.title(a.files.length)}),t.jsx("p",{children:r.untrackedFiles.guidance})]}),!k&&!j&&t.jsx("p",{children:r.untrackedFiles.readyToContinue}),t.jsxs("dl",{className:"mt-2 grid grid-cols-[auto_1fr] gap-x-2 text-xs",children:[t.jsx("dt",{children:r.untrackedFiles.agent}),t.jsx("dd",{children:a.agentId}),t.jsx("dt",{children:r.untrackedFiles.host}),t.jsx("dd",{children:a.host}),t.jsx("dt",{children:r.untrackedFiles.workdir}),t.jsx("dd",{className:"break-all",children:a.workdir})]}),k&&w(a.files),j&&t.jsxs(t.Fragment,{children:[t.jsx("p",{children:r.untrackedFiles.conflicts}),w(a.conflicts)]}),a.manualCleanupRequired&&t.jsx("p",{children:r.untrackedFiles.manualCleanup}),a.keepLimitExceeded&&t.jsx("p",{children:r.untrackedFiles.keepLimit}),a.trackedChanges&&t.jsx("p",{children:r.untrackedFiles.trackedChanges}),a.files.some(D=>D.kind==="directory")&&t.jsx("p",{children:r.untrackedFiles.directory}),k&&t.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"btn-primary",disabled:f||m||a.trackedChanges||a.keepLimitExceeded||j,onClick:()=>void A("keep",a),children:r.untrackedFiles.keep}),t.jsx("button",{type:"button",className:"btn-secondary",disabled:f||m||a.trackedChanges||a.manualCleanupRequired||a.files.some(D=>D.kind==="directory"),onClick:()=>c(a),children:r.untrackedFiles.discard})]}),!k&&!j&&t.jsx("button",{type:"button",className:"btn-primary mt-2",disabled:f||m||a.trackedChanges,onClick:()=>void A("continue",a),children:r.untrackedFiles.continue})]}),t.jsx("button",{type:"button",className:"btn-secondary mt-2",disabled:f||m,onClick:()=>{d(""),R()},children:r.untrackedFiles.refresh}),t.jsxs(Ce,{open:l!==null,title:r.untrackedFiles.confirmTitle,onClose:()=>c(null),size:"sm",footer:t.jsxs("div",{className:"flex justify-end gap-2",children:[t.jsx("button",{type:"button",className:"btn-secondary",onClick:()=>c(null),children:r.common.cancel}),t.jsx("button",{type:"button",className:"btn-danger",disabled:f,onClick:()=>{l&&A("discard",l)},children:r.untrackedFiles.discard})]}),children:[t.jsx("p",{children:r.untrackedFiles.confirmBody}),l&&w(l.files)]})]})}const Ht={unknown:"pill pill-idle",idle:"pill pill-idle",pending:"pill pill-warn",working:"pill pill-live",waiting:"pill pill-review",error:"pill pill-warn"};function Jr(e,n,s,r=s!==void 0){const a=s!==void 0?tn.has(s.status):r;return e==="greeting_failed"?"restart-runtime":e==="agent_dialog_pending"?"terminal":e==="bootstrap-marker-clear-failed"?(s==null?void 0:s.status)==="in_progress"||!s&&r?"task":"resume":e==="restart-redispatch-failed"?(s?["in_progress","fixing","approved"].includes(s.status):r)?"task":"resume":a&&(e==="agent_dialog_resolved_runtime"||e!=null&&e.startsWith("signal-arm-failed"))?"task":e==="dispatch-failed:ack_unknown"&&n==="dev"&&s&&["spec-ready","review","merge-ready","max_rounds"].includes(s.status)?"resume":a&&(e==="dispatch-failed:ack_unknown"||e==="dev-wait-gate-failed-after-qa-started")||a&&(s==null?void 0:s.status)!=="spec-ready"&&(s==null?void 0:s.status)!=="max_rounds"&&(e==="dirty-workdir"||e==="checkout-preparation-failed")&&n==="dev"?"task":"resume"}function xs(e){var n;return!!((n=e.binding)!=null&&n.creationToken)&&!e.binding.paneId&&e.binding.status!=="awaiting_human"&&e.reason!=="PENDING_HUMAN"}function Xr(e,n){var s,r,a;return e.tmuxSessionStatus==="unreachable"?{kind:"alert",label:n.sessionStatus.unreachable,cls:"pill pill-danger"}:xs(e)?{kind:"runtime",label:n.bootstrappingBadge,cls:"pill pill-review"}:Gn(e)?{kind:"runtime",label:n.dispatchingBadge,cls:"pill pill-review",title:n.dispatchingTitle}:e.tmuxSessionStatus==="absent"?{kind:"alert",label:n.sessionStatus.absent,cls:"pill pill-warn"}:e.runtimeStatus==="error"?{kind:"alert",label:n.runtimeStatus.error,cls:Ht.error}:((s=e.binding)==null?void 0:s.status)==="awaiting_human"?{kind:"alert",label:n.heldBadge,cls:"pill pill-warn",title:e.binding.awaitingReason??n.heldDefaultReason}:(a=(r=e.binding)==null?void 0:r.needInput)!=null&&a.at?{kind:"alert",label:n.needInputBadge,cls:"pill pill-warn",title:n.needInputTitle(new Date(e.binding.needInput.at).toLocaleString())}:e.runtimeStatus==="pending"?{kind:"alert",label:n.runtimeStatus.pending,cls:Ht.pending}:{kind:"runtime",label:n.runtimeStatus[e.runtimeStatus],cls:Ht[e.runtimeStatus]}}function Zr(e,n){const s=Xr(e,n);if(!e.stale)return{...s,stale:!1};const r=n.staleTitle(e.observedAt?new Date(e.observedAt).toLocaleString():void 0);return{...s,stale:!0,title:s.title?`${s.title} · ${r}`:r}}function bs({agent:e,projectId:n,role:s,runtime:r,model:a,onDeleted:i,pendingRestart:l=!1,terminalLoading:c=!1,showTaskBinding:m=!0,terminalMode:h="activity-preview",active:f,onActivate:p,task:u}){var Ee,$e,Re,Te,it,ot,lt,Qe,ct;const d=H(),[x,b]=o.useState(!1),[y,T]=o.useState(null),{show:R}=je(),A=ln(),{compact:w,clear:k,remove:j,compacting:v,clearing:D,deleting:P,deleteError:I,busy:O}=ls(n,[e.id],i),[J,E]=o.useState(!1),[W,re]=o.useState(!1),[te,X]=o.useState(!1),[V,ae]=o.useState(!1),z=(Ee=e.binding)==null?void 0:Ee.taskId,le=(u==null?void 0:u.id)===z?u:void 0,ne=(($e=e.binding)==null?void 0:$e.status)==="awaiting_human",ge=(Te=(Re=e.binding)==null?void 0:Re.needInput)==null?void 0:Te.at,q=ne&&((it=e.binding)==null?void 0:it.awaitingPhase)==="greeting_failed",ie=Jr((ot=e.binding)==null?void 0:ot.awaitingPhase,s,le,!!z),me=xs(e),xe=!l&&!c&&!e.stale&&!ne&&e.tmuxSessionStatus==="absent"&&!((lt=e.binding)!=null&&lt.creationToken)&&!z,ye=me&&e.tmuxSessionStatus!=="present",S=Zr(e,d.agents),we=h==="activity-preview"&&!ye&&(e.runtimeStatus==="working"||e.runtimeStatus==="pending"),pe=h==="embedded-full",L=pe&&typeof p=="function",G=L&&f===!0,N=c||l||ye,U=c?d.agents.agentStatusLoading:l?d.agents.terminalNeedsRestart:d.agents.bootstrappingTerminalDisabled,_=zn(r,a),se=async()=>{b(!0),T(null);try{await M.agents.stop(e.id)}catch(oe){T(oe instanceof Error?oe.message:String(oe))}finally{b(!1)}},B=async()=>{X(!0);try{(await M.projects.bootstrap(n)).ok?R({kind:"success",title:d.agents.retryBootstrapSucceededTitle,body:d.agents.retryBootstrapSucceededBody}):R({kind:"warn",title:d.agents.retryBootstrapStillFailingTitle,body:d.agents.retryBootstrapStillFailingBody})}catch(oe){R({kind:"error",title:d.agents.retryBootstrapFailedTitle,body:oe instanceof Error?oe.message:String(oe)})}finally{X(!1)}},C=async()=>{ae(!0);try{const oe=await M.projects.retryAgent(n,e.id);R({kind:oe.runtimeStatus==="pending"?"warn":"success",title:oe.runtimeStatus==="pending"?d.agents.retrySessionPending:d.agents.retrySessionReady})}catch(oe){R({kind:"error",title:d.agents.retrySessionFailed,body:oe instanceof Error?oe.message:String(oe)})}finally{ae(!1)}},$=async()=>{if(await A({title:d.agents.resumeConfirmTitle(e.id),body:q?d.agents.resumeGreetingBody:d.agents.resumeDefaultBody,confirmLabel:d.agents.resume})){E(!0);try{if(q){e.tmuxSessionStatus==="present"?await M.projects.restartRepl(n,e.id):await M.projects.retryAgent(n,e.id),R({kind:"success",title:d.agents.regreetingStartedTitle(e.id),body:d.agents.regreetingStartedBody});return}const Oe=await M.projects.resumeAgent(n,e.id);R({kind:"success",title:d.agents.resumedTitle(e.id),body:Oe.releasedBinding?d.agents.resumedReleasedBody:d.agents.resumedKeptBody})}catch(Oe){R({kind:"error",title:d.agents.resumeFailedTitle,body:Oe instanceof Error?Oe.message:String(Oe)})}finally{E(!1)}}},Z=L&&!N&&!G,K=["card relative flex h-full min-w-0 flex-col overflow-visible p-4",G?"ring-2 ring-accent":""].filter(Boolean).join(" "),ee="mb-3 flex items-start justify-between gap-2",be=["mb-2 mt-3 h-80 min-h-0 overflow-hidden border border-hairline bg-surface",Z?"cursor-pointer":""].filter(Boolean).join(" "),Ve=Z?()=>p==null?void 0:p():void 0,Me=Z?oe=>{(oe.key==="Enter"||oe.key===" ")&&(oe.preventDefault(),p==null||p())}:void 0;return t.jsxs("div",{className:K,"data-agent-card":L?e.id:void 0,children:[t.jsxs("div",{className:ee,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"?d.agents.qaRole:d.agents.devRole}),t.jsx("span",{className:"min-w-0 truncate whitespace-nowrap font-display text-xs text-og-1000",title:Kn(e.id,r,a),children:e.id}),_&&t.jsxs("span",{className:"hidden shrink-0 whitespace-nowrap text-xs text-og-400 sm:inline",title:_,children:["(",_,")"]})]}),t.jsx("span",{className:S.stale?`${S.cls} pill--stale shrink-0`:`${S.cls} shrink-0`,title:S.title,children:S.label}),S.stale&&t.jsx("span",{className:"sr-only",children:S.title})]}),ye&&t.jsx("div",{className:"mb-2 rounded-md border border-accent-soft bg-accent-soft/40 px-2.5 py-2 text-xs text-accent",children:d.agents.bootstrappingNotice}),ne&&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:[!W&&t.jsx("div",{className:"text-og-700",children:d.agents.holdRecovery[ie]}),t.jsxs("details",{children:[t.jsx("summary",{className:"cursor-pointer",children:d.common.technicalDetails}),t.jsxs("div",{className:"break-words",children:[t.jsx("span",{className:"font-mono",children:(Qe=e.binding)==null?void 0:Qe.awaitingPhase}),((ct=e.binding)==null?void 0:ct.awaitingReason)&&t.jsxs("span",{children:[" · ",e.binding.awaitingReason]})]})]})]}),ne&&z&&t.jsx(Yr,{taskId:z,agentId:e.id,onPendingChange:re},`${z}:${e.id}`),!me&&e.runtimeStatus==="pending"&&t.jsxs("div",{className:"mb-2 space-y-1 rounded-md border border-accent/25 bg-accent-soft/60 px-2.5 py-2 text-xs text-accent",children:[t.jsx("div",{className:"font-medium",children:d.agents.awaitingHumanIntervention}),t.jsxs("div",{children:[d.agents.openTerminalPrefix,t.jsx(Ne,{to:`/terminal/${e.id}`,className:"text-accent hover:text-accent-hover underline",children:d.agents.terminal}),d.agents.openTerminalSuffix]})]}),ge&&t.jsxs("div",{className:"mb-2 space-y-1 rounded-md border border-accent/25 bg-accent-soft/60 px-2.5 py-2 text-xs text-accent",children:[t.jsx("div",{className:"font-medium",children:d.agents.needInputNoticeTitle}),t.jsxs("div",{children:[d.agents.needInputPrefix,t.jsx(Ne,{to:`/terminal/${e.id}`,className:"text-accent hover:text-accent-hover underline",children:d.agents.terminal}),d.agents.needInputSuffix]})]}),e.latestError&&t.jsxs("div",{className:"mb-2 space-y-1 rounded-md border border-accent/25 bg-accent-soft px-2.5 py-2 text-xs text-accent",children:[t.jsx("div",{className:"break-words font-medium",children:e.latestError.message}),t.jsxs("div",{className:"font-mono text-xs opacity-80",children:[e.latestError.reason," · ",e.latestError.occurredAt]})]}),e.latestBootstrapError&&t.jsxs("div",{className:"mb-2 space-y-1 rounded-md border border-accent/25 bg-accent-soft px-2.5 py-2 text-xs text-accent",children:[t.jsx("div",{className:"break-words font-medium",children:e.latestBootstrapError.message}),e.latestBootstrapError.recommendation&&t.jsx("div",{className:"break-words",children:e.latestBootstrapError.recommendation}),t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsxs("div",{className:"truncate font-mono text-xs opacity-80",children:[e.latestBootstrapError.reason," · ",e.latestBootstrapError.occurredAt]}),t.jsx("button",{type:"button",onClick:B,disabled:te,className:"btn-primary shrink-0",children:te?d.common.retrying:d.agents.retryBootstrap})]})]}),m&&z&&t.jsxs("div",{className:"mb-2 text-xs text-og-500",children:[d.agents.taskLabel,t.jsx("span",{className:"font-mono text-og-700",children:z})]}),we&&t.jsx("div",{className:"mb-2 overflow-hidden border border-hairline bg-surface",children:t.jsx(Xe,{agentId:e.id,mode:"preview",maxLines:6,interactive:!1})}),pe&&t.jsx("div",{className:be,role:Z?"button":void 0,tabIndex:Z?0:void 0,"aria-label":Z?d.agents.activateTerminal(e.id):void 0,onClick:Ve,onKeyDown:Me,children:N?t.jsx("div",{className:"flex h-full items-center justify-center px-3 text-sm text-og-500",children:U}):L?G?t.jsx(Xe,{agentId:e.id,mode:"full",interactive:!0,autoFocus:!0}):t.jsx(Xe,{agentId:e.id,mode:"preview",interactive:!1}):t.jsx(Xe,{agentId:e.id,mode:"full",interactive:!0,autoFocus:!1,deferFullUntilFocus:!0})}),l&&t.jsx("div",{className:"mb-2 rounded-md border border-accent/25 bg-accent-soft/60 px-2.5 py-1.5 text-xs text-accent",children:d.agents.pendingRestartNotice}),t.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[t.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2 overflow-x-auto scrollbar-none",children:[xe&&t.jsx("button",{type:"button",className:"btn-primary shrink-0",disabled:V,onClick:C,children:V?d.common.retrying:d.agents.retrySession}),N?t.jsx("span",{className:"shrink-0 cursor-not-allowed text-sm text-og-400",title:U,children:d.agents.terminal}):t.jsx(Ne,{to:`/terminal/${e.id}`,className:"btn-secondary shrink-0",children:d.agents.terminal}),!l&&e.runtimeStatus==="working"&&t.jsx("button",{onClick:se,disabled:x,className:"btn-ghost shrink-0",children:x?d.agents.stopping:d.agents.stop}),ne&&!W&&(ie==="resume"||ie==="restart-runtime")&&t.jsx("button",{type:"button",onClick:$,disabled:J,title:q?d.agents.resumeGreetingButtonTitle:d.agents.resumeDefaultButtonTitle,className:"btn-primary shrink-0",children:J?d.agents.resuming:ie==="restart-runtime"?d.agents.restartRuntime:d.agents.resume}),ne&&ie==="terminal"&&t.jsx(Ne,{to:`/terminal/${e.id}`,className:"btn-primary shrink-0",children:d.agents.openTerminalAction}),ne&&ie==="task"&&z&&t.jsx(Ne,{to:Pe(n,z),className:"btn-primary shrink-0",children:d.agents.openTaskActions}),ne&&ie==="delete-agent"&&t.jsx("button",{type:"button",onClick:()=>void j(),disabled:P,className:"btn-primary shrink-0",children:P?d.common.deleting:d.agents.deleteToRecover})]}),t.jsx(Dt,{ariaLabel:d.agents.actionsMenu(e.id),className:"shrink-0",placement:"up",autoFocusFirstItem:!0,disabled:P,children:oe=>t.jsxs(t.Fragment,{children:[t.jsx(ke,{onClick:()=>{oe(),w()},disabled:O,title:d.agents.compactMenuItemTitle,children:v?d.agents.compacting:d.agents.compact}),t.jsx(ke,{onClick:()=>{oe(),k()},disabled:O,title:d.agents.clearMenuItemTitle,children:D?d.agents.clearing:d.agents.clear}),t.jsx(ke,{onClick:()=>{oe(),j()},disabled:O,children:P?d.common.deleting:d.common.delete})]})})]}),y&&t.jsx("div",{className:"mt-1.5 break-words text-xs text-accent",children:y}),I&&t.jsx("div",{className:"mt-1.5 break-words text-xs text-accent",children:I})]})}const qt="baxian:terminal-activated";function vs({coordinateAcrossInstances:e=!0}={}){const n=o.useId(),[s,r]=o.useState(null);o.useEffect(()=>{if(s===null)return;const i=m=>{m.composedPath().some(p=>p instanceof Element&&p.hasAttribute("data-agent-card"))||r(null)},l=m=>{if(m.key!=="Escape")return;const h=document.activeElement;h instanceof Element&&h.closest("[data-agent-card]")||r(null)},c=m=>{const h=m.detail;(h==null?void 0:h.ownerId)!==n&&r(null)};return document.addEventListener("click",i),document.addEventListener("keydown",l),e&&document.addEventListener(qt,c),()=>{document.removeEventListener("click",i),document.removeEventListener("keydown",l),e&&document.removeEventListener(qt,c)}},[s,e,n]);const a=o.useCallback(i=>{r(i),e&&document.dispatchEvent(new CustomEvent(qt,{detail:{ownerId:n}}))},[e,n]);return{activeAgentId:s,activateAgentCard:a}}function ys({team:e,projectId:n,agentsById:s,agentsLoaded:r,agentsError:a=!1,tasks:i,onDeleted:l,terminalMode:c="activity-preview"}){const m=H(),h=e.find(E=>E.role==="dev")??e[0],f=i.filter(E=>na(E,h==null?void 0:h.id)),p=h?i.filter(E=>sa(E,n,h.id)).sort((E,W)=>E.createdAt.localeCompare(W.createdAt)):[],u=e.map(E=>E.id).join(" / "),d=m.agents.teamLabel(u),x=Le(),{compact:b,clear:y,remove:T,compacting:R,clearing:A,deleting:w,deleteError:k,busy:j}=ls(n,e.map(E=>E.id),l),v=c==="embedded-full",{activeAgentId:D,activateAgentCard:P}=vs({coordinateAcrossInstances:v}),I=c==="embedded-full"?e.length<=1?"lg:grid-cols-1":e.length===2?"lg:grid-cols-2":e.length===3?"lg:grid-cols-3":"lg:grid-cols-4":"sm:grid-cols-2",O=!!h&&p.length>0,J=f.length===0&&!O;return t.jsxs("div",{role:"group","aria-label":d,className:"min-w-0 rounded-lg border border-og-100 bg-og-25/60 p-3",children:[t.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[t.jsx("span",{className:"shrink-0 font-display text-xs font-semibold uppercase tracking-[0.06em] text-og-500",children:m.agents.teamHeading}),t.jsx("span",{className:"min-w-0 truncate font-mono text-xs text-og-700",title:u,children:u}),t.jsx(Dt,{ariaLabel:m.agents.teamActionsMenu(u),className:"ml-auto shrink-0",autoFocusFirstItem:!0,disabled:w,children:E=>t.jsxs(t.Fragment,{children:[t.jsx(ke,{onClick:()=>{E(),b()},disabled:j,title:m.agents.teamCompactMenuItemTitle,children:R?m.agents.compacting:m.agents.compact}),t.jsx(ke,{onClick:()=>{E(),y()},disabled:j,title:m.agents.teamClearMenuItemTitle,children:A?m.agents.clearing:m.agents.clear}),t.jsx(ke,{onClick:()=>{E(),T()},disabled:j,children:w?m.common.deleting:m.common.delete})]})})]}),k&&t.jsx("div",{className:"mb-2 break-words text-xs text-accent",children:k}),O&&h&&t.jsx(ta,{tasks:p,devId:h.id,agentsById:s,label:d}),f.length>0&&t.jsx("div",{className:"card mb-2 max-h-28 overflow-y-auto divide-y divide-hairline",children:f.map(E=>{const W=Fe(E.phase)?E.specReviewRound??0:E.reviewRound;return t.jsxs("button",{type:"button",onClick:()=>x(Pe(E.projectId,E.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:E.id,children:un(E.id)}),t.jsx("span",{className:"truncate text-og-1000",children:E.title})]}),t.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[W>0&&t.jsx("span",{className:"shrink-0 text-xs text-og-500",children:m.agents.round(W)}),t.jsx(dn,{task:E,className:"shrink-0"})]})]},E.id)})}),J&&t.jsx("div",{className:"mb-2 rounded-lg border border-hairline bg-surface px-3 py-2 text-sm text-og-400","aria-label":m.agents.noActiveTaskAriaLabel(d),children:m.agents.noActiveTask}),t.jsx("div",{className:`grid grid-cols-1 ${I} gap-4`,children:e.map(E=>{var X;const W=s.get(E.id),re=W??{id:E.id,projectId:n,runtimeStatus:"unknown",tmuxSessionStatus:"unknown",stale:!0},te=((X=re.binding)==null?void 0:X.taskId)===void 0?void 0:i.find(V=>{var ae;return V.id===((ae=re.binding)==null?void 0:ae.taskId)});return t.jsx(bs,{agent:re,projectId:n,role:E.role,runtime:E.runtime,model:E.model,pendingRestart:r&&!W,terminalLoading:!r&&!W&&!a,onDeleted:l,showTaskBinding:!1,terminalMode:c,task:te,...v?{active:D===E.id,onActivate:()=>P(E.id)}:{}},E.id)})})]})}function ea(e){var n,s,r;return!!e&&e.runtimeStatus==="idle"&&((n=e.binding)==null?void 0:n.status)!=="awaiting_human"&&!((s=e.binding)!=null&&s.creationToken)&&!((r=e.binding)!=null&&r.taskId)}function ta({tasks:e,devId:n,agentsById:s,label:r}){const a=H(),{show:i}=je(),l=Le(),[c,m]=o.useState(null),h=async(f,p)=>{m(f);try{await M.tasks.advance(f,{executor:"dev",agentId:p}),i({kind:"success",title:a.agents.taskHandedTo(f,p)})}catch(u){i({kind:"error",title:a.agents.startFailed,body:u instanceof Error?u.message:String(u)})}finally{m(null)}};return t.jsx("div",{role:"group",className:"card mb-2 max-h-28 overflow-y-auto divide-y divide-hairline","aria-label":a.agents.claimableTasksLabel(r,n),children:e.map(f=>{const p=f.preferredAgentId||n,u=ea(s.get(p)),d=f.preferredAgentId==="",x=c!==null;return t.jsxs("div",{className:"flex items-center gap-3 px-3 py-2 text-sm",children:[t.jsxs("button",{type:"button",onClick:()=>l(Pe(f.projectId,f.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:f.id,children:un(f.id)}),t.jsx("span",{className:"truncate text-og-1000",title:f.title,children:f.title}),d&&t.jsx("span",{className:"pill shrink-0",children:a.agents.unassigned})]}),t.jsx("button",{type:"button",onClick:()=>void h(f.id,p),disabled:!u||x,title:u?a.agents.handToAndStart(p):a.agents.agentUnavailable(p),className:"shrink-0 text-sm font-medium text-accent transition-colors hover:text-accent-hover disabled:opacity-50 disabled:cursor-not-allowed",children:c===f.id?a.agents.starting:a.agents.start})]},f.id)})})}function na(e,n){return!n||!tn.has(e.status)?!1:e.devAgentId===n}function sa(e,n,s){return e.projectId!==n||e.status!=="pending"?!1:e.preferredAgentId===s||e.preferredAgentId===""}const he="w-full rounded-md border border-og-100 bg-surface px-2.5 py-1.5 text-sm text-og-800 placeholder:text-og-400 focus:border-accent focus:outline-none focus:ring-[3px] focus:ring-accent-soft disabled:cursor-not-allowed disabled:opacity-50",ue="mb-1.5 block text-xs font-medium text-og-700",St="mt-1 text-xs text-accent",qe="mt-1 text-xs text-og-500",Ie="h-3.5 w-3.5 accent-accent",ra=/^[a-z][a-z0-9-]{1,31}$/;function aa({open:e,onClose:n,onCreated:s}){const r=H(),[a,i]=o.useState(""),[l,c]=o.useState(""),[m,h]=o.useState(null),[f,p]=o.useState("human"),[u,d]=o.useState(!1),[x,b]=o.useState(null),[y,T]=o.useState({}),[R,A]=o.useState(new Set),w=o.useRef(0),{show:k}=je(),{flagDirty:j}=Lt();o.useEffect(()=>{if(!e)return;w.current+=1;const I=w.current;i(""),c(""),h(null),p("human"),b(null),T({}),A(new Set),M.config.get().then(O=>{I===w.current&&A(new Set(O.project.map(J=>J.id)))}).catch(O=>{I===w.current&&b(r.common.loadFailed(O instanceof Error?O.message:String(O)))})},[e]);const v=()=>{u||n()},D=()=>{const I={};return a?ra.test(a)?R.has(a)&&(I.id=r.createProject.idTakenError):I.id=r.common.idFormatError:I.id=r.createProject.required,l.trim()||(I.repo=r.createProject.required),T(I),Object.keys(I).length===0},P=async I=>{if(I.preventDefault(),!!D()){d(!0),b(null);try{const O=await M.projects.create({id:a,repo:l.trim(),merge:m,...f?{specApproval:f}:{}});O.restartRequired&&j(),k({kind:"success",title:r.createProject.createdToastTitle(O.project.id)}),s(O.project.id)}catch(O){b(O instanceof Error?O.message:String(O))}finally{d(!1)}}};return t.jsx(Ce,{open:e,onClose:v,title:r.createProject.title,size:"md",footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:v,disabled:u,className:"btn-secondary",children:r.common.cancel}),t.jsx("button",{type:"submit",form:"create-project-form",disabled:u,className:"btn-primary",children:u?r.common.creating:r.common.create})]}),children:t.jsxs("form",{id:"create-project-form",onSubmit:P,className:"space-y-3",children:[x&&t.jsx("div",{className:"whitespace-pre-line rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-sm text-accent",children:x}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"proj-id",children:r.createProject.idLabel}),t.jsx("input",{id:"proj-id",type:"text",value:a,onChange:I=>i(I.target.value),className:he,placeholder:"baxian",disabled:u}),y.id&&t.jsx("div",{className:St,children:y.id})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"proj-repo",children:r.createProject.repoLabel}),t.jsx("input",{id:"proj-repo",type:"text",value:l,onChange:I=>c(I.target.value),className:he,placeholder:"https://github.com/baxian-ai/baxian.git",disabled:u}),y.repo&&t.jsx("div",{className:St,children:y.repo})]}),t.jsxs("div",{children:[t.jsx("span",{className:ue,children:r.createProject.mergeStrategyLabel}),t.jsxs("label",{className:"mb-1 flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"merge",checked:m===null,onChange:()=>h(null),disabled:u,className:"h-3.5 w-3.5 accent-accent"}),t.jsx("span",{className:"text-sm text-og-800",children:r.createProject.mergeHumanLabel})]}),t.jsxs("label",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"merge",checked:m==="auto",onChange:()=>h("auto"),disabled:u,className:"h-3.5 w-3.5 accent-accent"}),t.jsx("span",{className:"text-sm text-og-800",children:r.createProject.mergeAutoLabel})]})]}),t.jsxs("div",{children:[t.jsx("span",{className:ue,children:r.createProject.specApprovalLabel}),t.jsxs("label",{className:"mb-1 flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"spec-approval",checked:f==="human",onChange:()=>p("human"),disabled:u,className:"h-3.5 w-3.5 accent-accent"}),t.jsx("span",{className:"text-sm text-og-800",children:r.createProject.specApprovalHumanLabel})]}),t.jsxs("label",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"spec-approval",checked:f===null,onChange:()=>p(null),disabled:u,className:"h-3.5 w-3.5 accent-accent"}),t.jsx("span",{className:"text-sm text-og-800",children:r.createProject.specApprovalAutoLabel})]})]})]})})}const Cn=/^[a-z][a-z0-9-]{1,31}$/,ia=500,Ut={id:"",mode:"local",host:"",runtime:"",workdir:"",yolo:!0,model:"",addDirs:""};function oa(e){return e.alias?e.alias:`${e.user?`${e.user}@`:""}${e.hostname}${e.port!=null?`:${e.port}`:""}`}function ws({open:e,onClose:n,projectId:s,onCreated:r}){var L,G,N,U,_,se;const a=H(),[i,l]=o.useState(Ut),[c,m]=o.useState(null),[h,f]=o.useState([]),[p,u]=o.useState(new Set),[d,x]=o.useState(null),[b,y]=o.useState(!1),[T,R]=o.useState(!1),[A,w]=o.useState(null),[k,j]=o.useState(!1),[v,D]=o.useState(null),[P,I]=o.useState(!1),O=o.useRef(null),J=o.useRef(null),E=o.useRef(0),W=o.useRef(0),{show:re}=je(),{flagDirty:te}=Lt();o.useEffect(()=>{if(!e)return;W.current+=1;const B=W.current;l(Ut),m(null),f([]),u(new Set),x(null),y(!1),R(!1),w(null),E.current+=1,D(null),I(!1),M.config.get().then(C=>{if(B!==W.current)return;f(C.host??[]);const $=new Set;C.project.forEach(Z=>Z.agent.forEach(K=>K.forEach(ee=>$.add(ee.id)))),u($)}).catch(()=>{})},[e,s]);const X=()=>{k||n()},V=o.useCallback(()=>{O.current&&O.current.abort();const B=new AbortController;O.current=B,y(!0),D(null);const C=i.mode==="remote"?{hostId:i.host}:{};M.agents.probe(i.mode,C,{signal:B.signal}).then($=>{B.signal.aborted||(x($),D(null))}).catch($=>{B.signal.aborted||(x(null),D($ instanceof Error?$.message:String($)))}).finally(()=>{O.current===B&&y(!1)})},[i.mode,i.host]);o.useEffect(()=>{if(e&&(x(null),w(null),R(!1),E.current+=1,O.current&&O.current.abort(),!(i.mode==="remote"&&!i.host)))return J.current&&clearTimeout(J.current),J.current=setTimeout(V,ia),()=>{J.current&&clearTimeout(J.current)}},[e,i.mode,i.host,c,V]),o.useEffect(()=>{e||O.current&&O.current.abort()},[e]),o.useEffect(()=>()=>{O.current&&O.current.abort(),J.current&&clearTimeout(J.current)},[]);const ae=()=>{if(T)return;const B=E.current;R(!0),w(null);const C=i.mode==="remote"?{hostId:i.host}:{};M.agents.installTmux(i.mode,C).then($=>{E.current===B&&(w({ok:$.ok,message:$.message}),R(!1),$.ok&&V())}).catch($=>{E.current===B&&(w({ok:!1,message:$ instanceof Error?$.message:String($)}),R(!1))})},z=c?"qa":"dev",le=Cn.test(i.id)&&!p.has(i.id)&&i.id!==(c==null?void 0:c.agent.id),ne=i.mode==="local"||i.mode==="remote"&&i.host!=="",ge=i.runtime!==""&&!!((L=d==null?void 0:d.runtimes[i.runtime])!=null&&L.ok),q=!!(d!=null&&d.tmux.ok),ie=i.mode==="local"||!!((G=d==null?void 0:d.ssh)!=null&&G.ok),me=!k&&le&&ne&&ge&&q&&ie,xe=async B=>{var Z,K;if(B.preventDefault(),!me)return;D(null);const C=i.addDirs.split(`
11
+ `).map(ee=>ee.trim()).filter(ee=>ee.length>0),$={id:i.id,role:z,runtime:i.runtime,mode:i.mode,...i.mode==="remote"?{host:i.host}:{},...i.workdir?{workdir:i.workdir}:{},yolo:i.yolo,...i.model.trim()?{model:i.model.trim()}:{},...C.length>0?{addDirs:C}:{}};if(!c){m({agent:$,form:i}),l(Ut),x(null),w(null),I(!1);return}j(!0);try{const ee=await M.projects.addAgentTeam(s,{agents:[c.agent,$]});ee.restartRequired&&te(),re({kind:(Z=ee.warnings)!=null&&Z.length?"warn":"success",title:a.createAgent.addedToastTitle(ee.agents.find(be=>be.role==="dev").id,ee.agents.find(be=>be.role==="qa").id,s),...(K=ee.warnings)!=null&&K.length?{body:ee.warnings.join(`
12
+ `)}:{}}),r(),n()}catch(ee){D(ee instanceof Error?ee.message:String(ee))}finally{j(!1)}},ye=()=>{!c||k||(l(c.form),m(null),x(null),w(null),I(!1))},S=({rt:B})=>{if(i.mode==="remote"&&!i.host)return t.jsx("span",{className:"ml-2 text-xs text-og-400",children:a.createAgent.selectHostFirstHint});if(b)return t.jsx("span",{className:"ml-2 text-xs text-og-400",children:a.createAgent.probingLabel});if(!d)return t.jsx("span",{className:"ml-2 text-xs text-og-400",children:"?"});const $=d.runtimes[B];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]}):t.jsx("span",{className:"ml-2 text-xs text-og-400",children:"?"})},we=()=>{var C;if(i.mode==="remote"&&!i.host)return null;if(b&&!T)return t.jsx("div",{className:"text-xs text-og-400",children:a.createAgent.tmuxProbingLabel});if(!d)return null;if(d.tmux.ok)return t.jsxs("div",{className:"text-xs text-probe-ok",children:["tmux: ✓ ",d.tmux.path??""]});const B=i.mode==="local"||!!((C=d.ssh)!=null&&C.ok);return t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"text-xs text-accent",children:["tmux: ⨯ ",d.tmux.message,B&&t.jsx("button",{type:"button",onClick:ae,className:"ml-2 text-accent underline transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",disabled:T||k,children:T?a.common.installing:a.common.oneClickInstall})]}),T&&t.jsx("div",{className:"text-xs text-og-500",children:a.common.installingTmuxNotice}),!T&&A&&t.jsxs("div",{className:`break-all text-xs ${A.ok?"text-probe-ok":"text-accent"}`,children:[A.ok?"✓ ":"⨯ ",A.message]})]})},pe=()=>i.mode!=="remote"||!i.host||!(d!=null&&d.ssh)?null:d.ssh.ok?t.jsxs("div",{className:"text-xs text-probe-ok",children:["SSH: ✓ ",d.ssh.message]}):t.jsxs("div",{className:"text-xs text-accent",children:["SSH: ⨯ ",d.ssh.message]});return t.jsx(Ce,{open:e,onClose:X,title:a.createAgent.modalTitle(s),size:"lg",footer:t.jsxs(t.Fragment,{children:[c&&t.jsx("button",{type:"button",onClick:ye,disabled:k,className:"btn-secondary",children:a.common.back}),t.jsx("button",{type:"button",onClick:X,disabled:k,className:"btn-secondary",children:a.common.cancel}),t.jsx("button",{type:"submit",form:"create-agent-form",disabled:!me,className:"btn-primary",children:k?a.createAgent.submitting:c?a.createAgent.submitLabel:a.createAgent.continueLabel})]}),children:t.jsxs("form",{id:"create-agent-form",onSubmit:xe,className:"space-y-3",children:[v&&t.jsx("div",{className:"whitespace-pre-line rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-sm text-accent",children:v}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"agent-id",children:a.createAgent.idLabel}),t.jsx("input",{id:"agent-id",type:"text",value:i.id,onChange:B=>l({...i,id:B.target.value}),className:he,placeholder:a.createAgent.idPlaceholder(s,z),disabled:k}),i.id&&!Cn.test(i.id)&&t.jsx("div",{className:St,children:a.common.idFormatError}),i.id&&(p.has(i.id)||i.id===(c==null?void 0:c.agent.id))&&t.jsx("div",{className:St,children:a.createAgent.idTakenGlobalError})]}),t.jsxs("div",{children:[t.jsx("span",{className:ue,children:a.createAgent.roleLabel}),t.jsx("div",{className:"text-sm text-og-800",children:z==="dev"?a.createAgent.devStepLabel:a.createAgent.qaStepLabel}),c&&t.jsx("div",{className:qe,children:a.createAgent.teamDevLabel(c.agent.id)})]}),t.jsxs("div",{children:[t.jsx("span",{className:ue,children:a.createAgent.modeLabel}),t.jsxs("label",{className:"mr-4 inline-flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"mode",checked:i.mode==="local",className:Ie,onChange:()=>l({...i,mode:"local",host:""}),disabled:k}),t.jsx("span",{className:"text-sm text-og-800",children:a.createAgent.localModeLabel})]}),t.jsxs("label",{className:"inline-flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"mode",checked:i.mode==="remote",className:Ie,onChange:()=>l({...i,mode:"remote"}),disabled:k}),t.jsx("span",{className:"text-sm text-og-800",children:a.createAgent.remoteModeLabel})]})]}),i.mode==="remote"&&t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"host",children:a.createAgent.hostLabel}),h.length===0?t.jsx("div",{className:"rounded-md border border-og-100 bg-og-50/40 px-3 py-2 text-xs text-og-600",children:a.createAgent.noHostsHint}):t.jsxs("select",{id:"host",value:i.host,onChange:B=>l({...i,host:B.target.value}),className:he,disabled:k,children:[t.jsx("option",{value:"",children:a.createAgent.selectHostPlaceholder}),h.map(B=>t.jsx("option",{value:B.id,children:oa(B)},B.id))]}),t.jsx("div",{className:qe,children:a.createAgent.sshConfigHint})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"mb-1.5 flex items-center justify-between",children:[t.jsx("span",{className:"text-xs font-medium text-og-700",children:a.createAgent.runtimeLabel}),t.jsx("button",{type:"button",onClick:V,className:"text-xs text-accent transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",disabled:k||b||i.mode==="remote"&&!i.host,children:a.createAgent.reprobeButton})]}),t.jsxs("label",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"runtime",checked:i.runtime==="claude-code",className:Ie,onChange:()=>l({...i,runtime:"claude-code"}),disabled:k||(d?!((N=d.runtimes["claude-code"])!=null&&N.ok):!1)}),t.jsx("span",{className:"text-sm text-og-800",children:"Claude Code"}),t.jsx(S,{rt:"claude-code"})]}),t.jsxs("label",{className:"mt-1 flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"runtime",checked:i.runtime==="codex",className:Ie,onChange:()=>l({...i,runtime:"codex"}),disabled:k||(d?!((U=d.runtimes.codex)!=null&&U.ok):!1)}),t.jsx("span",{className:"text-sm text-og-800",children:"Codex"}),t.jsx(S,{rt:"codex"})]}),t.jsxs("label",{className:"mt-1 flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"runtime",checked:i.runtime==="opencode",className:Ie,onChange:()=>l({...i,runtime:"opencode"}),disabled:k||(d?!((_=d.runtimes.opencode)!=null&&_.ok):!1)}),t.jsx("span",{className:"text-sm text-og-800",children:"OpenCode"}),t.jsx(S,{rt:"opencode"})]}),t.jsxs("label",{className:"mt-1 flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"runtime",checked:i.runtime==="qodercli",className:Ie,onChange:()=>l({...i,runtime:"qodercli"}),disabled:k||(d?!((se=d.runtimes.qodercli)!=null&&se.ok):!1)}),t.jsx("span",{className:"text-sm text-og-800",children:"Qoder CLI"}),t.jsx(S,{rt:"qodercli"})]}),t.jsx("div",{className:"mt-2",children:t.jsx(we,{})}),t.jsx("div",{children:t.jsx(pe,{})})]}),t.jsxs("div",{children:[t.jsxs("button",{type:"button",onClick:()=>I(B=>!B),"aria-expanded":P,"aria-controls":P?"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:P?a.createAgent.collapseLabel:a.createAgent.expandLabel})]}),P&&t.jsxs("div",{id:"advanced-options",className:"mt-3 space-y-3",children:[t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"workdir",children:a.createAgent.workdirLabel}),t.jsx("input",{id:"workdir",type:"text",value:i.workdir,onChange:B=>l({...i,workdir:B.target.value}),className:he,placeholder:a.createAgent.workdirPlaceholder,disabled:k}),t.jsx("div",{className:qe,children:a.createAgent.workdirHint})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"model",children:a.createAgent.modelLabel}),t.jsx("input",{id:"model",type:"text",value:i.model,onChange:B=>l({...i,model:B.target.value}),className:he,placeholder:i.runtime==="codex"?a.createAgent.modelPlaceholderCodex:a.createAgent.modelPlaceholderOther,disabled:k}),t.jsx("div",{className:qe,children:a.createAgent.modelHint})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"addDirs",children:a.createAgent.addDirsLabel}),t.jsx("textarea",{id:"addDirs",value:i.addDirs,onChange:B=>l({...i,addDirs:B.target.value}),className:`${he} font-mono text-xs`,rows:3,placeholder:a.createAgent.addDirsPlaceholder,disabled:k}),t.jsx("div",{className:qe,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:B=>l({...i,yolo:B.target.checked}),disabled:k}),t.jsxs("div",{className:"text-sm text-og-800",children:[t.jsx("div",{className:"font-medium",children:a.createAgent.yoloTitle}),t.jsx("div",{className:"mt-1 text-xs text-accent",children:i.runtime==="codex"?a.createAgent.yoloCodexBody:a.createAgent.yoloBody})]})]})})]})})}const Rn=200,An=16e3,la="baxian.draft.createTask:";function Jt(e){return`${la}${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:"",c=typeof r.preferredAgentId=="string"?r.preferredAgentId:"",m=typeof r.updatedAt=="number"?r.updatedAt:void 0;return!a.trim()&&!i.trim()?null:{title:a,description:i,projectId:l,preferredAgentId:c,updatedAt:m}}catch{return null}}function ca(e,n){const s=!n.title.trim()&&!n.description.trim();try{s?localStorage.removeItem(e):localStorage.setItem(e,JSON.stringify({...n,updatedAt:Date.now()}))}catch{}}function Pn(e){try{localStorage.removeItem(e)}catch{}}function da(e){const n=Jt(e),s=Dn(n);if(!e)return s;const r=Jt(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 Ln="mt-1 text-right text-xs text-og-400",ua=Math.floor(Pt/1024/1024);function mn(e){const n=H(),s=e.mode==="edit",{show:r}=je(),a=s?e.task.projectId:e.projectId,i=s?e.task.title:"",l=s?e.task.description:"",c=s?e.task.preferredAgentId:"",[m,h]=o.useState([]),[f,p]=o.useState([]),[u,d]=o.useState(a??""),[x,b]=o.useState(c),[y,T]=o.useState(i),[R,A]=o.useState(l),[w,k]=o.useState([]),j=o.useRef(null),[v,D]=o.useState(!1),[P,I]=o.useState(null),[O,J]=o.useState(!1),E=o.useRef(0),W=o.useRef(0),re=o.useRef(0),te=o.useRef(new Set),X=s?null:Jt(a);o.useEffect(()=>{if(!e.open)return;E.current+=1,W.current+=1;const C=E.current;h([]),p([]),te.current=new Set;const $=X?da(a):null;$&&te.current.add($.projectId),d(a??($==null?void 0:$.projectId)??""),b(($==null?void 0:$.preferredAgentId)||c),T(($==null?void 0:$.title)||i),A(($==null?void 0:$.description)||l),J($!==null),I(null),D(!1),k([]),Promise.all([M.projects.list(),M.agents.list()]).then(([Z,K])=>{C===E.current&&(h(Z),p(K))}).catch(Z=>{C===E.current&&I(Z instanceof Error?Z.message:String(Z))})},[e.open,a,i,l,c,X]),o.useEffect(()=>{if(!(!e.open||!X)){if(re.current!==W.current){re.current=W.current;return}ca(X,{title:y,description:R,projectId:u,preferredAgentId:x})}},[e.open,X,y,R,u,x]);const V=o.useMemo(()=>m.find(C=>C.id===u)??null,[m,u]),ae=o.useMemo(()=>V?V.agent.flat().filter(C=>C.role==="dev"):[],[V]),z=o.useMemo(()=>new Set(f.map(C=>C.id)),[f]),le=o.useMemo(()=>ae.filter(C=>z.has(C.id)),[ae,z]),ne=o.useMemo(()=>ae.filter(C=>!z.has(C.id)),[ae,z]);o.useEffect(()=>{s||V!==null&&x!==""&&!le.find(C=>C.id===x)&&b("")},[V,le,x,s]),o.useEffect(()=>{if(s||!V)return;const C=le.find($=>$.role==="dev");C&&(te.current.has(V.id)||(te.current.add(V.id),b($=>$===""?C.id:$)))},[s,V,le]);const ge=!s||le.find(C=>C.id===x),q=s&&!ge&&!!x,ie=q&&ne.some(C=>C.id===x),me=ie?n.createTask.noDevPendingRestartHint(x):q?n.createTask.noDevNotInRuntimeHint(x):!u||le.length>0?null:ne.length>0?n.createTask.noDevGlobalPendingRestartHint:null,xe=y.trim(),ye=R.trim(),we=!!u&&xe.length>0&&!v,pe=()=>{v||e.onClose()},L=()=>{X&&(Pn(X),d(a??""),b(c),T(i),A(l),I(null),J(!1))},G=async C=>{var $,Z;if(C.preventDefault(),!!we){D(!0),I(null);try{if(e.mode==="edit"){const K=await M.tasks.update(e.task.id,{title:xe,description:ye,preferredAgentId:x});r({kind:"success",title:n.createTask.updatedToastTitle}),($=e.onUpdated)==null||$.call(e,K),e.onClose()}else{const K=w.length?await Promise.all(w.map(async be=>({dataBase64:await Yn(be),filename:be.name}))):void 0,ee=await M.tasks.create({projectId:u,title:xe,description:ye,preferredAgentId:x,...K?{images:K}:{}});X&&Pn(X),r({kind:"success",title:n.createTask.createdToastTitle}),(Z=e.onCreated)==null||Z.call(e,ee),e.onClose()}}catch(K){I(K instanceof Error?K.message:String(K))}finally{D(!1)}}},N=C=>{const $=Array.from(C.target.files??[]);if(C.target.value="",$.length===0)return;const Z=$.filter(K=>K.size>Pt?(r({kind:"error",title:n.createTask.imageTooLargeToastTitle,body:n.createTask.imageTooLargeToastBody(K.name,ua)}),!1):!0);w.length+Z.length>ft&&r({kind:"warn",title:n.createTask.tooManyImagesToastTitle(ft)}),k(K=>[...K,...Z].slice(0,ft))},U=C=>k($=>$.filter((Z,K)=>K!==C)),_=s?n.createTask.titleEdit:n.createTask.titleCreate,se=s?v?n.common.saving:n.common.save:v?n.common.creating:n.common.create,B=!s&&!a;return t.jsx(Ce,{open:e.open,onClose:pe,title:_,size:"md",dismissOnBackdrop:!1,footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:pe,disabled:v,className:"btn-secondary",children:n.common.cancel}),t.jsx("button",{type:"submit",form:"create-task-form",disabled:!we,className:"btn-primary",children:se})]}),children:t.jsxs("form",{id:"create-task-form",onSubmit:G,className:"space-y-3",children:[!s&&O&&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:L,className:"shrink-0 underline hover:text-accent-hover",children:n.createTask.discardDraftButton})]}),P&&t.jsx("div",{className:"rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-sm text-accent",children:P}),B&&t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"task-project",children:n.createTask.projectLabel}),t.jsxs("select",{id:"task-project",value:u,onChange:C=>d(C.target.value),className:he,disabled:v,required:!0,children:[t.jsx("option",{value:"",disabled:!0,children:n.createTask.selectProjectPlaceholder}),m.map(C=>t.jsx("option",{value:C.id,children:C.id},C.id))]})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"task-dev",children:n.createTask.targetAgentLabel}),t.jsxs("select",{id:"task-dev",value:x,onChange:C=>b(C.target.value),className:he,disabled:v,children:[t.jsx("option",{value:"",children:n.createTask.notAssignedOption}),q&&t.jsxs("option",{value:x,children:[x," ",ie?n.createTask.pendingRestartSuffix:n.createTask.notInRuntimeSuffix]}),le.map(C=>t.jsx("option",{value:C.id,children:C.id},C.id))]}),me&&t.jsx("div",{className:"mt-1 text-xs text-accent",children:me})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"task-title",children:n.createTask.titleLabel}),t.jsx("input",{id:"task-title",type:"text",value:y,onChange:C=>T(C.target.value),maxLength:Rn,className:he,placeholder:n.createTask.titlePlaceholder,disabled:v,required:!0}),t.jsxs("div",{className:Ln,children:[y.length," / ",Rn]})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"task-description",children:n.createTask.descriptionLabel}),t.jsx("textarea",{id:"task-description",value:R,onChange:C=>A(C.target.value),maxLength:An,rows:8,className:`${he} font-mono text-xs`,placeholder:n.createTask.descriptionPlaceholder,disabled:v}),t.jsxs("div",{className:Ln,children:[R.length," / ",An]})]}),!s&&t.jsxs("div",{children:[t.jsx("label",{className:ue,children:n.createTask.imagesLabel}),t.jsx("button",{type:"button",onClick:()=>{var C;return(C=j.current)==null?void 0:C.click()},disabled:v||w.length>=ft,className:"btn-secondary",children:n.createTask.addImagesButton}),t.jsx("input",{ref:j,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:N}),w.length>0&&t.jsx("ul",{className:"mt-2 space-y-1",children:w.map((C,$)=>t.jsxs("li",{className:"flex items-center justify-between rounded-md border border-og-100 bg-surface px-2.5 py-1.5",children:[t.jsx("span",{title:C.name,className:"truncate text-xs text-og-700",children:C.name}),t.jsx("button",{type:"button","aria-label":n.createTask.removeImageAriaLabel(C.name),onClick:()=>U($),disabled:v,className:"ml-2 shrink-0 text-og-400 transition-colors",children:"✕"})]},`${C.name}-${$}`))})]})]})})}const En="***",Gt={hostname:"",port:"",alias:"",user:"",password:""};function ma(e){return e.alias?e.alias:`${e.user?`${e.user}@`:""}${e.hostname}${e.port!=null?`:${e.port}`:""}`}function ha({open:e,onClose:n}){var pe;const s=H(),[r,a]=o.useState([]),[i,l]=o.useState("list"),[c,m]=o.useState(null),[h,f]=o.useState(null),[p,u]=o.useState(!1),[d,x]=o.useState(!1),[b,y]=o.useState(Gt),[T,R]=o.useState(null),[A,w]=o.useState(!1),[k,j]=o.useState(!1),[v,D]=o.useState(null),[P,I]=o.useState(!1),[O,J]=o.useState(null),E=o.useRef(0),W=o.useRef(null),{show:re}=je(),te=o.useCallback(()=>{M.hosts.list().then(a).catch(L=>R(L instanceof Error?L.message:String(L)))},[]);o.useEffect(()=>{if(!e){W.current&&W.current.abort();return}l("list"),m(null),f(null),y(Gt),R(null),te()},[e,te]),o.useEffect(()=>{E.current+=1,W.current&&W.current.abort(),j(!1),D(null),I(!1),J(null)},[b.hostname,b.user,b.port,b.password,d,i]),o.useEffect(()=>()=>{W.current&&W.current.abort()},[]);const X=()=>{m(null),f(null),u(!1),x(!1),y(Gt),R(null),l("form")},V=L=>{m(L.id??null),f(L),u(L.password===En),x(!1),y({hostname:L.hostname,port:L.port!=null?String(L.port):"",alias:L.alias??"",user:L.user??"",password:""}),R(null),l("form")},ae=()=>{const L={hostname:b.hostname.trim()};return c?(L.port=b.port.trim()?Number(b.port):null,L.alias=b.alias.trim(),L.user=b.user.trim()):(b.port.trim()&&(L.port=Number(b.port)),b.alias.trim()&&(L.alias=b.alias.trim()),b.user.trim()&&(L.user=b.user.trim())),c&&d?L.password="":b.password&&(L.password=b.password),L},z=b.port.trim(),le=z===""||/^\d+$/.test(z)&&Number(z)>0&&Number(z)<=65535,ne=b.hostname.trim().length>0&&le,ge=!!h&&b.hostname.trim()===h.hostname&&b.user.trim()===(h.user??"")&&b.port.trim()===(h.port!=null?String(h.port):""),q=()=>c&&ge&&!b.password&&!d?{hostId:c}:{host:{hostname:b.hostname.trim(),...b.user.trim()?{user:b.user.trim()}:{},...z?{port:Number(z)}:{},...!d&&b.password?{password:b.password}:{}}},ie=async()=>{if(!ne||k)return;W.current&&W.current.abort();const L=new AbortController;W.current=L;const G=E.current;j(!0),D(null),J(null),R(null);try{const N=await M.agents.probe("remote",q(),{signal:L.signal});if(L.signal.aborted||E.current!==G)return;D(N)}catch(N){if(L.signal.aborted||E.current!==G)return;R(N instanceof Error?N.message:String(N))}finally{E.current===G&&j(!1)}},me=async()=>{if(P)return;const L=E.current;I(!0),J(null),R(null);try{const G=await M.agents.installTmux("remote",q());if(E.current!==L)return;J({ok:G.ok,message:G.message}),D(N=>N&&{...N,tmux:G.tmux})}catch(G){if(E.current!==L)return;R(G instanceof Error?G.message:String(G))}finally{E.current===L&&I(!1)}},xe=async L=>{if(L.preventDefault(),!(!ne||A)){w(!0),R(null);try{if(c)await M.hosts.update(c,ae()),re({kind:"success",title:s.hostMgmt.updatedToastTitle(c)});else{const G=await M.hosts.create(ae());re({kind:"success",title:s.hostMgmt.createdToastTitle(G.host.id)})}te(),l("list")}catch(G){R(G instanceof Error?G.message:String(G))}finally{w(!1)}}},ye=async L=>{R(null);try{await M.hosts.delete(L.id),re({kind:"success",title:s.hostMgmt.deletedToastTitle(L.id)}),te()}catch(G){R(G instanceof Error?G.message:String(G))}},S=t.jsx("button",{type:"button",onClick:n,className:"btn-secondary",children:s.common.close}),we=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:()=>l("list"),disabled:A,className:"btn-secondary",children:s.common.backText}),t.jsx("button",{type:"submit",form:"host-form",disabled:!ne||A,className:"btn-primary",children:A?s.common.saving:s.common.save})]});return t.jsxs(Ce,{open:e,onClose:n,title:s.hostMgmt.title,size:"md",footer:i==="list"?S:we,children:[T&&t.jsx("div",{className:"mb-3 whitespace-pre-line rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-sm text-accent",children:T}),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(L=>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:ma(L)}),t.jsxs("div",{className:"truncate text-xs text-og-500",children:[(L.user?`${L.user}@`:"")+L.hostname,L.port!=null?`:${L.port}`:"",L.password===En?s.hostMgmt.passwordSavedIndicator:""]})]}),t.jsxs("div",{className:"flex shrink-0 gap-2",children:[t.jsx("button",{type:"button",onClick:()=>V(L),className:"text-xs text-accent transition-colors hover:text-accent-hover",children:s.common.edit}),t.jsx("button",{type:"button",onClick:()=>ye(L),className:"text-xs text-accent transition-colors hover:opacity-80",children:s.common.delete})]})]},L.id))}),t.jsx("button",{type:"button",onClick:X,className:"btn-secondary w-full",children:s.hostMgmt.addHostButton})]}):t.jsxs("form",{id:"host-form",onSubmit:xe,className:"space-y-3",children:[t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"host-hostname",children:s.hostMgmt.addressLabel}),t.jsx("input",{id:"host-hostname",type:"text",value:b.hostname,onChange:L=>y({...b,hostname:L.target.value}),className:he,placeholder:"remote.example.com",disabled:A})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"host-port",children:s.hostMgmt.portLabel}),t.jsx("input",{id:"host-port",type:"text",inputMode:"numeric",value:b.port,onChange:L=>y({...b,port:L.target.value}),className:he,placeholder:"22",disabled:A}),b.port.trim()!==""&&!le&&t.jsx("div",{className:"mt-1 text-xs text-accent",children:s.hostMgmt.portRangeError})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"host-alias",children:s.hostMgmt.aliasLabel}),t.jsx("input",{id:"host-alias",type:"text",value:b.alias,onChange:L=>y({...b,alias:L.target.value}),className:he,placeholder:s.hostMgmt.aliasPlaceholder,disabled:A})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"host-user",children:s.hostMgmt.userLabel}),t.jsx("input",{id:"host-user",type:"text",value:b.user,onChange:L=>y({...b,user:L.target.value}),className:he,placeholder:s.hostMgmt.userPlaceholder,disabled:A})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"host-password",children:s.hostMgmt.passwordLabel}),t.jsx("input",{id:"host-password",type:"password",value:d?"":b.password,onChange:L=>y({...b,password:L.target.value}),className:he,placeholder:p?s.hostMgmt.passwordPlaceholderSet:s.hostMgmt.passwordPlaceholderUnset,disabled:A||d,autoComplete:"new-password"}),c&&p&&t.jsxs("label",{className:"mt-1.5 flex items-center gap-2 text-xs text-og-700",children:[t.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 accent-accent",checked:d,onChange:L=>x(L.target.checked),disabled:A}),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:!ne||k||A||P,className:"text-xs text-accent transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",children:k?s.hostMgmt.testing:s.hostMgmt.testConnection}),(v==null?void 0:v.ssh)&&t.jsxs("div",{className:`text-xs ${v.ssh.ok?"text-og-800":"text-accent"}`,children:["SSH: ",v.ssh.ok?"✓":"⨯"," ",v.ssh.message]}),v&&(v.tmux.ok?t.jsxs("div",{className:"text-xs text-og-800",children:["tmux: ✓ ",v.tmux.path??""]}):t.jsxs("div",{className:"text-xs text-accent",children:["tmux: ⨯ ",v.tmux.message,((pe=v.ssh)==null?void 0:pe.ok)&&t.jsx("button",{type:"button",onClick:me,disabled:P||A,className:"ml-2 text-accent underline transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",children:P?s.common.installing:s.common.oneClickInstall})]})),P&&t.jsx("div",{className:"text-xs text-og-500",children:s.common.installingTmuxNotice}),!P&&O&&t.jsxs("div",{className:`break-all text-xs ${O.ok?"text-og-800":"text-accent"}`,children:[O.ok?"✓ ":"⨯ ",O.message]})]})]})]})}const hn="baxian.taskNotifications.enabled";function fn(){if(typeof window>"u")return null;const e=window.Notification;return typeof e=="function"?e:null}function yt(){const e=fn();return e?e.permission:"unsupported"}function Wt(){try{return localStorage.getItem(hn)!=="0"}catch{return!0}}function wt(e){try{localStorage.setItem(hn,e?"1":"0")}catch{}}const ks=o.createContext(null);function fa({children:e}){const[n,s]=o.useState(yt),[r,a]=o.useState(Wt),[i,l]=o.useState(!1),c=o.useRef(!1),m=o.useRef(0);o.useEffect(()=>{const p=()=>{s(yt()),c.current||a(Wt())},u=d=>{if(d.key!==null&&d.key!==hn)return;s(yt());const x=d.key===null?Wt():d.newValue!=="0";x||(m.current+=1),a(x)};return window.addEventListener("focus",p),window.addEventListener("storage",u),()=>{window.removeEventListener("focus",p),window.removeEventListener("storage",u)}},[]);const h=o.useCallback(()=>{a(!0);const p=fn();if(!p){wt(!0);return}if(p.permission!=="default"){s(p.permission),wt(!0);return}if(c.current)return;c.current=!0,l(!0);const u=m.current;p.requestPermission().then(s).catch(d=>{console.warn("[task-notifications] permission request failed:",d),s(yt())}).finally(()=>{m.current===u&&wt(!0),c.current=!1,l(!1)})},[]),f=o.useCallback(()=>{m.current+=1,a(!1),wt(!1)},[]);return t.jsx(ks.Provider,{value:{permission:n,preferenceEnabled:r,enabled:n==="granted"&&r,requesting:i,enable:h,disable:f},children:e})}function js(){const e=o.useContext(ks);if(!e)throw new Error("useTaskNotifications must be used inside TaskNotificationsProvider");return e}const pa=[{value:"en-US",label:"English"},{value:"zh-CN",label:"简体中文"}];function ga({open:e,onClose:n}){const s=H(),{locale:r,saving:a,setLocale:i}=rs(),{show:l}=je(),c=async m=>{try{await i(m)}catch(h){const f=h instanceof Error?h.message:String(h);l({kind:"error",title:s.settings.languageSaveFailed(f)})}};return t.jsx(Ce,{open:e,onClose:n,title:s.settings.title,size:"sm",children:t.jsxs("div",{className:"space-y-5",children:[t.jsxs("fieldset",{children:[t.jsx("legend",{className:ue,children:s.settings.language}),t.jsx("div",{className:"flex gap-4",children:pa.map(m=>t.jsxs("label",{className:"inline-flex items-center gap-2 text-sm text-og-800",children:[t.jsx("input",{type:"radio",name:"baxian-language",className:Ie,checked:r===m.value,disabled:a,onChange:()=>void c(m.value)}),m.label]},m.value))})]}),t.jsx(xa,{})]})})}function xa(){const e=H(),{permission:n,enabled:s,requesting:r,enable:a,disable:i}=js();if(n==="unsupported")return null;const l=n==="denied";return t.jsxs("div",{children:[t.jsxs("label",{className:"inline-flex items-center gap-2 text-sm text-og-800",children:[t.jsx("input",{type:"checkbox",className:Ie,checked:s,disabled:l||r,onChange:()=>s?i():a()}),e.settings.taskNotifications]}),t.jsx("p",{className:qe,children:l?e.settings.taskNotificationsDenied:e.settings.taskNotificationsHint})]})}const Ts="topbar-actions";function $n(){return typeof document>"u"?null:document.getElementById(Ts)}function Ss({children:e}){const[n,s]=o.useState($n);return o.useEffect(()=>{n||s($n())},[n]),n?Ws.createPortal(e,n):null}function ba(){return ms("/api/realtime")}class va{constructor(n={}){ce(this,"wsUrl");ce(this,"wsFactory");ce(this,"tokenProvider");ce(this,"ws",null);ce(this,"topics",new Map);ce(this,"cache",new Map);ce(this,"outbox",[]);ce(this,"reconnectScheduler");ce(this,"explicitlyClosed",!1);this.wsUrl=n.wsUrl??ba(),this.wsFactory=n.wsFactory??hs,this.tokenProvider=n.tokenProvider??sn,this.reconnectScheduler=new cs({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.${us(n)}`]:void 0;let r;try{r=this.wsFactory(this.wsUrl,s)}catch(i){console.warn("[events-client] WebSocket constructor threw:",i),this.broadcastConnectionError({code:"connection_failed",message:i instanceof Error?i.message:"WebSocket constructor threw"}),this.scheduleReconnect();return}this.ws=r;let a=!1;r.onopen=()=>{if(r!==this.ws)return;a=!0,this.reconnectScheduler.reset();for(const l of this.topics.keys())try{r.send(JSON.stringify({op:"subscribe",topic:l}))}catch(c){console.warn("[events-client] resubscribe send failed:",c)}const i=this.outbox;this.outbox=[];for(const l of i)if(!(l.op==="subscribe"||l.op==="unsubscribe"))try{r.send(JSON.stringify(l))}catch(c){console.warn("[events-client] outbox flush failed:",c)}},r.onmessage=i=>{if(r!==this.ws)return;let l;try{const c=typeof i.data=="string"?i.data:String(i.data);l=JSON.parse(c)}catch{return}this.handleMessage(l)},r.onclose=i=>{r===this.ws&&(this.ws=null,!this.explicitlyClosed&&(ds(i,n,this.tokenProvider())||(a||this.broadcastConnectionError({code:"connection_failed",message:"WebSocket failed to connect (auth, network, or proxy issue)"}),this.topics.size!==0&&this.scheduleReconnect())))},r.onerror=()=>{}}scheduleReconnect(){this.reconnectScheduler.schedule()}broadcastConnectionError(n){for(const s of this.topics.values())for(const r of[...s.error])try{r(n)}catch(a){console.error("[events-client] error handler threw on connection error:",a)}}wsSendOrQueue(n){if(this.ws&&this.ws.readyState===WebSocket.OPEN)try{this.ws.send(JSON.stringify(n));return}catch(s){console.warn("[events-client] send failed, will queue:",s)}this.outbox.push(n)}handleMessage(n){switch(n.type){case"data":{const s=this.topics.get(n.topic);if(this.cache.set(n.topic,n.data),!s)return;for(const r of[...s.data])try{r(n.data)}catch(a){console.error(`[events-client] handler threw on ${n.topic}:`,a)}break}case"error":{const s={code:n.code,message:n.message};if(n.topic){const r=this.topics.get(n.topic);if(r)for(const a of[...r.error])try{a(s)}catch(i){console.error(`[events-client] error handler threw on ${n.topic}:`,i)}}else console.warn("[events-client] connection-level error:",n.code,n.message);break}}}}let zt=null;function rt(){return zt||(zt=new va),zt}function pn(){const[e,n]=o.useState(null),[s,r]=o.useState(!1),[a,i]=o.useState(null);return o.useEffect(()=>rt().subscribe("agents",c=>{i(null),n(c),r(!0)},c=>i(c)),[]),{data:e,loaded:s,error:a}}function Ns(e){const[n,s]=o.useState(null),[r,a]=o.useState(!1),[i,l]=o.useState(null);return o.useEffect(()=>(s(null),a(!1),l(null),rt().subscribe(`task:${e}`,m=>{l(null),s(m),a(!0)},m=>l(m))),[e]),{data:n,loaded:r,error:i}}function Cs(e){const[n,s]=o.useState(null),[r,a]=o.useState(!1),[i,l]=o.useState(null);return o.useEffect(()=>{if(!e){s(null),a(!1),l(null);return}s(null),a(!1),l(null);let c=!1,m=!1,h=!1;const f=rt().subscribe(`project-tasks:${e}`,p=>{c||(m=!0,l(null),s(p),a(!0))},p=>{c||(l(p),!(m||h)&&(h=!0,M.tasks.list(e).then(u=>{c||m||(s(u),a(!0))},u=>{console.warn(`[useProjectTasks] REST fallback failed for ${e}:`,u)})))});return()=>{c=!0,f()}},[e]),{data:n,loaded:r,error:i}}let Nt=null,Be=null,Ct=null,Ze=0;const Xt=new Set;function Rs(){Xt.forEach(e=>e())}async function ya(){const e=Ze;try{const n=await M.projects.list();if(e!==Ze)return;Nt=n,Ct=null}catch(n){if(e!==Ze)return;Ct=n instanceof Error?n.message:String(n)}finally{e===Ze&&(Be=null,Rs())}}function Zt(){return Be||(Be=ya(),Be)}function wa(){Ze+=1,Nt=null,Be=null,Ct=null,Rs()}typeof window<"u"&&window.addEventListener(et,wa);async function ka(){const e=Be!==null;await Zt(),e&&await Zt()}function at(){const[,e]=o.useState(0);return o.useEffect(()=>{const n=()=>e(s=>s+1);return Xt.add(n),Nt===null&&!Be&&Zt(),()=>{Xt.delete(n)}},[]),{projects:Nt,error:Ct,refresh:ka}}function ja(){const e=H(),n=Le(),{projects:s,error:r,refresh:a}=at(),i=s??[],l=s!==null,[c,m]=o.useState(!1),[h,f]=o.useState(!1),[p,u]=o.useState(!1),[d,x]=o.useState(!1),[b,y]=o.useState({kind:"closed"}),{data:T,loaded:R,error:A}=pn(),w=(A==null?void 0:A.message)??null,k=new Map((T??[]).map(P=>[P.id,P])),j=r??w,v=i.length===0,D=t.jsx("button",{type:"button",onClick:()=>f(!0),disabled:v,"aria-describedby":v?"create-task-hint":void 0,className:"btn-ghost",children:e.dashboard.newTask});return t.jsxs("div",{children:[t.jsxs(Ss,{children:[v?t.jsx("span",{className:"inline-flex",title:e.dashboard.createProjectFirst,children:D}):D,v&&t.jsx("span",{id:"create-task-hint",className:"sr-only",children:e.dashboard.createProjectFirst}),t.jsx(Dt,{ariaLabel:e.dashboard.moreActions,children:P=>t.jsxs(t.Fragment,{children:[t.jsx(ke,{onClick:()=>{P(),m(!0)},children:e.dashboard.newProject}),t.jsx(ke,{onClick:()=>{P(),u(!0)},children:e.dashboard.manageHosts}),t.jsx(ke,{onClick:()=>{P(),x(!0)},children:e.settings.entry})]})})]}),t.jsx("h1",{className:"sr-only",children:e.dashboard.title}),j&&t.jsx("div",{className:"mb-4 text-sm text-accent",children:e.common.loadFailed(j)}),l&&i.length===0&&!r&&t.jsx("div",{className:"rounded-lg border border-hairline bg-surface py-12 text-center text-sm text-og-500",children:e.dashboard.emptyProjects}),i.map(P=>t.jsx(Ta,{project:P,agentsById:k,agentsLoaded:R,agentsError:!!A,onAgentDeleted:a},P.id)),t.jsx(aa,{open:c,onClose:()=>m(!1),onCreated:P=>{m(!1),a(),y({kind:"asking",projectId:P})}}),t.jsx(ha,{open:p,onClose:()=>u(!1)}),t.jsx(Ce,{open:b.kind==="asking",onClose:()=>y({kind:"closed"}),title:e.dashboard.projectCreatedTitle,size:"sm",footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:()=>y({kind:"closed"}),className:"btn-secondary",children:e.dashboard.later}),t.jsx("button",{type:"button",onClick:()=>{b.kind==="asking"&&y({kind:"addingAgent",projectId:b.projectId})},className:"btn-primary",children:e.dashboard.continueAddingAgent})]}),children:t.jsx("p",{className:"text-sm text-og-700",children:e.dashboard.addAgentNowOrLater})}),b.kind==="addingAgent"&&t.jsx(ws,{open:!0,projectId:b.projectId,onClose:()=>y({kind:"closed"}),onCreated:()=>{a()}}),t.jsx(mn,{open:h,onClose:()=>f(!1),onCreated:P=>n(Pe(P.projectId,P.id))}),t.jsx(ga,{open:d,onClose:()=>x(!1)})]})}function Ta({project:e,agentsById:n,agentsLoaded:s,agentsError:r,onAgentDeleted:a}){const i=H(),{data:l,error:c}=Cs(e.id),m=l??[],h=(c==null?void 0:c.message)??null;return t.jsxs("div",{className:"mb-10",children:[t.jsxs("div",{className:"mb-3 -mx-2 flex items-baseline gap-x-3 gap-y-1 px-2 py-1",children:[t.jsx("h2",{className:"min-w-0 truncate font-display text-sm font-semibold tracking-tight text-og-1000",title:e.id,children:t.jsx(Ne,{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(Ne,{to:`/project/${e.id}`,className:"ml-auto text-sm text-accent hover:text-accent-hover","aria-label":i.dashboard.detailsAriaLabel(e.id),children:i.dashboard.detailsLink})]}),h&&t.jsx("div",{className:"mb-2 text-xs text-accent",children:i.dashboard.tasksLoadFailed(h)}),e.agent.flat().length===0?t.jsx("div",{className:"rounded-lg border border-hairline bg-surface py-6 text-center text-sm text-og-500",children:i.dashboard.noAgentsYet}):t.jsx("div",{className:e.agent.length===1?"space-y-3":"grid grid-cols-1 gap-3 xl:grid-cols-2",children:e.agent.map((f,p)=>t.jsx(ys,{team:f,projectId:e.id,agentsById:n,agentsLoaded:s,agentsError:r,tasks:m,onDeleted:a,terminalMode:"embedded-full"},f.map(u=>u.id).join(":")||p))})]})}const As="baxian.taskPanel.doneOpen";function Sa(){try{return localStorage.getItem(As)==="1"}catch{return!1}}function Rt(e){const n=e.match(/^task-(\d+)$/);return n?parseInt(n[1],10):Number.NaN}function Na(e,n){const s=Rt(e.id),r=Rt(n.id);return Number.isNaN(s)||Number.isNaN(r)?e.id.localeCompare(n.id):s-r}function Ca(e,n){const s=(n.updatedAt??"").localeCompare(e.updatedAt??"");if(s!==0)return s;const r=Rt(e.id),a=Rt(n.id);return Number.isNaN(r)||Number.isNaN(a)?n.id.localeCompare(e.id):a-r}function In(e,n){const[s,r]=o.useState(Bt);o.useEffect(()=>r(Bt),[n]);const a=e.slice(0,s),i=e.length>a.length;return{items:a,hasMore:i,loadMore:()=>r(c=>c+Bt),total:e.length}}function Ra(e){const[n,s]=o.useState([]),[r,a]=o.useState(!1),[i,l]=o.useState(!1),[c,m]=o.useState(!1),[h,f]=o.useState(null),p=o.useRef(0),u=o.useRef(0),d=o.useCallback(x=>{const b=++p.current,y=x==="first"?0:u.current;l(!0),f(null),M.tasks.page(e,{category:"done",offset:y}).then(T=>{p.current===b&&(s(R=>x==="first"?T.tasks:[...R,...T.tasks]),a(T.hasMore),u.current=T.nextOffset,m(!0),l(!1))},T=>{p.current===b&&(f(T instanceof Error?T.message:String(T)),l(!1))})},[e]);return o.useEffect(()=>{p.current+=1,u.current=0,s([]),a(!1),m(!1),f(null),l(!1)},[e]),{items:n,hasMore:r,loading:i,loaded:c,error:h,load:d}}function Aa({projectId:e,openTasks:n,className:s=""}){const r=H(),a=o.useMemo(()=>n.filter(u=>tn.has(u.status)).sort(Ca),[n]),i=o.useMemo(()=>n.filter(u=>u.status==="pending").sort(Na),[n]),l=In(a,e),c=In(i,e),m=Ra(e),[h,f]=o.useState(Sa);o.useEffect(()=>{try{localStorage.setItem(As,h?"1":"0")}catch{}},[h]),o.useEffect(()=>{h&&m.load("first")},[h,m.load]);const p=()=>f(u=>!u);return t.jsx("aside",{"aria-label":r.taskPanel.ariaLabel,className:`flex flex-col rounded-lg border border-hairline bg-surface ${s}`,children:t.jsxs("div",{children:[t.jsx(Bn,{title:r.taskPanel.inProgressTitle,section:l,emptyHint:r.taskPanel.emptyInProgress}),t.jsx(Bn,{title:r.taskPanel.pendingTitle,section:c,emptyHint:r.taskPanel.emptyPending}),t.jsxs("div",{children:[t.jsxs("button",{type:"button",onClick:p,"aria-expanded":h,className:"flex w-full items-center justify-between px-3 py-2 text-left text-xs font-normal uppercase tracking-[0.05em] text-og-500 transition-colors hover:bg-og-50/40",children:[t.jsx("span",{children:r.taskPanel.doneTitle}),t.jsx("span",{className:"font-normal normal-case text-accent",children:h?r.taskPanel.collapse:r.taskPanel.view})]}),h&&t.jsx(Da,{state:m})]})]})})}function Bn({title:e,section:n,emptyHint:s}){const r=H();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(Ds,{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 Da({state:e}){const n=H(),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(Ds,{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 Ds({task:e}){const n=H(),s=Le(),{show:r}=je(),[a,i]=o.useState(!1),l=Fe(e.phase)?e.specReviewRound??0:e.reviewRound,c=e.status==="pending"&&e.preferredAgentId==="",m=c?n.taskDetail.editTask:e.status==="pending"?n.taskDetail.startTask:e.status==="review"?n.taskDetail.restartReview:e.status==="approved"?n.taskDetail.retryPreMergeCheck:n.taskDetail.retryCurrentStep,h=e.attention?gs(n,e.attention,e.status):null,f=()=>s(Pe(e.projectId,e.id)),p=async()=>{if(c||e.postApproveRevoked||e.status==="review"&&Wn(e)){f();return}i(!0);try{await M.tasks.advance(e.id),r({kind:"success",title:n.taskDetail.advanceSucceededTitle})}catch(u){r({kind:"error",title:n.taskDetail.advanceFailedTitle,body:n.taskDetail.actionFailedBody,details:u instanceof Error?u.message:String(u)})}finally{i(!1)}};return t.jsxs("div",{className:"px-3 py-2",children:[t.jsx("div",{className:"flex items-center gap-2 text-sm",children:t.jsxs("button",{type:"button",onClick:f,className:"flex min-w-0 flex-1 items-center gap-2 text-left",children:[t.jsx("span",{className:"shrink-0 font-mono text-xs text-og-500",title:e.id,children:un(e.id)}),t.jsx("span",{className:"min-w-0 flex-1 truncate text-og-1000",title:e.title,children:e.title}),l>0&&t.jsx("span",{"aria-label":n.agents.round(l),className:"shrink-0 text-xs text-og-400",children:n.taskPanel.round(l)}),t.jsx(dn,{task:e,className:"shrink-0"})]})}),e.attention&&h&&t.jsxs("div",{className:"mt-2 rounded border border-accent/25 bg-accent-soft/60 px-2 py-1.5 text-xs text-accent",children:[t.jsxs("button",{type:"button",onClick:f,className:"block w-full text-left",children:[t.jsx("span",{className:"font-medium",children:h.title}),t.jsx("span",{className:"mt-0.5 block text-og-700",children:h.guidance})]}),t.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1.5",children:cn(e.attention,e.status).map(u=>t.jsx("button",{type:"button",disabled:u==="advance"&&a,onClick:()=>u==="advance"?void p():f(),className:u==="advance"?"btn-primary":"btn-secondary",children:u==="advance"?a?n.taskDetail.advancing:m:u==="verdict"?n.taskDetail.handleReview:u==="cancel"?n.taskDetail.cancelConfirmLabel:n.taskDetail.retryTask},u))}),t.jsxs("details",{open:h.expandDetails,className:"mt-1.5 text-og-500",children:[t.jsx("summary",{className:"cursor-pointer select-none text-accent",children:n.common.technicalDetails}),t.jsxs("div",{className:"mt-1 whitespace-pre-wrap break-words font-mono",children:[e.attention.reason,`
13
+ `,e.attention.runbook]})]})]})]})}const Pa=[],Ps="baxian.taskPanel.open";function La(){try{return localStorage.getItem(Ps)!=="0"}catch{return!0}}function Ea(){const{id:e}=At(),n=Le(),s=H(),{show:r}=je(),{refresh:a}=at(),[i,l]=o.useState(null),[c,m]=o.useState(null),[h,f]=o.useState(!1),[p,u]=o.useState(!1),d=o.useRef(null),[x,b]=o.useState(La),[y,T]=o.useState(!1),[R,A]=o.useState(""),[w,k]=o.useState(!1),[j,v]=o.useState(null),D=o.useRef(0),{data:P,loaded:I,error:O}=pn(),{data:J,error:E}=Cs(e),W=(O==null?void 0:O.message)??null,re=(E==null?void 0:E.message)??null,te=J??Pa,X=new Map((P??[]).map(q=>[q.id,q])),V=c??W??re,ae=o.useCallback(async q=>{const ie=++D.current;try{const me=await M.projects.get(q);if(ie!==D.current)return;l(me),m(null)}catch(me){if(ie!==D.current)return;m(me instanceof Error?me.message:String(me))}},[]);o.useEffect(()=>{e&&(l(null),m(null),ae(e))},[e,ae]),o.useEffect(()=>{y||(A(""),v(null))},[y]),o.useEffect(()=>{try{localStorage.setItem(Ps,x?"1":"0")}catch{}},[x]);const z=(i==null?void 0:i.agent.flat().length)??0,le=z===0,ne=!!i&&R.trim()===i.id,ge=async()=>{if(!(!i||!ne||w)){k(!0),v(null);try{await M.projects.delete(i.id),await a(),r({kind:"success",title:s.projectPage.deletedToastTitle(i.id)}),T(!1),n("/")}catch(q){v(q instanceof Error?q.message:String(q))}finally{k(!1)}}};return i?t.jsxs("div",{children:[t.jsxs(Ss,{children:[t.jsx("button",{type:"button",onClick:()=>u(!0),className:"btn-ghost",children:s.projectPage.newTaskButton}),t.jsx(Dt,{ariaLabel:s.projectPage.menuAriaLabel(i.id),menuClassName:"min-w-[180px]",triggerRef:d,children:q=>t.jsxs(t.Fragment,{children:[!x&&t.jsx(ke,{onClick:()=>{q(),b(!0)},children:s.projectPage.showTaskPanel}),t.jsx(ke,{onClick:()=>{q(),f(!0)},children:s.projectPage.addAgent}),t.jsx("div",{role:"none",className:"my-1 border-t border-hairline"}),t.jsx(ke,{onClick:()=>{q(),T(!0)},disabled:!le,title:le?void 0:s.projectPage.deleteAgentsFirstHint(z),children:s.projectPage.deleteProjectMenuItem})]})})]}),V&&t.jsx("div",{className:"mb-4 text-sm text-accent",children:s.common.loadFailed(V)}),t.jsxs("div",{className:"mb-6 flex items-baseline gap-x-3",children:[t.jsx("h1",{className:"min-w-0 truncate font-display text-sm font-semibold tracking-tight text-og-1000",title:i.id,children:i.id}),t.jsx("span",{className:"hidden min-w-0 truncate font-mono text-xs text-og-500 sm:inline-block",title:i.repo,children:i.repo})]}),t.jsxs("div",{className:"flex flex-col gap-4 lg:flex-row lg:items-start",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:"mb-3 flex h-8 items-center gap-2",children:t.jsx("h2",{className:"font-display text-xs font-semibold uppercase tracking-[0.06em] text-og-500",children:s.projectPage.agentsHeading})}),i.agent.flat().length===0?t.jsx("div",{className:"mb-8 rounded-lg border border-hairline bg-surface py-6 text-center text-sm text-og-500",children:s.projectPage.noAgentsYet}):t.jsx("div",{className:"mb-8 space-y-5",children:i.agent.map((q,ie)=>t.jsx(ys,{team:q,projectId:i.id,agentsById:X,agentsLoaded:I,agentsError:!!O,tasks:te,onDeleted:()=>{ae(i.id)},terminalMode:"embedded-full"},q.map(me=>me.id).join(":")||ie))})]}),x&&t.jsxs("div",{className:"w-full lg:w-[340px] lg:shrink-0 xl:w-[380px]",children:[t.jsxs("div",{className:"mb-3 flex h-8 items-center justify-between gap-2",children:[t.jsx("h2",{className:"font-display text-xs font-semibold uppercase tracking-[0.06em] text-og-500",children:s.projectPage.tasksHeading}),t.jsx("button",{type:"button",onClick:()=>{var q;b(!1),(q=d.current)==null||q.focus()},"aria-label":s.projectPage.closeTaskPanel,className:"flex h-7 w-7 items-center justify-center rounded text-og-500 transition-colors hover:bg-og-50 hover:text-og-1000",children:t.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[t.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),t.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),t.jsx(Aa,{projectId:i.id,openTasks:te})]})]}),t.jsx(ws,{open:h,projectId:i.id,onClose:()=>f(!1),onCreated:()=>{ae(i.id)}}),t.jsx(mn,{open:p,projectId:i.id,onClose:()=>u(!1),onCreated:q=>n(Pe(q.projectId,q.id))}),t.jsx(Ce,{open:y,onClose:()=>{w||T(!1)},title:s.projectPage.deleteModalTitle,size:"sm",footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:()=>T(!1),disabled:w,className:"btn-secondary",children:s.common.cancel}),t.jsx("button",{type:"button",onClick:()=>void ge(),disabled:!ne||w,className:"btn-primary",children:w?s.common.deleting:s.projectPage.confirmDeleteButton})]}),children:t.jsxs("div",{className:"space-y-4",children:[t.jsxs("p",{className:"text-sm text-og-700",children:[s.projectPage.deleteBodyLead,t.jsx("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:R,onChange:q=>A(q.target.value),placeholder:i.id,autoComplete:"off",autoCorrect:"off",spellCheck:!1,disabled:w,"aria-label":s.projectPage.confirmInputAriaLabel,className:"w-full rounded border border-hairline bg-surface px-3 py-2 font-mono text-sm text-og-1000 focus:border-accent focus:outline-none"}),j&&t.jsx("div",{className:"rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-xs text-accent",children:j})]})})]}):c?t.jsx("div",{className:"text-sm text-accent",children:s.common.loadFailed(c)}):t.jsx("div",{className:"text-sm text-og-500",children:s.common.loading})}const Ls={approve:"pill pill-live","request-changes":"pill pill-warn",comment:"pill"};function Es(e){const n=e.some(i=>i.roundToken!==void 0),s=i=>n?i.roundToken!==void 0:i.kind==="review",r=[];let a=[];for(const i of e)s(i)?(r.push({items:a,review:i}),a=[]):a.push(i);return a.length>0&&r.push({items:a}),r}function nt(e,n){const s=e.id||e.commitSha||e.createdAt||e.body||n;return e.sourceKey!==void 0?JSON.stringify([e.kind,e.sourceKey,s]):`${e.kind}-${s}`}function Et(e){if(e.id)return e.sourceKey!==void 0?`pr-${e.kind}.${e.sourceKey}.${e.id}`:`pr-${e.kind}-${e.id}`}function $s(e,n){return e.review?`round-${nt(e.review,n)}`:`round-in-progress-${e.items[0]?nt(e.items[0],n):n}`}function Is(e){const n=e.closedUnmergedAnchor;return[e.reviewRound,e.latestHeadSha??"",e.status,e.reviewDispatchedAt??"",e.prFeedbackReceivedAt??"",e.prNumber??"",e.reviewConversationUpdatedAt??"",n===void 0?"":`${n.generation}/${n.cleared===!0?"reopened":"closed"}`].join(":")}const $a=4e3,Ia=6e4;function Bs(e,n){const[s,r]=o.useState(null),[a,i]=o.useState(!1),[l,c]=o.useState(null),[m,h]=o.useState(!1),[f,p]=o.useState(null),[u,d]=o.useState(0),x=o.useRef(e),b=o.useRef(n),y=o.useRef(0),T=o.useRef(0),R=o.useRef(void 0),A=o.useRef(0),w=o.useRef(null);o.useEffect(()=>{const j=()=>{w.current!==null&&(w.current=null,h(!1),p(null))};x.current!==e&&(x.current=e,r(null),i(!1),p(null),T.current=0,j()),b.current!==n&&(b.current=n,T.current=0,j());const v=++y.current;return c(null),M.tasks.prReview(e).then(D=>{if(y.current===v)if(r(D),i(!0),D.available&&D.error&&T.current<3){T.current+=1;const P=D.rateLimited?Ia*2**(T.current-1):$a*T.current;R.current=setTimeout(()=>d(I=>I+1),P)}else D.error||(T.current=0)}).catch(D=>{y.current===v&&(c(D instanceof Error?D.message:String(D)),r(null),i(!0))}),()=>{clearTimeout(R.current),R.current=void 0}},[e,n,u]);const k=o.useCallback(()=>{if(w.current!==null)return;const j=++A.current;w.current=j,h(!0),p(null),M.tasks.prReviewRefresh(x.current).then(v=>{if(w.current===j){if(v.available&&(v.error!==void 0||v.rateLimited===!0)){p(v.error??"rate limited");return}clearTimeout(R.current),R.current=void 0,y.current+=1,T.current=0,r(v),i(!0),c(null)}}).catch(v=>{w.current===j&&p(v instanceof Error?v.message:String(v))}).finally(()=>{w.current===j&&(w.current=null,h(!1))})},[]);return{data:s,loaded:a,error:l,refresh:k,refreshing:m,refreshError:f}}function Ba(e){const n=new Date(e);if(Number.isNaN(n.getTime()))return e;const s=r=>String(r).padStart(2,"0");return`${n.getFullYear()}-${s(n.getMonth()+1)}-${s(n.getDate())} ${s(n.getHours())}:${s(n.getMinutes())}:${s(n.getSeconds())}`}function Fs({data:e,onRefresh:n,refreshing:s,refreshError:r}){const a=H(),i=e.autoRefresh===!0?e.autoRefreshIntervalMs:void 0,[l,c]=o.useState(void 0),m=o.useRef(Date.now());return o.useEffect(()=>{m.current=Date.now()},[e]),o.useEffect(()=>{if(i===void 0||i<=0){c(void 0);return}const h=()=>{const p=Date.now()-m.current;c(Math.ceil((i-p%i)/1e3))};h();const f=setInterval(h,1e3);return()=>clearInterval(f)},[i,e]),e.available?t.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-og-400",children:[e.fetchedAt&&t.jsx("span",{children:a.prReview.fetchedAtLabel(Ba(e.fetchedAt))}),e.autoRefresh===!1&&t.jsx("span",{children:a.prReview.autoRefreshStopped}),e.autoRefresh===!0&&l!==void 0&&t.jsx("span",{children:a.prReview.nextCheck(l)}),t.jsx("button",{type:"button",className:"text-accent hover:text-accent-hover disabled:opacity-60",onClick:n,disabled:s,children:s?a.prReview.refreshing:a.prReview.refresh}),r&&t.jsx("span",{className:"text-accent",children:a.prReview.refreshFailed(r)})]}):null}function Fa({role:e,label:n,summary:s,badge:r,onClick:a}){const i=H();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 Ma(e){return{"no-pr":e.prReview.reasonNoPr,"driver-unavailable":e.prReview.reasonDriverUnavailable}}function Oa(e){return(e==null?void 0:e.trim().split(`
14
+ `,1)[0])??""}function _a(e){if(!(e.kind!=="review-comment"||!e.path))return e.line!==void 0?`${e.path}:${e.line}`:e.path}function Ha(e,n){return n.bodyTruncated?e.prReview.truncatedSuffix:""}function qa(e,n){const s=Oa(n.body),r=Ha(e,n);if(n.kind==="review-comment"){const a=_a(n);if(n.inReplyTo){const i=[n.author,a,s].filter(l=>!!l);if(i.length>0)return`${i.join(" · ")}${r}`}return a&&s?`${a} · ${s}${r}`:`${s||a||e.prReview.inlineComment}${r}`}return n.kind==="issue-comment"?n.author&&s?`${n.author} · ${s}${r}`:`${s||n.author||e.prReview.comment}${r}`:`${s||e.prReview.noReviewBodyFallback}${r}`}function Ua(e,n){return n.verdict!==void 0||n.kind==="review"?e.review.reviewTurnLabel:n.kind==="review-comment"?n.inReplyTo?e.review.responseTurnLabel:e.prReview.inlineComment:e.prReview.comment}function Ga(e){return e.verdict!==void 0?"qa":e.kind==="issue-comment"||e.inReplyTo?"dev":"qa"}function Wa({task:e}){const n=H(),s=Le(),r=Is(e),{data:a,loaded:i,error:l,refresh:c,refreshing:m,refreshError:h}=Bs(e.id,r),f=Fe(e.phase)?n.prReview.specReviewHeading:n.prReview.codeReviewHeading;function p(x){s(`/tasks/${encodeURIComponent(e.id)}/pr-review${x?`#${x}`:""}`)}if(l)return t.jsx(Je,{title:f,children:t.jsx("div",{className:"text-sm text-accent",children:n.review.loadFailed(l)})});if(!i)return t.jsx(Je,{title:f,children:t.jsx("div",{className:"text-sm text-og-400",children:n.review.loadingRecords})});if(!(a!=null&&a.available)){const x=Ma(n);return t.jsx(Je,{title:f,children:t.jsx("div",{className:"text-sm text-og-400",children:x[(a==null?void 0:a.reason)??"no-pr"]??x["no-pr"]})})}const u=t.jsx(Fs,{data:a,onRefresh:c,refreshing:m,refreshError:h});if(a.items.length===0)return t.jsxs(Je,{title:f,children:[u,a.truncated?t.jsx("div",{className:"text-sm text-accent",children:n.prReview.listTruncated}):a.error?t.jsx("div",{className:"text-sm text-accent",children:n.prReview.fetchFailed(a.error)}):t.jsx("div",{className:"text-sm text-og-400",children:n.review.notStarted})]});const d=Es(a.items);return t.jsxs(Je,{title:f,children:[u,a.error&&t.jsx("div",{className:"text-xs text-accent",children:n.prReview.partialFetchFailed(a.error)}),a.truncated&&t.jsx("div",{className:"text-xs text-accent",children:n.prReview.listTruncated}),d.map((x,b)=>t.jsx(za,{round:x,index:b,onOpen:p},$s(x,String(b))))]})}function Je({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 za({round:e,index:n,onOpen:s}){const r=H(),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(Fn,{item:i,onOpen:s},nt(i,`${n}-${l}`))),e.review&&t.jsx(Fn,{item:e.review,onOpen:s})]})]})}function Fn({item:e,onOpen:n}){const s=H(),r=e.verdict,a=r?t.jsx("span",{className:Ls[r],children:r}):e.kind==="review"&&e.reviewState?t.jsx("span",{className:"pill",children:e.reviewState}):void 0;return t.jsx(Fa,{role:Ga(e),label:Ua(s,e),badge:a,summary:qa(s,e),onClick:()=>n(Et(e))})}function Ka({task:e}){const n=H();return e.prNumber===void 0?null:t.jsxs("section",{className:"mt-4","aria-label":n.review.sectionTitle,children:[t.jsx("div",{className:"mb-2 text-sm text-og-700",children:n.review.sectionTitle}),t.jsx(Wa,{task:e})]})}const Va=Vn;function Qa(e,n){if(!e||!n)return null;const s=e.match(/^(https?:\/\/[^/]+\/[^/]+\/[^/]+)\/pull\/\d+/);if(!s)return null;const r=n.split("/").map(encodeURIComponent).join("/");return`${s[1]}/tree/${r}`}function Mn(e){if(!/^[1-9]\d*$/.test(e.trim()))return;const n=Number(e);return Number.isSafeInteger(n)?n:void 0}function Ya(e){return e.status==="review"&&!Fe(e.phase)}function kt({children:e,open:n}){const s=H();return t.jsxs("details",{open:n,className:"mt-2 text-xs text-og-500",children:[t.jsx("summary",{className:"cursor-pointer select-none text-accent",children:s.common.technicalDetails}),t.jsx("div",{className:"mt-1 whitespace-pre-wrap break-words font-mono",children:e})]})}function Ja(){const{taskId:e=""}=At();return t.jsx(Xa,{taskId:e},e)}function Xa({taskId:e}){var xn;const n=Le(),s=H(),{show:r}=je(),a=ln(),[i,l]=o.useState(!1),[c,m]=o.useState(!1),[h,f]=o.useState(!1),[p,u]=o.useState(!1),[d,x]=o.useState(!1),[b,y]=o.useState("spec"),[T,R]=o.useState(""),[A,w]=o.useState(!1),[k,j]=o.useState(!1),[v,D]=o.useState(!1),[P,I]=o.useState(""),[O,J]=o.useState(!1),[E,W]=o.useState(""),[re,te]=o.useState(!1),[X,V]=o.useState(null),{data:ae,loaded:z,error:le}=Ns(e),{projects:ne,error:ge}=at(),{data:q,loaded:ie,error:me}=pn(),{activeAgentId:xe,activateAgentCard:ye}=vs(),S=X??ae,we=S!==null&&Ya(S),pe=we&&(re||((xn=S==null?void 0:S.attention)==null?void 0:xn.recommendedActions.includes("verdict"))===!0),L=(le==null?void 0:le.message)??null,G=S?ne==null?void 0:ne.find(g=>g.id===S.projectId):void 0,N=G===void 0?"unknown":G.merge==="auto"?"auto":"manual",U=ne===null&&ge===null,_=o.useMemo(()=>new Map((q??[]).map(g=>[g.id,g])),[q]);o.useEffect(()=>{X&&ae&&ae.updatedAt>=X.updatedAt&&V(null)},[X,ae]),o.useEffect(()=>{te(!1)},[S==null?void 0:S.status,S==null?void 0:S.reviewRound]);const se=g=>{V(g)},B=g=>({body:s.taskDetail.actionFailedBody,details:g instanceof Error?g.message:String(g)}),C=(g,F)=>{const Y=F??(g.status==="review"?"qa":"dev");return g.status==="pending"?g.preferredAgentId===""?s.taskDetail.editTask:s.taskDetail.startTask:Y==="qa"&&g.status!=="review"?s.taskDetail.startReview:g.status==="review"?s.taskDetail.restartReview:g.status==="approved"?s.taskDetail.retryPreMergeCheck:s.taskDetail.retryCurrentStep},$=()=>U?s.taskDetail.loadingMergeSetting:N==="auto"?s.taskDetail.confirmAndMerge:N==="manual"?s.taskDetail.confirmComplete:s.taskDetail.confirmResult,Z=async()=>{if(!S)return;const g=Vn.has(S.status);if(await a({title:s.taskDetail.cancelConfirmTitle(S.id),body:g?s.taskDetail.cancelConfirmBodyTerminal:s.taskDetail.cancelConfirmBodyActive,confirmLabel:s.taskDetail.cancelConfirmLabel,cancelLabel:s.common.backText})){m(!0);try{const Y=await M.tasks.update(S.id,{status:"cancelled"});se(Y),r({kind:"success",title:Y.status==="cancelled"?s.taskDetail.cancelledToastTitle:s.taskDetail.cancelCleanupToastTitle})}catch(Y){r({kind:"error",title:s.taskDetail.cancelFailedTitle,...B(Y)})}finally{m(!1)}}},K=async(g,F,Y)=>{u(!0);try{const de=await M.tasks.advance(g.id,{executor:F,...g.status==="pending"&&g.preferredAgentId?{agentId:g.preferredAgentId}:{},...Y??{}});se(de),x(!1),r({kind:"success",title:s.taskDetail.advanceSucceededTitle})}catch(de){r({kind:"error",title:s.taskDetail.advanceFailedTitle,...B(de)})}finally{u(!1)}},ee=async g=>{var ve;if(!S)return;if(S.status==="pending"&&S.preferredAgentId===""){l(!0);return}const F=g??(S.status==="review"?"qa":"dev"),Y=C(S,F);if(F==="qa"&&Wn(S)){y(S.phase??"spec"),R(((ve=S.prNumber)==null?void 0:ve.toString())??""),x(!0);return}if(S.postApproveRevoked){if(!await a({title:s.taskDetail.advanceRevokedConfirmTitle,body:S.postApproveRevoked.reason==="request-changes"?s.taskDetail.advanceRevokedRequestChangesBody:s.taskDetail.advanceRevokedRetryLimitBody,confirmLabel:Y}))return;await K(S,F,{confirmRevoked:!0});return}await a({title:s.taskDetail.advanceConfirmTitle(Y),body:S.status==="pending"?s.taskDetail.startTaskConfirmBody(S.id,S.preferredAgentId):F==="qa"&&S.status==="review"?s.taskDetail.restartReviewConfirmBody(S.id):F==="qa"?s.taskDetail.startReviewConfirmBody(S.id):S.status==="approved"?s.taskDetail.retryPreMergeConfirmBody:s.taskDetail.retryCurrentStepConfirmBody(S.id),confirmLabel:Y})&&await K(S,F)},be=async()=>{if(!(!S||!await a({title:s.taskDetail.retryConfirmTitle(S.id),body:S.status==="merged"?s.taskDetail.retryConfirmBodyMerged:s.taskDetail.retryConfirmBodyDefault,confirmLabel:s.taskDetail.retryTask}))){f(!0);try{const F=await M.tasks.retry(S.id);r({kind:"success",title:s.taskDetail.retryCreatedToastTitle(F.id)}),n(Pe(F.projectId,F.id))}catch(F){r({kind:"error",title:s.taskDetail.retryFailedTitle,...B(F)})}finally{f(!1)}}},Ve=async()=>{if(S&&await a({title:s.taskDetail.markCompleteConfirmTitle,body:s.taskDetail.markCompleteConfirmBody(S.prNumber??0),confirmLabel:s.taskDetail.verdictComplete})){w(!0);try{const g=await M.tasks.verdict(S.id,{action:"complete"});se(g),r({kind:"success",title:s.taskDetail.markCompleteToastTitle})}catch(g){r({kind:"error",title:s.taskDetail.markCompleteFailedTitle,...B(g)})}finally{w(!1)}}},Me=async()=>{if(S&&await a({title:s.taskDetail.continueConfirmTitle,body:s.taskDetail.continueConfirmBody(S.reviewRound+1),confirmLabel:s.taskDetail.verdictContinue})){j(!0);try{const g=await M.tasks.verdict(S.id,{action:"continue"});se(g),r({kind:"success",title:s.taskDetail.continuedToastTitle(g.reviewRound)})}catch(g){r({kind:"error",title:s.taskDetail.continueFailedTitle,...B(g)})}finally{j(!1)}}},Ee=async(g,F)=>{if(S){D(!0);try{const Y=await M.tasks.verdict(S.id,{action:g.verdict,...g.comments!==void 0?{comments:g.comments}:{}});se(Y),I(""),r({kind:"success",title:F.success})}catch(Y){r({kind:"error",title:F.failure,...B(Y)})}finally{D(!1)}}},$e=async()=>{S&&await a({title:s.taskDetail.specApproveConfirmTitle,body:s.taskDetail.specApproveConfirmBody(S.id),confirmLabel:s.taskDetail.specApprove})&&await Ee({verdict:"approve"},{success:s.taskDetail.specApprovedToastTitle,failure:s.taskDetail.specApproveFailedTitle})},Re=async()=>{const g=P.trim();g&&await Ee({verdict:"request-changes",comments:g},{success:s.taskDetail.specRejectedToastTitle,failure:s.taskDetail.specRejectFailedTitle})},Te=async g=>{if(!S)return;const F=E.trim();if(!(g==="request-changes"&&!F||!await a({title:g==="pass"?s.taskDetail.codePassConfirmTitle:s.taskDetail.codeRejectConfirmTitle,body:s.taskDetail.codeVerdictConfirmBody,confirmLabel:g==="pass"?s.taskDetail.codePass:s.taskDetail.codeRequestChanges}))){J(!0);try{const de=await M.tasks.verdict(S.id,{action:g,...F?{comments:F}:{}});se(de),W(""),r({kind:"success",title:s.taskDetail.codeVerdictSubmittedTitle})}catch(de){r({kind:"error",title:s.taskDetail.codeVerdictFailedTitle,...B(de)})}finally{J(!1)}}},it=()=>{var g;(g=document.getElementById("task-verdict-controls"))==null||g.scrollIntoView({behavior:"smooth",block:"center"})},ot=async()=>{if(!S||U)return;const g=S.prNumber??0,F=N==="auto"?s.taskDetail.confirmAutoMergeTitle(g):N==="manual"?s.taskDetail.confirmManualCompleteTitle:s.taskDetail.confirmResultTitle,Y=N==="auto"?s.taskDetail.confirmAutoMergeBody(g):N==="manual"?s.taskDetail.confirmManualCompleteBody(g):s.taskDetail.confirmResultBody;if(await a({title:F,body:Y,confirmLabel:$()})){w(!0);try{const de=await M.tasks.verdict(S.id,{action:"confirm-merge"});se(de),r({kind:"success",title:de.status==="merged"?s.taskDetail.confirmedMergedToastTitle:s.taskDetail.confirmedCompleteToastTitle})}catch(de){r({kind:"error",title:s.taskDetail.confirmFailedTitle,...B(de)})}finally{w(!1)}}};return t.jsxs("div",{children:[t.jsx("button",{type:"button",onClick:()=>n(-1),className:"btn-ghost mb-3",children:s.common.back}),L&&!S&&t.jsx("div",{className:"text-sm text-accent",children:s.common.loadFailed(L)}),z&&!S&&!L&&t.jsx("div",{className:"text-sm text-accent",children:s.taskDetail.taskNotFound(e)}),!S&&!L&&!z&&t.jsx("div",{className:"text-sm text-og-500",children:s.common.loading}),S&&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:S.id}),t.jsx("span",{className:"min-w-0 truncate font-display text-sm font-semibold tracking-tight text-og-1000",title:S.title,children:S.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:lt(S)}),t.jsx("aside",{className:"min-w-0 space-y-4",children:Oe(S)})]})]}),i&&S&&t.jsx(mn,{mode:"edit",open:!0,onClose:()=>l(!1),task:S,onUpdated:se}),d&&S&&t.jsx(Ce,{open:!0,title:s.taskDetail.reviewRecoveryTitle,onClose:()=>{p||x(!1)},size:"sm",dismissOnBackdrop:!p,footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",disabled:p,onClick:()=>x(!1),className:"btn-secondary",children:s.common.cancel}),t.jsx("button",{type:"submit",form:"review-recovery-form",disabled:p||S.prNumber===void 0&&Mn(T)===void 0,className:"btn-primary",children:p?s.taskDetail.advancing:s.taskDetail.reviewRecoverySubmit})]}),children:t.jsxs("form",{id:"review-recovery-form",className:"space-y-4",onSubmit:g=>{g.preventDefault();const F=S.prNumber??Mn(T);F===void 0||p||K(S,"qa",{stage:b,...S.prNumber===void 0?{prNumber:F}:{}})},children:[t.jsx("p",{className:"text-sm text-og-700",children:s.taskDetail.reviewRecoveryBody}),S.prNumber===void 0&&t.jsxs("div",{children:[t.jsx("label",{htmlFor:"review-recovery-pr-number",className:"mb-1 block text-sm text-og-700",children:s.taskDetail.reviewRecoveryPrNumberLabel}),t.jsx("input",{id:"review-recovery-pr-number",type:"number",min:1,step:1,value:T,required:!0,disabled:p,onChange:g=>R(g.target.value),placeholder:s.taskDetail.reviewRecoveryPrNumberPlaceholder,className:he})]}),t.jsxs("div",{children:[t.jsx("label",{htmlFor:"review-recovery-stage",className:"mb-1 block text-sm text-og-700",children:s.taskDetail.reviewRecoveryStageLabel}),t.jsxs("select",{id:"review-recovery-stage",value:b,required:!0,disabled:p||S.phase!==void 0,onChange:g=>y(g.target.value),className:he,children:[t.jsx("option",{value:"spec",children:s.taskDetail.reviewRecoveryStageSpec}),t.jsx("option",{value:"code",children:s.taskDetail.reviewRecoveryStageCode})]})]})]})})]});function lt(g){var mt;const F=g.preferredAgentId==="",Y=g.status==="approved"&&g.prNumber!==void 0,de=g.status==="merge-ready"&&g.prNumber!==void 0,ve=g.status==="spec-ready",Ae=pe,$t=g.status==="max_rounds"&&!Fe(g.phase),dt=g.status==="max_rounds"&&Fe(g.phase),De=Qn(g.prUrl),ut=Qa(De??void 0,g.branch??""),_e=g.attention?gs(s,g.attention,g.status):null,It=(q??[]).some(ht=>Gn(ht,g.id));return t.jsxs("div",{children:[L&&t.jsx("div",{className:"mb-4 text-sm text-accent",children:s.common.loadFailed(L)}),g.branchCleanupPending&&t.jsxs("div",{className:"mb-4 rounded-md border border-accent/25 bg-accent-soft/60 px-3 py-2.5 text-xs text-accent",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.branchCleanupPendingTitle}),t.jsx("div",{className:"mt-1 text-og-700",children:s.taskDetail.branchCleanupPendingBody}),t.jsx(kt,{children:g.branchCleanupPending.reason})]}),g.branchCleanupSkipped&&t.jsxs("div",{className:"mb-4 rounded-md border border-hairline bg-og-25 px-3 py-2.5 text-xs text-og-700",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.branchCleanupSkippedTitle}),t.jsx("div",{className:"mt-1",children:s.taskDetail.branchCleanupSkippedBody}),t.jsx(kt,{children:g.branchCleanupSkipped.reason})]}),F&&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:g.status==="pending"?s.taskDetail.unassignedPendingNotice:s.taskDetail.unassignedReadonlyNotice}),t.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-3",children:[t.jsx(dn,{task:g,className:"text-sm"}),It&&t.jsx("span",{className:"text-sm text-og-500",title:s.taskDetail.dispatchingHint,children:s.taskDetail.dispatching}),(g.specReviewRound??0)>0&&t.jsx("span",{className:"text-sm text-og-500",children:s.taskDetail.specReviewRound(g.specReviewRound??0)}),g.reviewRound>0&&t.jsx("span",{className:"text-sm text-og-500",children:s.taskDetail.codeReviewRound(g.reviewRound)})]}),t.jsx("div",{className:"mb-4 flex flex-wrap items-center gap-2",children:qs(g)}),t.jsxs("div",{className:"mb-4 text-sm text-og-500",children:[s.taskDetail.createdAtPrefix,_t(g.createdAt,!1),s.taskDetail.updatedAtPrefix,_t(g.updatedAt,!1),g.origin&&t.jsxs(t.Fragment,{children:[s.taskDetail.originPrefix,t.jsx(Ne,{to:Pe(g.projectId,g.origin.taskId),className:"underline hover:text-og-700",children:g.origin.taskId})]})]}),g.attention&&_e&&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:_e.title}),t.jsx("div",{className:"mt-1 text-og-700",children:_e.guidance}),t.jsx("div",{className:"mt-1 text-xs text-og-500",children:_t(g.attention.occurredAt)}),t.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:oe(g)}),t.jsx(kt,{open:_e.expandDetails,children:`${g.attention.reason}
15
+ ${g.attention.runbook}`})]}),Y&&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}),De&&t.jsx("a",{href:De,target:"_blank",rel:"noopener noreferrer",className:"btn-secondary mt-3",children:s.taskDetail.viewPr(g.prNumber??0)})]}),de&&t.jsxs("div",{id:"task-verdict-controls",className:"mb-4 rounded-lg border border-accent/25 bg-accent-soft p-4 text-sm text-accent",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.mergeReadyBannerTitle}),t.jsx("div",{className:"mt-1 text-og-700",children:N==="auto"?s.taskDetail.mergeReadyAutoBody(g.prNumber??0):N==="manual"?s.taskDetail.mergeReadyManualBody(g.prNumber??0):U?s.taskDetail.mergeReadyLoadingBody:s.taskDetail.mergeReadyUnknownBody}),N==="unknown"&&ge&&t.jsx(kt,{children:ge}),De&&t.jsx("a",{href:De,target:"_blank",rel:"noopener noreferrer",className:"btn-secondary mt-3",children:s.taskDetail.viewPr(g.prNumber??0)})]}),ve&&t.jsxs("div",{id:"task-verdict-controls",className:"mb-4 rounded-lg border border-accent-soft bg-accent-soft/40 p-4 text-sm text-accent",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.specReadyBannerTitle}),t.jsx("div",{className:"mt-1 text-og-700",children:s.taskDetail.specReadyNotice(g.specReviewRound??0)}),Qe()]}),Ae&&t.jsxs("div",{id:"task-verdict-controls",className:`mb-4 rounded-lg p-4 text-sm ${((mt=g.attention)==null?void 0:mt.reason)==="review-verdict-overdue"?"border border-accent/25 bg-accent-soft text-accent":"border border-hairline bg-og-25 text-og-800"}`,children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.codeVerdictTitle}),t.jsx("div",{className:"mt-1 text-og-700",children:s.taskDetail.codeVerdictBody}),ct()]}),$t&&t.jsxs("div",{id:"task-verdict-controls",className:"mb-4 rounded-lg border border-accent/25 bg-accent-soft/60 p-4 text-sm text-accent",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.codeMaxRoundsTitle(g.reviewRound)}),t.jsx("div",{className:"mt-1 text-og-700",children:s.taskDetail.codeMaxRoundsBody})]}),dt&&t.jsxs("div",{id:"task-verdict-controls",className:"mb-4 rounded-lg border border-accent/25 bg-accent-soft/60 p-4 text-sm text-accent",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.specMaxRoundsTitle(g.specReviewRound??0)}),t.jsx("div",{className:"mt-1 text-og-700",children:s.taskDetail.specMaxRoundsBody}),Qe()]}),t.jsxs("div",{className:"card mb-4 flex flex-wrap items-center gap-x-6 gap-y-1 p-4 text-sm",children:[t.jsxs("span",{className:"text-og-500",children:["PR:"," ",g.prNumber?De?t.jsxs("a",{href:De,target:"_blank",rel:"noopener noreferrer",className:"text-accent hover:text-accent-hover",children:["#",g.prNumber]}):t.jsxs("span",{className:"font-mono text-og-800",children:["#",g.prNumber]}):t.jsx("span",{className:"text-og-400",children:"—"})]}),t.jsxs("span",{className:"text-og-500",children:["Branch:"," ",g.branch?ut?t.jsx("a",{href:ut,target:"_blank",rel:"noopener noreferrer",className:"font-mono text-accent hover:text-accent-hover",children:g.branch}):t.jsx("span",{className:"font-mono text-og-800",children:g.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:g.description||t.jsx("span",{className:"text-og-400",children:s.taskDetail.noDescription})}),t.jsx(Ka,{task:g})]})}function Qe(){return t.jsxs("div",{className:"mt-3 flex flex-col gap-2",children:[t.jsx("textarea",{value:P,onChange:g=>I(g.target.value),placeholder:s.taskDetail.specCommentsPlaceholder,rows:3,disabled:v,className:he}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",disabled:v,onClick:$e,className:"btn-primary",children:v?s.taskDetail.submitting:s.taskDetail.specApproveButton}),t.jsx("button",{type:"button",disabled:v||P.trim()==="",onClick:Re,title:P.trim()===""?s.taskDetail.specRejectTitleEmpty:s.taskDetail.specRejectTitleReady,className:"btn-secondary",children:v?s.taskDetail.submitting:s.taskDetail.specReject})]})]})}function ct(){return t.jsxs("div",{className:"mt-3 flex flex-col gap-2",children:[t.jsx("textarea",{value:E,onChange:g=>W(g.target.value),placeholder:s.taskDetail.codeCommentsPlaceholder,rows:3,disabled:O,className:he}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",disabled:O,onClick:()=>void Te("pass"),className:"btn-secondary",children:O?s.taskDetail.submitting:s.taskDetail.codePass}),t.jsx("button",{type:"button",disabled:O||E.trim()==="",onClick:()=>void Te("request-changes"),className:"btn-secondary",children:O?s.taskDetail.submitting:s.taskDetail.codeRequestChanges})]})]})}function oe(g){return g.attention?cn(g.attention,g.status).map(F=>F==="advance"?t.jsx("button",{type:"button",disabled:p,onClick:()=>void ee(),className:"btn-primary",children:p?s.taskDetail.advancing:C(g)},F):F==="verdict"?t.jsx("button",{type:"button",onClick:it,className:"btn-primary",children:s.taskDetail.handleReview},F):F==="cancel"?t.jsx("button",{type:"button",disabled:c,onClick:Z,className:"btn-secondary",children:c?s.taskDetail.cancelling:s.taskDetail.cancelConfirmLabel},F):t.jsx("button",{type:"button",disabled:h,onClick:be,className:"btn-secondary",children:h?s.common.retrying:s.taskDetail.retryTask},F)):null}function Oe(g){if(ne===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 F=(G==null?void 0:G.agent.find(ve=>ve.some(Ae=>Ae.id===g.devAgentId)))??(g.qaAgentId?G==null?void 0:G.agent.find(ve=>ve.some(Ae=>Ae.id===g.qaAgentId)):void 0),Y=F==null?void 0:F.find(ve=>ve.role==="dev"&&ve.id===g.devAgentId),de=g.qaAgentId?F==null?void 0:F.find(ve=>ve.role==="qa"&&ve.id===g.qaAgentId):void 0;return!Y&&!de?t.jsx("div",{className:"rounded-lg border border-hairline bg-surface px-3 py-6 text-center text-sm text-og-400",children:s.taskDetail.noLinkedAgent}):t.jsxs(t.Fragment,{children:[Y?gn(g,Y):t.jsx(On,{role:"dev"}),de?gn(g,de):t.jsx(On,{role:"qa"})]})}function gn(g,F){const Y=_.get(F.id),de=Y??{id:F.id,projectId:g.projectId,runtimeStatus:"unknown",tmuxSessionStatus:"unknown",stale:!0};return t.jsx(bs,{agent:de,projectId:g.projectId,role:F.role,runtime:F.runtime,model:F.model,pendingRestart:ie&&!Y,terminalLoading:!ie&&!Y&&!me,showTaskBinding:!1,terminalMode:"embedded-full",active:xe===F.id,onActivate:()=>ye(F.id),task:g},F.id)}function qs(g){var ht,bn;const Y=g.status==="max_rounds"&&!Fe(g.phase),de=g.status==="merge-ready",ve=g.status==="pending",Ae=Va.has(g.status),$t=Ae&&!!g.preferredAgentId,dt=g.preferredAgentId==="",De=["pending","in_progress","fixing","review","approved"].includes(g.status)&&((ht=g.attention)==null?void 0:ht.reason)!=="bootstrap-marker-clear-failed"&&(((bn=g.attention)==null?void 0:bn.reason)!=="dispatch-failed:ack_unknown"||g.status==="review")&&!(g.status==="pending"&&dt),ut=(g.status==="in_progress"||g.status==="fixing")&&g.qaAgentId!==void 0,_e=Y&&g.prNumber!==void 0,It=_e&&!!g.agentId,mt=we&&!pe;return t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",disabled:!ve,onClick:()=>l(!0),className:"btn-secondary",children:s.taskDetail.editTask}),t.jsx("button",{type:"button",disabled:c,onClick:Z,title:s.taskDetail.cancelForceTitle,className:"btn-secondary",children:c?s.taskDetail.cancelling:s.taskDetail.cancelConfirmLabel}),Ae&&g.replacementTaskId===void 0&&t.jsx("button",{type:"button",disabled:!$t||h,onClick:be,title:dt?s.taskDetail.retryDisabledUnassignedTitle:s.taskDetail.retryEnabledTitle,className:"btn-secondary",children:h?s.common.retrying:s.taskDetail.retryTask}),De&&t.jsx("button",{type:"button",disabled:p,onClick:()=>void ee(),className:"btn-primary",children:p?s.taskDetail.advancing:C(g)}),ut&&t.jsx("button",{type:"button",disabled:p,onClick:()=>void ee("qa"),className:"btn-secondary",children:C(g,"qa")}),mt&&t.jsx("button",{type:"button",onClick:()=>te(!0),className:"btn-secondary",children:s.taskDetail.handleReview}),Y&&t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",disabled:!It||k,onClick:Me,title:s.taskDetail.continueButtonTitle,className:"btn-secondary",children:k?s.taskDetail.continuing:s.taskDetail.verdictContinue}),t.jsx("button",{type:"button",disabled:!_e||A,onClick:Ve,title:s.taskDetail.completeButtonTitle,className:"btn-primary",children:A?s.taskDetail.completing:s.taskDetail.verdictComplete})]}),de&&t.jsx("button",{type:"button",disabled:A||U,onClick:ot,title:U?s.taskDetail.confirmLoadingTitle:s.taskDetail.confirmButtonTitle,className:"btn-primary",children:A?s.taskDetail.confirming:$()})]})}}function On({role:e}){const n=H();return t.jsx("div",{className:"rounded-lg border border-hairline bg-surface px-3 py-6 text-center text-sm text-og-400",children:n.taskDetail.noAgentSlot(e)})}function Za(){const{agentId:e}=At(),{projects:n}=at(),s=H(),r=o.useMemo(()=>{if(e)for(const a of n??[])for(const i of a.agent){const l=i.find(c=>c.id===e);if(l)return{runtime:l.runtime,projectId:a.id}}},[e,n]);return e?t.jsxs("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden border border-hairline bg-surface",children:[t.jsxs("div",{className:"flex h-8 flex-none select-none items-center gap-3 border-b border-hairline bg-page px-3 font-mono text-xs text-og-500",children:[t.jsx("span",{"aria-hidden":!0,className:"block h-1.5 w-1.5 rounded-full bg-og-1000"}),t.jsx("span",{className:"text-og-700",title:Kn(e,r==null?void 0:r.runtime),children:e}),r&&t.jsx(Ne,{to:`/project/${encodeURIComponent(r.projectId)}`,className:"ml-auto text-accent",children:s.terminal.backToProject})]}),t.jsx("div",{className:"min-h-0 flex-1",children:t.jsx(Xe,{agentId:e,mode:"full",interactive:!0,arrowKeys:!0})})]}):t.jsx("div",{className:"text-sm text-accent",children:s.terminal.noAgent})}const ei=65536,ti=8e3,ni=["text-[18px] font-bold","text-[17px] font-bold","text-[16px] font-semibold","text-[15px] font-semibold","text-[15px] font-semibold","text-[15px] font-semibold"],si=/^(https?:\/\/|mailto:)/i,ri=/^https?:\/\//i;function ai(e){try{const n=new URL(e).hostname.toLowerCase();return n==="githubusercontent.com"||n.endsWith(".githubusercontent.com")}catch{return!1}}function ii({src:e,alt:n}){const s=H(),[r,a]=o.useState(!1);if(r||ai(e))return t.jsx("img",{src:e,alt:n,loading:"lazy",className:"max-w-full rounded border border-hairline"});let i=e;try{i=new URL(e).hostname}catch{i=e}return t.jsxs("button",{type:"button",onClick:()=>a(!0),className:"inline-flex max-w-full items-center gap-1.5 rounded border border-hairline bg-og-25 px-2 py-1 text-xs text-og-700",children:[t.jsx("span",{className:"shrink-0",children:s.review.loadExternalImage}),n&&t.jsx("span",{className:"min-w-0 truncate text-og-500",children:n}),t.jsx("span",{className:"min-w-0 truncate font-mono text-og-400",children:i})]})}function _n(e,n){let s=-1,r=-2;return a=>(r!==-2&&a>=s&&(r===-1||a<=r)||(s=a,r=e.indexOf(n,a)),r)}function oi(e){const n=/\s/g;let s=-1,r=-2;return a=>{if(r!==-2&&a>=s&&(r===-1||a<=r))return r;s=a,n.lastIndex=a;const i=n.exec(e);return r=i?i.index:-1,r}}function Hn(e,n,s){const r=n+1,a=s.bracket(r);if(a===-1||e[a+1]!=="(")return null;const i=a+2,l=s.paren(i);if(l===-1||l===i)return null;const c=s.whitespace(i);return c!==-1&&c<l?null:{label:e.slice(r,a),url:e.slice(i,l),end:l+1}}class Ms extends Error{}class li{constructor(n){ce(this,"count",0);this.max=n}charge(){if(++this.count>this.max)throw new Ms}}function Ue(e,n,s){const r=[];let a="",i=0;const l={bracket:_n(e,"]"),paren:_n(e,")"),whitespace:oi(e)},c=()=>{a!==""&&(n.charge(),r.push(a),a="")},m=f=>{c(),n.charge(),r.push(f)},h=()=>`${s}-${r.length}`;for(;i<e.length;){const f=e[i];if(f==="`"){const p=e.indexOf("`",i+1);if(p!==-1){const u=e.slice(i+1,p);c(),n.charge(),n.charge(),r.push(t.jsx("code",{className:"rounded bg-og-25 px-1 font-mono text-xs",children:u},h())),i=p+1;continue}}else if(f==="!"&&e[i+1]==="["){const p=Hn(e,i+1,l);if(p){ri.test(p.url)?m(t.jsx(ii,{src:p.url,alt:p.label},h())):a+=e.slice(i,p.end),i=p.end;continue}}else if(f==="["){const p=Hn(e,i,l);if(p){if(si.test(p.url)){c(),n.charge();const u=Ue(p.label,n,`${s}-a${r.length}`);r.push(t.jsx("a",{href:p.url,target:"_blank",rel:"noopener noreferrer",className:"text-accent hover:text-accent-hover",children:u},h()))}else a+=e.slice(i,p.end);i=p.end;continue}}else if(f==="*"){if(e.startsWith("***",i)){const u=e.indexOf("***",i+3);if(u>i+3){c(),n.charge(),n.charge();const d=Ue(e.slice(i+3,u),n,`${s}-bi${r.length}`);r.push(t.jsx("strong",{children:t.jsx("em",{children:d})},h())),i=u+3;continue}}if(e.startsWith("**",i)){const u=e.indexOf("**",i+2);if(u>i+2){c(),n.charge();const d=Ue(e.slice(i+2,u),n,`${s}-b${r.length}`);r.push(t.jsx("strong",{children:d},h())),i=u+2;continue}}const p=e.indexOf("*",i+1);if(p>i+1){c(),n.charge();const u=Ue(e.slice(i+1,p),n,`${s}-i${r.length}`);r.push(t.jsx("em",{children:u},h())),i=p+1;continue}}a+=f,i++}return c(),r}function ci(e,n){const s=[],r=e.split(`
16
+ `);let a=[];const i=()=>{if(a.length===0)return;const l=a;a=[],n.charge();const c=[];l.forEach((m,h)=>{h>0&&(n.charge(),c.push(t.jsx("br",{},`br-${s.length}-${h}`))),c.push(...Ue(m,n,`p${s.length}-l${h}`))}),s.push(t.jsx("p",{children:c},`p-${s.length}`))};for(let l=0;l<r.length;l++){const c=r[l];if(c.startsWith("```")){i();const h=[];let f=l+1;for(;f<r.length&&!/^```\s*$/.test(r[f]);)h.push(r[f]),f++;n.charge(),n.charge(),n.charge(),s.push(t.jsx("pre",{className:"overflow-x-auto rounded bg-og-25 p-2 font-mono text-xs",children:t.jsx("code",{children:h.join(`
17
+ `)})},`pre-${s.length}`)),l=f;continue}const m=/^(#{1,6}) (.*)$/.exec(c);if(m){i(),n.charge();const h=m[1].length,f=`h${h}`;s.push(t.jsx(f,{className:ni[h-1],children:Ue(c,n,`h${s.length}`)},`h-${s.length}`));continue}if(c.trim()===""){i();continue}a.push(c)}return i(),s}function di(e){if(typeof e!="string")return[];if(e.length>ei)return null;const n=new li(ti);try{return n.charge(),ci(e.replace(/\r\n/g,`
18
+ `),n)}catch(s){if(s instanceof Ms)return null;throw s}}function ui({text:e}){const n=o.useMemo(()=>di(e),[e]);return n===null?t.jsx("pre",{className:"whitespace-pre-wrap break-words",children:e}):t.jsx("div",{className:"space-y-2 break-words",children:n})}const mi={approve:"approve","request-changes":"request-changes",comment:"comment"};function hi(e){return e==="no-pr"||e==="driver-unavailable"?e:void 0}function fi(e){return{"no-pr":e.prReview.reasonNoPr,"driver-unavailable":e.prReview.reasonDriverUnavailable}}function Os(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 pi(){const e=H(),{taskId:n=""}=At(),s=Le(),{hash:r}=Un(),{data:a}=Ns(n),i=a?Is(a):void 0,{data:l,loaded:c,error:m,refresh:h,refreshing:f,refreshError:p}=Bs(n,i),[u,d]=o.useState(null),x=(l==null?void 0:l.prNumber)??(a==null?void 0:a.prNumber),b=(l==null?void 0:l.prUrl)??(a==null?void 0:a.prUrl),y=Qn(b),T=l?Es(l.items):[],R=c&&!m&&(l==null?void 0:l.available)===!0&&l.items.length>0,A=Fe(a==null?void 0:a.phase)?e.prReview.specReviewHeading:e.prReview.codeReviewHeading,w=o.useRef(null),k=o.useRef(void 0);return o.useEffect(()=>()=>clearTimeout(k.current),[]),o.useEffect(()=>{let j=null;if(r)try{j=decodeURIComponent(r.slice(1))}catch{j=null}if(!j){w.current=null,d(null);return}if(w.current===j||!R||!l)return;const v=document.getElementById(j);v&&(w.current=j,v.scrollIntoView({behavior:"smooth",block:"center"}),d(j),clearTimeout(k.current),k.current=setTimeout(()=>d(null),2e3))},[R,l,r]),t.jsxs("div",{className:"mx-auto w-full max-w-5xl",children:[t.jsx("button",{type:"button",onClick:()=>s(-1),className:"btn-ghost mb-3",children:e.common.back}),t.jsxs("div",{className:"mb-1 flex flex-wrap items-baseline gap-2",children:[t.jsx("span",{className:"font-mono text-og-400",children:n}),t.jsx("span",{className:"text-sm font-semibold text-og-1000",children:(a==null?void 0:a.title)??""})]}),t.jsxs("div",{className:"mb-4 flex flex-wrap items-center gap-2 text-xs text-og-500",children:[t.jsx("span",{className:"pill",children:A}),y&&x!==void 0&&t.jsx("a",{href:y,target:"_blank",rel:"noopener noreferrer",className:"text-accent hover:text-accent-hover",children:e.taskDetail.viewPr(x)}),(l==null?void 0:l.available)&&t.jsx(Fs,{data:l,onRefresh:h,refreshing:f,refreshError:p})]}),!c&&t.jsx("div",{className:"text-sm text-og-500",children:e.common.loading}),c&&m&&t.jsx("div",{className:"text-sm text-accent",children:e.review.loadFailed(m)}),c&&!m&&l&&!l.available&&t.jsx("div",{className:"text-sm text-og-500",children:fi(e)[hi(l.reason)??"no-pr"]}),c&&!m&&(l==null?void 0:l.available)&&(l.items.length===0?l.truncated?t.jsx("div",{className:"text-sm text-accent",children:e.prReview.listTruncated}):l.error?t.jsx("div",{className:"text-sm text-accent",children:e.prReview.fetchFailed(l.error)}):t.jsx("div",{className:"text-sm text-og-400",children:e.review.notStarted}):t.jsxs(t.Fragment,{children:[l.error&&t.jsx("div",{className:"mb-3 text-xs text-accent",children:e.prReview.partialFetchFailed(l.error)}),l.truncated&&t.jsx("div",{className:"mb-3 text-xs text-accent",children:e.prReview.listTruncated}),t.jsx("div",{className:"space-y-5",children:T.map((j,v)=>t.jsx(gi,{round:j,index:v,flashId:u},$s(j,String(v))))})]}))]})}function gi({round:e,index:n,flashId:s}){const r=H(),a=e.review?r.agents.round(n+1):r.status.in_progress;return t.jsxs("div",{children:[t.jsx("div",{className:"mb-1.5 text-xs font-medium text-og-700",children:a}),t.jsxs("div",{className:"space-y-2",children:[e.items.map((i,l)=>i.kind==="review"?t.jsx(qn,{item:i,flashId:s},nt(i,`${n}-${l}`)):t.jsx(xi,{item:i,flashId:s},nt(i,`${n}-${l}`))),e.review&&t.jsx(qn,{item:e.review,flashId:s})]})]})}function _s(e,n){const s=Et(e);return`card p-3 text-sm${s&&s===n?" ring-2 ring-accent":""}`}function xi({item:e,flashId:n}){const s=H(),r=e.kind==="review-comment";return t.jsxs("div",{id:Et(e),className:_s(e,n),children:[t.jsxs("div",{className:"mb-1 flex flex-wrap items-center gap-2",children:[t.jsx("span",{className:"pill shrink-0",children:r?s.prReview.inlineComment:s.prReview.comment}),e.author?t.jsx("span",{className:"font-medium text-og-700",children:e.author}):t.jsx("span",{className:"text-xs italic text-og-400",children:s.prReview.ghostAuthor}),r&&e.path&&t.jsx("span",{className:"min-w-0 break-all font-mono text-xs text-og-500",children:e.line!==void 0?`${e.path}:${e.line}`:e.path}),e.inReplyTo&&t.jsx("span",{className:"text-xs text-og-400",children:s.prReview.replyIndicator}),e.createdAt&&t.jsx("span",{className:"text-xs text-og-400",children:Os(e.createdAt)})]}),t.jsx(Hs,{item:e})]})}function qn({item:e,flashId:n}){const s=H(),r=e.verdict??"comment";return t.jsxs("div",{id:Et(e),className:_s(e,n),children:[t.jsxs("div",{className:"mb-1 flex flex-wrap items-center gap-2",children:[t.jsx("span",{className:"shrink-0 min-w-[1.75rem] text-xs font-semibold tracking-wide text-og-600",children:s.review.roleQa}),t.jsx("span",{className:Ls[r],children:mi[r]}),e.reviewState&&t.jsx("span",{className:"pill shrink-0",children:e.reviewState}),e.author?t.jsx("span",{className:"text-xs text-og-400",children:e.author}):t.jsx("span",{className:"text-xs italic text-og-400",children:s.prReview.ghostAuthor}),e.commitSha&&t.jsx("span",{className:"font-mono text-xs text-og-500",children:e.commitSha.slice(0,9)}),!e.commitSha&&e.anchorSha&&t.jsx("span",{className:"font-mono text-xs text-og-500",children:e.anchorSha.slice(0,9)}),e.createdAt&&t.jsx("span",{className:"text-xs text-og-400",children:Os(e.createdAt)})]}),t.jsx(Hs,{item:e,placeholder:s.prReview.noReviewBody})]})}function Hs({item:e,placeholder:n}){const s=H();return t.jsxs(t.Fragment,{children:[e.body?t.jsx("div",{className:"text-og-800",children:t.jsx(ui,{text:e.body})}):n?t.jsx("div",{className:"text-og-400",children:n}):null,e.bodyTruncated&&t.jsx("div",{className:"mt-1 text-xs text-accent",children:s.prReview.bodyTruncated})]})}function bi(){const e=H(),[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 vi(){const[e,n]=o.useState(null),[s,r]=o.useState(!1),[a,i]=o.useState(null);return o.useEffect(()=>rt().subscribe("pollers",c=>{i(null),n(c),r(!0)},c=>i(c)),[]),{data:e,loaded:s,error:a}}function yi(e){return e.lastErrorClass==="RATE_LIMIT"&&e.rateLimitedUntil!==void 0&&Date.parse(e.rateLimitedUntil)>Date.now()}function wi(e){const n=e.find(l=>l.lastErrorClass==="ACCESS_DENIED");if(n)return{poller:n,kind:"access-denied"};const s=e.find(l=>l.health==="failed"&&l.lastErrorClass==="NOT_FOUND");if(s)return{poller:s,kind:"not-found"};const r=e.find(l=>l.health==="failed");if(r)return{poller:r,kind:"failed"};const a=e.find(yi);if(a)return{poller:a,kind:"rate-limited"};const i=e.find(l=>l.health==="degraded");return i?{poller:i,kind:"degraded"}:null}function ki(){const e=H(),{data:n}=vi();if(!n)return null;const s=wi(n);if(!s)return null;const{poller:r,kind:a}=s,i=a==="access-denied"?e.banner.platformAccessDenied(r.repo,r.lastErrorMessage):a==="not-found"?e.banner.platformRepoNotFound(r.repo):a==="failed"?e.banner.platformUnreachable(r.repo):a==="rate-limited"?e.banner.platformRateLimited(r.repo,r.rateLimitedUntil):e.banner.platformDegraded(r.repo);return t.jsx("div",{className:"border-b border-accent/25 bg-accent-soft/60 px-4 py-2 text-sm text-accent",title:r.lastErrorMessage??"",children:i})}function ji(){const e=H(),{phase:n,count:s,error:r,triggerRestart:a}=Lt();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 Kt(e,n){const s=e.trim().replace(/\s+/g," ");return s.length>n?`${s.slice(0,n-1)}…`:s}function Si(e,n){return e?e.repo?`${e.id} · ${e.repo}`:e.id:n}function Ni(e){return e.title?`${e.id} · ${e.title}`:e.id}function Ci(e){return Ti.has(e)}function Ri(e,n,s){const r=fn();if(!(!r||r.permission!=="granted"))try{const a=ns(),i=new r(a.notification.taskDone(Kt(e.title||e.id,80)),{body:[a.notification.bodyProject(Kt(n,120)),a.notification.bodyTask(Kt(Ni(e),120)),a.notification.bodyStatus(Kr(e.status))].join(`
19
+ `),icon:"/baxian-logo.png",tag:`baxian-task-${e.id}`});i.onclick=()=>{window.focus(),s(),i.close()}}catch(a){console.warn("[task-notifications] failed to show notification:",a)}}function Ai(e,n,s){const r=o.useRef(new Map),a=o.useRef(new Set),i=o.useRef(new Map),l=o.useRef(new Set),c=o.useRef(new Set),m=o.useRef(new Map),h=o.useRef(n),f=o.useRef(new Map),p=o.useMemo(()=>s?(e??[]).map(u=>u.id).sort().join("\0"):"",[s,e]);o.useEffect(()=>{h.current=n},[n]),o.useEffect(()=>{f.current=new Map((e??[]).map(u=>[u.id,Si(u,u.id)]))},[e]),o.useEffect(()=>{const u=y=>{m.current.set(y,(m.current.get(y)??0)+1)};if(p===""){for(const y of c.current)u(y);c.current=new Set,r.current.clear(),i.current.clear(),l.current.clear();return}const d=p.split("\0"),x=new Set(d);for(const y of c.current)x.has(y)||u(y);c.current=x;for(const y of r.current.keys())x.has(y)||r.current.delete(y);for(const y of i.current.keys())x.has(y)||i.current.delete(y);const b=d.map(y=>rt().subscribe(`project-tasks:${y}`,T=>{const R=r.current.get(y),A=new Map(T.map(k=>[k.id,k]));r.current.set(y,A);const w=i.current.get(y)??new Set;if(i.current.set(y,w),!R){for(const k of A.keys())w.delete(k);return}for(const[k]of R)A.has(k)||a.current.has(k)||w.add(k);for(const k of[...w]){if(A.has(k)){w.delete(k);continue}const j=m.current.get(y)??0,v=`${y}:${j}:${k}`;l.current.has(v)||(l.current.add(v),M.tasks.get(k).then(D=>{if((m.current.get(y)??0)!==j)return;if(!D||D.projectId!==y||!Ci(D.status)){w.delete(k);return}w.delete(k),a.current.add(D.id);const P=f.current.get(y)??y;Ri(D,P,()=>h.current(D))}).catch(D=>{console.warn(`[task-notifications] failed to confirm completed task ${k}:`,D)}).finally(()=>{l.current.delete(v)}))}},T=>{console.warn(`[task-notifications] project task stream failed for ${y}:`,T)}));return()=>{for(const y of b)y()}},[p])}function Di(){const e=Un(),n=Le(),{projects:s}=at(),{enabled:r}=js(),a=!e.pathname.startsWith("/terminal/");return mr(),Ai(s,i=>n(Pe(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(Ne,{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:Ts,className:"ml-auto flex min-w-0 items-center justify-end gap-2"})]}),t.jsx(ji,{}),t.jsx(ki,{}),t.jsxs("main",{className:"flex min-h-0 flex-1 flex-col overflow-y-auto px-3 py-6 sm:px-6",children:[t.jsxs(Xs,{children:[t.jsx(Ye,{path:"/",element:t.jsx(ja,{})}),t.jsx(Ye,{path:"/project/:id",element:t.jsx(Ea,{})}),t.jsx(Ye,{path:"/project/:id/task/:taskId",element:t.jsx(Ja,{})}),t.jsx(Ye,{path:"/terminal/:agentId",element:t.jsx(Za,{})}),t.jsx(Ye,{path:"/tasks/:taskId/pr-review",element:t.jsx(pi,{})})]}),a&&t.jsx("footer",{className:"mt-auto flex justify-center pb-4 pt-24",children:t.jsx(bi,{})})]})]})}function Pi(){return t.jsx(Js,{children:t.jsx(fa,{children:t.jsx(Di,{})})})}function Li({children:e}){const n=H(),[s,r]=o.useState({kind:"probing"}),a=o.useRef(s);o.useEffect(()=>{a.current=s},[s]);const i=o.useCallback(async()=>{r({kind:"probing"});try{const c=await M.config.get();Qt(c.language),r({kind:"authorized"})}catch(c){if(c instanceof ze&&c.status===401){r({kind:"unauthorized"});return}r({kind:"error",message:c instanceof Error?c.message:void 0,fallback:"connectFallback"})}},[]);if(o.useEffect(()=>{i()},[i]),o.useEffect(()=>{const c=()=>{a.current.kind!=="probing"&&r({kind:"unauthorized",reason:"expired"})};return window.addEventListener(et,c),()=>window.removeEventListener(et,c)},[]),s.kind==="authorized")return t.jsx(t.Fragment,{children:e});if(s.kind==="error")return t.jsxs(en,{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(en,{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(Ei,{message:l,onSubmit:async c=>{er(c);try{const m=await M.config.get();Qt(m.language),r({kind:"authorized"})}catch(m){if(tr(),m instanceof ze&&m.status===401){r({kind:"unauthorized",reason:"invalid"});return}r({kind:"error",message:m instanceof Error?m.message:void 0,fallback:"loginFailed"})}}})}function en({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 Ei({message:e,onSubmit:n}){const s=H(),[r,a]=o.useState(""),[i,l]=o.useState(!1),[c,m]=o.useState(void 0),h=async p=>{p.preventDefault();const u=r.trim();if(!u){m(s.auth.tokenRequired);return}m(void 0),l(!0);try{await n(u)}finally{l(!1)}},f=c??e;return t.jsxs(en,{title:s.auth.loginTitle,children:[t.jsx("p",{className:"mb-4 text-sm text-og-600",children:s.auth.loginDescription}),t.jsxs("form",{onSubmit:p=>{h(p)},children:[t.jsx("label",{className:ue,htmlFor:"baxian-token",children:s.auth.tokenLabel}),t.jsx("input",{id:"baxian-token",type:"password",autoComplete:"current-password",autoFocus:!0,value:r,onChange:p=>a(p.target.value),className:`${he} font-mono`,placeholder:s.auth.tokenPlaceholder,disabled:i}),f&&t.jsx("p",{role:"alert",className:"mt-2 text-xs text-accent",children:f}),t.jsx("button",{type:"submit",disabled:i,className:"btn-primary mt-4 w-full",children:i?s.auth.submitting:s.auth.submit})]})]})}zs.createRoot(document.getElementById("root")).render(t.jsx(o.StrictMode,{children:t.jsx(ur,{children:t.jsx(jr,{children:t.jsx(gr,{children:t.jsx(br,{children:t.jsx(Li,{children:t.jsx(Pi,{})})})})})})}));