baxian 2.0.28 → 2.0.29

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.
@@ -7,10 +7,10 @@ ${r.map(a=>`${a.path}: ${a.message}`).join(`
7
7
  /Users/me/extra-repo`,addDirsHint:"透传到 --add-dir,让 CLI 把额外目录纳入工作根;非 YOLO 模式下同时扩大权限放行范围。",yoloTitle:"YOLO 模式(推荐开启)",yoloBodyLead:"开启后所选运行时以 ",yoloBodyTrail:" 启动。取消勾选则以运行时默认权限模式启动,权限请求会在终端挂起等待人工确认(agent 状态显示为等待输入)。",addedToastTitle:(e,n,s)=>`Agent Team ${e} + ${n} 已添加到 ${s}`},createTask:{titleCreate:"新建任务",titleEdit:"编辑任务",selectProjectPlaceholder:"选择项目",targetAgentLabel:"目标 Agent",notAssignedOption:"暂不指定",pendingRestartSuffix:"(待重启)",notInRuntimeSuffix:"(不在 runtime)",titlePlaceholder:"一句话描述要做什么",descriptionLabel:"Description(可选)",descriptionPlaceholder:"详细描述任务,支持 markdown;简单任务可不填",imagesLabel:"图片(可选)",addImagesButton:"添加图片",removeImageAriaLabel:e=>`移除图片 ${e}`,draftRestoredNotice:"已恢复上次未提交的草稿",discardDraftButton:"丢弃",updatedToastTitle:"任务已更新",createdToastTitle:"任务已创建",imageTooLargeToastTitle:"图片过大",imageTooLargeToastBody:(e,n)=>`${e} 超过 ${n} MiB`,tooManyImagesToastTitle:e=>`最多 ${e} 张图片`,noDevPendingRestartHint:e=>`当前 Dev agent "${e}" 在 baxian.json 中存在但 runtime 未加载,可能是手动编辑过配置文件;重启 server 可拉起`,noDevNotInRuntimeHint:e=>`当前 Dev agent "${e}" 不在 runtime(可能已从 project 配置移除);保存可能失败,请确认或选择新 Dev agent`,noDevGlobalPendingRestartHint:"baxian.json 里有 Dev agent 但 runtime 未加载(可能是手动编辑过配置);重启 server 后生效"},hostMgmt:{title:"Host 管理",emptyState:"还没有配置 Host。点击下方「添加 Host」。",addHostButton:"+ 添加 Host",passwordSavedIndicator:" · 密码已保存",addressLabel:"Host 地址",portLabel:"端口(可选)",portRangeError:"端口需为 1–65535 的整数",aliasLabel:"别名(可选)",userLabel:"用户名(可选)",userPlaceholder:"留空则读 ~/.ssh/config 的 User",passwordLabel:"密码(可选)",passwordPlaceholderSet:"已设置,留空保持不变",passwordPlaceholderUnset:"留空使用 key 认证",clearPasswordLabel:"清除已保存的密码(改用 key 登录)",passwordHintLead:"建议为该 Host 配置好",passwordHintStrong:"免密码登入(SSH key)。",plaintextWarningLead:"否则填写的密码将以",plaintextWarningStrong:"明文",plaintextWarningTrail:"保存到 baxian.json 中。",testConnection:"测试连接",testing:"测试中…",createdToastTitle:e=>`Host ${e} 已添加`,updatedToastTitle:e=>`Host ${e} 已更新`,deletedToastTitle:e=>`Host ${e} 已删除`},projectPage:{newTaskButton:"+ 新建任务",menuAriaLabel:e=>`项目 ${e} 操作菜单`,showTaskPanel:"显示任务面板",addAgent:"添加 Agent Team",deleteAgentsFirstHint:e=>`请先删除项目下的 ${e} 个 Agent`,deleteProjectMenuItem:"删除项目…",noAgentsYet:"还没有 Agent Team,点击右上角菜单添加。",closeTaskPanel:"关闭任务面板",deleteModalTitle:"删除项目",confirmDeleteButton:"确认删除",deleteBodyLead:"将从 ",deleteBodyMid:" 中移除项目 ",deleteBodySuffix:"。此操作不可撤销,且不会删除 Git 仓库本身。",confirmInputLead:"如需确认,请在下方输入项目 ID ",confirmInputSuffix:":",confirmInputAriaLabel:"输入项目 ID 以确认删除",deletedToastTitle:e=>`项目 ${e} 已删除`},taskDetail:{cancelConfirmTitle:e=>`取消任务 ${e}?`,cancelConfirmLabel:"取消任务",cancelledToastTitle:"任务已取消",cancelFailedTitle:"未能取消任务",cancelForceTitle:"停止任务并释放关联的开发与评审 Agent",cancelConfirmBodyActive:"当前处理会停止,已分配的 Agent 会被释放。如果已经发布 PR,baxian 还会关闭 PR 并清理任务分支。之后如仍需处理,可以重新执行该任务。",cancelConfirmBodyTerminal:"任务已经结束,状态不会改变。baxian 只会释放仍与该任务关联的 Agent。",cancelCleanupToastTitle:"已释放残留的 Agent 关联",retryTask:"重新执行任务",retryConfirmTitle:e=>`重新执行任务 ${e}?`,retryConfirmBodyMerged:"PR 已经合并。baxian 会用相同标题和描述新建任务,并从头开始处理。",retryConfirmBodyDefault:"baxian 会新建任务并从头开始处理;当前任务仍保留在历史记录中。",retryCreatedToastTitle:e=>`已新建任务 ${e}`,retryFailedTitle:"未能启动新任务",markCompleteConfirmTitle:"接受当前版本并合并?",markCompleteConfirmBody:e=>`PR #${e} 会按当前内容直接合并,任务随后结束;尚未解决的评审意见不会在本任务中继续修改。`,completing:"收尾中…",markCompleteToastTitle:"已接受当前版本,正在合并 PR",markCompleteFailedTitle:"未能接受并合并当前版本",branchCleanupPendingTitle:"本地任务分支暂时保留",branchCleanupPendingBody:"baxian 暂时无法安全删除本地任务分支,因此保留了分支,避免丢失改动。",branchCleanupSkippedTitle:"本地任务分支已保留",branchCleanupSkippedBody:"baxian 有意保留了本地任务分支,你可以稍后检查或手动删除。",continueConfirmTitle:"继续修改?",continueConfirmBody:e=>`开发 Agent 将开始第 ${e} 轮修改;改动完成后会重新开始代码评审。`,continuing:"正在开始修改…",continuedToastTitle:e=>`已开始第 ${e} 轮修改`,continueFailedTitle:"未能开始新一轮修改",specApproveConfirmTitle:"批准方案并开始开发?",specApproveConfirmBody:e=>`任务 ${e} 将按当前方案开始开发。`,specApprove:"批准方案",specApprovedToastTitle:"方案已批准,开发已开始",specApproveFailedTitle:"未能批准方案",specRejectedToastTitle:"修改要求已发送,开发 Agent 正在修改方案",specRejectFailedTitle:"未能提交方案修改要求",confirmAndMerge:"确认并合并",confirmComplete:"确认完成",confirmResult:"确认结果",confirmAutoMergeTitle:e=>`确认并合并 PR #${e}?`,confirmAutoMergeBody:e=>`baxian 会合并 PR #${e}、结束任务并释放关联 Agent。`,confirmManualCompleteTitle:"确认当前结果已完成?",confirmManualCompleteBody:e=>`baxian 会结束任务并释放关联 Agent;PR #${e} 仍需你在代码平台手动合并。`,confirmResultTitle:"确认当前结果?",confirmResultBody:"项目合并设置暂不可用。确认后可能会立即合并 PR、结束任务并释放关联 Agent;继续前请先检查 PR。",confirmedMergedToastTitle:"PR 已合并,任务已完成",confirmedCompleteToastTitle:"任务已确认完成",confirmFailedTitle:"未能确认结果",taskNotFound:e=>`任务不存在:${e}`,unassignedPendingNotice:"请通过「编辑任务」选择开发 Agent,或从空闲的开发 Agent 卡片开始此任务。",unassignedReadonlyNotice:"任务没有分配开发 Agent,目前只能查看。",specReviewRound:e=>`方案评审 · 第 ${e} 轮`,codeReviewRound:e=>`代码评审 · 第 ${e} 轮`,dispatching:"正在派发给 Agent…",dispatchingHint:"baxian 正在准备工作区、切换分支并注入提示词,这一步通常需要十几秒。",createdAtPrefix:"创建于 ",updatedAtPrefix:" · 更新于 ",originPrefix:" · 来自 ",editTask:"编辑任务",startTask:"开始任务",startReview:"开始评审",restartReview:"重新发起评审",retryCurrentStep:"重试当前步骤",retryPreMergeCheck:"重试合并前检查",advancing:"正在开始…",advanceSucceededTitle:"当前步骤已开始",advanceFailedTitle:"未能开始当前步骤",advanceConfirmTitle:e=>`${e}?`,startTaskConfirmBody:(e,n)=>`任务 ${e} 将交给开发 Agent ${n} 开始处理。`,startReviewConfirmBody:e=>`任务 ${e} 的当前结果将交给评审 Agent,已有改动会保留。`,restartReviewConfirmBody:e=>`任务 ${e} 的当前评审会重新交给评审 Agent,已有评审记录会保留。`,retryCurrentStepConfirmBody:e=>`任务 ${e} 的当前步骤会重新交给开发 Agent,已有改动和评审记录会保留。`,retryPreMergeConfirmBody:"开发 Agent 会重新执行合并前检查;继续前,系统会再次确认已通过的评审结果仍然有效。",advanceRevokedConfirmTitle:"重新检查 PR 并继续收尾?",advanceRevokedRequestChangesBody:"评审通过后出现了新反馈。只有评审结果仍然有效、且没有未处理反馈时,baxian 才会继续。",advanceRevokedRetryLimitBody:"合并前检查多次尝试后仍未完成。baxian 会先检查 PR 和未处理反馈,再重新尝试。",handleReview:"处理评审",verdictContinue:"继续修改",verdictComplete:"接受当前版本并合并",codeVerdictTitle:"代码评审需要你决定",codeVerdictBody:"自动评审暂未给出可用结果。请先查看 PR,再确认通过或填写修改要求。",codeCommentsPlaceholder:"需要修改什么?要求修改时必填,确认通过时可选",codePass:"确认通过",codeRequestChanges:"要求修改",codePassConfirmTitle:"确认代码评审通过?",codeRejectConfirmTitle:"发送这些修改要求?",codeVerdictConfirmBody:"你的决定会记录到 PR,任务随后继续。",codeVerdictSubmittedTitle:"评审决定已保存到 PR",codeVerdictFailedTitle:"未能保存评审决定",approvedBannerTitle:"代码评审已通过 · 正在做最终检查",approvedBannerBody:"开发 Agent 正在确认所有评审意见都已处理。检查完成后,任务会等待你确认结果。",viewPr:e=>`查看 PR #${e}`,mergeReadyBannerTitle:"评审已完成 · 等待你确认结果",mergeReadyAutoBody:e=>`所有评审意见都已处理。请检查 PR #${e};确认后,baxian 会合并 PR 并结束任务。`,mergeReadyManualBody:e=>`所有评审意见都已处理。确认后任务会结束;PR #${e} 仍需你在代码平台手动合并。`,mergeReadyLoadingBody:"正在加载项目合并设置,加载完成后才能确认结果。",mergeReadyUnknownBody:"项目合并设置暂不可用。确认后可能会立即合并 PR;继续前请先检查 PR。",specReadyBannerTitle:"方案已就绪,等待你确认",specReadyNotice:e=>`评审 Agent 已通过第 ${e} 轮方案。请查看下方方案和评审记录;批准后开始开发,要求修改后会按你的意见重新调整。`,specCommentsPlaceholder:"需要修改什么?要求修改时必填",submitting:"提交中…",specApproveButton:"批准方案并开始开发",specRejectTitleEmpty:"请先填写需要修改的内容",specRejectTitleReady:"开发 Agent 会根据这些意见修改方案",specReject:"要求修改方案",codeMaxRoundsTitle:e=>`代码评审经过 ${e} 轮仍有待确认问题`,codeMaxRoundsBody:"选择「继续修改」处理剩余问题,或选择「接受当前版本并合并」按现状合并 PR。超出原任务范围的工作建议另建任务。",specMaxRoundsTitle:e=>`方案评审经过 ${e} 轮仍有待确认问题`,specMaxRoundsBody:"请查看下方讨论,然后批准当前方案,或说明还需要修改什么。你也可以取消任务,或从头重新执行。",noDescription:"(无描述)",noLinkedAgent:"暂无关联 Agent",cancelling:"取消中…",retryDisabledUnassignedTitle:"重新执行前,请先选择开发 Agent",retryEnabledTitle:"使用相同内容新建任务并从头开始处理",reviewRecoveryTitle:"恢复 PR 评审",reviewRecoveryBody:"仅在开发 Agent 已经发布 PR、但任务没有进入评审时使用。补充下面的 PR 信息后即可开始评审。",reviewRecoveryPrNumberLabel:"PR 号(必填)",reviewRecoveryPrNumberPlaceholder:"例如 601",reviewRecoveryStageLabel:"PR 内容(必填)",reviewRecoveryStageSpec:"方案",reviewRecoveryStageCode:"代码",reviewRecoverySubmit:"保存并开始评审",continueButtonTitle:"开始新一轮修改,完成后重新评审",completeButtonTitle:"不再修改,接受当前版本并合并 PR",confirmButtonTitle:"确认结果前请先检查 PR",confirmLoadingTitle:"请等待项目合并设置加载完成",loadingMergeSetting:"正在加载合并设置…",confirming:"确认中…",actionFailedBody:"请刷新页面确认任务当前状态,再决定是否重试。",attentionReviewTitle:"评审需要你处理",attentionMergeTitle:"最终检查未能完成",attentionAgentTitle:"关联 Agent 的处理已中断",attentionHandoffTitle:"下一步骤未能开始",attentionDefaultTitle:"任务需要你处理",attentionVerdictGuidance:"请查看 PR 和下方评审记录,然后确认结果或提出修改要求。",attentionAdvanceGuidance:"请确认关联 Agent 和代码平台可用,然后重试当前步骤。",attentionRetryGuidance:"本次任务已经无法继续;准备好后,可以从头重新执行。",attentionCancelGuidance:"请先检查任务详情;如果不再需要继续,可以取消任务。",noAgentSlot:e=>e==="dev"?"暂无开发 Agent":"暂无评审 Agent"},taskPanel:{ariaLabel:"任务面板",inProgressTitle:"处理中",pendingTitle:"待开始",doneTitle:"已结束",round:e=>`第 ${e} 轮`,emptyInProgress:"暂无正在处理的任务",emptyPending:"暂无待处理的任务",collapse:"收起",view:"查看",loadMore:"加载更多",emptyDone:"暂无已处理的任务"},review:{loadExternalImage:"加载外部图片",loadFailed:e=>`加载评审记录失败:${e}`,loadingRecords:"加载评审记录…",notStarted:"评审尚未开始",sectionTitle:"评审记录",phaseLabel:{spec:"方案评审",code:"代码评审"},reviewTurnLabel:"评审",responseTurnLabel:"反馈",roleUser:"用户",roleQa:"评审 Agent",roleDev:"开发 Agent"},prReview:{reasonNoPr:"任务还没有 PR;创建 PR 后,这里会显示代码评审记录。",reasonDriverUnavailable:"暂时无法读取 PR 评审记录,请检查项目的代码平台配置。",specReviewHeading:"方案评审",codeReviewHeading:"代码评审",fetchFailed:e=>`评审记录拉取失败:${e}`,partialFetchFailed:e=>`部分评审记录拉取失败:${e}(仅展示已获取的部分)`,inlineComment:"行内评论",comment:"评论",replyIndicator:"↩ 回复",noReviewBody:"(无评审正文)",bodyTruncated:"内容较大,已截断。",truncatedSuffix:"(已截断)",noReviewBodyFallback:"无评审正文",ghostAuthor:"ghost(账号已注销)",listTruncated:"该 PR 评论过多,仅展示靠前的一部分。",fetchedAtLabel:e=>`数据拉取于 ${e}`,nextCheck:e=>`下次检查 ≤${e} 秒`,autoRefreshStopped:"已停止自动更新",refresh:"刷新",refreshing:"刷新中…",refreshFailed:e=>`刷新失败:${e}`},toast:{dismissAriaLabel:"关闭通知"},banner:{restartFailed:e=>`重启失败:${e}`,restarting:"重启中…",pendingNotice:e=>`有 ${e} 项配置变更待重启 baxian server 才生效`,restartNow:"现在重启",preRestartFetchFailed:e=>`获取重启前 startedAt 失败:${e}`,restartTriggerFailed:e=>`触发重启失败:${e}`,restartTimeout:"重启超时(30s 未恢复)。请检查日志或手动执行 baxian start --home <dir>",platformDegraded:e=>`平台轮询降级(${e})——评审与 PR 更新可能延迟,连通恢复后自动跟上`,platformUnreachable:e=>`平台无法访问(${e})——任务推进暂停,连通恢复后自动继续`,platformAccessDenied:(e,n)=>`平台拒绝访问(${e})——凭证失效或权限不足,任务推进暂停,需人工修复凭证后才会恢复。${n??""}`,platformRepoNotFound:e=>`平台返回资源不存在(${e})——仓库或所需资源不存在、已改名/删除,或当前凭证无权访问,任务推进暂停,需人工修复后才会恢复`,platformRateLimited:(e,n)=>`平台轮询触发限流(${e}),将于 ${new Date(n).toLocaleTimeString()} 后自动恢复`},terminal:{sessionEnded:"会话已结束",keyPadAriaLabel:"终端按键",arrowAriaLabel:e=>`方向键 ${e}`,arrowLabel:{up:"上",down:"下",left:"左",right:"右"},escKeyAriaLabel:"Esc 键"},imageUpload:{tooLargeBody:e=>`单张图片不能超过 ${e} MiB`,insertedTitle:"图片已插入",insertedBody:"路径已粘贴到终端输入,补充说明后回车",uploadFailedTitle:"图片上传失败",uploadAriaLabel:"上传图片"},pet:{missingManifest:"文件包中未找到 pet.json",manifestParseFailed:"pet.json 解析失败",missingSpritesheet:"文件包中未找到精灵图(png/webp)",disabledTitle:"已关闭 Agent Pet",disableFailedTitle:"关闭失败",selectedTitle:"已选择 Pet",selectFailedTitle:"选择失败",deleteConfirmTitle:e=>`删除 Pet「${e}」?`,deleteConfirmBody:"使用它的 Agent 会回到默认状态显示。",deletedTitle:e=>`Pet「${e}」已删除`,deleteFailedTitle:"删除失败",uploadedTitle:"Pet 上传成功",uploadFailedTitle:"Pet 上传失败",enableLabel:"启用 Agent Pet",enableHint:"开启后可上传 Codex Pet 文件包,或选择已上传过的 Pet 替换 Agent 卡片上的状态显示。",uploadButton:"上传 Pet 文件包",uploadInputAriaLabel:"上传 Codex Pet 文件包",uploadDirHint:"选择 Codex Pet 目录(含 pet.json 与精灵图)。",emptyState:"还没有上传过 Pet,点击上方按钮上传。",currentMarker:"(当前)",deleteAriaLabel:e=>`删除 ${e}`}},hn="baxian.language",rt="en-US",rs={"en-US":ss,"zh-CN":pr};function as(e){return e==="zh-CN"||e==="en-US"}function is(){try{const e=localStorage.getItem(hn);return as(e)?e:rt}catch{return rt}}function os(e){try{localStorage.setItem(hn,e)}catch{}}let Ve=is();const en=new Set;let St=0,gr=0,Nn=0;function fn(e){e!==Ve&&(Ve=e,en.forEach(n=>n(e)))}function tn(e){St+=1;const n=e??rt;os(n),fn(n)}function xr(e){const n=e??rt;os(n),fn(n)}function pn(){return rs[Ve]}const ls=o.createContext({locale:rt,messages:ss,saving:!1,setLocale:async()=>{throw new Error("setLocale requires I18nProvider")}});function br({children:e}){const[n,s]=o.useState(Ve),[r,a]=o.useState(!1);o.useEffect(()=>{const l=c=>s(c);return en.add(l),s(Ve),()=>{en.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!==hn)return;const h=c.key===null?is():c.newValue;as(h)&&(St+=1,fn(h))};return window.addEventListener("storage",l),()=>window.removeEventListener("storage",l)},[]);const i=async l=>{if(l!==Ve){a(!0);try{await $.config.patch({language:l}),tn(l)}finally{a(!1)}}};return t.jsx(ls.Provider,{value:{locale:n,messages:rs[n],saving:r,setLocale:i},children:e})}function cs(){return o.useContext(ls)}function q(){return cs().messages}function vr(){o.useEffect(()=>{const e=()=>{const s=St,r=++gr;$.config.get().then(a=>{s===St&&(r<=Nn||(Nn=r,xr(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 ds=o.createContext(null),yr={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"},wr={success:mr,warn:hr,error:fr};let kr=1;function jr({children:e}){const n=q(),[s,r]=o.useState([]),a=o.useRef(new Map),i=o.useRef(new Map);o.useEffect(()=>{const u=a.current,d=i.current;return()=>{for(const x of u.values())clearTimeout(x);u.clear(),d.clear()}},[]);const l=o.useCallback(u=>{const d=a.current.get(u);d&&clearTimeout(d),a.current.delete(u)},[]),c=o.useCallback(u=>{l(u),i.current.delete(u),r(d=>d.filter(x=>x.id!==u))},[l]),h=o.useCallback((u,d)=>{l(u),a.current.set(u,setTimeout(()=>c(u),d))},[l,c]),m=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 y=i.current.get(u);y==null||y.delete(d),(!y||y.size===0)&&h(u,x)},[h]),p=o.useCallback(u=>{const d=kr++,x=u.durationMs??3e3;r(y=>[...y,{...u,id:d,durationMs:x}]),h(d,x)},[h]);return t.jsxs(ds.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 ${yr[u.kind]}`,role:"status",onMouseEnter:()=>m(u.id,"hover"),onMouseLeave:()=>f(u.id,"hover",u.durationMs),onFocus:()=>m(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=wr[u.kind];return t.jsx(d,{className:"mt-0.5 shrink-0",width:14,height:14})})(),t.jsxs("div",{className:"flex-1",children:[t.jsx("div",{className:"text-sm font-semibold",children:u.title}),u.body&&t.jsx("div",{className:"mt-1 whitespace-pre-line text-xs text-og-700",children:u.body}),u.details&&t.jsxs("details",{className:"mt-1 text-xs text-og-500",children:[t.jsx("summary",{className:"cursor-pointer select-none text-accent",children:n.common.technicalDetails}),t.jsx("div",{className:"mt-1 whitespace-pre-wrap break-words font-mono",children:u.details})]})]}),t.jsx("button",{type:"button",onClick:()=>c(u.id),className:"text-current opacity-50 transition-opacity hover:opacity-100","aria-label":n.toast.dismissAriaLabel,children:"✕"})]})},u.id))})]})}function ke(){const e=o.useContext(ds);if(!e)throw new Error("useToast must be inside <ToastProvider>");return e}const Tr={sm:"max-w-md",md:"max-w-lg",lg:"max-w-2xl"},Sn='input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), [href], [tabindex]:not([tabindex="-1"])',Oe=[];function Se({open:e,onClose:n,title:s,titleContent:r,children:a,footer:i,size:l="md",dismissOnBackdrop:c=!0}){const h=q(),m=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;Oe.push(x);const y=()=>Oe[Oe.length-1]===x;p.current=document.activeElement;const w=R=>{if(!y())return;if(R.key==="Escape"){d.current();return}if(R.key!=="Tab")return;const v=m.current;if(!v)return;const b=Array.from(v.querySelectorAll(Sn)).filter(I=>I.offsetParent!==null||I===document.activeElement);if(b.length===0){R.preventDefault();return}const j=b[0],k=b[b.length-1],E=document.activeElement;R.shiftKey&&(E===j||!v.contains(E))?(R.preventDefault(),k.focus()):!R.shiftKey&&(E===k||!v.contains(E))&&(R.preventDefault(),j.focus())};document.addEventListener("keydown",w);const C=document.body.style.overflow;document.body.style.overflow="hidden";const S=m.current;if(S){const R=S.querySelector(Sn);R==null||R.focus()}return()=>{var v,b;const R=Oe.indexOf(x);R>=0&&Oe.splice(R,1),document.removeEventListener("keydown",w),document.body.style.overflow=C,(b=(v=p.current)==null?void 0:v.focus)==null||b.call(v)}},[e]),e?t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-og-1000/45 px-3 sm:px-4",onMouseDown:c?x=>{u.current=x.target===x.currentTarget&&Oe[Oe.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:m,className:`flex w-full ${Tr[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":h.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 us=o.createContext(null);function Nr({children:e}){const n=q(),[s,r]=o.useState(null),a=o.useRef(null),i=o.useCallback(c=>new Promise(h=>{var f;(f=a.current)==null||f.resolve(!1);const m={...c,resolve:h};a.current=m,r(m)}),[]),l=o.useCallback(c=>{const h=a.current;h&&(a.current=null,r(null),h.resolve(c))},[]);return t.jsxs(us.Provider,{value:i,children:[e,s&&t.jsx(Se,{open:!0,title:s.title,onClose:()=>l(!1),size:"sm",footer:t.jsxs("div",{className:"flex justify-end gap-2",children:[t.jsx("button",{type:"button",onClick:()=>l(!1),className:"btn-secondary",children:s.cancelLabel??n.common.cancel}),t.jsx("button",{type:"button",onClick:()=>l(!0),className:"btn-primary",children:s.confirmLabel??n.common.confirm})]}),children:s.body?t.jsx("p",{className:"whitespace-pre-line text-sm text-og-700",children:s.body}):null})]})}function gn(){const e=o.useContext(us);if(!e)throw new Error("useConfirm must be inside <ConfirmProvider>");return e}const Rt="baxian.pendingRestart",Sr=500,Rr=3e4,ms=o.createContext(null);function Cr(){try{const e=localStorage.getItem(Rt);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 Ar(e){try{e.count<=0?localStorage.removeItem(Rt):localStorage.setItem(Rt,JSON.stringify(e))}catch{}}function Pr({children:e}){const n=q(),s=Cr(),[r,a]=o.useState(s.count),[i,l]=o.useState(s.baselineStartedAt),[c,h]=o.useState(s.count>0?"pending":"idle"),[m,f]=o.useState(),p=o.useRef(s.count),u=o.useRef(s.count>0?"pending":"idle"),d=o.useRef(0),x=o.useCallback(v=>{p.current=v,a(v)},[]),y=o.useCallback(v=>{a(b=>{const j=v(b);return p.current=j,j})},[]),w=o.useCallback(v=>{u.current=v,h(v)},[]);o.useEffect(()=>{Ar({count:r,baselineStartedAt:i})},[r,i]),o.useEffect(()=>{let v=!1;(async()=>{try{const j=await $.health.get();if(v)return;l(k=>k!==null&&j.startedAt!==k?(x(0),w("idle"),null):k)}catch{}})();const b=j=>{if(j.key===Rt){if(j.newValue===null){if(u.current==="restarting"&&d.current>0){x(d.current),l(null);return}x(0),l(null),u.current!=="restarting"&&w("idle");return}try{const k=JSON.parse(j.newValue);typeof k.count=="number"&&(u.current==="restarting"&&k.count>p.current&&(d.current+=k.count-p.current),x(k.count),u.current!=="restarting"&&w(k.count>0?"pending":"idle")),typeof k.baselineStartedAt=="string"?l(k.baselineStartedAt):k.baselineStartedAt===null&&l(null)}catch{}}};return window.addEventListener("storage",b),()=>{v=!0,window.removeEventListener("storage",b)}},[x,w]);const C=o.useRef(!1),S=o.useCallback(()=>{y(v=>v+1),u.current==="restarting"?d.current+=1:w("pending"),l(v=>(v!==null||C.current||(C.current=!0,(async()=>{try{const b=await $.health.get();l(j=>j??b.startedAt)}catch{}finally{C.current=!1}})()),v))},[w,y]),R=o.useCallback(async()=>{d.current=0,f(void 0),w("restarting");let v;try{v=(await $.health.get()).startedAt}catch(j){w("failed"),f(n.banner.preRestartFetchFailed(j instanceof Error?j.message:String(j)));return}try{await $.server.restart()}catch(j){if(!(j instanceof Ke&&j.status===409)){w("failed"),f(n.banner.restartTriggerFailed(j instanceof Error?j.message:String(j)));return}}const b=Date.now();for(;Date.now()-b<Rr;){await new Promise(j=>setTimeout(j,Sr));try{const j=await $.health.get();if(j.startedAt!==v){const k=d.current;d.current=0,l(k>0?j.startedAt:null),x(k),w(k>0?"pending":"idle");return}}catch{}}w("failed"),f(n.banner.restartTimeout)},[x,w,n]);return t.jsx(ms.Provider,{value:{phase:c,count:r,error:m,flagDirty:S,triggerRestart:R},children:e})}function $t(){const e=o.useContext(ms);if(!e)throw new Error("usePendingRestart must be used inside PendingRestartProvider");return e}const Lr=[500,1e3,2e3,4e3,8e3,15e3,3e4];class hs{constructor(n){oe(this,"attempts",0);oe(this,"timer",null);oe(this,"delaysMs");this.opts=n,this.delaysMs=n.delaysMs??Lr}schedule(){if(this.timer||!this.shouldReconnect())return;const n=this.delaysMs[Math.min(this.attempts,this.delaysMs.length-1)];this.attempts+=1,this.timer=setTimeout(()=>{this.timer=null,this.shouldReconnect()&&this.opts.reconnect()},n)}cancel(){this.timer&&(clearTimeout(this.timer),this.timer=null)}reset(){this.attempts=0}shouldReconnect(){return this.opts.shouldReconnect?this.opts.shouldReconnect():!0}}function fs(e,n,s){return(e==null?void 0:e.code)!==4401||n!==s?!1:(window.dispatchEvent(new CustomEvent(st)),!0)}function ps(e){return Array.from(new TextEncoder().encode(e)).map(n=>n.toString(16).padStart(2,"0")).join("")}function gs(e){return`${location.protocol==="https:"?"wss":"ws"}://${location.host}${e}`}const xs=(e,n)=>n&&n.length>0?new WebSocket(e,n):new WebSocket(e);let Rn=0;function Er(){Rn++;const e=Math.random().toString(36).slice(2,8);return`sub-${Date.now().toString(36)}-${Rn}-${e}`}function Dr(){return gs("/api/stream")}class $r{constructor(n={}){oe(this,"wsUrl");oe(this,"wsFactory");oe(this,"tokenProvider");oe(this,"ws",null);oe(this,"subs",new Map);oe(this,"snapshotPending",new Set);oe(this,"preSubscribeQueue",new Map);oe(this,"outbox",[]);oe(this,"reconnectScheduler");oe(this,"explicitlyClosed",!1);this.wsUrl=n.wsUrl??Dr(),this.wsFactory=n.wsFactory??xs,this.tokenProvider=n.tokenProvider??un,this.reconnectScheduler=new hs({reconnect:()=>this.openSocket(),shouldReconnect:()=>!this.explicitlyClosed&&this.subs.size>0})}subscribe(n){const s=Er(),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.${ps(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&&(fs(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 Ht=null;function qt(){return Ht||(Ht=new $r),Ht}function Ir(e){const{agentId:n,mode:s}=e,r=o.useRef(null),a=o.useRef({onSnapshot:e.onSnapshot,onData:e.onData,onError:e.onError,onSessionGone:e.onSessionGone});a.current={onSnapshot:e.onSnapshot,onData:e.onData,onError:e.onError,onSessionGone:e.onSessionGone},o.useEffect(()=>{const h=qt().subscribe({agentId:n,mode:s,onSnapshot:m=>a.current.onSnapshot(m),onData:m=>a.current.onData(m),onError:m=>{var f,p;return(p=(f=a.current).onError)==null?void 0:p.call(f,m)},onSessionGone:()=>{var m,f;return(f=(m=a.current).onSessionGone)==null?void 0:f.call(m)}});return r.current=h.subscriberId,()=>{r.current=null,h.unsubscribe()}},[n,s]);const i=o.useCallback(c=>{const h=r.current;h&&qt().send(h,c)},[]),l=o.useCallback((c,h)=>{const m=r.current;m&&qt().resize(m,c,h)},[]);return{send:i,resize:l}}const Br=8;let xt=0,bt,Cn=!0;function bs(e){var n;return Array.from(((n=e.element)==null?void 0:n.querySelectorAll("canvas"))??[])}function An(e){for(const n of bs(e)){const s=n.getContext("webgl2");if(s)return s}return null}function nn(e){var n;(n=e==null?void 0:e.getExtension("WEBGL_lose_context"))==null||n.loseContext()}function Mr(){const e=document.createElement("canvas").getContext("webgl2");return e?(nn(e),!0):!1}function Fr(e,n){let s=null,r=!1;const a=()=>{if(r||!Cn)return;const m=new Zs.CanvasAddon;try{e.loadAddon(m),s={kind:"canvas",addon:m}}catch(f){Cn=!1,console.warn("[terminal-renderer] canvas renderer unavailable, using dom renderer:",f),m.dispose()}},i=()=>{if(!s)return;const{kind:m,addon:f}=s;s=null;const p=m==="webgl"?An(e):null;f.dispose(),m==="webgl"&&(xt--,nn(p))},l=()=>{if(bt===void 0&&(bt=Mr()),!bt||xt>=Br)return!1;let m=null;try{return m=new Xs.WebglAddon,m.onContextLoss(()=>{i(),a()}),e.loadAddon(m),xt++,s={kind:"webgl",addon:m},!0}catch(f){bt=!1,console.warn("[terminal-renderer] webgl renderer unavailable, using canvas from now on:",f),m==null||m.dispose();for(const p of bs(e))p.remove();return!1}},c=()=>{r||s||l()||a()},h=typeof IntersectionObserver=="function"?new IntersectionObserver(m=>{if(r)return;const f=m[m.length-1];f!=null&&f.isIntersecting?c():i()}):null;return h?h.observe(n):c(),{get kind(){return(s==null?void 0:s.kind)??"dom"},dispose(){if(r)return;r=!0,h==null||h.disconnect();const m=s;s=null;const f=(m==null?void 0:m.kind)==="webgl"?An(e):null;try{e.dispose()}catch(p){console.warn("[terminal-renderer] dispose failed:",p)}(m==null?void 0:m.kind)==="webgl"&&(xt--,nn(f))}}}const Or=[{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"}],vt=Object.fromEntries(Or.map(e=>[e.key,e]));function yt({arrow:e,ariaLabel:n,onPress:s}){return t.jsx("button",{type:"button","aria-label":n,"data-arrow":e.key,onMouseDown:r=>r.preventDefault(),onClick:()=>s(e.key),className:"flex h-8 w-8 items-center justify-center rounded border border-hairline bg-surface text-og-700 transition-colors hover:bg-og-50 hover:text-og-1000 active:bg-og-200",children:t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:t.jsx("path",{d:e.path})})})}function _r({onKey:e,onEscape:n,className:s}){const r=q();return t.jsxs("div",{role:"group","aria-label":r.terminal.keyPadAriaLabel,className:s??"flex flex-none items-center justify-center gap-1 border-t border-hairline bg-page px-3 py-2",children:[n&&t.jsx("button",{type:"button","aria-label":r.terminal.escKeyAriaLabel,"data-key":"escape",onMouseDown:a=>a.preventDefault(),onClick:n,className:"mr-2 flex h-8 items-center justify-center rounded border border-hairline bg-surface px-2.5 font-mono text-xs text-og-700 transition-colors hover:bg-og-50 hover:text-og-1000 active:bg-og-200",children:"ESC"}),t.jsx(yt,{arrow:vt.left,ariaLabel:r.terminal.arrowAriaLabel(r.terminal.arrowLabel.left),onPress:e}),t.jsx(yt,{arrow:vt.up,ariaLabel:r.terminal.arrowAriaLabel(r.terminal.arrowLabel.up),onPress:e}),t.jsx(yt,{arrow:vt.down,ariaLabel:r.terminal.arrowAriaLabel(r.terminal.arrowLabel.down),onPress:e}),t.jsx(yt,{arrow:vt.right,ariaLabel:r.terminal.arrowAriaLabel(r.terminal.arrowLabel.right),onPress:e})]})}const Hr=Math.floor(Dt/1024/1024);function qr({agentId:e,className:n}){const s=q(),r=o.useRef(null),[a,i]=o.useState(!1),{show:l}=ke(),c=async h=>{var f;const m=(f=h.target.files)==null?void 0:f[0];if(h.target.value="",!!m){if(m.size>Dt){l({kind:"error",title:s.createTask.imageTooLargeToastTitle,body:s.imageUpload.tooLargeBody(Hr)});return}i(!0);try{await $.agents.uploadImage(e,m),l({kind:"success",title:s.imageUpload.insertedTitle,body:s.imageUpload.insertedBody})}catch(p){const u=p instanceof Ke||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:h=>h.preventDefault(),onClick:()=>{var h;return(h=r.current)==null?void 0:h.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 Ur={up:"A",down:"B",right:"C",left:"D"};function Gr(e,n){return(n?"\x1BO":"\x1B[")+Ur[e]}const Pn=18,Wr=250,zr=256*1024,Ln="#fdfdfd",Vr='ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',Kr={background:Ln,foreground:"#474c55",cursor:"#1348dc",cursorAccent:Ln,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"},Yr=/\x1b\[(?:\?[\d;]*c|>[\d;]*c|\??\d+;\d+R|\d+n)/g;function Qr(e){return e.replace(Yr,"")}const Jr=1024*1024;function Xr(e){const n=e.indexOf(";");if(n===-1)return null;const s=e.slice(n+1);if(s.length===0||s==="?"||s.length>Jr)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 tt({agentId:e,mode:n,interactive:s=!1,maxLines:r,className:a,autoFocus:i=!0,deferFullUntilFocus:l=!1,arrowKeys:c=!1}){const h=q(),m=o.useRef(null),f=o.useRef(null),p=o.useRef(null),u=o.useRef(null),d=o.useRef(!1),x=o.useRef(""),y=o.useRef([]),w=o.useRef(0),C=o.useRef(null),S=o.useRef(null),R=o.useRef(null),v=o.useRef(Promise.resolve()),b=o.useRef(0),[j,k]=o.useState(null),[E,I]=o.useState(!1),_=`${e}\0${n}\0${l?"1":"0"}`,[F,te]=o.useState({key:_,active:!1}),z=F.key===_&&F.active,K=n==="full"&&l,re=K&&!z?"preview":n,Z=s&&re==="full",ne=(T,B)=>B.length===0?Promise.resolve():new Promise(M=>{try{T.write(B,()=>M())}catch(he){console.warn("[pane-terminal] write failed:",he),M()}}),Y=re==="preview",se=()=>{var D;if(!Y)return;const T=m.current,B=f.current;if(!T||!B||T.clientHeight<=0)return;const M=((D=T.querySelector(".xterm-screen"))==null?void 0:D.getBoundingClientRect().height)??0,he=M>0&&B.rows>0?M/B.rows:Pn,ie=(B.buffer.active.cursorY+1)*he;T.scrollTop=Math.max(0,ie-T.clientHeight)},ee=()=>{if(!Y||R.current!==null)return;let T=!1;const B=requestAnimationFrame(()=>{T=!0,R.current=null,se()});T||(R.current=B)},J=(T,B)=>{v.current=v.current.then(async()=>{const M=f.current;if(!(!M||B!==b.current))try{await T(M),Z&&M.scrollToBottom(),ee()}catch(he){console.warn("[pane-terminal] terminal task failed:",he)}}).catch(M=>{console.warn("[pane-terminal] write chain failed:",M)})},me=(T,B)=>{J(M=>ne(M,T),B)},ge=()=>{C.current!==null&&(cancelAnimationFrame(C.current),C.current=null),S.current!==null&&(clearTimeout(S.current),S.current=null)},H=()=>{ge(),y.current=[],w.current=0},le=()=>{ge();const T=y.current;T.length!==0&&(y.current=[],w.current=0,me(T.join(""),b.current))},ce=T=>{if(T.length!==0){if(y.current.push(T),w.current+=T.length,w.current>=zr){le();return}C.current===null&&(C.current=requestAnimationFrame(le)),S.current===null&&(S.current=setTimeout(le,Wr))}},{send:ae,resize:ye}=Ir({agentId:e,mode:re,onSnapshot:({cols:T,rows:B,data:M})=>{if(f.current)try{const ie=b.current+1;b.current=ie,H(),J(async D=>{var A;D.reset(),Z?((A=u.current)==null||A.call(u),await ne(D,M)):(T>0&&B>0&&D.resize(T,B),await ne(D,M))},ie)}catch(ie){console.warn("[pane-terminal] snapshot write failed:",ie)}},onData:T=>{ce(T)},onError:T=>k(`${T.code}: ${T.message}`),onSessionGone:()=>I(!0)});o.useEffect(()=>{k(null),I(!1)},[e,re]),o.useEffect(()=>{x.current=""},[_]),o.useEffect(()=>{if(re!=="full")return;const T=x.current;T.length!==0&&(x.current="",ae(T))},[ae,re]);const N=o.useCallback(()=>{!s||!K||z||(d.current=!0,te({key:_,active:!0}))},[_,z,s,K]),xe=o.useCallback(T=>{const B=Qr(T);if(B.length!==0){if(K&&(!z||x.current.length>0)){x.current+=B,N();return}ae(B)}},[N,z,ae,K]);o.useEffect(()=>{const T=m.current;if(!T)return;let B=!1;const M=new er.Terminal({cursorBlink:s,disableStdin:!s,theme:Kr,fontFamily:Vr,fontSize:13,lineHeight:1.4,scrollback:re==="full"?5e3:1e3}),he=new tr.FitAddon;M.loadAddon(he),M.open(T);const ie=Fr(M,T);f.current=M,p.current=he;const D=Y?M.onRender(()=>ee()):null;if(s&&(i||d.current)){d.current=!1;try{M.focus()}catch{}}s&&(M.onData(xe),re==="full"&&M.parser.registerOscHandler(52,$e=>{var Ce;const Re=Xr($e);return Re!==null&&((Ce=navigator.clipboard)==null||Ce.writeText(Re).catch(()=>{})),!0}));const A=()=>T.clientWidth>0&&T.clientHeight>0,L=($e=!1)=>{if(!A())return!1;const Re=M.cols,Ce=M.rows;try{he.fit()}catch{return!1}return Z&&M.scrollToBottom(),M.cols>0&&M.rows>0&&($e||M.cols!==Re||M.rows!==Ce)&&ye(M.cols,M.rows),!0};u.current=Z?()=>L(!0):null;let Q=null,G=null,X=null,we=0;const Fe=()=>{Q||(Q=new ResizeObserver(()=>{G&&clearTimeout(G),G=setTimeout(()=>{G=null,Z?L():Y&&ee()},100)}),Q.observe(T))},qe=()=>{X=requestAnimationFrame(()=>{if(X=null,!B){if(!Z){Y&&(Fe(),ee());return}if(L(!0)){Fe();return}if(we++<5){qe();return}Fe()}})};return qe(),()=>{B=!0,X!==null&&cancelAnimationFrame(X),C.current!==null&&(cancelAnimationFrame(C.current),C.current=null),S.current!==null&&(clearTimeout(S.current),S.current=null),R.current!==null&&(cancelAnimationFrame(R.current),R.current=null),b.current++,y.current=[],w.current=0,v.current=Promise.resolve(),G&&clearTimeout(G),Q==null||Q.disconnect(),D==null||D.dispose(),f.current=null,p.current=null,u.current=null,ie.dispose()}},[e,i,Z,xe,s,re,ye]);const be=()=>{var T;if(s){N();try{(T=f.current)==null||T.focus()}catch{}}};o.useEffect(()=>{if(s)return;const T=m.current;if(!T)return;const B=M=>{M.stopPropagation()};return T.addEventListener("wheel",B,{capture:!0,passive:!0}),()=>T.removeEventListener("wheel",B,{capture:!0})},[s]);const P=r&&r>0?{maxHeight:`${r*Pn}px`}:void 0;return t.jsxs("div",{className:a??"flex flex-col h-full w-full min-h-0 bg-term",children:[(j||E)&&t.jsx("div",{className:"border-b border-accent/25 bg-accent-soft px-3 py-1 font-mono text-xs text-accent",children:E?h.terminal.sessionEnded:j}),t.jsx("div",{className:"flex flex-1 min-h-0 px-2 py-1.5",style:P,children:t.jsx("div",{ref:m,className:"flex-1 min-h-0 overflow-hidden",onMouseDown:be})}),s&&c&&t.jsxs("div",{className:"grid grid-cols-[1fr_auto_1fr] gap-2 flex-none items-center border-t border-hairline bg-page px-3 py-2",children:[t.jsx("div",{className:"flex items-center",children:t.jsx(qr,{agentId:e})}),t.jsx(_r,{className:"flex items-center justify-center gap-1",onKey:T=>{var M,he;const B=!!((he=(M=f.current)==null?void 0:M.modes)!=null&&he.applicationCursorKeysMode);xe(Gr(T,B))},onEscape:()=>xe("\x1B")})]})]})}function Zr(){const[e,n]=o.useState([]),[s,r]=o.useState(!0),[a,i]=o.useState(null),l=o.useCallback(async()=>{r(!0);try{n(await $.pets.list()),i(null)}catch(c){i(c instanceof Error?c.message:String(c))}finally{r(!1)}},[]);return o.useEffect(()=>{l()},[l]),{pets:e,loading:s,error:a,refresh:l}}const Ut=new Map,Gt=new Map;function ea(e){const[n,s]=o.useState(()=>e?Gt.get(e)??null:null);return o.useEffect(()=>{if(!e){s(null);return}const r=Gt.get(e);if(s(r??null),r)return;let a=!1,i=Ut.get(e);return i||(i=$.pets.fetchSpritesheet(e).then(l=>{const c=URL.createObjectURL(l);return Gt.set(e,c),c}),Ut.set(e,i)),i.then(l=>{a||s(l)},()=>{a||s(null),Ut.delete(e)}),()=>{a=!0}},[e]),n}const ta=[{state:"idle",row:0,durations:[280,110,110,140,140,320]},{state:"running-right",row:1,durations:[120,120,120,120,120,120,120,220]},{state:"running-left",row:2,durations:[120,120,120,120,120,120,120,220]},{state:"waving",row:3,durations:[140,140,140,280]},{state:"jumping",row:4,durations:[140,140,140,140,280]},{state:"failed",row:5,durations:[140,140,140,140,140,140,140,240]},{state:"waiting",row:6,durations:[150,150,150,150,150,260]},{state:"running",row:7,durations:[120,120,120,120,120,220]},{state:"review",row:8,durations:[150,150,150,150,150,280]}];function na(e,n){if(n)return 3;switch(e){case"working":return 7;case"waiting":return 6;case"pending":return 6;case"error":return 5;case"idle":return 0;case"unknown":return 0;default:return 0}}const xn=36,sa=xn/ns,ra=ts*sa;function aa(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function vs({petId:e,status:n,bootstrapping:s=!1,label:r,displayHeight:a=xn,className:i}){const l=ea(e),c=na(n,s),h=ta[c],m=h.durations.length,[f,p]=o.useState(0),u=a/ns,d=ts*u;return o.useEffect(()=>{if(p(0),!l||m<=1||aa())return;let x,y=0;const w=()=>{y=(y+1)%m,p(y),x=setTimeout(w,h.durations[y])};return x=setTimeout(w,h.durations[0]),()=>clearTimeout(x)},[l,c,m,h]),l?t.jsx("span",{role:"img","aria-label":r,title:r,"data-pet-row":c,"data-pet-col":f,className:["inline-block shrink-0",i].filter(Boolean).join(" "),style:{width:`${d}px`,height:`${a}px`,backgroundImage:`url(${l})`,backgroundRepeat:"no-repeat",backgroundSize:`${ir*u}px ${or*u}px`,backgroundPositionX:`${-(f*d)}px`,backgroundPositionY:`${-(c*a)}px`,imageRendering:"pixelated"}}):t.jsx("span",{className:"pill pill-idle",title:r,children:r})}class Nt extends Error{constructor(n){super(n),this.name="PetPackageError"}}const wt=e=>e.split("/").pop()??e;function ia(e){return typeof e.text=="function"?e.text():new Promise((n,s)=>{const r=new FileReader;r.onerror=()=>s(r.error??new Error("file read failed")),r.onload=()=>n(typeof r.result=="string"?r.result:""),r.readAsText(e)})}async function oa(e){const n=pn(),s=e.find(c=>wt(c.name)==="pet.json"||wt(c.webkitRelativePath||"")==="pet.json");if(!s)throw new Nt(n.pet.missingManifest);let r;try{r=JSON.parse(await ia(s))}catch{throw new Nt(n.pet.manifestParseFailed)}const a=r&&typeof r=="object"&&typeof r.spritesheetPath=="string"?r.spritesheetPath:"",i=a?wt(a):"",l=(i?e.find(c=>wt(c.name)===i):void 0)??e.find(c=>/\.(png|webp)$/i.test(c.name));if(!l)throw new Nt(n.pet.missingSpritesheet);return{manifest:r,spritesheet:l}}function la({children:e,style:n}){const s=o.useRef(null),[r,a]=o.useState(typeof IntersectionObserver>"u");return o.useEffect(()=>{if(r||typeof IntersectionObserver>"u")return;const i=s.current;if(!i)return;const l=new IntersectionObserver(c=>{c.some(h=>h.isIntersecting)&&(a(!0),l.disconnect())});return l.observe(i),()=>l.disconnect()},[r]),t.jsx("span",{ref:s,className:"inline-block shrink-0",style:n,children:r?e:null})}function ca({agentId:e,currentPetId:n,onClose:s}){const r=q(),{show:a}=ke(),i=gn(),{pets:l,loading:c,refresh:h}=Zr(),[m,f]=o.useState(!!n),[p,u]=o.useState(n),[d,x]=o.useState(!1),y=o.useRef(null);o.useEffect(()=>{u(n)},[n]),o.useEffect(()=>{const b=y.current;b&&(b.setAttribute("webkitdirectory",""),b.setAttribute("directory",""))},[m]);const w=b=>b instanceof Ke||b instanceof Error?b.message:String(b),C=async b=>{if(f(b),!b&&p){x(!0);try{await $.agents.setPet(e,null),u(null),a({kind:"success",title:r.pet.disabledTitle})}catch(j){a({kind:"error",title:r.pet.disableFailedTitle,body:w(j)}),f(!0)}finally{x(!1)}}},S=async b=>{x(!0);try{await $.agents.setPet(e,b),u(b),a({kind:"success",title:r.pet.selectedTitle})}catch(j){a({kind:"error",title:r.pet.selectFailedTitle,body:w(j)})}finally{x(!1)}},R=async(b,j)=>{if(await i({title:r.pet.deleteConfirmTitle(j),body:r.pet.deleteConfirmBody,confirmLabel:r.common.delete})){x(!0);try{await $.pets.remove(b),await h(),a({kind:"success",title:r.pet.deletedTitle(j)})}catch(k){a({kind:"error",title:r.pet.deleteFailedTitle,body:w(k)})}finally{x(!1)}}},v=async b=>{const j=b.target.files?Array.from(b.target.files):[];if(b.target.value="",!!j.length){x(!0);try{const{manifest:k,spritesheet:E}=await oa(j);await $.pets.create(k,E),await h(),a({kind:"success",title:r.pet.uploadedTitle})}catch(k){const E=k instanceof Nt?k.message:w(k);a({kind:"error",title:r.pet.uploadFailedTitle,body:E})}finally{x(!1)}}};return t.jsx(Se,{open:!0,onClose:s,title:"Agent Pet",size:"md",children:t.jsxs("div",{className:"space-y-4",children:[t.jsxs("label",{className:"flex items-center gap-2 text-sm text-og-1000",children:[t.jsx("input",{type:"checkbox",checked:m,disabled:d,onChange:b=>void C(b.target.checked)}),r.pet.enableLabel]}),m?t.jsxs(t.Fragment,{children:[t.jsxs("div",{children:[t.jsx("button",{type:"button",onClick:()=>{var b;return(b=y.current)==null?void 0:b.click()},disabled:d,className:"btn-secondary",children:r.pet.uploadButton}),t.jsx("input",{ref:y,type:"file","aria-label":r.pet.uploadInputAriaLabel,className:"hidden",onChange:b=>void v(b)}),t.jsx("p",{className:"mt-1 text-xs text-og-400",children:r.pet.uploadDirHint})]}),c?t.jsx("p",{className:"text-sm text-og-500",children:r.common.loading}):l.length===0?t.jsx("p",{className:"text-sm text-og-500",children:r.pet.emptyState}):t.jsx("ul",{className:"grid grid-cols-2 gap-2",children:l.map(b=>{const j=b.id===p;return t.jsxs("li",{className:`flex items-center gap-2 rounded-md border p-2 ${j?"border-accent bg-accent-soft/40":"border-hairline"}`,children:[t.jsx(la,{style:{width:`${ra}px`,height:`${xn}px`},children:t.jsx(vs,{petId:b.id,status:"idle",label:b.displayName})}),t.jsxs("button",{type:"button",onClick:()=>void S(b.id),disabled:d||j,title:b.description||b.displayName,className:"min-w-0 flex-1 truncate text-left text-sm text-og-1000 hover:text-accent-hover disabled:cursor-default",children:[b.displayName,j&&t.jsx("span",{className:"ml-1 text-xs text-accent",children:r.pet.currentMarker})]}),t.jsx("button",{type:"button","aria-label":r.pet.deleteAriaLabel(b.displayName),onClick:()=>void R(b.id,b.displayName),disabled:d,className:"shrink-0 text-xs text-accent hover:underline disabled:opacity-50",children:r.common.delete})]},b.id)})})]}):t.jsx("p",{className:"text-xs text-og-500",children:r.pet.enableHint})]})})}function ys(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 da(e){return ys(pn(),e)}function ws(e,n){const{reason:s,recommendedActions:r}=n,a=/confirm-merge|post-approve|merge/.test(s)?e.taskDetail.attentionMergeTitle:/review|verdict/.test(s)?e.taskDetail.attentionReviewTitle:/runtime|session|recovery|tmux|repl/.test(s)?e.taskDetail.attentionAgentTitle:/dispatch|delivery|pr-created/.test(s)?e.taskDetail.attentionHandoffTitle:e.taskDetail.attentionDefaultTitle,i=r.includes("verdict")?e.taskDetail.attentionVerdictGuidance:r.includes("advance")?e.taskDetail.attentionAdvanceGuidance:r.includes("retry")?e.taskDetail.attentionRetryGuidance:e.taskDetail.attentionCancelGuidance;return{title:a,guidance:i}}const ua={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 bn({task:e,className:n=""}){const s=q(),r=ys(s,e);return t.jsx("span",{className:`${ua[e.status]??"pill"} ${n}`,title:r,"data-status":e.status,children:r})}function vn(e){if(!e)return"";const n=e.match(/^task-(\d+)$/);return n?n[1]:e}function Wt(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 Ee(e,n){return`/project/${encodeURIComponent(e)}/task/${encodeURIComponent(n)}`}const zt={unknown:"pill pill-idle",idle:"pill pill-idle",pending:"pill pill-warn",working:"pill pill-live",waiting:"pill pill-review",error:"pill pill-warn"},ma=72;function ha(e,n,s){const r=s!==void 0&&cn.has(s.status);return e==="greeting_failed"?"restart-runtime":e==="agent_dialog_pending"?"terminal":r&&(e==="agent_dialog_resolved_runtime"||e!=null&&e.startsWith("signal-arm-failed"))||r&&(e==="dispatch-failed:ack_unknown"||e==="dev-wait-gate-failed-after-qa-started")||r&&s.status!=="spec-ready"&&s.status!=="max_rounds"&&(e==="dirty-workdir"||e==="checkout-preparation-failed")&&n==="dev"?"task":"resume"}function ks(e){var n;return!!((n=e.binding)!=null&&n.creationToken)&&!e.binding.paneId&&e.binding.status!=="awaiting_human"&&e.reason!=="PENDING_HUMAN"}function fa(e,n){var s,r,a;return e.tmuxSessionStatus==="unreachable"?{kind:"alert",label:n.sessionStatus.unreachable,cls:"pill pill-danger"}:ks(e)?{kind:"runtime",label:n.bootstrappingBadge,cls:"pill pill-review"}:Yn(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:zt.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:zt.pending}:{kind:"runtime",label:n.runtimeStatus[e.runtimeStatus],cls:zt[e.runtimeStatus]}}function pa(e,n){const s=fa(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 js({agent:e,projectId:n,role:s,runtime:r,model:a,onDeleted:i,pendingRestart:l=!1,terminalLoading:c=!1,showTaskBinding:h=!0,terminalMode:m="activity-preview",active:f,onActivate:p,task:u}){var Re,Ce,Qe,lt,ct,dt,Je,ut;const d=q(),[x,y]=o.useState(!1),[w,C]=o.useState(null),{show:S}=ke(),R=gn(),{flagDirty:v}=$t(),[b,j]=o.useState(!1),[k,E]=o.useState(null),[I,_]=o.useState(!1),[F,te]=o.useState(!1),[z,K]=o.useState(!1),[re,Z]=o.useState(!1),[ne,Y]=o.useState(!1),se=(Re=e.binding)==null?void 0:Re.taskId,ee=(u==null?void 0:u.id)===se?u:void 0,J=((Ce=e.binding)==null?void 0:Ce.status)==="awaiting_human",me=(lt=(Qe=e.binding)==null?void 0:Qe.needInput)==null?void 0:lt.at,ge=J&&((ct=e.binding)==null?void 0:ct.awaitingPhase)==="greeting_failed",H=ha((dt=e.binding)==null?void 0:dt.awaitingPhase,s,ee),le=ks(e),ce=le&&e.tmuxSessionStatus!=="present",ae=pa(e,d.agents),ye=le?d.agents.bootstrappingBadge:d.agents.runtimeStatus[e.runtimeStatus],N=m==="activity-preview"&&!ce&&(e.runtimeStatus==="working"||e.runtimeStatus==="pending"),xe=m==="embedded-full",be=xe&&typeof p=="function",P=be&&f===!0,T=c||l||ce,B=c?d.agents.agentStatusLoading:l?d.agents.terminalNeedsRestart:d.agents.bootstrappingTerminalDisabled,M=Jn(r,a),he=async()=>{y(!0),C(null);try{await $.agents.stop(e.id)}catch(U){C(U instanceof Error?U.message:String(U))}finally{y(!1)}},ie=async()=>{Z(!0);try{(await $.projects.bootstrap(n)).ok?S({kind:"success",title:d.agents.retryBootstrapSucceededTitle,body:d.agents.retryBootstrapSucceededBody}):S({kind:"warn",title:d.agents.retryBootstrapStillFailingTitle,body:d.agents.retryBootstrapStillFailingBody})}catch(U){S({kind:"error",title:d.agents.retryBootstrapFailedTitle,body:U instanceof Error?U.message:String(U)})}finally{Z(!1)}},D=async()=>{if(await R({title:d.agents.resumeConfirmTitle(e.id),body:ge?d.agents.resumeGreetingBody:d.agents.resumeDefaultBody,confirmLabel:d.agents.resume})){K(!0);try{if(ge){e.tmuxSessionStatus==="present"?await $.projects.restartRepl(n,e.id):await $.projects.retryAgent(n,e.id),S({kind:"success",title:d.agents.regreetingStartedTitle(e.id),body:d.agents.regreetingStartedBody});return}const je=await $.projects.resumeAgent(n,e.id);S({kind:"success",title:d.agents.resumedTitle(e.id),body:je.releasedBinding?d.agents.resumedReleasedBody:d.agents.resumedKeptBody})}catch(je){S({kind:"error",title:d.agents.resumeFailedTitle,body:je instanceof Error?je.message:String(je)})}finally{K(!1)}}},A=async()=>{_(!0);try{await $.agents.compact(e.id),S({kind:"success",title:d.agents.compactSentTitle(e.id)})}catch(U){S({kind:"error",title:d.agents.compactFailedTitle,body:U instanceof Error?U.message:String(U)})}finally{_(!1)}},L=async()=>{if(await R({title:d.agents.clearConfirmTitle(e.id),body:d.agents.clearConfirmBody,confirmLabel:d.agents.clearConfirmLabel})){te(!0);try{await $.agents.clear(e.id),S({kind:"success",title:d.agents.clearSentTitle(e.id)})}catch(U){S({kind:"error",title:d.agents.clearFailedTitle,body:U instanceof Error?U.message:String(U)})}finally{te(!1)}}},Q=async()=>{if(await R({title:d.agents.deleteConfirmTitle(e.id),body:d.agents.deleteConfirmBody,confirmLabel:d.common.delete})){j(!0),E(null);try{const U=await $.projects.deleteAgent(n,e.id);U!=null&&U.restartRequired&&v();const je=(U==null?void 0:U.removed)??[e.id],Ue=[...(U==null?void 0:U.warnings)??[]];if(je.length>1){const Bt=je.filter(mt=>mt!==e.id).join(", ");Ue.unshift(d.agents.deletedWithTeamBody(Bt))}Ue.length>0?S({kind:"warn",title:je.length>1?d.agents.deletedWithTeamTitle(e.id):d.agents.deletedTitle(e.id),body:Ue.join(`
8
8
  `)}):S({kind:"success",title:d.agents.deletedTitle(e.id)}),i==null||i()}catch(U){E(U instanceof Error?U.message:String(U))}finally{j(!1)}}},G=be&&!T&&!P,X=["card relative flex h-full min-w-0 flex-col overflow-visible p-4",P?"ring-2 ring-accent":""].filter(Boolean).join(" "),we=["mb-3 flex items-start justify-between gap-2",e.petId?"pr-28":""].filter(Boolean).join(" "),Fe=["mb-2 mt-3 h-80 min-h-0 overflow-hidden border border-hairline bg-surface",G?"cursor-pointer":""].filter(Boolean).join(" "),qe=G?()=>p==null?void 0:p():void 0,$e=G?U=>{(U.key==="Enter"||U.key===" ")&&(U.preventDefault(),p==null||p())}:void 0;return t.jsxs("div",{className:X,"data-agent-card":be?e.id:void 0,children:[e.petId&&t.jsx("div",{className:"absolute -top-4 right-7 z-10",children:t.jsx(vs,{petId:e.petId,status:e.runtimeStatus,bootstrapping:le,label:ye,displayHeight:ma})}),t.jsxs("div",{className:we,children:[t.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[t.jsx("span",{className:"shrink-0 font-mono text-xs font-medium tracking-[0.05em] text-og-500",children:s==="qa"?"QA":"Dev"}),t.jsx("span",{className:"min-w-0 truncate whitespace-nowrap font-display text-sm font-semibold text-og-1000",title:Xn(e.id,r,a),children:e.id}),M&&t.jsxs("span",{className:"hidden shrink-0 whitespace-nowrap text-xs text-og-400 sm:inline",title:M,children:["(",M,")"]})]}),(!e.petId||ae.kind==="alert"||ae.stale)&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:ae.stale?`${ae.cls} pill--stale shrink-0`:`${ae.cls} shrink-0`,title:ae.title,children:ae.label}),ae.stale&&t.jsx("span",{className:"sr-only",children:ae.title})]})]}),ce&&t.jsx("div",{className:"mb-2 rounded-md border border-accent-soft bg-accent-soft/40 px-2.5 py-2 text-xs text-accent",children:d.agents.bootstrappingNotice}),J&&t.jsxs("div",{className:"mb-2 space-y-1 rounded-md border border-accent/25 bg-accent-soft/60 px-2.5 py-2 text-xs text-accent",children:[t.jsxs("div",{children:[t.jsx("span",{className:"font-mono",children:(Je=e.binding)==null?void 0:Je.awaitingPhase}),((ut=e.binding)==null?void 0:ut.awaitingReason)&&t.jsxs("span",{children:[" · ",e.binding.awaitingReason]})]}),t.jsx("div",{className:"text-og-700",children:d.agents.holdRecovery[H]})]}),!le&&e.runtimeStatus==="pending"&&t.jsxs("div",{className:"mb-2 space-y-1 rounded-md border border-accent/25 bg-accent-soft/60 px-2.5 py-2 text-xs text-accent",children:[t.jsx("div",{className:"font-medium",children:d.agents.awaitingHumanIntervention}),t.jsxs("div",{children:[d.agents.openTerminalPrefix,t.jsx(Le,{to:`/terminal/${e.id}`,className:"text-accent hover:text-accent-hover underline",children:d.agents.terminal}),d.agents.openTerminalSuffix]})]}),me&&t.jsxs("div",{className:"mb-2 space-y-1 rounded-md border border-accent/25 bg-accent-soft/60 px-2.5 py-2 text-xs text-accent",children:[t.jsx("div",{className:"font-medium",children:d.agents.needInputNoticeTitle}),t.jsxs("div",{children:[d.agents.needInputPrefix,t.jsx(Le,{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:ie,disabled:re,className:"btn-primary shrink-0",children:re?d.common.retrying:d.agents.retryBootstrap})]})]}),h&&se&&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:se})]}),N&&t.jsx("div",{className:"mb-2 overflow-hidden border border-hairline bg-surface",children:t.jsx(tt,{agentId:e.id,mode:"preview",maxLines:6,interactive:!1})}),xe&&t.jsx("div",{className:Fe,role:G?"button":void 0,tabIndex:G?0:void 0,"aria-label":G?d.agents.activateTerminal(e.id):void 0,onClick:qe,onKeyDown:$e,children:T?t.jsx("div",{className:"flex h-full items-center justify-center px-3 text-sm text-og-500",children:B}):be?P?t.jsx(tt,{agentId:e.id,mode:"full",interactive:!0,autoFocus:!0}):t.jsx(tt,{agentId:e.id,mode:"preview",interactive:!1}):t.jsx(tt,{agentId:e.id,mode:"full",interactive:!0,autoFocus:!1,deferFullUntilFocus:!0})}),l&&t.jsx("div",{className:"mb-2 rounded-md border border-accent/25 bg-accent-soft/60 px-2.5 py-1.5 text-xs text-accent",children:d.agents.pendingRestartNotice}),t.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[t.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2 overflow-x-auto scrollbar-none",children:[T?t.jsx("span",{className:"shrink-0 cursor-not-allowed text-sm text-og-400",title:B,children:d.agents.terminal}):t.jsx(Le,{to:`/terminal/${e.id}`,className:"btn-secondary shrink-0",children:d.agents.terminal}),!l&&e.runtimeStatus==="working"&&t.jsx("button",{onClick:he,disabled:x,className:"btn-ghost shrink-0",children:x?d.agents.stopping:d.agents.stop}),J&&(H==="resume"||H==="restart-runtime")&&t.jsx("button",{type:"button",onClick:D,disabled:z,title:ge?d.agents.resumeGreetingButtonTitle:d.agents.resumeDefaultButtonTitle,className:"btn-primary shrink-0",children:z?d.agents.resuming:H==="restart-runtime"?d.agents.restartRuntime:d.agents.resume}),J&&H==="terminal"&&t.jsx(Le,{to:`/terminal/${e.id}`,className:"btn-primary shrink-0",children:d.agents.openTerminalAction}),J&&H==="task"&&se&&t.jsx(Le,{to:Ee(n,se),className:"btn-primary shrink-0",children:d.agents.openTaskActions}),J&&H==="delete-agent"&&t.jsx("button",{type:"button",onClick:()=>void Q(),disabled:b,className:"btn-primary shrink-0",children:b?d.common.deleting:d.agents.deleteToRecover})]}),t.jsx(ln,{ariaLabel:d.agents.actionsMenu(e.id),className:"shrink-0",placement:"up",autoFocusFirstItem:!0,disabled:b,children:U=>t.jsxs(t.Fragment,{children:[t.jsx(Ne,{onClick:()=>{U(),Y(!0)},disabled:I||F||b,title:d.agents.agentPetMenuItemTitle,children:"Agent Pet"}),t.jsx(Ne,{onClick:()=>{U(),A()},disabled:I||F||b,title:d.agents.compactMenuItemTitle,children:I?d.agents.compacting:d.agents.compact}),t.jsx(Ne,{onClick:()=>{U(),L()},disabled:F||I||b,title:d.agents.clearMenuItemTitle,children:F?d.agents.clearing:d.agents.clear}),t.jsx(Ne,{onClick:()=>{U(),Q()},disabled:b||I||F,children:b?d.common.deleting:d.common.delete})]})})]}),w&&t.jsx("div",{className:"mt-1.5 break-words text-xs text-accent",children:w}),k&&t.jsx("div",{className:"mt-1.5 break-words text-xs text-accent",children:k}),ne&&t.jsx(ca,{agentId:e.id,currentPetId:e.petId??null,onClose:()=>Y(!1)})]})}const Vt="baxian:terminal-activated";function Ts({coordinateAcrossInstances:e=!0}={}){const n=o.useId(),[s,r]=o.useState(null);o.useEffect(()=>{if(s===null)return;const i=h=>{h.composedPath().some(p=>p instanceof Element&&p.hasAttribute("data-agent-card"))||r(null)},l=h=>{if(h.key!=="Escape")return;const m=document.activeElement;m instanceof Element&&m.closest("[data-agent-card]")||r(null)},c=h=>{const m=h.detail;(m==null?void 0:m.ownerId)!==n&&r(null)};return document.addEventListener("click",i),document.addEventListener("keydown",l),e&&document.addEventListener(Vt,c),()=>{document.removeEventListener("click",i),document.removeEventListener("keydown",l),e&&document.removeEventListener(Vt,c)}},[s,e,n]);const a=o.useCallback(i=>{r(i),e&&document.dispatchEvent(new CustomEvent(Vt,{detail:{ownerId:n}}))},[e,n]);return{activeAgentId:s,activateAgentCard:a}}function Ns({team:e,projectId:n,agentsById:s,agentsLoaded:r,agentsError:a=!1,tasks:i,onDeleted:l,terminalMode:c="activity-preview"}){const h=q(),m=e.find(v=>v.role==="dev")??e[0],f=i.filter(v=>ba(v,m==null?void 0:m.id)),p=m?i.filter(v=>va(v,n,m.id)).sort((v,b)=>v.createdAt.localeCompare(b.createdAt)):[],u=`Agent Team ${e.map(v=>v.id).join(" / ")}`,d=De(),x=c==="embedded-full",{activeAgentId:y,activateAgentCard:w}=Ts({coordinateAcrossInstances:x}),C=c==="embedded-full"?e.length<=1?"lg:grid-cols-1":e.length===2?"lg:grid-cols-2":e.length===3?"lg:grid-cols-3":"lg:grid-cols-4":"sm:grid-cols-2",S=!!m&&p.length>0,R=f.length===0&&!S;return t.jsxs("div",{role:"group","aria-label":u,className:"min-w-0",children:[S&&m&&t.jsx(xa,{tasks:p,devId:m.id,agentsById:s,label:u}),f.length>0&&t.jsx("div",{className:"card mb-2 max-h-28 overflow-y-auto divide-y divide-hairline",children:f.map(v=>{const b=Me(v.phase)?v.specReviewRound??0:v.reviewRound;return t.jsxs("button",{type:"button",onClick:()=>d(Ee(v.projectId,v.id)),className:"flex w-full items-center gap-3 px-3 py-2 text-left text-sm transition-colors hover:bg-og-50/60",children:[t.jsxs("div",{className:"min-w-0 flex-1 flex items-center gap-2",children:[t.jsx("span",{className:"shrink-0 font-mono text-xs text-og-500",title:v.id,children:vn(v.id)}),t.jsx("span",{className:"truncate text-og-1000",children:v.title})]}),t.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[b>0&&t.jsx("span",{className:"shrink-0 text-xs text-og-500",children:h.agents.round(b)}),t.jsx(bn,{task:v,className:"shrink-0"})]})]},v.id)})}),R&&t.jsx("div",{className:"mb-2 rounded-lg border border-hairline bg-surface px-3 py-2 text-sm text-og-400","aria-label":h.agents.noActiveTaskAriaLabel(u),children:h.agents.noActiveTask}),t.jsx("div",{className:`grid grid-cols-1 ${C} gap-4`,children:e.map(v=>{var E;const b=s.get(v.id),j=b??{id:v.id,projectId:n,runtimeStatus:"unknown",tmuxSessionStatus:"unknown",stale:!0},k=((E=j.binding)==null?void 0:E.taskId)===void 0?void 0:i.find(I=>{var _;return I.id===((_=j.binding)==null?void 0:_.taskId)});return t.jsx(js,{agent:j,projectId:n,role:v.role,runtime:v.runtime,model:v.model,pendingRestart:r&&!b,terminalLoading:!r&&!b&&!a,onDeleted:l,showTaskBinding:!1,terminalMode:c,task:k,...x?{active:y===v.id,onActivate:()=>w(v.id)}:{}},v.id)})})]})}function ga(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 xa({tasks:e,devId:n,agentsById:s,label:r}){const a=q(),{show:i}=ke(),l=De(),[c,h]=o.useState(null),m=async(f,p)=>{h(f);try{await $.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{h(null)}};return t.jsx("div",{role:"group",className:"card mb-2 max-h-28 overflow-y-auto divide-y divide-hairline","aria-label":`${r} claimable tasks for ${n}`,children:e.map(f=>{const p=f.preferredAgentId||n,u=ga(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(Ee(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:vn(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 m(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 ba(e,n){return!n||!cn.has(e.status)?!1:e.devAgentId===n}function va(e,n,s){return e.projectId!==n||e.status!=="pending"?!1:e.preferredAgentId===s||e.preferredAgentId===""}const fe="w-full rounded-md border border-og-100 bg-surface px-2.5 py-1.5 text-sm text-og-800 placeholder:text-og-400 focus:border-accent focus:outline-none focus:ring-[3px] focus:ring-accent-soft disabled:cursor-not-allowed disabled:opacity-50",ue="mb-1.5 block text-xs font-medium text-og-700",Ct="mt-1 text-xs text-accent",We="mt-1 text-xs text-og-500",Ie="h-3.5 w-3.5 accent-accent",ya=/^[a-z][a-z0-9-]{1,31}$/;function wa({open:e,onClose:n,onCreated:s}){const r=q(),[a,i]=o.useState(""),[l,c]=o.useState(""),[h,m]=o.useState(null),[f,p]=o.useState("human"),[u,d]=o.useState(!1),[x,y]=o.useState(null),[w,C]=o.useState({}),[S,R]=o.useState(new Set),v=o.useRef(0),{show:b}=ke(),{flagDirty:j}=$t();o.useEffect(()=>{if(!e)return;v.current+=1;const _=v.current;i(""),c(""),m(null),p("human"),y(null),C({}),R(new Set),$.config.get().then(F=>{_===v.current&&R(new Set(F.project.map(te=>te.id)))}).catch(F=>{_===v.current&&y(r.common.loadFailed(F instanceof Error?F.message:String(F)))})},[e]);const k=()=>{u||n()},E=()=>{const _={};return a?ya.test(a)?S.has(a)&&(_.id=r.createProject.idTakenError):_.id=r.common.idFormatError:_.id=r.createProject.required,l.trim()||(_.repo=r.createProject.required),C(_),Object.keys(_).length===0},I=async _=>{if(_.preventDefault(),!!E()){d(!0),y(null);try{const F=await $.projects.create({id:a,repo:l.trim(),merge:h,...f?{specApproval:f}:{}});F.restartRequired&&j(),b({kind:"success",title:r.createProject.createdToastTitle(F.project.id)}),s(F.project.id)}catch(F){y(F instanceof Error?F.message:String(F))}finally{d(!1)}}};return t.jsx(Se,{open:e,onClose:k,title:r.createProject.title,size:"md",footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:k,disabled:u,className:"btn-secondary",children:r.common.cancel}),t.jsx("button",{type:"submit",form:"create-project-form",disabled:u,className:"btn-primary",children:u?r.common.creating:r.common.create})]}),children:t.jsxs("form",{id:"create-project-form",onSubmit:I,className:"space-y-3",children:[x&&t.jsx("div",{className:"whitespace-pre-line rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-sm text-accent",children:x}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"proj-id",children:r.createProject.idLabel}),t.jsx("input",{id:"proj-id",type:"text",value:a,onChange:_=>i(_.target.value),className:fe,placeholder:"baxian",disabled:u}),w.id&&t.jsx("div",{className:Ct,children:w.id})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"proj-repo",children:r.createProject.repoLabel}),t.jsx("input",{id:"proj-repo",type:"text",value:l,onChange:_=>c(_.target.value),className:fe,placeholder:"https://github.com/baxian-ai/baxian.git",disabled:u}),w.repo&&t.jsx("div",{className:Ct,children:w.repo})]}),t.jsxs("div",{children:[t.jsx("span",{className:ue,children:r.createProject.mergeStrategyLabel}),t.jsxs("label",{className:"mb-1 flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"merge",checked:h===null,onChange:()=>m(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:h==="auto",onChange:()=>m("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 En=/^[a-z][a-z0-9-]{1,31}$/,ka=500,Kt={id:"",mode:"local",host:"",runtime:"",workdir:"",yolo:!0,model:"",addDirs:""};function ja(e){return e.alias?e.alias:`${e.user?`${e.user}@`:""}${e.hostname}${e.port!=null?`:${e.port}`:""}`}function Ss({open:e,onClose:n,projectId:s,onCreated:r}){var P,T,B,M,he,ie;const a=q(),[i,l]=o.useState(Kt),[c,h]=o.useState(null),[m,f]=o.useState([]),[p,u]=o.useState(new Set),[d,x]=o.useState(null),[y,w]=o.useState(!1),[C,S]=o.useState(!1),[R,v]=o.useState(null),[b,j]=o.useState(!1),[k,E]=o.useState(null),[I,_]=o.useState(!1),F=o.useRef(null),te=o.useRef(null),z=o.useRef(0),K=o.useRef(0),{show:re}=ke(),{flagDirty:Z}=$t();o.useEffect(()=>{if(!e)return;K.current+=1;const D=K.current;l(Kt),h(null),f([]),u(new Set),x(null),w(!1),S(!1),v(null),z.current+=1,E(null),_(!1),$.config.get().then(A=>{if(D!==K.current)return;f(A.host??[]);const L=new Set;A.project.forEach(Q=>Q.agent.forEach(G=>G.forEach(X=>L.add(X.id)))),u(L)}).catch(()=>{})},[e,s]);const ne=()=>{b||n()},Y=o.useCallback(()=>{F.current&&F.current.abort();const D=new AbortController;F.current=D,w(!0),E(null);const A=i.mode==="remote"?{hostId:i.host}:{};$.agents.probe(i.mode,A,{signal:D.signal}).then(L=>{D.signal.aborted||(x(L),E(null))}).catch(L=>{D.signal.aborted||(x(null),E(L instanceof Error?L.message:String(L)))}).finally(()=>{F.current===D&&w(!1)})},[i.mode,i.host]);o.useEffect(()=>{if(e&&(x(null),v(null),S(!1),z.current+=1,F.current&&F.current.abort(),!(i.mode==="remote"&&!i.host)))return te.current&&clearTimeout(te.current),te.current=setTimeout(Y,ka),()=>{te.current&&clearTimeout(te.current)}},[e,i.mode,i.host,c,Y]),o.useEffect(()=>{e||F.current&&F.current.abort()},[e]),o.useEffect(()=>()=>{F.current&&F.current.abort(),te.current&&clearTimeout(te.current)},[]);const se=()=>{if(C)return;const D=z.current;S(!0),v(null);const A=i.mode==="remote"?{hostId:i.host}:{};$.agents.installTmux(i.mode,A).then(L=>{z.current===D&&(v({ok:L.ok,message:L.message}),S(!1),L.ok&&Y())}).catch(L=>{z.current===D&&(v({ok:!1,message:L instanceof Error?L.message:String(L)}),S(!1))})},ee=c?"qa":"dev",J=En.test(i.id)&&!p.has(i.id)&&i.id!==(c==null?void 0:c.agent.id),me=i.mode==="local"||i.mode==="remote"&&i.host!=="",ge=i.runtime!==""&&!!((P=d==null?void 0:d.runtimes[i.runtime])!=null&&P.ok),H=!!(d!=null&&d.tmux.ok),le=i.mode==="local"||!!((T=d==null?void 0:d.ssh)!=null&&T.ok),ce=!b&&J&&me&&ge&&H&&le,ae=async D=>{var Q,G;if(D.preventDefault(),!ce)return;E(null);const A=i.addDirs.split(`
9
9
  `).map(X=>X.trim()).filter(X=>X.length>0),L={id:i.id,role:ee,runtime:i.runtime,mode:i.mode,...i.mode==="remote"?{host:i.host}:{},...i.workdir?{workdir:i.workdir}:{},yolo:i.yolo,...i.model.trim()?{model:i.model.trim()}:{},...A.length>0?{addDirs:A}:{}};if(!c){h({agent:L,form:i}),l(Kt),x(null),v(null),_(!1);return}j(!0);try{const X=await $.projects.addAgentTeam(s,{agents:[c.agent,L]});X.restartRequired&&Z(),re({kind:(Q=X.warnings)!=null&&Q.length?"warn":"success",title:a.createAgent.addedToastTitle(X.agents.find(we=>we.role==="dev").id,X.agents.find(we=>we.role==="qa").id,s),...(G=X.warnings)!=null&&G.length?{body:X.warnings.join(`
10
- `)}:{}}),r(),n()}catch(X){E(X instanceof Error?X.message:String(X))}finally{j(!1)}},ye=()=>{!c||b||(l(c.form),h(null),x(null),v(null),_(!1))},N=({rt:D})=>{if(i.mode==="remote"&&!i.host)return t.jsx("span",{className:"ml-2 text-xs text-og-400",children:a.createAgent.selectHostFirstHint});if(y)return t.jsx("span",{className:"ml-2 text-xs text-og-400",children:a.createAgent.probingLabel});if(!d)return t.jsx("span",{className:"ml-2 text-xs text-og-400",children:"?"});const L=d.runtimes[D];return L?L.ok?t.jsxs("span",{className:"ml-2 text-xs text-probe-ok",children:["✓ ",L.path??""]}):t.jsxs("span",{className:"ml-2 text-xs text-accent",title:L.message,children:["⨯ ",L.message]}):t.jsx("span",{className:"ml-2 text-xs text-og-400",children:"?"})},xe=()=>{var A;if(i.mode==="remote"&&!i.host)return null;if(y&&!C)return t.jsx("div",{className:"text-xs text-og-400",children:a.createAgent.tmuxProbingLabel});if(!d)return null;if(d.tmux.ok)return t.jsxs("div",{className:"text-xs text-probe-ok",children:["tmux: ✓ ",d.tmux.path??""]});const D=i.mode==="local"||!!((A=d.ssh)!=null&&A.ok);return t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"text-xs text-accent",children:["tmux: ⨯ ",d.tmux.message,D&&t.jsx("button",{type:"button",onClick:se,className:"ml-2 text-accent underline transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",disabled:C||b,children:C?a.common.installing:a.common.oneClickInstall})]}),C&&t.jsx("div",{className:"text-xs text-og-500",children:a.common.installingTmuxNotice}),!C&&R&&t.jsxs("div",{className:`break-all text-xs ${R.ok?"text-probe-ok":"text-accent"}`,children:[R.ok?"✓ ":"⨯ ",R.message]})]})},be=()=>i.mode!=="remote"||!i.host||!(d!=null&&d.ssh)?null:d.ssh.ok?t.jsxs("div",{className:"text-xs text-probe-ok",children:["SSH: ✓ ",d.ssh.message]}):t.jsxs("div",{className:"text-xs text-accent",children:["SSH: ⨯ ",d.ssh.message]});return t.jsx(Se,{open:e,onClose:ne,title:a.createAgent.modalTitle(s),size:"lg",footer:t.jsxs(t.Fragment,{children:[c&&t.jsx("button",{type:"button",onClick:ye,disabled:b,className:"btn-secondary",children:a.common.back}),t.jsx("button",{type:"button",onClick:ne,disabled:b,className:"btn-secondary",children:a.common.cancel}),t.jsx("button",{type:"submit",form:"create-agent-form",disabled:!ce,className:"btn-primary",children:b?a.createAgent.submitting:c?a.createAgent.submitLabel:a.createAgent.continueLabel})]}),children:t.jsxs("form",{id:"create-agent-form",onSubmit:ae,className:"space-y-3",children:[k&&t.jsx("div",{className:"whitespace-pre-line rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-sm text-accent",children:k}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"agent-id",children:"Agent ID"}),t.jsx("input",{id:"agent-id",type:"text",value:i.id,onChange:D=>l({...i,id:D.target.value}),className:fe,placeholder:a.createAgent.idPlaceholder(s,ee),disabled:b}),i.id&&!En.test(i.id)&&t.jsx("div",{className:Ct,children:a.common.idFormatError}),i.id&&(p.has(i.id)||i.id===(c==null?void 0:c.agent.id))&&t.jsx("div",{className:Ct,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:ee==="dev"?a.createAgent.devStepLabel:a.createAgent.qaStepLabel}),c&&t.jsx("div",{className:We,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:b}),t.jsx("span",{className:"text-sm text-og-800",children:a.createAgent.localModeLabel})]}),t.jsxs("label",{className:"inline-flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"mode",checked:i.mode==="remote",className:Ie,onChange:()=>l({...i,mode:"remote"}),disabled:b}),t.jsx("span",{className:"text-sm text-og-800",children:a.createAgent.remoteModeLabel})]})]}),i.mode==="remote"&&t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"host",children:"Host"}),m.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:D=>l({...i,host:D.target.value}),className:fe,disabled:b,children:[t.jsx("option",{value:"",children:a.createAgent.selectHostPlaceholder}),m.map(D=>t.jsx("option",{value:D.id,children:ja(D)},D.id))]}),t.jsx("div",{className:We,children:a.createAgent.sshConfigHint})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"mb-1.5 flex items-center justify-between",children:[t.jsx("span",{className:"text-xs font-medium text-og-700",children:a.createAgent.runtimeLabel}),t.jsx("button",{type:"button",onClick:Y,className:"text-xs text-accent transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",disabled:b||y||i.mode==="remote"&&!i.host,children:a.createAgent.reprobeButton})]}),t.jsxs("label",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"runtime",checked:i.runtime==="claude-code",className:Ie,onChange:()=>l({...i,runtime:"claude-code"}),disabled:b||(d?!((B=d.runtimes["claude-code"])!=null&&B.ok):!1)}),t.jsx("span",{className:"text-sm text-og-800",children:"Claude Code"}),t.jsx(N,{rt:"claude-code"})]}),t.jsxs("label",{className:"mt-1 flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"runtime",checked:i.runtime==="codex",className:Ie,onChange:()=>l({...i,runtime:"codex"}),disabled:b||(d?!((M=d.runtimes.codex)!=null&&M.ok):!1)}),t.jsx("span",{className:"text-sm text-og-800",children:"Codex"}),t.jsx(N,{rt:"codex"})]}),t.jsxs("label",{className:"mt-1 flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"runtime",checked:i.runtime==="opencode",className:Ie,onChange:()=>l({...i,runtime:"opencode"}),disabled:b||(d?!((he=d.runtimes.opencode)!=null&&he.ok):!1)}),t.jsx("span",{className:"text-sm text-og-800",children:"OpenCode"}),t.jsx(N,{rt:"opencode"})]}),t.jsxs("label",{className:"mt-1 flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"runtime",checked:i.runtime==="qodercli",className:Ie,onChange:()=>l({...i,runtime:"qodercli"}),disabled:b||(d?!((ie=d.runtimes.qodercli)!=null&&ie.ok):!1)}),t.jsx("span",{className:"text-sm text-og-800",children:"Qoder CLI"}),t.jsx(N,{rt:"qodercli"})]}),t.jsx("div",{className:"mt-2",children:t.jsx(xe,{})}),t.jsx("div",{children:t.jsx(be,{})})]}),t.jsxs("div",{children:[t.jsxs("button",{type:"button",onClick:()=>_(D=>!D),"aria-expanded":I,"aria-controls":I?"advanced-options":void 0,className:"flex w-full items-center justify-between rounded-md px-1 py-1.5 text-left text-xs font-medium text-og-700 transition-colors hover:bg-og-50",children:[t.jsx("span",{children:a.createAgent.advancedOptionsLabel}),t.jsx("span",{className:"text-og-400",children:I?a.createAgent.collapseLabel:a.createAgent.expandLabel})]}),I&&t.jsxs("div",{id:"advanced-options",className:"mt-3 space-y-3",children:[t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"workdir",children:a.createAgent.workdirLabel}),t.jsx("input",{id:"workdir",type:"text",value:i.workdir,onChange:D=>l({...i,workdir:D.target.value}),className:fe,placeholder:a.createAgent.workdirPlaceholder,disabled:b}),t.jsx("div",{className:We,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:D=>l({...i,model:D.target.value}),className:fe,placeholder:i.runtime==="codex"?a.createAgent.modelPlaceholderCodex:a.createAgent.modelPlaceholderOther,disabled:b}),t.jsx("div",{className:We,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:D=>l({...i,addDirs:D.target.value}),className:`${fe} font-mono text-xs`,rows:3,placeholder:a.createAgent.addDirsPlaceholder,disabled:b}),t.jsx("div",{className:We,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:D=>l({...i,yolo:D.target.checked}),disabled:b}),t.jsxs("div",{className:"text-sm text-og-800",children:[t.jsx("div",{className:"font-medium",children:a.createAgent.yoloTitle}),t.jsxs("div",{className:"mt-1 text-xs text-accent",children:[a.createAgent.yoloBodyLead,t.jsx("code",{children:ar[i.runtime||"claude-code"]}),a.createAgent.yoloBodyTrail]})]})]})})]})})}const Dn=200,$n=16e3,Ta="baxian.draft.createTask:";function sn(e){return`${Ta}${e??"*"}`}function In(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:"",h=typeof r.updatedAt=="number"?r.updatedAt:void 0;return!a.trim()&&!i.trim()?null:{title:a,description:i,projectId:l,preferredAgentId:c,updatedAt:h}}catch{return null}}function Na(e,n){const s=!n.title.trim()&&!n.description.trim();try{s?localStorage.removeItem(e):localStorage.setItem(e,JSON.stringify({...n,updatedAt:Date.now()}))}catch{}}function Bn(e){try{localStorage.removeItem(e)}catch{}}function Sa(e){const n=sn(e),s=In(n);if(!e)return s;const r=sn(void 0),a=In(r);if(!a||a.projectId!==e)return s;const i=!s||(a.updatedAt??0)>(s.updatedAt??0);if(i)try{localStorage.setItem(n,JSON.stringify(a))}catch{return a}try{localStorage.removeItem(r)}catch{}return i?a:s}const Mn="mt-1 text-right text-xs text-og-400",Ra=Math.floor(Dt/1024/1024);function yn(e){const n=q(),s=e.mode==="edit",{show:r}=ke(),a=s?e.task.projectId:e.projectId,i=s?e.task.title:"",l=s?e.task.description:"",c=s?e.task.preferredAgentId:"",[h,m]=o.useState([]),[f,p]=o.useState([]),[u,d]=o.useState(a??""),[x,y]=o.useState(c),[w,C]=o.useState(i),[S,R]=o.useState(l),[v,b]=o.useState([]),j=o.useRef(null),[k,E]=o.useState(!1),[I,_]=o.useState(null),[F,te]=o.useState(!1),z=o.useRef(0),K=o.useRef(0),re=o.useRef(0),Z=o.useRef(new Set),ne=s?null:sn(a);o.useEffect(()=>{if(!e.open)return;z.current+=1,K.current+=1;const A=z.current;m([]),p([]),Z.current=new Set;const L=ne?Sa(a):null;L&&Z.current.add(L.projectId),d(a??(L==null?void 0:L.projectId)??""),y((L==null?void 0:L.preferredAgentId)||c),C((L==null?void 0:L.title)||i),R((L==null?void 0:L.description)||l),te(L!==null),_(null),E(!1),b([]),Promise.all([$.projects.list(),$.agents.list()]).then(([Q,G])=>{A===z.current&&(m(Q),p(G))}).catch(Q=>{A===z.current&&_(Q instanceof Error?Q.message:String(Q))})},[e.open,a,i,l,c,ne]),o.useEffect(()=>{if(!(!e.open||!ne)){if(re.current!==K.current){re.current=K.current;return}Na(ne,{title:w,description:S,projectId:u,preferredAgentId:x})}},[e.open,ne,w,S,u,x]);const Y=o.useMemo(()=>h.find(A=>A.id===u)??null,[h,u]),se=o.useMemo(()=>Y?Y.agent.flat().filter(A=>A.role==="dev"):[],[Y]),ee=o.useMemo(()=>new Set(f.map(A=>A.id)),[f]),J=o.useMemo(()=>se.filter(A=>ee.has(A.id)),[se,ee]),me=o.useMemo(()=>se.filter(A=>!ee.has(A.id)),[se,ee]);o.useEffect(()=>{s||Y!==null&&x!==""&&!J.find(A=>A.id===x)&&y("")},[Y,J,x,s]),o.useEffect(()=>{if(s||!Y)return;const A=J.find(L=>L.role==="dev");A&&(Z.current.has(Y.id)||(Z.current.add(Y.id),y(L=>L===""?A.id:L)))},[s,Y,J]);const ge=!s||J.find(A=>A.id===x),H=s&&!ge&&!!x,le=H&&me.some(A=>A.id===x),ce=le?n.createTask.noDevPendingRestartHint(x):H?n.createTask.noDevNotInRuntimeHint(x):!u||J.length>0?null:me.length>0?n.createTask.noDevGlobalPendingRestartHint:null,ae=w.trim(),ye=S.trim(),xe=!!u&&ae.length>0&&!k,be=()=>{k||e.onClose()},P=()=>{ne&&(Bn(ne),d(a??""),y(c),C(i),R(l),_(null),te(!1))},T=async A=>{var L,Q;if(A.preventDefault(),!!xe){E(!0),_(null);try{if(e.mode==="edit"){const G=await $.tasks.update(e.task.id,{title:ae,description:ye,preferredAgentId:x});r({kind:"success",title:n.createTask.updatedToastTitle}),(L=e.onUpdated)==null||L.call(e,G),e.onClose()}else{const G=v.length?await Promise.all(v.map(async we=>({dataBase64:await Zt(we),filename:we.name}))):void 0,X=await $.tasks.create({projectId:u,title:ae,description:ye,preferredAgentId:x,...G?{images:G}:{}});ne&&Bn(ne),r({kind:"success",title:n.createTask.createdToastTitle}),(Q=e.onCreated)==null||Q.call(e,X),e.onClose()}}catch(G){_(G instanceof Error?G.message:String(G))}finally{E(!1)}}},B=A=>{const L=Array.from(A.target.files??[]);if(A.target.value="",L.length===0)return;const Q=L.filter(G=>G.size>Dt?(r({kind:"error",title:n.createTask.imageTooLargeToastTitle,body:n.createTask.imageTooLargeToastBody(G.name,Ra)}),!1):!0);b(G=>(G.length+Q.length>gt&&r({kind:"warn",title:n.createTask.tooManyImagesToastTitle(gt)}),[...G,...Q].slice(0,gt)))},M=A=>b(L=>L.filter((Q,G)=>G!==A)),he=s?n.createTask.titleEdit:n.createTask.titleCreate,ie=s?k?n.common.saving:n.common.save:k?n.common.creating:n.common.create,D=!s&&!a;return t.jsx(Se,{open:e.open,onClose:be,title:he,size:"md",dismissOnBackdrop:!1,footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:be,disabled:k,className:"btn-secondary",children:n.common.cancel}),t.jsx("button",{type:"submit",form:"create-task-form",disabled:!xe,className:"btn-primary",children:ie})]}),children:t.jsxs("form",{id:"create-task-form",onSubmit:T,className:"space-y-3",children:[!s&&F&&t.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-md border border-accent-soft bg-accent-soft/30 px-3 py-2 text-xs text-accent",children:[t.jsx("span",{children:n.createTask.draftRestoredNotice}),t.jsx("button",{type:"button",onClick:P,className:"shrink-0 underline hover:text-accent-hover",children:n.createTask.discardDraftButton})]}),I&&t.jsx("div",{className:"rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-sm text-accent",children:I}),D&&t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"task-project",children:"Project"}),t.jsxs("select",{id:"task-project",value:u,onChange:A=>d(A.target.value),className:fe,disabled:k,required:!0,children:[t.jsx("option",{value:"",disabled:!0,children:n.createTask.selectProjectPlaceholder}),h.map(A=>t.jsx("option",{value:A.id,children:A.id},A.id))]})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"task-dev",children:n.createTask.targetAgentLabel}),t.jsxs("select",{id:"task-dev",value:x,onChange:A=>y(A.target.value),className:fe,disabled:k,children:[t.jsx("option",{value:"",children:n.createTask.notAssignedOption}),H&&t.jsxs("option",{value:x,children:[x," ",le?n.createTask.pendingRestartSuffix:n.createTask.notInRuntimeSuffix]}),J.map(A=>t.jsx("option",{value:A.id,children:A.id},A.id))]}),ce&&t.jsx("div",{className:"mt-1 text-xs text-accent",children:ce})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"task-title",children:"Title"}),t.jsx("input",{id:"task-title",type:"text",value:w,onChange:A=>C(A.target.value),maxLength:Dn,className:fe,placeholder:n.createTask.titlePlaceholder,disabled:k,required:!0}),t.jsxs("div",{className:Mn,children:[w.length," / ",Dn]})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"task-description",children:n.createTask.descriptionLabel}),t.jsx("textarea",{id:"task-description",value:S,onChange:A=>R(A.target.value),maxLength:$n,rows:8,className:`${fe} font-mono text-xs`,placeholder:n.createTask.descriptionPlaceholder,disabled:k}),t.jsxs("div",{className:Mn,children:[S.length," / ",$n]})]}),!s&&t.jsxs("div",{children:[t.jsx("label",{className:ue,children:n.createTask.imagesLabel}),t.jsx("button",{type:"button",onClick:()=>{var A;return(A=j.current)==null?void 0:A.click()},disabled:k||v.length>=gt,className:"btn-secondary",children:n.createTask.addImagesButton}),t.jsx("input",{ref:j,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:B}),v.length>0&&t.jsx("ul",{className:"mt-2 space-y-1",children:v.map((A,L)=>t.jsxs("li",{className:"flex items-center justify-between rounded-md border border-og-100 bg-surface px-2.5 py-1.5",children:[t.jsx("span",{title:A.name,className:"truncate text-xs text-og-700",children:A.name}),t.jsx("button",{type:"button","aria-label":n.createTask.removeImageAriaLabel(A.name),onClick:()=>M(L),disabled:k,className:"ml-2 shrink-0 text-og-400 transition-colors",children:"✕"})]},`${A.name}-${L}`))})]})]})})}const Fn="***",Yt={hostname:"",port:"",alias:"",user:"",password:""};function Ca(e){return e.alias?e.alias:`${e.user?`${e.user}@`:""}${e.hostname}${e.port!=null?`:${e.port}`:""}`}function Aa({open:e,onClose:n}){var be;const s=q(),[r,a]=o.useState([]),[i,l]=o.useState("list"),[c,h]=o.useState(null),[m,f]=o.useState(null),[p,u]=o.useState(!1),[d,x]=o.useState(!1),[y,w]=o.useState(Yt),[C,S]=o.useState(null),[R,v]=o.useState(!1),[b,j]=o.useState(!1),[k,E]=o.useState(null),[I,_]=o.useState(!1),[F,te]=o.useState(null),z=o.useRef(0),K=o.useRef(null),{show:re}=ke(),Z=o.useCallback(()=>{$.hosts.list().then(a).catch(P=>S(P instanceof Error?P.message:String(P)))},[]);o.useEffect(()=>{if(!e){K.current&&K.current.abort();return}l("list"),h(null),f(null),w(Yt),S(null),Z()},[e,Z]),o.useEffect(()=>{z.current+=1,K.current&&K.current.abort(),j(!1),E(null),_(!1),te(null)},[y.hostname,y.user,y.port,y.password,d,i]),o.useEffect(()=>()=>{K.current&&K.current.abort()},[]);const ne=()=>{h(null),f(null),u(!1),x(!1),w(Yt),S(null),l("form")},Y=P=>{h(P.id??null),f(P),u(P.password===Fn),x(!1),w({hostname:P.hostname,port:P.port!=null?String(P.port):"",alias:P.alias??"",user:P.user??"",password:""}),S(null),l("form")},se=()=>{const P={hostname:y.hostname.trim()};return c?(P.port=y.port.trim()?Number(y.port):null,P.alias=y.alias.trim(),P.user=y.user.trim()):(y.port.trim()&&(P.port=Number(y.port)),y.alias.trim()&&(P.alias=y.alias.trim()),y.user.trim()&&(P.user=y.user.trim())),c&&d?P.password="":y.password&&(P.password=y.password),P},ee=y.port.trim(),J=ee===""||/^\d+$/.test(ee)&&Number(ee)>0&&Number(ee)<=65535,me=y.hostname.trim().length>0&&J,ge=!!m&&y.hostname.trim()===m.hostname&&y.user.trim()===(m.user??"")&&y.port.trim()===(m.port!=null?String(m.port):""),H=()=>c&&ge&&!y.password&&!d?{hostId:c}:{host:{hostname:y.hostname.trim(),...y.user.trim()?{user:y.user.trim()}:{},...ee?{port:Number(ee)}:{},...!d&&y.password?{password:y.password}:{}}},le=async()=>{if(!me||b)return;K.current&&K.current.abort();const P=new AbortController;K.current=P;const T=z.current;j(!0),E(null),te(null),S(null);try{const B=await $.agents.probe("remote",H(),{signal:P.signal});if(P.signal.aborted||z.current!==T)return;E(B)}catch(B){if(P.signal.aborted||z.current!==T)return;S(B instanceof Error?B.message:String(B))}finally{z.current===T&&j(!1)}},ce=async()=>{if(I)return;const P=z.current;_(!0),te(null),S(null);try{const T=await $.agents.installTmux("remote",H());if(z.current!==P)return;te({ok:T.ok,message:T.message}),E(B=>B&&{...B,tmux:T.tmux})}catch(T){if(z.current!==P)return;S(T instanceof Error?T.message:String(T))}finally{z.current===P&&_(!1)}},ae=async P=>{if(P.preventDefault(),!(!me||R)){v(!0),S(null);try{if(c)await $.hosts.update(c,se()),re({kind:"success",title:s.hostMgmt.updatedToastTitle(c)});else{const T=await $.hosts.create(se());re({kind:"success",title:s.hostMgmt.createdToastTitle(T.host.id)})}Z(),l("list")}catch(T){S(T instanceof Error?T.message:String(T))}finally{v(!1)}}},ye=async P=>{S(null);try{await $.hosts.delete(P.id),re({kind:"success",title:s.hostMgmt.deletedToastTitle(P.id)}),Z()}catch(T){S(T instanceof Error?T.message:String(T))}},N=t.jsx("button",{type:"button",onClick:n,className:"btn-secondary",children:s.common.close}),xe=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:()=>l("list"),disabled:R,className:"btn-secondary",children:s.common.backText}),t.jsx("button",{type:"submit",form:"host-form",disabled:!me||R,className:"btn-primary",children:R?s.common.saving:s.common.save})]});return t.jsxs(Se,{open:e,onClose:n,title:s.hostMgmt.title,size:"md",footer:i==="list"?N:xe,children:[C&&t.jsx("div",{className:"mb-3 whitespace-pre-line rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-sm text-accent",children:C}),i==="list"?t.jsxs("div",{className:"space-y-3",children:[r.length===0?t.jsx("p",{className:"text-sm text-og-500",children:s.hostMgmt.emptyState}):t.jsx("ul",{className:"space-y-1.5",children:r.map(P=>t.jsxs("li",{className:"flex items-center justify-between gap-3 rounded-md border border-og-100 px-3 py-2",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"truncate text-sm font-medium text-og-800",children:Ca(P)}),t.jsxs("div",{className:"truncate text-xs text-og-500",children:[(P.user?`${P.user}@`:"")+P.hostname,P.port!=null?`:${P.port}`:"",P.password===Fn?s.hostMgmt.passwordSavedIndicator:""]})]}),t.jsxs("div",{className:"flex shrink-0 gap-2",children:[t.jsx("button",{type:"button",onClick:()=>Y(P),className:"text-xs text-accent transition-colors hover:text-accent-hover",children:s.common.edit}),t.jsx("button",{type:"button",onClick:()=>ye(P),className:"text-xs text-accent transition-colors hover:opacity-80",children:s.common.delete})]})]},P.id))}),t.jsx("button",{type:"button",onClick:ne,className:"btn-secondary w-full",children:s.hostMgmt.addHostButton})]}):t.jsxs("form",{id:"host-form",onSubmit:ae,className:"space-y-3",children:[t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"host-hostname",children:s.hostMgmt.addressLabel}),t.jsx("input",{id:"host-hostname",type:"text",value:y.hostname,onChange:P=>w({...y,hostname:P.target.value}),className:fe,placeholder:"remote.example.com",disabled:R})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"host-port",children:s.hostMgmt.portLabel}),t.jsx("input",{id:"host-port",type:"text",inputMode:"numeric",value:y.port,onChange:P=>w({...y,port:P.target.value}),className:fe,placeholder:"22",disabled:R}),y.port.trim()!==""&&!J&&t.jsx("div",{className:"mt-1 text-xs text-accent",children:s.hostMgmt.portRangeError})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"host-alias",children:s.hostMgmt.aliasLabel}),t.jsx("input",{id:"host-alias",type:"text",value:y.alias,onChange:P=>w({...y,alias:P.target.value}),className:fe,placeholder:"Prod worker",disabled:R})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"host-user",children:s.hostMgmt.userLabel}),t.jsx("input",{id:"host-user",type:"text",value:y.user,onChange:P=>w({...y,user:P.target.value}),className:fe,placeholder:s.hostMgmt.userPlaceholder,disabled:R})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"host-password",children:s.hostMgmt.passwordLabel}),t.jsx("input",{id:"host-password",type:"password",value:d?"":y.password,onChange:P=>w({...y,password:P.target.value}),className:fe,placeholder:p?s.hostMgmt.passwordPlaceholderSet:s.hostMgmt.passwordPlaceholderUnset,disabled:R||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:P=>x(P.target.checked),disabled:R}),s.hostMgmt.clearPasswordLabel]})]}),t.jsxs("div",{className:"rounded-md border border-accent/25 bg-accent-soft/60 px-3 py-2.5 text-xs text-accent",children:[s.hostMgmt.passwordHintLead,t.jsx("strong",{className:"font-semibold",children:s.hostMgmt.passwordHintStrong})," ",s.hostMgmt.plaintextWarningLead,t.jsx("strong",{className:"font-semibold",children:s.hostMgmt.plaintextWarningStrong}),s.hostMgmt.plaintextWarningTrail]}),t.jsxs("div",{className:"space-y-1.5",children:[t.jsx("button",{type:"button",onClick:le,disabled:!me||b||R||I,className:"text-xs text-accent transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",children:b?s.hostMgmt.testing:s.hostMgmt.testConnection}),(k==null?void 0:k.ssh)&&t.jsxs("div",{className:`text-xs ${k.ssh.ok?"text-og-800":"text-accent"}`,children:["SSH: ",k.ssh.ok?"✓":"⨯"," ",k.ssh.message]}),k&&(k.tmux.ok?t.jsxs("div",{className:"text-xs text-og-800",children:["tmux: ✓ ",k.tmux.path??""]}):t.jsxs("div",{className:"text-xs text-accent",children:["tmux: ⨯ ",k.tmux.message,((be=k.ssh)==null?void 0:be.ok)&&t.jsx("button",{type:"button",onClick:ce,disabled:I||R,className:"ml-2 text-accent underline transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",children:I?s.common.installing:s.common.oneClickInstall})]})),I&&t.jsx("div",{className:"text-xs text-og-500",children:s.common.installingTmuxNotice}),!I&&F&&t.jsxs("div",{className:`break-all text-xs ${F.ok?"text-og-800":"text-accent"}`,children:[F.ok?"✓ ":"⨯ ",F.message]})]})]})]})}const wn="baxian.taskNotifications.enabled";function kn(){if(typeof window>"u")return null;const e=window.Notification;return typeof e=="function"?e:null}function kt(){const e=kn();return e?e.permission:"unsupported"}function Qt(){try{return localStorage.getItem(wn)!=="0"}catch{return!0}}function jt(e){try{localStorage.setItem(wn,e?"1":"0")}catch{}}const Rs=o.createContext(null);function Pa({children:e}){const[n,s]=o.useState(kt),[r,a]=o.useState(Qt),[i,l]=o.useState(!1),c=o.useRef(!1),h=o.useRef(0);o.useEffect(()=>{const p=()=>{s(kt()),c.current||a(Qt())},u=d=>{if(d.key!==null&&d.key!==wn)return;s(kt());const x=d.key===null?Qt():d.newValue!=="0";x||(h.current+=1),a(x)};return window.addEventListener("focus",p),window.addEventListener("storage",u),()=>{window.removeEventListener("focus",p),window.removeEventListener("storage",u)}},[]);const m=o.useCallback(()=>{a(!0);const p=kn();if(!p){jt(!0);return}if(p.permission!=="default"){s(p.permission),jt(!0);return}if(c.current)return;c.current=!0,l(!0);const u=h.current;p.requestPermission().then(s).catch(d=>{console.warn("[task-notifications] permission request failed:",d),s(kt())}).finally(()=>{h.current===u&&jt(!0),c.current=!1,l(!1)})},[]),f=o.useCallback(()=>{h.current+=1,a(!1),jt(!1)},[]);return t.jsx(Rs.Provider,{value:{permission:n,preferenceEnabled:r,enabled:n==="granted"&&r,requesting:i,enable:m,disable:f},children:e})}function Cs(){const e=o.useContext(Rs);if(!e)throw new Error("useTaskNotifications must be used inside TaskNotificationsProvider");return e}const La=[{value:"en-US",label:"English"},{value:"zh-CN",label:"简体中文"}];function Ea({open:e,onClose:n}){const s=q(),{locale:r,saving:a,setLocale:i}=cs(),{show:l}=ke(),c=async h=>{try{await i(h)}catch(m){const f=m instanceof Error?m.message:String(m);l({kind:"error",title:s.settings.languageSaveFailed(f)})}};return t.jsx(Se,{open:e,onClose:n,title:s.settings.title,size:"sm",children:t.jsxs("div",{className:"space-y-5",children:[t.jsxs("fieldset",{children:[t.jsx("legend",{className:ue,children:s.settings.language}),t.jsx("div",{className:"flex gap-4",children:La.map(h=>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===h.value,disabled:a,onChange:()=>void c(h.value)}),h.label]},h.value))})]}),t.jsx(Da,{})]})})}function Da(){const e=q(),{permission:n,enabled:s,requesting:r,enable:a,disable:i}=Cs();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:We,children:l?e.settings.taskNotificationsDenied:e.settings.taskNotificationsHint})]})}const As="topbar-actions";function On(){return typeof document>"u"?null:document.getElementById(As)}function Ps({children:e}){const[n,s]=o.useState(On);return o.useEffect(()=>{n||s(On())},[n]),n?Qs.createPortal(e,n):null}function $a(){return gs("/api/realtime")}class Ia{constructor(n={}){oe(this,"wsUrl");oe(this,"wsFactory");oe(this,"tokenProvider");oe(this,"ws",null);oe(this,"topics",new Map);oe(this,"cache",new Map);oe(this,"outbox",[]);oe(this,"reconnectScheduler");oe(this,"explicitlyClosed",!1);this.wsUrl=n.wsUrl??$a(),this.wsFactory=n.wsFactory??xs,this.tokenProvider=n.tokenProvider??un,this.reconnectScheduler=new hs({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.${ps(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&&(fs(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 Jt=null;function it(){return Jt||(Jt=new Ia),Jt}function jn(){const[e,n]=o.useState(null),[s,r]=o.useState(!1),[a,i]=o.useState(null);return o.useEffect(()=>it().subscribe("agents",c=>{i(null),n(c),r(!0)},c=>i(c)),[]),{data:e,loaded:s,error:a}}function Ls(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),it().subscribe(`task:${e}`,h=>{l(null),s(h),a(!0)},h=>l(h))),[e]),{data:n,loaded:r,error:i}}function Es(e){const[n,s]=o.useState(null),[r,a]=o.useState(!1),[i,l]=o.useState(null);return o.useEffect(()=>{if(!e){s(null),a(!1),l(null);return}s(null),a(!1),l(null);let c=!1,h=!1,m=!1;const f=it().subscribe(`project-tasks:${e}`,p=>{c||(h=!0,l(null),s(p),a(!0))},p=>{c||(l(p),!(h||m)&&(m=!0,$.tasks.list(e).then(u=>{c||h||(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 At=null,Be=null,Pt=null,nt=0;const rn=new Set;function Ds(){rn.forEach(e=>e())}async function Ba(){const e=nt;try{const n=await $.projects.list();if(e!==nt)return;At=n,Pt=null}catch(n){if(e!==nt)return;Pt=n instanceof Error?n.message:String(n)}finally{e===nt&&(Be=null,Ds())}}function an(){return Be||(Be=Ba(),Be)}function Ma(){nt+=1,At=null,Be=null,Pt=null,Ds()}typeof window<"u"&&window.addEventListener(st,Ma);async function Fa(){const e=Be!==null;await an(),e&&await an()}function ot(){const[,e]=o.useState(0);return o.useEffect(()=>{const n=()=>e(s=>s+1);return rn.add(n),At===null&&!Be&&an(),()=>{rn.delete(n)}},[]),{projects:At,error:Pt,refresh:Fa}}function Oa(){const e=q(),n=De(),{projects:s,error:r,refresh:a}=ot(),i=s??[],l=s!==null,[c,h]=o.useState(!1),[m,f]=o.useState(!1),[p,u]=o.useState(!1),[d,x]=o.useState(!1),[y,w]=o.useState({kind:"closed"}),{data:C,loaded:S,error:R}=jn(),v=(R==null?void 0:R.message)??null,b=new Map((C??[]).map(I=>[I.id,I])),j=r??v,k=i.length===0,E=t.jsx("button",{type:"button",onClick:()=>f(!0),disabled:k,"aria-describedby":k?"create-task-hint":void 0,className:"btn-ghost",children:e.dashboard.newTask});return t.jsxs("div",{children:[t.jsxs(Ps,{children:[k?t.jsx("span",{className:"inline-flex",title:e.dashboard.createProjectFirst,children:E}):E,k&&t.jsx("span",{id:"create-task-hint",className:"sr-only",children:e.dashboard.createProjectFirst}),t.jsx(ln,{ariaLabel:e.dashboard.moreActions,children:I=>t.jsxs(t.Fragment,{children:[t.jsx(Ne,{onClick:()=>{I(),h(!0)},children:e.dashboard.newProject}),t.jsx(Ne,{onClick:()=>{I(),u(!0)},children:e.dashboard.manageHosts}),t.jsx(Ne,{onClick:()=>{I(),x(!0)},children:e.settings.entry})]})})]}),t.jsx("h1",{className:"sr-only",children:"Dashboard"}),j&&t.jsx("div",{className:"mb-4 text-sm text-accent",children:e.common.loadFailed(j)}),l&&i.length===0&&!r&&t.jsx("div",{className:"rounded-lg border border-hairline bg-surface py-12 text-center text-sm text-og-500",children:e.dashboard.emptyProjects}),i.map(I=>t.jsx(_a,{project:I,agentsById:b,agentsLoaded:S,agentsError:!!R,onAgentDeleted:a},I.id)),t.jsx(wa,{open:c,onClose:()=>h(!1),onCreated:I=>{h(!1),a(),w({kind:"asking",projectId:I})}}),t.jsx(Aa,{open:p,onClose:()=>u(!1)}),t.jsx(Se,{open:y.kind==="asking",onClose:()=>w({kind:"closed"}),title:e.dashboard.projectCreatedTitle,size:"sm",footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:()=>w({kind:"closed"}),className:"btn-secondary",children:e.dashboard.later}),t.jsx("button",{type:"button",onClick:()=>{y.kind==="asking"&&w({kind:"addingAgent",projectId:y.projectId})},className:"btn-primary",children:e.dashboard.continueAddingAgent})]}),children:t.jsx("p",{className:"text-sm text-og-700",children:e.dashboard.addAgentNowOrLater})}),y.kind==="addingAgent"&&t.jsx(Ss,{open:!0,projectId:y.projectId,onClose:()=>w({kind:"closed"}),onCreated:()=>{a()}}),t.jsx(yn,{open:m,onClose:()=>f(!1),onCreated:I=>n(Ee(I.projectId,I.id))}),t.jsx(Ea,{open:d,onClose:()=>x(!1)})]})}function _a({project:e,agentsById:n,agentsLoaded:s,agentsError:r,onAgentDeleted:a}){const i=q(),{data:l,error:c}=Es(e.id),h=l??[],m=(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(Le,{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(Le,{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})]}),m&&t.jsx("div",{className:"mb-2 text-xs text-accent",children:i.dashboard.tasksLoadFailed(m)}),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(Ns,{team:f,projectId:e.id,agentsById:n,agentsLoaded:s,agentsError:r,tasks:h,onDeleted:a,terminalMode:"embedded-full"},f.map(u=>u.id).join(":")||p))})]})}const $s="baxian.taskPanel.doneOpen";function Ha(){try{return localStorage.getItem($s)==="1"}catch{return!1}}function Lt(e){const n=e.match(/^task-(\d+)$/);return n?parseInt(n[1],10):Number.NaN}function qa(e,n){const s=Lt(e.id),r=Lt(n.id);return Number.isNaN(s)||Number.isNaN(r)?e.id.localeCompare(n.id):s-r}function Ua(e,n){const s=(n.updatedAt??"").localeCompare(e.updatedAt??"");if(s!==0)return s;const r=Lt(e.id),a=Lt(n.id);return Number.isNaN(r)||Number.isNaN(a)?n.id.localeCompare(e.id):a-r}function _n(e,n){const[s,r]=o.useState(Ot);o.useEffect(()=>r(Ot),[n]);const a=e.slice(0,s),i=e.length>a.length;return{items:a,hasMore:i,loadMore:()=>r(c=>c+Ot),total:e.length}}function Ga(e){const[n,s]=o.useState([]),[r,a]=o.useState(!1),[i,l]=o.useState(!1),[c,h]=o.useState(!1),[m,f]=o.useState(null),p=o.useRef(0),u=o.useRef(0),d=o.useCallback(x=>{const y=++p.current,w=x==="first"?0:u.current;l(!0),f(null),$.tasks.page(e,{category:"done",offset:w}).then(C=>{p.current===y&&(s(S=>x==="first"?C.tasks:[...S,...C.tasks]),a(C.hasMore),u.current=C.nextOffset,h(!0),l(!1))},C=>{p.current===y&&(f(C instanceof Error?C.message:String(C)),l(!1))})},[e]);return o.useEffect(()=>{p.current+=1,u.current=0,s([]),a(!1),h(!1),f(null),l(!1)},[e]),{items:n,hasMore:r,loading:i,loaded:c,error:m,load:d}}function Wa({projectId:e,openTasks:n,className:s=""}){const r=q(),a=o.useMemo(()=>n.filter(u=>cn.has(u.status)).sort(Ua),[n]),i=o.useMemo(()=>n.filter(u=>u.status==="pending").sort(qa),[n]),l=_n(a,e),c=_n(i,e),h=Ga(e),[m,f]=o.useState(Ha);o.useEffect(()=>{try{localStorage.setItem($s,m?"1":"0")}catch{}},[m]),o.useEffect(()=>{m&&h.load("first")},[m,h.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(Hn,{title:r.taskPanel.inProgressTitle,section:l,emptyHint:r.taskPanel.emptyInProgress}),t.jsx(Hn,{title:r.taskPanel.pendingTitle,section:c,emptyHint:r.taskPanel.emptyPending}),t.jsxs("div",{children:[t.jsxs("button",{type:"button",onClick:p,"aria-expanded":m,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:m?r.taskPanel.collapse:r.taskPanel.view})]}),m&&t.jsx(za,{state:h})]})]})})}function Hn({title:e,section:n,emptyHint:s}){const r=q();return t.jsxs("section",{"aria-label":e,className:"border-b border-hairline",children:[t.jsxs("div",{className:"px-3 py-2 text-xs font-normal uppercase tracking-[0.05em] text-og-500",children:[e," ",t.jsxs("span",{className:"text-og-400",children:["(",n.total,")"]})]}),n.items.length===0?t.jsx("div",{className:"px-3 pb-3 text-xs text-og-400",children:s}):t.jsxs("div",{className:"divide-y divide-hairline",children:[n.items.map(a=>t.jsx(Is,{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 za({state:e}){const n=q(),s=e.loaded&&!e.error&&e.items.length===0;return t.jsxs("div",{className:"divide-y divide-hairline",children:[e.items.map(r=>t.jsx(Is,{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 Is({task:e}){const n=q(),s=De(),{show:r}=ke(),[a,i]=o.useState(!1),l=Me(e.phase)?e.specReviewRound??0:e.reviewRound,c=e.status==="pending"&&e.preferredAgentId==="",h=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,m=e.attention?ws(n,e.attention):null,f=()=>s(Ee(e.projectId,e.id)),p=async()=>{if(c||e.postApproveRevoked||e.status==="review"&&Qn(e)){f();return}i(!0);try{await $.tasks.advance(e.id),r({kind:"success",title:n.taskDetail.advanceSucceededTitle})}catch(u){r({kind:"error",title:n.taskDetail.advanceFailedTitle,body:n.taskDetail.actionFailedBody,details:u instanceof Error?u.message:String(u)})}finally{i(!1)}};return t.jsxs("div",{className:"px-3 py-2",children:[t.jsx("div",{className:"flex items-center gap-2 text-sm",children:t.jsxs("button",{type:"button",onClick: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:vn(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(bn,{task:e,className:"shrink-0"})]})}),e.attention&&m&&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:m.title}),t.jsx("span",{className:"mt-0.5 block text-og-700",children:m.guidance})]}),t.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1.5",children:e.attention.recommendedActions.map(u=>t.jsx("button",{type:"button",disabled:u==="advance"&&a,onClick:()=>u==="advance"?void p():f(),className:u==="advance"?"btn-primary":"btn-secondary",children:u==="advance"?a?n.taskDetail.advancing:h:u==="verdict"?n.taskDetail.handleReview:u==="cancel"?n.taskDetail.cancelConfirmLabel:n.taskDetail.retryTask},u))}),t.jsxs("details",{className:"mt-1.5 text-og-500",children:[t.jsx("summary",{className:"cursor-pointer select-none text-accent",children:n.common.technicalDetails}),t.jsxs("div",{className:"mt-1 whitespace-pre-wrap break-words font-mono",children:[e.attention.reason,`
10
+ `)}:{}}),r(),n()}catch(X){E(X instanceof Error?X.message:String(X))}finally{j(!1)}},ye=()=>{!c||b||(l(c.form),h(null),x(null),v(null),_(!1))},N=({rt:D})=>{if(i.mode==="remote"&&!i.host)return t.jsx("span",{className:"ml-2 text-xs text-og-400",children:a.createAgent.selectHostFirstHint});if(y)return t.jsx("span",{className:"ml-2 text-xs text-og-400",children:a.createAgent.probingLabel});if(!d)return t.jsx("span",{className:"ml-2 text-xs text-og-400",children:"?"});const L=d.runtimes[D];return L?L.ok?t.jsxs("span",{className:"ml-2 text-xs text-probe-ok",children:["✓ ",L.path??""]}):t.jsxs("span",{className:"ml-2 text-xs text-accent",title:L.message,children:["⨯ ",L.message]}):t.jsx("span",{className:"ml-2 text-xs text-og-400",children:"?"})},xe=()=>{var A;if(i.mode==="remote"&&!i.host)return null;if(y&&!C)return t.jsx("div",{className:"text-xs text-og-400",children:a.createAgent.tmuxProbingLabel});if(!d)return null;if(d.tmux.ok)return t.jsxs("div",{className:"text-xs text-probe-ok",children:["tmux: ✓ ",d.tmux.path??""]});const D=i.mode==="local"||!!((A=d.ssh)!=null&&A.ok);return t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"text-xs text-accent",children:["tmux: ⨯ ",d.tmux.message,D&&t.jsx("button",{type:"button",onClick:se,className:"ml-2 text-accent underline transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",disabled:C||b,children:C?a.common.installing:a.common.oneClickInstall})]}),C&&t.jsx("div",{className:"text-xs text-og-500",children:a.common.installingTmuxNotice}),!C&&R&&t.jsxs("div",{className:`break-all text-xs ${R.ok?"text-probe-ok":"text-accent"}`,children:[R.ok?"✓ ":"⨯ ",R.message]})]})},be=()=>i.mode!=="remote"||!i.host||!(d!=null&&d.ssh)?null:d.ssh.ok?t.jsxs("div",{className:"text-xs text-probe-ok",children:["SSH: ✓ ",d.ssh.message]}):t.jsxs("div",{className:"text-xs text-accent",children:["SSH: ⨯ ",d.ssh.message]});return t.jsx(Se,{open:e,onClose:ne,title:a.createAgent.modalTitle(s),size:"lg",footer:t.jsxs(t.Fragment,{children:[c&&t.jsx("button",{type:"button",onClick:ye,disabled:b,className:"btn-secondary",children:a.common.back}),t.jsx("button",{type:"button",onClick:ne,disabled:b,className:"btn-secondary",children:a.common.cancel}),t.jsx("button",{type:"submit",form:"create-agent-form",disabled:!ce,className:"btn-primary",children:b?a.createAgent.submitting:c?a.createAgent.submitLabel:a.createAgent.continueLabel})]}),children:t.jsxs("form",{id:"create-agent-form",onSubmit:ae,className:"space-y-3",children:[k&&t.jsx("div",{className:"whitespace-pre-line rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-sm text-accent",children:k}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"agent-id",children:"Agent ID"}),t.jsx("input",{id:"agent-id",type:"text",value:i.id,onChange:D=>l({...i,id:D.target.value}),className:fe,placeholder:a.createAgent.idPlaceholder(s,ee),disabled:b}),i.id&&!En.test(i.id)&&t.jsx("div",{className:Ct,children:a.common.idFormatError}),i.id&&(p.has(i.id)||i.id===(c==null?void 0:c.agent.id))&&t.jsx("div",{className:Ct,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:ee==="dev"?a.createAgent.devStepLabel:a.createAgent.qaStepLabel}),c&&t.jsx("div",{className:We,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:b}),t.jsx("span",{className:"text-sm text-og-800",children:a.createAgent.localModeLabel})]}),t.jsxs("label",{className:"inline-flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"mode",checked:i.mode==="remote",className:Ie,onChange:()=>l({...i,mode:"remote"}),disabled:b}),t.jsx("span",{className:"text-sm text-og-800",children:a.createAgent.remoteModeLabel})]})]}),i.mode==="remote"&&t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"host",children:"Host"}),m.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:D=>l({...i,host:D.target.value}),className:fe,disabled:b,children:[t.jsx("option",{value:"",children:a.createAgent.selectHostPlaceholder}),m.map(D=>t.jsx("option",{value:D.id,children:ja(D)},D.id))]}),t.jsx("div",{className:We,children:a.createAgent.sshConfigHint})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"mb-1.5 flex items-center justify-between",children:[t.jsx("span",{className:"text-xs font-medium text-og-700",children:a.createAgent.runtimeLabel}),t.jsx("button",{type:"button",onClick:Y,className:"text-xs text-accent transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",disabled:b||y||i.mode==="remote"&&!i.host,children:a.createAgent.reprobeButton})]}),t.jsxs("label",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"runtime",checked:i.runtime==="claude-code",className:Ie,onChange:()=>l({...i,runtime:"claude-code"}),disabled:b||(d?!((B=d.runtimes["claude-code"])!=null&&B.ok):!1)}),t.jsx("span",{className:"text-sm text-og-800",children:"Claude Code"}),t.jsx(N,{rt:"claude-code"})]}),t.jsxs("label",{className:"mt-1 flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"runtime",checked:i.runtime==="codex",className:Ie,onChange:()=>l({...i,runtime:"codex"}),disabled:b||(d?!((M=d.runtimes.codex)!=null&&M.ok):!1)}),t.jsx("span",{className:"text-sm text-og-800",children:"Codex"}),t.jsx(N,{rt:"codex"})]}),t.jsxs("label",{className:"mt-1 flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"runtime",checked:i.runtime==="opencode",className:Ie,onChange:()=>l({...i,runtime:"opencode"}),disabled:b||(d?!((he=d.runtimes.opencode)!=null&&he.ok):!1)}),t.jsx("span",{className:"text-sm text-og-800",children:"OpenCode"}),t.jsx(N,{rt:"opencode"})]}),t.jsxs("label",{className:"mt-1 flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"runtime",checked:i.runtime==="qodercli",className:Ie,onChange:()=>l({...i,runtime:"qodercli"}),disabled:b||(d?!((ie=d.runtimes.qodercli)!=null&&ie.ok):!1)}),t.jsx("span",{className:"text-sm text-og-800",children:"Qoder CLI"}),t.jsx(N,{rt:"qodercli"})]}),t.jsx("div",{className:"mt-2",children:t.jsx(xe,{})}),t.jsx("div",{children:t.jsx(be,{})})]}),t.jsxs("div",{children:[t.jsxs("button",{type:"button",onClick:()=>_(D=>!D),"aria-expanded":I,"aria-controls":I?"advanced-options":void 0,className:"flex w-full items-center justify-between rounded-md px-1 py-1.5 text-left text-xs font-medium text-og-700 transition-colors hover:bg-og-50",children:[t.jsx("span",{children:a.createAgent.advancedOptionsLabel}),t.jsx("span",{className:"text-og-400",children:I?a.createAgent.collapseLabel:a.createAgent.expandLabel})]}),I&&t.jsxs("div",{id:"advanced-options",className:"mt-3 space-y-3",children:[t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"workdir",children:a.createAgent.workdirLabel}),t.jsx("input",{id:"workdir",type:"text",value:i.workdir,onChange:D=>l({...i,workdir:D.target.value}),className:fe,placeholder:a.createAgent.workdirPlaceholder,disabled:b}),t.jsx("div",{className:We,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:D=>l({...i,model:D.target.value}),className:fe,placeholder:i.runtime==="codex"?a.createAgent.modelPlaceholderCodex:a.createAgent.modelPlaceholderOther,disabled:b}),t.jsx("div",{className:We,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:D=>l({...i,addDirs:D.target.value}),className:`${fe} font-mono text-xs`,rows:3,placeholder:a.createAgent.addDirsPlaceholder,disabled:b}),t.jsx("div",{className:We,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:D=>l({...i,yolo:D.target.checked}),disabled:b}),t.jsxs("div",{className:"text-sm text-og-800",children:[t.jsx("div",{className:"font-medium",children:a.createAgent.yoloTitle}),t.jsxs("div",{className:"mt-1 text-xs text-accent",children:[a.createAgent.yoloBodyLead,t.jsx("code",{children:ar[i.runtime||"claude-code"]}),a.createAgent.yoloBodyTrail]})]})]})})]})})}const Dn=200,$n=16e3,Ta="baxian.draft.createTask:";function sn(e){return`${Ta}${e??"*"}`}function In(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:"",h=typeof r.updatedAt=="number"?r.updatedAt:void 0;return!a.trim()&&!i.trim()?null:{title:a,description:i,projectId:l,preferredAgentId:c,updatedAt:h}}catch{return null}}function Na(e,n){const s=!n.title.trim()&&!n.description.trim();try{s?localStorage.removeItem(e):localStorage.setItem(e,JSON.stringify({...n,updatedAt:Date.now()}))}catch{}}function Bn(e){try{localStorage.removeItem(e)}catch{}}function Sa(e){const n=sn(e),s=In(n);if(!e)return s;const r=sn(void 0),a=In(r);if(!a||a.projectId!==e)return s;const i=!s||(a.updatedAt??0)>(s.updatedAt??0);if(i)try{localStorage.setItem(n,JSON.stringify(a))}catch{return a}try{localStorage.removeItem(r)}catch{}return i?a:s}const Mn="mt-1 text-right text-xs text-og-400",Ra=Math.floor(Dt/1024/1024);function yn(e){const n=q(),s=e.mode==="edit",{show:r}=ke(),a=s?e.task.projectId:e.projectId,i=s?e.task.title:"",l=s?e.task.description:"",c=s?e.task.preferredAgentId:"",[h,m]=o.useState([]),[f,p]=o.useState([]),[u,d]=o.useState(a??""),[x,y]=o.useState(c),[w,C]=o.useState(i),[S,R]=o.useState(l),[v,b]=o.useState([]),j=o.useRef(null),[k,E]=o.useState(!1),[I,_]=o.useState(null),[F,te]=o.useState(!1),z=o.useRef(0),K=o.useRef(0),re=o.useRef(0),Z=o.useRef(new Set),ne=s?null:sn(a);o.useEffect(()=>{if(!e.open)return;z.current+=1,K.current+=1;const A=z.current;m([]),p([]),Z.current=new Set;const L=ne?Sa(a):null;L&&Z.current.add(L.projectId),d(a??(L==null?void 0:L.projectId)??""),y((L==null?void 0:L.preferredAgentId)||c),C((L==null?void 0:L.title)||i),R((L==null?void 0:L.description)||l),te(L!==null),_(null),E(!1),b([]),Promise.all([$.projects.list(),$.agents.list()]).then(([Q,G])=>{A===z.current&&(m(Q),p(G))}).catch(Q=>{A===z.current&&_(Q instanceof Error?Q.message:String(Q))})},[e.open,a,i,l,c,ne]),o.useEffect(()=>{if(!(!e.open||!ne)){if(re.current!==K.current){re.current=K.current;return}Na(ne,{title:w,description:S,projectId:u,preferredAgentId:x})}},[e.open,ne,w,S,u,x]);const Y=o.useMemo(()=>h.find(A=>A.id===u)??null,[h,u]),se=o.useMemo(()=>Y?Y.agent.flat().filter(A=>A.role==="dev"):[],[Y]),ee=o.useMemo(()=>new Set(f.map(A=>A.id)),[f]),J=o.useMemo(()=>se.filter(A=>ee.has(A.id)),[se,ee]),me=o.useMemo(()=>se.filter(A=>!ee.has(A.id)),[se,ee]);o.useEffect(()=>{s||Y!==null&&x!==""&&!J.find(A=>A.id===x)&&y("")},[Y,J,x,s]),o.useEffect(()=>{if(s||!Y)return;const A=J.find(L=>L.role==="dev");A&&(Z.current.has(Y.id)||(Z.current.add(Y.id),y(L=>L===""?A.id:L)))},[s,Y,J]);const ge=!s||J.find(A=>A.id===x),H=s&&!ge&&!!x,le=H&&me.some(A=>A.id===x),ce=le?n.createTask.noDevPendingRestartHint(x):H?n.createTask.noDevNotInRuntimeHint(x):!u||J.length>0?null:me.length>0?n.createTask.noDevGlobalPendingRestartHint:null,ae=w.trim(),ye=S.trim(),xe=!!u&&ae.length>0&&!k,be=()=>{k||e.onClose()},P=()=>{ne&&(Bn(ne),d(a??""),y(c),C(i),R(l),_(null),te(!1))},T=async A=>{var L,Q;if(A.preventDefault(),!!xe){E(!0),_(null);try{if(e.mode==="edit"){const G=await $.tasks.update(e.task.id,{title:ae,description:ye,preferredAgentId:x});r({kind:"success",title:n.createTask.updatedToastTitle}),(L=e.onUpdated)==null||L.call(e,G),e.onClose()}else{const G=v.length?await Promise.all(v.map(async we=>({dataBase64:await Zt(we),filename:we.name}))):void 0,X=await $.tasks.create({projectId:u,title:ae,description:ye,preferredAgentId:x,...G?{images:G}:{}});ne&&Bn(ne),r({kind:"success",title:n.createTask.createdToastTitle}),(Q=e.onCreated)==null||Q.call(e,X),e.onClose()}}catch(G){_(G instanceof Error?G.message:String(G))}finally{E(!1)}}},B=A=>{const L=Array.from(A.target.files??[]);if(A.target.value="",L.length===0)return;const Q=L.filter(G=>G.size>Dt?(r({kind:"error",title:n.createTask.imageTooLargeToastTitle,body:n.createTask.imageTooLargeToastBody(G.name,Ra)}),!1):!0);v.length+Q.length>gt&&r({kind:"warn",title:n.createTask.tooManyImagesToastTitle(gt)}),b(G=>[...G,...Q].slice(0,gt))},M=A=>b(L=>L.filter((Q,G)=>G!==A)),he=s?n.createTask.titleEdit:n.createTask.titleCreate,ie=s?k?n.common.saving:n.common.save:k?n.common.creating:n.common.create,D=!s&&!a;return t.jsx(Se,{open:e.open,onClose:be,title:he,size:"md",dismissOnBackdrop:!1,footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:be,disabled:k,className:"btn-secondary",children:n.common.cancel}),t.jsx("button",{type:"submit",form:"create-task-form",disabled:!xe,className:"btn-primary",children:ie})]}),children:t.jsxs("form",{id:"create-task-form",onSubmit:T,className:"space-y-3",children:[!s&&F&&t.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-md border border-accent-soft bg-accent-soft/30 px-3 py-2 text-xs text-accent",children:[t.jsx("span",{children:n.createTask.draftRestoredNotice}),t.jsx("button",{type:"button",onClick:P,className:"shrink-0 underline hover:text-accent-hover",children:n.createTask.discardDraftButton})]}),I&&t.jsx("div",{className:"rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-sm text-accent",children:I}),D&&t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"task-project",children:"Project"}),t.jsxs("select",{id:"task-project",value:u,onChange:A=>d(A.target.value),className:fe,disabled:k,required:!0,children:[t.jsx("option",{value:"",disabled:!0,children:n.createTask.selectProjectPlaceholder}),h.map(A=>t.jsx("option",{value:A.id,children:A.id},A.id))]})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"task-dev",children:n.createTask.targetAgentLabel}),t.jsxs("select",{id:"task-dev",value:x,onChange:A=>y(A.target.value),className:fe,disabled:k,children:[t.jsx("option",{value:"",children:n.createTask.notAssignedOption}),H&&t.jsxs("option",{value:x,children:[x," ",le?n.createTask.pendingRestartSuffix:n.createTask.notInRuntimeSuffix]}),J.map(A=>t.jsx("option",{value:A.id,children:A.id},A.id))]}),ce&&t.jsx("div",{className:"mt-1 text-xs text-accent",children:ce})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"task-title",children:"Title"}),t.jsx("input",{id:"task-title",type:"text",value:w,onChange:A=>C(A.target.value),maxLength:Dn,className:fe,placeholder:n.createTask.titlePlaceholder,disabled:k,required:!0}),t.jsxs("div",{className:Mn,children:[w.length," / ",Dn]})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"task-description",children:n.createTask.descriptionLabel}),t.jsx("textarea",{id:"task-description",value:S,onChange:A=>R(A.target.value),maxLength:$n,rows:8,className:`${fe} font-mono text-xs`,placeholder:n.createTask.descriptionPlaceholder,disabled:k}),t.jsxs("div",{className:Mn,children:[S.length," / ",$n]})]}),!s&&t.jsxs("div",{children:[t.jsx("label",{className:ue,children:n.createTask.imagesLabel}),t.jsx("button",{type:"button",onClick:()=>{var A;return(A=j.current)==null?void 0:A.click()},disabled:k||v.length>=gt,className:"btn-secondary",children:n.createTask.addImagesButton}),t.jsx("input",{ref:j,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:B}),v.length>0&&t.jsx("ul",{className:"mt-2 space-y-1",children:v.map((A,L)=>t.jsxs("li",{className:"flex items-center justify-between rounded-md border border-og-100 bg-surface px-2.5 py-1.5",children:[t.jsx("span",{title:A.name,className:"truncate text-xs text-og-700",children:A.name}),t.jsx("button",{type:"button","aria-label":n.createTask.removeImageAriaLabel(A.name),onClick:()=>M(L),disabled:k,className:"ml-2 shrink-0 text-og-400 transition-colors",children:"✕"})]},`${A.name}-${L}`))})]})]})})}const Fn="***",Yt={hostname:"",port:"",alias:"",user:"",password:""};function Ca(e){return e.alias?e.alias:`${e.user?`${e.user}@`:""}${e.hostname}${e.port!=null?`:${e.port}`:""}`}function Aa({open:e,onClose:n}){var be;const s=q(),[r,a]=o.useState([]),[i,l]=o.useState("list"),[c,h]=o.useState(null),[m,f]=o.useState(null),[p,u]=o.useState(!1),[d,x]=o.useState(!1),[y,w]=o.useState(Yt),[C,S]=o.useState(null),[R,v]=o.useState(!1),[b,j]=o.useState(!1),[k,E]=o.useState(null),[I,_]=o.useState(!1),[F,te]=o.useState(null),z=o.useRef(0),K=o.useRef(null),{show:re}=ke(),Z=o.useCallback(()=>{$.hosts.list().then(a).catch(P=>S(P instanceof Error?P.message:String(P)))},[]);o.useEffect(()=>{if(!e){K.current&&K.current.abort();return}l("list"),h(null),f(null),w(Yt),S(null),Z()},[e,Z]),o.useEffect(()=>{z.current+=1,K.current&&K.current.abort(),j(!1),E(null),_(!1),te(null)},[y.hostname,y.user,y.port,y.password,d,i]),o.useEffect(()=>()=>{K.current&&K.current.abort()},[]);const ne=()=>{h(null),f(null),u(!1),x(!1),w(Yt),S(null),l("form")},Y=P=>{h(P.id??null),f(P),u(P.password===Fn),x(!1),w({hostname:P.hostname,port:P.port!=null?String(P.port):"",alias:P.alias??"",user:P.user??"",password:""}),S(null),l("form")},se=()=>{const P={hostname:y.hostname.trim()};return c?(P.port=y.port.trim()?Number(y.port):null,P.alias=y.alias.trim(),P.user=y.user.trim()):(y.port.trim()&&(P.port=Number(y.port)),y.alias.trim()&&(P.alias=y.alias.trim()),y.user.trim()&&(P.user=y.user.trim())),c&&d?P.password="":y.password&&(P.password=y.password),P},ee=y.port.trim(),J=ee===""||/^\d+$/.test(ee)&&Number(ee)>0&&Number(ee)<=65535,me=y.hostname.trim().length>0&&J,ge=!!m&&y.hostname.trim()===m.hostname&&y.user.trim()===(m.user??"")&&y.port.trim()===(m.port!=null?String(m.port):""),H=()=>c&&ge&&!y.password&&!d?{hostId:c}:{host:{hostname:y.hostname.trim(),...y.user.trim()?{user:y.user.trim()}:{},...ee?{port:Number(ee)}:{},...!d&&y.password?{password:y.password}:{}}},le=async()=>{if(!me||b)return;K.current&&K.current.abort();const P=new AbortController;K.current=P;const T=z.current;j(!0),E(null),te(null),S(null);try{const B=await $.agents.probe("remote",H(),{signal:P.signal});if(P.signal.aborted||z.current!==T)return;E(B)}catch(B){if(P.signal.aborted||z.current!==T)return;S(B instanceof Error?B.message:String(B))}finally{z.current===T&&j(!1)}},ce=async()=>{if(I)return;const P=z.current;_(!0),te(null),S(null);try{const T=await $.agents.installTmux("remote",H());if(z.current!==P)return;te({ok:T.ok,message:T.message}),E(B=>B&&{...B,tmux:T.tmux})}catch(T){if(z.current!==P)return;S(T instanceof Error?T.message:String(T))}finally{z.current===P&&_(!1)}},ae=async P=>{if(P.preventDefault(),!(!me||R)){v(!0),S(null);try{if(c)await $.hosts.update(c,se()),re({kind:"success",title:s.hostMgmt.updatedToastTitle(c)});else{const T=await $.hosts.create(se());re({kind:"success",title:s.hostMgmt.createdToastTitle(T.host.id)})}Z(),l("list")}catch(T){S(T instanceof Error?T.message:String(T))}finally{v(!1)}}},ye=async P=>{S(null);try{await $.hosts.delete(P.id),re({kind:"success",title:s.hostMgmt.deletedToastTitle(P.id)}),Z()}catch(T){S(T instanceof Error?T.message:String(T))}},N=t.jsx("button",{type:"button",onClick:n,className:"btn-secondary",children:s.common.close}),xe=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:()=>l("list"),disabled:R,className:"btn-secondary",children:s.common.backText}),t.jsx("button",{type:"submit",form:"host-form",disabled:!me||R,className:"btn-primary",children:R?s.common.saving:s.common.save})]});return t.jsxs(Se,{open:e,onClose:n,title:s.hostMgmt.title,size:"md",footer:i==="list"?N:xe,children:[C&&t.jsx("div",{className:"mb-3 whitespace-pre-line rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-sm text-accent",children:C}),i==="list"?t.jsxs("div",{className:"space-y-3",children:[r.length===0?t.jsx("p",{className:"text-sm text-og-500",children:s.hostMgmt.emptyState}):t.jsx("ul",{className:"space-y-1.5",children:r.map(P=>t.jsxs("li",{className:"flex items-center justify-between gap-3 rounded-md border border-og-100 px-3 py-2",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"truncate text-sm font-medium text-og-800",children:Ca(P)}),t.jsxs("div",{className:"truncate text-xs text-og-500",children:[(P.user?`${P.user}@`:"")+P.hostname,P.port!=null?`:${P.port}`:"",P.password===Fn?s.hostMgmt.passwordSavedIndicator:""]})]}),t.jsxs("div",{className:"flex shrink-0 gap-2",children:[t.jsx("button",{type:"button",onClick:()=>Y(P),className:"text-xs text-accent transition-colors hover:text-accent-hover",children:s.common.edit}),t.jsx("button",{type:"button",onClick:()=>ye(P),className:"text-xs text-accent transition-colors hover:opacity-80",children:s.common.delete})]})]},P.id))}),t.jsx("button",{type:"button",onClick:ne,className:"btn-secondary w-full",children:s.hostMgmt.addHostButton})]}):t.jsxs("form",{id:"host-form",onSubmit:ae,className:"space-y-3",children:[t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"host-hostname",children:s.hostMgmt.addressLabel}),t.jsx("input",{id:"host-hostname",type:"text",value:y.hostname,onChange:P=>w({...y,hostname:P.target.value}),className:fe,placeholder:"remote.example.com",disabled:R})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"host-port",children:s.hostMgmt.portLabel}),t.jsx("input",{id:"host-port",type:"text",inputMode:"numeric",value:y.port,onChange:P=>w({...y,port:P.target.value}),className:fe,placeholder:"22",disabled:R}),y.port.trim()!==""&&!J&&t.jsx("div",{className:"mt-1 text-xs text-accent",children:s.hostMgmt.portRangeError})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"host-alias",children:s.hostMgmt.aliasLabel}),t.jsx("input",{id:"host-alias",type:"text",value:y.alias,onChange:P=>w({...y,alias:P.target.value}),className:fe,placeholder:"Prod worker",disabled:R})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"host-user",children:s.hostMgmt.userLabel}),t.jsx("input",{id:"host-user",type:"text",value:y.user,onChange:P=>w({...y,user:P.target.value}),className:fe,placeholder:s.hostMgmt.userPlaceholder,disabled:R})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"host-password",children:s.hostMgmt.passwordLabel}),t.jsx("input",{id:"host-password",type:"password",value:d?"":y.password,onChange:P=>w({...y,password:P.target.value}),className:fe,placeholder:p?s.hostMgmt.passwordPlaceholderSet:s.hostMgmt.passwordPlaceholderUnset,disabled:R||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:P=>x(P.target.checked),disabled:R}),s.hostMgmt.clearPasswordLabel]})]}),t.jsxs("div",{className:"rounded-md border border-accent/25 bg-accent-soft/60 px-3 py-2.5 text-xs text-accent",children:[s.hostMgmt.passwordHintLead,t.jsx("strong",{className:"font-semibold",children:s.hostMgmt.passwordHintStrong})," ",s.hostMgmt.plaintextWarningLead,t.jsx("strong",{className:"font-semibold",children:s.hostMgmt.plaintextWarningStrong}),s.hostMgmt.plaintextWarningTrail]}),t.jsxs("div",{className:"space-y-1.5",children:[t.jsx("button",{type:"button",onClick:le,disabled:!me||b||R||I,className:"text-xs text-accent transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",children:b?s.hostMgmt.testing:s.hostMgmt.testConnection}),(k==null?void 0:k.ssh)&&t.jsxs("div",{className:`text-xs ${k.ssh.ok?"text-og-800":"text-accent"}`,children:["SSH: ",k.ssh.ok?"✓":"⨯"," ",k.ssh.message]}),k&&(k.tmux.ok?t.jsxs("div",{className:"text-xs text-og-800",children:["tmux: ✓ ",k.tmux.path??""]}):t.jsxs("div",{className:"text-xs text-accent",children:["tmux: ⨯ ",k.tmux.message,((be=k.ssh)==null?void 0:be.ok)&&t.jsx("button",{type:"button",onClick:ce,disabled:I||R,className:"ml-2 text-accent underline transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",children:I?s.common.installing:s.common.oneClickInstall})]})),I&&t.jsx("div",{className:"text-xs text-og-500",children:s.common.installingTmuxNotice}),!I&&F&&t.jsxs("div",{className:`break-all text-xs ${F.ok?"text-og-800":"text-accent"}`,children:[F.ok?"✓ ":"⨯ ",F.message]})]})]})]})}const wn="baxian.taskNotifications.enabled";function kn(){if(typeof window>"u")return null;const e=window.Notification;return typeof e=="function"?e:null}function kt(){const e=kn();return e?e.permission:"unsupported"}function Qt(){try{return localStorage.getItem(wn)!=="0"}catch{return!0}}function jt(e){try{localStorage.setItem(wn,e?"1":"0")}catch{}}const Rs=o.createContext(null);function Pa({children:e}){const[n,s]=o.useState(kt),[r,a]=o.useState(Qt),[i,l]=o.useState(!1),c=o.useRef(!1),h=o.useRef(0);o.useEffect(()=>{const p=()=>{s(kt()),c.current||a(Qt())},u=d=>{if(d.key!==null&&d.key!==wn)return;s(kt());const x=d.key===null?Qt():d.newValue!=="0";x||(h.current+=1),a(x)};return window.addEventListener("focus",p),window.addEventListener("storage",u),()=>{window.removeEventListener("focus",p),window.removeEventListener("storage",u)}},[]);const m=o.useCallback(()=>{a(!0);const p=kn();if(!p){jt(!0);return}if(p.permission!=="default"){s(p.permission),jt(!0);return}if(c.current)return;c.current=!0,l(!0);const u=h.current;p.requestPermission().then(s).catch(d=>{console.warn("[task-notifications] permission request failed:",d),s(kt())}).finally(()=>{h.current===u&&jt(!0),c.current=!1,l(!1)})},[]),f=o.useCallback(()=>{h.current+=1,a(!1),jt(!1)},[]);return t.jsx(Rs.Provider,{value:{permission:n,preferenceEnabled:r,enabled:n==="granted"&&r,requesting:i,enable:m,disable:f},children:e})}function Cs(){const e=o.useContext(Rs);if(!e)throw new Error("useTaskNotifications must be used inside TaskNotificationsProvider");return e}const La=[{value:"en-US",label:"English"},{value:"zh-CN",label:"简体中文"}];function Ea({open:e,onClose:n}){const s=q(),{locale:r,saving:a,setLocale:i}=cs(),{show:l}=ke(),c=async h=>{try{await i(h)}catch(m){const f=m instanceof Error?m.message:String(m);l({kind:"error",title:s.settings.languageSaveFailed(f)})}};return t.jsx(Se,{open:e,onClose:n,title:s.settings.title,size:"sm",children:t.jsxs("div",{className:"space-y-5",children:[t.jsxs("fieldset",{children:[t.jsx("legend",{className:ue,children:s.settings.language}),t.jsx("div",{className:"flex gap-4",children:La.map(h=>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===h.value,disabled:a,onChange:()=>void c(h.value)}),h.label]},h.value))})]}),t.jsx(Da,{})]})})}function Da(){const e=q(),{permission:n,enabled:s,requesting:r,enable:a,disable:i}=Cs();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:We,children:l?e.settings.taskNotificationsDenied:e.settings.taskNotificationsHint})]})}const As="topbar-actions";function On(){return typeof document>"u"?null:document.getElementById(As)}function Ps({children:e}){const[n,s]=o.useState(On);return o.useEffect(()=>{n||s(On())},[n]),n?Qs.createPortal(e,n):null}function $a(){return gs("/api/realtime")}class Ia{constructor(n={}){oe(this,"wsUrl");oe(this,"wsFactory");oe(this,"tokenProvider");oe(this,"ws",null);oe(this,"topics",new Map);oe(this,"cache",new Map);oe(this,"outbox",[]);oe(this,"reconnectScheduler");oe(this,"explicitlyClosed",!1);this.wsUrl=n.wsUrl??$a(),this.wsFactory=n.wsFactory??xs,this.tokenProvider=n.tokenProvider??un,this.reconnectScheduler=new hs({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.${ps(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&&(fs(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 Jt=null;function it(){return Jt||(Jt=new Ia),Jt}function jn(){const[e,n]=o.useState(null),[s,r]=o.useState(!1),[a,i]=o.useState(null);return o.useEffect(()=>it().subscribe("agents",c=>{i(null),n(c),r(!0)},c=>i(c)),[]),{data:e,loaded:s,error:a}}function Ls(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),it().subscribe(`task:${e}`,h=>{l(null),s(h),a(!0)},h=>l(h))),[e]),{data:n,loaded:r,error:i}}function Es(e){const[n,s]=o.useState(null),[r,a]=o.useState(!1),[i,l]=o.useState(null);return o.useEffect(()=>{if(!e){s(null),a(!1),l(null);return}s(null),a(!1),l(null);let c=!1,h=!1,m=!1;const f=it().subscribe(`project-tasks:${e}`,p=>{c||(h=!0,l(null),s(p),a(!0))},p=>{c||(l(p),!(h||m)&&(m=!0,$.tasks.list(e).then(u=>{c||h||(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 At=null,Be=null,Pt=null,nt=0;const rn=new Set;function Ds(){rn.forEach(e=>e())}async function Ba(){const e=nt;try{const n=await $.projects.list();if(e!==nt)return;At=n,Pt=null}catch(n){if(e!==nt)return;Pt=n instanceof Error?n.message:String(n)}finally{e===nt&&(Be=null,Ds())}}function an(){return Be||(Be=Ba(),Be)}function Ma(){nt+=1,At=null,Be=null,Pt=null,Ds()}typeof window<"u"&&window.addEventListener(st,Ma);async function Fa(){const e=Be!==null;await an(),e&&await an()}function ot(){const[,e]=o.useState(0);return o.useEffect(()=>{const n=()=>e(s=>s+1);return rn.add(n),At===null&&!Be&&an(),()=>{rn.delete(n)}},[]),{projects:At,error:Pt,refresh:Fa}}function Oa(){const e=q(),n=De(),{projects:s,error:r,refresh:a}=ot(),i=s??[],l=s!==null,[c,h]=o.useState(!1),[m,f]=o.useState(!1),[p,u]=o.useState(!1),[d,x]=o.useState(!1),[y,w]=o.useState({kind:"closed"}),{data:C,loaded:S,error:R}=jn(),v=(R==null?void 0:R.message)??null,b=new Map((C??[]).map(I=>[I.id,I])),j=r??v,k=i.length===0,E=t.jsx("button",{type:"button",onClick:()=>f(!0),disabled:k,"aria-describedby":k?"create-task-hint":void 0,className:"btn-ghost",children:e.dashboard.newTask});return t.jsxs("div",{children:[t.jsxs(Ps,{children:[k?t.jsx("span",{className:"inline-flex",title:e.dashboard.createProjectFirst,children:E}):E,k&&t.jsx("span",{id:"create-task-hint",className:"sr-only",children:e.dashboard.createProjectFirst}),t.jsx(ln,{ariaLabel:e.dashboard.moreActions,children:I=>t.jsxs(t.Fragment,{children:[t.jsx(Ne,{onClick:()=>{I(),h(!0)},children:e.dashboard.newProject}),t.jsx(Ne,{onClick:()=>{I(),u(!0)},children:e.dashboard.manageHosts}),t.jsx(Ne,{onClick:()=>{I(),x(!0)},children:e.settings.entry})]})})]}),t.jsx("h1",{className:"sr-only",children:"Dashboard"}),j&&t.jsx("div",{className:"mb-4 text-sm text-accent",children:e.common.loadFailed(j)}),l&&i.length===0&&!r&&t.jsx("div",{className:"rounded-lg border border-hairline bg-surface py-12 text-center text-sm text-og-500",children:e.dashboard.emptyProjects}),i.map(I=>t.jsx(_a,{project:I,agentsById:b,agentsLoaded:S,agentsError:!!R,onAgentDeleted:a},I.id)),t.jsx(wa,{open:c,onClose:()=>h(!1),onCreated:I=>{h(!1),a(),w({kind:"asking",projectId:I})}}),t.jsx(Aa,{open:p,onClose:()=>u(!1)}),t.jsx(Se,{open:y.kind==="asking",onClose:()=>w({kind:"closed"}),title:e.dashboard.projectCreatedTitle,size:"sm",footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:()=>w({kind:"closed"}),className:"btn-secondary",children:e.dashboard.later}),t.jsx("button",{type:"button",onClick:()=>{y.kind==="asking"&&w({kind:"addingAgent",projectId:y.projectId})},className:"btn-primary",children:e.dashboard.continueAddingAgent})]}),children:t.jsx("p",{className:"text-sm text-og-700",children:e.dashboard.addAgentNowOrLater})}),y.kind==="addingAgent"&&t.jsx(Ss,{open:!0,projectId:y.projectId,onClose:()=>w({kind:"closed"}),onCreated:()=>{a()}}),t.jsx(yn,{open:m,onClose:()=>f(!1),onCreated:I=>n(Ee(I.projectId,I.id))}),t.jsx(Ea,{open:d,onClose:()=>x(!1)})]})}function _a({project:e,agentsById:n,agentsLoaded:s,agentsError:r,onAgentDeleted:a}){const i=q(),{data:l,error:c}=Es(e.id),h=l??[],m=(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(Le,{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(Le,{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})]}),m&&t.jsx("div",{className:"mb-2 text-xs text-accent",children:i.dashboard.tasksLoadFailed(m)}),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(Ns,{team:f,projectId:e.id,agentsById:n,agentsLoaded:s,agentsError:r,tasks:h,onDeleted:a,terminalMode:"embedded-full"},f.map(u=>u.id).join(":")||p))})]})}const $s="baxian.taskPanel.doneOpen";function Ha(){try{return localStorage.getItem($s)==="1"}catch{return!1}}function Lt(e){const n=e.match(/^task-(\d+)$/);return n?parseInt(n[1],10):Number.NaN}function qa(e,n){const s=Lt(e.id),r=Lt(n.id);return Number.isNaN(s)||Number.isNaN(r)?e.id.localeCompare(n.id):s-r}function Ua(e,n){const s=(n.updatedAt??"").localeCompare(e.updatedAt??"");if(s!==0)return s;const r=Lt(e.id),a=Lt(n.id);return Number.isNaN(r)||Number.isNaN(a)?n.id.localeCompare(e.id):a-r}function _n(e,n){const[s,r]=o.useState(Ot);o.useEffect(()=>r(Ot),[n]);const a=e.slice(0,s),i=e.length>a.length;return{items:a,hasMore:i,loadMore:()=>r(c=>c+Ot),total:e.length}}function Ga(e){const[n,s]=o.useState([]),[r,a]=o.useState(!1),[i,l]=o.useState(!1),[c,h]=o.useState(!1),[m,f]=o.useState(null),p=o.useRef(0),u=o.useRef(0),d=o.useCallback(x=>{const y=++p.current,w=x==="first"?0:u.current;l(!0),f(null),$.tasks.page(e,{category:"done",offset:w}).then(C=>{p.current===y&&(s(S=>x==="first"?C.tasks:[...S,...C.tasks]),a(C.hasMore),u.current=C.nextOffset,h(!0),l(!1))},C=>{p.current===y&&(f(C instanceof Error?C.message:String(C)),l(!1))})},[e]);return o.useEffect(()=>{p.current+=1,u.current=0,s([]),a(!1),h(!1),f(null),l(!1)},[e]),{items:n,hasMore:r,loading:i,loaded:c,error:m,load:d}}function Wa({projectId:e,openTasks:n,className:s=""}){const r=q(),a=o.useMemo(()=>n.filter(u=>cn.has(u.status)).sort(Ua),[n]),i=o.useMemo(()=>n.filter(u=>u.status==="pending").sort(qa),[n]),l=_n(a,e),c=_n(i,e),h=Ga(e),[m,f]=o.useState(Ha);o.useEffect(()=>{try{localStorage.setItem($s,m?"1":"0")}catch{}},[m]),o.useEffect(()=>{m&&h.load("first")},[m,h.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(Hn,{title:r.taskPanel.inProgressTitle,section:l,emptyHint:r.taskPanel.emptyInProgress}),t.jsx(Hn,{title:r.taskPanel.pendingTitle,section:c,emptyHint:r.taskPanel.emptyPending}),t.jsxs("div",{children:[t.jsxs("button",{type:"button",onClick:p,"aria-expanded":m,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:m?r.taskPanel.collapse:r.taskPanel.view})]}),m&&t.jsx(za,{state:h})]})]})})}function Hn({title:e,section:n,emptyHint:s}){const r=q();return t.jsxs("section",{"aria-label":e,className:"border-b border-hairline",children:[t.jsxs("div",{className:"px-3 py-2 text-xs font-normal uppercase tracking-[0.05em] text-og-500",children:[e," ",t.jsxs("span",{className:"text-og-400",children:["(",n.total,")"]})]}),n.items.length===0?t.jsx("div",{className:"px-3 pb-3 text-xs text-og-400",children:s}):t.jsxs("div",{className:"divide-y divide-hairline",children:[n.items.map(a=>t.jsx(Is,{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 za({state:e}){const n=q(),s=e.loaded&&!e.error&&e.items.length===0;return t.jsxs("div",{className:"divide-y divide-hairline",children:[e.items.map(r=>t.jsx(Is,{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 Is({task:e}){const n=q(),s=De(),{show:r}=ke(),[a,i]=o.useState(!1),l=Me(e.phase)?e.specReviewRound??0:e.reviewRound,c=e.status==="pending"&&e.preferredAgentId==="",h=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,m=e.attention?ws(n,e.attention):null,f=()=>s(Ee(e.projectId,e.id)),p=async()=>{if(c||e.postApproveRevoked||e.status==="review"&&Qn(e)){f();return}i(!0);try{await $.tasks.advance(e.id),r({kind:"success",title:n.taskDetail.advanceSucceededTitle})}catch(u){r({kind:"error",title:n.taskDetail.advanceFailedTitle,body:n.taskDetail.actionFailedBody,details:u instanceof Error?u.message:String(u)})}finally{i(!1)}};return t.jsxs("div",{className:"px-3 py-2",children:[t.jsx("div",{className:"flex items-center gap-2 text-sm",children:t.jsxs("button",{type:"button",onClick: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:vn(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(bn,{task:e,className:"shrink-0"})]})}),e.attention&&m&&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:m.title}),t.jsx("span",{className:"mt-0.5 block text-og-700",children:m.guidance})]}),t.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1.5",children:e.attention.recommendedActions.map(u=>t.jsx("button",{type:"button",disabled:u==="advance"&&a,onClick:()=>u==="advance"?void p():f(),className:u==="advance"?"btn-primary":"btn-secondary",children:u==="advance"?a?n.taskDetail.advancing:h:u==="verdict"?n.taskDetail.handleReview:u==="cancel"?n.taskDetail.cancelConfirmLabel:n.taskDetail.retryTask},u))}),t.jsxs("details",{className:"mt-1.5 text-og-500",children:[t.jsx("summary",{className:"cursor-pointer select-none text-accent",children:n.common.technicalDetails}),t.jsxs("div",{className:"mt-1 whitespace-pre-wrap break-words font-mono",children:[e.attention.reason,`
11
11
  `,e.attention.runbook]})]})]})]})}const Va=[],Bs="baxian.taskPanel.open";function Ka(){try{return localStorage.getItem(Bs)!=="0"}catch{return!0}}function Ya(){const{id:e}=Et(),n=De(),s=q(),{show:r}=ke(),{refresh:a}=ot(),[i,l]=o.useState(null),[c,h]=o.useState(null),[m,f]=o.useState(!1),[p,u]=o.useState(!1),d=o.useRef(null),[x,y]=o.useState(Ka),[w,C]=o.useState(!1),[S,R]=o.useState(""),[v,b]=o.useState(!1),[j,k]=o.useState(null),E=o.useRef(0),{data:I,loaded:_,error:F}=jn(),{data:te,error:z}=Es(e),K=(F==null?void 0:F.message)??null,re=(z==null?void 0:z.message)??null,Z=te??Va,ne=new Map((I??[]).map(H=>[H.id,H])),Y=c??K??re,se=o.useCallback(async H=>{const le=++E.current;try{const ce=await $.projects.get(H);if(le!==E.current)return;l(ce),h(null)}catch(ce){if(le!==E.current)return;h(ce instanceof Error?ce.message:String(ce))}},[]);o.useEffect(()=>{e&&(l(null),h(null),se(e))},[e,se]),o.useEffect(()=>{w||(R(""),k(null))},[w]),o.useEffect(()=>{try{localStorage.setItem(Bs,x?"1":"0")}catch{}},[x]);const ee=(i==null?void 0:i.agent.flat().length)??0,J=ee===0,me=!!i&&S.trim()===i.id,ge=async()=>{if(!(!i||!me||v)){b(!0),k(null);try{await $.projects.delete(i.id),await a(),r({kind:"success",title:s.projectPage.deletedToastTitle(i.id)}),C(!1),n("/")}catch(H){k(H instanceof Error?H.message:String(H))}finally{b(!1)}}};return i?t.jsxs("div",{children:[t.jsxs(Ps,{children:[t.jsx("button",{type:"button",onClick:()=>u(!0),className:"btn-ghost",children:s.projectPage.newTaskButton}),t.jsx(ln,{ariaLabel:s.projectPage.menuAriaLabel(i.id),menuClassName:"min-w-[180px]",triggerRef:d,children:H=>t.jsxs(t.Fragment,{children:[!x&&t.jsx(Ne,{onClick:()=>{H(),y(!0)},children:s.projectPage.showTaskPanel}),t.jsx(Ne,{onClick:()=>{H(),f(!0)},children:s.projectPage.addAgent}),t.jsx("div",{role:"none",className:"my-1 border-t border-hairline"}),t.jsx(Ne,{onClick:()=>{H(),C(!0)},disabled:!J,title:J?void 0:s.projectPage.deleteAgentsFirstHint(ee),children:s.projectPage.deleteProjectMenuItem})]})})]}),Y&&t.jsx("div",{className:"mb-4 text-sm text-accent",children:s.common.loadFailed(Y)}),t.jsxs("div",{className:"mb-6 flex items-baseline gap-x-3",children:[t.jsx("h1",{className:"min-w-0 truncate font-display text-sm font-semibold tracking-tight text-og-1000",title:i.id,children:i.id}),t.jsx("span",{className:"hidden min-w-0 truncate font-mono text-xs text-og-500 sm:inline-block",title:i.repo,children:i.repo})]}),t.jsxs("div",{className:"flex flex-col gap-4 lg:flex-row lg:items-start",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:"mb-3 flex h-8 items-center gap-2",children:t.jsx("h2",{className:"font-display text-xs font-semibold uppercase tracking-[0.06em] text-og-500",children:"Agents"})}),i.agent.flat().length===0?t.jsx("div",{className:"mb-8 rounded-lg border border-hairline bg-surface py-6 text-center text-sm text-og-500",children:s.projectPage.noAgentsYet}):t.jsx("div",{className:"mb-8 space-y-5",children:i.agent.map((H,le)=>t.jsx(Ns,{team:H,projectId:i.id,agentsById:ne,agentsLoaded:_,agentsError:!!F,tasks:Z,onDeleted:()=>{se(i.id)},terminalMode:"embedded-full"},H.map(ce=>ce.id).join(":")||le))})]}),x&&t.jsxs("div",{className:"w-full lg:w-[340px] lg:shrink-0 xl:w-[380px]",children:[t.jsxs("div",{className:"mb-3 flex h-8 items-center justify-between gap-2",children:[t.jsx("h2",{className:"font-display text-xs font-semibold uppercase tracking-[0.06em] text-og-500",children:"Tasks"}),t.jsx("button",{type:"button",onClick:()=>{var H;y(!1),(H=d.current)==null||H.focus()},"aria-label":s.projectPage.closeTaskPanel,className:"flex h-7 w-7 items-center justify-center rounded text-og-500 transition-colors hover:bg-og-50 hover:text-og-1000",children:t.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[t.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),t.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),t.jsx(Wa,{projectId:i.id,openTasks:Z})]})]}),t.jsx(Ss,{open:m,projectId:i.id,onClose:()=>f(!1),onCreated:()=>{se(i.id)}}),t.jsx(yn,{open:p,projectId:i.id,onClose:()=>u(!1),onCreated:H=>n(Ee(H.projectId,H.id))}),t.jsx(Se,{open:w,onClose:()=>{v||C(!1)},title:s.projectPage.deleteModalTitle,size:"sm",footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:()=>C(!1),disabled:v,className:"btn-secondary",children:s.common.cancel}),t.jsx("button",{type:"button",onClick:()=>void ge(),disabled:!me||v,className:"btn-primary",children:v?s.common.deleting:s.projectPage.confirmDeleteButton})]}),children:t.jsxs("div",{className:"space-y-4",children:[t.jsxs("p",{className:"text-sm text-og-700",children:[s.projectPage.deleteBodyLead,t.jsx("code",{className:"font-mono text-og-1000",children:"baxian.json"}),s.projectPage.deleteBodyMid,t.jsx("span",{className:"font-mono text-og-1000",children:i.id}),s.projectPage.deleteBodySuffix]}),t.jsxs("p",{className:"text-sm text-og-700",children:[s.projectPage.confirmInputLead,t.jsx("span",{className:"font-mono text-og-1000",children:i.id}),s.projectPage.confirmInputSuffix]}),t.jsx("input",{type:"text",value:S,onChange:H=>R(H.target.value),placeholder:i.id,autoComplete:"off",autoCorrect:"off",spellCheck:!1,disabled:v,"aria-label":s.projectPage.confirmInputAriaLabel,className:"w-full rounded border border-hairline bg-surface px-3 py-2 font-mono text-sm text-og-1000 focus:border-accent focus:outline-none"}),j&&t.jsx("div",{className:"rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-xs text-accent",children:j})]})})]}):c?t.jsx("div",{className:"text-sm text-accent",children:s.common.loadFailed(c)}):t.jsx("div",{className:"text-sm text-og-500",children:s.common.loading})}const Ms={approve:"pill pill-live","request-changes":"pill pill-warn",comment:"pill"};function Fs(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 at(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 It(e){if(e.id)return e.sourceKey!==void 0?`pr-${e.kind}.${e.sourceKey}.${e.id}`:`pr-${e.kind}-${e.id}`}function Os(e,n){return e.review?`round-${at(e.review,n)}`:`round-in-progress-${e.items[0]?at(e.items[0],n):n}`}function _s(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 Qa=4e3,Ja=6e4;function Hs(e,n){const[s,r]=o.useState(null),[a,i]=o.useState(!1),[l,c]=o.useState(null),[h,m]=o.useState(!1),[f,p]=o.useState(null),[u,d]=o.useState(0),x=o.useRef(e),y=o.useRef(n),w=o.useRef(0),C=o.useRef(0),S=o.useRef(void 0),R=o.useRef(0),v=o.useRef(null);o.useEffect(()=>{const j=()=>{v.current!==null&&(v.current=null,m(!1),p(null))};x.current!==e&&(x.current=e,r(null),i(!1),p(null),C.current=0,j()),y.current!==n&&(y.current=n,C.current=0,j());const k=++w.current;return c(null),$.tasks.prReview(e).then(E=>{if(w.current===k)if(r(E),i(!0),E.available&&E.error&&C.current<3){C.current+=1;const I=E.rateLimited?Ja*2**(C.current-1):Qa*C.current;S.current=setTimeout(()=>d(_=>_+1),I)}else E.error||(C.current=0)}).catch(E=>{w.current===k&&(c(E instanceof Error?E.message:String(E)),r(null),i(!0))}),()=>{clearTimeout(S.current),S.current=void 0}},[e,n,u]);const b=o.useCallback(()=>{if(v.current!==null)return;const j=++R.current;v.current=j,m(!0),p(null),$.tasks.prReviewRefresh(x.current).then(k=>{if(v.current===j){if(k.available&&(k.error!==void 0||k.rateLimited===!0)){p(k.error??"rate limited");return}clearTimeout(S.current),S.current=void 0,w.current+=1,C.current=0,r(k),i(!0),c(null)}}).catch(k=>{v.current===j&&p(k instanceof Error?k.message:String(k))}).finally(()=>{v.current===j&&(v.current=null,m(!1))})},[]);return{data:s,loaded:a,error:l,refresh:b,refreshing:h,refreshError:f}}function Xa(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 qs({data:e,onRefresh:n,refreshing:s,refreshError:r}){const a=q(),i=e.autoRefresh===!0?e.autoRefreshIntervalMs:void 0,[l,c]=o.useState(void 0),h=o.useRef(Date.now());return o.useEffect(()=>{h.current=Date.now()},[e]),o.useEffect(()=>{if(i===void 0||i<=0){c(void 0);return}const m=()=>{const p=Date.now()-h.current;c(Math.ceil((i-p%i)/1e3))};m();const f=setInterval(m,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(Xa(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 Za({role:e,label:n,summary:s,badge:r,onClick:a}){const i=q();return t.jsxs("button",{type:"button",onClick:a,className:"card flex w-full items-center gap-2 px-3 py-2 text-left text-sm",children:[t.jsx("span",{className:"shrink-0 min-w-[1.75rem] text-xs tracking-wide text-og-600",children:e==="qa"?i.review.roleQa:e==="user"?i.review.roleUser:i.review.roleDev}),t.jsx("span",{className:"shrink-0 text-og-800",children:n}),r,t.jsx("span",{className:"min-w-0 flex-1 truncate text-og-500",children:s}),t.jsx("span",{"aria-hidden":!0,className:"shrink-0 text-og-300",children:"›"})]})}function ei(e){return{"no-pr":e.prReview.reasonNoPr,"driver-unavailable":e.prReview.reasonDriverUnavailable}}function ti(e){return(e==null?void 0:e.trim().split(`
12
- `,1)[0])??""}function ni(e){if(!(e.kind!=="review-comment"||!e.path))return e.line!==void 0?`${e.path}:${e.line}`:e.path}function si(e,n){return n.bodyTruncated?e.prReview.truncatedSuffix:""}function ri(e,n){const s=ti(n.body),r=si(e,n);if(n.kind==="review-comment"){const a=ni(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 ai(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 ii(e){return e.verdict!==void 0?"qa":e.kind==="issue-comment"||e.inReplyTo?"dev":"qa"}function oi({task:e}){const n=q(),s=De(),r=_s(e),{data:a,loaded:i,error:l,refresh:c,refreshing:h,refreshError:m}=Hs(e.id,r),f=Me(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(et,{title:f,children:t.jsx("div",{className:"text-sm text-accent",children:n.review.loadFailed(l)})});if(!i)return t.jsx(et,{title:f,children:t.jsx("div",{className:"text-sm text-og-400",children:n.review.loadingRecords})});if(!(a!=null&&a.available)){const x=ei(n);return t.jsx(et,{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(qs,{data:a,onRefresh:c,refreshing:h,refreshError:m});if(a.items.length===0)return t.jsxs(et,{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=Fs(a.items);return t.jsxs(et,{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,y)=>t.jsx(li,{round:x,index:y,onOpen:p},Os(x,String(y))))]})}function et({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 li({round:e,index:n,onOpen:s}){const r=q(),a=e.review?r.agents.round(n+1):r.status.in_progress;return t.jsxs("div",{children:[t.jsx("div",{className:"mb-1 text-xs text-og-400",children:a}),t.jsxs("div",{className:"space-y-1.5",children:[e.items.map((i,l)=>t.jsx(qn,{item:i,onOpen:s},at(i,`${n}-${l}`))),e.review&&t.jsx(qn,{item:e.review,onOpen:s})]})]})}function qn({item:e,onOpen:n}){const s=q(),r=e.verdict,a=r?t.jsx("span",{className:Ms[r],children:r}):e.kind==="review"&&e.reviewState?t.jsx("span",{className:"pill",children:e.reviewState}):void 0;return t.jsx(Za,{role:ii(e),label:ai(s,e),badge:a,summary:ri(s,e),onClick:()=>n(It(e))})}function ci({task:e}){const n=q();return e.prNumber===void 0?null:t.jsxs("section",{className:"mt-4","aria-label":n.review.sectionTitle,children:[t.jsx("div",{className:"mb-2 text-sm text-og-700",children:n.review.sectionTitle}),t.jsx(oi,{task:e})]})}const di=Zn;function ui(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 Un(e){if(!/^[1-9]\d*$/.test(e.trim()))return;const n=Number(e);return Number.isSafeInteger(n)?n:void 0}function mi(e){return e.status==="review"&&!Me(e.phase)}function Tt({children:e}){const n=q();return t.jsxs("details",{className:"mt-2 text-xs text-og-500",children:[t.jsx("summary",{className:"cursor-pointer select-none text-accent",children:n.common.technicalDetails}),t.jsx("div",{className:"mt-1 whitespace-pre-wrap break-words font-mono",children:e})]})}function hi(){const{taskId:e=""}=Et();return t.jsx(fi,{taskId:e},e)}function fi({taskId:e}){var mt;const n=De(),s=q(),{show:r}=ke(),a=gn(),[i,l]=o.useState(!1),[c,h]=o.useState(!1),[m,f]=o.useState(!1),[p,u]=o.useState(!1),[d,x]=o.useState(!1),[y,w]=o.useState("spec"),[C,S]=o.useState(""),[R,v]=o.useState(!1),[b,j]=o.useState(!1),[k,E]=o.useState(!1),[I,_]=o.useState(""),[F,te]=o.useState(!1),[z,K]=o.useState(""),[re,Z]=o.useState(!1),[ne,Y]=o.useState(null),{data:se,loaded:ee,error:J}=Ls(e),{projects:me,error:ge}=ot(),{data:H,loaded:le,error:ce}=jn(),{activeAgentId:ae,activateAgentCard:ye}=Ts(),N=ne??se,xe=N!==null&&mi(N),be=xe&&(re||((mt=N==null?void 0:N.attention)==null?void 0:mt.recommendedActions.includes("verdict"))===!0),P=(J==null?void 0:J.message)??null,T=N?me==null?void 0:me.find(g=>g.id===N.projectId):void 0,B=T===void 0?"unknown":T.merge==="auto"?"auto":"manual",M=me===null&&ge===null,he=o.useMemo(()=>new Map((H??[]).map(g=>[g.id,g])),[H]);o.useEffect(()=>{ne&&se&&se.updatedAt>=ne.updatedAt&&Y(null)},[ne,se]),o.useEffect(()=>{Z(!1)},[N==null?void 0:N.status,N==null?void 0:N.reviewRound]);const ie=g=>{Y(g)},D=g=>({body:s.taskDetail.actionFailedBody,details:g instanceof Error?g.message:String(g)}),A=(g,O)=>{const W=O??(g.status==="review"?"qa":"dev");return g.status==="pending"?g.preferredAgentId===""?s.taskDetail.editTask:s.taskDetail.startTask:W==="qa"&&g.status!=="review"?s.taskDetail.startReview:g.status==="review"?s.taskDetail.restartReview:g.status==="approved"?s.taskDetail.retryPreMergeCheck:s.taskDetail.retryCurrentStep},L=()=>M?s.taskDetail.loadingMergeSetting:B==="auto"?s.taskDetail.confirmAndMerge:B==="manual"?s.taskDetail.confirmComplete:s.taskDetail.confirmResult,Q=async()=>{if(!N)return;const g=Zn.has(N.status);if(await a({title:s.taskDetail.cancelConfirmTitle(N.id),body:g?s.taskDetail.cancelConfirmBodyTerminal:s.taskDetail.cancelConfirmBodyActive,confirmLabel:s.taskDetail.cancelConfirmLabel,cancelLabel:s.common.backText})){h(!0);try{const W=await $.tasks.update(N.id,{status:"cancelled"});ie(W),r({kind:"success",title:W.status==="cancelled"?s.taskDetail.cancelledToastTitle:s.taskDetail.cancelCleanupToastTitle})}catch(W){r({kind:"error",title:s.taskDetail.cancelFailedTitle,...D(W)})}finally{h(!1)}}},G=async(g,O,W)=>{u(!0);try{const de=await $.tasks.advance(g.id,{executor:O,...g.status==="pending"&&g.preferredAgentId?{agentId:g.preferredAgentId}:{},...W??{}});ie(de),x(!1),r({kind:"success",title:s.taskDetail.advanceSucceededTitle})}catch(de){r({kind:"error",title:s.taskDetail.advanceFailedTitle,...D(de)})}finally{u(!1)}},X=async g=>{var ve;if(!N)return;if(N.status==="pending"&&N.preferredAgentId===""){l(!0);return}const O=g??(N.status==="review"?"qa":"dev"),W=A(N,O);if(O==="qa"&&Qn(N)){w(N.phase??"spec"),S(((ve=N.prNumber)==null?void 0:ve.toString())??""),x(!0);return}if(N.postApproveRevoked){if(!await a({title:s.taskDetail.advanceRevokedConfirmTitle,body:N.postApproveRevoked.reason==="request-changes"?s.taskDetail.advanceRevokedRequestChangesBody:s.taskDetail.advanceRevokedRetryLimitBody,confirmLabel:W}))return;await G(N,O,{confirmRevoked:!0});return}await a({title:s.taskDetail.advanceConfirmTitle(W),body:N.status==="pending"?s.taskDetail.startTaskConfirmBody(N.id,N.preferredAgentId):O==="qa"&&N.status==="review"?s.taskDetail.restartReviewConfirmBody(N.id):O==="qa"?s.taskDetail.startReviewConfirmBody(N.id):N.status==="approved"?s.taskDetail.retryPreMergeConfirmBody:s.taskDetail.retryCurrentStepConfirmBody(N.id),confirmLabel:W})&&await G(N,O)},we=async()=>{if(!(!N||!await a({title:s.taskDetail.retryConfirmTitle(N.id),body:N.status==="merged"?s.taskDetail.retryConfirmBodyMerged:s.taskDetail.retryConfirmBodyDefault,confirmLabel:s.taskDetail.retryTask}))){f(!0);try{const O=await $.tasks.retry(N.id);r({kind:"success",title:s.taskDetail.retryCreatedToastTitle(O.id)}),n(Ee(O.projectId,O.id))}catch(O){r({kind:"error",title:s.taskDetail.retryFailedTitle,...D(O)})}finally{f(!1)}}},Fe=async()=>{if(N&&await a({title:s.taskDetail.markCompleteConfirmTitle,body:s.taskDetail.markCompleteConfirmBody(N.prNumber??0),confirmLabel:s.taskDetail.verdictComplete})){v(!0);try{const g=await $.tasks.verdict(N.id,{action:"complete"});ie(g),r({kind:"success",title:s.taskDetail.markCompleteToastTitle})}catch(g){r({kind:"error",title:s.taskDetail.markCompleteFailedTitle,...D(g)})}finally{v(!1)}}},qe=async()=>{if(N&&await a({title:s.taskDetail.continueConfirmTitle,body:s.taskDetail.continueConfirmBody(N.reviewRound+1),confirmLabel:s.taskDetail.verdictContinue})){j(!0);try{const g=await $.tasks.verdict(N.id,{action:"continue"});ie(g),r({kind:"success",title:s.taskDetail.continuedToastTitle(g.reviewRound)})}catch(g){r({kind:"error",title:s.taskDetail.continueFailedTitle,...D(g)})}finally{j(!1)}}},$e=async(g,O)=>{if(N){E(!0);try{const W=await $.tasks.verdict(N.id,{action:g.verdict,...g.comments!==void 0?{comments:g.comments}:{}});ie(W),_(""),r({kind:"success",title:O.success})}catch(W){r({kind:"error",title:O.failure,...D(W)})}finally{E(!1)}}},Re=async()=>{N&&await a({title:s.taskDetail.specApproveConfirmTitle,body:s.taskDetail.specApproveConfirmBody(N.id),confirmLabel:s.taskDetail.specApprove})&&await $e({verdict:"approve"},{success:s.taskDetail.specApprovedToastTitle,failure:s.taskDetail.specApproveFailedTitle})},Ce=async()=>{const g=I.trim();g&&await $e({verdict:"request-changes",comments:g},{success:s.taskDetail.specRejectedToastTitle,failure:s.taskDetail.specRejectFailedTitle})},Qe=async g=>{if(!N)return;const O=z.trim();if(!(g==="request-changes"&&!O||!await a({title:g==="pass"?s.taskDetail.codePassConfirmTitle:s.taskDetail.codeRejectConfirmTitle,body:s.taskDetail.codeVerdictConfirmBody,confirmLabel:g==="pass"?s.taskDetail.codePass:s.taskDetail.codeRequestChanges}))){te(!0);try{const de=await $.tasks.verdict(N.id,{action:g,...O?{comments:O}:{}});ie(de),K(""),r({kind:"success",title:s.taskDetail.codeVerdictSubmittedTitle})}catch(de){r({kind:"error",title:s.taskDetail.codeVerdictFailedTitle,...D(de)})}finally{te(!1)}}},lt=()=>{var g;(g=document.getElementById("task-verdict-controls"))==null||g.scrollIntoView({behavior:"smooth",block:"center"})},ct=async()=>{if(!N||M)return;const g=N.prNumber??0,O=B==="auto"?s.taskDetail.confirmAutoMergeTitle(g):B==="manual"?s.taskDetail.confirmManualCompleteTitle:s.taskDetail.confirmResultTitle,W=B==="auto"?s.taskDetail.confirmAutoMergeBody(g):B==="manual"?s.taskDetail.confirmManualCompleteBody(g):s.taskDetail.confirmResultBody;if(await a({title:O,body:W,confirmLabel:L()})){v(!0);try{const de=await $.tasks.verdict(N.id,{action:"confirm-merge"});ie(de),r({kind:"success",title:de.status==="merged"?s.taskDetail.confirmedMergedToastTitle:s.taskDetail.confirmedCompleteToastTitle})}catch(de){r({kind:"error",title:s.taskDetail.confirmFailedTitle,...D(de)})}finally{v(!1)}}};return t.jsxs("div",{children:[t.jsx("button",{type:"button",onClick:()=>n(-1),className:"btn-ghost mb-3",children:s.common.back}),P&&!N&&t.jsx("div",{className:"text-sm text-accent",children:s.common.loadFailed(P)}),ee&&!N&&!P&&t.jsx("div",{className:"text-sm text-accent",children:s.taskDetail.taskNotFound(e)}),!N&&!P&&!ee&&t.jsx("div",{className:"text-sm text-og-500",children:s.common.loading}),N&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mb-4",children:t.jsxs("h1",{className:"flex min-w-0 items-baseline gap-2",children:[t.jsx("span",{className:"shrink-0 font-mono text-sm text-og-400",children:N.id}),t.jsx("span",{className:"min-w-0 truncate font-display text-sm font-semibold tracking-tight text-og-1000",title:N.title,children:N.title})]})}),t.jsxs("div",{className:"grid grid-cols-1 items-start gap-6 lg:grid-cols-2",children:[t.jsx("section",{className:"min-w-0",children:dt(N)}),t.jsx("aside",{className:"min-w-0 space-y-4",children:je(N)})]})]}),i&&N&&t.jsx(yn,{mode:"edit",open:!0,onClose:()=>l(!1),task:N,onUpdated:ie}),d&&N&&t.jsx(Se,{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||N.prNumber===void 0&&Un(C)===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 O=N.prNumber??Un(C);O===void 0||p||G(N,"qa",{stage:y,...N.prNumber===void 0?{prNumber:O}:{}})},children:[t.jsx("p",{className:"text-sm text-og-700",children:s.taskDetail.reviewRecoveryBody}),N.prNumber===void 0&&t.jsxs("div",{children:[t.jsx("label",{htmlFor:"review-recovery-pr-number",className:"mb-1 block text-sm text-og-700",children:s.taskDetail.reviewRecoveryPrNumberLabel}),t.jsx("input",{id:"review-recovery-pr-number",type:"number",min:1,step:1,value:C,required:!0,disabled:p,onChange:g=>S(g.target.value),placeholder:s.taskDetail.reviewRecoveryPrNumberPlaceholder,className:fe})]}),t.jsxs("div",{children:[t.jsx("label",{htmlFor:"review-recovery-stage",className:"mb-1 block text-sm text-og-700",children:s.taskDetail.reviewRecoveryStageLabel}),t.jsxs("select",{id:"review-recovery-stage",value:y,required:!0,disabled:p||N.phase!==void 0,onChange:g=>w(g.target.value),className:fe,children:[t.jsx("option",{value:"spec",children:s.taskDetail.reviewRecoveryStageSpec}),t.jsx("option",{value:"code",children:s.taskDetail.reviewRecoveryStageCode})]})]})]})})]});function dt(g){var pt;const O=g.preferredAgentId==="",W=g.status==="approved"&&g.prNumber!==void 0,de=g.status==="merge-ready"&&g.prNumber!==void 0,ve=g.status==="spec-ready",Ae=be,Mt=g.status==="max_rounds"&&!Me(g.phase),ht=g.status==="max_rounds"&&Me(g.phase),Pe=es(g.prUrl),ft=ui(Pe??void 0,g.branch??""),Ge=g.attention?ws(s,g.attention):null,Ft=(H??[]).some(Vs=>Yn(Vs,g.id));return t.jsxs("div",{children:[P&&t.jsx("div",{className:"mb-4 text-sm text-accent",children:s.common.loadFailed(P)}),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(Tt,{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(Tt,{children:g.branchCleanupSkipped.reason})]}),O&&t.jsx("div",{className:"mb-4 rounded-md border border-accent/25 bg-accent-soft/60 px-3 py-2.5 text-xs text-accent",children: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(bn,{task:g,className:"text-sm"}),Ft&&t.jsx("span",{"data-testid":"task-dispatching",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:Bt(g)}),t.jsxs("div",{className:"mb-4 text-sm text-og-500",children:[s.taskDetail.createdAtPrefix,Wt(g.createdAt,!1),s.taskDetail.updatedAtPrefix,Wt(g.updatedAt,!1),g.origin&&t.jsxs(t.Fragment,{children:[s.taskDetail.originPrefix,t.jsx(Le,{to:Ee(g.projectId,g.origin.taskId),className:"underline hover:text-og-700",children:g.origin.taskId})]})]}),g.attention&&Ge&&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:Ge.title}),t.jsx("div",{className:"mt-1 text-og-700",children:Ge.guidance}),t.jsx("div",{className:"mt-1 text-xs text-og-500",children:Wt(g.attention.occurredAt)}),t.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:U(g)}),t.jsx(Tt,{children:`${g.attention.reason}
13
- ${g.attention.runbook}`})]}),W&&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}),Pe&&t.jsx("a",{href:Pe,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:B==="auto"?s.taskDetail.mergeReadyAutoBody(g.prNumber??0):B==="manual"?s.taskDetail.mergeReadyManualBody(g.prNumber??0):M?s.taskDetail.mergeReadyLoadingBody:s.taskDetail.mergeReadyUnknownBody}),B==="unknown"&&ge&&t.jsx(Tt,{children:ge}),Pe&&t.jsx("a",{href:Pe,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)}),Je()]}),Ae&&t.jsxs("div",{id:"task-verdict-controls",className:`mb-4 rounded-lg p-4 text-sm ${((pt=g.attention)==null?void 0:pt.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}),ut()]}),Mt&&t.jsxs("div",{id:"task-verdict-controls",className:"mb-4 rounded-lg border border-accent/25 bg-accent-soft/60 p-4 text-sm text-accent",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.codeMaxRoundsTitle(g.reviewRound)}),t.jsx("div",{className:"mt-1 text-og-700",children:s.taskDetail.codeMaxRoundsBody})]}),ht&&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}),Je()]}),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?Pe?t.jsxs("a",{href:Pe,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?ft?t.jsx("a",{href:ft,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(ci,{task:g})]})}function Je(){return t.jsxs("div",{className:"mt-3 flex flex-col gap-2",children:[t.jsx("textarea",{value:I,onChange:g=>_(g.target.value),placeholder:s.taskDetail.specCommentsPlaceholder,rows:3,disabled:k,className:fe}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",disabled:k,onClick:Re,className:"btn-primary",children:k?s.taskDetail.submitting:s.taskDetail.specApproveButton}),t.jsx("button",{type:"button",disabled:k||I.trim()==="",onClick:Ce,title:I.trim()===""?s.taskDetail.specRejectTitleEmpty:s.taskDetail.specRejectTitleReady,className:"btn-secondary",children:k?s.taskDetail.submitting:s.taskDetail.specReject})]})]})}function ut(){return t.jsxs("div",{className:"mt-3 flex flex-col gap-2",children:[t.jsx("textarea",{value:z,onChange:g=>K(g.target.value),placeholder:s.taskDetail.codeCommentsPlaceholder,rows:3,disabled:F,className:fe}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",disabled:F,onClick:()=>void Qe("pass"),className:"btn-secondary",children:F?s.taskDetail.submitting:s.taskDetail.codePass}),t.jsx("button",{type:"button",disabled:F||z.trim()==="",onClick:()=>void Qe("request-changes"),className:"btn-secondary",children:F?s.taskDetail.submitting:s.taskDetail.codeRequestChanges})]})]})}function U(g){var O;return(O=g.attention)==null?void 0:O.recommendedActions.map(W=>W==="advance"?t.jsx("button",{type:"button",disabled:p,onClick:()=>void X(),className:"btn-primary",children:p?s.taskDetail.advancing:A(g)},W):W==="verdict"?t.jsx("button",{type:"button",onClick:lt,className:"btn-primary",children:s.taskDetail.handleReview},W):W==="cancel"?t.jsx("button",{type:"button",disabled:c,onClick:Q,className:"btn-secondary",children:c?s.taskDetail.cancelling:s.taskDetail.cancelConfirmLabel},W):t.jsx("button",{type:"button",disabled:m,onClick:we,className:"btn-secondary",children:m?s.common.retrying:s.taskDetail.retryTask},W))}function je(g){if(me===null)return t.jsx("div",{className:"rounded-lg border border-hairline bg-surface px-3 py-6 text-center text-sm text-og-400",children:s.common.loading});const O=(T==null?void 0:T.agent.find(ve=>ve.some(Ae=>Ae.id===g.devAgentId)))??(g.qaAgentId?T==null?void 0:T.agent.find(ve=>ve.some(Ae=>Ae.id===g.qaAgentId)):void 0),W=O==null?void 0:O.find(ve=>ve.role==="dev"&&ve.id===g.devAgentId),de=g.qaAgentId?O==null?void 0:O.find(ve=>ve.role==="qa"&&ve.id===g.qaAgentId):void 0;return!W&&!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:[W?Ue(g,W):t.jsx(Gn,{role:"dev"}),de?Ue(g,de):t.jsx(Gn,{role:"qa"})]})}function Ue(g,O){const W=he.get(O.id),de=W??{id:O.id,projectId:g.projectId,runtimeStatus:"unknown",tmuxSessionStatus:"unknown",stale:!0};return t.jsx(js,{agent:de,projectId:g.projectId,role:O.role,runtime:O.runtime,model:O.model,pendingRestart:le&&!W,terminalLoading:!le&&!W&&!ce,showTaskBinding:!1,terminalMode:"embedded-full",active:ae===O.id,onActivate:()=>ye(O.id),task:g},O.id)}function Bt(g){const W=g.status==="max_rounds"&&!Me(g.phase),de=g.status==="merge-ready",ve=g.status==="pending",Ae=di.has(g.status),Mt=Ae&&!!g.preferredAgentId,ht=g.preferredAgentId==="",Pe=["pending","in_progress","fixing","review","approved"].includes(g.status)&&!(g.status==="pending"&&ht),ft=(g.status==="in_progress"||g.status==="fixing")&&g.qaAgentId!==void 0,Ge=W&&g.prNumber!==void 0,Ft=Ge&&!!g.agentId,pt=xe&&!be;return t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",disabled:!ve,onClick:()=>l(!0),className:"btn-secondary",children:s.taskDetail.editTask}),t.jsx("button",{type:"button",disabled:c,onClick:Q,title:s.taskDetail.cancelForceTitle,className:"btn-secondary",children:c?s.taskDetail.cancelling:s.taskDetail.cancelConfirmLabel}),Ae&&g.replacementTaskId===void 0&&t.jsx("button",{type:"button",disabled:!Mt||m,onClick:we,title:ht?s.taskDetail.retryDisabledUnassignedTitle:s.taskDetail.retryEnabledTitle,className:"btn-secondary",children:m?s.common.retrying:s.taskDetail.retryTask}),Pe&&t.jsx("button",{type:"button",disabled:p,onClick:()=>void X(),className:"btn-primary",children:p?s.taskDetail.advancing:A(g)}),ft&&t.jsx("button",{type:"button",disabled:p,onClick:()=>void X("qa"),className:"btn-secondary",children:A(g,"qa")}),pt&&t.jsx("button",{type:"button",onClick:()=>Z(!0),className:"btn-secondary",children:s.taskDetail.handleReview}),W&&t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",disabled:!Ft||b,onClick:qe,title:s.taskDetail.continueButtonTitle,className:"btn-secondary",children:b?s.taskDetail.continuing:s.taskDetail.verdictContinue}),t.jsx("button",{type:"button",disabled:!Ge||R,onClick:Fe,title:s.taskDetail.completeButtonTitle,className:"btn-primary",children:R?s.taskDetail.completing:s.taskDetail.verdictComplete})]}),de&&t.jsx("button",{type:"button",disabled:R||M,onClick:ct,title:M?s.taskDetail.confirmLoadingTitle:s.taskDetail.confirmButtonTitle,className:"btn-primary",children:R?s.taskDetail.confirming:L()})]})}}function Gn({role:e}){const n=q();return t.jsx("div",{className:"rounded-lg border border-hairline bg-surface px-3 py-6 text-center text-sm text-og-400",children:n.taskDetail.noAgentSlot(e)})}function pi(){const{agentId:e}=Et(),{projects:n}=ot(),s=o.useMemo(()=>{if(e)for(const r of n??[])for(const a of r.agent){const i=a.find(l=>l.id===e);if(i)return i.runtime}},[e,n]);return e?t.jsxs("div",{"data-testid":"terminal-page-container",className:"flex min-h-0 flex-1 flex-col overflow-hidden border border-hairline bg-surface",children:[t.jsxs("div",{className:"flex h-8 flex-none select-none items-center gap-3 border-b border-hairline bg-page px-3 font-mono text-xs text-og-500",children:[t.jsx("span",{"aria-hidden":!0,className:"block h-1.5 w-1.5 rounded-full bg-og-1000"}),t.jsx("span",{className:"text-og-700",title:Xn(e,s),children:e})]}),t.jsx("div",{className:"min-h-0 flex-1",children:t.jsx(tt,{agentId:e,mode:"full",interactive:!0,arrowKeys:!0})})]}):t.jsx("div",{className:"text-sm text-accent",children:"No agent specified"})}const gi=65536,xi=8e3,bi=["text-[18px] font-bold","text-[17px] font-bold","text-[16px] font-semibold","text-[15px] font-semibold","text-[15px] font-semibold","text-[15px] font-semibold"],vi=/^(https?:\/\/|mailto:)/i,yi=/^https?:\/\//i;function wi(e){try{const n=new URL(e).hostname.toLowerCase();return n==="githubusercontent.com"||n.endsWith(".githubusercontent.com")}catch{return!1}}function ki({src:e,alt:n}){const s=q(),[r,a]=o.useState(!1);if(r||wi(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 Wn(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 ji(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 zn(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 Us extends Error{}class Ti{constructor(n){oe(this,"count",0);this.max=n}charge(){if(++this.count>this.max)throw new Us}}function ze(e,n,s){const r=[];let a="",i=0;const l={bracket:Wn(e,"]"),paren:Wn(e,")"),whitespace:ji(e)},c=()=>{a!==""&&(n.charge(),r.push(a),a="")},h=f=>{c(),n.charge(),r.push(f)},m=()=>`${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},m())),i=p+1;continue}}else if(f==="!"&&e[i+1]==="["){const p=zn(e,i+1,l);if(p){yi.test(p.url)?h(t.jsx(ki,{src:p.url,alt:p.label},m())):a+=e.slice(i,p.end),i=p.end;continue}}else if(f==="["){const p=zn(e,i,l);if(p){if(vi.test(p.url)){c(),n.charge();const u=ze(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},m()))}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=ze(e.slice(i+3,u),n,`${s}-bi${r.length}`);r.push(t.jsx("strong",{children:t.jsx("em",{children:d})},m())),i=u+3;continue}}if(e.startsWith("**",i)){const u=e.indexOf("**",i+2);if(u>i+2){c(),n.charge();const d=ze(e.slice(i+2,u),n,`${s}-b${r.length}`);r.push(t.jsx("strong",{children:d},m())),i=u+2;continue}}const p=e.indexOf("*",i+1);if(p>i+1){c(),n.charge();const u=ze(e.slice(i+1,p),n,`${s}-i${r.length}`);r.push(t.jsx("em",{children:u},m())),i=p+1;continue}}a+=f,i++}return c(),r}function Ni(e,n){const s=[],r=e.split(`
12
+ `,1)[0])??""}function ni(e){if(!(e.kind!=="review-comment"||!e.path))return e.line!==void 0?`${e.path}:${e.line}`:e.path}function si(e,n){return n.bodyTruncated?e.prReview.truncatedSuffix:""}function ri(e,n){const s=ti(n.body),r=si(e,n);if(n.kind==="review-comment"){const a=ni(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 ai(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 ii(e){return e.verdict!==void 0?"qa":e.kind==="issue-comment"||e.inReplyTo?"dev":"qa"}function oi({task:e}){const n=q(),s=De(),r=_s(e),{data:a,loaded:i,error:l,refresh:c,refreshing:h,refreshError:m}=Hs(e.id,r),f=Me(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(et,{title:f,children:t.jsx("div",{className:"text-sm text-accent",children:n.review.loadFailed(l)})});if(!i)return t.jsx(et,{title:f,children:t.jsx("div",{className:"text-sm text-og-400",children:n.review.loadingRecords})});if(!(a!=null&&a.available)){const x=ei(n);return t.jsx(et,{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(qs,{data:a,onRefresh:c,refreshing:h,refreshError:m});if(a.items.length===0)return t.jsxs(et,{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=Fs(a.items);return t.jsxs(et,{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,y)=>t.jsx(li,{round:x,index:y,onOpen:p},Os(x,String(y))))]})}function et({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 li({round:e,index:n,onOpen:s}){const r=q(),a=e.review?r.agents.round(n+1):r.status.in_progress;return t.jsxs("div",{children:[t.jsx("div",{className:"mb-1 text-xs text-og-400",children:a}),t.jsxs("div",{className:"space-y-1.5",children:[e.items.map((i,l)=>t.jsx(qn,{item:i,onOpen:s},at(i,`${n}-${l}`))),e.review&&t.jsx(qn,{item:e.review,onOpen:s})]})]})}function qn({item:e,onOpen:n}){const s=q(),r=e.verdict,a=r?t.jsx("span",{className:Ms[r],children:r}):e.kind==="review"&&e.reviewState?t.jsx("span",{className:"pill",children:e.reviewState}):void 0;return t.jsx(Za,{role:ii(e),label:ai(s,e),badge:a,summary:ri(s,e),onClick:()=>n(It(e))})}function ci({task:e}){const n=q();return e.prNumber===void 0?null:t.jsxs("section",{className:"mt-4","aria-label":n.review.sectionTitle,children:[t.jsx("div",{className:"mb-2 text-sm text-og-700",children:n.review.sectionTitle}),t.jsx(oi,{task:e})]})}const di=Zn;function ui(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 Un(e){if(!/^[1-9]\d*$/.test(e.trim()))return;const n=Number(e);return Number.isSafeInteger(n)?n:void 0}function mi(e){return e.status==="review"&&!Me(e.phase)}function Tt({children:e}){const n=q();return t.jsxs("details",{className:"mt-2 text-xs text-og-500",children:[t.jsx("summary",{className:"cursor-pointer select-none text-accent",children:n.common.technicalDetails}),t.jsx("div",{className:"mt-1 whitespace-pre-wrap break-words font-mono",children:e})]})}function hi(){const{taskId:e=""}=Et();return t.jsx(fi,{taskId:e},e)}function fi({taskId:e}){var mt;const n=De(),s=q(),{show:r}=ke(),a=gn(),[i,l]=o.useState(!1),[c,h]=o.useState(!1),[m,f]=o.useState(!1),[p,u]=o.useState(!1),[d,x]=o.useState(!1),[y,w]=o.useState("spec"),[C,S]=o.useState(""),[R,v]=o.useState(!1),[b,j]=o.useState(!1),[k,E]=o.useState(!1),[I,_]=o.useState(""),[F,te]=o.useState(!1),[z,K]=o.useState(""),[re,Z]=o.useState(!1),[ne,Y]=o.useState(null),{data:se,loaded:ee,error:J}=Ls(e),{projects:me,error:ge}=ot(),{data:H,loaded:le,error:ce}=jn(),{activeAgentId:ae,activateAgentCard:ye}=Ts(),N=ne??se,xe=N!==null&&mi(N),be=xe&&(re||((mt=N==null?void 0:N.attention)==null?void 0:mt.recommendedActions.includes("verdict"))===!0),P=(J==null?void 0:J.message)??null,T=N?me==null?void 0:me.find(g=>g.id===N.projectId):void 0,B=T===void 0?"unknown":T.merge==="auto"?"auto":"manual",M=me===null&&ge===null,he=o.useMemo(()=>new Map((H??[]).map(g=>[g.id,g])),[H]);o.useEffect(()=>{ne&&se&&se.updatedAt>=ne.updatedAt&&Y(null)},[ne,se]),o.useEffect(()=>{Z(!1)},[N==null?void 0:N.status,N==null?void 0:N.reviewRound]);const ie=g=>{Y(g)},D=g=>({body:s.taskDetail.actionFailedBody,details:g instanceof Error?g.message:String(g)}),A=(g,O)=>{const W=O??(g.status==="review"?"qa":"dev");return g.status==="pending"?g.preferredAgentId===""?s.taskDetail.editTask:s.taskDetail.startTask:W==="qa"&&g.status!=="review"?s.taskDetail.startReview:g.status==="review"?s.taskDetail.restartReview:g.status==="approved"?s.taskDetail.retryPreMergeCheck:s.taskDetail.retryCurrentStep},L=()=>M?s.taskDetail.loadingMergeSetting:B==="auto"?s.taskDetail.confirmAndMerge:B==="manual"?s.taskDetail.confirmComplete:s.taskDetail.confirmResult,Q=async()=>{if(!N)return;const g=Zn.has(N.status);if(await a({title:s.taskDetail.cancelConfirmTitle(N.id),body:g?s.taskDetail.cancelConfirmBodyTerminal:s.taskDetail.cancelConfirmBodyActive,confirmLabel:s.taskDetail.cancelConfirmLabel,cancelLabel:s.common.backText})){h(!0);try{const W=await $.tasks.update(N.id,{status:"cancelled"});ie(W),r({kind:"success",title:W.status==="cancelled"?s.taskDetail.cancelledToastTitle:s.taskDetail.cancelCleanupToastTitle})}catch(W){r({kind:"error",title:s.taskDetail.cancelFailedTitle,...D(W)})}finally{h(!1)}}},G=async(g,O,W)=>{u(!0);try{const de=await $.tasks.advance(g.id,{executor:O,...g.status==="pending"&&g.preferredAgentId?{agentId:g.preferredAgentId}:{},...W??{}});ie(de),x(!1),r({kind:"success",title:s.taskDetail.advanceSucceededTitle})}catch(de){r({kind:"error",title:s.taskDetail.advanceFailedTitle,...D(de)})}finally{u(!1)}},X=async g=>{var ve;if(!N)return;if(N.status==="pending"&&N.preferredAgentId===""){l(!0);return}const O=g??(N.status==="review"?"qa":"dev"),W=A(N,O);if(O==="qa"&&Qn(N)){w(N.phase??"spec"),S(((ve=N.prNumber)==null?void 0:ve.toString())??""),x(!0);return}if(N.postApproveRevoked){if(!await a({title:s.taskDetail.advanceRevokedConfirmTitle,body:N.postApproveRevoked.reason==="request-changes"?s.taskDetail.advanceRevokedRequestChangesBody:s.taskDetail.advanceRevokedRetryLimitBody,confirmLabel:W}))return;await G(N,O,{confirmRevoked:!0});return}await a({title:s.taskDetail.advanceConfirmTitle(W),body:N.status==="pending"?s.taskDetail.startTaskConfirmBody(N.id,N.preferredAgentId):O==="qa"&&N.status==="review"?s.taskDetail.restartReviewConfirmBody(N.id):O==="qa"?s.taskDetail.startReviewConfirmBody(N.id):N.status==="approved"?s.taskDetail.retryPreMergeConfirmBody:s.taskDetail.retryCurrentStepConfirmBody(N.id),confirmLabel:W})&&await G(N,O)},we=async()=>{if(!(!N||!await a({title:s.taskDetail.retryConfirmTitle(N.id),body:N.status==="merged"?s.taskDetail.retryConfirmBodyMerged:s.taskDetail.retryConfirmBodyDefault,confirmLabel:s.taskDetail.retryTask}))){f(!0);try{const O=await $.tasks.retry(N.id);r({kind:"success",title:s.taskDetail.retryCreatedToastTitle(O.id)}),n(Ee(O.projectId,O.id))}catch(O){r({kind:"error",title:s.taskDetail.retryFailedTitle,...D(O)})}finally{f(!1)}}},Fe=async()=>{if(N&&await a({title:s.taskDetail.markCompleteConfirmTitle,body:s.taskDetail.markCompleteConfirmBody(N.prNumber??0),confirmLabel:s.taskDetail.verdictComplete})){v(!0);try{const g=await $.tasks.verdict(N.id,{action:"complete"});ie(g),r({kind:"success",title:s.taskDetail.markCompleteToastTitle})}catch(g){r({kind:"error",title:s.taskDetail.markCompleteFailedTitle,...D(g)})}finally{v(!1)}}},qe=async()=>{if(N&&await a({title:s.taskDetail.continueConfirmTitle,body:s.taskDetail.continueConfirmBody(N.reviewRound+1),confirmLabel:s.taskDetail.verdictContinue})){j(!0);try{const g=await $.tasks.verdict(N.id,{action:"continue"});ie(g),r({kind:"success",title:s.taskDetail.continuedToastTitle(g.reviewRound)})}catch(g){r({kind:"error",title:s.taskDetail.continueFailedTitle,...D(g)})}finally{j(!1)}}},$e=async(g,O)=>{if(N){E(!0);try{const W=await $.tasks.verdict(N.id,{action:g.verdict,...g.comments!==void 0?{comments:g.comments}:{}});ie(W),_(""),r({kind:"success",title:O.success})}catch(W){r({kind:"error",title:O.failure,...D(W)})}finally{E(!1)}}},Re=async()=>{N&&await a({title:s.taskDetail.specApproveConfirmTitle,body:s.taskDetail.specApproveConfirmBody(N.id),confirmLabel:s.taskDetail.specApprove})&&await $e({verdict:"approve"},{success:s.taskDetail.specApprovedToastTitle,failure:s.taskDetail.specApproveFailedTitle})},Ce=async()=>{const g=I.trim();g&&await $e({verdict:"request-changes",comments:g},{success:s.taskDetail.specRejectedToastTitle,failure:s.taskDetail.specRejectFailedTitle})},Qe=async g=>{if(!N)return;const O=z.trim();if(!(g==="request-changes"&&!O||!await a({title:g==="pass"?s.taskDetail.codePassConfirmTitle:s.taskDetail.codeRejectConfirmTitle,body:s.taskDetail.codeVerdictConfirmBody,confirmLabel:g==="pass"?s.taskDetail.codePass:s.taskDetail.codeRequestChanges}))){te(!0);try{const de=await $.tasks.verdict(N.id,{action:g,...O?{comments:O}:{}});ie(de),K(""),r({kind:"success",title:s.taskDetail.codeVerdictSubmittedTitle})}catch(de){r({kind:"error",title:s.taskDetail.codeVerdictFailedTitle,...D(de)})}finally{te(!1)}}},lt=()=>{var g;(g=document.getElementById("task-verdict-controls"))==null||g.scrollIntoView({behavior:"smooth",block:"center"})},ct=async()=>{if(!N||M)return;const g=N.prNumber??0,O=B==="auto"?s.taskDetail.confirmAutoMergeTitle(g):B==="manual"?s.taskDetail.confirmManualCompleteTitle:s.taskDetail.confirmResultTitle,W=B==="auto"?s.taskDetail.confirmAutoMergeBody(g):B==="manual"?s.taskDetail.confirmManualCompleteBody(g):s.taskDetail.confirmResultBody;if(await a({title:O,body:W,confirmLabel:L()})){v(!0);try{const de=await $.tasks.verdict(N.id,{action:"confirm-merge"});ie(de),r({kind:"success",title:de.status==="merged"?s.taskDetail.confirmedMergedToastTitle:s.taskDetail.confirmedCompleteToastTitle})}catch(de){r({kind:"error",title:s.taskDetail.confirmFailedTitle,...D(de)})}finally{v(!1)}}};return t.jsxs("div",{children:[t.jsx("button",{type:"button",onClick:()=>n(-1),className:"btn-ghost mb-3",children:s.common.back}),P&&!N&&t.jsx("div",{className:"text-sm text-accent",children:s.common.loadFailed(P)}),ee&&!N&&!P&&t.jsx("div",{className:"text-sm text-accent",children:s.taskDetail.taskNotFound(e)}),!N&&!P&&!ee&&t.jsx("div",{className:"text-sm text-og-500",children:s.common.loading}),N&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mb-4",children:t.jsxs("h1",{className:"flex min-w-0 items-baseline gap-2",children:[t.jsx("span",{className:"shrink-0 font-mono text-sm text-og-400",children:N.id}),t.jsx("span",{className:"min-w-0 truncate font-display text-sm font-semibold tracking-tight text-og-1000",title:N.title,children:N.title})]})}),t.jsxs("div",{className:"grid grid-cols-1 items-start gap-6 lg:grid-cols-2",children:[t.jsx("section",{className:"min-w-0",children:dt(N)}),t.jsx("aside",{className:"min-w-0 space-y-4",children:je(N)})]})]}),i&&N&&t.jsx(yn,{mode:"edit",open:!0,onClose:()=>l(!1),task:N,onUpdated:ie}),d&&N&&t.jsx(Se,{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||N.prNumber===void 0&&Un(C)===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 O=N.prNumber??Un(C);O===void 0||p||G(N,"qa",{stage:y,...N.prNumber===void 0?{prNumber:O}:{}})},children:[t.jsx("p",{className:"text-sm text-og-700",children:s.taskDetail.reviewRecoveryBody}),N.prNumber===void 0&&t.jsxs("div",{children:[t.jsx("label",{htmlFor:"review-recovery-pr-number",className:"mb-1 block text-sm text-og-700",children:s.taskDetail.reviewRecoveryPrNumberLabel}),t.jsx("input",{id:"review-recovery-pr-number",type:"number",min:1,step:1,value:C,required:!0,disabled:p,onChange:g=>S(g.target.value),placeholder:s.taskDetail.reviewRecoveryPrNumberPlaceholder,className:fe})]}),t.jsxs("div",{children:[t.jsx("label",{htmlFor:"review-recovery-stage",className:"mb-1 block text-sm text-og-700",children:s.taskDetail.reviewRecoveryStageLabel}),t.jsxs("select",{id:"review-recovery-stage",value:y,required:!0,disabled:p||N.phase!==void 0,onChange:g=>w(g.target.value),className:fe,children:[t.jsx("option",{value:"spec",children:s.taskDetail.reviewRecoveryStageSpec}),t.jsx("option",{value:"code",children:s.taskDetail.reviewRecoveryStageCode})]})]})]})})]});function dt(g){var pt;const O=g.preferredAgentId==="",W=g.status==="approved"&&g.prNumber!==void 0,de=g.status==="merge-ready"&&g.prNumber!==void 0,ve=g.status==="spec-ready",Ae=be,Mt=g.status==="max_rounds"&&!Me(g.phase),ht=g.status==="max_rounds"&&Me(g.phase),Pe=es(g.prUrl),ft=ui(Pe??void 0,g.branch??""),Ge=g.attention?ws(s,g.attention):null,Ft=(H??[]).some(Vs=>Yn(Vs,g.id));return t.jsxs("div",{children:[P&&t.jsx("div",{className:"mb-4 text-sm text-accent",children:s.common.loadFailed(P)}),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(Tt,{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(Tt,{children:g.branchCleanupSkipped.reason})]}),O&&t.jsx("div",{className:"mb-4 rounded-md border border-accent/25 bg-accent-soft/60 px-3 py-2.5 text-xs text-accent",children: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(bn,{task:g,className:"text-sm"}),Ft&&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:Bt(g)}),t.jsxs("div",{className:"mb-4 text-sm text-og-500",children:[s.taskDetail.createdAtPrefix,Wt(g.createdAt,!1),s.taskDetail.updatedAtPrefix,Wt(g.updatedAt,!1),g.origin&&t.jsxs(t.Fragment,{children:[s.taskDetail.originPrefix,t.jsx(Le,{to:Ee(g.projectId,g.origin.taskId),className:"underline hover:text-og-700",children:g.origin.taskId})]})]}),g.attention&&Ge&&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:Ge.title}),t.jsx("div",{className:"mt-1 text-og-700",children:Ge.guidance}),t.jsx("div",{className:"mt-1 text-xs text-og-500",children:Wt(g.attention.occurredAt)}),t.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:U(g)}),t.jsx(Tt,{children:`${g.attention.reason}
13
+ ${g.attention.runbook}`})]}),W&&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}),Pe&&t.jsx("a",{href:Pe,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:B==="auto"?s.taskDetail.mergeReadyAutoBody(g.prNumber??0):B==="manual"?s.taskDetail.mergeReadyManualBody(g.prNumber??0):M?s.taskDetail.mergeReadyLoadingBody:s.taskDetail.mergeReadyUnknownBody}),B==="unknown"&&ge&&t.jsx(Tt,{children:ge}),Pe&&t.jsx("a",{href:Pe,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)}),Je()]}),Ae&&t.jsxs("div",{id:"task-verdict-controls",className:`mb-4 rounded-lg p-4 text-sm ${((pt=g.attention)==null?void 0:pt.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}),ut()]}),Mt&&t.jsxs("div",{id:"task-verdict-controls",className:"mb-4 rounded-lg border border-accent/25 bg-accent-soft/60 p-4 text-sm text-accent",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.codeMaxRoundsTitle(g.reviewRound)}),t.jsx("div",{className:"mt-1 text-og-700",children:s.taskDetail.codeMaxRoundsBody})]}),ht&&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}),Je()]}),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?Pe?t.jsxs("a",{href:Pe,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?ft?t.jsx("a",{href:ft,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(ci,{task:g})]})}function Je(){return t.jsxs("div",{className:"mt-3 flex flex-col gap-2",children:[t.jsx("textarea",{value:I,onChange:g=>_(g.target.value),placeholder:s.taskDetail.specCommentsPlaceholder,rows:3,disabled:k,className:fe}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",disabled:k,onClick:Re,className:"btn-primary",children:k?s.taskDetail.submitting:s.taskDetail.specApproveButton}),t.jsx("button",{type:"button",disabled:k||I.trim()==="",onClick:Ce,title:I.trim()===""?s.taskDetail.specRejectTitleEmpty:s.taskDetail.specRejectTitleReady,className:"btn-secondary",children:k?s.taskDetail.submitting:s.taskDetail.specReject})]})]})}function ut(){return t.jsxs("div",{className:"mt-3 flex flex-col gap-2",children:[t.jsx("textarea",{value:z,onChange:g=>K(g.target.value),placeholder:s.taskDetail.codeCommentsPlaceholder,rows:3,disabled:F,className:fe}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",disabled:F,onClick:()=>void Qe("pass"),className:"btn-secondary",children:F?s.taskDetail.submitting:s.taskDetail.codePass}),t.jsx("button",{type:"button",disabled:F||z.trim()==="",onClick:()=>void Qe("request-changes"),className:"btn-secondary",children:F?s.taskDetail.submitting:s.taskDetail.codeRequestChanges})]})]})}function U(g){var O;return(O=g.attention)==null?void 0:O.recommendedActions.map(W=>W==="advance"?t.jsx("button",{type:"button",disabled:p,onClick:()=>void X(),className:"btn-primary",children:p?s.taskDetail.advancing:A(g)},W):W==="verdict"?t.jsx("button",{type:"button",onClick:lt,className:"btn-primary",children:s.taskDetail.handleReview},W):W==="cancel"?t.jsx("button",{type:"button",disabled:c,onClick:Q,className:"btn-secondary",children:c?s.taskDetail.cancelling:s.taskDetail.cancelConfirmLabel},W):t.jsx("button",{type:"button",disabled:m,onClick:we,className:"btn-secondary",children:m?s.common.retrying:s.taskDetail.retryTask},W))}function je(g){if(me===null)return t.jsx("div",{className:"rounded-lg border border-hairline bg-surface px-3 py-6 text-center text-sm text-og-400",children:s.common.loading});const O=(T==null?void 0:T.agent.find(ve=>ve.some(Ae=>Ae.id===g.devAgentId)))??(g.qaAgentId?T==null?void 0:T.agent.find(ve=>ve.some(Ae=>Ae.id===g.qaAgentId)):void 0),W=O==null?void 0:O.find(ve=>ve.role==="dev"&&ve.id===g.devAgentId),de=g.qaAgentId?O==null?void 0:O.find(ve=>ve.role==="qa"&&ve.id===g.qaAgentId):void 0;return!W&&!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:[W?Ue(g,W):t.jsx(Gn,{role:"dev"}),de?Ue(g,de):t.jsx(Gn,{role:"qa"})]})}function Ue(g,O){const W=he.get(O.id),de=W??{id:O.id,projectId:g.projectId,runtimeStatus:"unknown",tmuxSessionStatus:"unknown",stale:!0};return t.jsx(js,{agent:de,projectId:g.projectId,role:O.role,runtime:O.runtime,model:O.model,pendingRestart:le&&!W,terminalLoading:!le&&!W&&!ce,showTaskBinding:!1,terminalMode:"embedded-full",active:ae===O.id,onActivate:()=>ye(O.id),task:g},O.id)}function Bt(g){const W=g.status==="max_rounds"&&!Me(g.phase),de=g.status==="merge-ready",ve=g.status==="pending",Ae=di.has(g.status),Mt=Ae&&!!g.preferredAgentId,ht=g.preferredAgentId==="",Pe=["pending","in_progress","fixing","review","approved"].includes(g.status)&&!(g.status==="pending"&&ht),ft=(g.status==="in_progress"||g.status==="fixing")&&g.qaAgentId!==void 0,Ge=W&&g.prNumber!==void 0,Ft=Ge&&!!g.agentId,pt=xe&&!be;return t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",disabled:!ve,onClick:()=>l(!0),className:"btn-secondary",children:s.taskDetail.editTask}),t.jsx("button",{type:"button",disabled:c,onClick:Q,title:s.taskDetail.cancelForceTitle,className:"btn-secondary",children:c?s.taskDetail.cancelling:s.taskDetail.cancelConfirmLabel}),Ae&&g.replacementTaskId===void 0&&t.jsx("button",{type:"button",disabled:!Mt||m,onClick:we,title:ht?s.taskDetail.retryDisabledUnassignedTitle:s.taskDetail.retryEnabledTitle,className:"btn-secondary",children:m?s.common.retrying:s.taskDetail.retryTask}),Pe&&t.jsx("button",{type:"button",disabled:p,onClick:()=>void X(),className:"btn-primary",children:p?s.taskDetail.advancing:A(g)}),ft&&t.jsx("button",{type:"button",disabled:p,onClick:()=>void X("qa"),className:"btn-secondary",children:A(g,"qa")}),pt&&t.jsx("button",{type:"button",onClick:()=>Z(!0),className:"btn-secondary",children:s.taskDetail.handleReview}),W&&t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",disabled:!Ft||b,onClick:qe,title:s.taskDetail.continueButtonTitle,className:"btn-secondary",children:b?s.taskDetail.continuing:s.taskDetail.verdictContinue}),t.jsx("button",{type:"button",disabled:!Ge||R,onClick:Fe,title:s.taskDetail.completeButtonTitle,className:"btn-primary",children:R?s.taskDetail.completing:s.taskDetail.verdictComplete})]}),de&&t.jsx("button",{type:"button",disabled:R||M,onClick:ct,title:M?s.taskDetail.confirmLoadingTitle:s.taskDetail.confirmButtonTitle,className:"btn-primary",children:R?s.taskDetail.confirming:L()})]})}}function Gn({role:e}){const n=q();return t.jsx("div",{className:"rounded-lg border border-hairline bg-surface px-3 py-6 text-center text-sm text-og-400",children:n.taskDetail.noAgentSlot(e)})}function pi(){const{agentId:e}=Et(),{projects:n}=ot(),s=o.useMemo(()=>{if(e)for(const r of n??[])for(const a of r.agent){const i=a.find(l=>l.id===e);if(i)return i.runtime}},[e,n]);return e?t.jsxs("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden border border-hairline bg-surface",children:[t.jsxs("div",{className:"flex h-8 flex-none select-none items-center gap-3 border-b border-hairline bg-page px-3 font-mono text-xs text-og-500",children:[t.jsx("span",{"aria-hidden":!0,className:"block h-1.5 w-1.5 rounded-full bg-og-1000"}),t.jsx("span",{className:"text-og-700",title:Xn(e,s),children:e})]}),t.jsx("div",{className:"min-h-0 flex-1",children:t.jsx(tt,{agentId:e,mode:"full",interactive:!0,arrowKeys:!0})})]}):t.jsx("div",{className:"text-sm text-accent",children:"No agent specified"})}const gi=65536,xi=8e3,bi=["text-[18px] font-bold","text-[17px] font-bold","text-[16px] font-semibold","text-[15px] font-semibold","text-[15px] font-semibold","text-[15px] font-semibold"],vi=/^(https?:\/\/|mailto:)/i,yi=/^https?:\/\//i;function wi(e){try{const n=new URL(e).hostname.toLowerCase();return n==="githubusercontent.com"||n.endsWith(".githubusercontent.com")}catch{return!1}}function ki({src:e,alt:n}){const s=q(),[r,a]=o.useState(!1);if(r||wi(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 Wn(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 ji(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 zn(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 Us extends Error{}class Ti{constructor(n){oe(this,"count",0);this.max=n}charge(){if(++this.count>this.max)throw new Us}}function ze(e,n,s){const r=[];let a="",i=0;const l={bracket:Wn(e,"]"),paren:Wn(e,")"),whitespace:ji(e)},c=()=>{a!==""&&(n.charge(),r.push(a),a="")},h=f=>{c(),n.charge(),r.push(f)},m=()=>`${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},m())),i=p+1;continue}}else if(f==="!"&&e[i+1]==="["){const p=zn(e,i+1,l);if(p){yi.test(p.url)?h(t.jsx(ki,{src:p.url,alt:p.label},m())):a+=e.slice(i,p.end),i=p.end;continue}}else if(f==="["){const p=zn(e,i,l);if(p){if(vi.test(p.url)){c(),n.charge();const u=ze(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},m()))}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=ze(e.slice(i+3,u),n,`${s}-bi${r.length}`);r.push(t.jsx("strong",{children:t.jsx("em",{children:d})},m())),i=u+3;continue}}if(e.startsWith("**",i)){const u=e.indexOf("**",i+2);if(u>i+2){c(),n.charge();const d=ze(e.slice(i+2,u),n,`${s}-b${r.length}`);r.push(t.jsx("strong",{children:d},m())),i=u+2;continue}}const p=e.indexOf("*",i+1);if(p>i+1){c(),n.charge();const u=ze(e.slice(i+1,p),n,`${s}-i${r.length}`);r.push(t.jsx("em",{children:u},m())),i=p+1;continue}}a+=f,i++}return c(),r}function Ni(e,n){const s=[],r=e.split(`
14
14
  `);let a=[];const i=()=>{if(a.length===0)return;const l=a;a=[],n.charge();const c=[];l.forEach((h,m)=>{m>0&&(n.charge(),c.push(t.jsx("br",{},`br-${s.length}-${m}`))),c.push(...ze(h,n,`p${s.length}-l${m}`))}),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 m=[];let f=l+1;for(;f<r.length&&!/^```\s*$/.test(r[f]);)m.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:m.join(`
15
15
  `)})},`pre-${s.length}`)),l=f;continue}const h=/^(#{1,6}) (.*)$/.exec(c);if(h){i(),n.charge();const m=h[1].length,f=`h${m}`;s.push(t.jsx(f,{className:bi[m-1],children:ze(c,n,`h${s.length}`)},`h-${s.length}`));continue}if(c.trim()===""){i();continue}a.push(c)}return i(),s}function Si(e){if(typeof e!="string")return[];if(e.length>gi)return null;const n=new Ti(xi);try{return n.charge(),Ni(e.replace(/\r\n/g,`
16
16
  `),n)}catch(s){if(s instanceof Us)return null;throw s}}function Ri({text:e}){const n=o.useMemo(()=>Si(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 Ci={approve:"approve","request-changes":"request-changes",comment:"comment"};function Ai(e){return e==="no-pr"||e==="driver-unavailable"?e:void 0}function Pi(e){return{"no-pr":e.prReview.reasonNoPr,"driver-unavailable":e.prReview.reasonDriverUnavailable}}function Gs(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 Li(){const e=q(),{taskId:n=""}=Et(),s=De(),{hash:r}=Kn(),{data:a}=Ls(n),i=a?_s(a):void 0,{data:l,loaded:c,error:h,refresh:m,refreshing:f,refreshError:p}=Hs(n,i),[u,d]=o.useState(null),x=(l==null?void 0:l.prNumber)??(a==null?void 0:a.prNumber),y=(l==null?void 0:l.prUrl)??(a==null?void 0:a.prUrl),w=es(y),C=l?Fs(l.items):[],S=c&&!h&&(l==null?void 0:l.available)===!0&&l.items.length>0,R=Me(a==null?void 0:a.phase)?e.prReview.specReviewHeading:e.prReview.codeReviewHeading,v=o.useRef(null),b=o.useRef(void 0);return o.useEffect(()=>()=>clearTimeout(b.current),[]),o.useEffect(()=>{let j=null;if(r)try{j=decodeURIComponent(r.slice(1))}catch{j=null}if(!j){v.current=null,d(null);return}if(v.current===j||!S||!l)return;const k=document.getElementById(j);k&&(v.current=j,k.scrollIntoView({behavior:"smooth",block:"center"}),d(j),clearTimeout(b.current),b.current=setTimeout(()=>d(null),2e3))},[S,l,r]),t.jsxs("div",{className:"mx-auto w-full max-w-5xl",children:[t.jsx("button",{type:"button",onClick:()=>s(-1),className:"btn-ghost mb-3",children:e.common.back}),t.jsxs("div",{className:"mb-1 flex flex-wrap items-baseline gap-2",children:[t.jsx("span",{className:"font-mono text-og-400",children:n}),t.jsx("span",{className:"text-sm font-semibold text-og-1000",children:(a==null?void 0:a.title)??""})]}),t.jsxs("div",{className:"mb-4 flex flex-wrap items-center gap-2 text-xs text-og-500",children:[t.jsx("span",{className:"pill",children:R}),w&&x!==void 0&&t.jsx("a",{href:w,target:"_blank",rel:"noopener noreferrer",className:"text-accent hover:text-accent-hover",children:e.taskDetail.viewPr(x)}),(l==null?void 0:l.available)&&t.jsx(qs,{data:l,onRefresh:m,refreshing:f,refreshError:p})]}),!c&&t.jsx("div",{className:"text-sm text-og-500",children:e.common.loading}),c&&h&&t.jsx("div",{className:"text-sm text-accent",children:e.review.loadFailed(h)}),c&&!h&&l&&!l.available&&t.jsx("div",{className:"text-sm text-og-500",children:Pi(e)[Ai(l.reason)??"no-pr"]}),c&&!h&&(l==null?void 0:l.available)&&(l.items.length===0?l.truncated?t.jsx("div",{className:"text-sm text-accent",children:e.prReview.listTruncated}):l.error?t.jsx("div",{className:"text-sm text-accent",children:e.prReview.fetchFailed(l.error)}):t.jsx("div",{className:"text-sm text-og-400",children:e.review.notStarted}):t.jsxs(t.Fragment,{children:[l.error&&t.jsx("div",{className:"mb-3 text-xs text-accent",children:e.prReview.partialFetchFailed(l.error)}),l.truncated&&t.jsx("div",{className:"mb-3 text-xs text-accent",children:e.prReview.listTruncated}),t.jsx("div",{className:"space-y-5",children:C.map((j,k)=>t.jsx(Ei,{round:j,index:k,flashId:u},Os(j,String(k))))})]}))]})}function Ei({round:e,index:n,flashId:s}){const r=q(),a=e.review?r.agents.round(n+1):r.status.in_progress;return t.jsxs("div",{children:[t.jsx("div",{className:"mb-1.5 text-xs font-medium text-og-700",children:a}),t.jsxs("div",{className:"space-y-2",children:[e.items.map((i,l)=>i.kind==="review"?t.jsx(Vn,{item:i,flashId:s},at(i,`${n}-${l}`)):t.jsx(Di,{item:i,flashId:s},at(i,`${n}-${l}`))),e.review&&t.jsx(Vn,{item:e.review,flashId:s})]})]})}function Ws(e,n){const s=It(e);return`card p-3 text-sm${s&&s===n?" ring-2 ring-accent":""}`}function Di({item:e,flashId:n}){const s=q(),r=e.kind==="review-comment";return t.jsxs("div",{id:It(e),className:Ws(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:Gs(e.createdAt)})]}),t.jsx(zs,{item:e})]})}function Vn({item:e,flashId:n}){const s=q(),r=e.verdict??"comment";return t.jsxs("div",{id:It(e),className:Ws(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:Ms[r],children:Ci[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:Gs(e.createdAt)})]}),t.jsx(zs,{item:e,placeholder:s.prReview.noReviewBody})]})}function zs({item:e,placeholder:n}){const s=q();return t.jsxs(t.Fragment,{children:[e.body?t.jsx("div",{className:"text-og-800",children:t.jsx(Ri,{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 $i(){const e=q(),[n,s]=o.useState(!1);return t.jsx("button",{type:"button",onClick:()=>s(r=>!r),"aria-label":n?e.nav.toggleToIcon:e.nav.toggleToText,className:"flex h-7 min-w-[60px] shrink-0 items-center justify-center font-display text-sm font-semibold tracking-tight text-og-1000",children:n?t.jsx("span",{className:"inline-flex h-6 items-center leading-none",children:"baxian"}):t.jsx("img",{src:"/baxian-logo.png",alt:"baxian",width:20,height:24,className:"block h-6 w-auto"})})}function Ii(){const[e,n]=o.useState(null),[s,r]=o.useState(!1),[a,i]=o.useState(null);return o.useEffect(()=>it().subscribe("pollers",c=>{i(null),n(c),r(!0)},c=>i(c)),[]),{data:e,loaded:s,error:a}}function Bi(e){return e.lastErrorClass==="RATE_LIMIT"&&e.rateLimitedUntil!==void 0&&Date.parse(e.rateLimitedUntil)>Date.now()}function Mi(e){const n=e.find(l=>l.lastErrorClass==="ACCESS_DENIED");if(n)return{poller:n,kind:"access-denied"};const s=e.find(l=>l.health==="failed"&&l.lastErrorClass==="NOT_FOUND");if(s)return{poller:s,kind:"not-found"};const r=e.find(l=>l.health==="failed");if(r)return{poller:r,kind:"failed"};const a=e.find(Bi);if(a)return{poller:a,kind:"rate-limited"};const i=e.find(l=>l.health==="degraded");return i?{poller:i,kind:"degraded"}:null}function Fi(){const e=q(),{data:n}=Ii();if(!n)return null;const s=Mi(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 Oi(){const e=q(),{phase:n,count:s,error:r,triggerRestart:a}=$t();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 _i=new Set(["done","merged"]);function Xt(e,n){const s=e.trim().replace(/\s+/g," ");return s.length>n?`${s.slice(0,n-1)}…`:s}function Hi(e,n){return e?e.repo?`${e.id} · ${e.repo}`:e.id:n}function qi(e){return e.title?`${e.id} · ${e.title}`:e.id}function Ui(e){return _i.has(e)}function Gi(e,n,s){const r=kn();if(!(!r||r.permission!=="granted"))try{const a=pn(),i=new r(a.notification.taskDone(Xt(e.title||e.id,80)),{body:[a.notification.bodyProject(Xt(n,120)),a.notification.bodyTask(Xt(qi(e),120)),a.notification.bodyStatus(da(e.status))].join(`