baxian 2.1.1 → 2.1.2
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,13 +7,13 @@ ${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:"任务需要你处理",attentionDirtyWorkdirTitle:"工作目录有未提交改动",attentionDirtyWorkdirGuidance:"本次操作要求工作目录干净。请在关联 Agent 的工作目录提交或暂存需要保留的改动。",attentionCheckoutTitle:"任务工作目录准备失败",attentionCheckoutGuidance:"请检查并处理下方工作目录或分支错误。",attentionReplayTitle:"任务指令未能重新发送",attentionReplayGuidance:"请检查并处理下方指令发送错误。“恢复 Agent”不会重新发送任务指令。",attentionBootstrapDeliveredTitle:"初始任务指令已经发送",attentionDeliveryUnknownTitle:"任务指令的发送结果尚未确认",attentionDeliveryUnknownGuidance:"指令可能已经在执行。请先到关联 Agent 的终端核实结果,再选择后续操作。",attentionBootstrapDeliveredGuidance:"请在任务页的关联 Agent 终端核实执行结果。再次发送这条指令可能导致任务重复执行。",attentionVerdictGuidance:"请查看 PR 和下方评审记录,然后确认结果或提出修改要求。",attentionAdvanceGuidance:"请确认关联 Agent 和代码平台可用,然后重试当前步骤。",attentionRetryGuidance:"本次任务已经无法继续;准备好后,可以从头重新执行。",attentionCancelGuidance:"请先检查任务详情;如果不再需要继续,可以取消任务。",noAgentSlot:e=>e==="dev"?"暂无开发 Agent":"暂无评审 Agent"},untrackedFiles:{heading:"工作目录文件",unavailable:"当前暂时无法处理文件。",conflicts:"切换分支会覆盖下列文件,保留它们无法继续这一步。请在终端移动或重命名;若在未跟踪清单中,也可以选择丢弃。",manualCleanup:"部分冲突文件被 Git 忽略,或此前已选择保留。请在终端处理后刷新清单。",keepLimit:"保留后将超过单个任务的上限(1000 个路径或 64 KiB 清单)。请在终端减少文件,或丢弃清单中的文件。",title:e=>`发现 ${e} 个未跟踪文件,请选择如何处理`,guidance:"这些文件尚未提交到 Git。你可以保留它们继续工作,或丢弃清单中的文件后继续。保留不会自动提交,本任务内同一批文件不再重复询问。",keep:"保留文件并继续",discard:"丢弃文件并继续",readyToContinue:"没有待处理的未跟踪文件,可以继续任务。此前的保留选择仍然有效。",continue:"继续任务",confirmTitle:"确认丢弃这些未跟踪文件?",confirmBody:"清单中的文件将被永久删除,无法通过 Git 撤销。",refresh:"刷新文件清单",loading:"正在检查未跟踪文件…",working:"正在处理文件并继续任务…",trackedChanges:"已跟踪文件也有改动,请先保存这些改动再继续。",directory:"清单包含嵌套目录。请保留它或在终端处理,这里不能直接丢弃。",host:"所在机器",workdir:"工作目录",agent:"Agent"},taskPanel:{ariaLabel:"任务面板",inProgressTitle:"处理中",pendingTitle:"待开始",doneTitle:"已结束",round:e=>`第 ${e} 轮`,emptyInProgress:"暂无正在处理的任务",emptyPending:"暂无待处理的任务",collapse:"收起",view:"查看",loadMore:"加载更多",emptyDone:"暂无已处理的任务"},review:{loadExternalImage:"加载外部图片",loadFailed:e=>`加载评审记录失败:${e}`,loadingRecords:"加载评审记录…",notStarted:"评审尚未开始",sectionTitle:"评审记录",phaseLabel:{spec:"方案评审",code:"代码评审"},reviewTurnLabel:"评审",responseTurnLabel:"反馈",roleUser:"用户",roleQa:"评审 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:"终端会话不存在或已结束。",sessionRecovery:"请回到项目页面检查 agent 并重试启动;若已绑定任务,请按任务页的恢复提示处理。会话就绪后,在这里重新连接。",reconnect:"重新连接",backToProject:"返回项目",keyPadAriaLabel:"终端按键",arrowAriaLabel:e=>`方向键 ${e}`,arrowLabel:{up:"上",down:"下",left:"左",right:"右"},escKeyAriaLabel:"Esc 键"},imageUpload:{tooLargeBody:e=>`单张图片不能超过 ${e} MiB`,insertedTitle:"图片已插入",insertedBody:"路径已粘贴到终端输入,补充说明后回车",uploadFailedTitle:"图片上传失败",uploadAriaLabel:"上传图片"}},an="baxian.language",tt="en-US",Xn={"en-US":Jn,"zh-CN":cr};function Zn(e){return e==="zh-CN"||e==="en-US"}function es(){try{const e=localStorage.getItem(an);return Zn(e)?e:tt}catch{return tt}}function ts(e){try{localStorage.setItem(an,e)}catch{}}let Ge=es();const Vt=new Set;let jt=0,dr=0,vn=0;function on(e){e!==Ge&&(Ge=e,Vt.forEach(n=>n(e)))}function Qt(e){jt+=1;const n=e??tt;ts(n),on(n)}function ur(e){const n=e??tt;ts(n),on(n)}function ns(){return Xn[Ge]}const ss=o.createContext({locale:tt,messages:Jn,saving:!1,setLocale:async()=>{throw new Error("setLocale requires I18nProvider")}});function mr({children:e}){const[n,s]=o.useState(Ge),[r,a]=o.useState(!1);o.useEffect(()=>{const l=c=>s(c);return Vt.add(l),s(Ge),()=>{Vt.delete(l)}},[]),o.useEffect(()=>{document.documentElement.lang=n==="zh-CN"?"zh-CN":"en"},[n]),o.useEffect(()=>{const l=c=>{if(c.key!==null&&c.key!==an)return;const m=c.key===null?es():c.newValue;Zn(m)&&(jt+=1,on(m))};return window.addEventListener("storage",l),()=>window.removeEventListener("storage",l)},[]);const i=async l=>{if(l!==Ge){a(!0);try{await M.config.patch({language:l}),Qt(l)}finally{a(!1)}}};return t.jsx(ss.Provider,{value:{locale:n,messages:Xn[n],saving:r,setLocale:i},children:e})}function rs(){return o.useContext(ss)}function H(){return rs().messages}function hr(){o.useEffect(()=>{const e=()=>{const s=jt,r=++dr;M.config.get().then(a=>{s===jt&&(r<=vn||(vn=r,ur(a.language)))}).catch(()=>{})},n=()=>{document.visibilityState==="visible"&&e()};return window.addEventListener("focus",e),document.addEventListener("visibilitychange",n),()=>{window.removeEventListener("focus",e),document.removeEventListener("visibilitychange",n)}},[])}const as=o.createContext(null),fr={success:"border-hairline bg-surface text-og-800",warn:"border-accent/25 bg-accent-soft text-accent",error:"border-accent/25 bg-accent-soft text-accent"},pr={success:ir,warn:or,error:lr};let gr=1;function xr({children:e}){const n=H(),[s,r]=o.useState([]),a=o.useRef(new Map),i=o.useRef(new Map);o.useEffect(()=>{const u=a.current,d=i.current;return()=>{for(const x of u.values())clearTimeout(x);u.clear(),d.clear()}},[]);const l=o.useCallback(u=>{const d=a.current.get(u);d&&clearTimeout(d),a.current.delete(u)},[]),c=o.useCallback(u=>{l(u),i.current.delete(u),r(d=>d.filter(x=>x.id!==u))},[l]),m=o.useCallback((u,d)=>{l(u),a.current.set(u,setTimeout(()=>c(u),d))},[l,c]),h=o.useCallback((u,d)=>{const x=i.current.get(u)??new Set;x.add(d),i.current.set(u,x),l(u)},[l]),f=o.useCallback((u,d,x)=>{const b=i.current.get(u);b==null||b.delete(d),(!b||b.size===0)&&m(u,x)},[m]),p=o.useCallback(u=>{const d=gr++,x=u.durationMs??3e3;r(b=>[...b,{...u,id:d,durationMs:x}]),m(d,x)},[m]);return t.jsxs(as.Provider,{value:{show:p},children:[e,t.jsx("div",{className:"pointer-events-none fixed inset-x-4 top-4 z-[60] flex flex-col items-end gap-2",children:s.map(u=>t.jsx("div",{className:`pointer-events-auto w-full max-w-xs rounded-lg border px-4 py-3 shadow-toast ${fr[u.kind]}`,role:"status",onMouseEnter:()=>h(u.id,"hover"),onMouseLeave:()=>f(u.id,"hover",u.durationMs),onFocus:()=>h(u.id,"focus"),onBlur:d=>{d.currentTarget.contains(d.relatedTarget)||f(u.id,"focus",u.durationMs)},children:t.jsxs("div",{className:"flex items-start gap-2",children:[(()=>{const d=pr[u.kind];return t.jsx(d,{className:"mt-0.5 shrink-0",width:14,height:14})})(),t.jsxs("div",{className:"flex-1",children:[t.jsx("div",{className:"text-sm font-semibold",children:u.title}),u.body&&t.jsx("div",{className:"mt-1 whitespace-pre-line text-xs text-og-700",children:u.body}),u.details&&t.jsxs("details",{className:"mt-1 text-xs text-og-500",children:[t.jsx("summary",{className:"cursor-pointer select-none text-accent",children:n.common.technicalDetails}),t.jsx("div",{className:"mt-1 whitespace-pre-wrap break-words font-mono",children:u.details})]})]}),t.jsx("button",{type:"button",onClick:()=>c(u.id),className:"text-current opacity-50 transition-opacity hover:opacity-100","aria-label":n.toast.dismissAriaLabel,children:"✕"})]})},u.id))})]})}function je(){const e=o.useContext(as);if(!e)throw new Error("useToast must be inside <ToastProvider>");return e}const br={sm:"max-w-md",md:"max-w-lg",lg:"max-w-2xl"},yn='input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), [href], [tabindex]:not([tabindex="-1"])',He=[];function Re({open:e,onClose:n,title:s,titleContent:r,children:a,footer:i,size:l="md",dismissOnBackdrop:c=!0}){const m=H(),h=o.useRef(null),f=o.useRef();f.current||(f.current=Symbol("modal"));const p=o.useRef(null),u=o.useRef(!1),d=o.useRef(n);return o.useEffect(()=>{d.current=n},[n]),o.useEffect(()=>{if(!e)return;const x=f.current;He.push(x);const b=()=>He[He.length-1]===x;p.current=document.activeElement;const y=A=>{if(!b())return;if(A.key==="Escape"){d.current();return}if(A.key!=="Tab")return;const w=h.current;if(!w)return;const k=Array.from(w.querySelectorAll(yn)).filter(P=>P.offsetParent!==null||P===document.activeElement);if(k.length===0){A.preventDefault();return}const j=k[0],v=k[k.length-1],D=document.activeElement;A.shiftKey&&(D===j||!w.contains(D))?(A.preventDefault(),v.focus()):!A.shiftKey&&(D===v||!w.contains(D))&&(A.preventDefault(),j.focus())};document.addEventListener("keydown",y);const T=document.body.style.overflow;document.body.style.overflow="hidden";const C=h.current;if(C){const A=C.querySelector(yn);A==null||A.focus()}return()=>{var w,k;const A=He.indexOf(x);A>=0&&He.splice(A,1),document.removeEventListener("keydown",y),document.body.style.overflow=T,(k=(w=p.current)==null?void 0:w.focus)==null||k.call(w)}},[e]),e?t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-og-1000/45 px-3 sm:px-4",onMouseDown:c?x=>{u.current=x.target===x.currentTarget&&He[He.length-1]===f.current}:void 0,onClick:c?x=>{x.target===x.currentTarget&&u.current&&d.current()}:void 0,role:"presentation",children:t.jsxs("div",{ref:h,className:`flex w-full ${br[l]} max-h-[90dvh] flex-col overflow-hidden rounded-lg border border-og-100 bg-surface shadow-modal`,onClick:x=>x.stopPropagation(),role:"dialog","aria-modal":"true","aria-label":s,children:[t.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-3 border-b border-hairline px-5 py-3",children:[t.jsx("h2",{title:s,className:"min-w-0 truncate font-display text-sm font-semibold tracking-tight text-og-1000",children:r??s}),t.jsx("button",{type:"button",onClick:()=>d.current(),className:"-mr-1 flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-og-400 transition-colors hover:bg-og-50 hover:text-og-800","aria-label":m.common.close,children:"✕"})]}),t.jsx("div",{className:"min-h-0 flex-1 overflow-auto px-5 py-4",children:a}),i&&t.jsx("div",{className:"flex shrink-0 flex-wrap items-center justify-end gap-2 border-t border-hairline px-5 py-3",children:i})]})}):null}const is=o.createContext(null);function vr({children:e}){const n=H(),[s,r]=o.useState(null),a=o.useRef(null),i=o.useCallback(c=>new Promise(m=>{var f;(f=a.current)==null||f.resolve(!1);const h={...c,resolve:m};a.current=h,r(h)}),[]),l=o.useCallback(c=>{const m=a.current;m&&(a.current=null,r(null),m.resolve(c))},[]);return t.jsxs(is.Provider,{value:i,children:[e,s&&t.jsx(Re,{open:!0,title:s.title,onClose:()=>l(!1),size:"sm",footer:t.jsxs("div",{className:"flex justify-end gap-2",children:[t.jsx("button",{type:"button",onClick:()=>l(!1),className:"btn-secondary",children:s.cancelLabel??n.common.cancel}),t.jsx("button",{type:"button",onClick:()=>l(!0),className:"btn-primary",children:s.confirmLabel??n.common.confirm})]}),children:s.body?t.jsx("p",{className:"whitespace-pre-line text-sm text-og-700",children:s.body}):null})]})}function ln(){const e=o.useContext(is);if(!e)throw new Error("useConfirm must be inside <ConfirmProvider>");return e}const Tt="baxian.pendingRestart",yr=500,wr=3e4,os=o.createContext(null);function kr(){try{const e=localStorage.getItem(Tt);if(!e)return{count:0,baselineStartedAt:null};const n=JSON.parse(e);return{count:typeof n.count=="number"?n.count:0,baselineStartedAt:typeof n.baselineStartedAt=="string"?n.baselineStartedAt:null}}catch{return{count:0,baselineStartedAt:null}}}function jr(e){try{e.count<=0?localStorage.removeItem(Tt):localStorage.setItem(Tt,JSON.stringify(e))}catch{}}function Tr({children:e}){const n=H(),s=kr(),[r,a]=o.useState(s.count),[i,l]=o.useState(s.baselineStartedAt),[c,m]=o.useState(s.count>0?"pending":"idle"),[h,f]=o.useState(),p=o.useRef(s.count),u=o.useRef(s.count>0?"pending":"idle"),d=o.useRef(0),x=o.useCallback(w=>{p.current=w,a(w)},[]),b=o.useCallback(w=>{a(k=>{const j=w(k);return p.current=j,j})},[]),y=o.useCallback(w=>{u.current=w,m(w)},[]);o.useEffect(()=>{jr({count:r,baselineStartedAt:i})},[r,i]),o.useEffect(()=>{let w=!1;(async()=>{try{const j=await M.health.get();if(w)return;l(v=>v!==null&&j.startedAt!==v?(x(0),y("idle"),null):v)}catch{}})();const k=j=>{if(j.key===Tt){if(j.newValue===null){if(u.current==="restarting"&&d.current>0){x(d.current),l(null);return}x(0),l(null),u.current!=="restarting"&&y("idle");return}try{const v=JSON.parse(j.newValue);typeof v.count=="number"&&(u.current==="restarting"&&v.count>p.current&&(d.current+=v.count-p.current),x(v.count),u.current!=="restarting"&&y(v.count>0?"pending":"idle")),typeof v.baselineStartedAt=="string"?l(v.baselineStartedAt):v.baselineStartedAt===null&&l(null)}catch{}}};return window.addEventListener("storage",k),()=>{w=!0,window.removeEventListener("storage",k)}},[x,y]);const T=o.useRef(!1),C=o.useCallback(()=>{b(w=>w+1),u.current==="restarting"?d.current+=1:y("pending"),l(w=>(w!==null||T.current||(T.current=!0,(async()=>{try{const k=await M.health.get();l(j=>j??k.startedAt)}catch{}finally{T.current=!1}})()),w))},[y,b]),A=o.useCallback(async()=>{d.current=0,f(void 0),y("restarting");let w;try{w=(await M.health.get()).startedAt}catch(j){y("failed"),f(n.banner.preRestartFetchFailed(j instanceof Error?j.message:String(j)));return}try{await M.server.restart()}catch(j){if(!(j instanceof ze&&j.status===409)){y("failed"),f(n.banner.restartTriggerFailed(j instanceof Error?j.message:String(j)));return}}const k=Date.now();for(;Date.now()-k<wr;){await new Promise(j=>setTimeout(j,yr));try{const j=await M.health.get();if(j.startedAt!==w){const v=d.current;d.current=0,l(v>0?j.startedAt:null),x(v),y(v>0?"pending":"idle");return}}catch{}}y("failed"),f(n.banner.restartTimeout)},[x,y,n]);return t.jsx(os.Provider,{value:{phase:c,count:r,error:h,flagDirty:C,triggerRestart:A},children:e})}function Lt(){const e=o.useContext(os);if(!e)throw new Error("usePendingRestart must be used inside PendingRestartProvider");return e}function wn(e){return e instanceof Error?e.message:String(e)}function ls(e,n,s){const r=H(),{show:a}=je(),i=ln(),{flagDirty:l}=Lt(),[c,m]=o.useState(!1),[h,f]=o.useState(!1),[p,u]=o.useState(!1),[d,x]=o.useState(null),b=n[0]??"",y=n.join(" / "),T=n.length>1,C=async j=>(await Promise.allSettled(n.map(D=>j(D)))).flatMap((D,P)=>D.status==="rejected"?[`${n[P]}: ${wn(D.reason)}`]:[]);return{compact:async()=>{m(!0);try{const j=await C(v=>M.agents.compact(v));if(j.length>0){a({kind:"error",title:r.agents.compactFailedTitle,body:j.join(`
|
|
8
8
|
`)});return}a({kind:"success",title:T?r.agents.teamCompactSentTitle(y):r.agents.compactSentTitle(b)})}finally{m(!1)}},clear:async()=>{if(await i({title:T?r.agents.teamClearConfirmTitle(y):r.agents.clearConfirmTitle(b),body:T?r.agents.teamClearConfirmBody:r.agents.clearConfirmBody,confirmLabel:r.agents.clearConfirmLabel})){f(!0);try{const v=await C(D=>M.agents.clear(D));if(v.length>0){a({kind:"error",title:r.agents.clearFailedTitle,body:v.join(`
|
|
9
9
|
`)});return}a({kind:"success",title:T?r.agents.teamClearSentTitle(y):r.agents.clearSentTitle(b)})}finally{f(!1)}}},remove:async()=>{if(await i({title:T?r.agents.teamDeleteConfirmTitle(y):r.agents.deleteConfirmTitle(b),body:r.agents.deleteConfirmBody,confirmLabel:r.common.delete})){u(!0),x(null);try{const v=await M.projects.deleteAgent(e,b);v!=null&&v.restartRequired&&l();const D=(v==null?void 0:v.removed)??[b],P=[...(v==null?void 0:v.warnings)??[]],I=T?[]:D.filter(J=>J!==b);I.length>0&&P.unshift(r.agents.deletedWithTeamBody(I.join(", ")));const O=T?r.agents.teamDeletedTitle(y):I.length>0?r.agents.deletedWithTeamTitle(b):r.agents.deletedTitle(b);a(P.length>0?{kind:"warn",title:O,body:P.join(`
|
|
10
|
-
`)}:{kind:"success",title:O}),s==null||s()}catch(v){x(wn(v))}finally{u(!1)}}},compacting:c,clearing:h,deleting:p,deleteError:d,busy:c||h||p}}const Nr=[500,1e3,2e3,4e3,8e3,15e3,3e4];class cs{constructor(n){ce(this,"attempts",0);ce(this,"timer",null);ce(this,"delaysMs");this.opts=n,this.delaysMs=n.delaysMs??Nr}schedule(){if(this.timer||!this.shouldReconnect())return;const n=this.delaysMs[Math.min(this.attempts,this.delaysMs.length-1)];this.attempts+=1,this.timer=setTimeout(()=>{this.timer=null,this.shouldReconnect()&&this.opts.reconnect()},n)}cancel(){this.timer&&(clearTimeout(this.timer),this.timer=null)}reset(){this.attempts=0}shouldReconnect(){return this.opts.shouldReconnect?this.opts.shouldReconnect():!0}}function ds(e,n,s){return(e==null?void 0:e.code)!==4401||n!==s?!1:(window.dispatchEvent(new CustomEvent(et)),!0)}function us(e){return Array.from(new TextEncoder().encode(e)).map(n=>n.toString(16).padStart(2,"0")).join("")}function ms(e){return`${location.protocol==="https:"?"wss":"ws"}://${location.host}${e}`}const hs=(e,n)=>n&&n.length>0?new WebSocket(e,n):new WebSocket(e);let kn=0;function Sr(){kn++;const e=Math.random().toString(36).slice(2,8);return`sub-${Date.now().toString(36)}-${kn}-${e}`}function Rr(){return ms("/api/stream")}class Cr{constructor(n={}){ce(this,"wsUrl");ce(this,"wsFactory");ce(this,"tokenProvider");ce(this,"ws",null);ce(this,"subs",new Map);ce(this,"snapshotPending",new Set);ce(this,"preSubscribeQueue",new Map);ce(this,"outbox",[]);ce(this,"reconnectScheduler");ce(this,"explicitlyClosed",!1);this.wsUrl=n.wsUrl??Rr(),this.wsFactory=n.wsFactory??hs,this.tokenProvider=n.tokenProvider??sn,this.reconnectScheduler=new cs({reconnect:()=>this.openSocket(),shouldReconnect:()=>!this.explicitlyClosed&&this.subs.size>0})}subscribe(n){const s=Sr(),r={subscriberId:s,agentId:n.agentId,mode:n.mode,onSnapshot:n.onSnapshot,onData:n.onData,onError:n.onError,onSessionGone:n.onSessionGone};return this.subs.set(s,r),this.snapshotPending.add(s),this.preSubscribeQueue.set(s,[]),this.ensureSocket(),this.wsSendOrQueue({op:"subscribe",subscriberId:s,agentId:n.agentId,mode:n.mode}),{subscriberId:s,unsubscribe:()=>this.unsubscribe(s)}}send(n,s){if(this.subs.has(n)){if(this.snapshotPending.has(n)){this.outbox.push({op:"input",subscriberId:n,data:s});return}this.wsSendOrQueue({op:"input",subscriberId:n,data:s})}}resize(n,s,r){const a=this.subs.get(n);a&&(a.lastSize={cols:s,rows:r},!this.snapshotPending.has(n)&&this.wsSendOrQueue({op:"resize",subscriberId:n,cols:s,rows:r}))}ping(){this.wsSendOrQueue({op:"ping"})}close(){if(this.explicitlyClosed=!0,this.reconnectScheduler.cancel(),this.reconnectScheduler.reset(),this.ws){try{this.ws.close()}catch{}this.ws=null}this.subs.clear(),this.snapshotPending.clear(),this.preSubscribeQueue.clear(),this.outbox=[]}unsubscribe(n){this.subs.has(n)&&(this.subs.delete(n),this.snapshotPending.delete(n),this.preSubscribeQueue.delete(n),this.wsSendOrQueue({op:"unsubscribe",subscriberId:n}),this.subs.size===0&&this.teardownSocket())}teardownSocket(){if(this.reconnectScheduler.cancel(),this.reconnectScheduler.reset(),this.outbox=[],this.ws){try{this.ws.close()}catch{}this.ws=null}}ensureSocket(){this.explicitlyClosed||this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING)||this.openSocket()}openSocket(){if(this.explicitlyClosed)return;this.reconnectScheduler.cancel();const n=this.tokenProvider(),s=n?[`baxian.token.${us(n)}`]:void 0;let r;try{r=this.wsFactory(this.wsUrl,s)}catch(a){console.warn("[pane-stream] WebSocket constructor threw:",a),this.scheduleReconnect();return}this.ws=r,r.onopen=()=>{if(r!==this.ws)return;this.reconnectScheduler.reset();for(const i of this.subs.values()){this.snapshotPending.add(i.subscriberId),this.preSubscribeQueue.set(i.subscriberId,[]),i.snapshotSeq=void 0;try{r.send(JSON.stringify({op:"subscribe",subscriberId:i.subscriberId,agentId:i.agentId,mode:i.mode}))}catch(l){console.warn("[pane-stream] resubscribe send failed:",l)}}const a=this.outbox;this.outbox=[];for(const i of a)if(i.op!=="subscribe"){if("subscriberId"in i&&i.subscriberId){if(!this.subs.has(i.subscriberId))continue;if(this.snapshotPending.has(i.subscriberId)&&i.op!=="unsubscribe"){this.outbox.push(i);continue}}try{r.send(JSON.stringify(i))}catch(l){console.warn("[pane-stream] outbox flush failed:",l)}}},r.onmessage=a=>{if(r!==this.ws)return;let i;try{const l=typeof a.data=="string"?a.data:String(a.data);i=JSON.parse(l)}catch{return}this.handleMessage(i)},r.onclose=a=>{r===this.ws&&(this.ws=null,!this.explicitlyClosed&&(ds(a,n,this.tokenProvider())||this.subs.size!==0&&this.scheduleReconnect()))},r.onerror=()=>{}}scheduleReconnect(){this.reconnectScheduler.schedule()}wsSendOrQueue(n){if(this.ws&&this.ws.readyState===WebSocket.OPEN)try{this.ws.send(JSON.stringify(n));return}catch(s){console.warn("[pane-stream] send failed, will queue:",s)}this.outbox.push(n)}handleMessage(n){var s,r;switch(n.type){case"snapshot":this.handleSnapshot(n);break;case"subscribed":this.handleSubscribed(n);break;case"data":this.dispatch(n);break;case"session_gone":for(const a of[...this.subs.values()])a.agentId===n.agentId&&((s=a.onSessionGone)==null||s.call(a));break;case"error":{if(n.subscriberId){const a=this.subs.get(n.subscriberId);(r=a==null?void 0:a.onError)==null||r.call(a,{code:n.code,message:n.message})}else console.warn("[pane-stream] connection-level error:",n.code,n.message);break}}}handleSnapshot(n){const s=this.subs.get(n.subscriberId);s&&s.onSnapshot({cols:n.cols,rows:n.rows,data:n.data})}handleSubscribed(n){const s=this.subs.get(n.subscriberId);if(!s)return;s.snapshotSeq=n.snapshotSeq,s.lastSize||(s.lastSize={cols:n.cols,rows:n.rows}),this.snapshotPending.delete(n.subscriberId);const r=this.preSubscribeQueue.get(n.subscriberId);if(this.preSubscribeQueue.delete(n.subscriberId),r)for(const a of r)a.seq>n.snapshotSeq&&s.onData(a.data);s.mode==="full"&&s.lastSize&&this.wsSendOrQueue({op:"resize",subscriberId:s.subscriberId,cols:s.lastSize.cols,rows:s.lastSize.rows}),this.flushOutboxForSub(n.subscriberId)}flushOutboxForSub(n){if(this.outbox.length===0||!this.ws||this.ws.readyState!==WebSocket.OPEN)return;const s=[];for(const r of this.outbox)if("subscriberId"in r&&r.subscriberId===n&&r.op!=="subscribe")try{this.ws.send(JSON.stringify(r))}catch(a){console.warn("[pane-stream] flushOutboxForSub send failed:",a)}else s.push(r);this.outbox=s}dispatch(n){for(const s of this.subs.values())if(s.agentId===n.agentId)if(this.snapshotPending.has(s.subscriberId)){const r=this.preSubscribeQueue.get(s.subscriberId);r&&r.push({seq:n.seq,data:n.data})}else s.onData(n.data)}}let Mt=null;function Ot(){return Mt||(Mt=new Cr),Mt}function Ar(e){const{agentId:n,mode:s}=e,r=o.useRef(null),[a,i]=o.useState(0),l=o.useRef({onSnapshot:e.onSnapshot,onData:e.onData,onError:e.onError,onSessionGone:e.onSessionGone});l.current={onSnapshot:e.onSnapshot,onData:e.onData,onError:e.onError,onSessionGone:e.onSessionGone},o.useEffect(()=>{const p=Ot().subscribe({agentId:n,mode:s,onSnapshot:u=>l.current.onSnapshot(u),onData:u=>l.current.onData(u),onError:u=>{var d,x;return(x=(d=l.current).onError)==null?void 0:x.call(d,u)},onSessionGone:()=>{var u,d;return(d=(u=l.current).onSessionGone)==null?void 0:d.call(u)}});return r.current=p.subscriberId,()=>{r.current=null,p.unsubscribe()}},[n,s,a]);const c=o.useCallback(f=>{const p=r.current;p&&Ot().send(p,f)},[]),m=o.useCallback((f,p)=>{const u=r.current;u&&Ot().resize(u,f,p)},[]),h=o.useCallback(()=>i(f=>f+1),[]);return{send:c,resize:m,reconnect:h}}const Dr=8;let gt=0,xt,jn=!0;function fs(e){var n;return Array.from(((n=e.element)==null?void 0:n.querySelectorAll("canvas"))??[])}function Tn(e){for(const n of fs(e)){const s=n.getContext("webgl2");if(s)return s}return null}function Yt(e){var n;(n=e==null?void 0:e.getExtension("WEBGL_lose_context"))==null||n.loseContext()}function Pr(){const e=document.createElement("canvas").getContext("webgl2");return e?(Yt(e),!0):!1}function Lr(e,n){let s=null,r=!1;const a=()=>{if(r||!jn)return;const h=new Vs.CanvasAddon;try{e.loadAddon(h),s={kind:"canvas",addon:h}}catch(f){jn=!1,console.warn("[terminal-renderer] canvas renderer unavailable, using dom renderer:",f),h.dispose()}},i=()=>{if(!s)return;const{kind:h,addon:f}=s;s=null;const p=h==="webgl"?Tn(e):null;f.dispose(),h==="webgl"&&(gt--,Yt(p))},l=()=>{if(xt===void 0&&(xt=Pr()),!xt||gt>=Dr)return!1;let h=null;try{return h=new Ks.WebglAddon,h.onContextLoss(()=>{i(),a()}),e.loadAddon(h),gt++,s={kind:"webgl",addon:h},!0}catch(f){xt=!1,console.warn("[terminal-renderer] webgl renderer unavailable, using canvas from now on:",f),h==null||h.dispose();for(const p of fs(e))p.remove();return!1}},c=()=>{r||s||l()||a()},m=typeof IntersectionObserver=="function"?new IntersectionObserver(h=>{if(r)return;const f=h[h.length-1];f!=null&&f.isIntersecting?c():i()}):null;return m?m.observe(n):c(),{get kind(){return(s==null?void 0:s.kind)??"dom"},dispose(){if(r)return;r=!0,m==null||m.disconnect();const h=s;s=null;const f=(h==null?void 0:h.kind)==="webgl"?Tn(e):null;try{e.dispose()}catch(p){console.warn("[terminal-renderer] dispose failed:",p)}(h==null?void 0:h.kind)==="webgl"&&(gt--,Yt(f))}}}const Er=[{key:"up",path:"M12 5l-6 6m6-6l6 6m-6-6v14"},{key:"down",path:"M12 19l6-6m-6 6l-6-6m6 6V5"},{key:"left",path:"M5 12l6-6m-6 6l6 6m-6-6h14"},{key:"right",path:"M19 12l-6-6m6 6l-6 6m6-6H5"}],bt=Object.fromEntries(Er.map(e=>[e.key,e]));function vt({arrow:e,ariaLabel:n,onPress:s}){return t.jsx("button",{type:"button","aria-label":n,"data-arrow":e.key,onMouseDown:r=>r.preventDefault(),onClick:()=>s(e.key),className:"flex h-8 w-8 items-center justify-center rounded border border-hairline bg-surface text-og-700 transition-colors hover:bg-og-50 hover:text-og-1000 active:bg-og-200",children:t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:t.jsx("path",{d:e.path})})})}function $r({onKey:e,onEscape:n,className:s}){const r=H();return t.jsxs("div",{role:"group","aria-label":r.terminal.keyPadAriaLabel,className:s??"flex flex-none items-center justify-center gap-1 border-t border-hairline bg-page px-3 py-2",children:[n&&t.jsx("button",{type:"button","aria-label":r.terminal.escKeyAriaLabel,"data-key":"escape",onMouseDown:a=>a.preventDefault(),onClick:n,className:"mr-2 flex h-8 items-center justify-center rounded border border-hairline bg-surface px-2.5 font-mono text-xs text-og-700 transition-colors hover:bg-og-50 hover:text-og-1000 active:bg-og-200",children:"ESC"}),t.jsx(vt,{arrow:bt.left,ariaLabel:r.terminal.arrowAriaLabel(r.terminal.arrowLabel.left),onPress:e}),t.jsx(vt,{arrow:bt.up,ariaLabel:r.terminal.arrowAriaLabel(r.terminal.arrowLabel.up),onPress:e}),t.jsx(vt,{arrow:bt.down,ariaLabel:r.terminal.arrowAriaLabel(r.terminal.arrowLabel.down),onPress:e}),t.jsx(vt,{arrow:bt.right,ariaLabel:r.terminal.arrowAriaLabel(r.terminal.arrowLabel.right),onPress:e})]})}const Ir=Math.floor(Pt/1024/1024);function Br({agentId:e,className:n}){const s=H(),r=o.useRef(null),[a,i]=o.useState(!1),{show:l}=je(),c=async m=>{var f;const h=(f=m.target.files)==null?void 0:f[0];if(m.target.value="",!!h){if(h.size>Pt){l({kind:"error",title:s.createTask.imageTooLargeToastTitle,body:s.imageUpload.tooLargeBody(Ir)});return}i(!0);try{await M.agents.uploadImage(e,h),l({kind:"success",title:s.imageUpload.insertedTitle,body:s.imageUpload.insertedBody})}catch(p){const u=p instanceof ze||p instanceof Error?p.message:String(p);l({kind:"error",title:s.imageUpload.uploadFailedTitle,body:u})}finally{i(!1)}}};return t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button","aria-label":s.imageUpload.uploadAriaLabel,disabled:a,onMouseDown:m=>m.preventDefault(),onClick:()=>{var m;return(m=r.current)==null?void 0:m.click()},className:n??"flex h-8 w-8 items-center justify-center rounded border border-hairline bg-surface text-og-700 transition-colors hover:bg-og-50 hover:text-og-1000 active:bg-og-200 disabled:cursor-not-allowed disabled:opacity-50",children:t.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[t.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),t.jsx("circle",{cx:"9",cy:"9",r:"2"}),t.jsx("path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"})]})}),t.jsx("input",{ref:r,type:"file",accept:"image/*",className:"hidden",onChange:c})]})}const Fr={up:"A",down:"B",right:"C",left:"D"};function Mr(e,n){return(n?"\x1BO":"\x1B[")+Fr[e]}const Nn=18,Or=250,_r=256*1024,Sn="#fdfdfd",Hr='ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',qr={background:Sn,foreground:"#474c55",cursor:"#1348dc",cursorAccent:Sn,selectionBackground:"#eaf0ff",black:"#0d0d0f",red:"#b91c1c",green:"#15803d",yellow:"#b45309",blue:"#1348dc",magenta:"#9333ea",cyan:"#0e7490",white:"#474c55",brightBlack:"#878e9b",brightRed:"#dc2626",brightGreen:"#16a34a",brightYellow:"#d97706",brightBlue:"#3080ff",brightMagenta:"#a855f7",brightCyan:"#0891b2",brightWhite:"#0d0d0f"},Ur=/\x1b\[(?:\?[\d;]*c|>[\d;]*c|\??\d+;\d+R|\d+n)/g;function Gr(e){return e.replace(Ur,"")}const Wr=1024*1024;function zr(e){const n=e.indexOf(";");if(n===-1)return null;const s=e.slice(n+1);if(s.length===0||s==="?"||s.length>Wr)return null;try{const r=atob(s),a=new Uint8Array(r.length);for(let i=0;i<r.length;i++)a[i]=r.charCodeAt(i);return new TextDecoder().decode(a)}catch{return null}}function Xe({agentId:e,mode:n,interactive:s=!1,maxLines:r,className:a,autoFocus:i=!0,deferFullUntilFocus:l=!1,arrowKeys:c=!1}){const m=H(),h=o.useRef(null),f=o.useRef(null),p=o.useRef(null),u=o.useRef(null),d=o.useRef(!1),x=o.useRef(""),b=o.useRef([]),y=o.useRef(0),T=o.useRef(null),C=o.useRef(null),A=o.useRef(null),w=o.useRef(Promise.resolve()),k=o.useRef(0),[j,v]=o.useState(null),[D,P]=o.useState(!1),I=`${e}\0${n}\0${l?"1":"0"}`,[O,J]=o.useState({key:I,active:!1}),E=O.key===I&&O.active,W=n==="full"&&l,re=W&&!E?"preview":n,te=s&&re==="full",X=(S,U)=>U.length===0?Promise.resolve():new Promise(_=>{try{S.write(U,()=>_())}catch(se){console.warn("[pane-terminal] write failed:",se),_()}}),V=re==="preview",ae=()=>{var R;if(!V)return;const S=h.current,U=f.current;if(!S||!U||S.clientHeight<=0)return;const _=((R=S.querySelector(".xterm-screen"))==null?void 0:R.getBoundingClientRect().height)??0,se=_>0&&U.rows>0?_/U.rows:Nn,B=(U.buffer.active.cursorY+1)*se;S.scrollTop=Math.max(0,B-S.clientHeight)},z=()=>{if(!V||A.current!==null)return;let S=!1;const U=requestAnimationFrame(()=>{S=!0,A.current=null,ae()});S||(A.current=U)},le=(S,U)=>{w.current=w.current.then(async()=>{const _=f.current;if(!(!_||U!==k.current))try{await S(_),te&&_.scrollToBottom(),z()}catch(se){console.warn("[pane-terminal] terminal task failed:",se)}}).catch(_=>{console.warn("[pane-terminal] write chain failed:",_)})},ne=(S,U)=>{le(_=>X(_,S),U)},ge=()=>{T.current!==null&&(cancelAnimationFrame(T.current),T.current=null),C.current!==null&&(clearTimeout(C.current),C.current=null)},q=()=>{ge(),b.current=[],y.current=0},ie=()=>{ge();const S=b.current;S.length!==0&&(b.current=[],y.current=0,ne(S.join(""),k.current))},me=S=>{if(S.length!==0){if(b.current.push(S),y.current+=S.length,y.current>=_r){ie();return}T.current===null&&(T.current=requestAnimationFrame(ie)),C.current===null&&(C.current=setTimeout(ie,Or))}},{send:xe,resize:ye,reconnect:N}=Ar({agentId:e,mode:re,onSnapshot:({cols:S,rows:U,data:_})=>{if(v(null),P(!1),!!f.current)try{const B=k.current+1;k.current=B,q(),le(async R=>{var $;R.reset(),te?(($=u.current)==null||$.call(u),await X(R,_)):(S>0&&U>0&&R.resize(S,U),await X(R,_))},B)}catch(B){console.warn("[pane-terminal] snapshot write failed:",B)}},onData:S=>{me(S)},onError:S=>{P(S.code==="session_not_found"),v(S.code==="session_not_found"?null:`${S.code}: ${S.message}`)},onSessionGone:()=>P(!0)});o.useEffect(()=>{v(null),P(!1)},[e,re]),o.useEffect(()=>{x.current=""},[I]),o.useEffect(()=>{if(re!=="full")return;const S=x.current;S.length!==0&&(x.current="",xe(S))},[xe,re]);const we=o.useCallback(()=>{!s||!W||E||(d.current=!0,J({key:I,active:!0}))},[I,E,s,W]),pe=o.useCallback(S=>{const U=Gr(S);if(U.length!==0){if(W&&(!E||x.current.length>0)){x.current+=U,we();return}xe(U)}},[we,E,xe,W]);o.useEffect(()=>{const S=h.current;if(!S)return;let U=!1;const _=new Qs.Terminal({cursorBlink:s,disableStdin:!s,theme:qr,fontFamily:Hr,fontSize:13,lineHeight:1.4,scrollback:re==="full"?5e3:1e3}),se=new Ys.FitAddon;_.loadAddon(se),_.open(S);const B=Lr(_,S);f.current=_,p.current=se;const R=V?_.onRender(()=>z()):null;if(s&&(i||d.current)){d.current=!1;try{_.focus()}catch{}}s&&(_.onData(pe),re==="full"&&_.parser.registerOscHandler(52,$e=>{var Te;const Ce=zr($e);return Ce!==null&&((Te=navigator.clipboard)==null||Te.writeText(Ce).catch(()=>{})),!0}));const $=()=>S.clientWidth>0&&S.clientHeight>0,Z=($e=!1)=>{if(!$())return!1;const Ce=_.cols,Te=_.rows;try{se.fit()}catch{return!1}return te&&_.scrollToBottom(),_.cols>0&&_.rows>0&&($e||_.cols!==Ce||_.rows!==Te)&&ye(_.cols,_.rows),!0};u.current=te?()=>Z(!0):null;let K=null,ee=null,be=null,Ve=0;const Me=()=>{K||(K=new ResizeObserver(()=>{ee&&clearTimeout(ee),ee=setTimeout(()=>{ee=null,te?Z():V&&z()},100)}),K.observe(S))},Ee=()=>{be=requestAnimationFrame(()=>{if(be=null,!U){if(!te){V&&(Me(),z());return}if(Z(!0)){Me();return}if(Ve++<5){Ee();return}Me()}})};return Ee(),()=>{U=!0,be!==null&&cancelAnimationFrame(be),T.current!==null&&(cancelAnimationFrame(T.current),T.current=null),C.current!==null&&(clearTimeout(C.current),C.current=null),A.current!==null&&(cancelAnimationFrame(A.current),A.current=null),k.current++,b.current=[],y.current=0,w.current=Promise.resolve(),ee&&clearTimeout(ee),K==null||K.disconnect(),R==null||R.dispose(),f.current=null,p.current=null,u.current=null,B.dispose()}},[e,i,te,pe,s,re,ye]);const L=()=>{var S;if(s){we();try{(S=f.current)==null||S.focus()}catch{}}};o.useEffect(()=>{if(s)return;const S=h.current;if(!S)return;const U=_=>{_.stopPropagation()};return S.addEventListener("wheel",U,{capture:!0,passive:!0}),()=>S.removeEventListener("wheel",U,{capture:!0})},[s]);const G=r&&r>0?{maxHeight:`${r*Nn}px`}:void 0;return t.jsxs("div",{className:a??"flex flex-col h-full w-full min-h-0 bg-term",children:[(j||D)&&t.jsxs("div",{role:"alert",className:"border-b border-accent/25 bg-accent-soft px-3 py-1 text-xs text-accent",children:[t.jsx("div",{children:D?m.terminal.sessionEnded:j}),D&&t.jsx("div",{children:m.terminal.sessionRecovery}),t.jsx("button",{type:"button",className:"btn-secondary mt-1",onKeyDown:S=>S.stopPropagation(),onClick:S=>{S.stopPropagation(),N()},children:m.terminal.reconnect})]}),t.jsx("div",{className:"flex flex-1 min-h-0 px-2 py-1.5",style:G,children:t.jsx("div",{ref:h,className:"flex-1 min-h-0 overflow-hidden",onMouseDown:L})}),s&&c&&t.jsxs("div",{className:"grid grid-cols-[1fr_auto_1fr] gap-2 flex-none items-center border-t border-hairline bg-page px-3 py-2",children:[t.jsx("div",{className:"flex items-center",children:t.jsx(Br,{agentId:e})}),t.jsx($r,{className:"flex items-center justify-center gap-1",onKey:S=>{var _,se;const U=!!((se=(_=f.current)==null?void 0:_.modes)!=null&&se.applicationCursorKeysMode);pe(Mr(S,U))},onEscape:()=>pe("\x1B")})]})]})}function ps(e,n){const s=typeof n=="string"?{status:n}:n,{status:r,phase:a}=s;if(r==="pending"&&s.preferredAgentId==="")return e.statusContext.pendingUnassigned;if(r==="in_progress"){if(a==="spec")return e.statusContext.inProgressSpec;if(a==="code")return e.statusContext.inProgressCode}if(r==="review"){if(a==="spec")return e.statusContext.reviewSpec;if(a==="code")return e.statusContext.reviewCode}if(r==="fixing"){if(a==="spec")return e.statusContext.fixingSpec;if(a==="code")return e.statusContext.fixingCode}if(r==="max_rounds"){if(a==="spec")return e.statusContext.maxRoundsSpec;if(a==="code")return e.statusContext.maxRoundsCode}return e.status[r]??r}function Kr(e){return ps(ns(),e)}function cn(e,n){return e.reason==="bootstrap-marker-clear-failed"||e.reason==="dispatch-failed:ack_unknown"&&n!=="review"?e.recommendedActions.filter(s=>s!=="advance"):e.recommendedActions}function gs(e,n,s){const{reason:r}=n,a=cn(n,s),l={"dirty-workdir":{title:e.taskDetail.attentionDirtyWorkdirTitle,guidance:e.taskDetail.attentionDirtyWorkdirGuidance},"checkout-preparation-failed":{title:e.taskDetail.attentionCheckoutTitle,guidance:e.taskDetail.attentionCheckoutGuidance},"restart-redispatch-failed":{title:e.taskDetail.attentionReplayTitle,guidance:e.taskDetail.attentionReplayGuidance},"bootstrap-marker-clear-failed":{title:e.taskDetail.attentionBootstrapDeliveredTitle,guidance:e.taskDetail.attentionBootstrapDeliveredGuidance},"dispatch-failed:ack_unknown":{title:e.taskDetail.attentionDeliveryUnknownTitle,guidance:e.taskDetail.attentionDeliveryUnknownGuidance}}[r],c=(l==null?void 0:l.title)??(/confirm-merge|post-approve|merge/.test(r)?e.taskDetail.attentionMergeTitle:/review|verdict/.test(r)?e.taskDetail.attentionReviewTitle:/runtime|session|recovery|tmux|repl/.test(r)?e.taskDetail.attentionAgentTitle:/dispatch|delivery|pr-created/.test(r)?e.taskDetail.attentionHandoffTitle:e.taskDetail.attentionDefaultTitle),m=a.includes("verdict")?e.taskDetail.attentionVerdictGuidance:a.includes("advance")?e.taskDetail.attentionAdvanceGuidance:a.includes("retry")?e.taskDetail.attentionRetryGuidance:e.taskDetail.attentionCancelGuidance;return{title:c,guidance:l?`${l.guidance} ${m}`:m,...l?{expandDetails:!0}:{}}}const Vr={pending:"pill",in_progress:"pill pill-live",review:"pill pill-review",fixing:"pill pill-warn","spec-ready":"pill pill-warn",approved:"pill pill-live","merge-ready":"pill pill-warn",merged:"pill pill-live",done:"pill pill-live",failed:"pill pill-danger",max_rounds:"pill pill-warn",cancelled:"pill"};function dn({task:e,className:n=""}){const s=H(),r=ps(s,e);return t.jsx("span",{className:`${Vr[e.status]??"pill"} ${n}`,title:r,"data-status":e.status,children:r})}function un(e){if(!e)return"";const n=e.match(/^task-(\d+)$/);return n?n[1]:e}function _t(e,n=!0){if(e==null)return"";const s=String(e).trim();if(!s)return"";const r=new Date(s.replace(/^(\d{4}-\d{2}-\d{2}) /,"$1T"));if(Number.isNaN(r.getTime()))return s;const a=c=>String(c).padStart(2,"0"),i=`${r.getFullYear()}-${a(r.getMonth()+1)}-${a(r.getDate())}`,l=`${a(r.getHours())}:${a(r.getMinutes())}`;return n?`${i} ${l}:${a(r.getSeconds())}`:`${i} ${l}`}function Pe(e,n){return`/project/${encodeURIComponent(e)}/task/${encodeURIComponent(n)}`}function Qr(e){return e>=1048576?`${(e/1048576).toFixed(1)} MiB`:e>=1024?`${(e/1024).toFixed(1)} KiB`:`${e} B`}function Yr({taskId:e,agentId:n,onPendingChange:s}){var v;const r=H(),[a,i]=o.useState(null),[l,c]=o.useState(null),[m,h]=o.useState(!0),[f,p]=o.useState(!1),[u,d]=o.useState(""),[x,b]=o.useState(""),y=o.useRef(!1),T=o.useRef(0);o.useEffect(()=>(s==null||s(!!a),()=>s==null?void 0:s(!1)),[a,s]);const C=o.useCallback(async()=>{const D=++T.current;h(!0),b("");try{const P=await M.tasks.untrackedFiles(e,n);D===T.current&&i(P)}catch(P){D===T.current&&(i(null),P instanceof ze&&P.status===409?b(P.message):d(P instanceof Error?P.message:String(P)))}finally{D===T.current&&h(!1)}},[e,n]);o.useEffect(()=>(i(null),c(null),d(""),C(),()=>{T.current+=1}),[C]);const A=async(D,P)=>{if(!y.current){y.current=!0,p(!0),d(""),c(null);try{await M.tasks.resolveUntrackedFiles(e,n,{action:D,token:P.token}),T.current+=1,i(null)}catch(I){d(I instanceof Error?I.message:String(I)),await C()}finally{y.current=!1,p(!1)}}},w=D=>t.jsx("ul",{className:"my-2 max-h-48 overflow-auto rounded bg-og-25 p-2 font-mono text-xs",children:D.map(P=>t.jsxs("li",{className:"flex justify-between gap-3",children:[t.jsx("span",{className:"whitespace-pre-wrap break-all",children:P.path}),t.jsx("span",{className:"shrink-0 text-og-500",children:Qr(P.size)})]},P.pathBase64??P.path))}),k=!!(a!=null&&a.files.length),j=!!((v=a==null?void 0:a.conflicts)!=null&&v.length);return!m&&!f&&!u&&!x&&!a?null:t.jsxs("section",{className:"mb-2 rounded-md border border-accent/25 bg-accent-soft/60 p-3 text-sm","aria-label":r.untrackedFiles.heading,children:[(m||f)&&t.jsx("p",{role:"status",children:f?r.untrackedFiles.working:r.untrackedFiles.loading}),x&&t.jsxs("p",{role:"status",children:[r.untrackedFiles.unavailable," ",x]}),u&&t.jsx("p",{role:"alert",className:"whitespace-pre-wrap break-words text-red-600",children:u}),a&&t.jsxs(t.Fragment,{children:[k&&t.jsxs(t.Fragment,{children:[t.jsx("h3",{className:"font-semibold",children:r.untrackedFiles.title(a.files.length)}),t.jsx("p",{children:r.untrackedFiles.guidance})]}),!k&&!j&&t.jsx("p",{children:r.untrackedFiles.readyToContinue}),t.jsxs("dl",{className:"mt-2 grid grid-cols-[auto_1fr] gap-x-2 text-xs",children:[t.jsx("dt",{children:r.untrackedFiles.agent}),t.jsx("dd",{children:a.agentId}),t.jsx("dt",{children:r.untrackedFiles.host}),t.jsx("dd",{children:a.host}),t.jsx("dt",{children:r.untrackedFiles.workdir}),t.jsx("dd",{className:"break-all",children:a.workdir})]}),k&&w(a.files),j&&t.jsxs(t.Fragment,{children:[t.jsx("p",{children:r.untrackedFiles.conflicts}),w(a.conflicts)]}),a.manualCleanupRequired&&t.jsx("p",{children:r.untrackedFiles.manualCleanup}),a.keepLimitExceeded&&t.jsx("p",{children:r.untrackedFiles.keepLimit}),a.trackedChanges&&t.jsx("p",{children:r.untrackedFiles.trackedChanges}),a.files.some(D=>D.kind==="directory")&&t.jsx("p",{children:r.untrackedFiles.directory}),k&&t.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"btn-primary",disabled:f||m||a.trackedChanges||a.keepLimitExceeded||j,onClick:()=>void A("keep",a),children:r.untrackedFiles.keep}),t.jsx("button",{type:"button",className:"btn-secondary",disabled:f||m||a.trackedChanges||a.manualCleanupRequired||a.files.some(D=>D.kind==="directory"),onClick:()=>c(a),children:r.untrackedFiles.discard})]}),!k&&!j&&t.jsx("button",{type:"button",className:"btn-primary mt-2",disabled:f||m||a.trackedChanges,onClick:()=>void A("continue",a),children:r.untrackedFiles.continue})]}),t.jsx("button",{type:"button",className:"btn-secondary mt-2",disabled:f||m,onClick:()=>{d(""),C()},children:r.untrackedFiles.refresh}),t.jsxs(Re,{open:l!==null,title:r.untrackedFiles.confirmTitle,onClose:()=>c(null),size:"sm",footer:t.jsxs("div",{className:"flex justify-end gap-2",children:[t.jsx("button",{type:"button",className:"btn-secondary",onClick:()=>c(null),children:r.common.cancel}),t.jsx("button",{type:"button",className:"btn-danger",disabled:f,onClick:()=>{l&&A("discard",l)},children:r.untrackedFiles.discard})]}),children:[t.jsx("p",{children:r.untrackedFiles.confirmBody}),l&&w(l.files)]})]})}const Ht={unknown:"pill pill-idle",idle:"pill pill-idle",pending:"pill pill-warn",working:"pill pill-live",waiting:"pill pill-review",error:"pill pill-warn"};function Jr(e,n,s,r=s!==void 0){const a=s!==void 0?tn.has(s.status):r;return e==="greeting_failed"?"restart-runtime":e==="agent_dialog_pending"?"terminal":e==="bootstrap-marker-clear-failed"?(s==null?void 0:s.status)==="in_progress"||!s&&r?"task":"resume":e==="restart-redispatch-failed"?(s?["in_progress","fixing","approved"].includes(s.status):r)?"task":"resume":a&&(e==="agent_dialog_resolved_runtime"||e!=null&&e.startsWith("signal-arm-failed"))?"task":e==="dispatch-failed:ack_unknown"&&n==="dev"&&s&&["spec-ready","review","merge-ready","max_rounds"].includes(s.status)?"resume":a&&(e==="dispatch-failed:ack_unknown"||e==="dev-wait-gate-failed-after-qa-started")||a&&(s==null?void 0:s.status)!=="spec-ready"&&(s==null?void 0:s.status)!=="max_rounds"&&(e==="dirty-workdir"||e==="checkout-preparation-failed")&&n==="dev"?"task":"resume"}function xs(e){var n;return!!((n=e.binding)!=null&&n.creationToken)&&!e.binding.paneId&&e.binding.status!=="awaiting_human"&&e.reason!=="PENDING_HUMAN"}function Xr(e,n){var s,r,a;return e.tmuxSessionStatus==="unreachable"?{kind:"alert",label:n.sessionStatus.unreachable,cls:"pill pill-danger"}:xs(e)?{kind:"runtime",label:n.bootstrappingBadge,cls:"pill pill-review"}:Gn(e)?{kind:"runtime",label:n.dispatchingBadge,cls:"pill pill-review",title:n.dispatchingTitle}:e.tmuxSessionStatus==="absent"?{kind:"alert",label:n.sessionStatus.absent,cls:"pill pill-warn"}:e.runtimeStatus==="error"?{kind:"alert",label:n.runtimeStatus.error,cls:Ht.error}:((s=e.binding)==null?void 0:s.status)==="awaiting_human"?{kind:"alert",label:n.heldBadge,cls:"pill pill-warn",title:e.binding.awaitingReason??n.heldDefaultReason}:(a=(r=e.binding)==null?void 0:r.needInput)!=null&&a.at?{kind:"alert",label:n.needInputBadge,cls:"pill pill-warn",title:n.needInputTitle(new Date(e.binding.needInput.at).toLocaleString())}:e.runtimeStatus==="pending"?{kind:"alert",label:n.runtimeStatus.pending,cls:Ht.pending}:{kind:"runtime",label:n.runtimeStatus[e.runtimeStatus],cls:Ht[e.runtimeStatus]}}function Zr(e,n){const s=Xr(e,n);if(!e.stale)return{...s,stale:!1};const r=n.staleTitle(e.observedAt?new Date(e.observedAt).toLocaleString():void 0);return{...s,stale:!0,title:s.title?`${s.title} · ${r}`:r}}function bs({agent:e,projectId:n,role:s,runtime:r,model:a,onDeleted:i,pendingRestart:l=!1,terminalLoading:c=!1,showTaskBinding:m=!0,terminalMode:h="activity-preview",active:f,onActivate:p,task:u}){var Ee,$e,Ce,Te,it,ot,lt,Qe,ct;const d=H(),[x,b]=o.useState(!1),[y,T]=o.useState(null),{show:C}=je(),A=ln(),{compact:w,clear:k,remove:j,compacting:v,clearing:D,deleting:P,deleteError:I,busy:O}=ls(n,[e.id],i),[J,E]=o.useState(!1),[W,re]=o.useState(!1),[te,X]=o.useState(!1),[V,ae]=o.useState(!1),z=(Ee=e.binding)==null?void 0:Ee.taskId,le=(u==null?void 0:u.id)===z?u:void 0,ne=(($e=e.binding)==null?void 0:$e.status)==="awaiting_human",ge=(Te=(Ce=e.binding)==null?void 0:Ce.needInput)==null?void 0:Te.at,q=ne&&((it=e.binding)==null?void 0:it.awaitingPhase)==="greeting_failed",ie=Jr((ot=e.binding)==null?void 0:ot.awaitingPhase,s,le,!!z),me=xs(e),xe=!l&&!c&&!e.stale&&!ne&&e.tmuxSessionStatus==="absent"&&!((lt=e.binding)!=null&<.creationToken)&&!z,ye=me&&e.tmuxSessionStatus!=="present",N=Zr(e,d.agents),we=h==="activity-preview"&&!ye&&(e.runtimeStatus==="working"||e.runtimeStatus==="pending"),pe=h==="embedded-full",L=pe&&typeof p=="function",G=L&&f===!0,S=c||l||ye,U=c?d.agents.agentStatusLoading:l?d.agents.terminalNeedsRestart:d.agents.bootstrappingTerminalDisabled,_=zn(r,a),se=async()=>{b(!0),T(null);try{await M.agents.stop(e.id)}catch(oe){T(oe instanceof Error?oe.message:String(oe))}finally{b(!1)}},B=async()=>{X(!0);try{(await M.projects.bootstrap(n)).ok?C({kind:"success",title:d.agents.retryBootstrapSucceededTitle,body:d.agents.retryBootstrapSucceededBody}):C({kind:"warn",title:d.agents.retryBootstrapStillFailingTitle,body:d.agents.retryBootstrapStillFailingBody})}catch(oe){C({kind:"error",title:d.agents.retryBootstrapFailedTitle,body:oe instanceof Error?oe.message:String(oe)})}finally{X(!1)}},R=async()=>{ae(!0);try{const oe=await M.projects.retryAgent(n,e.id);C({kind:oe.runtimeStatus==="pending"?"warn":"success",title:oe.runtimeStatus==="pending"?d.agents.retrySessionPending:d.agents.retrySessionReady})}catch(oe){C({kind:"error",title:d.agents.retrySessionFailed,body:oe instanceof Error?oe.message:String(oe)})}finally{ae(!1)}},$=async()=>{if(await A({title:d.agents.resumeConfirmTitle(e.id),body:q?d.agents.resumeGreetingBody:d.agents.resumeDefaultBody,confirmLabel:d.agents.resume})){E(!0);try{if(q){e.tmuxSessionStatus==="present"?await M.projects.restartRepl(n,e.id):await M.projects.retryAgent(n,e.id),C({kind:"success",title:d.agents.regreetingStartedTitle(e.id),body:d.agents.regreetingStartedBody});return}const Oe=await M.projects.resumeAgent(n,e.id);C({kind:"success",title:d.agents.resumedTitle(e.id),body:Oe.releasedBinding?d.agents.resumedReleasedBody:d.agents.resumedKeptBody})}catch(Oe){C({kind:"error",title:d.agents.resumeFailedTitle,body:Oe instanceof Error?Oe.message:String(Oe)})}finally{E(!1)}}},Z=L&&!S&&!G,K=["card relative flex h-full min-w-0 flex-col overflow-visible p-4",G?"ring-2 ring-accent":""].filter(Boolean).join(" "),ee="mb-3 flex items-start justify-between gap-2",be=["mb-2 mt-3 h-80 min-h-0 overflow-hidden border border-hairline bg-surface",Z?"cursor-pointer":""].filter(Boolean).join(" "),Ve=Z?()=>p==null?void 0:p():void 0,Me=Z?oe=>{(oe.key==="Enter"||oe.key===" ")&&(oe.preventDefault(),p==null||p())}:void 0;return t.jsxs("div",{className:K,"data-agent-card":L?e.id:void 0,children:[t.jsxs("div",{className:ee,children:[t.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[t.jsx("span",{className:"shrink-0 font-mono text-xs font-medium tracking-[0.05em] text-og-500",children:s==="qa"?"QA":"Dev"}),t.jsx("span",{className:"min-w-0 truncate whitespace-nowrap font-display text-xs text-og-1000",title:Kn(e.id,r,a),children:e.id}),_&&t.jsxs("span",{className:"hidden shrink-0 whitespace-nowrap text-xs text-og-400 sm:inline",title:_,children:["(",_,")"]})]}),t.jsx("span",{className:N.stale?`${N.cls} pill--stale shrink-0`:`${N.cls} shrink-0`,title:N.title,children:N.label}),N.stale&&t.jsx("span",{className:"sr-only",children:N.title})]}),ye&&t.jsx("div",{className:"mb-2 rounded-md border border-accent-soft bg-accent-soft/40 px-2.5 py-2 text-xs text-accent",children:d.agents.bootstrappingNotice}),ne&&t.jsxs("div",{className:"mb-2 space-y-1 rounded-md border border-accent/25 bg-accent-soft/60 px-2.5 py-2 text-xs text-accent",children:[t.jsxs("div",{children:[t.jsx("span",{className:"font-mono",children:(Qe=e.binding)==null?void 0:Qe.awaitingPhase}),((ct=e.binding)==null?void 0:ct.awaitingReason)&&t.jsxs("span",{children:[" · ",e.binding.awaitingReason]})]}),!W&&t.jsx("div",{className:"text-og-700",children:d.agents.holdRecovery[ie]})]}),ne&&z&&t.jsx(Yr,{taskId:z,agentId:e.id,onPendingChange:re},`${z}:${e.id}`),!me&&e.runtimeStatus==="pending"&&t.jsxs("div",{className:"mb-2 space-y-1 rounded-md border border-accent/25 bg-accent-soft/60 px-2.5 py-2 text-xs text-accent",children:[t.jsx("div",{className:"font-medium",children:d.agents.awaitingHumanIntervention}),t.jsxs("div",{children:[d.agents.openTerminalPrefix,t.jsx(Se,{to:`/terminal/${e.id}`,className:"text-accent hover:text-accent-hover underline",children:d.agents.terminal}),d.agents.openTerminalSuffix]})]}),ge&&t.jsxs("div",{className:"mb-2 space-y-1 rounded-md border border-accent/25 bg-accent-soft/60 px-2.5 py-2 text-xs text-accent",children:[t.jsx("div",{className:"font-medium",children:d.agents.needInputNoticeTitle}),t.jsxs("div",{children:[d.agents.needInputPrefix,t.jsx(Se,{to:`/terminal/${e.id}`,className:"text-accent hover:text-accent-hover underline",children:d.agents.terminal}),d.agents.needInputSuffix]})]}),e.latestError&&t.jsxs("div",{className:"mb-2 space-y-1 rounded-md border border-accent/25 bg-accent-soft px-2.5 py-2 text-xs text-accent",children:[t.jsx("div",{className:"break-words font-medium",children:e.latestError.message}),t.jsxs("div",{className:"font-mono text-xs opacity-80",children:[e.latestError.reason," · ",e.latestError.occurredAt]})]}),e.latestBootstrapError&&t.jsxs("div",{className:"mb-2 space-y-1 rounded-md border border-accent/25 bg-accent-soft px-2.5 py-2 text-xs text-accent",children:[t.jsx("div",{className:"break-words font-medium",children:e.latestBootstrapError.message}),e.latestBootstrapError.recommendation&&t.jsx("div",{className:"break-words",children:e.latestBootstrapError.recommendation}),t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsxs("div",{className:"truncate font-mono text-xs opacity-80",children:[e.latestBootstrapError.reason," · ",e.latestBootstrapError.occurredAt]}),t.jsx("button",{type:"button",onClick:B,disabled:te,className:"btn-primary shrink-0",children:te?d.common.retrying:d.agents.retryBootstrap})]})]}),m&&z&&t.jsxs("div",{className:"mb-2 text-xs text-og-500",children:[d.agents.taskLabel,t.jsx("span",{className:"font-mono text-og-700",children:z})]}),we&&t.jsx("div",{className:"mb-2 overflow-hidden border border-hairline bg-surface",children:t.jsx(Xe,{agentId:e.id,mode:"preview",maxLines:6,interactive:!1})}),pe&&t.jsx("div",{className:be,role:Z?"button":void 0,tabIndex:Z?0:void 0,"aria-label":Z?d.agents.activateTerminal(e.id):void 0,onClick:Ve,onKeyDown:Me,children:S?t.jsx("div",{className:"flex h-full items-center justify-center px-3 text-sm text-og-500",children:U}):L?G?t.jsx(Xe,{agentId:e.id,mode:"full",interactive:!0,autoFocus:!0}):t.jsx(Xe,{agentId:e.id,mode:"preview",interactive:!1}):t.jsx(Xe,{agentId:e.id,mode:"full",interactive:!0,autoFocus:!1,deferFullUntilFocus:!0})}),l&&t.jsx("div",{className:"mb-2 rounded-md border border-accent/25 bg-accent-soft/60 px-2.5 py-1.5 text-xs text-accent",children:d.agents.pendingRestartNotice}),t.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[t.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2 overflow-x-auto scrollbar-none",children:[xe&&t.jsx("button",{type:"button",className:"btn-primary shrink-0",disabled:V,onClick:R,children:V?d.common.retrying:d.agents.retrySession}),S?t.jsx("span",{className:"shrink-0 cursor-not-allowed text-sm text-og-400",title:U,children:d.agents.terminal}):t.jsx(Se,{to:`/terminal/${e.id}`,className:"btn-secondary shrink-0",children:d.agents.terminal}),!l&&e.runtimeStatus==="working"&&t.jsx("button",{onClick:se,disabled:x,className:"btn-ghost shrink-0",children:x?d.agents.stopping:d.agents.stop}),ne&&!W&&(ie==="resume"||ie==="restart-runtime")&&t.jsx("button",{type:"button",onClick:$,disabled:J,title:q?d.agents.resumeGreetingButtonTitle:d.agents.resumeDefaultButtonTitle,className:"btn-primary shrink-0",children:J?d.agents.resuming:ie==="restart-runtime"?d.agents.restartRuntime:d.agents.resume}),ne&&ie==="terminal"&&t.jsx(Se,{to:`/terminal/${e.id}`,className:"btn-primary shrink-0",children:d.agents.openTerminalAction}),ne&&ie==="task"&&z&&t.jsx(Se,{to:Pe(n,z),className:"btn-primary shrink-0",children:d.agents.openTaskActions}),ne&&ie==="delete-agent"&&t.jsx("button",{type:"button",onClick:()=>void j(),disabled:P,className:"btn-primary shrink-0",children:P?d.common.deleting:d.agents.deleteToRecover})]}),t.jsx(Dt,{ariaLabel:d.agents.actionsMenu(e.id),className:"shrink-0",placement:"up",autoFocusFirstItem:!0,disabled:P,children:oe=>t.jsxs(t.Fragment,{children:[t.jsx(ke,{onClick:()=>{oe(),w()},disabled:O,title:d.agents.compactMenuItemTitle,children:v?d.agents.compacting:d.agents.compact}),t.jsx(ke,{onClick:()=>{oe(),k()},disabled:O,title:d.agents.clearMenuItemTitle,children:D?d.agents.clearing:d.agents.clear}),t.jsx(ke,{onClick:()=>{oe(),j()},disabled:O,children:P?d.common.deleting:d.common.delete})]})})]}),y&&t.jsx("div",{className:"mt-1.5 break-words text-xs text-accent",children:y}),I&&t.jsx("div",{className:"mt-1.5 break-words text-xs text-accent",children:I})]})}const qt="baxian:terminal-activated";function vs({coordinateAcrossInstances:e=!0}={}){const n=o.useId(),[s,r]=o.useState(null);o.useEffect(()=>{if(s===null)return;const i=m=>{m.composedPath().some(p=>p instanceof Element&&p.hasAttribute("data-agent-card"))||r(null)},l=m=>{if(m.key!=="Escape")return;const h=document.activeElement;h instanceof Element&&h.closest("[data-agent-card]")||r(null)},c=m=>{const h=m.detail;(h==null?void 0:h.ownerId)!==n&&r(null)};return document.addEventListener("click",i),document.addEventListener("keydown",l),e&&document.addEventListener(qt,c),()=>{document.removeEventListener("click",i),document.removeEventListener("keydown",l),e&&document.removeEventListener(qt,c)}},[s,e,n]);const a=o.useCallback(i=>{r(i),e&&document.dispatchEvent(new CustomEvent(qt,{detail:{ownerId:n}}))},[e,n]);return{activeAgentId:s,activateAgentCard:a}}function ys({team:e,projectId:n,agentsById:s,agentsLoaded:r,agentsError:a=!1,tasks:i,onDeleted:l,terminalMode:c="activity-preview"}){const m=H(),h=e.find(E=>E.role==="dev")??e[0],f=i.filter(E=>na(E,h==null?void 0:h.id)),p=h?i.filter(E=>sa(E,n,h.id)).sort((E,W)=>E.createdAt.localeCompare(W.createdAt)):[],u=e.map(E=>E.id).join(" / "),d=`Agent Team ${u}`,x=Le(),{compact:b,clear:y,remove:T,compacting:C,clearing:A,deleting:w,deleteError:k,busy:j}=ls(n,e.map(E=>E.id),l),v=c==="embedded-full",{activeAgentId:D,activateAgentCard:P}=vs({coordinateAcrossInstances:v}),I=c==="embedded-full"?e.length<=1?"lg:grid-cols-1":e.length===2?"lg:grid-cols-2":e.length===3?"lg:grid-cols-3":"lg:grid-cols-4":"sm:grid-cols-2",O=!!h&&p.length>0,J=f.length===0&&!O;return t.jsxs("div",{role:"group","aria-label":d,className:"min-w-0 rounded-lg border border-og-100 bg-og-25/60 p-3",children:[t.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[t.jsx("span",{className:"shrink-0 font-display text-xs font-semibold uppercase tracking-[0.06em] text-og-500",children:"Team"}),t.jsx("span",{className:"min-w-0 truncate font-mono text-xs text-og-700",title:u,children:u}),t.jsx(Dt,{ariaLabel:m.agents.teamActionsMenu(u),className:"ml-auto shrink-0",autoFocusFirstItem:!0,disabled:w,children:E=>t.jsxs(t.Fragment,{children:[t.jsx(ke,{onClick:()=>{E(),b()},disabled:j,title:m.agents.teamCompactMenuItemTitle,children:C?m.agents.compacting:m.agents.compact}),t.jsx(ke,{onClick:()=>{E(),y()},disabled:j,title:m.agents.teamClearMenuItemTitle,children:A?m.agents.clearing:m.agents.clear}),t.jsx(ke,{onClick:()=>{E(),T()},disabled:j,children:w?m.common.deleting:m.common.delete})]})})]}),k&&t.jsx("div",{className:"mb-2 break-words text-xs text-accent",children:k}),O&&h&&t.jsx(ta,{tasks:p,devId:h.id,agentsById:s,label:d}),f.length>0&&t.jsx("div",{className:"card mb-2 max-h-28 overflow-y-auto divide-y divide-hairline",children:f.map(E=>{const W=Fe(E.phase)?E.specReviewRound??0:E.reviewRound;return t.jsxs("button",{type:"button",onClick:()=>x(Pe(E.projectId,E.id)),className:"flex w-full items-center gap-3 px-3 py-2 text-left text-sm transition-colors hover:bg-og-50/60",children:[t.jsxs("div",{className:"min-w-0 flex-1 flex items-center gap-2",children:[t.jsx("span",{className:"shrink-0 font-mono text-xs text-og-500",title:E.id,children:un(E.id)}),t.jsx("span",{className:"truncate text-og-1000",children:E.title})]}),t.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[W>0&&t.jsx("span",{className:"shrink-0 text-xs text-og-500",children:m.agents.round(W)}),t.jsx(dn,{task:E,className:"shrink-0"})]})]},E.id)})}),J&&t.jsx("div",{className:"mb-2 rounded-lg border border-hairline bg-surface px-3 py-2 text-sm text-og-400","aria-label":m.agents.noActiveTaskAriaLabel(d),children:m.agents.noActiveTask}),t.jsx("div",{className:`grid grid-cols-1 ${I} gap-4`,children:e.map(E=>{var X;const W=s.get(E.id),re=W??{id:E.id,projectId:n,runtimeStatus:"unknown",tmuxSessionStatus:"unknown",stale:!0},te=((X=re.binding)==null?void 0:X.taskId)===void 0?void 0:i.find(V=>{var ae;return V.id===((ae=re.binding)==null?void 0:ae.taskId)});return t.jsx(bs,{agent:re,projectId:n,role:E.role,runtime:E.runtime,model:E.model,pendingRestart:r&&!W,terminalLoading:!r&&!W&&!a,onDeleted:l,showTaskBinding:!1,terminalMode:c,task:te,...v?{active:D===E.id,onActivate:()=>P(E.id)}:{}},E.id)})})]})}function ea(e){var n,s,r;return!!e&&e.runtimeStatus==="idle"&&((n=e.binding)==null?void 0:n.status)!=="awaiting_human"&&!((s=e.binding)!=null&&s.creationToken)&&!((r=e.binding)!=null&&r.taskId)}function ta({tasks:e,devId:n,agentsById:s,label:r}){const a=H(),{show:i}=je(),l=Le(),[c,m]=o.useState(null),h=async(f,p)=>{m(f);try{await M.tasks.advance(f,{executor:"dev",agentId:p}),i({kind:"success",title:a.agents.taskHandedTo(f,p)})}catch(u){i({kind:"error",title:a.agents.startFailed,body:u instanceof Error?u.message:String(u)})}finally{m(null)}};return t.jsx("div",{role:"group",className:"card mb-2 max-h-28 overflow-y-auto divide-y divide-hairline","aria-label":`${r} claimable tasks for ${n}`,children:e.map(f=>{const p=f.preferredAgentId||n,u=ea(s.get(p)),d=f.preferredAgentId==="",x=c!==null;return t.jsxs("div",{className:"flex items-center gap-3 px-3 py-2 text-sm",children:[t.jsxs("button",{type:"button",onClick:()=>l(Pe(f.projectId,f.id)),className:"min-w-0 flex-1 flex items-center gap-2 text-left transition-colors hover:text-accent-hover",children:[t.jsx("span",{className:"shrink-0 font-mono text-xs text-og-500",title:f.id,children:un(f.id)}),t.jsx("span",{className:"truncate text-og-1000",title:f.title,children:f.title}),d&&t.jsx("span",{className:"pill shrink-0",children:a.agents.unassigned})]}),t.jsx("button",{type:"button",onClick:()=>void h(f.id,p),disabled:!u||x,title:u?a.agents.handToAndStart(p):a.agents.agentUnavailable(p),className:"shrink-0 text-sm font-medium text-accent transition-colors hover:text-accent-hover disabled:opacity-50 disabled:cursor-not-allowed",children:c===f.id?a.agents.starting:a.agents.start})]},f.id)})})}function na(e,n){return!n||!tn.has(e.status)?!1:e.devAgentId===n}function sa(e,n,s){return e.projectId!==n||e.status!=="pending"?!1:e.preferredAgentId===s||e.preferredAgentId===""}const he="w-full rounded-md border border-og-100 bg-surface px-2.5 py-1.5 text-sm text-og-800 placeholder:text-og-400 focus:border-accent focus:outline-none focus:ring-[3px] focus:ring-accent-soft disabled:cursor-not-allowed disabled:opacity-50",ue="mb-1.5 block text-xs font-medium text-og-700",Nt="mt-1 text-xs text-accent",qe="mt-1 text-xs text-og-500",Ie="h-3.5 w-3.5 accent-accent",ra=/^[a-z][a-z0-9-]{1,31}$/;function aa({open:e,onClose:n,onCreated:s}){const r=H(),[a,i]=o.useState(""),[l,c]=o.useState(""),[m,h]=o.useState(null),[f,p]=o.useState("human"),[u,d]=o.useState(!1),[x,b]=o.useState(null),[y,T]=o.useState({}),[C,A]=o.useState(new Set),w=o.useRef(0),{show:k}=je(),{flagDirty:j}=Lt();o.useEffect(()=>{if(!e)return;w.current+=1;const I=w.current;i(""),c(""),h(null),p("human"),b(null),T({}),A(new Set),M.config.get().then(O=>{I===w.current&&A(new Set(O.project.map(J=>J.id)))}).catch(O=>{I===w.current&&b(r.common.loadFailed(O instanceof Error?O.message:String(O)))})},[e]);const v=()=>{u||n()},D=()=>{const I={};return a?ra.test(a)?C.has(a)&&(I.id=r.createProject.idTakenError):I.id=r.common.idFormatError:I.id=r.createProject.required,l.trim()||(I.repo=r.createProject.required),T(I),Object.keys(I).length===0},P=async I=>{if(I.preventDefault(),!!D()){d(!0),b(null);try{const O=await M.projects.create({id:a,repo:l.trim(),merge:m,...f?{specApproval:f}:{}});O.restartRequired&&j(),k({kind:"success",title:r.createProject.createdToastTitle(O.project.id)}),s(O.project.id)}catch(O){b(O instanceof Error?O.message:String(O))}finally{d(!1)}}};return t.jsx(Re,{open:e,onClose:v,title:r.createProject.title,size:"md",footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:v,disabled:u,className:"btn-secondary",children:r.common.cancel}),t.jsx("button",{type:"submit",form:"create-project-form",disabled:u,className:"btn-primary",children:u?r.common.creating:r.common.create})]}),children:t.jsxs("form",{id:"create-project-form",onSubmit:P,className:"space-y-3",children:[x&&t.jsx("div",{className:"whitespace-pre-line rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-sm text-accent",children:x}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"proj-id",children:r.createProject.idLabel}),t.jsx("input",{id:"proj-id",type:"text",value:a,onChange:I=>i(I.target.value),className:he,placeholder:"baxian",disabled:u}),y.id&&t.jsx("div",{className:Nt,children:y.id})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"proj-repo",children:r.createProject.repoLabel}),t.jsx("input",{id:"proj-repo",type:"text",value:l,onChange:I=>c(I.target.value),className:he,placeholder:"https://github.com/baxian-ai/baxian.git",disabled:u}),y.repo&&t.jsx("div",{className:Nt,children:y.repo})]}),t.jsxs("div",{children:[t.jsx("span",{className:ue,children:r.createProject.mergeStrategyLabel}),t.jsxs("label",{className:"mb-1 flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"merge",checked:m===null,onChange:()=>h(null),disabled:u,className:"h-3.5 w-3.5 accent-accent"}),t.jsx("span",{className:"text-sm text-og-800",children:r.createProject.mergeHumanLabel})]}),t.jsxs("label",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"merge",checked:m==="auto",onChange:()=>h("auto"),disabled:u,className:"h-3.5 w-3.5 accent-accent"}),t.jsx("span",{className:"text-sm text-og-800",children:r.createProject.mergeAutoLabel})]})]}),t.jsxs("div",{children:[t.jsx("span",{className:ue,children:r.createProject.specApprovalLabel}),t.jsxs("label",{className:"mb-1 flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"spec-approval",checked:f==="human",onChange:()=>p("human"),disabled:u,className:"h-3.5 w-3.5 accent-accent"}),t.jsx("span",{className:"text-sm text-og-800",children:r.createProject.specApprovalHumanLabel})]}),t.jsxs("label",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"spec-approval",checked:f===null,onChange:()=>p(null),disabled:u,className:"h-3.5 w-3.5 accent-accent"}),t.jsx("span",{className:"text-sm text-og-800",children:r.createProject.specApprovalAutoLabel})]})]})]})})}const Rn=/^[a-z][a-z0-9-]{1,31}$/,ia=500,Ut={id:"",mode:"local",host:"",runtime:"",workdir:"",yolo:!0,model:"",addDirs:""};function oa(e){return e.alias?e.alias:`${e.user?`${e.user}@`:""}${e.hostname}${e.port!=null?`:${e.port}`:""}`}function ws({open:e,onClose:n,projectId:s,onCreated:r}){var L,G,S,U,_,se;const a=H(),[i,l]=o.useState(Ut),[c,m]=o.useState(null),[h,f]=o.useState([]),[p,u]=o.useState(new Set),[d,x]=o.useState(null),[b,y]=o.useState(!1),[T,C]=o.useState(!1),[A,w]=o.useState(null),[k,j]=o.useState(!1),[v,D]=o.useState(null),[P,I]=o.useState(!1),O=o.useRef(null),J=o.useRef(null),E=o.useRef(0),W=o.useRef(0),{show:re}=je(),{flagDirty:te}=Lt();o.useEffect(()=>{if(!e)return;W.current+=1;const B=W.current;l(Ut),m(null),f([]),u(new Set),x(null),y(!1),C(!1),w(null),E.current+=1,D(null),I(!1),M.config.get().then(R=>{if(B!==W.current)return;f(R.host??[]);const $=new Set;R.project.forEach(Z=>Z.agent.forEach(K=>K.forEach(ee=>$.add(ee.id)))),u($)}).catch(()=>{})},[e,s]);const X=()=>{k||n()},V=o.useCallback(()=>{O.current&&O.current.abort();const B=new AbortController;O.current=B,y(!0),D(null);const R=i.mode==="remote"?{hostId:i.host}:{};M.agents.probe(i.mode,R,{signal:B.signal}).then($=>{B.signal.aborted||(x($),D(null))}).catch($=>{B.signal.aborted||(x(null),D($ instanceof Error?$.message:String($)))}).finally(()=>{O.current===B&&y(!1)})},[i.mode,i.host]);o.useEffect(()=>{if(e&&(x(null),w(null),C(!1),E.current+=1,O.current&&O.current.abort(),!(i.mode==="remote"&&!i.host)))return J.current&&clearTimeout(J.current),J.current=setTimeout(V,ia),()=>{J.current&&clearTimeout(J.current)}},[e,i.mode,i.host,c,V]),o.useEffect(()=>{e||O.current&&O.current.abort()},[e]),o.useEffect(()=>()=>{O.current&&O.current.abort(),J.current&&clearTimeout(J.current)},[]);const ae=()=>{if(T)return;const B=E.current;C(!0),w(null);const R=i.mode==="remote"?{hostId:i.host}:{};M.agents.installTmux(i.mode,R).then($=>{E.current===B&&(w({ok:$.ok,message:$.message}),C(!1),$.ok&&V())}).catch($=>{E.current===B&&(w({ok:!1,message:$ instanceof Error?$.message:String($)}),C(!1))})},z=c?"qa":"dev",le=Rn.test(i.id)&&!p.has(i.id)&&i.id!==(c==null?void 0:c.agent.id),ne=i.mode==="local"||i.mode==="remote"&&i.host!=="",ge=i.runtime!==""&&!!((L=d==null?void 0:d.runtimes[i.runtime])!=null&&L.ok),q=!!(d!=null&&d.tmux.ok),ie=i.mode==="local"||!!((G=d==null?void 0:d.ssh)!=null&&G.ok),me=!k&&le&&ne&&ge&&q&&ie,xe=async B=>{var Z,K;if(B.preventDefault(),!me)return;D(null);const R=i.addDirs.split(`
|
|
10
|
+
`)}:{kind:"success",title:O}),s==null||s()}catch(v){x(wn(v))}finally{u(!1)}}},compacting:c,clearing:h,deleting:p,deleteError:d,busy:c||h||p}}const Nr=[500,1e3,2e3,4e3,8e3,15e3,3e4];class cs{constructor(n){ce(this,"attempts",0);ce(this,"timer",null);ce(this,"delaysMs");this.opts=n,this.delaysMs=n.delaysMs??Nr}schedule(){if(this.timer||!this.shouldReconnect())return;const n=this.delaysMs[Math.min(this.attempts,this.delaysMs.length-1)];this.attempts+=1,this.timer=setTimeout(()=>{this.timer=null,this.shouldReconnect()&&this.opts.reconnect()},n)}cancel(){this.timer&&(clearTimeout(this.timer),this.timer=null)}reset(){this.attempts=0}shouldReconnect(){return this.opts.shouldReconnect?this.opts.shouldReconnect():!0}}function ds(e,n,s){return(e==null?void 0:e.code)!==4401||n!==s?!1:(window.dispatchEvent(new CustomEvent(et)),!0)}function us(e){return Array.from(new TextEncoder().encode(e)).map(n=>n.toString(16).padStart(2,"0")).join("")}function ms(e){return`${location.protocol==="https:"?"wss":"ws"}://${location.host}${e}`}const hs=(e,n)=>n&&n.length>0?new WebSocket(e,n):new WebSocket(e);let kn=0;function Sr(){kn++;const e=Math.random().toString(36).slice(2,8);return`sub-${Date.now().toString(36)}-${kn}-${e}`}function Rr(){return ms("/api/stream")}class Cr{constructor(n={}){ce(this,"wsUrl");ce(this,"wsFactory");ce(this,"tokenProvider");ce(this,"ws",null);ce(this,"subs",new Map);ce(this,"snapshotPending",new Set);ce(this,"preSubscribeQueue",new Map);ce(this,"outbox",[]);ce(this,"reconnectScheduler");ce(this,"explicitlyClosed",!1);this.wsUrl=n.wsUrl??Rr(),this.wsFactory=n.wsFactory??hs,this.tokenProvider=n.tokenProvider??sn,this.reconnectScheduler=new cs({reconnect:()=>this.openSocket(),shouldReconnect:()=>!this.explicitlyClosed&&this.subs.size>0})}subscribe(n){const s=Sr(),r={subscriberId:s,agentId:n.agentId,mode:n.mode,onSnapshot:n.onSnapshot,onData:n.onData,onError:n.onError,onSessionGone:n.onSessionGone};return this.subs.set(s,r),this.snapshotPending.add(s),this.preSubscribeQueue.set(s,[]),this.ensureSocket(),this.wsSendOrQueue({op:"subscribe",subscriberId:s,agentId:n.agentId,mode:n.mode}),{subscriberId:s,unsubscribe:()=>this.unsubscribe(s)}}send(n,s){if(this.subs.has(n)){if(this.snapshotPending.has(n)){this.outbox.push({op:"input",subscriberId:n,data:s});return}this.wsSendOrQueue({op:"input",subscriberId:n,data:s})}}resize(n,s,r){const a=this.subs.get(n);a&&(a.lastSize={cols:s,rows:r},!this.snapshotPending.has(n)&&this.wsSendOrQueue({op:"resize",subscriberId:n,cols:s,rows:r}))}ping(){this.wsSendOrQueue({op:"ping"})}close(){if(this.explicitlyClosed=!0,this.reconnectScheduler.cancel(),this.reconnectScheduler.reset(),this.ws){try{this.ws.close()}catch{}this.ws=null}this.subs.clear(),this.snapshotPending.clear(),this.preSubscribeQueue.clear(),this.outbox=[]}unsubscribe(n){this.subs.has(n)&&(this.subs.delete(n),this.snapshotPending.delete(n),this.preSubscribeQueue.delete(n),this.wsSendOrQueue({op:"unsubscribe",subscriberId:n}),this.subs.size===0&&this.teardownSocket())}teardownSocket(){if(this.reconnectScheduler.cancel(),this.reconnectScheduler.reset(),this.outbox=[],this.ws){try{this.ws.close()}catch{}this.ws=null}}ensureSocket(){this.explicitlyClosed||this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING)||this.openSocket()}openSocket(){if(this.explicitlyClosed)return;this.reconnectScheduler.cancel();const n=this.tokenProvider(),s=n?[`baxian.token.${us(n)}`]:void 0;let r;try{r=this.wsFactory(this.wsUrl,s)}catch(a){console.warn("[pane-stream] WebSocket constructor threw:",a),this.scheduleReconnect();return}this.ws=r,r.onopen=()=>{if(r!==this.ws)return;this.reconnectScheduler.reset();for(const i of this.subs.values()){this.snapshotPending.add(i.subscriberId),this.preSubscribeQueue.set(i.subscriberId,[]),i.snapshotSeq=void 0;try{r.send(JSON.stringify({op:"subscribe",subscriberId:i.subscriberId,agentId:i.agentId,mode:i.mode}))}catch(l){console.warn("[pane-stream] resubscribe send failed:",l)}}const a=this.outbox;this.outbox=[];for(const i of a)if(i.op!=="subscribe"){if("subscriberId"in i&&i.subscriberId){if(!this.subs.has(i.subscriberId))continue;if(this.snapshotPending.has(i.subscriberId)&&i.op!=="unsubscribe"){this.outbox.push(i);continue}}try{r.send(JSON.stringify(i))}catch(l){console.warn("[pane-stream] outbox flush failed:",l)}}},r.onmessage=a=>{if(r!==this.ws)return;let i;try{const l=typeof a.data=="string"?a.data:String(a.data);i=JSON.parse(l)}catch{return}this.handleMessage(i)},r.onclose=a=>{r===this.ws&&(this.ws=null,!this.explicitlyClosed&&(ds(a,n,this.tokenProvider())||this.subs.size!==0&&this.scheduleReconnect()))},r.onerror=()=>{}}scheduleReconnect(){this.reconnectScheduler.schedule()}wsSendOrQueue(n){if(this.ws&&this.ws.readyState===WebSocket.OPEN)try{this.ws.send(JSON.stringify(n));return}catch(s){console.warn("[pane-stream] send failed, will queue:",s)}this.outbox.push(n)}handleMessage(n){var s,r;switch(n.type){case"snapshot":this.handleSnapshot(n);break;case"subscribed":this.handleSubscribed(n);break;case"data":this.dispatch(n);break;case"session_gone":for(const a of[...this.subs.values()])a.agentId===n.agentId&&((s=a.onSessionGone)==null||s.call(a));break;case"error":{if(n.subscriberId){const a=this.subs.get(n.subscriberId);(r=a==null?void 0:a.onError)==null||r.call(a,{code:n.code,message:n.message})}else console.warn("[pane-stream] connection-level error:",n.code,n.message);break}}}handleSnapshot(n){const s=this.subs.get(n.subscriberId);s&&s.onSnapshot({cols:n.cols,rows:n.rows,data:n.data})}handleSubscribed(n){const s=this.subs.get(n.subscriberId);if(!s)return;s.snapshotSeq=n.snapshotSeq,s.lastSize||(s.lastSize={cols:n.cols,rows:n.rows}),this.snapshotPending.delete(n.subscriberId);const r=this.preSubscribeQueue.get(n.subscriberId);if(this.preSubscribeQueue.delete(n.subscriberId),r)for(const a of r)a.seq>n.snapshotSeq&&s.onData(a.data);s.mode==="full"&&s.lastSize&&this.wsSendOrQueue({op:"resize",subscriberId:s.subscriberId,cols:s.lastSize.cols,rows:s.lastSize.rows}),this.flushOutboxForSub(n.subscriberId)}flushOutboxForSub(n){if(this.outbox.length===0||!this.ws||this.ws.readyState!==WebSocket.OPEN)return;const s=[];for(const r of this.outbox)if("subscriberId"in r&&r.subscriberId===n&&r.op!=="subscribe")try{this.ws.send(JSON.stringify(r))}catch(a){console.warn("[pane-stream] flushOutboxForSub send failed:",a)}else s.push(r);this.outbox=s}dispatch(n){for(const s of this.subs.values())if(s.agentId===n.agentId)if(this.snapshotPending.has(s.subscriberId)){const r=this.preSubscribeQueue.get(s.subscriberId);r&&r.push({seq:n.seq,data:n.data})}else s.onData(n.data)}}let Mt=null;function Ot(){return Mt||(Mt=new Cr),Mt}function Ar(e){const{agentId:n,mode:s}=e,r=o.useRef(null),[a,i]=o.useState(0),l=o.useRef({onSnapshot:e.onSnapshot,onData:e.onData,onError:e.onError,onSessionGone:e.onSessionGone});l.current={onSnapshot:e.onSnapshot,onData:e.onData,onError:e.onError,onSessionGone:e.onSessionGone},o.useEffect(()=>{const p=Ot().subscribe({agentId:n,mode:s,onSnapshot:u=>l.current.onSnapshot(u),onData:u=>l.current.onData(u),onError:u=>{var d,x;return(x=(d=l.current).onError)==null?void 0:x.call(d,u)},onSessionGone:()=>{var u,d;return(d=(u=l.current).onSessionGone)==null?void 0:d.call(u)}});return r.current=p.subscriberId,()=>{r.current=null,p.unsubscribe()}},[n,s,a]);const c=o.useCallback(f=>{const p=r.current;p&&Ot().send(p,f)},[]),m=o.useCallback((f,p)=>{const u=r.current;u&&Ot().resize(u,f,p)},[]),h=o.useCallback(()=>i(f=>f+1),[]);return{send:c,resize:m,reconnect:h}}const Dr=8;let gt=0,xt,jn=!0;function fs(e){var n;return Array.from(((n=e.element)==null?void 0:n.querySelectorAll("canvas"))??[])}function Tn(e){for(const n of fs(e)){const s=n.getContext("webgl2");if(s)return s}return null}function Yt(e){var n;(n=e==null?void 0:e.getExtension("WEBGL_lose_context"))==null||n.loseContext()}function Pr(){const e=document.createElement("canvas").getContext("webgl2");return e?(Yt(e),!0):!1}function Lr(e,n){let s=null,r=!1;const a=()=>{if(r||!jn)return;const h=new Vs.CanvasAddon;try{e.loadAddon(h),s={kind:"canvas",addon:h}}catch(f){jn=!1,console.warn("[terminal-renderer] canvas renderer unavailable, using dom renderer:",f),h.dispose()}},i=()=>{if(!s)return;const{kind:h,addon:f}=s;s=null;const p=h==="webgl"?Tn(e):null;f.dispose(),h==="webgl"&&(gt--,Yt(p))},l=()=>{if(xt===void 0&&(xt=Pr()),!xt||gt>=Dr)return!1;let h=null;try{return h=new Ks.WebglAddon,h.onContextLoss(()=>{i(),a()}),e.loadAddon(h),gt++,s={kind:"webgl",addon:h},!0}catch(f){xt=!1,console.warn("[terminal-renderer] webgl renderer unavailable, using canvas from now on:",f),h==null||h.dispose();for(const p of fs(e))p.remove();return!1}},c=()=>{r||s||l()||a()},m=typeof IntersectionObserver=="function"?new IntersectionObserver(h=>{if(r)return;const f=h[h.length-1];f!=null&&f.isIntersecting?c():i()}):null;return m?m.observe(n):c(),{get kind(){return(s==null?void 0:s.kind)??"dom"},dispose(){if(r)return;r=!0,m==null||m.disconnect();const h=s;s=null;const f=(h==null?void 0:h.kind)==="webgl"?Tn(e):null;try{e.dispose()}catch(p){console.warn("[terminal-renderer] dispose failed:",p)}(h==null?void 0:h.kind)==="webgl"&&(gt--,Yt(f))}}}const Er=[{key:"up",path:"M12 5l-6 6m6-6l6 6m-6-6v14"},{key:"down",path:"M12 19l6-6m-6 6l-6-6m6 6V5"},{key:"left",path:"M5 12l6-6m-6 6l6 6m-6-6h14"},{key:"right",path:"M19 12l-6-6m6 6l-6 6m6-6H5"}],bt=Object.fromEntries(Er.map(e=>[e.key,e]));function vt({arrow:e,ariaLabel:n,onPress:s}){return t.jsx("button",{type:"button","aria-label":n,"data-arrow":e.key,onMouseDown:r=>r.preventDefault(),onClick:()=>s(e.key),className:"flex h-8 w-8 items-center justify-center rounded border border-hairline bg-surface text-og-700 transition-colors hover:bg-og-50 hover:text-og-1000 active:bg-og-200",children:t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:t.jsx("path",{d:e.path})})})}function $r({onKey:e,onEscape:n,className:s}){const r=H();return t.jsxs("div",{role:"group","aria-label":r.terminal.keyPadAriaLabel,className:s??"flex flex-none items-center justify-center gap-1 border-t border-hairline bg-page px-3 py-2",children:[n&&t.jsx("button",{type:"button","aria-label":r.terminal.escKeyAriaLabel,"data-key":"escape",onMouseDown:a=>a.preventDefault(),onClick:n,className:"mr-2 flex h-8 items-center justify-center rounded border border-hairline bg-surface px-2.5 font-mono text-xs text-og-700 transition-colors hover:bg-og-50 hover:text-og-1000 active:bg-og-200",children:"ESC"}),t.jsx(vt,{arrow:bt.left,ariaLabel:r.terminal.arrowAriaLabel(r.terminal.arrowLabel.left),onPress:e}),t.jsx(vt,{arrow:bt.up,ariaLabel:r.terminal.arrowAriaLabel(r.terminal.arrowLabel.up),onPress:e}),t.jsx(vt,{arrow:bt.down,ariaLabel:r.terminal.arrowAriaLabel(r.terminal.arrowLabel.down),onPress:e}),t.jsx(vt,{arrow:bt.right,ariaLabel:r.terminal.arrowAriaLabel(r.terminal.arrowLabel.right),onPress:e})]})}const Ir=Math.floor(Pt/1024/1024);function Br({agentId:e,className:n}){const s=H(),r=o.useRef(null),[a,i]=o.useState(!1),{show:l}=je(),c=async m=>{var f;const h=(f=m.target.files)==null?void 0:f[0];if(m.target.value="",!!h){if(h.size>Pt){l({kind:"error",title:s.createTask.imageTooLargeToastTitle,body:s.imageUpload.tooLargeBody(Ir)});return}i(!0);try{await M.agents.uploadImage(e,h),l({kind:"success",title:s.imageUpload.insertedTitle,body:s.imageUpload.insertedBody})}catch(p){const u=p instanceof ze||p instanceof Error?p.message:String(p);l({kind:"error",title:s.imageUpload.uploadFailedTitle,body:u})}finally{i(!1)}}};return t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button","aria-label":s.imageUpload.uploadAriaLabel,disabled:a,onMouseDown:m=>m.preventDefault(),onClick:()=>{var m;return(m=r.current)==null?void 0:m.click()},className:n??"flex h-8 w-8 items-center justify-center rounded border border-hairline bg-surface text-og-700 transition-colors hover:bg-og-50 hover:text-og-1000 active:bg-og-200 disabled:cursor-not-allowed disabled:opacity-50",children:t.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[t.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),t.jsx("circle",{cx:"9",cy:"9",r:"2"}),t.jsx("path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"})]})}),t.jsx("input",{ref:r,type:"file",accept:"image/*",className:"hidden",onChange:c})]})}const Fr={up:"A",down:"B",right:"C",left:"D"};function Mr(e,n){return(n?"\x1BO":"\x1B[")+Fr[e]}const Nn=18,Or=250,_r=256*1024,Sn="#fdfdfd",Hr=4.5,qr='ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',Ur={background:Sn,foreground:"#474c55",cursor:"#1348dc",cursorAccent:Sn,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"},Gr=/\x1b\[(?:\?[\d;]*c|>[\d;]*c|\??\d+;\d+R|\d+n)/g;function Wr(e){return e.replace(Gr,"")}const zr=1024*1024;function Kr(e){const n=e.indexOf(";");if(n===-1)return null;const s=e.slice(n+1);if(s.length===0||s==="?"||s.length>zr)return null;try{const r=atob(s),a=new Uint8Array(r.length);for(let i=0;i<r.length;i++)a[i]=r.charCodeAt(i);return new TextDecoder().decode(a)}catch{return null}}function Xe({agentId:e,mode:n,interactive:s=!1,maxLines:r,className:a,autoFocus:i=!0,deferFullUntilFocus:l=!1,arrowKeys:c=!1}){const m=H(),h=o.useRef(null),f=o.useRef(null),p=o.useRef(null),u=o.useRef(null),d=o.useRef(!1),x=o.useRef(""),b=o.useRef([]),y=o.useRef(0),T=o.useRef(null),C=o.useRef(null),A=o.useRef(null),w=o.useRef(Promise.resolve()),k=o.useRef(0),[j,v]=o.useState(null),[D,P]=o.useState(!1),I=`${e}\0${n}\0${l?"1":"0"}`,[O,J]=o.useState({key:I,active:!1}),E=O.key===I&&O.active,W=n==="full"&&l,re=W&&!E?"preview":n,te=s&&re==="full",X=(S,U)=>U.length===0?Promise.resolve():new Promise(_=>{try{S.write(U,()=>_())}catch(se){console.warn("[pane-terminal] write failed:",se),_()}}),V=re==="preview",ae=()=>{var R;if(!V)return;const S=h.current,U=f.current;if(!S||!U||S.clientHeight<=0)return;const _=((R=S.querySelector(".xterm-screen"))==null?void 0:R.getBoundingClientRect().height)??0,se=_>0&&U.rows>0?_/U.rows:Nn,B=(U.buffer.active.cursorY+1)*se;S.scrollTop=Math.max(0,B-S.clientHeight)},z=()=>{if(!V||A.current!==null)return;let S=!1;const U=requestAnimationFrame(()=>{S=!0,A.current=null,ae()});S||(A.current=U)},le=(S,U)=>{w.current=w.current.then(async()=>{const _=f.current;if(!(!_||U!==k.current))try{await S(_),te&&_.scrollToBottom(),z()}catch(se){console.warn("[pane-terminal] terminal task failed:",se)}}).catch(_=>{console.warn("[pane-terminal] write chain failed:",_)})},ne=(S,U)=>{le(_=>X(_,S),U)},ge=()=>{T.current!==null&&(cancelAnimationFrame(T.current),T.current=null),C.current!==null&&(clearTimeout(C.current),C.current=null)},q=()=>{ge(),b.current=[],y.current=0},ie=()=>{ge();const S=b.current;S.length!==0&&(b.current=[],y.current=0,ne(S.join(""),k.current))},me=S=>{if(S.length!==0){if(b.current.push(S),y.current+=S.length,y.current>=_r){ie();return}T.current===null&&(T.current=requestAnimationFrame(ie)),C.current===null&&(C.current=setTimeout(ie,Or))}},{send:xe,resize:ye,reconnect:N}=Ar({agentId:e,mode:re,onSnapshot:({cols:S,rows:U,data:_})=>{if(v(null),P(!1),!!f.current)try{const B=k.current+1;k.current=B,q(),le(async R=>{var $;R.reset(),te?(($=u.current)==null||$.call(u),await X(R,_)):(S>0&&U>0&&R.resize(S,U),await X(R,_))},B)}catch(B){console.warn("[pane-terminal] snapshot write failed:",B)}},onData:S=>{me(S)},onError:S=>{P(S.code==="session_not_found"),v(S.code==="session_not_found"?null:`${S.code}: ${S.message}`)},onSessionGone:()=>P(!0)});o.useEffect(()=>{v(null),P(!1)},[e,re]),o.useEffect(()=>{x.current=""},[I]),o.useEffect(()=>{if(re!=="full")return;const S=x.current;S.length!==0&&(x.current="",xe(S))},[xe,re]);const we=o.useCallback(()=>{!s||!W||E||(d.current=!0,J({key:I,active:!0}))},[I,E,s,W]),pe=o.useCallback(S=>{const U=Wr(S);if(U.length!==0){if(W&&(!E||x.current.length>0)){x.current+=U,we();return}xe(U)}},[we,E,xe,W]);o.useEffect(()=>{const S=h.current;if(!S)return;let U=!1;const _=new Qs.Terminal({cursorBlink:s,disableStdin:!s,theme:Ur,minimumContrastRatio:Hr,fontFamily:qr,fontSize:13,lineHeight:1.4,scrollback:re==="full"?5e3:1e3}),se=new Ys.FitAddon;_.loadAddon(se),_.open(S);const B=Lr(_,S);f.current=_,p.current=se;const R=V?_.onRender(()=>z()):null;if(s&&(i||d.current)){d.current=!1;try{_.focus()}catch{}}s&&(_.onData(pe),re==="full"&&_.parser.registerOscHandler(52,$e=>{var Te;const Ce=Kr($e);return Ce!==null&&((Te=navigator.clipboard)==null||Te.writeText(Ce).catch(()=>{})),!0}));const $=()=>S.clientWidth>0&&S.clientHeight>0,Z=($e=!1)=>{if(!$())return!1;const Ce=_.cols,Te=_.rows;try{se.fit()}catch{return!1}return te&&_.scrollToBottom(),_.cols>0&&_.rows>0&&($e||_.cols!==Ce||_.rows!==Te)&&ye(_.cols,_.rows),!0};u.current=te?()=>Z(!0):null;let K=null,ee=null,be=null,Ve=0;const Me=()=>{K||(K=new ResizeObserver(()=>{ee&&clearTimeout(ee),ee=setTimeout(()=>{ee=null,te?Z():V&&z()},100)}),K.observe(S))},Ee=()=>{be=requestAnimationFrame(()=>{if(be=null,!U){if(!te){V&&(Me(),z());return}if(Z(!0)){Me();return}if(Ve++<5){Ee();return}Me()}})};return Ee(),()=>{U=!0,be!==null&&cancelAnimationFrame(be),T.current!==null&&(cancelAnimationFrame(T.current),T.current=null),C.current!==null&&(clearTimeout(C.current),C.current=null),A.current!==null&&(cancelAnimationFrame(A.current),A.current=null),k.current++,b.current=[],y.current=0,w.current=Promise.resolve(),ee&&clearTimeout(ee),K==null||K.disconnect(),R==null||R.dispose(),f.current=null,p.current=null,u.current=null,B.dispose()}},[e,i,te,pe,s,re,ye]);const L=()=>{var S;if(s){we();try{(S=f.current)==null||S.focus()}catch{}}};o.useEffect(()=>{if(s)return;const S=h.current;if(!S)return;const U=_=>{_.stopPropagation()};return S.addEventListener("wheel",U,{capture:!0,passive:!0}),()=>S.removeEventListener("wheel",U,{capture:!0})},[s]);const G=r&&r>0?{maxHeight:`${r*Nn}px`}:void 0;return t.jsxs("div",{className:a??"flex flex-col h-full w-full min-h-0 bg-term",children:[(j||D)&&t.jsxs("div",{role:"alert",className:"border-b border-accent/25 bg-accent-soft px-3 py-1 text-xs text-accent",children:[t.jsx("div",{children:D?m.terminal.sessionEnded:j}),D&&t.jsx("div",{children:m.terminal.sessionRecovery}),t.jsx("button",{type:"button",className:"btn-secondary mt-1",onKeyDown:S=>S.stopPropagation(),onClick:S=>{S.stopPropagation(),N()},children:m.terminal.reconnect})]}),t.jsx("div",{className:"flex flex-1 min-h-0 px-2 py-1.5",style:G,children:t.jsx("div",{ref:h,className:"flex-1 min-h-0 overflow-hidden",onMouseDown:L})}),s&&c&&t.jsxs("div",{className:"grid grid-cols-[1fr_auto_1fr] gap-2 flex-none items-center border-t border-hairline bg-page px-3 py-2",children:[t.jsx("div",{className:"flex items-center",children:t.jsx(Br,{agentId:e})}),t.jsx($r,{className:"flex items-center justify-center gap-1",onKey:S=>{var _,se;const U=!!((se=(_=f.current)==null?void 0:_.modes)!=null&&se.applicationCursorKeysMode);pe(Mr(S,U))},onEscape:()=>pe("\x1B")})]})]})}function ps(e,n){const s=typeof n=="string"?{status:n}:n,{status:r,phase:a}=s;if(r==="pending"&&s.preferredAgentId==="")return e.statusContext.pendingUnassigned;if(r==="in_progress"){if(a==="spec")return e.statusContext.inProgressSpec;if(a==="code")return e.statusContext.inProgressCode}if(r==="review"){if(a==="spec")return e.statusContext.reviewSpec;if(a==="code")return e.statusContext.reviewCode}if(r==="fixing"){if(a==="spec")return e.statusContext.fixingSpec;if(a==="code")return e.statusContext.fixingCode}if(r==="max_rounds"){if(a==="spec")return e.statusContext.maxRoundsSpec;if(a==="code")return e.statusContext.maxRoundsCode}return e.status[r]??r}function Vr(e){return ps(ns(),e)}function cn(e,n){return e.reason==="bootstrap-marker-clear-failed"||e.reason==="dispatch-failed:ack_unknown"&&n!=="review"?e.recommendedActions.filter(s=>s!=="advance"):e.recommendedActions}function gs(e,n,s){const{reason:r}=n,a=cn(n,s),l={"dirty-workdir":{title:e.taskDetail.attentionDirtyWorkdirTitle,guidance:e.taskDetail.attentionDirtyWorkdirGuidance},"checkout-preparation-failed":{title:e.taskDetail.attentionCheckoutTitle,guidance:e.taskDetail.attentionCheckoutGuidance},"restart-redispatch-failed":{title:e.taskDetail.attentionReplayTitle,guidance:e.taskDetail.attentionReplayGuidance},"bootstrap-marker-clear-failed":{title:e.taskDetail.attentionBootstrapDeliveredTitle,guidance:e.taskDetail.attentionBootstrapDeliveredGuidance},"dispatch-failed:ack_unknown":{title:e.taskDetail.attentionDeliveryUnknownTitle,guidance:e.taskDetail.attentionDeliveryUnknownGuidance}}[r],c=(l==null?void 0:l.title)??(/confirm-merge|post-approve|merge/.test(r)?e.taskDetail.attentionMergeTitle:/review|verdict/.test(r)?e.taskDetail.attentionReviewTitle:/runtime|session|recovery|tmux|repl/.test(r)?e.taskDetail.attentionAgentTitle:/dispatch|delivery|pr-created/.test(r)?e.taskDetail.attentionHandoffTitle:e.taskDetail.attentionDefaultTitle),m=a.includes("verdict")?e.taskDetail.attentionVerdictGuidance:a.includes("advance")?e.taskDetail.attentionAdvanceGuidance:a.includes("retry")?e.taskDetail.attentionRetryGuidance:e.taskDetail.attentionCancelGuidance;return{title:c,guidance:l?`${l.guidance} ${m}`:m,...l?{expandDetails:!0}:{}}}const Qr={pending:"pill",in_progress:"pill pill-live",review:"pill pill-review",fixing:"pill pill-warn","spec-ready":"pill pill-warn",approved:"pill pill-live","merge-ready":"pill pill-warn",merged:"pill pill-live",done:"pill pill-live",failed:"pill pill-danger",max_rounds:"pill pill-warn",cancelled:"pill"};function dn({task:e,className:n=""}){const s=H(),r=ps(s,e);return t.jsx("span",{className:`${Qr[e.status]??"pill"} ${n}`,title:r,"data-status":e.status,children:r})}function un(e){if(!e)return"";const n=e.match(/^task-(\d+)$/);return n?n[1]:e}function _t(e,n=!0){if(e==null)return"";const s=String(e).trim();if(!s)return"";const r=new Date(s.replace(/^(\d{4}-\d{2}-\d{2}) /,"$1T"));if(Number.isNaN(r.getTime()))return s;const a=c=>String(c).padStart(2,"0"),i=`${r.getFullYear()}-${a(r.getMonth()+1)}-${a(r.getDate())}`,l=`${a(r.getHours())}:${a(r.getMinutes())}`;return n?`${i} ${l}:${a(r.getSeconds())}`:`${i} ${l}`}function Pe(e,n){return`/project/${encodeURIComponent(e)}/task/${encodeURIComponent(n)}`}function Yr(e){return e>=1048576?`${(e/1048576).toFixed(1)} MiB`:e>=1024?`${(e/1024).toFixed(1)} KiB`:`${e} B`}function Jr({taskId:e,agentId:n,onPendingChange:s}){var v;const r=H(),[a,i]=o.useState(null),[l,c]=o.useState(null),[m,h]=o.useState(!0),[f,p]=o.useState(!1),[u,d]=o.useState(""),[x,b]=o.useState(""),y=o.useRef(!1),T=o.useRef(0);o.useEffect(()=>(s==null||s(!!a),()=>s==null?void 0:s(!1)),[a,s]);const C=o.useCallback(async()=>{const D=++T.current;h(!0),b("");try{const P=await M.tasks.untrackedFiles(e,n);D===T.current&&i(P)}catch(P){D===T.current&&(i(null),P instanceof ze&&P.status===409?b(P.message):d(P instanceof Error?P.message:String(P)))}finally{D===T.current&&h(!1)}},[e,n]);o.useEffect(()=>(i(null),c(null),d(""),C(),()=>{T.current+=1}),[C]);const A=async(D,P)=>{if(!y.current){y.current=!0,p(!0),d(""),c(null);try{await M.tasks.resolveUntrackedFiles(e,n,{action:D,token:P.token}),T.current+=1,i(null)}catch(I){d(I instanceof Error?I.message:String(I)),await C()}finally{y.current=!1,p(!1)}}},w=D=>t.jsx("ul",{className:"my-2 max-h-48 overflow-auto rounded bg-og-25 p-2 font-mono text-xs",children:D.map(P=>t.jsxs("li",{className:"flex justify-between gap-3",children:[t.jsx("span",{className:"whitespace-pre-wrap break-all",children:P.path}),t.jsx("span",{className:"shrink-0 text-og-500",children:Yr(P.size)})]},P.pathBase64??P.path))}),k=!!(a!=null&&a.files.length),j=!!((v=a==null?void 0:a.conflicts)!=null&&v.length);return!m&&!f&&!u&&!x&&!a?null:t.jsxs("section",{className:"mb-2 rounded-md border border-accent/25 bg-accent-soft/60 p-3 text-sm","aria-label":r.untrackedFiles.heading,children:[(m||f)&&t.jsx("p",{role:"status",children:f?r.untrackedFiles.working:r.untrackedFiles.loading}),x&&t.jsxs("p",{role:"status",children:[r.untrackedFiles.unavailable," ",x]}),u&&t.jsx("p",{role:"alert",className:"whitespace-pre-wrap break-words text-red-600",children:u}),a&&t.jsxs(t.Fragment,{children:[k&&t.jsxs(t.Fragment,{children:[t.jsx("h3",{className:"font-semibold",children:r.untrackedFiles.title(a.files.length)}),t.jsx("p",{children:r.untrackedFiles.guidance})]}),!k&&!j&&t.jsx("p",{children:r.untrackedFiles.readyToContinue}),t.jsxs("dl",{className:"mt-2 grid grid-cols-[auto_1fr] gap-x-2 text-xs",children:[t.jsx("dt",{children:r.untrackedFiles.agent}),t.jsx("dd",{children:a.agentId}),t.jsx("dt",{children:r.untrackedFiles.host}),t.jsx("dd",{children:a.host}),t.jsx("dt",{children:r.untrackedFiles.workdir}),t.jsx("dd",{className:"break-all",children:a.workdir})]}),k&&w(a.files),j&&t.jsxs(t.Fragment,{children:[t.jsx("p",{children:r.untrackedFiles.conflicts}),w(a.conflicts)]}),a.manualCleanupRequired&&t.jsx("p",{children:r.untrackedFiles.manualCleanup}),a.keepLimitExceeded&&t.jsx("p",{children:r.untrackedFiles.keepLimit}),a.trackedChanges&&t.jsx("p",{children:r.untrackedFiles.trackedChanges}),a.files.some(D=>D.kind==="directory")&&t.jsx("p",{children:r.untrackedFiles.directory}),k&&t.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"btn-primary",disabled:f||m||a.trackedChanges||a.keepLimitExceeded||j,onClick:()=>void A("keep",a),children:r.untrackedFiles.keep}),t.jsx("button",{type:"button",className:"btn-secondary",disabled:f||m||a.trackedChanges||a.manualCleanupRequired||a.files.some(D=>D.kind==="directory"),onClick:()=>c(a),children:r.untrackedFiles.discard})]}),!k&&!j&&t.jsx("button",{type:"button",className:"btn-primary mt-2",disabled:f||m||a.trackedChanges,onClick:()=>void A("continue",a),children:r.untrackedFiles.continue})]}),t.jsx("button",{type:"button",className:"btn-secondary mt-2",disabled:f||m,onClick:()=>{d(""),C()},children:r.untrackedFiles.refresh}),t.jsxs(Re,{open:l!==null,title:r.untrackedFiles.confirmTitle,onClose:()=>c(null),size:"sm",footer:t.jsxs("div",{className:"flex justify-end gap-2",children:[t.jsx("button",{type:"button",className:"btn-secondary",onClick:()=>c(null),children:r.common.cancel}),t.jsx("button",{type:"button",className:"btn-danger",disabled:f,onClick:()=>{l&&A("discard",l)},children:r.untrackedFiles.discard})]}),children:[t.jsx("p",{children:r.untrackedFiles.confirmBody}),l&&w(l.files)]})]})}const Ht={unknown:"pill pill-idle",idle:"pill pill-idle",pending:"pill pill-warn",working:"pill pill-live",waiting:"pill pill-review",error:"pill pill-warn"};function Xr(e,n,s,r=s!==void 0){const a=s!==void 0?tn.has(s.status):r;return e==="greeting_failed"?"restart-runtime":e==="agent_dialog_pending"?"terminal":e==="bootstrap-marker-clear-failed"?(s==null?void 0:s.status)==="in_progress"||!s&&r?"task":"resume":e==="restart-redispatch-failed"?(s?["in_progress","fixing","approved"].includes(s.status):r)?"task":"resume":a&&(e==="agent_dialog_resolved_runtime"||e!=null&&e.startsWith("signal-arm-failed"))?"task":e==="dispatch-failed:ack_unknown"&&n==="dev"&&s&&["spec-ready","review","merge-ready","max_rounds"].includes(s.status)?"resume":a&&(e==="dispatch-failed:ack_unknown"||e==="dev-wait-gate-failed-after-qa-started")||a&&(s==null?void 0:s.status)!=="spec-ready"&&(s==null?void 0:s.status)!=="max_rounds"&&(e==="dirty-workdir"||e==="checkout-preparation-failed")&&n==="dev"?"task":"resume"}function xs(e){var n;return!!((n=e.binding)!=null&&n.creationToken)&&!e.binding.paneId&&e.binding.status!=="awaiting_human"&&e.reason!=="PENDING_HUMAN"}function Zr(e,n){var s,r,a;return e.tmuxSessionStatus==="unreachable"?{kind:"alert",label:n.sessionStatus.unreachable,cls:"pill pill-danger"}:xs(e)?{kind:"runtime",label:n.bootstrappingBadge,cls:"pill pill-review"}:Gn(e)?{kind:"runtime",label:n.dispatchingBadge,cls:"pill pill-review",title:n.dispatchingTitle}:e.tmuxSessionStatus==="absent"?{kind:"alert",label:n.sessionStatus.absent,cls:"pill pill-warn"}:e.runtimeStatus==="error"?{kind:"alert",label:n.runtimeStatus.error,cls:Ht.error}:((s=e.binding)==null?void 0:s.status)==="awaiting_human"?{kind:"alert",label:n.heldBadge,cls:"pill pill-warn",title:e.binding.awaitingReason??n.heldDefaultReason}:(a=(r=e.binding)==null?void 0:r.needInput)!=null&&a.at?{kind:"alert",label:n.needInputBadge,cls:"pill pill-warn",title:n.needInputTitle(new Date(e.binding.needInput.at).toLocaleString())}:e.runtimeStatus==="pending"?{kind:"alert",label:n.runtimeStatus.pending,cls:Ht.pending}:{kind:"runtime",label:n.runtimeStatus[e.runtimeStatus],cls:Ht[e.runtimeStatus]}}function ea(e,n){const s=Zr(e,n);if(!e.stale)return{...s,stale:!1};const r=n.staleTitle(e.observedAt?new Date(e.observedAt).toLocaleString():void 0);return{...s,stale:!0,title:s.title?`${s.title} · ${r}`:r}}function bs({agent:e,projectId:n,role:s,runtime:r,model:a,onDeleted:i,pendingRestart:l=!1,terminalLoading:c=!1,showTaskBinding:m=!0,terminalMode:h="activity-preview",active:f,onActivate:p,task:u}){var Ee,$e,Ce,Te,it,ot,lt,Qe,ct;const d=H(),[x,b]=o.useState(!1),[y,T]=o.useState(null),{show:C}=je(),A=ln(),{compact:w,clear:k,remove:j,compacting:v,clearing:D,deleting:P,deleteError:I,busy:O}=ls(n,[e.id],i),[J,E]=o.useState(!1),[W,re]=o.useState(!1),[te,X]=o.useState(!1),[V,ae]=o.useState(!1),z=(Ee=e.binding)==null?void 0:Ee.taskId,le=(u==null?void 0:u.id)===z?u:void 0,ne=(($e=e.binding)==null?void 0:$e.status)==="awaiting_human",ge=(Te=(Ce=e.binding)==null?void 0:Ce.needInput)==null?void 0:Te.at,q=ne&&((it=e.binding)==null?void 0:it.awaitingPhase)==="greeting_failed",ie=Xr((ot=e.binding)==null?void 0:ot.awaitingPhase,s,le,!!z),me=xs(e),xe=!l&&!c&&!e.stale&&!ne&&e.tmuxSessionStatus==="absent"&&!((lt=e.binding)!=null&<.creationToken)&&!z,ye=me&&e.tmuxSessionStatus!=="present",N=ea(e,d.agents),we=h==="activity-preview"&&!ye&&(e.runtimeStatus==="working"||e.runtimeStatus==="pending"),pe=h==="embedded-full",L=pe&&typeof p=="function",G=L&&f===!0,S=c||l||ye,U=c?d.agents.agentStatusLoading:l?d.agents.terminalNeedsRestart:d.agents.bootstrappingTerminalDisabled,_=zn(r,a),se=async()=>{b(!0),T(null);try{await M.agents.stop(e.id)}catch(oe){T(oe instanceof Error?oe.message:String(oe))}finally{b(!1)}},B=async()=>{X(!0);try{(await M.projects.bootstrap(n)).ok?C({kind:"success",title:d.agents.retryBootstrapSucceededTitle,body:d.agents.retryBootstrapSucceededBody}):C({kind:"warn",title:d.agents.retryBootstrapStillFailingTitle,body:d.agents.retryBootstrapStillFailingBody})}catch(oe){C({kind:"error",title:d.agents.retryBootstrapFailedTitle,body:oe instanceof Error?oe.message:String(oe)})}finally{X(!1)}},R=async()=>{ae(!0);try{const oe=await M.projects.retryAgent(n,e.id);C({kind:oe.runtimeStatus==="pending"?"warn":"success",title:oe.runtimeStatus==="pending"?d.agents.retrySessionPending:d.agents.retrySessionReady})}catch(oe){C({kind:"error",title:d.agents.retrySessionFailed,body:oe instanceof Error?oe.message:String(oe)})}finally{ae(!1)}},$=async()=>{if(await A({title:d.agents.resumeConfirmTitle(e.id),body:q?d.agents.resumeGreetingBody:d.agents.resumeDefaultBody,confirmLabel:d.agents.resume})){E(!0);try{if(q){e.tmuxSessionStatus==="present"?await M.projects.restartRepl(n,e.id):await M.projects.retryAgent(n,e.id),C({kind:"success",title:d.agents.regreetingStartedTitle(e.id),body:d.agents.regreetingStartedBody});return}const Oe=await M.projects.resumeAgent(n,e.id);C({kind:"success",title:d.agents.resumedTitle(e.id),body:Oe.releasedBinding?d.agents.resumedReleasedBody:d.agents.resumedKeptBody})}catch(Oe){C({kind:"error",title:d.agents.resumeFailedTitle,body:Oe instanceof Error?Oe.message:String(Oe)})}finally{E(!1)}}},Z=L&&!S&&!G,K=["card relative flex h-full min-w-0 flex-col overflow-visible p-4",G?"ring-2 ring-accent":""].filter(Boolean).join(" "),ee="mb-3 flex items-start justify-between gap-2",be=["mb-2 mt-3 h-80 min-h-0 overflow-hidden border border-hairline bg-surface",Z?"cursor-pointer":""].filter(Boolean).join(" "),Ve=Z?()=>p==null?void 0:p():void 0,Me=Z?oe=>{(oe.key==="Enter"||oe.key===" ")&&(oe.preventDefault(),p==null||p())}:void 0;return t.jsxs("div",{className:K,"data-agent-card":L?e.id:void 0,children:[t.jsxs("div",{className:ee,children:[t.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[t.jsx("span",{className:"shrink-0 font-mono text-xs font-medium tracking-[0.05em] text-og-500",children:s==="qa"?"QA":"Dev"}),t.jsx("span",{className:"min-w-0 truncate whitespace-nowrap font-display text-xs text-og-1000",title:Kn(e.id,r,a),children:e.id}),_&&t.jsxs("span",{className:"hidden shrink-0 whitespace-nowrap text-xs text-og-400 sm:inline",title:_,children:["(",_,")"]})]}),t.jsx("span",{className:N.stale?`${N.cls} pill--stale shrink-0`:`${N.cls} shrink-0`,title:N.title,children:N.label}),N.stale&&t.jsx("span",{className:"sr-only",children:N.title})]}),ye&&t.jsx("div",{className:"mb-2 rounded-md border border-accent-soft bg-accent-soft/40 px-2.5 py-2 text-xs text-accent",children:d.agents.bootstrappingNotice}),ne&&t.jsxs("div",{className:"mb-2 space-y-1 rounded-md border border-accent/25 bg-accent-soft/60 px-2.5 py-2 text-xs text-accent",children:[t.jsxs("div",{children:[t.jsx("span",{className:"font-mono",children:(Qe=e.binding)==null?void 0:Qe.awaitingPhase}),((ct=e.binding)==null?void 0:ct.awaitingReason)&&t.jsxs("span",{children:[" · ",e.binding.awaitingReason]})]}),!W&&t.jsx("div",{className:"text-og-700",children:d.agents.holdRecovery[ie]})]}),ne&&z&&t.jsx(Jr,{taskId:z,agentId:e.id,onPendingChange:re},`${z}:${e.id}`),!me&&e.runtimeStatus==="pending"&&t.jsxs("div",{className:"mb-2 space-y-1 rounded-md border border-accent/25 bg-accent-soft/60 px-2.5 py-2 text-xs text-accent",children:[t.jsx("div",{className:"font-medium",children:d.agents.awaitingHumanIntervention}),t.jsxs("div",{children:[d.agents.openTerminalPrefix,t.jsx(Se,{to:`/terminal/${e.id}`,className:"text-accent hover:text-accent-hover underline",children:d.agents.terminal}),d.agents.openTerminalSuffix]})]}),ge&&t.jsxs("div",{className:"mb-2 space-y-1 rounded-md border border-accent/25 bg-accent-soft/60 px-2.5 py-2 text-xs text-accent",children:[t.jsx("div",{className:"font-medium",children:d.agents.needInputNoticeTitle}),t.jsxs("div",{children:[d.agents.needInputPrefix,t.jsx(Se,{to:`/terminal/${e.id}`,className:"text-accent hover:text-accent-hover underline",children:d.agents.terminal}),d.agents.needInputSuffix]})]}),e.latestError&&t.jsxs("div",{className:"mb-2 space-y-1 rounded-md border border-accent/25 bg-accent-soft px-2.5 py-2 text-xs text-accent",children:[t.jsx("div",{className:"break-words font-medium",children:e.latestError.message}),t.jsxs("div",{className:"font-mono text-xs opacity-80",children:[e.latestError.reason," · ",e.latestError.occurredAt]})]}),e.latestBootstrapError&&t.jsxs("div",{className:"mb-2 space-y-1 rounded-md border border-accent/25 bg-accent-soft px-2.5 py-2 text-xs text-accent",children:[t.jsx("div",{className:"break-words font-medium",children:e.latestBootstrapError.message}),e.latestBootstrapError.recommendation&&t.jsx("div",{className:"break-words",children:e.latestBootstrapError.recommendation}),t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsxs("div",{className:"truncate font-mono text-xs opacity-80",children:[e.latestBootstrapError.reason," · ",e.latestBootstrapError.occurredAt]}),t.jsx("button",{type:"button",onClick:B,disabled:te,className:"btn-primary shrink-0",children:te?d.common.retrying:d.agents.retryBootstrap})]})]}),m&&z&&t.jsxs("div",{className:"mb-2 text-xs text-og-500",children:[d.agents.taskLabel,t.jsx("span",{className:"font-mono text-og-700",children:z})]}),we&&t.jsx("div",{className:"mb-2 overflow-hidden border border-hairline bg-surface",children:t.jsx(Xe,{agentId:e.id,mode:"preview",maxLines:6,interactive:!1})}),pe&&t.jsx("div",{className:be,role:Z?"button":void 0,tabIndex:Z?0:void 0,"aria-label":Z?d.agents.activateTerminal(e.id):void 0,onClick:Ve,onKeyDown:Me,children:S?t.jsx("div",{className:"flex h-full items-center justify-center px-3 text-sm text-og-500",children:U}):L?G?t.jsx(Xe,{agentId:e.id,mode:"full",interactive:!0,autoFocus:!0}):t.jsx(Xe,{agentId:e.id,mode:"preview",interactive:!1}):t.jsx(Xe,{agentId:e.id,mode:"full",interactive:!0,autoFocus:!1,deferFullUntilFocus:!0})}),l&&t.jsx("div",{className:"mb-2 rounded-md border border-accent/25 bg-accent-soft/60 px-2.5 py-1.5 text-xs text-accent",children:d.agents.pendingRestartNotice}),t.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[t.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2 overflow-x-auto scrollbar-none",children:[xe&&t.jsx("button",{type:"button",className:"btn-primary shrink-0",disabled:V,onClick:R,children:V?d.common.retrying:d.agents.retrySession}),S?t.jsx("span",{className:"shrink-0 cursor-not-allowed text-sm text-og-400",title:U,children:d.agents.terminal}):t.jsx(Se,{to:`/terminal/${e.id}`,className:"btn-secondary shrink-0",children:d.agents.terminal}),!l&&e.runtimeStatus==="working"&&t.jsx("button",{onClick:se,disabled:x,className:"btn-ghost shrink-0",children:x?d.agents.stopping:d.agents.stop}),ne&&!W&&(ie==="resume"||ie==="restart-runtime")&&t.jsx("button",{type:"button",onClick:$,disabled:J,title:q?d.agents.resumeGreetingButtonTitle:d.agents.resumeDefaultButtonTitle,className:"btn-primary shrink-0",children:J?d.agents.resuming:ie==="restart-runtime"?d.agents.restartRuntime:d.agents.resume}),ne&&ie==="terminal"&&t.jsx(Se,{to:`/terminal/${e.id}`,className:"btn-primary shrink-0",children:d.agents.openTerminalAction}),ne&&ie==="task"&&z&&t.jsx(Se,{to:Pe(n,z),className:"btn-primary shrink-0",children:d.agents.openTaskActions}),ne&&ie==="delete-agent"&&t.jsx("button",{type:"button",onClick:()=>void j(),disabled:P,className:"btn-primary shrink-0",children:P?d.common.deleting:d.agents.deleteToRecover})]}),t.jsx(Dt,{ariaLabel:d.agents.actionsMenu(e.id),className:"shrink-0",placement:"up",autoFocusFirstItem:!0,disabled:P,children:oe=>t.jsxs(t.Fragment,{children:[t.jsx(ke,{onClick:()=>{oe(),w()},disabled:O,title:d.agents.compactMenuItemTitle,children:v?d.agents.compacting:d.agents.compact}),t.jsx(ke,{onClick:()=>{oe(),k()},disabled:O,title:d.agents.clearMenuItemTitle,children:D?d.agents.clearing:d.agents.clear}),t.jsx(ke,{onClick:()=>{oe(),j()},disabled:O,children:P?d.common.deleting:d.common.delete})]})})]}),y&&t.jsx("div",{className:"mt-1.5 break-words text-xs text-accent",children:y}),I&&t.jsx("div",{className:"mt-1.5 break-words text-xs text-accent",children:I})]})}const qt="baxian:terminal-activated";function vs({coordinateAcrossInstances:e=!0}={}){const n=o.useId(),[s,r]=o.useState(null);o.useEffect(()=>{if(s===null)return;const i=m=>{m.composedPath().some(p=>p instanceof Element&&p.hasAttribute("data-agent-card"))||r(null)},l=m=>{if(m.key!=="Escape")return;const h=document.activeElement;h instanceof Element&&h.closest("[data-agent-card]")||r(null)},c=m=>{const h=m.detail;(h==null?void 0:h.ownerId)!==n&&r(null)};return document.addEventListener("click",i),document.addEventListener("keydown",l),e&&document.addEventListener(qt,c),()=>{document.removeEventListener("click",i),document.removeEventListener("keydown",l),e&&document.removeEventListener(qt,c)}},[s,e,n]);const a=o.useCallback(i=>{r(i),e&&document.dispatchEvent(new CustomEvent(qt,{detail:{ownerId:n}}))},[e,n]);return{activeAgentId:s,activateAgentCard:a}}function ys({team:e,projectId:n,agentsById:s,agentsLoaded:r,agentsError:a=!1,tasks:i,onDeleted:l,terminalMode:c="activity-preview"}){const m=H(),h=e.find(E=>E.role==="dev")??e[0],f=i.filter(E=>sa(E,h==null?void 0:h.id)),p=h?i.filter(E=>ra(E,n,h.id)).sort((E,W)=>E.createdAt.localeCompare(W.createdAt)):[],u=e.map(E=>E.id).join(" / "),d=`Agent Team ${u}`,x=Le(),{compact:b,clear:y,remove:T,compacting:C,clearing:A,deleting:w,deleteError:k,busy:j}=ls(n,e.map(E=>E.id),l),v=c==="embedded-full",{activeAgentId:D,activateAgentCard:P}=vs({coordinateAcrossInstances:v}),I=c==="embedded-full"?e.length<=1?"lg:grid-cols-1":e.length===2?"lg:grid-cols-2":e.length===3?"lg:grid-cols-3":"lg:grid-cols-4":"sm:grid-cols-2",O=!!h&&p.length>0,J=f.length===0&&!O;return t.jsxs("div",{role:"group","aria-label":d,className:"min-w-0 rounded-lg border border-og-100 bg-og-25/60 p-3",children:[t.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[t.jsx("span",{className:"shrink-0 font-display text-xs font-semibold uppercase tracking-[0.06em] text-og-500",children:"Team"}),t.jsx("span",{className:"min-w-0 truncate font-mono text-xs text-og-700",title:u,children:u}),t.jsx(Dt,{ariaLabel:m.agents.teamActionsMenu(u),className:"ml-auto shrink-0",autoFocusFirstItem:!0,disabled:w,children:E=>t.jsxs(t.Fragment,{children:[t.jsx(ke,{onClick:()=>{E(),b()},disabled:j,title:m.agents.teamCompactMenuItemTitle,children:C?m.agents.compacting:m.agents.compact}),t.jsx(ke,{onClick:()=>{E(),y()},disabled:j,title:m.agents.teamClearMenuItemTitle,children:A?m.agents.clearing:m.agents.clear}),t.jsx(ke,{onClick:()=>{E(),T()},disabled:j,children:w?m.common.deleting:m.common.delete})]})})]}),k&&t.jsx("div",{className:"mb-2 break-words text-xs text-accent",children:k}),O&&h&&t.jsx(na,{tasks:p,devId:h.id,agentsById:s,label:d}),f.length>0&&t.jsx("div",{className:"card mb-2 max-h-28 overflow-y-auto divide-y divide-hairline",children:f.map(E=>{const W=Fe(E.phase)?E.specReviewRound??0:E.reviewRound;return t.jsxs("button",{type:"button",onClick:()=>x(Pe(E.projectId,E.id)),className:"flex w-full items-center gap-3 px-3 py-2 text-left text-sm transition-colors hover:bg-og-50/60",children:[t.jsxs("div",{className:"min-w-0 flex-1 flex items-center gap-2",children:[t.jsx("span",{className:"shrink-0 font-mono text-xs text-og-500",title:E.id,children:un(E.id)}),t.jsx("span",{className:"truncate text-og-1000",children:E.title})]}),t.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[W>0&&t.jsx("span",{className:"shrink-0 text-xs text-og-500",children:m.agents.round(W)}),t.jsx(dn,{task:E,className:"shrink-0"})]})]},E.id)})}),J&&t.jsx("div",{className:"mb-2 rounded-lg border border-hairline bg-surface px-3 py-2 text-sm text-og-400","aria-label":m.agents.noActiveTaskAriaLabel(d),children:m.agents.noActiveTask}),t.jsx("div",{className:`grid grid-cols-1 ${I} gap-4`,children:e.map(E=>{var X;const W=s.get(E.id),re=W??{id:E.id,projectId:n,runtimeStatus:"unknown",tmuxSessionStatus:"unknown",stale:!0},te=((X=re.binding)==null?void 0:X.taskId)===void 0?void 0:i.find(V=>{var ae;return V.id===((ae=re.binding)==null?void 0:ae.taskId)});return t.jsx(bs,{agent:re,projectId:n,role:E.role,runtime:E.runtime,model:E.model,pendingRestart:r&&!W,terminalLoading:!r&&!W&&!a,onDeleted:l,showTaskBinding:!1,terminalMode:c,task:te,...v?{active:D===E.id,onActivate:()=>P(E.id)}:{}},E.id)})})]})}function ta(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 na({tasks:e,devId:n,agentsById:s,label:r}){const a=H(),{show:i}=je(),l=Le(),[c,m]=o.useState(null),h=async(f,p)=>{m(f);try{await M.tasks.advance(f,{executor:"dev",agentId:p}),i({kind:"success",title:a.agents.taskHandedTo(f,p)})}catch(u){i({kind:"error",title:a.agents.startFailed,body:u instanceof Error?u.message:String(u)})}finally{m(null)}};return t.jsx("div",{role:"group",className:"card mb-2 max-h-28 overflow-y-auto divide-y divide-hairline","aria-label":`${r} claimable tasks for ${n}`,children:e.map(f=>{const p=f.preferredAgentId||n,u=ta(s.get(p)),d=f.preferredAgentId==="",x=c!==null;return t.jsxs("div",{className:"flex items-center gap-3 px-3 py-2 text-sm",children:[t.jsxs("button",{type:"button",onClick:()=>l(Pe(f.projectId,f.id)),className:"min-w-0 flex-1 flex items-center gap-2 text-left transition-colors hover:text-accent-hover",children:[t.jsx("span",{className:"shrink-0 font-mono text-xs text-og-500",title:f.id,children:un(f.id)}),t.jsx("span",{className:"truncate text-og-1000",title:f.title,children:f.title}),d&&t.jsx("span",{className:"pill shrink-0",children:a.agents.unassigned})]}),t.jsx("button",{type:"button",onClick:()=>void h(f.id,p),disabled:!u||x,title:u?a.agents.handToAndStart(p):a.agents.agentUnavailable(p),className:"shrink-0 text-sm font-medium text-accent transition-colors hover:text-accent-hover disabled:opacity-50 disabled:cursor-not-allowed",children:c===f.id?a.agents.starting:a.agents.start})]},f.id)})})}function sa(e,n){return!n||!tn.has(e.status)?!1:e.devAgentId===n}function ra(e,n,s){return e.projectId!==n||e.status!=="pending"?!1:e.preferredAgentId===s||e.preferredAgentId===""}const he="w-full rounded-md border border-og-100 bg-surface px-2.5 py-1.5 text-sm text-og-800 placeholder:text-og-400 focus:border-accent focus:outline-none focus:ring-[3px] focus:ring-accent-soft disabled:cursor-not-allowed disabled:opacity-50",ue="mb-1.5 block text-xs font-medium text-og-700",Nt="mt-1 text-xs text-accent",qe="mt-1 text-xs text-og-500",Ie="h-3.5 w-3.5 accent-accent",aa=/^[a-z][a-z0-9-]{1,31}$/;function ia({open:e,onClose:n,onCreated:s}){const r=H(),[a,i]=o.useState(""),[l,c]=o.useState(""),[m,h]=o.useState(null),[f,p]=o.useState("human"),[u,d]=o.useState(!1),[x,b]=o.useState(null),[y,T]=o.useState({}),[C,A]=o.useState(new Set),w=o.useRef(0),{show:k}=je(),{flagDirty:j}=Lt();o.useEffect(()=>{if(!e)return;w.current+=1;const I=w.current;i(""),c(""),h(null),p("human"),b(null),T({}),A(new Set),M.config.get().then(O=>{I===w.current&&A(new Set(O.project.map(J=>J.id)))}).catch(O=>{I===w.current&&b(r.common.loadFailed(O instanceof Error?O.message:String(O)))})},[e]);const v=()=>{u||n()},D=()=>{const I={};return a?aa.test(a)?C.has(a)&&(I.id=r.createProject.idTakenError):I.id=r.common.idFormatError:I.id=r.createProject.required,l.trim()||(I.repo=r.createProject.required),T(I),Object.keys(I).length===0},P=async I=>{if(I.preventDefault(),!!D()){d(!0),b(null);try{const O=await M.projects.create({id:a,repo:l.trim(),merge:m,...f?{specApproval:f}:{}});O.restartRequired&&j(),k({kind:"success",title:r.createProject.createdToastTitle(O.project.id)}),s(O.project.id)}catch(O){b(O instanceof Error?O.message:String(O))}finally{d(!1)}}};return t.jsx(Re,{open:e,onClose:v,title:r.createProject.title,size:"md",footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:v,disabled:u,className:"btn-secondary",children:r.common.cancel}),t.jsx("button",{type:"submit",form:"create-project-form",disabled:u,className:"btn-primary",children:u?r.common.creating:r.common.create})]}),children:t.jsxs("form",{id:"create-project-form",onSubmit:P,className:"space-y-3",children:[x&&t.jsx("div",{className:"whitespace-pre-line rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-sm text-accent",children:x}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"proj-id",children:r.createProject.idLabel}),t.jsx("input",{id:"proj-id",type:"text",value:a,onChange:I=>i(I.target.value),className:he,placeholder:"baxian",disabled:u}),y.id&&t.jsx("div",{className:Nt,children:y.id})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"proj-repo",children:r.createProject.repoLabel}),t.jsx("input",{id:"proj-repo",type:"text",value:l,onChange:I=>c(I.target.value),className:he,placeholder:"https://github.com/baxian-ai/baxian.git",disabled:u}),y.repo&&t.jsx("div",{className:Nt,children:y.repo})]}),t.jsxs("div",{children:[t.jsx("span",{className:ue,children:r.createProject.mergeStrategyLabel}),t.jsxs("label",{className:"mb-1 flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"merge",checked:m===null,onChange:()=>h(null),disabled:u,className:"h-3.5 w-3.5 accent-accent"}),t.jsx("span",{className:"text-sm text-og-800",children:r.createProject.mergeHumanLabel})]}),t.jsxs("label",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"merge",checked:m==="auto",onChange:()=>h("auto"),disabled:u,className:"h-3.5 w-3.5 accent-accent"}),t.jsx("span",{className:"text-sm text-og-800",children:r.createProject.mergeAutoLabel})]})]}),t.jsxs("div",{children:[t.jsx("span",{className:ue,children:r.createProject.specApprovalLabel}),t.jsxs("label",{className:"mb-1 flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"spec-approval",checked:f==="human",onChange:()=>p("human"),disabled:u,className:"h-3.5 w-3.5 accent-accent"}),t.jsx("span",{className:"text-sm text-og-800",children:r.createProject.specApprovalHumanLabel})]}),t.jsxs("label",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"spec-approval",checked:f===null,onChange:()=>p(null),disabled:u,className:"h-3.5 w-3.5 accent-accent"}),t.jsx("span",{className:"text-sm text-og-800",children:r.createProject.specApprovalAutoLabel})]})]})]})})}const Rn=/^[a-z][a-z0-9-]{1,31}$/,oa=500,Ut={id:"",mode:"local",host:"",runtime:"",workdir:"",yolo:!0,model:"",addDirs:""};function la(e){return e.alias?e.alias:`${e.user?`${e.user}@`:""}${e.hostname}${e.port!=null?`:${e.port}`:""}`}function ws({open:e,onClose:n,projectId:s,onCreated:r}){var L,G,S,U,_,se;const a=H(),[i,l]=o.useState(Ut),[c,m]=o.useState(null),[h,f]=o.useState([]),[p,u]=o.useState(new Set),[d,x]=o.useState(null),[b,y]=o.useState(!1),[T,C]=o.useState(!1),[A,w]=o.useState(null),[k,j]=o.useState(!1),[v,D]=o.useState(null),[P,I]=o.useState(!1),O=o.useRef(null),J=o.useRef(null),E=o.useRef(0),W=o.useRef(0),{show:re}=je(),{flagDirty:te}=Lt();o.useEffect(()=>{if(!e)return;W.current+=1;const B=W.current;l(Ut),m(null),f([]),u(new Set),x(null),y(!1),C(!1),w(null),E.current+=1,D(null),I(!1),M.config.get().then(R=>{if(B!==W.current)return;f(R.host??[]);const $=new Set;R.project.forEach(Z=>Z.agent.forEach(K=>K.forEach(ee=>$.add(ee.id)))),u($)}).catch(()=>{})},[e,s]);const X=()=>{k||n()},V=o.useCallback(()=>{O.current&&O.current.abort();const B=new AbortController;O.current=B,y(!0),D(null);const R=i.mode==="remote"?{hostId:i.host}:{};M.agents.probe(i.mode,R,{signal:B.signal}).then($=>{B.signal.aborted||(x($),D(null))}).catch($=>{B.signal.aborted||(x(null),D($ instanceof Error?$.message:String($)))}).finally(()=>{O.current===B&&y(!1)})},[i.mode,i.host]);o.useEffect(()=>{if(e&&(x(null),w(null),C(!1),E.current+=1,O.current&&O.current.abort(),!(i.mode==="remote"&&!i.host)))return J.current&&clearTimeout(J.current),J.current=setTimeout(V,oa),()=>{J.current&&clearTimeout(J.current)}},[e,i.mode,i.host,c,V]),o.useEffect(()=>{e||O.current&&O.current.abort()},[e]),o.useEffect(()=>()=>{O.current&&O.current.abort(),J.current&&clearTimeout(J.current)},[]);const ae=()=>{if(T)return;const B=E.current;C(!0),w(null);const R=i.mode==="remote"?{hostId:i.host}:{};M.agents.installTmux(i.mode,R).then($=>{E.current===B&&(w({ok:$.ok,message:$.message}),C(!1),$.ok&&V())}).catch($=>{E.current===B&&(w({ok:!1,message:$ instanceof Error?$.message:String($)}),C(!1))})},z=c?"qa":"dev",le=Rn.test(i.id)&&!p.has(i.id)&&i.id!==(c==null?void 0:c.agent.id),ne=i.mode==="local"||i.mode==="remote"&&i.host!=="",ge=i.runtime!==""&&!!((L=d==null?void 0:d.runtimes[i.runtime])!=null&&L.ok),q=!!(d!=null&&d.tmux.ok),ie=i.mode==="local"||!!((G=d==null?void 0:d.ssh)!=null&&G.ok),me=!k&&le&&ne&&ge&&q&&ie,xe=async B=>{var Z,K;if(B.preventDefault(),!me)return;D(null);const R=i.addDirs.split(`
|
|
11
11
|
`).map(ee=>ee.trim()).filter(ee=>ee.length>0),$={id:i.id,role:z,runtime:i.runtime,mode:i.mode,...i.mode==="remote"?{host:i.host}:{},...i.workdir?{workdir:i.workdir}:{},yolo:i.yolo,...i.model.trim()?{model:i.model.trim()}:{},...R.length>0?{addDirs:R}:{}};if(!c){m({agent:$,form:i}),l(Ut),x(null),w(null),I(!1);return}j(!0);try{const ee=await M.projects.addAgentTeam(s,{agents:[c.agent,$]});ee.restartRequired&&te(),re({kind:(Z=ee.warnings)!=null&&Z.length?"warn":"success",title:a.createAgent.addedToastTitle(ee.agents.find(be=>be.role==="dev").id,ee.agents.find(be=>be.role==="qa").id,s),...(K=ee.warnings)!=null&&K.length?{body:ee.warnings.join(`
|
|
12
|
-
`)}:{}}),r(),n()}catch(ee){D(ee instanceof Error?ee.message:String(ee))}finally{j(!1)}},ye=()=>{!c||k||(l(c.form),m(null),x(null),w(null),I(!1))},N=({rt:B})=>{if(i.mode==="remote"&&!i.host)return t.jsx("span",{className:"ml-2 text-xs text-og-400",children:a.createAgent.selectHostFirstHint});if(b)return t.jsx("span",{className:"ml-2 text-xs text-og-400",children:a.createAgent.probingLabel});if(!d)return t.jsx("span",{className:"ml-2 text-xs text-og-400",children:"?"});const $=d.runtimes[B];return $?$.ok?t.jsxs("span",{className:"ml-2 text-xs text-probe-ok",children:["✓ ",$.path??""]}):t.jsxs("span",{className:"ml-2 text-xs text-accent",title:$.message,children:["⨯ ",$.message]}):t.jsx("span",{className:"ml-2 text-xs text-og-400",children:"?"})},we=()=>{var R;if(i.mode==="remote"&&!i.host)return null;if(b&&!T)return t.jsx("div",{className:"text-xs text-og-400",children:a.createAgent.tmuxProbingLabel});if(!d)return null;if(d.tmux.ok)return t.jsxs("div",{className:"text-xs text-probe-ok",children:["tmux: ✓ ",d.tmux.path??""]});const B=i.mode==="local"||!!((R=d.ssh)!=null&&R.ok);return t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"text-xs text-accent",children:["tmux: ⨯ ",d.tmux.message,B&&t.jsx("button",{type:"button",onClick:ae,className:"ml-2 text-accent underline transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",disabled:T||k,children:T?a.common.installing:a.common.oneClickInstall})]}),T&&t.jsx("div",{className:"text-xs text-og-500",children:a.common.installingTmuxNotice}),!T&&A&&t.jsxs("div",{className:`break-all text-xs ${A.ok?"text-probe-ok":"text-accent"}`,children:[A.ok?"✓ ":"⨯ ",A.message]})]})},pe=()=>i.mode!=="remote"||!i.host||!(d!=null&&d.ssh)?null:d.ssh.ok?t.jsxs("div",{className:"text-xs text-probe-ok",children:["SSH: ✓ ",d.ssh.message]}):t.jsxs("div",{className:"text-xs text-accent",children:["SSH: ⨯ ",d.ssh.message]});return t.jsx(Re,{open:e,onClose:X,title:a.createAgent.modalTitle(s),size:"lg",footer:t.jsxs(t.Fragment,{children:[c&&t.jsx("button",{type:"button",onClick:ye,disabled:k,className:"btn-secondary",children:a.common.back}),t.jsx("button",{type:"button",onClick:X,disabled:k,className:"btn-secondary",children:a.common.cancel}),t.jsx("button",{type:"submit",form:"create-agent-form",disabled:!me,className:"btn-primary",children:k?a.createAgent.submitting:c?a.createAgent.submitLabel:a.createAgent.continueLabel})]}),children:t.jsxs("form",{id:"create-agent-form",onSubmit:xe,className:"space-y-3",children:[v&&t.jsx("div",{className:"whitespace-pre-line rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-sm text-accent",children:v}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"agent-id",children:"Agent ID"}),t.jsx("input",{id:"agent-id",type:"text",value:i.id,onChange:B=>l({...i,id:B.target.value}),className:he,placeholder:a.createAgent.idPlaceholder(s,z),disabled:k}),i.id&&!Rn.test(i.id)&&t.jsx("div",{className:Nt,children:a.common.idFormatError}),i.id&&(p.has(i.id)||i.id===(c==null?void 0:c.agent.id))&&t.jsx("div",{className:Nt,children:a.createAgent.idTakenGlobalError})]}),t.jsxs("div",{children:[t.jsx("span",{className:ue,children:a.createAgent.roleLabel}),t.jsx("div",{className:"text-sm text-og-800",children:z==="dev"?a.createAgent.devStepLabel:a.createAgent.qaStepLabel}),c&&t.jsx("div",{className:qe,children:a.createAgent.teamDevLabel(c.agent.id)})]}),t.jsxs("div",{children:[t.jsx("span",{className:ue,children:a.createAgent.modeLabel}),t.jsxs("label",{className:"mr-4 inline-flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"mode",checked:i.mode==="local",className:Ie,onChange:()=>l({...i,mode:"local",host:""}),disabled:k}),t.jsx("span",{className:"text-sm text-og-800",children:a.createAgent.localModeLabel})]}),t.jsxs("label",{className:"inline-flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"mode",checked:i.mode==="remote",className:Ie,onChange:()=>l({...i,mode:"remote"}),disabled:k}),t.jsx("span",{className:"text-sm text-og-800",children:a.createAgent.remoteModeLabel})]})]}),i.mode==="remote"&&t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"host",children:"Host"}),h.length===0?t.jsx("div",{className:"rounded-md border border-og-100 bg-og-50/40 px-3 py-2 text-xs text-og-600",children:a.createAgent.noHostsHint}):t.jsxs("select",{id:"host",value:i.host,onChange:B=>l({...i,host:B.target.value}),className:he,disabled:k,children:[t.jsx("option",{value:"",children:a.createAgent.selectHostPlaceholder}),h.map(B=>t.jsx("option",{value:B.id,children:oa(B)},B.id))]}),t.jsx("div",{className:qe,children:a.createAgent.sshConfigHint})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"mb-1.5 flex items-center justify-between",children:[t.jsx("span",{className:"text-xs font-medium text-og-700",children:a.createAgent.runtimeLabel}),t.jsx("button",{type:"button",onClick:V,className:"text-xs text-accent transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",disabled:k||b||i.mode==="remote"&&!i.host,children:a.createAgent.reprobeButton})]}),t.jsxs("label",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"runtime",checked:i.runtime==="claude-code",className:Ie,onChange:()=>l({...i,runtime:"claude-code"}),disabled:k||(d?!((S=d.runtimes["claude-code"])!=null&&S.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:k||(d?!((U=d.runtimes.codex)!=null&&U.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:k||(d?!((_=d.runtimes.opencode)!=null&&_.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:k||(d?!((se=d.runtimes.qodercli)!=null&&se.ok):!1)}),t.jsx("span",{className:"text-sm text-og-800",children:"Qoder CLI"}),t.jsx(N,{rt:"qodercli"})]}),t.jsx("div",{className:"mt-2",children:t.jsx(we,{})}),t.jsx("div",{children:t.jsx(pe,{})})]}),t.jsxs("div",{children:[t.jsxs("button",{type:"button",onClick:()=>I(B=>!B),"aria-expanded":P,"aria-controls":P?"advanced-options":void 0,className:"flex w-full items-center justify-between rounded-md px-1 py-1.5 text-left text-xs font-medium text-og-700 transition-colors hover:bg-og-50",children:[t.jsx("span",{children:a.createAgent.advancedOptionsLabel}),t.jsx("span",{className:"text-og-400",children:P?a.createAgent.collapseLabel:a.createAgent.expandLabel})]}),P&&t.jsxs("div",{id:"advanced-options",className:"mt-3 space-y-3",children:[t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"workdir",children:a.createAgent.workdirLabel}),t.jsx("input",{id:"workdir",type:"text",value:i.workdir,onChange:B=>l({...i,workdir:B.target.value}),className:he,placeholder:a.createAgent.workdirPlaceholder,disabled:k}),t.jsx("div",{className:qe,children:a.createAgent.workdirHint})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"model",children:a.createAgent.modelLabel}),t.jsx("input",{id:"model",type:"text",value:i.model,onChange:B=>l({...i,model:B.target.value}),className:he,placeholder:i.runtime==="codex"?a.createAgent.modelPlaceholderCodex:a.createAgent.modelPlaceholderOther,disabled:k}),t.jsx("div",{className:qe,children:a.createAgent.modelHint})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"addDirs",children:a.createAgent.addDirsLabel}),t.jsx("textarea",{id:"addDirs",value:i.addDirs,onChange:B=>l({...i,addDirs:B.target.value}),className:`${he} font-mono text-xs`,rows:3,placeholder:a.createAgent.addDirsPlaceholder,disabled:k}),t.jsx("div",{className:qe,children:a.createAgent.addDirsHint})]})]})]}),t.jsx("div",{className:"rounded-md border border-accent/25 bg-accent-soft/60 px-3 py-2.5",children:t.jsxs("label",{className:"flex cursor-pointer items-start gap-2",children:[t.jsx("input",{type:"checkbox",className:"mt-1 h-3.5 w-3.5 accent-accent",checked:i.yolo,onChange:B=>l({...i,yolo:B.target.checked}),disabled:k}),t.jsxs("div",{className:"text-sm text-og-800",children:[t.jsx("div",{className:"font-medium",children:a.createAgent.yoloTitle}),t.jsxs("div",{className:"mt-1 text-xs text-accent",children:[a.createAgent.yoloBodyLead,t.jsx("code",{children:er[i.runtime||"claude-code"]}),a.createAgent.yoloBodyTrail]})]})]})})]})})}const Cn=200,An=16e3,la="baxian.draft.createTask:";function Jt(e){return`${la}${e??"*"}`}function Dn(e){try{const n=localStorage.getItem(e);if(!n)return null;const s=JSON.parse(n);if(!s||typeof s!="object")return null;const r=s,a=typeof r.title=="string"?r.title:"",i=typeof r.description=="string"?r.description:"",l=typeof r.projectId=="string"?r.projectId:"",c=typeof r.preferredAgentId=="string"?r.preferredAgentId:"",m=typeof r.updatedAt=="number"?r.updatedAt:void 0;return!a.trim()&&!i.trim()?null:{title:a,description:i,projectId:l,preferredAgentId:c,updatedAt:m}}catch{return null}}function ca(e,n){const s=!n.title.trim()&&!n.description.trim();try{s?localStorage.removeItem(e):localStorage.setItem(e,JSON.stringify({...n,updatedAt:Date.now()}))}catch{}}function Pn(e){try{localStorage.removeItem(e)}catch{}}function da(e){const n=Jt(e),s=Dn(n);if(!e)return s;const r=Jt(void 0),a=Dn(r);if(!a||a.projectId!==e)return s;const i=!s||(a.updatedAt??0)>(s.updatedAt??0);if(i)try{localStorage.setItem(n,JSON.stringify(a))}catch{return a}try{localStorage.removeItem(r)}catch{}return i?a:s}const Ln="mt-1 text-right text-xs text-og-400",ua=Math.floor(Pt/1024/1024);function mn(e){const n=H(),s=e.mode==="edit",{show:r}=je(),a=s?e.task.projectId:e.projectId,i=s?e.task.title:"",l=s?e.task.description:"",c=s?e.task.preferredAgentId:"",[m,h]=o.useState([]),[f,p]=o.useState([]),[u,d]=o.useState(a??""),[x,b]=o.useState(c),[y,T]=o.useState(i),[C,A]=o.useState(l),[w,k]=o.useState([]),j=o.useRef(null),[v,D]=o.useState(!1),[P,I]=o.useState(null),[O,J]=o.useState(!1),E=o.useRef(0),W=o.useRef(0),re=o.useRef(0),te=o.useRef(new Set),X=s?null:Jt(a);o.useEffect(()=>{if(!e.open)return;E.current+=1,W.current+=1;const R=E.current;h([]),p([]),te.current=new Set;const $=X?da(a):null;$&&te.current.add($.projectId),d(a??($==null?void 0:$.projectId)??""),b(($==null?void 0:$.preferredAgentId)||c),T(($==null?void 0:$.title)||i),A(($==null?void 0:$.description)||l),J($!==null),I(null),D(!1),k([]),Promise.all([M.projects.list(),M.agents.list()]).then(([Z,K])=>{R===E.current&&(h(Z),p(K))}).catch(Z=>{R===E.current&&I(Z instanceof Error?Z.message:String(Z))})},[e.open,a,i,l,c,X]),o.useEffect(()=>{if(!(!e.open||!X)){if(re.current!==W.current){re.current=W.current;return}ca(X,{title:y,description:C,projectId:u,preferredAgentId:x})}},[e.open,X,y,C,u,x]);const V=o.useMemo(()=>m.find(R=>R.id===u)??null,[m,u]),ae=o.useMemo(()=>V?V.agent.flat().filter(R=>R.role==="dev"):[],[V]),z=o.useMemo(()=>new Set(f.map(R=>R.id)),[f]),le=o.useMemo(()=>ae.filter(R=>z.has(R.id)),[ae,z]),ne=o.useMemo(()=>ae.filter(R=>!z.has(R.id)),[ae,z]);o.useEffect(()=>{s||V!==null&&x!==""&&!le.find(R=>R.id===x)&&b("")},[V,le,x,s]),o.useEffect(()=>{if(s||!V)return;const R=le.find($=>$.role==="dev");R&&(te.current.has(V.id)||(te.current.add(V.id),b($=>$===""?R.id:$)))},[s,V,le]);const ge=!s||le.find(R=>R.id===x),q=s&&!ge&&!!x,ie=q&&ne.some(R=>R.id===x),me=ie?n.createTask.noDevPendingRestartHint(x):q?n.createTask.noDevNotInRuntimeHint(x):!u||le.length>0?null:ne.length>0?n.createTask.noDevGlobalPendingRestartHint:null,xe=y.trim(),ye=C.trim(),we=!!u&&xe.length>0&&!v,pe=()=>{v||e.onClose()},L=()=>{X&&(Pn(X),d(a??""),b(c),T(i),A(l),I(null),J(!1))},G=async R=>{var $,Z;if(R.preventDefault(),!!we){D(!0),I(null);try{if(e.mode==="edit"){const K=await M.tasks.update(e.task.id,{title:xe,description:ye,preferredAgentId:x});r({kind:"success",title:n.createTask.updatedToastTitle}),($=e.onUpdated)==null||$.call(e,K),e.onClose()}else{const K=w.length?await Promise.all(w.map(async be=>({dataBase64:await Yn(be),filename:be.name}))):void 0,ee=await M.tasks.create({projectId:u,title:xe,description:ye,preferredAgentId:x,...K?{images:K}:{}});X&&Pn(X),r({kind:"success",title:n.createTask.createdToastTitle}),(Z=e.onCreated)==null||Z.call(e,ee),e.onClose()}}catch(K){I(K instanceof Error?K.message:String(K))}finally{D(!1)}}},S=R=>{const $=Array.from(R.target.files??[]);if(R.target.value="",$.length===0)return;const Z=$.filter(K=>K.size>Pt?(r({kind:"error",title:n.createTask.imageTooLargeToastTitle,body:n.createTask.imageTooLargeToastBody(K.name,ua)}),!1):!0);w.length+Z.length>ft&&r({kind:"warn",title:n.createTask.tooManyImagesToastTitle(ft)}),k(K=>[...K,...Z].slice(0,ft))},U=R=>k($=>$.filter((Z,K)=>K!==R)),_=s?n.createTask.titleEdit:n.createTask.titleCreate,se=s?v?n.common.saving:n.common.save:v?n.common.creating:n.common.create,B=!s&&!a;return t.jsx(Re,{open:e.open,onClose:pe,title:_,size:"md",dismissOnBackdrop:!1,footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:pe,disabled:v,className:"btn-secondary",children:n.common.cancel}),t.jsx("button",{type:"submit",form:"create-task-form",disabled:!we,className:"btn-primary",children:se})]}),children:t.jsxs("form",{id:"create-task-form",onSubmit:G,className:"space-y-3",children:[!s&&O&&t.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-md border border-accent-soft bg-accent-soft/30 px-3 py-2 text-xs text-accent",children:[t.jsx("span",{children:n.createTask.draftRestoredNotice}),t.jsx("button",{type:"button",onClick:L,className:"shrink-0 underline hover:text-accent-hover",children:n.createTask.discardDraftButton})]}),P&&t.jsx("div",{className:"rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-sm text-accent",children:P}),B&&t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"task-project",children:"Project"}),t.jsxs("select",{id:"task-project",value:u,onChange:R=>d(R.target.value),className:he,disabled:v,required:!0,children:[t.jsx("option",{value:"",disabled:!0,children:n.createTask.selectProjectPlaceholder}),m.map(R=>t.jsx("option",{value:R.id,children:R.id},R.id))]})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"task-dev",children:n.createTask.targetAgentLabel}),t.jsxs("select",{id:"task-dev",value:x,onChange:R=>b(R.target.value),className:he,disabled:v,children:[t.jsx("option",{value:"",children:n.createTask.notAssignedOption}),q&&t.jsxs("option",{value:x,children:[x," ",ie?n.createTask.pendingRestartSuffix:n.createTask.notInRuntimeSuffix]}),le.map(R=>t.jsx("option",{value:R.id,children:R.id},R.id))]}),me&&t.jsx("div",{className:"mt-1 text-xs text-accent",children:me})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"task-title",children:"Title"}),t.jsx("input",{id:"task-title",type:"text",value:y,onChange:R=>T(R.target.value),maxLength:Cn,className:he,placeholder:n.createTask.titlePlaceholder,disabled:v,required:!0}),t.jsxs("div",{className:Ln,children:[y.length," / ",Cn]})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"task-description",children:n.createTask.descriptionLabel}),t.jsx("textarea",{id:"task-description",value:C,onChange:R=>A(R.target.value),maxLength:An,rows:8,className:`${he} font-mono text-xs`,placeholder:n.createTask.descriptionPlaceholder,disabled:v}),t.jsxs("div",{className:Ln,children:[C.length," / ",An]})]}),!s&&t.jsxs("div",{children:[t.jsx("label",{className:ue,children:n.createTask.imagesLabel}),t.jsx("button",{type:"button",onClick:()=>{var R;return(R=j.current)==null?void 0:R.click()},disabled:v||w.length>=ft,className:"btn-secondary",children:n.createTask.addImagesButton}),t.jsx("input",{ref:j,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:S}),w.length>0&&t.jsx("ul",{className:"mt-2 space-y-1",children:w.map((R,$)=>t.jsxs("li",{className:"flex items-center justify-between rounded-md border border-og-100 bg-surface px-2.5 py-1.5",children:[t.jsx("span",{title:R.name,className:"truncate text-xs text-og-700",children:R.name}),t.jsx("button",{type:"button","aria-label":n.createTask.removeImageAriaLabel(R.name),onClick:()=>U($),disabled:v,className:"ml-2 shrink-0 text-og-400 transition-colors",children:"✕"})]},`${R.name}-${$}`))})]})]})})}const En="***",Gt={hostname:"",port:"",alias:"",user:"",password:""};function ma(e){return e.alias?e.alias:`${e.user?`${e.user}@`:""}${e.hostname}${e.port!=null?`:${e.port}`:""}`}function ha({open:e,onClose:n}){var pe;const s=H(),[r,a]=o.useState([]),[i,l]=o.useState("list"),[c,m]=o.useState(null),[h,f]=o.useState(null),[p,u]=o.useState(!1),[d,x]=o.useState(!1),[b,y]=o.useState(Gt),[T,C]=o.useState(null),[A,w]=o.useState(!1),[k,j]=o.useState(!1),[v,D]=o.useState(null),[P,I]=o.useState(!1),[O,J]=o.useState(null),E=o.useRef(0),W=o.useRef(null),{show:re}=je(),te=o.useCallback(()=>{M.hosts.list().then(a).catch(L=>C(L instanceof Error?L.message:String(L)))},[]);o.useEffect(()=>{if(!e){W.current&&W.current.abort();return}l("list"),m(null),f(null),y(Gt),C(null),te()},[e,te]),o.useEffect(()=>{E.current+=1,W.current&&W.current.abort(),j(!1),D(null),I(!1),J(null)},[b.hostname,b.user,b.port,b.password,d,i]),o.useEffect(()=>()=>{W.current&&W.current.abort()},[]);const X=()=>{m(null),f(null),u(!1),x(!1),y(Gt),C(null),l("form")},V=L=>{m(L.id??null),f(L),u(L.password===En),x(!1),y({hostname:L.hostname,port:L.port!=null?String(L.port):"",alias:L.alias??"",user:L.user??"",password:""}),C(null),l("form")},ae=()=>{const L={hostname:b.hostname.trim()};return c?(L.port=b.port.trim()?Number(b.port):null,L.alias=b.alias.trim(),L.user=b.user.trim()):(b.port.trim()&&(L.port=Number(b.port)),b.alias.trim()&&(L.alias=b.alias.trim()),b.user.trim()&&(L.user=b.user.trim())),c&&d?L.password="":b.password&&(L.password=b.password),L},z=b.port.trim(),le=z===""||/^\d+$/.test(z)&&Number(z)>0&&Number(z)<=65535,ne=b.hostname.trim().length>0&&le,ge=!!h&&b.hostname.trim()===h.hostname&&b.user.trim()===(h.user??"")&&b.port.trim()===(h.port!=null?String(h.port):""),q=()=>c&&ge&&!b.password&&!d?{hostId:c}:{host:{hostname:b.hostname.trim(),...b.user.trim()?{user:b.user.trim()}:{},...z?{port:Number(z)}:{},...!d&&b.password?{password:b.password}:{}}},ie=async()=>{if(!ne||k)return;W.current&&W.current.abort();const L=new AbortController;W.current=L;const G=E.current;j(!0),D(null),J(null),C(null);try{const S=await M.agents.probe("remote",q(),{signal:L.signal});if(L.signal.aborted||E.current!==G)return;D(S)}catch(S){if(L.signal.aborted||E.current!==G)return;C(S instanceof Error?S.message:String(S))}finally{E.current===G&&j(!1)}},me=async()=>{if(P)return;const L=E.current;I(!0),J(null),C(null);try{const G=await M.agents.installTmux("remote",q());if(E.current!==L)return;J({ok:G.ok,message:G.message}),D(S=>S&&{...S,tmux:G.tmux})}catch(G){if(E.current!==L)return;C(G instanceof Error?G.message:String(G))}finally{E.current===L&&I(!1)}},xe=async L=>{if(L.preventDefault(),!(!ne||A)){w(!0),C(null);try{if(c)await M.hosts.update(c,ae()),re({kind:"success",title:s.hostMgmt.updatedToastTitle(c)});else{const G=await M.hosts.create(ae());re({kind:"success",title:s.hostMgmt.createdToastTitle(G.host.id)})}te(),l("list")}catch(G){C(G instanceof Error?G.message:String(G))}finally{w(!1)}}},ye=async L=>{C(null);try{await M.hosts.delete(L.id),re({kind:"success",title:s.hostMgmt.deletedToastTitle(L.id)}),te()}catch(G){C(G instanceof Error?G.message:String(G))}},N=t.jsx("button",{type:"button",onClick:n,className:"btn-secondary",children:s.common.close}),we=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:()=>l("list"),disabled:A,className:"btn-secondary",children:s.common.backText}),t.jsx("button",{type:"submit",form:"host-form",disabled:!ne||A,className:"btn-primary",children:A?s.common.saving:s.common.save})]});return t.jsxs(Re,{open:e,onClose:n,title:s.hostMgmt.title,size:"md",footer:i==="list"?N:we,children:[T&&t.jsx("div",{className:"mb-3 whitespace-pre-line rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-sm text-accent",children:T}),i==="list"?t.jsxs("div",{className:"space-y-3",children:[r.length===0?t.jsx("p",{className:"text-sm text-og-500",children:s.hostMgmt.emptyState}):t.jsx("ul",{className:"space-y-1.5",children:r.map(L=>t.jsxs("li",{className:"flex items-center justify-between gap-3 rounded-md border border-og-100 px-3 py-2",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"truncate text-sm font-medium text-og-800",children:ma(L)}),t.jsxs("div",{className:"truncate text-xs text-og-500",children:[(L.user?`${L.user}@`:"")+L.hostname,L.port!=null?`:${L.port}`:"",L.password===En?s.hostMgmt.passwordSavedIndicator:""]})]}),t.jsxs("div",{className:"flex shrink-0 gap-2",children:[t.jsx("button",{type:"button",onClick:()=>V(L),className:"text-xs text-accent transition-colors hover:text-accent-hover",children:s.common.edit}),t.jsx("button",{type:"button",onClick:()=>ye(L),className:"text-xs text-accent transition-colors hover:opacity-80",children:s.common.delete})]})]},L.id))}),t.jsx("button",{type:"button",onClick:X,className:"btn-secondary w-full",children:s.hostMgmt.addHostButton})]}):t.jsxs("form",{id:"host-form",onSubmit:xe,className:"space-y-3",children:[t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"host-hostname",children:s.hostMgmt.addressLabel}),t.jsx("input",{id:"host-hostname",type:"text",value:b.hostname,onChange:L=>y({...b,hostname:L.target.value}),className:he,placeholder:"remote.example.com",disabled:A})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"host-port",children:s.hostMgmt.portLabel}),t.jsx("input",{id:"host-port",type:"text",inputMode:"numeric",value:b.port,onChange:L=>y({...b,port:L.target.value}),className:he,placeholder:"22",disabled:A}),b.port.trim()!==""&&!le&&t.jsx("div",{className:"mt-1 text-xs text-accent",children:s.hostMgmt.portRangeError})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"host-alias",children:s.hostMgmt.aliasLabel}),t.jsx("input",{id:"host-alias",type:"text",value:b.alias,onChange:L=>y({...b,alias:L.target.value}),className:he,placeholder:"Prod worker",disabled:A})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"host-user",children:s.hostMgmt.userLabel}),t.jsx("input",{id:"host-user",type:"text",value:b.user,onChange:L=>y({...b,user:L.target.value}),className:he,placeholder:s.hostMgmt.userPlaceholder,disabled:A})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"host-password",children:s.hostMgmt.passwordLabel}),t.jsx("input",{id:"host-password",type:"password",value:d?"":b.password,onChange:L=>y({...b,password:L.target.value}),className:he,placeholder:p?s.hostMgmt.passwordPlaceholderSet:s.hostMgmt.passwordPlaceholderUnset,disabled:A||d,autoComplete:"new-password"}),c&&p&&t.jsxs("label",{className:"mt-1.5 flex items-center gap-2 text-xs text-og-700",children:[t.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 accent-accent",checked:d,onChange:L=>x(L.target.checked),disabled:A}),s.hostMgmt.clearPasswordLabel]})]}),t.jsxs("div",{className:"rounded-md border border-accent/25 bg-accent-soft/60 px-3 py-2.5 text-xs text-accent",children:[s.hostMgmt.passwordHintLead,t.jsx("strong",{className:"font-semibold",children:s.hostMgmt.passwordHintStrong})," ",s.hostMgmt.plaintextWarningLead,t.jsx("strong",{className:"font-semibold",children:s.hostMgmt.plaintextWarningStrong}),s.hostMgmt.plaintextWarningTrail]}),t.jsxs("div",{className:"space-y-1.5",children:[t.jsx("button",{type:"button",onClick:ie,disabled:!ne||k||A||P,className:"text-xs text-accent transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",children:k?s.hostMgmt.testing:s.hostMgmt.testConnection}),(v==null?void 0:v.ssh)&&t.jsxs("div",{className:`text-xs ${v.ssh.ok?"text-og-800":"text-accent"}`,children:["SSH: ",v.ssh.ok?"✓":"⨯"," ",v.ssh.message]}),v&&(v.tmux.ok?t.jsxs("div",{className:"text-xs text-og-800",children:["tmux: ✓ ",v.tmux.path??""]}):t.jsxs("div",{className:"text-xs text-accent",children:["tmux: ⨯ ",v.tmux.message,((pe=v.ssh)==null?void 0:pe.ok)&&t.jsx("button",{type:"button",onClick:me,disabled:P||A,className:"ml-2 text-accent underline transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",children:P?s.common.installing:s.common.oneClickInstall})]})),P&&t.jsx("div",{className:"text-xs text-og-500",children:s.common.installingTmuxNotice}),!P&&O&&t.jsxs("div",{className:`break-all text-xs ${O.ok?"text-og-800":"text-accent"}`,children:[O.ok?"✓ ":"⨯ ",O.message]})]})]})]})}const hn="baxian.taskNotifications.enabled";function fn(){if(typeof window>"u")return null;const e=window.Notification;return typeof e=="function"?e:null}function yt(){const e=fn();return e?e.permission:"unsupported"}function Wt(){try{return localStorage.getItem(hn)!=="0"}catch{return!0}}function wt(e){try{localStorage.setItem(hn,e?"1":"0")}catch{}}const ks=o.createContext(null);function fa({children:e}){const[n,s]=o.useState(yt),[r,a]=o.useState(Wt),[i,l]=o.useState(!1),c=o.useRef(!1),m=o.useRef(0);o.useEffect(()=>{const p=()=>{s(yt()),c.current||a(Wt())},u=d=>{if(d.key!==null&&d.key!==hn)return;s(yt());const x=d.key===null?Wt():d.newValue!=="0";x||(m.current+=1),a(x)};return window.addEventListener("focus",p),window.addEventListener("storage",u),()=>{window.removeEventListener("focus",p),window.removeEventListener("storage",u)}},[]);const h=o.useCallback(()=>{a(!0);const p=fn();if(!p){wt(!0);return}if(p.permission!=="default"){s(p.permission),wt(!0);return}if(c.current)return;c.current=!0,l(!0);const u=m.current;p.requestPermission().then(s).catch(d=>{console.warn("[task-notifications] permission request failed:",d),s(yt())}).finally(()=>{m.current===u&&wt(!0),c.current=!1,l(!1)})},[]),f=o.useCallback(()=>{m.current+=1,a(!1),wt(!1)},[]);return t.jsx(ks.Provider,{value:{permission:n,preferenceEnabled:r,enabled:n==="granted"&&r,requesting:i,enable:h,disable:f},children:e})}function js(){const e=o.useContext(ks);if(!e)throw new Error("useTaskNotifications must be used inside TaskNotificationsProvider");return e}const pa=[{value:"en-US",label:"English"},{value:"zh-CN",label:"简体中文"}];function ga({open:e,onClose:n}){const s=H(),{locale:r,saving:a,setLocale:i}=rs(),{show:l}=je(),c=async m=>{try{await i(m)}catch(h){const f=h instanceof Error?h.message:String(h);l({kind:"error",title:s.settings.languageSaveFailed(f)})}};return t.jsx(Re,{open:e,onClose:n,title:s.settings.title,size:"sm",children:t.jsxs("div",{className:"space-y-5",children:[t.jsxs("fieldset",{children:[t.jsx("legend",{className:ue,children:s.settings.language}),t.jsx("div",{className:"flex gap-4",children:pa.map(m=>t.jsxs("label",{className:"inline-flex items-center gap-2 text-sm text-og-800",children:[t.jsx("input",{type:"radio",name:"baxian-language",className:Ie,checked:r===m.value,disabled:a,onChange:()=>void c(m.value)}),m.label]},m.value))})]}),t.jsx(xa,{})]})})}function xa(){const e=H(),{permission:n,enabled:s,requesting:r,enable:a,disable:i}=js();if(n==="unsupported")return null;const l=n==="denied";return t.jsxs("div",{children:[t.jsxs("label",{className:"inline-flex items-center gap-2 text-sm text-og-800",children:[t.jsx("input",{type:"checkbox",className:Ie,checked:s,disabled:l||r,onChange:()=>s?i():a()}),e.settings.taskNotifications]}),t.jsx("p",{className:qe,children:l?e.settings.taskNotificationsDenied:e.settings.taskNotificationsHint})]})}const Ts="topbar-actions";function $n(){return typeof document>"u"?null:document.getElementById(Ts)}function Ns({children:e}){const[n,s]=o.useState($n);return o.useEffect(()=>{n||s($n())},[n]),n?Ws.createPortal(e,n):null}function ba(){return ms("/api/realtime")}class va{constructor(n={}){ce(this,"wsUrl");ce(this,"wsFactory");ce(this,"tokenProvider");ce(this,"ws",null);ce(this,"topics",new Map);ce(this,"cache",new Map);ce(this,"outbox",[]);ce(this,"reconnectScheduler");ce(this,"explicitlyClosed",!1);this.wsUrl=n.wsUrl??ba(),this.wsFactory=n.wsFactory??hs,this.tokenProvider=n.tokenProvider??sn,this.reconnectScheduler=new cs({reconnect:()=>this.openSocket(),shouldReconnect:()=>!this.explicitlyClosed&&this.topics.size>0})}subscribe(n,s,r){let a=this.topics.get(n);const i=!a;return a||(a={data:new Set,error:new Set},this.topics.set(n,a)),a.data.add(s),r&&a.error.add(r),i?(this.ensureSocket(),this.wsSendOrQueue({op:"subscribe",topic:n})):this.cache.has(n)&&queueMicrotask(()=>{var l;(l=this.topics.get(n))!=null&&l.data.has(s)&&this.cache.has(n)&&s(this.cache.get(n))}),()=>this.unsubscribe(n,s,r)}close(){if(this.explicitlyClosed=!0,this.reconnectScheduler.cancel(),this.reconnectScheduler.reset(),this.ws){try{this.ws.close()}catch{}this.ws=null}this.topics.clear(),this.cache.clear(),this.outbox=[]}unsubscribe(n,s,r){const a=this.topics.get(n);a&&(a.data.delete(s),r&&a.error.delete(r),a.data.size===0&&a.error.size===0&&(this.topics.delete(n),this.cache.delete(n),this.wsSendOrQueue({op:"unsubscribe",topic:n}),this.topics.size===0&&this.teardownSocket()))}teardownSocket(){if(this.reconnectScheduler.cancel(),this.reconnectScheduler.reset(),this.outbox=[],this.ws){try{this.ws.close()}catch{}this.ws=null}}ensureSocket(){this.explicitlyClosed||this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING)||this.openSocket()}openSocket(){if(this.explicitlyClosed)return;this.reconnectScheduler.cancel();const n=this.tokenProvider(),s=n?[`baxian.token.${us(n)}`]:void 0;let r;try{r=this.wsFactory(this.wsUrl,s)}catch(i){console.warn("[events-client] WebSocket constructor threw:",i),this.broadcastConnectionError({code:"connection_failed",message:i instanceof Error?i.message:"WebSocket constructor threw"}),this.scheduleReconnect();return}this.ws=r;let a=!1;r.onopen=()=>{if(r!==this.ws)return;a=!0,this.reconnectScheduler.reset();for(const l of this.topics.keys())try{r.send(JSON.stringify({op:"subscribe",topic:l}))}catch(c){console.warn("[events-client] resubscribe send failed:",c)}const i=this.outbox;this.outbox=[];for(const l of i)if(!(l.op==="subscribe"||l.op==="unsubscribe"))try{r.send(JSON.stringify(l))}catch(c){console.warn("[events-client] outbox flush failed:",c)}},r.onmessage=i=>{if(r!==this.ws)return;let l;try{const c=typeof i.data=="string"?i.data:String(i.data);l=JSON.parse(c)}catch{return}this.handleMessage(l)},r.onclose=i=>{r===this.ws&&(this.ws=null,!this.explicitlyClosed&&(ds(i,n,this.tokenProvider())||(a||this.broadcastConnectionError({code:"connection_failed",message:"WebSocket failed to connect (auth, network, or proxy issue)"}),this.topics.size!==0&&this.scheduleReconnect())))},r.onerror=()=>{}}scheduleReconnect(){this.reconnectScheduler.schedule()}broadcastConnectionError(n){for(const s of this.topics.values())for(const r of[...s.error])try{r(n)}catch(a){console.error("[events-client] error handler threw on connection error:",a)}}wsSendOrQueue(n){if(this.ws&&this.ws.readyState===WebSocket.OPEN)try{this.ws.send(JSON.stringify(n));return}catch(s){console.warn("[events-client] send failed, will queue:",s)}this.outbox.push(n)}handleMessage(n){switch(n.type){case"data":{const s=this.topics.get(n.topic);if(this.cache.set(n.topic,n.data),!s)return;for(const r of[...s.data])try{r(n.data)}catch(a){console.error(`[events-client] handler threw on ${n.topic}:`,a)}break}case"error":{const s={code:n.code,message:n.message};if(n.topic){const r=this.topics.get(n.topic);if(r)for(const a of[...r.error])try{a(s)}catch(i){console.error(`[events-client] error handler threw on ${n.topic}:`,i)}}else console.warn("[events-client] connection-level error:",n.code,n.message);break}}}}let zt=null;function rt(){return zt||(zt=new va),zt}function pn(){const[e,n]=o.useState(null),[s,r]=o.useState(!1),[a,i]=o.useState(null);return o.useEffect(()=>rt().subscribe("agents",c=>{i(null),n(c),r(!0)},c=>i(c)),[]),{data:e,loaded:s,error:a}}function Ss(e){const[n,s]=o.useState(null),[r,a]=o.useState(!1),[i,l]=o.useState(null);return o.useEffect(()=>(s(null),a(!1),l(null),rt().subscribe(`task:${e}`,m=>{l(null),s(m),a(!0)},m=>l(m))),[e]),{data:n,loaded:r,error:i}}function Rs(e){const[n,s]=o.useState(null),[r,a]=o.useState(!1),[i,l]=o.useState(null);return o.useEffect(()=>{if(!e){s(null),a(!1),l(null);return}s(null),a(!1),l(null);let c=!1,m=!1,h=!1;const f=rt().subscribe(`project-tasks:${e}`,p=>{c||(m=!0,l(null),s(p),a(!0))},p=>{c||(l(p),!(m||h)&&(h=!0,M.tasks.list(e).then(u=>{c||m||(s(u),a(!0))},u=>{console.warn(`[useProjectTasks] REST fallback failed for ${e}:`,u)})))});return()=>{c=!0,f()}},[e]),{data:n,loaded:r,error:i}}let St=null,Be=null,Rt=null,Ze=0;const Xt=new Set;function Cs(){Xt.forEach(e=>e())}async function ya(){const e=Ze;try{const n=await M.projects.list();if(e!==Ze)return;St=n,Rt=null}catch(n){if(e!==Ze)return;Rt=n instanceof Error?n.message:String(n)}finally{e===Ze&&(Be=null,Cs())}}function Zt(){return Be||(Be=ya(),Be)}function wa(){Ze+=1,St=null,Be=null,Rt=null,Cs()}typeof window<"u"&&window.addEventListener(et,wa);async function ka(){const e=Be!==null;await Zt(),e&&await Zt()}function at(){const[,e]=o.useState(0);return o.useEffect(()=>{const n=()=>e(s=>s+1);return Xt.add(n),St===null&&!Be&&Zt(),()=>{Xt.delete(n)}},[]),{projects:St,error:Rt,refresh:ka}}function ja(){const e=H(),n=Le(),{projects:s,error:r,refresh:a}=at(),i=s??[],l=s!==null,[c,m]=o.useState(!1),[h,f]=o.useState(!1),[p,u]=o.useState(!1),[d,x]=o.useState(!1),[b,y]=o.useState({kind:"closed"}),{data:T,loaded:C,error:A}=pn(),w=(A==null?void 0:A.message)??null,k=new Map((T??[]).map(P=>[P.id,P])),j=r??w,v=i.length===0,D=t.jsx("button",{type:"button",onClick:()=>f(!0),disabled:v,"aria-describedby":v?"create-task-hint":void 0,className:"btn-ghost",children:e.dashboard.newTask});return t.jsxs("div",{children:[t.jsxs(Ns,{children:[v?t.jsx("span",{className:"inline-flex",title:e.dashboard.createProjectFirst,children:D}):D,v&&t.jsx("span",{id:"create-task-hint",className:"sr-only",children:e.dashboard.createProjectFirst}),t.jsx(Dt,{ariaLabel:e.dashboard.moreActions,children:P=>t.jsxs(t.Fragment,{children:[t.jsx(ke,{onClick:()=>{P(),m(!0)},children:e.dashboard.newProject}),t.jsx(ke,{onClick:()=>{P(),u(!0)},children:e.dashboard.manageHosts}),t.jsx(ke,{onClick:()=>{P(),x(!0)},children:e.settings.entry})]})})]}),t.jsx("h1",{className:"sr-only",children:"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(P=>t.jsx(Ta,{project:P,agentsById:k,agentsLoaded:C,agentsError:!!A,onAgentDeleted:a},P.id)),t.jsx(aa,{open:c,onClose:()=>m(!1),onCreated:P=>{m(!1),a(),y({kind:"asking",projectId:P})}}),t.jsx(ha,{open:p,onClose:()=>u(!1)}),t.jsx(Re,{open:b.kind==="asking",onClose:()=>y({kind:"closed"}),title:e.dashboard.projectCreatedTitle,size:"sm",footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:()=>y({kind:"closed"}),className:"btn-secondary",children:e.dashboard.later}),t.jsx("button",{type:"button",onClick:()=>{b.kind==="asking"&&y({kind:"addingAgent",projectId:b.projectId})},className:"btn-primary",children:e.dashboard.continueAddingAgent})]}),children:t.jsx("p",{className:"text-sm text-og-700",children:e.dashboard.addAgentNowOrLater})}),b.kind==="addingAgent"&&t.jsx(ws,{open:!0,projectId:b.projectId,onClose:()=>y({kind:"closed"}),onCreated:()=>{a()}}),t.jsx(mn,{open:h,onClose:()=>f(!1),onCreated:P=>n(Pe(P.projectId,P.id))}),t.jsx(ga,{open:d,onClose:()=>x(!1)})]})}function Ta({project:e,agentsById:n,agentsLoaded:s,agentsError:r,onAgentDeleted:a}){const i=H(),{data:l,error:c}=Rs(e.id),m=l??[],h=(c==null?void 0:c.message)??null;return t.jsxs("div",{className:"mb-10",children:[t.jsxs("div",{className:"mb-3 -mx-2 flex items-baseline gap-x-3 gap-y-1 px-2 py-1",children:[t.jsx("h2",{className:"min-w-0 truncate font-display text-sm font-semibold tracking-tight text-og-1000",title:e.id,children:t.jsx(Se,{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(Se,{to:`/project/${e.id}`,className:"ml-auto text-sm text-accent hover:text-accent-hover","aria-label":i.dashboard.detailsAriaLabel(e.id),children:i.dashboard.detailsLink})]}),h&&t.jsx("div",{className:"mb-2 text-xs text-accent",children:i.dashboard.tasksLoadFailed(h)}),e.agent.flat().length===0?t.jsx("div",{className:"rounded-lg border border-hairline bg-surface py-6 text-center text-sm text-og-500",children:i.dashboard.noAgentsYet}):t.jsx("div",{className:e.agent.length===1?"space-y-3":"grid grid-cols-1 gap-3 xl:grid-cols-2",children:e.agent.map((f,p)=>t.jsx(ys,{team:f,projectId:e.id,agentsById:n,agentsLoaded:s,agentsError:r,tasks:m,onDeleted:a,terminalMode:"embedded-full"},f.map(u=>u.id).join(":")||p))})]})}const As="baxian.taskPanel.doneOpen";function Na(){try{return localStorage.getItem(As)==="1"}catch{return!1}}function Ct(e){const n=e.match(/^task-(\d+)$/);return n?parseInt(n[1],10):Number.NaN}function Sa(e,n){const s=Ct(e.id),r=Ct(n.id);return Number.isNaN(s)||Number.isNaN(r)?e.id.localeCompare(n.id):s-r}function Ra(e,n){const s=(n.updatedAt??"").localeCompare(e.updatedAt??"");if(s!==0)return s;const r=Ct(e.id),a=Ct(n.id);return Number.isNaN(r)||Number.isNaN(a)?n.id.localeCompare(e.id):a-r}function In(e,n){const[s,r]=o.useState(Bt);o.useEffect(()=>r(Bt),[n]);const a=e.slice(0,s),i=e.length>a.length;return{items:a,hasMore:i,loadMore:()=>r(c=>c+Bt),total:e.length}}function Ca(e){const[n,s]=o.useState([]),[r,a]=o.useState(!1),[i,l]=o.useState(!1),[c,m]=o.useState(!1),[h,f]=o.useState(null),p=o.useRef(0),u=o.useRef(0),d=o.useCallback(x=>{const b=++p.current,y=x==="first"?0:u.current;l(!0),f(null),M.tasks.page(e,{category:"done",offset:y}).then(T=>{p.current===b&&(s(C=>x==="first"?T.tasks:[...C,...T.tasks]),a(T.hasMore),u.current=T.nextOffset,m(!0),l(!1))},T=>{p.current===b&&(f(T instanceof Error?T.message:String(T)),l(!1))})},[e]);return o.useEffect(()=>{p.current+=1,u.current=0,s([]),a(!1),m(!1),f(null),l(!1)},[e]),{items:n,hasMore:r,loading:i,loaded:c,error:h,load:d}}function Aa({projectId:e,openTasks:n,className:s=""}){const r=H(),a=o.useMemo(()=>n.filter(u=>tn.has(u.status)).sort(Ra),[n]),i=o.useMemo(()=>n.filter(u=>u.status==="pending").sort(Sa),[n]),l=In(a,e),c=In(i,e),m=Ca(e),[h,f]=o.useState(Na);o.useEffect(()=>{try{localStorage.setItem(As,h?"1":"0")}catch{}},[h]),o.useEffect(()=>{h&&m.load("first")},[h,m.load]);const p=()=>f(u=>!u);return t.jsx("aside",{"aria-label":r.taskPanel.ariaLabel,className:`flex flex-col rounded-lg border border-hairline bg-surface ${s}`,children:t.jsxs("div",{children:[t.jsx(Bn,{title:r.taskPanel.inProgressTitle,section:l,emptyHint:r.taskPanel.emptyInProgress}),t.jsx(Bn,{title:r.taskPanel.pendingTitle,section:c,emptyHint:r.taskPanel.emptyPending}),t.jsxs("div",{children:[t.jsxs("button",{type:"button",onClick:p,"aria-expanded":h,className:"flex w-full items-center justify-between px-3 py-2 text-left text-xs font-normal uppercase tracking-[0.05em] text-og-500 transition-colors hover:bg-og-50/40",children:[t.jsx("span",{children:r.taskPanel.doneTitle}),t.jsx("span",{className:"font-normal normal-case text-accent",children:h?r.taskPanel.collapse:r.taskPanel.view})]}),h&&t.jsx(Da,{state:m})]})]})})}function Bn({title:e,section:n,emptyHint:s}){const r=H();return t.jsxs("section",{"aria-label":e,className:"border-b border-hairline",children:[t.jsxs("div",{className:"px-3 py-2 text-xs font-normal uppercase tracking-[0.05em] text-og-500",children:[e," ",t.jsxs("span",{className:"text-og-400",children:["(",n.total,")"]})]}),n.items.length===0?t.jsx("div",{className:"px-3 pb-3 text-xs text-og-400",children:s}):t.jsxs("div",{className:"divide-y divide-hairline",children:[n.items.map(a=>t.jsx(Ds,{task:a},a.id)),n.hasMore&&t.jsx("button",{type:"button",onClick:n.loadMore,className:"w-full px-3 py-2 text-center text-xs text-accent transition-colors hover:bg-og-50/40",children:r.taskPanel.loadMore})]})]})}function Da({state:e}){const n=H(),s=e.loaded&&!e.error&&e.items.length===0;return t.jsxs("div",{className:"divide-y divide-hairline",children:[e.items.map(r=>t.jsx(Ds,{task:r},r.id)),e.error&&t.jsx("div",{className:"px-3 py-2 text-xs text-accent",children:n.common.loadFailed(e.error)}),s&&t.jsx("div",{className:"px-3 pb-3 pt-1 text-xs text-og-400",children:n.taskPanel.emptyDone}),e.loading&&e.items.length===0&&t.jsx("div",{className:"px-3 py-3 text-center text-xs text-og-400",children:n.common.loading}),e.hasMore&&t.jsx("button",{type:"button",onClick:()=>e.load("more"),disabled:e.loading,className:"w-full px-3 py-2 text-center text-xs text-accent transition-colors hover:bg-og-50/40 disabled:opacity-50",children:e.loading?n.common.loading:n.taskPanel.loadMore})]})}function Ds({task:e}){const n=H(),s=Le(),{show:r}=je(),[a,i]=o.useState(!1),l=Fe(e.phase)?e.specReviewRound??0:e.reviewRound,c=e.status==="pending"&&e.preferredAgentId==="",m=c?n.taskDetail.editTask:e.status==="pending"?n.taskDetail.startTask:e.status==="review"?n.taskDetail.restartReview:e.status==="approved"?n.taskDetail.retryPreMergeCheck:n.taskDetail.retryCurrentStep,h=e.attention?gs(n,e.attention,e.status):null,f=()=>s(Pe(e.projectId,e.id)),p=async()=>{if(c||e.postApproveRevoked||e.status==="review"&&Wn(e)){f();return}i(!0);try{await M.tasks.advance(e.id),r({kind:"success",title:n.taskDetail.advanceSucceededTitle})}catch(u){r({kind:"error",title:n.taskDetail.advanceFailedTitle,body:n.taskDetail.actionFailedBody,details:u instanceof Error?u.message:String(u)})}finally{i(!1)}};return t.jsxs("div",{className:"px-3 py-2",children:[t.jsx("div",{className:"flex items-center gap-2 text-sm",children:t.jsxs("button",{type:"button",onClick:f,className:"flex min-w-0 flex-1 items-center gap-2 text-left",children:[t.jsx("span",{className:"shrink-0 font-mono text-xs text-og-500",title:e.id,children:un(e.id)}),t.jsx("span",{className:"min-w-0 flex-1 truncate text-og-1000",title:e.title,children:e.title}),l>0&&t.jsx("span",{"aria-label":n.agents.round(l),className:"shrink-0 text-xs text-og-400",children:n.taskPanel.round(l)}),t.jsx(dn,{task:e,className:"shrink-0"})]})}),e.attention&&h&&t.jsxs("div",{className:"mt-2 rounded border border-accent/25 bg-accent-soft/60 px-2 py-1.5 text-xs text-accent",children:[t.jsxs("button",{type:"button",onClick:f,className:"block w-full text-left",children:[t.jsx("span",{className:"font-medium",children:h.title}),t.jsx("span",{className:"mt-0.5 block text-og-700",children:h.guidance})]}),t.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1.5",children:cn(e.attention,e.status).map(u=>t.jsx("button",{type:"button",disabled:u==="advance"&&a,onClick:()=>u==="advance"?void p():f(),className:u==="advance"?"btn-primary":"btn-secondary",children:u==="advance"?a?n.taskDetail.advancing:m:u==="verdict"?n.taskDetail.handleReview:u==="cancel"?n.taskDetail.cancelConfirmLabel:n.taskDetail.retryTask},u))}),t.jsxs("details",{open:h.expandDetails,className:"mt-1.5 text-og-500",children:[t.jsx("summary",{className:"cursor-pointer select-none text-accent",children:n.common.technicalDetails}),t.jsxs("div",{className:"mt-1 whitespace-pre-wrap break-words font-mono",children:[e.attention.reason,`
|
|
13
|
-
`,e.attention.runbook]})]})]})]})}const Pa=[],Ps="baxian.taskPanel.open";function La(){try{return localStorage.getItem(Ps)!=="0"}catch{return!0}}function Ea(){const{id:e}=At(),n=Le(),s=H(),{show:r}=je(),{refresh:a}=at(),[i,l]=o.useState(null),[c,m]=o.useState(null),[h,f]=o.useState(!1),[p,u]=o.useState(!1),d=o.useRef(null),[x,b]=o.useState(La),[y,T]=o.useState(!1),[C,A]=o.useState(""),[w,k]=o.useState(!1),[j,v]=o.useState(null),D=o.useRef(0),{data:P,loaded:I,error:O}=pn(),{data:J,error:E}=Rs(e),W=(O==null?void 0:O.message)??null,re=(E==null?void 0:E.message)??null,te=J??Pa,X=new Map((P??[]).map(q=>[q.id,q])),V=c??W??re,ae=o.useCallback(async q=>{const ie=++D.current;try{const me=await M.projects.get(q);if(ie!==D.current)return;l(me),m(null)}catch(me){if(ie!==D.current)return;m(me instanceof Error?me.message:String(me))}},[]);o.useEffect(()=>{e&&(l(null),m(null),ae(e))},[e,ae]),o.useEffect(()=>{y||(A(""),v(null))},[y]),o.useEffect(()=>{try{localStorage.setItem(Ps,x?"1":"0")}catch{}},[x]);const z=(i==null?void 0:i.agent.flat().length)??0,le=z===0,ne=!!i&&C.trim()===i.id,ge=async()=>{if(!(!i||!ne||w)){k(!0),v(null);try{await M.projects.delete(i.id),await a(),r({kind:"success",title:s.projectPage.deletedToastTitle(i.id)}),T(!1),n("/")}catch(q){v(q instanceof Error?q.message:String(q))}finally{k(!1)}}};return i?t.jsxs("div",{children:[t.jsxs(Ns,{children:[t.jsx("button",{type:"button",onClick:()=>u(!0),className:"btn-ghost",children:s.projectPage.newTaskButton}),t.jsx(Dt,{ariaLabel:s.projectPage.menuAriaLabel(i.id),menuClassName:"min-w-[180px]",triggerRef:d,children:q=>t.jsxs(t.Fragment,{children:[!x&&t.jsx(ke,{onClick:()=>{q(),b(!0)},children:s.projectPage.showTaskPanel}),t.jsx(ke,{onClick:()=>{q(),f(!0)},children:s.projectPage.addAgent}),t.jsx("div",{role:"none",className:"my-1 border-t border-hairline"}),t.jsx(ke,{onClick:()=>{q(),T(!0)},disabled:!le,title:le?void 0:s.projectPage.deleteAgentsFirstHint(z),children:s.projectPage.deleteProjectMenuItem})]})})]}),V&&t.jsx("div",{className:"mb-4 text-sm text-accent",children:s.common.loadFailed(V)}),t.jsxs("div",{className:"mb-6 flex items-baseline gap-x-3",children:[t.jsx("h1",{className:"min-w-0 truncate font-display text-sm font-semibold tracking-tight text-og-1000",title:i.id,children:i.id}),t.jsx("span",{className:"hidden min-w-0 truncate font-mono text-xs text-og-500 sm:inline-block",title:i.repo,children:i.repo})]}),t.jsxs("div",{className:"flex flex-col gap-4 lg:flex-row lg:items-start",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:"mb-3 flex h-8 items-center gap-2",children:t.jsx("h2",{className:"font-display text-xs font-semibold uppercase tracking-[0.06em] text-og-500",children:"Agents"})}),i.agent.flat().length===0?t.jsx("div",{className:"mb-8 rounded-lg border border-hairline bg-surface py-6 text-center text-sm text-og-500",children:s.projectPage.noAgentsYet}):t.jsx("div",{className:"mb-8 space-y-5",children:i.agent.map((q,ie)=>t.jsx(ys,{team:q,projectId:i.id,agentsById:X,agentsLoaded:I,agentsError:!!O,tasks:te,onDeleted:()=>{ae(i.id)},terminalMode:"embedded-full"},q.map(me=>me.id).join(":")||ie))})]}),x&&t.jsxs("div",{className:"w-full lg:w-[340px] lg:shrink-0 xl:w-[380px]",children:[t.jsxs("div",{className:"mb-3 flex h-8 items-center justify-between gap-2",children:[t.jsx("h2",{className:"font-display text-xs font-semibold uppercase tracking-[0.06em] text-og-500",children:"Tasks"}),t.jsx("button",{type:"button",onClick:()=>{var q;b(!1),(q=d.current)==null||q.focus()},"aria-label":s.projectPage.closeTaskPanel,className:"flex h-7 w-7 items-center justify-center rounded text-og-500 transition-colors hover:bg-og-50 hover:text-og-1000",children:t.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[t.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),t.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),t.jsx(Aa,{projectId:i.id,openTasks:te})]})]}),t.jsx(ws,{open:h,projectId:i.id,onClose:()=>f(!1),onCreated:()=>{ae(i.id)}}),t.jsx(mn,{open:p,projectId:i.id,onClose:()=>u(!1),onCreated:q=>n(Pe(q.projectId,q.id))}),t.jsx(Re,{open:y,onClose:()=>{w||T(!1)},title:s.projectPage.deleteModalTitle,size:"sm",footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:()=>T(!1),disabled:w,className:"btn-secondary",children:s.common.cancel}),t.jsx("button",{type:"button",onClick:()=>void ge(),disabled:!ne||w,className:"btn-primary",children:w?s.common.deleting:s.projectPage.confirmDeleteButton})]}),children:t.jsxs("div",{className:"space-y-4",children:[t.jsxs("p",{className:"text-sm text-og-700",children:[s.projectPage.deleteBodyLead,t.jsx("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:C,onChange:q=>A(q.target.value),placeholder:i.id,autoComplete:"off",autoCorrect:"off",spellCheck:!1,disabled:w,"aria-label":s.projectPage.confirmInputAriaLabel,className:"w-full rounded border border-hairline bg-surface px-3 py-2 font-mono text-sm text-og-1000 focus:border-accent focus:outline-none"}),j&&t.jsx("div",{className:"rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-xs text-accent",children:j})]})})]}):c?t.jsx("div",{className:"text-sm text-accent",children:s.common.loadFailed(c)}):t.jsx("div",{className:"text-sm text-og-500",children:s.common.loading})}const Ls={approve:"pill pill-live","request-changes":"pill pill-warn",comment:"pill"};function Es(e){const n=e.some(i=>i.roundToken!==void 0),s=i=>n?i.roundToken!==void 0:i.kind==="review",r=[];let a=[];for(const i of e)s(i)?(r.push({items:a,review:i}),a=[]):a.push(i);return a.length>0&&r.push({items:a}),r}function nt(e,n){const s=e.id||e.commitSha||e.createdAt||e.body||n;return e.sourceKey!==void 0?JSON.stringify([e.kind,e.sourceKey,s]):`${e.kind}-${s}`}function Et(e){if(e.id)return e.sourceKey!==void 0?`pr-${e.kind}.${e.sourceKey}.${e.id}`:`pr-${e.kind}-${e.id}`}function $s(e,n){return e.review?`round-${nt(e.review,n)}`:`round-in-progress-${e.items[0]?nt(e.items[0],n):n}`}function Is(e){const n=e.closedUnmergedAnchor;return[e.reviewRound,e.latestHeadSha??"",e.status,e.reviewDispatchedAt??"",e.prFeedbackReceivedAt??"",e.prNumber??"",e.reviewConversationUpdatedAt??"",n===void 0?"":`${n.generation}/${n.cleared===!0?"reopened":"closed"}`].join(":")}const $a=4e3,Ia=6e4;function Bs(e,n){const[s,r]=o.useState(null),[a,i]=o.useState(!1),[l,c]=o.useState(null),[m,h]=o.useState(!1),[f,p]=o.useState(null),[u,d]=o.useState(0),x=o.useRef(e),b=o.useRef(n),y=o.useRef(0),T=o.useRef(0),C=o.useRef(void 0),A=o.useRef(0),w=o.useRef(null);o.useEffect(()=>{const j=()=>{w.current!==null&&(w.current=null,h(!1),p(null))};x.current!==e&&(x.current=e,r(null),i(!1),p(null),T.current=0,j()),b.current!==n&&(b.current=n,T.current=0,j());const v=++y.current;return c(null),M.tasks.prReview(e).then(D=>{if(y.current===v)if(r(D),i(!0),D.available&&D.error&&T.current<3){T.current+=1;const P=D.rateLimited?Ia*2**(T.current-1):$a*T.current;C.current=setTimeout(()=>d(I=>I+1),P)}else D.error||(T.current=0)}).catch(D=>{y.current===v&&(c(D instanceof Error?D.message:String(D)),r(null),i(!0))}),()=>{clearTimeout(C.current),C.current=void 0}},[e,n,u]);const k=o.useCallback(()=>{if(w.current!==null)return;const j=++A.current;w.current=j,h(!0),p(null),M.tasks.prReviewRefresh(x.current).then(v=>{if(w.current===j){if(v.available&&(v.error!==void 0||v.rateLimited===!0)){p(v.error??"rate limited");return}clearTimeout(C.current),C.current=void 0,y.current+=1,T.current=0,r(v),i(!0),c(null)}}).catch(v=>{w.current===j&&p(v instanceof Error?v.message:String(v))}).finally(()=>{w.current===j&&(w.current=null,h(!1))})},[]);return{data:s,loaded:a,error:l,refresh:k,refreshing:m,refreshError:f}}function Ba(e){const n=new Date(e);if(Number.isNaN(n.getTime()))return e;const s=r=>String(r).padStart(2,"0");return`${n.getFullYear()}-${s(n.getMonth()+1)}-${s(n.getDate())} ${s(n.getHours())}:${s(n.getMinutes())}:${s(n.getSeconds())}`}function Fs({data:e,onRefresh:n,refreshing:s,refreshError:r}){const a=H(),i=e.autoRefresh===!0?e.autoRefreshIntervalMs:void 0,[l,c]=o.useState(void 0),m=o.useRef(Date.now());return o.useEffect(()=>{m.current=Date.now()},[e]),o.useEffect(()=>{if(i===void 0||i<=0){c(void 0);return}const h=()=>{const p=Date.now()-m.current;c(Math.ceil((i-p%i)/1e3))};h();const f=setInterval(h,1e3);return()=>clearInterval(f)},[i,e]),e.available?t.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-og-400",children:[e.fetchedAt&&t.jsx("span",{children:a.prReview.fetchedAtLabel(Ba(e.fetchedAt))}),e.autoRefresh===!1&&t.jsx("span",{children:a.prReview.autoRefreshStopped}),e.autoRefresh===!0&&l!==void 0&&t.jsx("span",{children:a.prReview.nextCheck(l)}),t.jsx("button",{type:"button",className:"text-accent hover:text-accent-hover disabled:opacity-60",onClick:n,disabled:s,children:s?a.prReview.refreshing:a.prReview.refresh}),r&&t.jsx("span",{className:"text-accent",children:a.prReview.refreshFailed(r)})]}):null}function Fa({role:e,label:n,summary:s,badge:r,onClick:a}){const i=H();return t.jsxs("button",{type:"button",onClick:a,className:"card flex w-full items-center gap-2 px-3 py-2 text-left text-sm",children:[t.jsx("span",{className:"shrink-0 min-w-[1.75rem] text-xs tracking-wide text-og-600",children:e==="qa"?i.review.roleQa:e==="user"?i.review.roleUser:i.review.roleDev}),t.jsx("span",{className:"shrink-0 text-og-800",children:n}),r,t.jsx("span",{className:"min-w-0 flex-1 truncate text-og-500",children:s}),t.jsx("span",{"aria-hidden":!0,className:"shrink-0 text-og-300",children:"›"})]})}function Ma(e){return{"no-pr":e.prReview.reasonNoPr,"driver-unavailable":e.prReview.reasonDriverUnavailable}}function Oa(e){return(e==null?void 0:e.trim().split(`
|
|
14
|
-
`,1)[0])??""}function _a(e){if(!(e.kind!=="review-comment"||!e.path))return e.line!==void 0?`${e.path}:${e.line}`:e.path}function Ha(e,n){return n.bodyTruncated?e.prReview.truncatedSuffix:""}function qa(e,n){const s=Oa(n.body),r=Ha(e,n);if(n.kind==="review-comment"){const a=_a(n);if(n.inReplyTo){const i=[n.author,a,s].filter(l=>!!l);if(i.length>0)return`${i.join(" · ")}${r}`}return a&&s?`${a} · ${s}${r}`:`${s||a||e.prReview.inlineComment}${r}`}return n.kind==="issue-comment"?n.author&&s?`${n.author} · ${s}${r}`:`${s||n.author||e.prReview.comment}${r}`:`${s||e.prReview.noReviewBodyFallback}${r}`}function Ua(e,n){return n.verdict!==void 0||n.kind==="review"?e.review.reviewTurnLabel:n.kind==="review-comment"?n.inReplyTo?e.review.responseTurnLabel:e.prReview.inlineComment:e.prReview.comment}function Ga(e){return e.verdict!==void 0?"qa":e.kind==="issue-comment"||e.inReplyTo?"dev":"qa"}function Wa({task:e}){const n=H(),s=Le(),r=Is(e),{data:a,loaded:i,error:l,refresh:c,refreshing:m,refreshError:h}=Bs(e.id,r),f=Fe(e.phase)?n.prReview.specReviewHeading:n.prReview.codeReviewHeading;function p(x){s(`/tasks/${encodeURIComponent(e.id)}/pr-review${x?`#${x}`:""}`)}if(l)return t.jsx(Je,{title:f,children:t.jsx("div",{className:"text-sm text-accent",children:n.review.loadFailed(l)})});if(!i)return t.jsx(Je,{title:f,children:t.jsx("div",{className:"text-sm text-og-400",children:n.review.loadingRecords})});if(!(a!=null&&a.available)){const x=Ma(n);return t.jsx(Je,{title:f,children:t.jsx("div",{className:"text-sm text-og-400",children:x[(a==null?void 0:a.reason)??"no-pr"]??x["no-pr"]})})}const u=t.jsx(Fs,{data:a,onRefresh:c,refreshing:m,refreshError:h});if(a.items.length===0)return t.jsxs(Je,{title:f,children:[u,a.truncated?t.jsx("div",{className:"text-sm text-accent",children:n.prReview.listTruncated}):a.error?t.jsx("div",{className:"text-sm text-accent",children:n.prReview.fetchFailed(a.error)}):t.jsx("div",{className:"text-sm text-og-400",children:n.review.notStarted})]});const d=Es(a.items);return t.jsxs(Je,{title:f,children:[u,a.error&&t.jsx("div",{className:"text-xs text-accent",children:n.prReview.partialFetchFailed(a.error)}),a.truncated&&t.jsx("div",{className:"text-xs text-accent",children:n.prReview.listTruncated}),d.map((x,b)=>t.jsx(za,{round:x,index:b,onOpen:p},$s(x,String(b))))]})}function Je({title:e,children:n}){return t.jsxs("div",{children:[t.jsx("div",{className:"mb-1.5 text-xs text-og-700",children:e}),t.jsx("div",{className:"space-y-3",children:n})]})}function za({round:e,index:n,onOpen:s}){const r=H(),a=e.review?r.agents.round(n+1):r.status.in_progress;return t.jsxs("div",{children:[t.jsx("div",{className:"mb-1 text-xs text-og-400",children:a}),t.jsxs("div",{className:"space-y-1.5",children:[e.items.map((i,l)=>t.jsx(Fn,{item:i,onOpen:s},nt(i,`${n}-${l}`))),e.review&&t.jsx(Fn,{item:e.review,onOpen:s})]})]})}function Fn({item:e,onOpen:n}){const s=H(),r=e.verdict,a=r?t.jsx("span",{className:Ls[r],children:r}):e.kind==="review"&&e.reviewState?t.jsx("span",{className:"pill",children:e.reviewState}):void 0;return t.jsx(Fa,{role:Ga(e),label:Ua(s,e),badge:a,summary:qa(s,e),onClick:()=>n(Et(e))})}function Ka({task:e}){const n=H();return e.prNumber===void 0?null:t.jsxs("section",{className:"mt-4","aria-label":n.review.sectionTitle,children:[t.jsx("div",{className:"mb-2 text-sm text-og-700",children:n.review.sectionTitle}),t.jsx(Wa,{task:e})]})}const Va=Vn;function Qa(e,n){if(!e||!n)return null;const s=e.match(/^(https?:\/\/[^/]+\/[^/]+\/[^/]+)\/pull\/\d+/);if(!s)return null;const r=n.split("/").map(encodeURIComponent).join("/");return`${s[1]}/tree/${r}`}function Mn(e){if(!/^[1-9]\d*$/.test(e.trim()))return;const n=Number(e);return Number.isSafeInteger(n)?n:void 0}function Ya(e){return e.status==="review"&&!Fe(e.phase)}function kt({children:e,open:n}){const s=H();return t.jsxs("details",{open:n,className:"mt-2 text-xs text-og-500",children:[t.jsx("summary",{className:"cursor-pointer select-none text-accent",children:s.common.technicalDetails}),t.jsx("div",{className:"mt-1 whitespace-pre-wrap break-words font-mono",children:e})]})}function Ja(){const{taskId:e=""}=At();return t.jsx(Xa,{taskId:e},e)}function Xa({taskId:e}){var xn;const n=Le(),s=H(),{show:r}=je(),a=ln(),[i,l]=o.useState(!1),[c,m]=o.useState(!1),[h,f]=o.useState(!1),[p,u]=o.useState(!1),[d,x]=o.useState(!1),[b,y]=o.useState("spec"),[T,C]=o.useState(""),[A,w]=o.useState(!1),[k,j]=o.useState(!1),[v,D]=o.useState(!1),[P,I]=o.useState(""),[O,J]=o.useState(!1),[E,W]=o.useState(""),[re,te]=o.useState(!1),[X,V]=o.useState(null),{data:ae,loaded:z,error:le}=Ss(e),{projects:ne,error:ge}=at(),{data:q,loaded:ie,error:me}=pn(),{activeAgentId:xe,activateAgentCard:ye}=vs(),N=X??ae,we=N!==null&&Ya(N),pe=we&&(re||((xn=N==null?void 0:N.attention)==null?void 0:xn.recommendedActions.includes("verdict"))===!0),L=(le==null?void 0:le.message)??null,G=N?ne==null?void 0:ne.find(g=>g.id===N.projectId):void 0,S=G===void 0?"unknown":G.merge==="auto"?"auto":"manual",U=ne===null&&ge===null,_=o.useMemo(()=>new Map((q??[]).map(g=>[g.id,g])),[q]);o.useEffect(()=>{X&&ae&&ae.updatedAt>=X.updatedAt&&V(null)},[X,ae]),o.useEffect(()=>{te(!1)},[N==null?void 0:N.status,N==null?void 0:N.reviewRound]);const se=g=>{V(g)},B=g=>({body:s.taskDetail.actionFailedBody,details:g instanceof Error?g.message:String(g)}),R=(g,F)=>{const Y=F??(g.status==="review"?"qa":"dev");return g.status==="pending"?g.preferredAgentId===""?s.taskDetail.editTask:s.taskDetail.startTask:Y==="qa"&&g.status!=="review"?s.taskDetail.startReview:g.status==="review"?s.taskDetail.restartReview:g.status==="approved"?s.taskDetail.retryPreMergeCheck:s.taskDetail.retryCurrentStep},$=()=>U?s.taskDetail.loadingMergeSetting:S==="auto"?s.taskDetail.confirmAndMerge:S==="manual"?s.taskDetail.confirmComplete:s.taskDetail.confirmResult,Z=async()=>{if(!N)return;const g=Vn.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})){m(!0);try{const Y=await M.tasks.update(N.id,{status:"cancelled"});se(Y),r({kind:"success",title:Y.status==="cancelled"?s.taskDetail.cancelledToastTitle:s.taskDetail.cancelCleanupToastTitle})}catch(Y){r({kind:"error",title:s.taskDetail.cancelFailedTitle,...B(Y)})}finally{m(!1)}}},K=async(g,F,Y)=>{u(!0);try{const de=await M.tasks.advance(g.id,{executor:F,...g.status==="pending"&&g.preferredAgentId?{agentId:g.preferredAgentId}:{},...Y??{}});se(de),x(!1),r({kind:"success",title:s.taskDetail.advanceSucceededTitle})}catch(de){r({kind:"error",title:s.taskDetail.advanceFailedTitle,...B(de)})}finally{u(!1)}},ee=async g=>{var ve;if(!N)return;if(N.status==="pending"&&N.preferredAgentId===""){l(!0);return}const F=g??(N.status==="review"?"qa":"dev"),Y=R(N,F);if(F==="qa"&&Wn(N)){y(N.phase??"spec"),C(((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:Y}))return;await K(N,F,{confirmRevoked:!0});return}await a({title:s.taskDetail.advanceConfirmTitle(Y),body:N.status==="pending"?s.taskDetail.startTaskConfirmBody(N.id,N.preferredAgentId):F==="qa"&&N.status==="review"?s.taskDetail.restartReviewConfirmBody(N.id):F==="qa"?s.taskDetail.startReviewConfirmBody(N.id):N.status==="approved"?s.taskDetail.retryPreMergeConfirmBody:s.taskDetail.retryCurrentStepConfirmBody(N.id),confirmLabel:Y})&&await K(N,F)},be=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 F=await M.tasks.retry(N.id);r({kind:"success",title:s.taskDetail.retryCreatedToastTitle(F.id)}),n(Pe(F.projectId,F.id))}catch(F){r({kind:"error",title:s.taskDetail.retryFailedTitle,...B(F)})}finally{f(!1)}}},Ve=async()=>{if(N&&await a({title:s.taskDetail.markCompleteConfirmTitle,body:s.taskDetail.markCompleteConfirmBody(N.prNumber??0),confirmLabel:s.taskDetail.verdictComplete})){w(!0);try{const g=await M.tasks.verdict(N.id,{action:"complete"});se(g),r({kind:"success",title:s.taskDetail.markCompleteToastTitle})}catch(g){r({kind:"error",title:s.taskDetail.markCompleteFailedTitle,...B(g)})}finally{w(!1)}}},Me=async()=>{if(N&&await a({title:s.taskDetail.continueConfirmTitle,body:s.taskDetail.continueConfirmBody(N.reviewRound+1),confirmLabel:s.taskDetail.verdictContinue})){j(!0);try{const g=await M.tasks.verdict(N.id,{action:"continue"});se(g),r({kind:"success",title:s.taskDetail.continuedToastTitle(g.reviewRound)})}catch(g){r({kind:"error",title:s.taskDetail.continueFailedTitle,...B(g)})}finally{j(!1)}}},Ee=async(g,F)=>{if(N){D(!0);try{const Y=await M.tasks.verdict(N.id,{action:g.verdict,...g.comments!==void 0?{comments:g.comments}:{}});se(Y),I(""),r({kind:"success",title:F.success})}catch(Y){r({kind:"error",title:F.failure,...B(Y)})}finally{D(!1)}}},$e=async()=>{N&&await a({title:s.taskDetail.specApproveConfirmTitle,body:s.taskDetail.specApproveConfirmBody(N.id),confirmLabel:s.taskDetail.specApprove})&&await Ee({verdict:"approve"},{success:s.taskDetail.specApprovedToastTitle,failure:s.taskDetail.specApproveFailedTitle})},Ce=async()=>{const g=P.trim();g&&await Ee({verdict:"request-changes",comments:g},{success:s.taskDetail.specRejectedToastTitle,failure:s.taskDetail.specRejectFailedTitle})},Te=async g=>{if(!N)return;const F=E.trim();if(!(g==="request-changes"&&!F||!await a({title:g==="pass"?s.taskDetail.codePassConfirmTitle:s.taskDetail.codeRejectConfirmTitle,body:s.taskDetail.codeVerdictConfirmBody,confirmLabel:g==="pass"?s.taskDetail.codePass:s.taskDetail.codeRequestChanges}))){J(!0);try{const de=await M.tasks.verdict(N.id,{action:g,...F?{comments:F}:{}});se(de),W(""),r({kind:"success",title:s.taskDetail.codeVerdictSubmittedTitle})}catch(de){r({kind:"error",title:s.taskDetail.codeVerdictFailedTitle,...B(de)})}finally{J(!1)}}},it=()=>{var g;(g=document.getElementById("task-verdict-controls"))==null||g.scrollIntoView({behavior:"smooth",block:"center"})},ot=async()=>{if(!N||U)return;const g=N.prNumber??0,F=S==="auto"?s.taskDetail.confirmAutoMergeTitle(g):S==="manual"?s.taskDetail.confirmManualCompleteTitle:s.taskDetail.confirmResultTitle,Y=S==="auto"?s.taskDetail.confirmAutoMergeBody(g):S==="manual"?s.taskDetail.confirmManualCompleteBody(g):s.taskDetail.confirmResultBody;if(await a({title:F,body:Y,confirmLabel:$()})){w(!0);try{const de=await M.tasks.verdict(N.id,{action:"confirm-merge"});se(de),r({kind:"success",title:de.status==="merged"?s.taskDetail.confirmedMergedToastTitle:s.taskDetail.confirmedCompleteToastTitle})}catch(de){r({kind:"error",title:s.taskDetail.confirmFailedTitle,...B(de)})}finally{w(!1)}}};return t.jsxs("div",{children:[t.jsx("button",{type:"button",onClick:()=>n(-1),className:"btn-ghost mb-3",children:s.common.back}),L&&!N&&t.jsx("div",{className:"text-sm text-accent",children:s.common.loadFailed(L)}),z&&!N&&!L&&t.jsx("div",{className:"text-sm text-accent",children:s.taskDetail.taskNotFound(e)}),!N&&!L&&!z&&t.jsx("div",{className:"text-sm text-og-500",children:s.common.loading}),N&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mb-4",children:t.jsxs("h1",{className:"flex min-w-0 items-baseline gap-2",children:[t.jsx("span",{className:"shrink-0 font-mono text-sm text-og-400",children:N.id}),t.jsx("span",{className:"min-w-0 truncate font-display text-sm font-semibold tracking-tight text-og-1000",title:N.title,children:N.title})]})}),t.jsxs("div",{className:"grid grid-cols-1 items-start gap-6 lg:grid-cols-2",children:[t.jsx("section",{className:"min-w-0",children:lt(N)}),t.jsx("aside",{className:"min-w-0 space-y-4",children:Oe(N)})]})]}),i&&N&&t.jsx(mn,{mode:"edit",open:!0,onClose:()=>l(!1),task:N,onUpdated:se}),d&&N&&t.jsx(Re,{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&&Mn(T)===void 0,className:"btn-primary",children:p?s.taskDetail.advancing:s.taskDetail.reviewRecoverySubmit})]}),children:t.jsxs("form",{id:"review-recovery-form",className:"space-y-4",onSubmit:g=>{g.preventDefault();const F=N.prNumber??Mn(T);F===void 0||p||K(N,"qa",{stage:b,...N.prNumber===void 0?{prNumber:F}:{}})},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:T,required:!0,disabled:p,onChange:g=>C(g.target.value),placeholder:s.taskDetail.reviewRecoveryPrNumberPlaceholder,className:he})]}),t.jsxs("div",{children:[t.jsx("label",{htmlFor:"review-recovery-stage",className:"mb-1 block text-sm text-og-700",children:s.taskDetail.reviewRecoveryStageLabel}),t.jsxs("select",{id:"review-recovery-stage",value:b,required:!0,disabled:p||N.phase!==void 0,onChange:g=>y(g.target.value),className:he,children:[t.jsx("option",{value:"spec",children:s.taskDetail.reviewRecoveryStageSpec}),t.jsx("option",{value:"code",children:s.taskDetail.reviewRecoveryStageCode})]})]})]})})]});function lt(g){var mt;const F=g.preferredAgentId==="",Y=g.status==="approved"&&g.prNumber!==void 0,de=g.status==="merge-ready"&&g.prNumber!==void 0,ve=g.status==="spec-ready",Ae=pe,$t=g.status==="max_rounds"&&!Fe(g.phase),dt=g.status==="max_rounds"&&Fe(g.phase),De=Qn(g.prUrl),ut=Qa(De??void 0,g.branch??""),_e=g.attention?gs(s,g.attention,g.status):null,It=(q??[]).some(ht=>Gn(ht,g.id));return t.jsxs("div",{children:[L&&t.jsx("div",{className:"mb-4 text-sm text-accent",children:s.common.loadFailed(L)}),g.branchCleanupPending&&t.jsxs("div",{className:"mb-4 rounded-md border border-accent/25 bg-accent-soft/60 px-3 py-2.5 text-xs text-accent",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.branchCleanupPendingTitle}),t.jsx("div",{className:"mt-1 text-og-700",children:s.taskDetail.branchCleanupPendingBody}),t.jsx(kt,{children:g.branchCleanupPending.reason})]}),g.branchCleanupSkipped&&t.jsxs("div",{className:"mb-4 rounded-md border border-hairline bg-og-25 px-3 py-2.5 text-xs text-og-700",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.branchCleanupSkippedTitle}),t.jsx("div",{className:"mt-1",children:s.taskDetail.branchCleanupSkippedBody}),t.jsx(kt,{children:g.branchCleanupSkipped.reason})]}),F&&t.jsx("div",{className:"mb-4 rounded-md border border-accent/25 bg-accent-soft/60 px-3 py-2.5 text-xs text-accent",children:g.status==="pending"?s.taskDetail.unassignedPendingNotice:s.taskDetail.unassignedReadonlyNotice}),t.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-3",children:[t.jsx(dn,{task:g,className:"text-sm"}),It&&t.jsx("span",{className:"text-sm text-og-500",title:s.taskDetail.dispatchingHint,children:s.taskDetail.dispatching}),(g.specReviewRound??0)>0&&t.jsx("span",{className:"text-sm text-og-500",children:s.taskDetail.specReviewRound(g.specReviewRound??0)}),g.reviewRound>0&&t.jsx("span",{className:"text-sm text-og-500",children:s.taskDetail.codeReviewRound(g.reviewRound)})]}),t.jsx("div",{className:"mb-4 flex flex-wrap items-center gap-2",children:qs(g)}),t.jsxs("div",{className:"mb-4 text-sm text-og-500",children:[s.taskDetail.createdAtPrefix,_t(g.createdAt,!1),s.taskDetail.updatedAtPrefix,_t(g.updatedAt,!1),g.origin&&t.jsxs(t.Fragment,{children:[s.taskDetail.originPrefix,t.jsx(Se,{to:Pe(g.projectId,g.origin.taskId),className:"underline hover:text-og-700",children:g.origin.taskId})]})]}),g.attention&&_e&&t.jsxs("div",{className:"mb-4 rounded-lg border border-accent/25 bg-accent-soft p-4 text-sm text-accent",children:[t.jsx("div",{className:"font-semibold",children:_e.title}),t.jsx("div",{className:"mt-1 text-og-700",children:_e.guidance}),t.jsx("div",{className:"mt-1 text-xs text-og-500",children:_t(g.attention.occurredAt)}),t.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:oe(g)}),t.jsx(kt,{open:_e.expandDetails,children:`${g.attention.reason}
|
|
15
|
-
${g.attention.runbook}`})]}),Y&&t.jsxs("div",{className:"mb-4 rounded-lg border border-hairline bg-og-25 p-4 text-sm text-og-800",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.approvedBannerTitle}),t.jsx("div",{className:"mt-1 text-og-700",children:s.taskDetail.approvedBannerBody}),De&&t.jsx("a",{href:De,target:"_blank",rel:"noopener noreferrer",className:"btn-secondary mt-3",children:s.taskDetail.viewPr(g.prNumber??0)})]}),de&&t.jsxs("div",{id:"task-verdict-controls",className:"mb-4 rounded-lg border border-accent/25 bg-accent-soft p-4 text-sm text-accent",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.mergeReadyBannerTitle}),t.jsx("div",{className:"mt-1 text-og-700",children:S==="auto"?s.taskDetail.mergeReadyAutoBody(g.prNumber??0):S==="manual"?s.taskDetail.mergeReadyManualBody(g.prNumber??0):U?s.taskDetail.mergeReadyLoadingBody:s.taskDetail.mergeReadyUnknownBody}),S==="unknown"&&ge&&t.jsx(kt,{children:ge}),De&&t.jsx("a",{href:De,target:"_blank",rel:"noopener noreferrer",className:"btn-secondary mt-3",children:s.taskDetail.viewPr(g.prNumber??0)})]}),ve&&t.jsxs("div",{id:"task-verdict-controls",className:"mb-4 rounded-lg border border-accent-soft bg-accent-soft/40 p-4 text-sm text-accent",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.specReadyBannerTitle}),t.jsx("div",{className:"mt-1 text-og-700",children:s.taskDetail.specReadyNotice(g.specReviewRound??0)}),Qe()]}),Ae&&t.jsxs("div",{id:"task-verdict-controls",className:`mb-4 rounded-lg p-4 text-sm ${((mt=g.attention)==null?void 0:mt.reason)==="review-verdict-overdue"?"border border-accent/25 bg-accent-soft text-accent":"border border-hairline bg-og-25 text-og-800"}`,children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.codeVerdictTitle}),t.jsx("div",{className:"mt-1 text-og-700",children:s.taskDetail.codeVerdictBody}),ct()]}),$t&&t.jsxs("div",{id:"task-verdict-controls",className:"mb-4 rounded-lg border border-accent/25 bg-accent-soft/60 p-4 text-sm text-accent",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.codeMaxRoundsTitle(g.reviewRound)}),t.jsx("div",{className:"mt-1 text-og-700",children:s.taskDetail.codeMaxRoundsBody})]}),dt&&t.jsxs("div",{id:"task-verdict-controls",className:"mb-4 rounded-lg border border-accent/25 bg-accent-soft/60 p-4 text-sm text-accent",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.specMaxRoundsTitle(g.specReviewRound??0)}),t.jsx("div",{className:"mt-1 text-og-700",children:s.taskDetail.specMaxRoundsBody}),Qe()]}),t.jsxs("div",{className:"card mb-4 flex flex-wrap items-center gap-x-6 gap-y-1 p-4 text-sm",children:[t.jsxs("span",{className:"text-og-500",children:["PR:"," ",g.prNumber?De?t.jsxs("a",{href:De,target:"_blank",rel:"noopener noreferrer",className:"text-accent hover:text-accent-hover",children:["#",g.prNumber]}):t.jsxs("span",{className:"font-mono text-og-800",children:["#",g.prNumber]}):t.jsx("span",{className:"text-og-400",children:"—"})]}),t.jsxs("span",{className:"text-og-500",children:["Branch:"," ",g.branch?ut?t.jsx("a",{href:ut,target:"_blank",rel:"noopener noreferrer",className:"font-mono text-accent hover:text-accent-hover",children:g.branch}):t.jsx("span",{className:"font-mono text-og-800",children:g.branch}):t.jsx("span",{className:"text-og-400",children:"—"})]})]}),t.jsx("pre",{className:"card mb-4 whitespace-pre-wrap p-4 text-sm text-og-800",children:g.description||t.jsx("span",{className:"text-og-400",children:s.taskDetail.noDescription})}),t.jsx(Ka,{task:g})]})}function Qe(){return t.jsxs("div",{className:"mt-3 flex flex-col gap-2",children:[t.jsx("textarea",{value:P,onChange:g=>I(g.target.value),placeholder:s.taskDetail.specCommentsPlaceholder,rows:3,disabled:v,className:he}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",disabled:v,onClick:$e,className:"btn-primary",children:v?s.taskDetail.submitting:s.taskDetail.specApproveButton}),t.jsx("button",{type:"button",disabled:v||P.trim()==="",onClick:Ce,title:P.trim()===""?s.taskDetail.specRejectTitleEmpty:s.taskDetail.specRejectTitleReady,className:"btn-secondary",children:v?s.taskDetail.submitting:s.taskDetail.specReject})]})]})}function ct(){return t.jsxs("div",{className:"mt-3 flex flex-col gap-2",children:[t.jsx("textarea",{value:E,onChange:g=>W(g.target.value),placeholder:s.taskDetail.codeCommentsPlaceholder,rows:3,disabled:O,className:he}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",disabled:O,onClick:()=>void Te("pass"),className:"btn-secondary",children:O?s.taskDetail.submitting:s.taskDetail.codePass}),t.jsx("button",{type:"button",disabled:O||E.trim()==="",onClick:()=>void Te("request-changes"),className:"btn-secondary",children:O?s.taskDetail.submitting:s.taskDetail.codeRequestChanges})]})]})}function oe(g){return g.attention?cn(g.attention,g.status).map(F=>F==="advance"?t.jsx("button",{type:"button",disabled:p,onClick:()=>void ee(),className:"btn-primary",children:p?s.taskDetail.advancing:R(g)},F):F==="verdict"?t.jsx("button",{type:"button",onClick:it,className:"btn-primary",children:s.taskDetail.handleReview},F):F==="cancel"?t.jsx("button",{type:"button",disabled:c,onClick:Z,className:"btn-secondary",children:c?s.taskDetail.cancelling:s.taskDetail.cancelConfirmLabel},F):t.jsx("button",{type:"button",disabled:h,onClick:be,className:"btn-secondary",children:h?s.common.retrying:s.taskDetail.retryTask},F)):null}function Oe(g){if(ne===null)return t.jsx("div",{className:"rounded-lg border border-hairline bg-surface px-3 py-6 text-center text-sm text-og-400",children:s.common.loading});const F=(G==null?void 0:G.agent.find(ve=>ve.some(Ae=>Ae.id===g.devAgentId)))??(g.qaAgentId?G==null?void 0:G.agent.find(ve=>ve.some(Ae=>Ae.id===g.qaAgentId)):void 0),Y=F==null?void 0:F.find(ve=>ve.role==="dev"&&ve.id===g.devAgentId),de=g.qaAgentId?F==null?void 0:F.find(ve=>ve.role==="qa"&&ve.id===g.qaAgentId):void 0;return!Y&&!de?t.jsx("div",{className:"rounded-lg border border-hairline bg-surface px-3 py-6 text-center text-sm text-og-400",children:s.taskDetail.noLinkedAgent}):t.jsxs(t.Fragment,{children:[Y?gn(g,Y):t.jsx(On,{role:"dev"}),de?gn(g,de):t.jsx(On,{role:"qa"})]})}function gn(g,F){const Y=_.get(F.id),de=Y??{id:F.id,projectId:g.projectId,runtimeStatus:"unknown",tmuxSessionStatus:"unknown",stale:!0};return t.jsx(bs,{agent:de,projectId:g.projectId,role:F.role,runtime:F.runtime,model:F.model,pendingRestart:ie&&!Y,terminalLoading:!ie&&!Y&&!me,showTaskBinding:!1,terminalMode:"embedded-full",active:xe===F.id,onActivate:()=>ye(F.id),task:g},F.id)}function qs(g){var ht,bn;const Y=g.status==="max_rounds"&&!Fe(g.phase),de=g.status==="merge-ready",ve=g.status==="pending",Ae=Va.has(g.status),$t=Ae&&!!g.preferredAgentId,dt=g.preferredAgentId==="",De=["pending","in_progress","fixing","review","approved"].includes(g.status)&&((ht=g.attention)==null?void 0:ht.reason)!=="bootstrap-marker-clear-failed"&&(((bn=g.attention)==null?void 0:bn.reason)!=="dispatch-failed:ack_unknown"||g.status==="review")&&!(g.status==="pending"&&dt),ut=(g.status==="in_progress"||g.status==="fixing")&&g.qaAgentId!==void 0,_e=Y&&g.prNumber!==void 0,It=_e&&!!g.agentId,mt=we&&!pe;return t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",disabled:!ve,onClick:()=>l(!0),className:"btn-secondary",children:s.taskDetail.editTask}),t.jsx("button",{type:"button",disabled:c,onClick:Z,title:s.taskDetail.cancelForceTitle,className:"btn-secondary",children:c?s.taskDetail.cancelling:s.taskDetail.cancelConfirmLabel}),Ae&&g.replacementTaskId===void 0&&t.jsx("button",{type:"button",disabled:!$t||h,onClick:be,title:dt?s.taskDetail.retryDisabledUnassignedTitle:s.taskDetail.retryEnabledTitle,className:"btn-secondary",children:h?s.common.retrying:s.taskDetail.retryTask}),De&&t.jsx("button",{type:"button",disabled:p,onClick:()=>void ee(),className:"btn-primary",children:p?s.taskDetail.advancing:R(g)}),ut&&t.jsx("button",{type:"button",disabled:p,onClick:()=>void ee("qa"),className:"btn-secondary",children:R(g,"qa")}),mt&&t.jsx("button",{type:"button",onClick:()=>te(!0),className:"btn-secondary",children:s.taskDetail.handleReview}),Y&&t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",disabled:!It||k,onClick:Me,title:s.taskDetail.continueButtonTitle,className:"btn-secondary",children:k?s.taskDetail.continuing:s.taskDetail.verdictContinue}),t.jsx("button",{type:"button",disabled:!_e||A,onClick:Ve,title:s.taskDetail.completeButtonTitle,className:"btn-primary",children:A?s.taskDetail.completing:s.taskDetail.verdictComplete})]}),de&&t.jsx("button",{type:"button",disabled:A||U,onClick:ot,title:U?s.taskDetail.confirmLoadingTitle:s.taskDetail.confirmButtonTitle,className:"btn-primary",children:A?s.taskDetail.confirming:$()})]})}}function On({role:e}){const n=H();return t.jsx("div",{className:"rounded-lg border border-hairline bg-surface px-3 py-6 text-center text-sm text-og-400",children:n.taskDetail.noAgentSlot(e)})}function Za(){const{agentId:e}=At(),{projects:n}=at(),s=H(),r=o.useMemo(()=>{if(e)for(const a of n??[])for(const i of a.agent){const l=i.find(c=>c.id===e);if(l)return{runtime:l.runtime,projectId:a.id}}},[e,n]);return e?t.jsxs("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden border border-hairline bg-surface",children:[t.jsxs("div",{className:"flex h-8 flex-none select-none items-center gap-3 border-b border-hairline bg-page px-3 font-mono text-xs text-og-500",children:[t.jsx("span",{"aria-hidden":!0,className:"block h-1.5 w-1.5 rounded-full bg-og-1000"}),t.jsx("span",{className:"text-og-700",title:Kn(e,r==null?void 0:r.runtime),children:e}),r&&t.jsx(Se,{to:`/project/${encodeURIComponent(r.projectId)}`,className:"ml-auto text-accent",children:s.terminal.backToProject})]}),t.jsx("div",{className:"min-h-0 flex-1",children:t.jsx(Xe,{agentId:e,mode:"full",interactive:!0,arrowKeys:!0})})]}):t.jsx("div",{className:"text-sm text-accent",children:"No agent specified"})}const ei=65536,ti=8e3,ni=["text-[18px] font-bold","text-[17px] font-bold","text-[16px] font-semibold","text-[15px] font-semibold","text-[15px] font-semibold","text-[15px] font-semibold"],si=/^(https?:\/\/|mailto:)/i,ri=/^https?:\/\//i;function ai(e){try{const n=new URL(e).hostname.toLowerCase();return n==="githubusercontent.com"||n.endsWith(".githubusercontent.com")}catch{return!1}}function ii({src:e,alt:n}){const s=H(),[r,a]=o.useState(!1);if(r||ai(e))return t.jsx("img",{src:e,alt:n,loading:"lazy",className:"max-w-full rounded border border-hairline"});let i=e;try{i=new URL(e).hostname}catch{i=e}return t.jsxs("button",{type:"button",onClick:()=>a(!0),className:"inline-flex max-w-full items-center gap-1.5 rounded border border-hairline bg-og-25 px-2 py-1 text-xs text-og-700",children:[t.jsx("span",{className:"shrink-0",children:s.review.loadExternalImage}),n&&t.jsx("span",{className:"min-w-0 truncate text-og-500",children:n}),t.jsx("span",{className:"min-w-0 truncate font-mono text-og-400",children:i})]})}function _n(e,n){let s=-1,r=-2;return a=>(r!==-2&&a>=s&&(r===-1||a<=r)||(s=a,r=e.indexOf(n,a)),r)}function oi(e){const n=/\s/g;let s=-1,r=-2;return a=>{if(r!==-2&&a>=s&&(r===-1||a<=r))return r;s=a,n.lastIndex=a;const i=n.exec(e);return r=i?i.index:-1,r}}function Hn(e,n,s){const r=n+1,a=s.bracket(r);if(a===-1||e[a+1]!=="(")return null;const i=a+2,l=s.paren(i);if(l===-1||l===i)return null;const c=s.whitespace(i);return c!==-1&&c<l?null:{label:e.slice(r,a),url:e.slice(i,l),end:l+1}}class Ms extends Error{}class li{constructor(n){ce(this,"count",0);this.max=n}charge(){if(++this.count>this.max)throw new Ms}}function Ue(e,n,s){const r=[];let a="",i=0;const l={bracket:_n(e,"]"),paren:_n(e,")"),whitespace:oi(e)},c=()=>{a!==""&&(n.charge(),r.push(a),a="")},m=f=>{c(),n.charge(),r.push(f)},h=()=>`${s}-${r.length}`;for(;i<e.length;){const f=e[i];if(f==="`"){const p=e.indexOf("`",i+1);if(p!==-1){const u=e.slice(i+1,p);c(),n.charge(),n.charge(),r.push(t.jsx("code",{className:"rounded bg-og-25 px-1 font-mono text-xs",children:u},h())),i=p+1;continue}}else if(f==="!"&&e[i+1]==="["){const p=Hn(e,i+1,l);if(p){ri.test(p.url)?m(t.jsx(ii,{src:p.url,alt:p.label},h())):a+=e.slice(i,p.end),i=p.end;continue}}else if(f==="["){const p=Hn(e,i,l);if(p){if(si.test(p.url)){c(),n.charge();const u=Ue(p.label,n,`${s}-a${r.length}`);r.push(t.jsx("a",{href:p.url,target:"_blank",rel:"noopener noreferrer",className:"text-accent hover:text-accent-hover",children:u},h()))}else a+=e.slice(i,p.end);i=p.end;continue}}else if(f==="*"){if(e.startsWith("***",i)){const u=e.indexOf("***",i+3);if(u>i+3){c(),n.charge(),n.charge();const d=Ue(e.slice(i+3,u),n,`${s}-bi${r.length}`);r.push(t.jsx("strong",{children:t.jsx("em",{children:d})},h())),i=u+3;continue}}if(e.startsWith("**",i)){const u=e.indexOf("**",i+2);if(u>i+2){c(),n.charge();const d=Ue(e.slice(i+2,u),n,`${s}-b${r.length}`);r.push(t.jsx("strong",{children:d},h())),i=u+2;continue}}const p=e.indexOf("*",i+1);if(p>i+1){c(),n.charge();const u=Ue(e.slice(i+1,p),n,`${s}-i${r.length}`);r.push(t.jsx("em",{children:u},h())),i=p+1;continue}}a+=f,i++}return c(),r}function ci(e,n){const s=[],r=e.split(`
|
|
12
|
+
`)}:{}}),r(),n()}catch(ee){D(ee instanceof Error?ee.message:String(ee))}finally{j(!1)}},ye=()=>{!c||k||(l(c.form),m(null),x(null),w(null),I(!1))},N=({rt:B})=>{if(i.mode==="remote"&&!i.host)return t.jsx("span",{className:"ml-2 text-xs text-og-400",children:a.createAgent.selectHostFirstHint});if(b)return t.jsx("span",{className:"ml-2 text-xs text-og-400",children:a.createAgent.probingLabel});if(!d)return t.jsx("span",{className:"ml-2 text-xs text-og-400",children:"?"});const $=d.runtimes[B];return $?$.ok?t.jsxs("span",{className:"ml-2 text-xs text-probe-ok",children:["✓ ",$.path??""]}):t.jsxs("span",{className:"ml-2 text-xs text-accent",title:$.message,children:["⨯ ",$.message]}):t.jsx("span",{className:"ml-2 text-xs text-og-400",children:"?"})},we=()=>{var R;if(i.mode==="remote"&&!i.host)return null;if(b&&!T)return t.jsx("div",{className:"text-xs text-og-400",children:a.createAgent.tmuxProbingLabel});if(!d)return null;if(d.tmux.ok)return t.jsxs("div",{className:"text-xs text-probe-ok",children:["tmux: ✓ ",d.tmux.path??""]});const B=i.mode==="local"||!!((R=d.ssh)!=null&&R.ok);return t.jsxs("div",{className:"space-y-1",children:[t.jsxs("div",{className:"text-xs text-accent",children:["tmux: ⨯ ",d.tmux.message,B&&t.jsx("button",{type:"button",onClick:ae,className:"ml-2 text-accent underline transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",disabled:T||k,children:T?a.common.installing:a.common.oneClickInstall})]}),T&&t.jsx("div",{className:"text-xs text-og-500",children:a.common.installingTmuxNotice}),!T&&A&&t.jsxs("div",{className:`break-all text-xs ${A.ok?"text-probe-ok":"text-accent"}`,children:[A.ok?"✓ ":"⨯ ",A.message]})]})},pe=()=>i.mode!=="remote"||!i.host||!(d!=null&&d.ssh)?null:d.ssh.ok?t.jsxs("div",{className:"text-xs text-probe-ok",children:["SSH: ✓ ",d.ssh.message]}):t.jsxs("div",{className:"text-xs text-accent",children:["SSH: ⨯ ",d.ssh.message]});return t.jsx(Re,{open:e,onClose:X,title:a.createAgent.modalTitle(s),size:"lg",footer:t.jsxs(t.Fragment,{children:[c&&t.jsx("button",{type:"button",onClick:ye,disabled:k,className:"btn-secondary",children:a.common.back}),t.jsx("button",{type:"button",onClick:X,disabled:k,className:"btn-secondary",children:a.common.cancel}),t.jsx("button",{type:"submit",form:"create-agent-form",disabled:!me,className:"btn-primary",children:k?a.createAgent.submitting:c?a.createAgent.submitLabel:a.createAgent.continueLabel})]}),children:t.jsxs("form",{id:"create-agent-form",onSubmit:xe,className:"space-y-3",children:[v&&t.jsx("div",{className:"whitespace-pre-line rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-sm text-accent",children:v}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"agent-id",children:"Agent ID"}),t.jsx("input",{id:"agent-id",type:"text",value:i.id,onChange:B=>l({...i,id:B.target.value}),className:he,placeholder:a.createAgent.idPlaceholder(s,z),disabled:k}),i.id&&!Rn.test(i.id)&&t.jsx("div",{className:Nt,children:a.common.idFormatError}),i.id&&(p.has(i.id)||i.id===(c==null?void 0:c.agent.id))&&t.jsx("div",{className:Nt,children:a.createAgent.idTakenGlobalError})]}),t.jsxs("div",{children:[t.jsx("span",{className:ue,children:a.createAgent.roleLabel}),t.jsx("div",{className:"text-sm text-og-800",children:z==="dev"?a.createAgent.devStepLabel:a.createAgent.qaStepLabel}),c&&t.jsx("div",{className:qe,children:a.createAgent.teamDevLabel(c.agent.id)})]}),t.jsxs("div",{children:[t.jsx("span",{className:ue,children:a.createAgent.modeLabel}),t.jsxs("label",{className:"mr-4 inline-flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"mode",checked:i.mode==="local",className:Ie,onChange:()=>l({...i,mode:"local",host:""}),disabled:k}),t.jsx("span",{className:"text-sm text-og-800",children:a.createAgent.localModeLabel})]}),t.jsxs("label",{className:"inline-flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"mode",checked:i.mode==="remote",className:Ie,onChange:()=>l({...i,mode:"remote"}),disabled:k}),t.jsx("span",{className:"text-sm text-og-800",children:a.createAgent.remoteModeLabel})]})]}),i.mode==="remote"&&t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"host",children:"Host"}),h.length===0?t.jsx("div",{className:"rounded-md border border-og-100 bg-og-50/40 px-3 py-2 text-xs text-og-600",children:a.createAgent.noHostsHint}):t.jsxs("select",{id:"host",value:i.host,onChange:B=>l({...i,host:B.target.value}),className:he,disabled:k,children:[t.jsx("option",{value:"",children:a.createAgent.selectHostPlaceholder}),h.map(B=>t.jsx("option",{value:B.id,children:la(B)},B.id))]}),t.jsx("div",{className:qe,children:a.createAgent.sshConfigHint})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"mb-1.5 flex items-center justify-between",children:[t.jsx("span",{className:"text-xs font-medium text-og-700",children:a.createAgent.runtimeLabel}),t.jsx("button",{type:"button",onClick:V,className:"text-xs text-accent transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",disabled:k||b||i.mode==="remote"&&!i.host,children:a.createAgent.reprobeButton})]}),t.jsxs("label",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"radio",name:"runtime",checked:i.runtime==="claude-code",className:Ie,onChange:()=>l({...i,runtime:"claude-code"}),disabled:k||(d?!((S=d.runtimes["claude-code"])!=null&&S.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:k||(d?!((U=d.runtimes.codex)!=null&&U.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:k||(d?!((_=d.runtimes.opencode)!=null&&_.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:k||(d?!((se=d.runtimes.qodercli)!=null&&se.ok):!1)}),t.jsx("span",{className:"text-sm text-og-800",children:"Qoder CLI"}),t.jsx(N,{rt:"qodercli"})]}),t.jsx("div",{className:"mt-2",children:t.jsx(we,{})}),t.jsx("div",{children:t.jsx(pe,{})})]}),t.jsxs("div",{children:[t.jsxs("button",{type:"button",onClick:()=>I(B=>!B),"aria-expanded":P,"aria-controls":P?"advanced-options":void 0,className:"flex w-full items-center justify-between rounded-md px-1 py-1.5 text-left text-xs font-medium text-og-700 transition-colors hover:bg-og-50",children:[t.jsx("span",{children:a.createAgent.advancedOptionsLabel}),t.jsx("span",{className:"text-og-400",children:P?a.createAgent.collapseLabel:a.createAgent.expandLabel})]}),P&&t.jsxs("div",{id:"advanced-options",className:"mt-3 space-y-3",children:[t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"workdir",children:a.createAgent.workdirLabel}),t.jsx("input",{id:"workdir",type:"text",value:i.workdir,onChange:B=>l({...i,workdir:B.target.value}),className:he,placeholder:a.createAgent.workdirPlaceholder,disabled:k}),t.jsx("div",{className:qe,children:a.createAgent.workdirHint})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"model",children:a.createAgent.modelLabel}),t.jsx("input",{id:"model",type:"text",value:i.model,onChange:B=>l({...i,model:B.target.value}),className:he,placeholder:i.runtime==="codex"?a.createAgent.modelPlaceholderCodex:a.createAgent.modelPlaceholderOther,disabled:k}),t.jsx("div",{className:qe,children:a.createAgent.modelHint})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"addDirs",children:a.createAgent.addDirsLabel}),t.jsx("textarea",{id:"addDirs",value:i.addDirs,onChange:B=>l({...i,addDirs:B.target.value}),className:`${he} font-mono text-xs`,rows:3,placeholder:a.createAgent.addDirsPlaceholder,disabled:k}),t.jsx("div",{className:qe,children:a.createAgent.addDirsHint})]})]})]}),t.jsx("div",{className:"rounded-md border border-accent/25 bg-accent-soft/60 px-3 py-2.5",children:t.jsxs("label",{className:"flex cursor-pointer items-start gap-2",children:[t.jsx("input",{type:"checkbox",className:"mt-1 h-3.5 w-3.5 accent-accent",checked:i.yolo,onChange:B=>l({...i,yolo:B.target.checked}),disabled:k}),t.jsxs("div",{className:"text-sm text-og-800",children:[t.jsx("div",{className:"font-medium",children:a.createAgent.yoloTitle}),t.jsxs("div",{className:"mt-1 text-xs text-accent",children:[a.createAgent.yoloBodyLead,t.jsx("code",{children:er[i.runtime||"claude-code"]}),a.createAgent.yoloBodyTrail]})]})]})})]})})}const Cn=200,An=16e3,ca="baxian.draft.createTask:";function Jt(e){return`${ca}${e??"*"}`}function Dn(e){try{const n=localStorage.getItem(e);if(!n)return null;const s=JSON.parse(n);if(!s||typeof s!="object")return null;const r=s,a=typeof r.title=="string"?r.title:"",i=typeof r.description=="string"?r.description:"",l=typeof r.projectId=="string"?r.projectId:"",c=typeof r.preferredAgentId=="string"?r.preferredAgentId:"",m=typeof r.updatedAt=="number"?r.updatedAt:void 0;return!a.trim()&&!i.trim()?null:{title:a,description:i,projectId:l,preferredAgentId:c,updatedAt:m}}catch{return null}}function da(e,n){const s=!n.title.trim()&&!n.description.trim();try{s?localStorage.removeItem(e):localStorage.setItem(e,JSON.stringify({...n,updatedAt:Date.now()}))}catch{}}function Pn(e){try{localStorage.removeItem(e)}catch{}}function ua(e){const n=Jt(e),s=Dn(n);if(!e)return s;const r=Jt(void 0),a=Dn(r);if(!a||a.projectId!==e)return s;const i=!s||(a.updatedAt??0)>(s.updatedAt??0);if(i)try{localStorage.setItem(n,JSON.stringify(a))}catch{return a}try{localStorage.removeItem(r)}catch{}return i?a:s}const Ln="mt-1 text-right text-xs text-og-400",ma=Math.floor(Pt/1024/1024);function mn(e){const n=H(),s=e.mode==="edit",{show:r}=je(),a=s?e.task.projectId:e.projectId,i=s?e.task.title:"",l=s?e.task.description:"",c=s?e.task.preferredAgentId:"",[m,h]=o.useState([]),[f,p]=o.useState([]),[u,d]=o.useState(a??""),[x,b]=o.useState(c),[y,T]=o.useState(i),[C,A]=o.useState(l),[w,k]=o.useState([]),j=o.useRef(null),[v,D]=o.useState(!1),[P,I]=o.useState(null),[O,J]=o.useState(!1),E=o.useRef(0),W=o.useRef(0),re=o.useRef(0),te=o.useRef(new Set),X=s?null:Jt(a);o.useEffect(()=>{if(!e.open)return;E.current+=1,W.current+=1;const R=E.current;h([]),p([]),te.current=new Set;const $=X?ua(a):null;$&&te.current.add($.projectId),d(a??($==null?void 0:$.projectId)??""),b(($==null?void 0:$.preferredAgentId)||c),T(($==null?void 0:$.title)||i),A(($==null?void 0:$.description)||l),J($!==null),I(null),D(!1),k([]),Promise.all([M.projects.list(),M.agents.list()]).then(([Z,K])=>{R===E.current&&(h(Z),p(K))}).catch(Z=>{R===E.current&&I(Z instanceof Error?Z.message:String(Z))})},[e.open,a,i,l,c,X]),o.useEffect(()=>{if(!(!e.open||!X)){if(re.current!==W.current){re.current=W.current;return}da(X,{title:y,description:C,projectId:u,preferredAgentId:x})}},[e.open,X,y,C,u,x]);const V=o.useMemo(()=>m.find(R=>R.id===u)??null,[m,u]),ae=o.useMemo(()=>V?V.agent.flat().filter(R=>R.role==="dev"):[],[V]),z=o.useMemo(()=>new Set(f.map(R=>R.id)),[f]),le=o.useMemo(()=>ae.filter(R=>z.has(R.id)),[ae,z]),ne=o.useMemo(()=>ae.filter(R=>!z.has(R.id)),[ae,z]);o.useEffect(()=>{s||V!==null&&x!==""&&!le.find(R=>R.id===x)&&b("")},[V,le,x,s]),o.useEffect(()=>{if(s||!V)return;const R=le.find($=>$.role==="dev");R&&(te.current.has(V.id)||(te.current.add(V.id),b($=>$===""?R.id:$)))},[s,V,le]);const ge=!s||le.find(R=>R.id===x),q=s&&!ge&&!!x,ie=q&&ne.some(R=>R.id===x),me=ie?n.createTask.noDevPendingRestartHint(x):q?n.createTask.noDevNotInRuntimeHint(x):!u||le.length>0?null:ne.length>0?n.createTask.noDevGlobalPendingRestartHint:null,xe=y.trim(),ye=C.trim(),we=!!u&&xe.length>0&&!v,pe=()=>{v||e.onClose()},L=()=>{X&&(Pn(X),d(a??""),b(c),T(i),A(l),I(null),J(!1))},G=async R=>{var $,Z;if(R.preventDefault(),!!we){D(!0),I(null);try{if(e.mode==="edit"){const K=await M.tasks.update(e.task.id,{title:xe,description:ye,preferredAgentId:x});r({kind:"success",title:n.createTask.updatedToastTitle}),($=e.onUpdated)==null||$.call(e,K),e.onClose()}else{const K=w.length?await Promise.all(w.map(async be=>({dataBase64:await Yn(be),filename:be.name}))):void 0,ee=await M.tasks.create({projectId:u,title:xe,description:ye,preferredAgentId:x,...K?{images:K}:{}});X&&Pn(X),r({kind:"success",title:n.createTask.createdToastTitle}),(Z=e.onCreated)==null||Z.call(e,ee),e.onClose()}}catch(K){I(K instanceof Error?K.message:String(K))}finally{D(!1)}}},S=R=>{const $=Array.from(R.target.files??[]);if(R.target.value="",$.length===0)return;const Z=$.filter(K=>K.size>Pt?(r({kind:"error",title:n.createTask.imageTooLargeToastTitle,body:n.createTask.imageTooLargeToastBody(K.name,ma)}),!1):!0);w.length+Z.length>ft&&r({kind:"warn",title:n.createTask.tooManyImagesToastTitle(ft)}),k(K=>[...K,...Z].slice(0,ft))},U=R=>k($=>$.filter((Z,K)=>K!==R)),_=s?n.createTask.titleEdit:n.createTask.titleCreate,se=s?v?n.common.saving:n.common.save:v?n.common.creating:n.common.create,B=!s&&!a;return t.jsx(Re,{open:e.open,onClose:pe,title:_,size:"md",dismissOnBackdrop:!1,footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:pe,disabled:v,className:"btn-secondary",children:n.common.cancel}),t.jsx("button",{type:"submit",form:"create-task-form",disabled:!we,className:"btn-primary",children:se})]}),children:t.jsxs("form",{id:"create-task-form",onSubmit:G,className:"space-y-3",children:[!s&&O&&t.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-md border border-accent-soft bg-accent-soft/30 px-3 py-2 text-xs text-accent",children:[t.jsx("span",{children:n.createTask.draftRestoredNotice}),t.jsx("button",{type:"button",onClick:L,className:"shrink-0 underline hover:text-accent-hover",children:n.createTask.discardDraftButton})]}),P&&t.jsx("div",{className:"rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-sm text-accent",children:P}),B&&t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"task-project",children:"Project"}),t.jsxs("select",{id:"task-project",value:u,onChange:R=>d(R.target.value),className:he,disabled:v,required:!0,children:[t.jsx("option",{value:"",disabled:!0,children:n.createTask.selectProjectPlaceholder}),m.map(R=>t.jsx("option",{value:R.id,children:R.id},R.id))]})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"task-dev",children:n.createTask.targetAgentLabel}),t.jsxs("select",{id:"task-dev",value:x,onChange:R=>b(R.target.value),className:he,disabled:v,children:[t.jsx("option",{value:"",children:n.createTask.notAssignedOption}),q&&t.jsxs("option",{value:x,children:[x," ",ie?n.createTask.pendingRestartSuffix:n.createTask.notInRuntimeSuffix]}),le.map(R=>t.jsx("option",{value:R.id,children:R.id},R.id))]}),me&&t.jsx("div",{className:"mt-1 text-xs text-accent",children:me})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"task-title",children:"Title"}),t.jsx("input",{id:"task-title",type:"text",value:y,onChange:R=>T(R.target.value),maxLength:Cn,className:he,placeholder:n.createTask.titlePlaceholder,disabled:v,required:!0}),t.jsxs("div",{className:Ln,children:[y.length," / ",Cn]})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"task-description",children:n.createTask.descriptionLabel}),t.jsx("textarea",{id:"task-description",value:C,onChange:R=>A(R.target.value),maxLength:An,rows:8,className:`${he} font-mono text-xs`,placeholder:n.createTask.descriptionPlaceholder,disabled:v}),t.jsxs("div",{className:Ln,children:[C.length," / ",An]})]}),!s&&t.jsxs("div",{children:[t.jsx("label",{className:ue,children:n.createTask.imagesLabel}),t.jsx("button",{type:"button",onClick:()=>{var R;return(R=j.current)==null?void 0:R.click()},disabled:v||w.length>=ft,className:"btn-secondary",children:n.createTask.addImagesButton}),t.jsx("input",{ref:j,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:S}),w.length>0&&t.jsx("ul",{className:"mt-2 space-y-1",children:w.map((R,$)=>t.jsxs("li",{className:"flex items-center justify-between rounded-md border border-og-100 bg-surface px-2.5 py-1.5",children:[t.jsx("span",{title:R.name,className:"truncate text-xs text-og-700",children:R.name}),t.jsx("button",{type:"button","aria-label":n.createTask.removeImageAriaLabel(R.name),onClick:()=>U($),disabled:v,className:"ml-2 shrink-0 text-og-400 transition-colors",children:"✕"})]},`${R.name}-${$}`))})]})]})})}const En="***",Gt={hostname:"",port:"",alias:"",user:"",password:""};function ha(e){return e.alias?e.alias:`${e.user?`${e.user}@`:""}${e.hostname}${e.port!=null?`:${e.port}`:""}`}function fa({open:e,onClose:n}){var pe;const s=H(),[r,a]=o.useState([]),[i,l]=o.useState("list"),[c,m]=o.useState(null),[h,f]=o.useState(null),[p,u]=o.useState(!1),[d,x]=o.useState(!1),[b,y]=o.useState(Gt),[T,C]=o.useState(null),[A,w]=o.useState(!1),[k,j]=o.useState(!1),[v,D]=o.useState(null),[P,I]=o.useState(!1),[O,J]=o.useState(null),E=o.useRef(0),W=o.useRef(null),{show:re}=je(),te=o.useCallback(()=>{M.hosts.list().then(a).catch(L=>C(L instanceof Error?L.message:String(L)))},[]);o.useEffect(()=>{if(!e){W.current&&W.current.abort();return}l("list"),m(null),f(null),y(Gt),C(null),te()},[e,te]),o.useEffect(()=>{E.current+=1,W.current&&W.current.abort(),j(!1),D(null),I(!1),J(null)},[b.hostname,b.user,b.port,b.password,d,i]),o.useEffect(()=>()=>{W.current&&W.current.abort()},[]);const X=()=>{m(null),f(null),u(!1),x(!1),y(Gt),C(null),l("form")},V=L=>{m(L.id??null),f(L),u(L.password===En),x(!1),y({hostname:L.hostname,port:L.port!=null?String(L.port):"",alias:L.alias??"",user:L.user??"",password:""}),C(null),l("form")},ae=()=>{const L={hostname:b.hostname.trim()};return c?(L.port=b.port.trim()?Number(b.port):null,L.alias=b.alias.trim(),L.user=b.user.trim()):(b.port.trim()&&(L.port=Number(b.port)),b.alias.trim()&&(L.alias=b.alias.trim()),b.user.trim()&&(L.user=b.user.trim())),c&&d?L.password="":b.password&&(L.password=b.password),L},z=b.port.trim(),le=z===""||/^\d+$/.test(z)&&Number(z)>0&&Number(z)<=65535,ne=b.hostname.trim().length>0&&le,ge=!!h&&b.hostname.trim()===h.hostname&&b.user.trim()===(h.user??"")&&b.port.trim()===(h.port!=null?String(h.port):""),q=()=>c&&ge&&!b.password&&!d?{hostId:c}:{host:{hostname:b.hostname.trim(),...b.user.trim()?{user:b.user.trim()}:{},...z?{port:Number(z)}:{},...!d&&b.password?{password:b.password}:{}}},ie=async()=>{if(!ne||k)return;W.current&&W.current.abort();const L=new AbortController;W.current=L;const G=E.current;j(!0),D(null),J(null),C(null);try{const S=await M.agents.probe("remote",q(),{signal:L.signal});if(L.signal.aborted||E.current!==G)return;D(S)}catch(S){if(L.signal.aborted||E.current!==G)return;C(S instanceof Error?S.message:String(S))}finally{E.current===G&&j(!1)}},me=async()=>{if(P)return;const L=E.current;I(!0),J(null),C(null);try{const G=await M.agents.installTmux("remote",q());if(E.current!==L)return;J({ok:G.ok,message:G.message}),D(S=>S&&{...S,tmux:G.tmux})}catch(G){if(E.current!==L)return;C(G instanceof Error?G.message:String(G))}finally{E.current===L&&I(!1)}},xe=async L=>{if(L.preventDefault(),!(!ne||A)){w(!0),C(null);try{if(c)await M.hosts.update(c,ae()),re({kind:"success",title:s.hostMgmt.updatedToastTitle(c)});else{const G=await M.hosts.create(ae());re({kind:"success",title:s.hostMgmt.createdToastTitle(G.host.id)})}te(),l("list")}catch(G){C(G instanceof Error?G.message:String(G))}finally{w(!1)}}},ye=async L=>{C(null);try{await M.hosts.delete(L.id),re({kind:"success",title:s.hostMgmt.deletedToastTitle(L.id)}),te()}catch(G){C(G instanceof Error?G.message:String(G))}},N=t.jsx("button",{type:"button",onClick:n,className:"btn-secondary",children:s.common.close}),we=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:()=>l("list"),disabled:A,className:"btn-secondary",children:s.common.backText}),t.jsx("button",{type:"submit",form:"host-form",disabled:!ne||A,className:"btn-primary",children:A?s.common.saving:s.common.save})]});return t.jsxs(Re,{open:e,onClose:n,title:s.hostMgmt.title,size:"md",footer:i==="list"?N:we,children:[T&&t.jsx("div",{className:"mb-3 whitespace-pre-line rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-sm text-accent",children:T}),i==="list"?t.jsxs("div",{className:"space-y-3",children:[r.length===0?t.jsx("p",{className:"text-sm text-og-500",children:s.hostMgmt.emptyState}):t.jsx("ul",{className:"space-y-1.5",children:r.map(L=>t.jsxs("li",{className:"flex items-center justify-between gap-3 rounded-md border border-og-100 px-3 py-2",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"truncate text-sm font-medium text-og-800",children:ha(L)}),t.jsxs("div",{className:"truncate text-xs text-og-500",children:[(L.user?`${L.user}@`:"")+L.hostname,L.port!=null?`:${L.port}`:"",L.password===En?s.hostMgmt.passwordSavedIndicator:""]})]}),t.jsxs("div",{className:"flex shrink-0 gap-2",children:[t.jsx("button",{type:"button",onClick:()=>V(L),className:"text-xs text-accent transition-colors hover:text-accent-hover",children:s.common.edit}),t.jsx("button",{type:"button",onClick:()=>ye(L),className:"text-xs text-accent transition-colors hover:opacity-80",children:s.common.delete})]})]},L.id))}),t.jsx("button",{type:"button",onClick:X,className:"btn-secondary w-full",children:s.hostMgmt.addHostButton})]}):t.jsxs("form",{id:"host-form",onSubmit:xe,className:"space-y-3",children:[t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"host-hostname",children:s.hostMgmt.addressLabel}),t.jsx("input",{id:"host-hostname",type:"text",value:b.hostname,onChange:L=>y({...b,hostname:L.target.value}),className:he,placeholder:"remote.example.com",disabled:A})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"host-port",children:s.hostMgmt.portLabel}),t.jsx("input",{id:"host-port",type:"text",inputMode:"numeric",value:b.port,onChange:L=>y({...b,port:L.target.value}),className:he,placeholder:"22",disabled:A}),b.port.trim()!==""&&!le&&t.jsx("div",{className:"mt-1 text-xs text-accent",children:s.hostMgmt.portRangeError})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"host-alias",children:s.hostMgmt.aliasLabel}),t.jsx("input",{id:"host-alias",type:"text",value:b.alias,onChange:L=>y({...b,alias:L.target.value}),className:he,placeholder:"Prod worker",disabled:A})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"host-user",children:s.hostMgmt.userLabel}),t.jsx("input",{id:"host-user",type:"text",value:b.user,onChange:L=>y({...b,user:L.target.value}),className:he,placeholder:s.hostMgmt.userPlaceholder,disabled:A})]}),t.jsxs("div",{children:[t.jsx("label",{className:ue,htmlFor:"host-password",children:s.hostMgmt.passwordLabel}),t.jsx("input",{id:"host-password",type:"password",value:d?"":b.password,onChange:L=>y({...b,password:L.target.value}),className:he,placeholder:p?s.hostMgmt.passwordPlaceholderSet:s.hostMgmt.passwordPlaceholderUnset,disabled:A||d,autoComplete:"new-password"}),c&&p&&t.jsxs("label",{className:"mt-1.5 flex items-center gap-2 text-xs text-og-700",children:[t.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 accent-accent",checked:d,onChange:L=>x(L.target.checked),disabled:A}),s.hostMgmt.clearPasswordLabel]})]}),t.jsxs("div",{className:"rounded-md border border-accent/25 bg-accent-soft/60 px-3 py-2.5 text-xs text-accent",children:[s.hostMgmt.passwordHintLead,t.jsx("strong",{className:"font-semibold",children:s.hostMgmt.passwordHintStrong})," ",s.hostMgmt.plaintextWarningLead,t.jsx("strong",{className:"font-semibold",children:s.hostMgmt.plaintextWarningStrong}),s.hostMgmt.plaintextWarningTrail]}),t.jsxs("div",{className:"space-y-1.5",children:[t.jsx("button",{type:"button",onClick:ie,disabled:!ne||k||A||P,className:"text-xs text-accent transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",children:k?s.hostMgmt.testing:s.hostMgmt.testConnection}),(v==null?void 0:v.ssh)&&t.jsxs("div",{className:`text-xs ${v.ssh.ok?"text-og-800":"text-accent"}`,children:["SSH: ",v.ssh.ok?"✓":"⨯"," ",v.ssh.message]}),v&&(v.tmux.ok?t.jsxs("div",{className:"text-xs text-og-800",children:["tmux: ✓ ",v.tmux.path??""]}):t.jsxs("div",{className:"text-xs text-accent",children:["tmux: ⨯ ",v.tmux.message,((pe=v.ssh)==null?void 0:pe.ok)&&t.jsx("button",{type:"button",onClick:me,disabled:P||A,className:"ml-2 text-accent underline transition-colors hover:text-accent-hover disabled:cursor-not-allowed disabled:opacity-50",children:P?s.common.installing:s.common.oneClickInstall})]})),P&&t.jsx("div",{className:"text-xs text-og-500",children:s.common.installingTmuxNotice}),!P&&O&&t.jsxs("div",{className:`break-all text-xs ${O.ok?"text-og-800":"text-accent"}`,children:[O.ok?"✓ ":"⨯ ",O.message]})]})]})]})}const hn="baxian.taskNotifications.enabled";function fn(){if(typeof window>"u")return null;const e=window.Notification;return typeof e=="function"?e:null}function yt(){const e=fn();return e?e.permission:"unsupported"}function Wt(){try{return localStorage.getItem(hn)!=="0"}catch{return!0}}function wt(e){try{localStorage.setItem(hn,e?"1":"0")}catch{}}const ks=o.createContext(null);function pa({children:e}){const[n,s]=o.useState(yt),[r,a]=o.useState(Wt),[i,l]=o.useState(!1),c=o.useRef(!1),m=o.useRef(0);o.useEffect(()=>{const p=()=>{s(yt()),c.current||a(Wt())},u=d=>{if(d.key!==null&&d.key!==hn)return;s(yt());const x=d.key===null?Wt():d.newValue!=="0";x||(m.current+=1),a(x)};return window.addEventListener("focus",p),window.addEventListener("storage",u),()=>{window.removeEventListener("focus",p),window.removeEventListener("storage",u)}},[]);const h=o.useCallback(()=>{a(!0);const p=fn();if(!p){wt(!0);return}if(p.permission!=="default"){s(p.permission),wt(!0);return}if(c.current)return;c.current=!0,l(!0);const u=m.current;p.requestPermission().then(s).catch(d=>{console.warn("[task-notifications] permission request failed:",d),s(yt())}).finally(()=>{m.current===u&&wt(!0),c.current=!1,l(!1)})},[]),f=o.useCallback(()=>{m.current+=1,a(!1),wt(!1)},[]);return t.jsx(ks.Provider,{value:{permission:n,preferenceEnabled:r,enabled:n==="granted"&&r,requesting:i,enable:h,disable:f},children:e})}function js(){const e=o.useContext(ks);if(!e)throw new Error("useTaskNotifications must be used inside TaskNotificationsProvider");return e}const ga=[{value:"en-US",label:"English"},{value:"zh-CN",label:"简体中文"}];function xa({open:e,onClose:n}){const s=H(),{locale:r,saving:a,setLocale:i}=rs(),{show:l}=je(),c=async m=>{try{await i(m)}catch(h){const f=h instanceof Error?h.message:String(h);l({kind:"error",title:s.settings.languageSaveFailed(f)})}};return t.jsx(Re,{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:ga.map(m=>t.jsxs("label",{className:"inline-flex items-center gap-2 text-sm text-og-800",children:[t.jsx("input",{type:"radio",name:"baxian-language",className:Ie,checked:r===m.value,disabled:a,onChange:()=>void c(m.value)}),m.label]},m.value))})]}),t.jsx(ba,{})]})})}function ba(){const e=H(),{permission:n,enabled:s,requesting:r,enable:a,disable:i}=js();if(n==="unsupported")return null;const l=n==="denied";return t.jsxs("div",{children:[t.jsxs("label",{className:"inline-flex items-center gap-2 text-sm text-og-800",children:[t.jsx("input",{type:"checkbox",className:Ie,checked:s,disabled:l||r,onChange:()=>s?i():a()}),e.settings.taskNotifications]}),t.jsx("p",{className:qe,children:l?e.settings.taskNotificationsDenied:e.settings.taskNotificationsHint})]})}const Ts="topbar-actions";function $n(){return typeof document>"u"?null:document.getElementById(Ts)}function Ns({children:e}){const[n,s]=o.useState($n);return o.useEffect(()=>{n||s($n())},[n]),n?Ws.createPortal(e,n):null}function va(){return ms("/api/realtime")}class ya{constructor(n={}){ce(this,"wsUrl");ce(this,"wsFactory");ce(this,"tokenProvider");ce(this,"ws",null);ce(this,"topics",new Map);ce(this,"cache",new Map);ce(this,"outbox",[]);ce(this,"reconnectScheduler");ce(this,"explicitlyClosed",!1);this.wsUrl=n.wsUrl??va(),this.wsFactory=n.wsFactory??hs,this.tokenProvider=n.tokenProvider??sn,this.reconnectScheduler=new cs({reconnect:()=>this.openSocket(),shouldReconnect:()=>!this.explicitlyClosed&&this.topics.size>0})}subscribe(n,s,r){let a=this.topics.get(n);const i=!a;return a||(a={data:new Set,error:new Set},this.topics.set(n,a)),a.data.add(s),r&&a.error.add(r),i?(this.ensureSocket(),this.wsSendOrQueue({op:"subscribe",topic:n})):this.cache.has(n)&&queueMicrotask(()=>{var l;(l=this.topics.get(n))!=null&&l.data.has(s)&&this.cache.has(n)&&s(this.cache.get(n))}),()=>this.unsubscribe(n,s,r)}close(){if(this.explicitlyClosed=!0,this.reconnectScheduler.cancel(),this.reconnectScheduler.reset(),this.ws){try{this.ws.close()}catch{}this.ws=null}this.topics.clear(),this.cache.clear(),this.outbox=[]}unsubscribe(n,s,r){const a=this.topics.get(n);a&&(a.data.delete(s),r&&a.error.delete(r),a.data.size===0&&a.error.size===0&&(this.topics.delete(n),this.cache.delete(n),this.wsSendOrQueue({op:"unsubscribe",topic:n}),this.topics.size===0&&this.teardownSocket()))}teardownSocket(){if(this.reconnectScheduler.cancel(),this.reconnectScheduler.reset(),this.outbox=[],this.ws){try{this.ws.close()}catch{}this.ws=null}}ensureSocket(){this.explicitlyClosed||this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING)||this.openSocket()}openSocket(){if(this.explicitlyClosed)return;this.reconnectScheduler.cancel();const n=this.tokenProvider(),s=n?[`baxian.token.${us(n)}`]:void 0;let r;try{r=this.wsFactory(this.wsUrl,s)}catch(i){console.warn("[events-client] WebSocket constructor threw:",i),this.broadcastConnectionError({code:"connection_failed",message:i instanceof Error?i.message:"WebSocket constructor threw"}),this.scheduleReconnect();return}this.ws=r;let a=!1;r.onopen=()=>{if(r!==this.ws)return;a=!0,this.reconnectScheduler.reset();for(const l of this.topics.keys())try{r.send(JSON.stringify({op:"subscribe",topic:l}))}catch(c){console.warn("[events-client] resubscribe send failed:",c)}const i=this.outbox;this.outbox=[];for(const l of i)if(!(l.op==="subscribe"||l.op==="unsubscribe"))try{r.send(JSON.stringify(l))}catch(c){console.warn("[events-client] outbox flush failed:",c)}},r.onmessage=i=>{if(r!==this.ws)return;let l;try{const c=typeof i.data=="string"?i.data:String(i.data);l=JSON.parse(c)}catch{return}this.handleMessage(l)},r.onclose=i=>{r===this.ws&&(this.ws=null,!this.explicitlyClosed&&(ds(i,n,this.tokenProvider())||(a||this.broadcastConnectionError({code:"connection_failed",message:"WebSocket failed to connect (auth, network, or proxy issue)"}),this.topics.size!==0&&this.scheduleReconnect())))},r.onerror=()=>{}}scheduleReconnect(){this.reconnectScheduler.schedule()}broadcastConnectionError(n){for(const s of this.topics.values())for(const r of[...s.error])try{r(n)}catch(a){console.error("[events-client] error handler threw on connection error:",a)}}wsSendOrQueue(n){if(this.ws&&this.ws.readyState===WebSocket.OPEN)try{this.ws.send(JSON.stringify(n));return}catch(s){console.warn("[events-client] send failed, will queue:",s)}this.outbox.push(n)}handleMessage(n){switch(n.type){case"data":{const s=this.topics.get(n.topic);if(this.cache.set(n.topic,n.data),!s)return;for(const r of[...s.data])try{r(n.data)}catch(a){console.error(`[events-client] handler threw on ${n.topic}:`,a)}break}case"error":{const s={code:n.code,message:n.message};if(n.topic){const r=this.topics.get(n.topic);if(r)for(const a of[...r.error])try{a(s)}catch(i){console.error(`[events-client] error handler threw on ${n.topic}:`,i)}}else console.warn("[events-client] connection-level error:",n.code,n.message);break}}}}let zt=null;function rt(){return zt||(zt=new ya),zt}function pn(){const[e,n]=o.useState(null),[s,r]=o.useState(!1),[a,i]=o.useState(null);return o.useEffect(()=>rt().subscribe("agents",c=>{i(null),n(c),r(!0)},c=>i(c)),[]),{data:e,loaded:s,error:a}}function Ss(e){const[n,s]=o.useState(null),[r,a]=o.useState(!1),[i,l]=o.useState(null);return o.useEffect(()=>(s(null),a(!1),l(null),rt().subscribe(`task:${e}`,m=>{l(null),s(m),a(!0)},m=>l(m))),[e]),{data:n,loaded:r,error:i}}function Rs(e){const[n,s]=o.useState(null),[r,a]=o.useState(!1),[i,l]=o.useState(null);return o.useEffect(()=>{if(!e){s(null),a(!1),l(null);return}s(null),a(!1),l(null);let c=!1,m=!1,h=!1;const f=rt().subscribe(`project-tasks:${e}`,p=>{c||(m=!0,l(null),s(p),a(!0))},p=>{c||(l(p),!(m||h)&&(h=!0,M.tasks.list(e).then(u=>{c||m||(s(u),a(!0))},u=>{console.warn(`[useProjectTasks] REST fallback failed for ${e}:`,u)})))});return()=>{c=!0,f()}},[e]),{data:n,loaded:r,error:i}}let St=null,Be=null,Rt=null,Ze=0;const Xt=new Set;function Cs(){Xt.forEach(e=>e())}async function wa(){const e=Ze;try{const n=await M.projects.list();if(e!==Ze)return;St=n,Rt=null}catch(n){if(e!==Ze)return;Rt=n instanceof Error?n.message:String(n)}finally{e===Ze&&(Be=null,Cs())}}function Zt(){return Be||(Be=wa(),Be)}function ka(){Ze+=1,St=null,Be=null,Rt=null,Cs()}typeof window<"u"&&window.addEventListener(et,ka);async function ja(){const e=Be!==null;await Zt(),e&&await Zt()}function at(){const[,e]=o.useState(0);return o.useEffect(()=>{const n=()=>e(s=>s+1);return Xt.add(n),St===null&&!Be&&Zt(),()=>{Xt.delete(n)}},[]),{projects:St,error:Rt,refresh:ja}}function Ta(){const e=H(),n=Le(),{projects:s,error:r,refresh:a}=at(),i=s??[],l=s!==null,[c,m]=o.useState(!1),[h,f]=o.useState(!1),[p,u]=o.useState(!1),[d,x]=o.useState(!1),[b,y]=o.useState({kind:"closed"}),{data:T,loaded:C,error:A}=pn(),w=(A==null?void 0:A.message)??null,k=new Map((T??[]).map(P=>[P.id,P])),j=r??w,v=i.length===0,D=t.jsx("button",{type:"button",onClick:()=>f(!0),disabled:v,"aria-describedby":v?"create-task-hint":void 0,className:"btn-ghost",children:e.dashboard.newTask});return t.jsxs("div",{children:[t.jsxs(Ns,{children:[v?t.jsx("span",{className:"inline-flex",title:e.dashboard.createProjectFirst,children:D}):D,v&&t.jsx("span",{id:"create-task-hint",className:"sr-only",children:e.dashboard.createProjectFirst}),t.jsx(Dt,{ariaLabel:e.dashboard.moreActions,children:P=>t.jsxs(t.Fragment,{children:[t.jsx(ke,{onClick:()=>{P(),m(!0)},children:e.dashboard.newProject}),t.jsx(ke,{onClick:()=>{P(),u(!0)},children:e.dashboard.manageHosts}),t.jsx(ke,{onClick:()=>{P(),x(!0)},children:e.settings.entry})]})})]}),t.jsx("h1",{className:"sr-only",children:"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(P=>t.jsx(Na,{project:P,agentsById:k,agentsLoaded:C,agentsError:!!A,onAgentDeleted:a},P.id)),t.jsx(ia,{open:c,onClose:()=>m(!1),onCreated:P=>{m(!1),a(),y({kind:"asking",projectId:P})}}),t.jsx(fa,{open:p,onClose:()=>u(!1)}),t.jsx(Re,{open:b.kind==="asking",onClose:()=>y({kind:"closed"}),title:e.dashboard.projectCreatedTitle,size:"sm",footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:()=>y({kind:"closed"}),className:"btn-secondary",children:e.dashboard.later}),t.jsx("button",{type:"button",onClick:()=>{b.kind==="asking"&&y({kind:"addingAgent",projectId:b.projectId})},className:"btn-primary",children:e.dashboard.continueAddingAgent})]}),children:t.jsx("p",{className:"text-sm text-og-700",children:e.dashboard.addAgentNowOrLater})}),b.kind==="addingAgent"&&t.jsx(ws,{open:!0,projectId:b.projectId,onClose:()=>y({kind:"closed"}),onCreated:()=>{a()}}),t.jsx(mn,{open:h,onClose:()=>f(!1),onCreated:P=>n(Pe(P.projectId,P.id))}),t.jsx(xa,{open:d,onClose:()=>x(!1)})]})}function Na({project:e,agentsById:n,agentsLoaded:s,agentsError:r,onAgentDeleted:a}){const i=H(),{data:l,error:c}=Rs(e.id),m=l??[],h=(c==null?void 0:c.message)??null;return t.jsxs("div",{className:"mb-10",children:[t.jsxs("div",{className:"mb-3 -mx-2 flex items-baseline gap-x-3 gap-y-1 px-2 py-1",children:[t.jsx("h2",{className:"min-w-0 truncate font-display text-sm font-semibold tracking-tight text-og-1000",title:e.id,children:t.jsx(Se,{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(Se,{to:`/project/${e.id}`,className:"ml-auto text-sm text-accent hover:text-accent-hover","aria-label":i.dashboard.detailsAriaLabel(e.id),children:i.dashboard.detailsLink})]}),h&&t.jsx("div",{className:"mb-2 text-xs text-accent",children:i.dashboard.tasksLoadFailed(h)}),e.agent.flat().length===0?t.jsx("div",{className:"rounded-lg border border-hairline bg-surface py-6 text-center text-sm text-og-500",children:i.dashboard.noAgentsYet}):t.jsx("div",{className:e.agent.length===1?"space-y-3":"grid grid-cols-1 gap-3 xl:grid-cols-2",children:e.agent.map((f,p)=>t.jsx(ys,{team:f,projectId:e.id,agentsById:n,agentsLoaded:s,agentsError:r,tasks:m,onDeleted:a,terminalMode:"embedded-full"},f.map(u=>u.id).join(":")||p))})]})}const As="baxian.taskPanel.doneOpen";function Sa(){try{return localStorage.getItem(As)==="1"}catch{return!1}}function Ct(e){const n=e.match(/^task-(\d+)$/);return n?parseInt(n[1],10):Number.NaN}function Ra(e,n){const s=Ct(e.id),r=Ct(n.id);return Number.isNaN(s)||Number.isNaN(r)?e.id.localeCompare(n.id):s-r}function Ca(e,n){const s=(n.updatedAt??"").localeCompare(e.updatedAt??"");if(s!==0)return s;const r=Ct(e.id),a=Ct(n.id);return Number.isNaN(r)||Number.isNaN(a)?n.id.localeCompare(e.id):a-r}function In(e,n){const[s,r]=o.useState(Bt);o.useEffect(()=>r(Bt),[n]);const a=e.slice(0,s),i=e.length>a.length;return{items:a,hasMore:i,loadMore:()=>r(c=>c+Bt),total:e.length}}function Aa(e){const[n,s]=o.useState([]),[r,a]=o.useState(!1),[i,l]=o.useState(!1),[c,m]=o.useState(!1),[h,f]=o.useState(null),p=o.useRef(0),u=o.useRef(0),d=o.useCallback(x=>{const b=++p.current,y=x==="first"?0:u.current;l(!0),f(null),M.tasks.page(e,{category:"done",offset:y}).then(T=>{p.current===b&&(s(C=>x==="first"?T.tasks:[...C,...T.tasks]),a(T.hasMore),u.current=T.nextOffset,m(!0),l(!1))},T=>{p.current===b&&(f(T instanceof Error?T.message:String(T)),l(!1))})},[e]);return o.useEffect(()=>{p.current+=1,u.current=0,s([]),a(!1),m(!1),f(null),l(!1)},[e]),{items:n,hasMore:r,loading:i,loaded:c,error:h,load:d}}function Da({projectId:e,openTasks:n,className:s=""}){const r=H(),a=o.useMemo(()=>n.filter(u=>tn.has(u.status)).sort(Ca),[n]),i=o.useMemo(()=>n.filter(u=>u.status==="pending").sort(Ra),[n]),l=In(a,e),c=In(i,e),m=Aa(e),[h,f]=o.useState(Sa);o.useEffect(()=>{try{localStorage.setItem(As,h?"1":"0")}catch{}},[h]),o.useEffect(()=>{h&&m.load("first")},[h,m.load]);const p=()=>f(u=>!u);return t.jsx("aside",{"aria-label":r.taskPanel.ariaLabel,className:`flex flex-col rounded-lg border border-hairline bg-surface ${s}`,children:t.jsxs("div",{children:[t.jsx(Bn,{title:r.taskPanel.inProgressTitle,section:l,emptyHint:r.taskPanel.emptyInProgress}),t.jsx(Bn,{title:r.taskPanel.pendingTitle,section:c,emptyHint:r.taskPanel.emptyPending}),t.jsxs("div",{children:[t.jsxs("button",{type:"button",onClick:p,"aria-expanded":h,className:"flex w-full items-center justify-between px-3 py-2 text-left text-xs font-normal uppercase tracking-[0.05em] text-og-500 transition-colors hover:bg-og-50/40",children:[t.jsx("span",{children:r.taskPanel.doneTitle}),t.jsx("span",{className:"font-normal normal-case text-accent",children:h?r.taskPanel.collapse:r.taskPanel.view})]}),h&&t.jsx(Pa,{state:m})]})]})})}function Bn({title:e,section:n,emptyHint:s}){const r=H();return t.jsxs("section",{"aria-label":e,className:"border-b border-hairline",children:[t.jsxs("div",{className:"px-3 py-2 text-xs font-normal uppercase tracking-[0.05em] text-og-500",children:[e," ",t.jsxs("span",{className:"text-og-400",children:["(",n.total,")"]})]}),n.items.length===0?t.jsx("div",{className:"px-3 pb-3 text-xs text-og-400",children:s}):t.jsxs("div",{className:"divide-y divide-hairline",children:[n.items.map(a=>t.jsx(Ds,{task:a},a.id)),n.hasMore&&t.jsx("button",{type:"button",onClick:n.loadMore,className:"w-full px-3 py-2 text-center text-xs text-accent transition-colors hover:bg-og-50/40",children:r.taskPanel.loadMore})]})]})}function Pa({state:e}){const n=H(),s=e.loaded&&!e.error&&e.items.length===0;return t.jsxs("div",{className:"divide-y divide-hairline",children:[e.items.map(r=>t.jsx(Ds,{task:r},r.id)),e.error&&t.jsx("div",{className:"px-3 py-2 text-xs text-accent",children:n.common.loadFailed(e.error)}),s&&t.jsx("div",{className:"px-3 pb-3 pt-1 text-xs text-og-400",children:n.taskPanel.emptyDone}),e.loading&&e.items.length===0&&t.jsx("div",{className:"px-3 py-3 text-center text-xs text-og-400",children:n.common.loading}),e.hasMore&&t.jsx("button",{type:"button",onClick:()=>e.load("more"),disabled:e.loading,className:"w-full px-3 py-2 text-center text-xs text-accent transition-colors hover:bg-og-50/40 disabled:opacity-50",children:e.loading?n.common.loading:n.taskPanel.loadMore})]})}function Ds({task:e}){const n=H(),s=Le(),{show:r}=je(),[a,i]=o.useState(!1),l=Fe(e.phase)?e.specReviewRound??0:e.reviewRound,c=e.status==="pending"&&e.preferredAgentId==="",m=c?n.taskDetail.editTask:e.status==="pending"?n.taskDetail.startTask:e.status==="review"?n.taskDetail.restartReview:e.status==="approved"?n.taskDetail.retryPreMergeCheck:n.taskDetail.retryCurrentStep,h=e.attention?gs(n,e.attention,e.status):null,f=()=>s(Pe(e.projectId,e.id)),p=async()=>{if(c||e.postApproveRevoked||e.status==="review"&&Wn(e)){f();return}i(!0);try{await M.tasks.advance(e.id),r({kind:"success",title:n.taskDetail.advanceSucceededTitle})}catch(u){r({kind:"error",title:n.taskDetail.advanceFailedTitle,body:n.taskDetail.actionFailedBody,details:u instanceof Error?u.message:String(u)})}finally{i(!1)}};return t.jsxs("div",{className:"px-3 py-2",children:[t.jsx("div",{className:"flex items-center gap-2 text-sm",children:t.jsxs("button",{type:"button",onClick:f,className:"flex min-w-0 flex-1 items-center gap-2 text-left",children:[t.jsx("span",{className:"shrink-0 font-mono text-xs text-og-500",title:e.id,children:un(e.id)}),t.jsx("span",{className:"min-w-0 flex-1 truncate text-og-1000",title:e.title,children:e.title}),l>0&&t.jsx("span",{"aria-label":n.agents.round(l),className:"shrink-0 text-xs text-og-400",children:n.taskPanel.round(l)}),t.jsx(dn,{task:e,className:"shrink-0"})]})}),e.attention&&h&&t.jsxs("div",{className:"mt-2 rounded border border-accent/25 bg-accent-soft/60 px-2 py-1.5 text-xs text-accent",children:[t.jsxs("button",{type:"button",onClick:f,className:"block w-full text-left",children:[t.jsx("span",{className:"font-medium",children:h.title}),t.jsx("span",{className:"mt-0.5 block text-og-700",children:h.guidance})]}),t.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1.5",children:cn(e.attention,e.status).map(u=>t.jsx("button",{type:"button",disabled:u==="advance"&&a,onClick:()=>u==="advance"?void p():f(),className:u==="advance"?"btn-primary":"btn-secondary",children:u==="advance"?a?n.taskDetail.advancing:m:u==="verdict"?n.taskDetail.handleReview:u==="cancel"?n.taskDetail.cancelConfirmLabel:n.taskDetail.retryTask},u))}),t.jsxs("details",{open:h.expandDetails,className:"mt-1.5 text-og-500",children:[t.jsx("summary",{className:"cursor-pointer select-none text-accent",children:n.common.technicalDetails}),t.jsxs("div",{className:"mt-1 whitespace-pre-wrap break-words font-mono",children:[e.attention.reason,`
|
|
13
|
+
`,e.attention.runbook]})]})]})]})}const La=[],Ps="baxian.taskPanel.open";function Ea(){try{return localStorage.getItem(Ps)!=="0"}catch{return!0}}function $a(){const{id:e}=At(),n=Le(),s=H(),{show:r}=je(),{refresh:a}=at(),[i,l]=o.useState(null),[c,m]=o.useState(null),[h,f]=o.useState(!1),[p,u]=o.useState(!1),d=o.useRef(null),[x,b]=o.useState(Ea),[y,T]=o.useState(!1),[C,A]=o.useState(""),[w,k]=o.useState(!1),[j,v]=o.useState(null),D=o.useRef(0),{data:P,loaded:I,error:O}=pn(),{data:J,error:E}=Rs(e),W=(O==null?void 0:O.message)??null,re=(E==null?void 0:E.message)??null,te=J??La,X=new Map((P??[]).map(q=>[q.id,q])),V=c??W??re,ae=o.useCallback(async q=>{const ie=++D.current;try{const me=await M.projects.get(q);if(ie!==D.current)return;l(me),m(null)}catch(me){if(ie!==D.current)return;m(me instanceof Error?me.message:String(me))}},[]);o.useEffect(()=>{e&&(l(null),m(null),ae(e))},[e,ae]),o.useEffect(()=>{y||(A(""),v(null))},[y]),o.useEffect(()=>{try{localStorage.setItem(Ps,x?"1":"0")}catch{}},[x]);const z=(i==null?void 0:i.agent.flat().length)??0,le=z===0,ne=!!i&&C.trim()===i.id,ge=async()=>{if(!(!i||!ne||w)){k(!0),v(null);try{await M.projects.delete(i.id),await a(),r({kind:"success",title:s.projectPage.deletedToastTitle(i.id)}),T(!1),n("/")}catch(q){v(q instanceof Error?q.message:String(q))}finally{k(!1)}}};return i?t.jsxs("div",{children:[t.jsxs(Ns,{children:[t.jsx("button",{type:"button",onClick:()=>u(!0),className:"btn-ghost",children:s.projectPage.newTaskButton}),t.jsx(Dt,{ariaLabel:s.projectPage.menuAriaLabel(i.id),menuClassName:"min-w-[180px]",triggerRef:d,children:q=>t.jsxs(t.Fragment,{children:[!x&&t.jsx(ke,{onClick:()=>{q(),b(!0)},children:s.projectPage.showTaskPanel}),t.jsx(ke,{onClick:()=>{q(),f(!0)},children:s.projectPage.addAgent}),t.jsx("div",{role:"none",className:"my-1 border-t border-hairline"}),t.jsx(ke,{onClick:()=>{q(),T(!0)},disabled:!le,title:le?void 0:s.projectPage.deleteAgentsFirstHint(z),children:s.projectPage.deleteProjectMenuItem})]})})]}),V&&t.jsx("div",{className:"mb-4 text-sm text-accent",children:s.common.loadFailed(V)}),t.jsxs("div",{className:"mb-6 flex items-baseline gap-x-3",children:[t.jsx("h1",{className:"min-w-0 truncate font-display text-sm font-semibold tracking-tight text-og-1000",title:i.id,children:i.id}),t.jsx("span",{className:"hidden min-w-0 truncate font-mono text-xs text-og-500 sm:inline-block",title:i.repo,children:i.repo})]}),t.jsxs("div",{className:"flex flex-col gap-4 lg:flex-row lg:items-start",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:"mb-3 flex h-8 items-center gap-2",children:t.jsx("h2",{className:"font-display text-xs font-semibold uppercase tracking-[0.06em] text-og-500",children:"Agents"})}),i.agent.flat().length===0?t.jsx("div",{className:"mb-8 rounded-lg border border-hairline bg-surface py-6 text-center text-sm text-og-500",children:s.projectPage.noAgentsYet}):t.jsx("div",{className:"mb-8 space-y-5",children:i.agent.map((q,ie)=>t.jsx(ys,{team:q,projectId:i.id,agentsById:X,agentsLoaded:I,agentsError:!!O,tasks:te,onDeleted:()=>{ae(i.id)},terminalMode:"embedded-full"},q.map(me=>me.id).join(":")||ie))})]}),x&&t.jsxs("div",{className:"w-full lg:w-[340px] lg:shrink-0 xl:w-[380px]",children:[t.jsxs("div",{className:"mb-3 flex h-8 items-center justify-between gap-2",children:[t.jsx("h2",{className:"font-display text-xs font-semibold uppercase tracking-[0.06em] text-og-500",children:"Tasks"}),t.jsx("button",{type:"button",onClick:()=>{var q;b(!1),(q=d.current)==null||q.focus()},"aria-label":s.projectPage.closeTaskPanel,className:"flex h-7 w-7 items-center justify-center rounded text-og-500 transition-colors hover:bg-og-50 hover:text-og-1000",children:t.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[t.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),t.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),t.jsx(Da,{projectId:i.id,openTasks:te})]})]}),t.jsx(ws,{open:h,projectId:i.id,onClose:()=>f(!1),onCreated:()=>{ae(i.id)}}),t.jsx(mn,{open:p,projectId:i.id,onClose:()=>u(!1),onCreated:q=>n(Pe(q.projectId,q.id))}),t.jsx(Re,{open:y,onClose:()=>{w||T(!1)},title:s.projectPage.deleteModalTitle,size:"sm",footer:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",onClick:()=>T(!1),disabled:w,className:"btn-secondary",children:s.common.cancel}),t.jsx("button",{type:"button",onClick:()=>void ge(),disabled:!ne||w,className:"btn-primary",children:w?s.common.deleting:s.projectPage.confirmDeleteButton})]}),children:t.jsxs("div",{className:"space-y-4",children:[t.jsxs("p",{className:"text-sm text-og-700",children:[s.projectPage.deleteBodyLead,t.jsx("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:C,onChange:q=>A(q.target.value),placeholder:i.id,autoComplete:"off",autoCorrect:"off",spellCheck:!1,disabled:w,"aria-label":s.projectPage.confirmInputAriaLabel,className:"w-full rounded border border-hairline bg-surface px-3 py-2 font-mono text-sm text-og-1000 focus:border-accent focus:outline-none"}),j&&t.jsx("div",{className:"rounded-md border border-accent/25 bg-accent-soft px-3 py-2 text-xs text-accent",children:j})]})})]}):c?t.jsx("div",{className:"text-sm text-accent",children:s.common.loadFailed(c)}):t.jsx("div",{className:"text-sm text-og-500",children:s.common.loading})}const Ls={approve:"pill pill-live","request-changes":"pill pill-warn",comment:"pill"};function Es(e){const n=e.some(i=>i.roundToken!==void 0),s=i=>n?i.roundToken!==void 0:i.kind==="review",r=[];let a=[];for(const i of e)s(i)?(r.push({items:a,review:i}),a=[]):a.push(i);return a.length>0&&r.push({items:a}),r}function nt(e,n){const s=e.id||e.commitSha||e.createdAt||e.body||n;return e.sourceKey!==void 0?JSON.stringify([e.kind,e.sourceKey,s]):`${e.kind}-${s}`}function Et(e){if(e.id)return e.sourceKey!==void 0?`pr-${e.kind}.${e.sourceKey}.${e.id}`:`pr-${e.kind}-${e.id}`}function $s(e,n){return e.review?`round-${nt(e.review,n)}`:`round-in-progress-${e.items[0]?nt(e.items[0],n):n}`}function Is(e){const n=e.closedUnmergedAnchor;return[e.reviewRound,e.latestHeadSha??"",e.status,e.reviewDispatchedAt??"",e.prFeedbackReceivedAt??"",e.prNumber??"",e.reviewConversationUpdatedAt??"",n===void 0?"":`${n.generation}/${n.cleared===!0?"reopened":"closed"}`].join(":")}const Ia=4e3,Ba=6e4;function Bs(e,n){const[s,r]=o.useState(null),[a,i]=o.useState(!1),[l,c]=o.useState(null),[m,h]=o.useState(!1),[f,p]=o.useState(null),[u,d]=o.useState(0),x=o.useRef(e),b=o.useRef(n),y=o.useRef(0),T=o.useRef(0),C=o.useRef(void 0),A=o.useRef(0),w=o.useRef(null);o.useEffect(()=>{const j=()=>{w.current!==null&&(w.current=null,h(!1),p(null))};x.current!==e&&(x.current=e,r(null),i(!1),p(null),T.current=0,j()),b.current!==n&&(b.current=n,T.current=0,j());const v=++y.current;return c(null),M.tasks.prReview(e).then(D=>{if(y.current===v)if(r(D),i(!0),D.available&&D.error&&T.current<3){T.current+=1;const P=D.rateLimited?Ba*2**(T.current-1):Ia*T.current;C.current=setTimeout(()=>d(I=>I+1),P)}else D.error||(T.current=0)}).catch(D=>{y.current===v&&(c(D instanceof Error?D.message:String(D)),r(null),i(!0))}),()=>{clearTimeout(C.current),C.current=void 0}},[e,n,u]);const k=o.useCallback(()=>{if(w.current!==null)return;const j=++A.current;w.current=j,h(!0),p(null),M.tasks.prReviewRefresh(x.current).then(v=>{if(w.current===j){if(v.available&&(v.error!==void 0||v.rateLimited===!0)){p(v.error??"rate limited");return}clearTimeout(C.current),C.current=void 0,y.current+=1,T.current=0,r(v),i(!0),c(null)}}).catch(v=>{w.current===j&&p(v instanceof Error?v.message:String(v))}).finally(()=>{w.current===j&&(w.current=null,h(!1))})},[]);return{data:s,loaded:a,error:l,refresh:k,refreshing:m,refreshError:f}}function Fa(e){const n=new Date(e);if(Number.isNaN(n.getTime()))return e;const s=r=>String(r).padStart(2,"0");return`${n.getFullYear()}-${s(n.getMonth()+1)}-${s(n.getDate())} ${s(n.getHours())}:${s(n.getMinutes())}:${s(n.getSeconds())}`}function Fs({data:e,onRefresh:n,refreshing:s,refreshError:r}){const a=H(),i=e.autoRefresh===!0?e.autoRefreshIntervalMs:void 0,[l,c]=o.useState(void 0),m=o.useRef(Date.now());return o.useEffect(()=>{m.current=Date.now()},[e]),o.useEffect(()=>{if(i===void 0||i<=0){c(void 0);return}const h=()=>{const p=Date.now()-m.current;c(Math.ceil((i-p%i)/1e3))};h();const f=setInterval(h,1e3);return()=>clearInterval(f)},[i,e]),e.available?t.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-og-400",children:[e.fetchedAt&&t.jsx("span",{children:a.prReview.fetchedAtLabel(Fa(e.fetchedAt))}),e.autoRefresh===!1&&t.jsx("span",{children:a.prReview.autoRefreshStopped}),e.autoRefresh===!0&&l!==void 0&&t.jsx("span",{children:a.prReview.nextCheck(l)}),t.jsx("button",{type:"button",className:"text-accent hover:text-accent-hover disabled:opacity-60",onClick:n,disabled:s,children:s?a.prReview.refreshing:a.prReview.refresh}),r&&t.jsx("span",{className:"text-accent",children:a.prReview.refreshFailed(r)})]}):null}function Ma({role:e,label:n,summary:s,badge:r,onClick:a}){const i=H();return t.jsxs("button",{type:"button",onClick:a,className:"card flex w-full items-center gap-2 px-3 py-2 text-left text-sm",children:[t.jsx("span",{className:"shrink-0 min-w-[1.75rem] text-xs tracking-wide text-og-600",children:e==="qa"?i.review.roleQa:e==="user"?i.review.roleUser:i.review.roleDev}),t.jsx("span",{className:"shrink-0 text-og-800",children:n}),r,t.jsx("span",{className:"min-w-0 flex-1 truncate text-og-500",children:s}),t.jsx("span",{"aria-hidden":!0,className:"shrink-0 text-og-300",children:"›"})]})}function Oa(e){return{"no-pr":e.prReview.reasonNoPr,"driver-unavailable":e.prReview.reasonDriverUnavailable}}function _a(e){return(e==null?void 0:e.trim().split(`
|
|
14
|
+
`,1)[0])??""}function Ha(e){if(!(e.kind!=="review-comment"||!e.path))return e.line!==void 0?`${e.path}:${e.line}`:e.path}function qa(e,n){return n.bodyTruncated?e.prReview.truncatedSuffix:""}function Ua(e,n){const s=_a(n.body),r=qa(e,n);if(n.kind==="review-comment"){const a=Ha(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 Ga(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 Wa(e){return e.verdict!==void 0?"qa":e.kind==="issue-comment"||e.inReplyTo?"dev":"qa"}function za({task:e}){const n=H(),s=Le(),r=Is(e),{data:a,loaded:i,error:l,refresh:c,refreshing:m,refreshError:h}=Bs(e.id,r),f=Fe(e.phase)?n.prReview.specReviewHeading:n.prReview.codeReviewHeading;function p(x){s(`/tasks/${encodeURIComponent(e.id)}/pr-review${x?`#${x}`:""}`)}if(l)return t.jsx(Je,{title:f,children:t.jsx("div",{className:"text-sm text-accent",children:n.review.loadFailed(l)})});if(!i)return t.jsx(Je,{title:f,children:t.jsx("div",{className:"text-sm text-og-400",children:n.review.loadingRecords})});if(!(a!=null&&a.available)){const x=Oa(n);return t.jsx(Je,{title:f,children:t.jsx("div",{className:"text-sm text-og-400",children:x[(a==null?void 0:a.reason)??"no-pr"]??x["no-pr"]})})}const u=t.jsx(Fs,{data:a,onRefresh:c,refreshing:m,refreshError:h});if(a.items.length===0)return t.jsxs(Je,{title:f,children:[u,a.truncated?t.jsx("div",{className:"text-sm text-accent",children:n.prReview.listTruncated}):a.error?t.jsx("div",{className:"text-sm text-accent",children:n.prReview.fetchFailed(a.error)}):t.jsx("div",{className:"text-sm text-og-400",children:n.review.notStarted})]});const d=Es(a.items);return t.jsxs(Je,{title:f,children:[u,a.error&&t.jsx("div",{className:"text-xs text-accent",children:n.prReview.partialFetchFailed(a.error)}),a.truncated&&t.jsx("div",{className:"text-xs text-accent",children:n.prReview.listTruncated}),d.map((x,b)=>t.jsx(Ka,{round:x,index:b,onOpen:p},$s(x,String(b))))]})}function Je({title:e,children:n}){return t.jsxs("div",{children:[t.jsx("div",{className:"mb-1.5 text-xs text-og-700",children:e}),t.jsx("div",{className:"space-y-3",children:n})]})}function Ka({round:e,index:n,onOpen:s}){const r=H(),a=e.review?r.agents.round(n+1):r.status.in_progress;return t.jsxs("div",{children:[t.jsx("div",{className:"mb-1 text-xs text-og-400",children:a}),t.jsxs("div",{className:"space-y-1.5",children:[e.items.map((i,l)=>t.jsx(Fn,{item:i,onOpen:s},nt(i,`${n}-${l}`))),e.review&&t.jsx(Fn,{item:e.review,onOpen:s})]})]})}function Fn({item:e,onOpen:n}){const s=H(),r=e.verdict,a=r?t.jsx("span",{className:Ls[r],children:r}):e.kind==="review"&&e.reviewState?t.jsx("span",{className:"pill",children:e.reviewState}):void 0;return t.jsx(Ma,{role:Wa(e),label:Ga(s,e),badge:a,summary:Ua(s,e),onClick:()=>n(Et(e))})}function Va({task:e}){const n=H();return e.prNumber===void 0?null:t.jsxs("section",{className:"mt-4","aria-label":n.review.sectionTitle,children:[t.jsx("div",{className:"mb-2 text-sm text-og-700",children:n.review.sectionTitle}),t.jsx(za,{task:e})]})}const Qa=Vn;function Ya(e,n){if(!e||!n)return null;const s=e.match(/^(https?:\/\/[^/]+\/[^/]+\/[^/]+)\/pull\/\d+/);if(!s)return null;const r=n.split("/").map(encodeURIComponent).join("/");return`${s[1]}/tree/${r}`}function Mn(e){if(!/^[1-9]\d*$/.test(e.trim()))return;const n=Number(e);return Number.isSafeInteger(n)?n:void 0}function Ja(e){return e.status==="review"&&!Fe(e.phase)}function kt({children:e,open:n}){const s=H();return t.jsxs("details",{open:n,className:"mt-2 text-xs text-og-500",children:[t.jsx("summary",{className:"cursor-pointer select-none text-accent",children:s.common.technicalDetails}),t.jsx("div",{className:"mt-1 whitespace-pre-wrap break-words font-mono",children:e})]})}function Xa(){const{taskId:e=""}=At();return t.jsx(Za,{taskId:e},e)}function Za({taskId:e}){var xn;const n=Le(),s=H(),{show:r}=je(),a=ln(),[i,l]=o.useState(!1),[c,m]=o.useState(!1),[h,f]=o.useState(!1),[p,u]=o.useState(!1),[d,x]=o.useState(!1),[b,y]=o.useState("spec"),[T,C]=o.useState(""),[A,w]=o.useState(!1),[k,j]=o.useState(!1),[v,D]=o.useState(!1),[P,I]=o.useState(""),[O,J]=o.useState(!1),[E,W]=o.useState(""),[re,te]=o.useState(!1),[X,V]=o.useState(null),{data:ae,loaded:z,error:le}=Ss(e),{projects:ne,error:ge}=at(),{data:q,loaded:ie,error:me}=pn(),{activeAgentId:xe,activateAgentCard:ye}=vs(),N=X??ae,we=N!==null&&Ja(N),pe=we&&(re||((xn=N==null?void 0:N.attention)==null?void 0:xn.recommendedActions.includes("verdict"))===!0),L=(le==null?void 0:le.message)??null,G=N?ne==null?void 0:ne.find(g=>g.id===N.projectId):void 0,S=G===void 0?"unknown":G.merge==="auto"?"auto":"manual",U=ne===null&&ge===null,_=o.useMemo(()=>new Map((q??[]).map(g=>[g.id,g])),[q]);o.useEffect(()=>{X&&ae&&ae.updatedAt>=X.updatedAt&&V(null)},[X,ae]),o.useEffect(()=>{te(!1)},[N==null?void 0:N.status,N==null?void 0:N.reviewRound]);const se=g=>{V(g)},B=g=>({body:s.taskDetail.actionFailedBody,details:g instanceof Error?g.message:String(g)}),R=(g,F)=>{const Y=F??(g.status==="review"?"qa":"dev");return g.status==="pending"?g.preferredAgentId===""?s.taskDetail.editTask:s.taskDetail.startTask:Y==="qa"&&g.status!=="review"?s.taskDetail.startReview:g.status==="review"?s.taskDetail.restartReview:g.status==="approved"?s.taskDetail.retryPreMergeCheck:s.taskDetail.retryCurrentStep},$=()=>U?s.taskDetail.loadingMergeSetting:S==="auto"?s.taskDetail.confirmAndMerge:S==="manual"?s.taskDetail.confirmComplete:s.taskDetail.confirmResult,Z=async()=>{if(!N)return;const g=Vn.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})){m(!0);try{const Y=await M.tasks.update(N.id,{status:"cancelled"});se(Y),r({kind:"success",title:Y.status==="cancelled"?s.taskDetail.cancelledToastTitle:s.taskDetail.cancelCleanupToastTitle})}catch(Y){r({kind:"error",title:s.taskDetail.cancelFailedTitle,...B(Y)})}finally{m(!1)}}},K=async(g,F,Y)=>{u(!0);try{const de=await M.tasks.advance(g.id,{executor:F,...g.status==="pending"&&g.preferredAgentId?{agentId:g.preferredAgentId}:{},...Y??{}});se(de),x(!1),r({kind:"success",title:s.taskDetail.advanceSucceededTitle})}catch(de){r({kind:"error",title:s.taskDetail.advanceFailedTitle,...B(de)})}finally{u(!1)}},ee=async g=>{var ve;if(!N)return;if(N.status==="pending"&&N.preferredAgentId===""){l(!0);return}const F=g??(N.status==="review"?"qa":"dev"),Y=R(N,F);if(F==="qa"&&Wn(N)){y(N.phase??"spec"),C(((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:Y}))return;await K(N,F,{confirmRevoked:!0});return}await a({title:s.taskDetail.advanceConfirmTitle(Y),body:N.status==="pending"?s.taskDetail.startTaskConfirmBody(N.id,N.preferredAgentId):F==="qa"&&N.status==="review"?s.taskDetail.restartReviewConfirmBody(N.id):F==="qa"?s.taskDetail.startReviewConfirmBody(N.id):N.status==="approved"?s.taskDetail.retryPreMergeConfirmBody:s.taskDetail.retryCurrentStepConfirmBody(N.id),confirmLabel:Y})&&await K(N,F)},be=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 F=await M.tasks.retry(N.id);r({kind:"success",title:s.taskDetail.retryCreatedToastTitle(F.id)}),n(Pe(F.projectId,F.id))}catch(F){r({kind:"error",title:s.taskDetail.retryFailedTitle,...B(F)})}finally{f(!1)}}},Ve=async()=>{if(N&&await a({title:s.taskDetail.markCompleteConfirmTitle,body:s.taskDetail.markCompleteConfirmBody(N.prNumber??0),confirmLabel:s.taskDetail.verdictComplete})){w(!0);try{const g=await M.tasks.verdict(N.id,{action:"complete"});se(g),r({kind:"success",title:s.taskDetail.markCompleteToastTitle})}catch(g){r({kind:"error",title:s.taskDetail.markCompleteFailedTitle,...B(g)})}finally{w(!1)}}},Me=async()=>{if(N&&await a({title:s.taskDetail.continueConfirmTitle,body:s.taskDetail.continueConfirmBody(N.reviewRound+1),confirmLabel:s.taskDetail.verdictContinue})){j(!0);try{const g=await M.tasks.verdict(N.id,{action:"continue"});se(g),r({kind:"success",title:s.taskDetail.continuedToastTitle(g.reviewRound)})}catch(g){r({kind:"error",title:s.taskDetail.continueFailedTitle,...B(g)})}finally{j(!1)}}},Ee=async(g,F)=>{if(N){D(!0);try{const Y=await M.tasks.verdict(N.id,{action:g.verdict,...g.comments!==void 0?{comments:g.comments}:{}});se(Y),I(""),r({kind:"success",title:F.success})}catch(Y){r({kind:"error",title:F.failure,...B(Y)})}finally{D(!1)}}},$e=async()=>{N&&await a({title:s.taskDetail.specApproveConfirmTitle,body:s.taskDetail.specApproveConfirmBody(N.id),confirmLabel:s.taskDetail.specApprove})&&await Ee({verdict:"approve"},{success:s.taskDetail.specApprovedToastTitle,failure:s.taskDetail.specApproveFailedTitle})},Ce=async()=>{const g=P.trim();g&&await Ee({verdict:"request-changes",comments:g},{success:s.taskDetail.specRejectedToastTitle,failure:s.taskDetail.specRejectFailedTitle})},Te=async g=>{if(!N)return;const F=E.trim();if(!(g==="request-changes"&&!F||!await a({title:g==="pass"?s.taskDetail.codePassConfirmTitle:s.taskDetail.codeRejectConfirmTitle,body:s.taskDetail.codeVerdictConfirmBody,confirmLabel:g==="pass"?s.taskDetail.codePass:s.taskDetail.codeRequestChanges}))){J(!0);try{const de=await M.tasks.verdict(N.id,{action:g,...F?{comments:F}:{}});se(de),W(""),r({kind:"success",title:s.taskDetail.codeVerdictSubmittedTitle})}catch(de){r({kind:"error",title:s.taskDetail.codeVerdictFailedTitle,...B(de)})}finally{J(!1)}}},it=()=>{var g;(g=document.getElementById("task-verdict-controls"))==null||g.scrollIntoView({behavior:"smooth",block:"center"})},ot=async()=>{if(!N||U)return;const g=N.prNumber??0,F=S==="auto"?s.taskDetail.confirmAutoMergeTitle(g):S==="manual"?s.taskDetail.confirmManualCompleteTitle:s.taskDetail.confirmResultTitle,Y=S==="auto"?s.taskDetail.confirmAutoMergeBody(g):S==="manual"?s.taskDetail.confirmManualCompleteBody(g):s.taskDetail.confirmResultBody;if(await a({title:F,body:Y,confirmLabel:$()})){w(!0);try{const de=await M.tasks.verdict(N.id,{action:"confirm-merge"});se(de),r({kind:"success",title:de.status==="merged"?s.taskDetail.confirmedMergedToastTitle:s.taskDetail.confirmedCompleteToastTitle})}catch(de){r({kind:"error",title:s.taskDetail.confirmFailedTitle,...B(de)})}finally{w(!1)}}};return t.jsxs("div",{children:[t.jsx("button",{type:"button",onClick:()=>n(-1),className:"btn-ghost mb-3",children:s.common.back}),L&&!N&&t.jsx("div",{className:"text-sm text-accent",children:s.common.loadFailed(L)}),z&&!N&&!L&&t.jsx("div",{className:"text-sm text-accent",children:s.taskDetail.taskNotFound(e)}),!N&&!L&&!z&&t.jsx("div",{className:"text-sm text-og-500",children:s.common.loading}),N&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mb-4",children:t.jsxs("h1",{className:"flex min-w-0 items-baseline gap-2",children:[t.jsx("span",{className:"shrink-0 font-mono text-sm text-og-400",children:N.id}),t.jsx("span",{className:"min-w-0 truncate font-display text-sm font-semibold tracking-tight text-og-1000",title:N.title,children:N.title})]})}),t.jsxs("div",{className:"grid grid-cols-1 items-start gap-6 lg:grid-cols-2",children:[t.jsx("section",{className:"min-w-0",children:lt(N)}),t.jsx("aside",{className:"min-w-0 space-y-4",children:Oe(N)})]})]}),i&&N&&t.jsx(mn,{mode:"edit",open:!0,onClose:()=>l(!1),task:N,onUpdated:se}),d&&N&&t.jsx(Re,{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&&Mn(T)===void 0,className:"btn-primary",children:p?s.taskDetail.advancing:s.taskDetail.reviewRecoverySubmit})]}),children:t.jsxs("form",{id:"review-recovery-form",className:"space-y-4",onSubmit:g=>{g.preventDefault();const F=N.prNumber??Mn(T);F===void 0||p||K(N,"qa",{stage:b,...N.prNumber===void 0?{prNumber:F}:{}})},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:T,required:!0,disabled:p,onChange:g=>C(g.target.value),placeholder:s.taskDetail.reviewRecoveryPrNumberPlaceholder,className:he})]}),t.jsxs("div",{children:[t.jsx("label",{htmlFor:"review-recovery-stage",className:"mb-1 block text-sm text-og-700",children:s.taskDetail.reviewRecoveryStageLabel}),t.jsxs("select",{id:"review-recovery-stage",value:b,required:!0,disabled:p||N.phase!==void 0,onChange:g=>y(g.target.value),className:he,children:[t.jsx("option",{value:"spec",children:s.taskDetail.reviewRecoveryStageSpec}),t.jsx("option",{value:"code",children:s.taskDetail.reviewRecoveryStageCode})]})]})]})})]});function lt(g){var mt;const F=g.preferredAgentId==="",Y=g.status==="approved"&&g.prNumber!==void 0,de=g.status==="merge-ready"&&g.prNumber!==void 0,ve=g.status==="spec-ready",Ae=pe,$t=g.status==="max_rounds"&&!Fe(g.phase),dt=g.status==="max_rounds"&&Fe(g.phase),De=Qn(g.prUrl),ut=Ya(De??void 0,g.branch??""),_e=g.attention?gs(s,g.attention,g.status):null,It=(q??[]).some(ht=>Gn(ht,g.id));return t.jsxs("div",{children:[L&&t.jsx("div",{className:"mb-4 text-sm text-accent",children:s.common.loadFailed(L)}),g.branchCleanupPending&&t.jsxs("div",{className:"mb-4 rounded-md border border-accent/25 bg-accent-soft/60 px-3 py-2.5 text-xs text-accent",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.branchCleanupPendingTitle}),t.jsx("div",{className:"mt-1 text-og-700",children:s.taskDetail.branchCleanupPendingBody}),t.jsx(kt,{children:g.branchCleanupPending.reason})]}),g.branchCleanupSkipped&&t.jsxs("div",{className:"mb-4 rounded-md border border-hairline bg-og-25 px-3 py-2.5 text-xs text-og-700",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.branchCleanupSkippedTitle}),t.jsx("div",{className:"mt-1",children:s.taskDetail.branchCleanupSkippedBody}),t.jsx(kt,{children:g.branchCleanupSkipped.reason})]}),F&&t.jsx("div",{className:"mb-4 rounded-md border border-accent/25 bg-accent-soft/60 px-3 py-2.5 text-xs text-accent",children:g.status==="pending"?s.taskDetail.unassignedPendingNotice:s.taskDetail.unassignedReadonlyNotice}),t.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-3",children:[t.jsx(dn,{task:g,className:"text-sm"}),It&&t.jsx("span",{className:"text-sm text-og-500",title:s.taskDetail.dispatchingHint,children:s.taskDetail.dispatching}),(g.specReviewRound??0)>0&&t.jsx("span",{className:"text-sm text-og-500",children:s.taskDetail.specReviewRound(g.specReviewRound??0)}),g.reviewRound>0&&t.jsx("span",{className:"text-sm text-og-500",children:s.taskDetail.codeReviewRound(g.reviewRound)})]}),t.jsx("div",{className:"mb-4 flex flex-wrap items-center gap-2",children:qs(g)}),t.jsxs("div",{className:"mb-4 text-sm text-og-500",children:[s.taskDetail.createdAtPrefix,_t(g.createdAt,!1),s.taskDetail.updatedAtPrefix,_t(g.updatedAt,!1),g.origin&&t.jsxs(t.Fragment,{children:[s.taskDetail.originPrefix,t.jsx(Se,{to:Pe(g.projectId,g.origin.taskId),className:"underline hover:text-og-700",children:g.origin.taskId})]})]}),g.attention&&_e&&t.jsxs("div",{className:"mb-4 rounded-lg border border-accent/25 bg-accent-soft p-4 text-sm text-accent",children:[t.jsx("div",{className:"font-semibold",children:_e.title}),t.jsx("div",{className:"mt-1 text-og-700",children:_e.guidance}),t.jsx("div",{className:"mt-1 text-xs text-og-500",children:_t(g.attention.occurredAt)}),t.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:oe(g)}),t.jsx(kt,{open:_e.expandDetails,children:`${g.attention.reason}
|
|
15
|
+
${g.attention.runbook}`})]}),Y&&t.jsxs("div",{className:"mb-4 rounded-lg border border-hairline bg-og-25 p-4 text-sm text-og-800",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.approvedBannerTitle}),t.jsx("div",{className:"mt-1 text-og-700",children:s.taskDetail.approvedBannerBody}),De&&t.jsx("a",{href:De,target:"_blank",rel:"noopener noreferrer",className:"btn-secondary mt-3",children:s.taskDetail.viewPr(g.prNumber??0)})]}),de&&t.jsxs("div",{id:"task-verdict-controls",className:"mb-4 rounded-lg border border-accent/25 bg-accent-soft p-4 text-sm text-accent",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.mergeReadyBannerTitle}),t.jsx("div",{className:"mt-1 text-og-700",children:S==="auto"?s.taskDetail.mergeReadyAutoBody(g.prNumber??0):S==="manual"?s.taskDetail.mergeReadyManualBody(g.prNumber??0):U?s.taskDetail.mergeReadyLoadingBody:s.taskDetail.mergeReadyUnknownBody}),S==="unknown"&&ge&&t.jsx(kt,{children:ge}),De&&t.jsx("a",{href:De,target:"_blank",rel:"noopener noreferrer",className:"btn-secondary mt-3",children:s.taskDetail.viewPr(g.prNumber??0)})]}),ve&&t.jsxs("div",{id:"task-verdict-controls",className:"mb-4 rounded-lg border border-accent-soft bg-accent-soft/40 p-4 text-sm text-accent",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.specReadyBannerTitle}),t.jsx("div",{className:"mt-1 text-og-700",children:s.taskDetail.specReadyNotice(g.specReviewRound??0)}),Qe()]}),Ae&&t.jsxs("div",{id:"task-verdict-controls",className:`mb-4 rounded-lg p-4 text-sm ${((mt=g.attention)==null?void 0:mt.reason)==="review-verdict-overdue"?"border border-accent/25 bg-accent-soft text-accent":"border border-hairline bg-og-25 text-og-800"}`,children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.codeVerdictTitle}),t.jsx("div",{className:"mt-1 text-og-700",children:s.taskDetail.codeVerdictBody}),ct()]}),$t&&t.jsxs("div",{id:"task-verdict-controls",className:"mb-4 rounded-lg border border-accent/25 bg-accent-soft/60 p-4 text-sm text-accent",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.codeMaxRoundsTitle(g.reviewRound)}),t.jsx("div",{className:"mt-1 text-og-700",children:s.taskDetail.codeMaxRoundsBody})]}),dt&&t.jsxs("div",{id:"task-verdict-controls",className:"mb-4 rounded-lg border border-accent/25 bg-accent-soft/60 p-4 text-sm text-accent",children:[t.jsx("div",{className:"font-semibold",children:s.taskDetail.specMaxRoundsTitle(g.specReviewRound??0)}),t.jsx("div",{className:"mt-1 text-og-700",children:s.taskDetail.specMaxRoundsBody}),Qe()]}),t.jsxs("div",{className:"card mb-4 flex flex-wrap items-center gap-x-6 gap-y-1 p-4 text-sm",children:[t.jsxs("span",{className:"text-og-500",children:["PR:"," ",g.prNumber?De?t.jsxs("a",{href:De,target:"_blank",rel:"noopener noreferrer",className:"text-accent hover:text-accent-hover",children:["#",g.prNumber]}):t.jsxs("span",{className:"font-mono text-og-800",children:["#",g.prNumber]}):t.jsx("span",{className:"text-og-400",children:"—"})]}),t.jsxs("span",{className:"text-og-500",children:["Branch:"," ",g.branch?ut?t.jsx("a",{href:ut,target:"_blank",rel:"noopener noreferrer",className:"font-mono text-accent hover:text-accent-hover",children:g.branch}):t.jsx("span",{className:"font-mono text-og-800",children:g.branch}):t.jsx("span",{className:"text-og-400",children:"—"})]})]}),t.jsx("pre",{className:"card mb-4 whitespace-pre-wrap p-4 text-sm text-og-800",children:g.description||t.jsx("span",{className:"text-og-400",children:s.taskDetail.noDescription})}),t.jsx(Va,{task:g})]})}function Qe(){return t.jsxs("div",{className:"mt-3 flex flex-col gap-2",children:[t.jsx("textarea",{value:P,onChange:g=>I(g.target.value),placeholder:s.taskDetail.specCommentsPlaceholder,rows:3,disabled:v,className:he}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",disabled:v,onClick:$e,className:"btn-primary",children:v?s.taskDetail.submitting:s.taskDetail.specApproveButton}),t.jsx("button",{type:"button",disabled:v||P.trim()==="",onClick:Ce,title:P.trim()===""?s.taskDetail.specRejectTitleEmpty:s.taskDetail.specRejectTitleReady,className:"btn-secondary",children:v?s.taskDetail.submitting:s.taskDetail.specReject})]})]})}function ct(){return t.jsxs("div",{className:"mt-3 flex flex-col gap-2",children:[t.jsx("textarea",{value:E,onChange:g=>W(g.target.value),placeholder:s.taskDetail.codeCommentsPlaceholder,rows:3,disabled:O,className:he}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",disabled:O,onClick:()=>void Te("pass"),className:"btn-secondary",children:O?s.taskDetail.submitting:s.taskDetail.codePass}),t.jsx("button",{type:"button",disabled:O||E.trim()==="",onClick:()=>void Te("request-changes"),className:"btn-secondary",children:O?s.taskDetail.submitting:s.taskDetail.codeRequestChanges})]})]})}function oe(g){return g.attention?cn(g.attention,g.status).map(F=>F==="advance"?t.jsx("button",{type:"button",disabled:p,onClick:()=>void ee(),className:"btn-primary",children:p?s.taskDetail.advancing:R(g)},F):F==="verdict"?t.jsx("button",{type:"button",onClick:it,className:"btn-primary",children:s.taskDetail.handleReview},F):F==="cancel"?t.jsx("button",{type:"button",disabled:c,onClick:Z,className:"btn-secondary",children:c?s.taskDetail.cancelling:s.taskDetail.cancelConfirmLabel},F):t.jsx("button",{type:"button",disabled:h,onClick:be,className:"btn-secondary",children:h?s.common.retrying:s.taskDetail.retryTask},F)):null}function Oe(g){if(ne===null)return t.jsx("div",{className:"rounded-lg border border-hairline bg-surface px-3 py-6 text-center text-sm text-og-400",children:s.common.loading});const F=(G==null?void 0:G.agent.find(ve=>ve.some(Ae=>Ae.id===g.devAgentId)))??(g.qaAgentId?G==null?void 0:G.agent.find(ve=>ve.some(Ae=>Ae.id===g.qaAgentId)):void 0),Y=F==null?void 0:F.find(ve=>ve.role==="dev"&&ve.id===g.devAgentId),de=g.qaAgentId?F==null?void 0:F.find(ve=>ve.role==="qa"&&ve.id===g.qaAgentId):void 0;return!Y&&!de?t.jsx("div",{className:"rounded-lg border border-hairline bg-surface px-3 py-6 text-center text-sm text-og-400",children:s.taskDetail.noLinkedAgent}):t.jsxs(t.Fragment,{children:[Y?gn(g,Y):t.jsx(On,{role:"dev"}),de?gn(g,de):t.jsx(On,{role:"qa"})]})}function gn(g,F){const Y=_.get(F.id),de=Y??{id:F.id,projectId:g.projectId,runtimeStatus:"unknown",tmuxSessionStatus:"unknown",stale:!0};return t.jsx(bs,{agent:de,projectId:g.projectId,role:F.role,runtime:F.runtime,model:F.model,pendingRestart:ie&&!Y,terminalLoading:!ie&&!Y&&!me,showTaskBinding:!1,terminalMode:"embedded-full",active:xe===F.id,onActivate:()=>ye(F.id),task:g},F.id)}function qs(g){var ht,bn;const Y=g.status==="max_rounds"&&!Fe(g.phase),de=g.status==="merge-ready",ve=g.status==="pending",Ae=Qa.has(g.status),$t=Ae&&!!g.preferredAgentId,dt=g.preferredAgentId==="",De=["pending","in_progress","fixing","review","approved"].includes(g.status)&&((ht=g.attention)==null?void 0:ht.reason)!=="bootstrap-marker-clear-failed"&&(((bn=g.attention)==null?void 0:bn.reason)!=="dispatch-failed:ack_unknown"||g.status==="review")&&!(g.status==="pending"&&dt),ut=(g.status==="in_progress"||g.status==="fixing")&&g.qaAgentId!==void 0,_e=Y&&g.prNumber!==void 0,It=_e&&!!g.agentId,mt=we&&!pe;return t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",disabled:!ve,onClick:()=>l(!0),className:"btn-secondary",children:s.taskDetail.editTask}),t.jsx("button",{type:"button",disabled:c,onClick:Z,title:s.taskDetail.cancelForceTitle,className:"btn-secondary",children:c?s.taskDetail.cancelling:s.taskDetail.cancelConfirmLabel}),Ae&&g.replacementTaskId===void 0&&t.jsx("button",{type:"button",disabled:!$t||h,onClick:be,title:dt?s.taskDetail.retryDisabledUnassignedTitle:s.taskDetail.retryEnabledTitle,className:"btn-secondary",children:h?s.common.retrying:s.taskDetail.retryTask}),De&&t.jsx("button",{type:"button",disabled:p,onClick:()=>void ee(),className:"btn-primary",children:p?s.taskDetail.advancing:R(g)}),ut&&t.jsx("button",{type:"button",disabled:p,onClick:()=>void ee("qa"),className:"btn-secondary",children:R(g,"qa")}),mt&&t.jsx("button",{type:"button",onClick:()=>te(!0),className:"btn-secondary",children:s.taskDetail.handleReview}),Y&&t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",disabled:!It||k,onClick:Me,title:s.taskDetail.continueButtonTitle,className:"btn-secondary",children:k?s.taskDetail.continuing:s.taskDetail.verdictContinue}),t.jsx("button",{type:"button",disabled:!_e||A,onClick:Ve,title:s.taskDetail.completeButtonTitle,className:"btn-primary",children:A?s.taskDetail.completing:s.taskDetail.verdictComplete})]}),de&&t.jsx("button",{type:"button",disabled:A||U,onClick:ot,title:U?s.taskDetail.confirmLoadingTitle:s.taskDetail.confirmButtonTitle,className:"btn-primary",children:A?s.taskDetail.confirming:$()})]})}}function On({role:e}){const n=H();return t.jsx("div",{className:"rounded-lg border border-hairline bg-surface px-3 py-6 text-center text-sm text-og-400",children:n.taskDetail.noAgentSlot(e)})}function ei(){const{agentId:e}=At(),{projects:n}=at(),s=H(),r=o.useMemo(()=>{if(e)for(const a of n??[])for(const i of a.agent){const l=i.find(c=>c.id===e);if(l)return{runtime:l.runtime,projectId:a.id}}},[e,n]);return e?t.jsxs("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden border border-hairline bg-surface",children:[t.jsxs("div",{className:"flex h-8 flex-none select-none items-center gap-3 border-b border-hairline bg-page px-3 font-mono text-xs text-og-500",children:[t.jsx("span",{"aria-hidden":!0,className:"block h-1.5 w-1.5 rounded-full bg-og-1000"}),t.jsx("span",{className:"text-og-700",title:Kn(e,r==null?void 0:r.runtime),children:e}),r&&t.jsx(Se,{to:`/project/${encodeURIComponent(r.projectId)}`,className:"ml-auto text-accent",children:s.terminal.backToProject})]}),t.jsx("div",{className:"min-h-0 flex-1",children:t.jsx(Xe,{agentId:e,mode:"full",interactive:!0,arrowKeys:!0})})]}):t.jsx("div",{className:"text-sm text-accent",children:"No agent specified"})}const ti=65536,ni=8e3,si=["text-[18px] font-bold","text-[17px] font-bold","text-[16px] font-semibold","text-[15px] font-semibold","text-[15px] font-semibold","text-[15px] font-semibold"],ri=/^(https?:\/\/|mailto:)/i,ai=/^https?:\/\//i;function ii(e){try{const n=new URL(e).hostname.toLowerCase();return n==="githubusercontent.com"||n.endsWith(".githubusercontent.com")}catch{return!1}}function oi({src:e,alt:n}){const s=H(),[r,a]=o.useState(!1);if(r||ii(e))return t.jsx("img",{src:e,alt:n,loading:"lazy",className:"max-w-full rounded border border-hairline"});let i=e;try{i=new URL(e).hostname}catch{i=e}return t.jsxs("button",{type:"button",onClick:()=>a(!0),className:"inline-flex max-w-full items-center gap-1.5 rounded border border-hairline bg-og-25 px-2 py-1 text-xs text-og-700",children:[t.jsx("span",{className:"shrink-0",children:s.review.loadExternalImage}),n&&t.jsx("span",{className:"min-w-0 truncate text-og-500",children:n}),t.jsx("span",{className:"min-w-0 truncate font-mono text-og-400",children:i})]})}function _n(e,n){let s=-1,r=-2;return a=>(r!==-2&&a>=s&&(r===-1||a<=r)||(s=a,r=e.indexOf(n,a)),r)}function li(e){const n=/\s/g;let s=-1,r=-2;return a=>{if(r!==-2&&a>=s&&(r===-1||a<=r))return r;s=a,n.lastIndex=a;const i=n.exec(e);return r=i?i.index:-1,r}}function Hn(e,n,s){const r=n+1,a=s.bracket(r);if(a===-1||e[a+1]!=="(")return null;const i=a+2,l=s.paren(i);if(l===-1||l===i)return null;const c=s.whitespace(i);return c!==-1&&c<l?null:{label:e.slice(r,a),url:e.slice(i,l),end:l+1}}class Ms extends Error{}class ci{constructor(n){ce(this,"count",0);this.max=n}charge(){if(++this.count>this.max)throw new Ms}}function Ue(e,n,s){const r=[];let a="",i=0;const l={bracket:_n(e,"]"),paren:_n(e,")"),whitespace:li(e)},c=()=>{a!==""&&(n.charge(),r.push(a),a="")},m=f=>{c(),n.charge(),r.push(f)},h=()=>`${s}-${r.length}`;for(;i<e.length;){const f=e[i];if(f==="`"){const p=e.indexOf("`",i+1);if(p!==-1){const u=e.slice(i+1,p);c(),n.charge(),n.charge(),r.push(t.jsx("code",{className:"rounded bg-og-25 px-1 font-mono text-xs",children:u},h())),i=p+1;continue}}else if(f==="!"&&e[i+1]==="["){const p=Hn(e,i+1,l);if(p){ai.test(p.url)?m(t.jsx(oi,{src:p.url,alt:p.label},h())):a+=e.slice(i,p.end),i=p.end;continue}}else if(f==="["){const p=Hn(e,i,l);if(p){if(ri.test(p.url)){c(),n.charge();const u=Ue(p.label,n,`${s}-a${r.length}`);r.push(t.jsx("a",{href:p.url,target:"_blank",rel:"noopener noreferrer",className:"text-accent hover:text-accent-hover",children:u},h()))}else a+=e.slice(i,p.end);i=p.end;continue}}else if(f==="*"){if(e.startsWith("***",i)){const u=e.indexOf("***",i+3);if(u>i+3){c(),n.charge(),n.charge();const d=Ue(e.slice(i+3,u),n,`${s}-bi${r.length}`);r.push(t.jsx("strong",{children:t.jsx("em",{children:d})},h())),i=u+3;continue}}if(e.startsWith("**",i)){const u=e.indexOf("**",i+2);if(u>i+2){c(),n.charge();const d=Ue(e.slice(i+2,u),n,`${s}-b${r.length}`);r.push(t.jsx("strong",{children:d},h())),i=u+2;continue}}const p=e.indexOf("*",i+1);if(p>i+1){c(),n.charge();const u=Ue(e.slice(i+1,p),n,`${s}-i${r.length}`);r.push(t.jsx("em",{children:u},h())),i=p+1;continue}}a+=f,i++}return c(),r}function di(e,n){const s=[],r=e.split(`
|
|
16
16
|
`);let a=[];const i=()=>{if(a.length===0)return;const l=a;a=[],n.charge();const c=[];l.forEach((m,h)=>{h>0&&(n.charge(),c.push(t.jsx("br",{},`br-${s.length}-${h}`))),c.push(...Ue(m,n,`p${s.length}-l${h}`))}),s.push(t.jsx("p",{children:c},`p-${s.length}`))};for(let l=0;l<r.length;l++){const c=r[l];if(c.startsWith("```")){i();const h=[];let f=l+1;for(;f<r.length&&!/^```\s*$/.test(r[f]);)h.push(r[f]),f++;n.charge(),n.charge(),n.charge(),s.push(t.jsx("pre",{className:"overflow-x-auto rounded bg-og-25 p-2 font-mono text-xs",children:t.jsx("code",{children:h.join(`
|
|
17
|
-
`)})},`pre-${s.length}`)),l=f;continue}const m=/^(#{1,6}) (.*)$/.exec(c);if(m){i(),n.charge();const h=m[1].length,f=`h${h}`;s.push(t.jsx(f,{className:
|
|
18
|
-
`),n)}catch(s){if(s instanceof Ms)return null;throw s}}function
|
|
19
|
-
`),icon:"/baxian-logo.png",tag:`baxian-task-${e.id}`});i.onclick=()=>{window.focus(),s(),i.close()}}catch(a){console.warn("[task-notifications] failed to show notification:",a)}}function
|
|
17
|
+
`)})},`pre-${s.length}`)),l=f;continue}const m=/^(#{1,6}) (.*)$/.exec(c);if(m){i(),n.charge();const h=m[1].length,f=`h${h}`;s.push(t.jsx(f,{className:si[h-1],children:Ue(c,n,`h${s.length}`)},`h-${s.length}`));continue}if(c.trim()===""){i();continue}a.push(c)}return i(),s}function ui(e){if(typeof e!="string")return[];if(e.length>ti)return null;const n=new ci(ni);try{return n.charge(),di(e.replace(/\r\n/g,`
|
|
18
|
+
`),n)}catch(s){if(s instanceof Ms)return null;throw s}}function mi({text:e}){const n=o.useMemo(()=>ui(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 hi={approve:"approve","request-changes":"request-changes",comment:"comment"};function fi(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 Os(e){if(!e)return"";const n=e.match(/^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2})/);return n?`${n[1]} ${n[2]}`:e}function gi(){const e=H(),{taskId:n=""}=At(),s=Le(),{hash:r}=Un(),{data:a}=Ss(n),i=a?Is(a):void 0,{data:l,loaded:c,error:m,refresh:h,refreshing:f,refreshError:p}=Bs(n,i),[u,d]=o.useState(null),x=(l==null?void 0:l.prNumber)??(a==null?void 0:a.prNumber),b=(l==null?void 0:l.prUrl)??(a==null?void 0:a.prUrl),y=Qn(b),T=l?Es(l.items):[],C=c&&!m&&(l==null?void 0:l.available)===!0&&l.items.length>0,A=Fe(a==null?void 0:a.phase)?e.prReview.specReviewHeading:e.prReview.codeReviewHeading,w=o.useRef(null),k=o.useRef(void 0);return o.useEffect(()=>()=>clearTimeout(k.current),[]),o.useEffect(()=>{let j=null;if(r)try{j=decodeURIComponent(r.slice(1))}catch{j=null}if(!j){w.current=null,d(null);return}if(w.current===j||!C||!l)return;const v=document.getElementById(j);v&&(w.current=j,v.scrollIntoView({behavior:"smooth",block:"center"}),d(j),clearTimeout(k.current),k.current=setTimeout(()=>d(null),2e3))},[C,l,r]),t.jsxs("div",{className:"mx-auto w-full max-w-5xl",children:[t.jsx("button",{type:"button",onClick:()=>s(-1),className:"btn-ghost mb-3",children:e.common.back}),t.jsxs("div",{className:"mb-1 flex flex-wrap items-baseline gap-2",children:[t.jsx("span",{className:"font-mono text-og-400",children:n}),t.jsx("span",{className:"text-sm font-semibold text-og-1000",children:(a==null?void 0:a.title)??""})]}),t.jsxs("div",{className:"mb-4 flex flex-wrap items-center gap-2 text-xs text-og-500",children:[t.jsx("span",{className:"pill",children:A}),y&&x!==void 0&&t.jsx("a",{href:y,target:"_blank",rel:"noopener noreferrer",className:"text-accent hover:text-accent-hover",children:e.taskDetail.viewPr(x)}),(l==null?void 0:l.available)&&t.jsx(Fs,{data:l,onRefresh:h,refreshing:f,refreshError:p})]}),!c&&t.jsx("div",{className:"text-sm text-og-500",children:e.common.loading}),c&&m&&t.jsx("div",{className:"text-sm text-accent",children:e.review.loadFailed(m)}),c&&!m&&l&&!l.available&&t.jsx("div",{className:"text-sm text-og-500",children:pi(e)[fi(l.reason)??"no-pr"]}),c&&!m&&(l==null?void 0:l.available)&&(l.items.length===0?l.truncated?t.jsx("div",{className:"text-sm text-accent",children:e.prReview.listTruncated}):l.error?t.jsx("div",{className:"text-sm text-accent",children:e.prReview.fetchFailed(l.error)}):t.jsx("div",{className:"text-sm text-og-400",children:e.review.notStarted}):t.jsxs(t.Fragment,{children:[l.error&&t.jsx("div",{className:"mb-3 text-xs text-accent",children:e.prReview.partialFetchFailed(l.error)}),l.truncated&&t.jsx("div",{className:"mb-3 text-xs text-accent",children:e.prReview.listTruncated}),t.jsx("div",{className:"space-y-5",children:T.map((j,v)=>t.jsx(xi,{round:j,index:v,flashId:u},$s(j,String(v))))})]}))]})}function xi({round:e,index:n,flashId:s}){const r=H(),a=e.review?r.agents.round(n+1):r.status.in_progress;return t.jsxs("div",{children:[t.jsx("div",{className:"mb-1.5 text-xs font-medium text-og-700",children:a}),t.jsxs("div",{className:"space-y-2",children:[e.items.map((i,l)=>i.kind==="review"?t.jsx(qn,{item:i,flashId:s},nt(i,`${n}-${l}`)):t.jsx(bi,{item:i,flashId:s},nt(i,`${n}-${l}`))),e.review&&t.jsx(qn,{item:e.review,flashId:s})]})]})}function _s(e,n){const s=Et(e);return`card p-3 text-sm${s&&s===n?" ring-2 ring-accent":""}`}function bi({item:e,flashId:n}){const s=H(),r=e.kind==="review-comment";return t.jsxs("div",{id:Et(e),className:_s(e,n),children:[t.jsxs("div",{className:"mb-1 flex flex-wrap items-center gap-2",children:[t.jsx("span",{className:"pill shrink-0",children:r?s.prReview.inlineComment:s.prReview.comment}),e.author?t.jsx("span",{className:"font-medium text-og-700",children:e.author}):t.jsx("span",{className:"text-xs italic text-og-400",children:s.prReview.ghostAuthor}),r&&e.path&&t.jsx("span",{className:"min-w-0 break-all font-mono text-xs text-og-500",children:e.line!==void 0?`${e.path}:${e.line}`:e.path}),e.inReplyTo&&t.jsx("span",{className:"text-xs text-og-400",children:s.prReview.replyIndicator}),e.createdAt&&t.jsx("span",{className:"text-xs text-og-400",children:Os(e.createdAt)})]}),t.jsx(Hs,{item:e})]})}function qn({item:e,flashId:n}){const s=H(),r=e.verdict??"comment";return t.jsxs("div",{id:Et(e),className:_s(e,n),children:[t.jsxs("div",{className:"mb-1 flex flex-wrap items-center gap-2",children:[t.jsx("span",{className:"shrink-0 min-w-[1.75rem] text-xs font-semibold tracking-wide text-og-600",children:s.review.roleQa}),t.jsx("span",{className:Ls[r],children:hi[r]}),e.reviewState&&t.jsx("span",{className:"pill shrink-0",children:e.reviewState}),e.author?t.jsx("span",{className:"text-xs text-og-400",children:e.author}):t.jsx("span",{className:"text-xs italic text-og-400",children:s.prReview.ghostAuthor}),e.commitSha&&t.jsx("span",{className:"font-mono text-xs text-og-500",children:e.commitSha.slice(0,9)}),!e.commitSha&&e.anchorSha&&t.jsx("span",{className:"font-mono text-xs text-og-500",children:e.anchorSha.slice(0,9)}),e.createdAt&&t.jsx("span",{className:"text-xs text-og-400",children:Os(e.createdAt)})]}),t.jsx(Hs,{item:e,placeholder:s.prReview.noReviewBody})]})}function Hs({item:e,placeholder:n}){const s=H();return t.jsxs(t.Fragment,{children:[e.body?t.jsx("div",{className:"text-og-800",children:t.jsx(mi,{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 vi(){const e=H(),[n,s]=o.useState(!1);return t.jsx("button",{type:"button",onClick:()=>s(r=>!r),"aria-label":n?e.nav.toggleToIcon:e.nav.toggleToText,className:"flex h-7 min-w-[60px] shrink-0 items-center justify-center font-display text-sm font-semibold tracking-tight text-og-1000",children:n?t.jsx("span",{className:"inline-flex h-6 items-center leading-none",children:"baxian"}):t.jsx("img",{src:"/baxian-logo.png",alt:"baxian",width:20,height:24,className:"block h-6 w-auto"})})}function yi(){const[e,n]=o.useState(null),[s,r]=o.useState(!1),[a,i]=o.useState(null);return o.useEffect(()=>rt().subscribe("pollers",c=>{i(null),n(c),r(!0)},c=>i(c)),[]),{data:e,loaded:s,error:a}}function wi(e){return e.lastErrorClass==="RATE_LIMIT"&&e.rateLimitedUntil!==void 0&&Date.parse(e.rateLimitedUntil)>Date.now()}function ki(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(wi);if(a)return{poller:a,kind:"rate-limited"};const i=e.find(l=>l.health==="degraded");return i?{poller:i,kind:"degraded"}:null}function ji(){const e=H(),{data:n}=yi();if(!n)return null;const s=ki(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 Ti(){const e=H(),{phase:n,count:s,error:r,triggerRestart:a}=Lt();return n==="idle"?null:n==="failed"?t.jsxs("div",{className:"flex items-center justify-between border-b border-accent/25 bg-accent-soft px-4 py-2",children:[t.jsx("div",{className:"text-sm text-accent",children:e.banner.restartFailed(r??"")}),t.jsx("button",{onClick:()=>{a()},className:"btn-ghost",children:e.common.retry})]}):n==="restarting"?t.jsx("div",{className:"border-b border-accent-soft bg-accent-soft/40 px-4 py-2 text-sm text-accent",children:e.banner.restarting}):t.jsxs("div",{className:"flex items-center justify-between border-b border-accent/25 bg-accent-soft/60 px-4 py-2",children:[t.jsx("div",{className:"text-sm text-accent",children:e.banner.pendingNotice(s)}),t.jsx("button",{onClick:()=>{a()},className:"btn-primary",children:e.banner.restartNow})]})}const Ni=new Set(["done","merged"]);function Kt(e,n){const s=e.trim().replace(/\s+/g," ");return s.length>n?`${s.slice(0,n-1)}…`:s}function Si(e,n){return e?e.repo?`${e.id} · ${e.repo}`:e.id:n}function Ri(e){return e.title?`${e.id} · ${e.title}`:e.id}function Ci(e){return Ni.has(e)}function Ai(e,n,s){const r=fn();if(!(!r||r.permission!=="granted"))try{const a=ns(),i=new r(a.notification.taskDone(Kt(e.title||e.id,80)),{body:[a.notification.bodyProject(Kt(n,120)),a.notification.bodyTask(Kt(Ri(e),120)),a.notification.bodyStatus(Vr(e.status))].join(`
|
|
19
|
+
`),icon:"/baxian-logo.png",tag:`baxian-task-${e.id}`});i.onclick=()=>{window.focus(),s(),i.close()}}catch(a){console.warn("[task-notifications] failed to show notification:",a)}}function Di(e,n,s){const r=o.useRef(new Map),a=o.useRef(new Set),i=o.useRef(new Map),l=o.useRef(new Set),c=o.useRef(new Set),m=o.useRef(new Map),h=o.useRef(n),f=o.useRef(new Map),p=o.useMemo(()=>s?(e??[]).map(u=>u.id).sort().join("\0"):"",[s,e]);o.useEffect(()=>{h.current=n},[n]),o.useEffect(()=>{f.current=new Map((e??[]).map(u=>[u.id,Si(u,u.id)]))},[e]),o.useEffect(()=>{const u=y=>{m.current.set(y,(m.current.get(y)??0)+1)};if(p===""){for(const y of c.current)u(y);c.current=new Set,r.current.clear(),i.current.clear(),l.current.clear();return}const d=p.split("\0"),x=new Set(d);for(const y of c.current)x.has(y)||u(y);c.current=x;for(const y of r.current.keys())x.has(y)||r.current.delete(y);for(const y of i.current.keys())x.has(y)||i.current.delete(y);const b=d.map(y=>rt().subscribe(`project-tasks:${y}`,T=>{const C=r.current.get(y),A=new Map(T.map(k=>[k.id,k]));r.current.set(y,A);const w=i.current.get(y)??new Set;if(i.current.set(y,w),!C){for(const k of A.keys())w.delete(k);return}for(const[k]of C)A.has(k)||a.current.has(k)||w.add(k);for(const k of[...w]){if(A.has(k)){w.delete(k);continue}const j=m.current.get(y)??0,v=`${y}:${j}:${k}`;l.current.has(v)||(l.current.add(v),M.tasks.get(k).then(D=>{if((m.current.get(y)??0)!==j)return;if(!D||D.projectId!==y||!Ci(D.status)){w.delete(k);return}w.delete(k),a.current.add(D.id);const P=f.current.get(y)??y;Ai(D,P,()=>h.current(D))}).catch(D=>{console.warn(`[task-notifications] failed to confirm completed task ${k}:`,D)}).finally(()=>{l.current.delete(v)}))}},T=>{console.warn(`[task-notifications] project task stream failed for ${y}:`,T)}));return()=>{for(const y of b)y()}},[p])}function Pi(){const e=Un(),n=Le(),{projects:s}=at(),{enabled:r}=js(),a=!e.pathname.startsWith("/terminal/");return hr(),Di(s,i=>n(Pe(i.projectId,i.id)),r),t.jsxs("div",{className:"flex h-dvh flex-col bg-page",children:[t.jsxs("nav",{className:"flex h-12 flex-none items-center border-b border-hairline bg-surface px-3 sm:px-6",children:[t.jsxs(Se,{to:"/",className:"flex shrink-0 items-center gap-2 font-display text-sm font-semibold tracking-tight text-og-1000",children:[t.jsx("span",{"aria-hidden":!0,className:"block h-2.5 w-2.5 rounded-full bg-accent"}),"baxian"]}),t.jsx("div",{id:Ts,className:"ml-auto flex min-w-0 items-center justify-end gap-2"})]}),t.jsx(Ti,{}),t.jsx(ji,{}),t.jsxs("main",{className:"flex min-h-0 flex-1 flex-col overflow-y-auto px-3 py-6 sm:px-6",children:[t.jsxs(Xs,{children:[t.jsx(Ye,{path:"/",element:t.jsx(Ta,{})}),t.jsx(Ye,{path:"/project/:id",element:t.jsx($a,{})}),t.jsx(Ye,{path:"/project/:id/task/:taskId",element:t.jsx(Xa,{})}),t.jsx(Ye,{path:"/terminal/:agentId",element:t.jsx(ei,{})}),t.jsx(Ye,{path:"/tasks/:taskId/pr-review",element:t.jsx(gi,{})})]}),a&&t.jsx("footer",{className:"mt-auto flex justify-center pb-4 pt-24",children:t.jsx(vi,{})})]})]})}function Li(){return t.jsx(Js,{children:t.jsx(pa,{children:t.jsx(Pi,{})})})}function Ei({children:e}){const n=H(),[s,r]=o.useState({kind:"probing"}),a=o.useRef(s);o.useEffect(()=>{a.current=s},[s]);const i=o.useCallback(async()=>{r({kind:"probing"});try{const c=await M.config.get();Qt(c.language),r({kind:"authorized"})}catch(c){if(c instanceof ze&&c.status===401){r({kind:"unauthorized"});return}r({kind:"error",message:c instanceof Error?c.message:void 0,fallback:"connectFallback"})}},[]);if(o.useEffect(()=>{i()},[i]),o.useEffect(()=>{const c=()=>{a.current.kind!=="probing"&&r({kind:"unauthorized",reason:"expired"})};return window.addEventListener(et,c),()=>window.removeEventListener(et,c)},[]),s.kind==="authorized")return t.jsx(t.Fragment,{children:e});if(s.kind==="error")return t.jsxs(en,{title:n.auth.connectFailedTitle,children:[t.jsx("p",{className:"text-sm text-og-600",children:s.message??n.auth[s.fallback]}),t.jsx("button",{type:"button",onClick:()=>{i()},className:"btn-primary mt-4 w-full",children:n.common.retry})]});if(s.kind==="probing")return t.jsx(en,{title:n.auth.checkingTitle,children:t.jsx("p",{className:"text-sm text-og-500",children:n.auth.checkingBody})});const l=s.reason==="expired"?n.auth.sessionExpired:s.reason==="invalid"?n.auth.tokenInvalid:void 0;return t.jsx($i,{message:l,onSubmit:async c=>{tr(c);try{const m=await M.config.get();Qt(m.language),r({kind:"authorized"})}catch(m){if(nr(),m instanceof ze&&m.status===401){r({kind:"unauthorized",reason:"invalid"});return}r({kind:"error",message:m instanceof Error?m.message:void 0,fallback:"loginFailed"})}}})}function en({title:e,children:n}){return t.jsx("div",{className:"flex min-h-dvh items-center justify-center bg-page px-4",children:t.jsxs("div",{className:"w-full max-w-sm rounded-lg border border-hairline bg-surface px-6 py-6",children:[t.jsx("h1",{className:"mb-3 font-display text-sm font-semibold tracking-tight text-og-1000",children:e}),n]})})}function $i({message:e,onSubmit:n}){const s=H(),[r,a]=o.useState(""),[i,l]=o.useState(!1),[c,m]=o.useState(void 0),h=async p=>{p.preventDefault();const u=r.trim();if(!u){m(s.auth.tokenRequired);return}m(void 0),l(!0);try{await n(u)}finally{l(!1)}},f=c??e;return t.jsxs(en,{title:s.auth.loginTitle,children:[t.jsx("p",{className:"mb-4 text-sm text-og-600",children:s.auth.loginDescription}),t.jsxs("form",{onSubmit:p=>{h(p)},children:[t.jsx("label",{className:ue,htmlFor:"baxian-token",children:s.auth.tokenLabel}),t.jsx("input",{id:"baxian-token",type:"password",autoComplete:"current-password",autoFocus:!0,value:r,onChange:p=>a(p.target.value),className:`${he} font-mono`,placeholder:s.auth.tokenPlaceholder,disabled:i}),f&&t.jsx("p",{role:"alert",className:"mt-2 text-xs text-accent",children:f}),t.jsx("button",{type:"submit",disabled:i,className:"btn-primary mt-4 w-full",children:i?s.auth.submitting:s.auth.submit})]})]})}zs.createRoot(document.getElementById("root")).render(t.jsx(o.StrictMode,{children:t.jsx(mr,{children:t.jsx(Tr,{children:t.jsx(xr,{children:t.jsx(vr,{children:t.jsx(Ei,{children:t.jsx(Li,{})})})})})})}));
|
package/dist/web/index.html
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
<link rel="icon" type="image/png" href="/baxian-logo.png" />
|
|
7
7
|
<link rel="apple-touch-icon" href="/baxian-logo.png" />
|
|
8
8
|
<title>baxian</title>
|
|
9
|
-
<script type="module" crossorigin src="/assets/index-
|
|
9
|
+
<script type="module" crossorigin src="/assets/index-0zP-ekk7.js"></script>
|
|
10
10
|
<link rel="modulepreload" crossorigin href="/assets/react-BFCkCmbU.js">
|
|
11
11
|
<link rel="modulepreload" crossorigin href="/assets/xterm-DYzQPKhn.js">
|
|
12
12
|
<link rel="modulepreload" crossorigin href="/assets/router-BgSDZqI0.js">
|