@vibedeckx/ui-dist 0.3.55 → 0.3.56
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.
- package/package.json +1 -1
- package/ui/404/index.html +2 -2
- package/ui/404.html +2 -2
- package/ui/__next.__PAGE__.txt +2 -2
- package/ui/__next._full.txt +6 -6
- package/ui/__next._head.txt +1 -1
- package/ui/__next._index.txt +5 -5
- package/ui/__next._tree.txt +2 -2
- package/ui/_next/static/chunks/{82f956dc117bd57d.js → 473c63f718b9eb2b.js} +6 -17
- package/ui/_next/static/chunks/{d4b86a3e81520116.js → 61826ba4f9172010.js} +1 -1
- package/ui/_next/static/chunks/f33043cc975fc94b.css +1 -0
- package/ui/_not-found/__next._full.txt +5 -5
- package/ui/_not-found/__next._head.txt +1 -1
- package/ui/_not-found/__next._index.txt +5 -5
- package/ui/_not-found/__next._not-found.__PAGE__.txt +1 -1
- package/ui/_not-found/__next._not-found.txt +1 -1
- package/ui/_not-found/__next._tree.txt +2 -2
- package/ui/_not-found/index.html +2 -2
- package/ui/_not-found/index.txt +5 -5
- package/ui/build-id.json +1 -1
- package/ui/index.html +2 -2
- package/ui/index.txt +6 -6
- package/ui/_next/static/chunks/97b3ea70c78997f8.css +0 -1
- /package/ui/_next/static/{uEwO5wufGJaEnCuGJjVfd → gErEhnRtoHScmuwSc-lqj}/_buildManifest.js +0 -0
- /package/ui/_next/static/{uEwO5wufGJaEnCuGJjVfd → gErEhnRtoHScmuwSc-lqj}/_clientMiddlewareManifest.json +0 -0
- /package/ui/_next/static/{uEwO5wufGJaEnCuGJjVfd → gErEhnRtoHScmuwSc-lqj}/_ssgManifest.js +0 -0
|
@@ -33,28 +33,17 @@ ${T1}`:T1:[...c,{type:"text",text:T1}]),"task"===e5&&(d=f,f="string"==typeof d?d
|
|
|
33
33
|
|
|
34
34
|
${T5}`:T5:[...d,{type:"text",text:T5}]),f=function(e,r){if(0===r.length)return e;let s=[`<vselected-tasks note="${T7("Tasks the user selected from the project's task list for this message, with their content as of selection. Act on what the user says about them. To change one, propose it with propose_task_update and its id; to file sub-tasks, pass its id as parent_task_id to propose_task. Never change a task unless the user asks. A task's existing direct sub-tasks are listed as <subtask> entries; read one in full with get_task when available. When you mention one to the user, link it as [title](#ref:task:<id>).")}">`,...r.map(e=>[`<task id="${T7(e.id)}" title="${T7(e.title)}" status="${e.status}" priority="${e.priority}">`,(e.description?.trim()||"(no description)").replace(/<\/(task|vselected-tasks)>/gi,"<\\/$1>"),...(e.subtasks??[]).map(e=>`<subtask id="${T7(e.id)}" title="${T7(e.title)}" status="${e.status}" />`),"</task>"].join("\n")),"</vselected-tasks>"].join("\n");return"string"==typeof e?e.length>0?`${e}
|
|
35
35
|
|
|
36
|
-
${s}`:s:[...e,{type:"text",text:s}]}(f,e9),ey){let e;console.log(`[AgentConversation] handleSubmit: existing session ${ey.id}, status=${ew}`);try{e=await eL(f,void 0,to.selectedIds)}catch(e){return await w("Failed to send message",e)}if(!1===e){if(ev(r)&&(T(s),p(),M(A),F(I)),y(),n)throw Error("Failed to send message");return}b()}else{t2(m??t1.current)||await g();let e=m?.prepared??null;m=null;let i=to.selectedIds,a=e?await eW(e,f,i,to.adoptInto):await eB(f,P,ee,i,to.adoptInto);if(a)b(),console.log(`[AgentConversation] handleSubmit: started session ${a.session.id}`),ex(r)&&ei(a.session.id);else if(ev(r)&&(T(s),p(),M(A),F(I)),y(),n)throw Error("Failed to start session")}}finally{V.current===l&&(V.current=null,H(!1),q(!1))}},{settings:t9}=(0,dh.useConversationSettings)();return e?(0,B.jsxs)("div",{className:"h-full flex flex-col min-h-0",style:{"--conv-font-size":`${t9.agentFontSize}px`},children:[(0,B.jsxs)("div",{className:"flex-shrink-0 flex items-center justify-between px-4 h-10 border-b border-border/60 bg-muted/20",children:[(0,B.jsxs)("div",{className:"flex items-center gap-2",children:[J.length>1?(0,B.jsxs)(a_,{children:[(0,B.jsx)(aS,{asChild:!0,children:(0,B.jsxs)("button",{disabled:ej||"running"===ew&&eb.length>0,className:(0,eR.cn)("inline-flex items-center gap-1 rounded-md border bg-muted/50 px-2 py-0.5 text-xs font-medium transition-colors hover:bg-muted",(ej||"running"===ew&&eb.length>0)&&"opacity-50 cursor-not-allowed"),children:[(0,B.jsx)(ME,{type:X}),(0,B.jsx)(Mr,{candidates:J.map(e=>e.displayName),children:tw}),(0,B.jsx)(aI,{className:"h-3 w-3 text-muted-foreground"})]})}),(0,B.jsx)(aj,{align:"start",className:"min-w-[var(--radix-dropdown-menu-trigger-width)]",children:(0,B.jsx)(aN,{value:X,onValueChange:async e=>{if(!ey){e!==X&&et(null),Y(e);return}let r=await eV(e);r?xN.toast.error("Failed to switch agent",{description:r}):Y(e)},children:J.map(e=>(0,B.jsxs)(aE,{value:e.type,disabled:!e.available,className:"text-xs pl-2 [&>span:first-child]:hidden data-[state=checked]:bg-accent data-[state=checked]:text-accent-foreground",children:[(0,B.jsx)(ME,{type:e.type}),e.displayName]},e.type))})})]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(ME,{type:X,className:"h-4 w-4"}),(0,B.jsx)("span",{className:"text-sm font-medium",children:tw})]}),(0,B.jsx)(Mo,{models:J.find(e=>e.type===X)?.models??[],widthCandidates:J.flatMap(e=>e.models??[]),value:ey?ey.model??null:ee,onChange:ey?tg:et,locked:null!=ey&&"running"===ew&&eb.length>0}),(0,B.jsx)(MN,{mode:P,onModeChange:tm}),ef.length>=1&&o&&(0,B.jsx)(kV,{targets:ef,activeTarget:a?.agent_mode??"local",onTargetChange:o}),ey&&(C=ey.id.startsWith("remote-"),N="text-muted-foreground",E=(0,B.jsx)(dH,{className:"h-3 w-3"}),D="Disconnected",ek?(N="text-muted-foreground",E=(0,B.jsx)(a7,{className:"h-3 w-3 animate-spin"}),D="Checking for newer output..."):e_?C&&"connected"!==eN&&null!==eN?"reconnecting"===eN?(N="text-amber-500",E=(0,B.jsx)(AV,{className:"h-3 w-3 animate-pulse"}),D="Reconnecting..."):"disconnected"===eN&&(N="text-red-500",E=(0,B.jsx)(dH,{className:"h-3 w-3"}),D="Remote disconnected"):(N="text-green-500",E=(0,B.jsx)(AV,{className:"h-3 w-3"}),D="Connected"):tf||(N="text-amber-500",E=(0,B.jsx)(AV,{className:"h-3 w-3 animate-pulse"}),D="Connecting..."),(0,B.jsx)(Mt,{label:D,children:(0,B.jsx)("span",{className:`flex items-center ${N}`,role:"img","aria-label":D,children:E})}))]}),(0,B.jsxs)("div",{className:"flex items-center gap-1",children:[e&&(0,B.jsx)(MY,{projectId:e,branch:r,sessionId:ey?.id??null,currentAgentType:X,providers:J,shortcutEnabled:tX,onStarted:e=>b?.(e,tW)}),e&&(0,B.jsx)(MF,{projectId:e,branch:r,currentSessionId:ey?.id??null,refreshKey:er,pendingTitleSessionId:en,aiTitleOverride:ea,onSwitch:e=>{u?.(e),i?.(e)},onDelete:(e,r)=>{if(e===ey?.id){let e=r[0];i?.(e?e.id:null)}}}),(0,B.jsx)(Mt,{label:"New Conversation (⌘⇧O / Ctrl+Shift+O)",children:(0,B.jsx)("span",{className:"inline-flex",children:(0,B.jsx)(Z.Button,{variant:"ghost",size:"icon",onClick:tJ,disabled:ej||!ey,className:"h-7 w-7","aria-label":"New Conversation",children:(0,B.jsx)(AX,{className:"h-3.5 w-3.5"})})})}),(0,B.jsxs)(Z.Button,{variant:"ghost",size:"sm",onClick:()=>eK(),disabled:"running"!==ew,className:"h-7 text-xs",children:[(0,B.jsx)(cb,{className:"h-3 w-3 mr-1"}),"Stop"]})]})]}),t$&&(0,B.jsxs)("div",{className:"flex items-center gap-2 px-4 py-1.5 border-b bg-muted/40 text-xs text-muted-foreground shrink-0","data-testid":"source-preparing-review",children:[(0,B.jsx)(a7,{className:"h-3 w-3 animate-spin shrink-0"}),(0,B.jsx)("span",{className:"flex-1 truncate",children:"Preparing review — summarizing this conversation and starting the reviewer"}),w&&(0,B.jsx)("button",{type:"button",className:"shrink-0 font-medium text-foreground/80 hover:text-foreground underline-offset-2 hover:underline",onClick:()=>w(t$.runId),children:"View"})]}),(0,B.jsxs)("div",{className:"flex-1 min-h-0 relative",children:[(0,B.jsxs)(dc,{className:"h-full",initial:"instant",resize:tI?"smooth":"instant",children:[(0,B.jsx)(dd,{className:"gap-1 p-4 mx-auto w-full max-w-[1200px]",scrollClassName:"edge-scrollbar will-change-transform",children:tO?(0,B.jsx)(MG,{children:tH}):tB?(0,B.jsx)(MJ,{error:tP?.error,children:tH}):ey||0!==eb.length?(0,B.jsx)(M4.Provider,{value:{sendMessage:eL,messages:eb,acceptPlan:tx,permissionMode:ey?.permissionMode??P,agentType:ey?.agentType??X,sessionId:ey?.id??null,projectId:e,branch:r,target:ep,targetLabel:em,openSchedule:x,openTask:v},children:(0,B.jsxs)("div",{className:"space-y-1 outline-none",ref:el,tabIndex:-1,onKeyDown:ec,children:[ey?.lifecycleState==="activation_uncertain"&&(0,B.jsxs)("div",{className:"flex items-start gap-2 p-3 mb-2 rounded-lg border border-amber-500/40 bg-amber-500/10 text-sm text-amber-700 dark:text-amber-400",children:[(0,B.jsx)(a5,{className:"h-4 w-4 mt-0.5 shrink-0"}),(0,B.jsx)("span",{children:"First message delivery could not be confirmed for this session. Check whether the agent actually responded before resending — a resend may duplicate the task."})]}),eI&&(0,B.jsx)("div",{className:"flex justify-center pb-3",children:(0,B.jsxs)(Z.Button,{type:"button",variant:"ghost",size:"sm",disabled:eF,onClick:()=>void eP(),children:[eF?(0,B.jsx)(a7,{className:"h-3.5 w-3.5 animate-spin"}):(0,B.jsx)(aI,{className:"h-3.5 w-3.5 rotate-180"}),"Load earlier turns"]})}),eb.map((e,r)=>e?.type==="turn_end"?(0,B.jsx)(A2,{durationMs:e.durationMs,outcome:e.outcome,emphasis:r===tM?"normal":"subtle",agentType:X,currentAgentName:tw,alternateProviders:t_,onBranch:e=>tb(e,tt[r]??r),disabled:tv,showFinalize:r===tM&&tF?.status==="discussing",finalizeBusy:tU,onFinalize:tK,sendBack:tS&&(tt[r]??r)>tj?{available:!tD&&ey?.branchedFromAvailable!==!1,sent:tk.has(tt[r]??r),busy:tN===(tt[r]??r),onSend:()=>void tA(tt[r]??r,r)}:void 0},tt[r]??r):(0,B.jsx)("div",{"data-message-idx":r,..."user"===e.type?{"data-user-msg-idx":r}:{},className:"scroll-mt-2",children:(0,B.jsx)(Ae,{message:e,messageIndex:r,entryIndex:tt[r]??r,streaming:"assistant"===e.type&&tI&&r===eb.length-1})},tt[r]??r)),ej&&!ek&&(0,B.jsxs)("div",{className:"flex items-center gap-2 py-4 text-muted-foreground",children:[(0,B.jsx)(AL,{className:"h-4 w-4"}),(0,B.jsx)("span",{className:"text-sm",children:"Connecting to agent..."})]})]})}):(0,B.jsx)("div",{className:"text-center py-16",children:ej||e&&!eS?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(AL,{className:"h-6 w-6 mx-auto mb-4"}),(0,B.jsx)("h3",{className:"text-sm font-semibold mb-1 text-foreground",children:"Connecting to agent..."}),(0,B.jsx)("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"Setting up the session for this worktree"})]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)("div",{className:"mx-auto w-12 h-12 rounded-xl bg-primary/10 flex items-center justify-center mb-4",children:(0,B.jsx)(a3,{className:"h-6 w-6 text-primary/60"})}),(0,B.jsx)("h3",{className:"text-sm font-semibold mb-1 text-foreground",children:"Start a conversation"}),(0,B.jsx)("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"Ask the agent to help you with coding tasks in this worktree"})]})})}),(0,B.jsx)(du,{}),(0,B.jsx)(Mz,{messageCount:eb.length,turnInFlight:tI,sessionId:ey?.id??null})]}),(0,B.jsx)(MM,{messages:eb,contentRef:el}),(0,B.jsx)(M$,{containerRef:el,onQuote:tG})]}),(0,B.jsx)("div",{className:"flex-shrink-0 py-3 px-[14px]",children:(0,B.jsxs)("div",{className:"mx-auto w-full max-w-[1200px] px-4",children:[(0,B.jsx)(A9,{sessionId:tr,tasks:eD.tasks,turnParked:eD.turnParked,parkDeadlineAt:eD.parkDeadlineAt,canStopTasks:eD.canStopTasks,agentWorking:"running"===ew}),eC&&(0,B.jsxs)("div",{className:"flex items-center gap-2 p-3 mb-2 bg-red-500/10 rounded-lg text-red-500 text-sm",children:[(0,B.jsx)(a5,{className:"h-4 w-4 shrink-0"}),(0,B.jsx)("span",{className:"min-w-0 break-words",children:eC})]}),(0,B.jsxs)(Aj,{onSubmit:t8,maxFileSize:0x1400000,onError:t7,skipAttachmentConversion:!0,className:"w-full",children:[(0,B.jsx)(M3,{uploads:t4,workspaceKey:`${e}::${r}`,apiRef:t6}),(0,B.jsxs)("div",{className:"relative flex w-full flex-col",children:[ta&&(0,B.jsx)(Mm,{granted:to.granted,onRevoke:e=>to.toggle(e,!1)}),(0,B.jsx)(Mb,{tasks:e9,onRemove:e=>te(e,!1)}),z&&(0,B.jsx)("div",{className:"flex items-center pl-12 pr-2 pt-1.5 pb-0.5",children:(0,B.jsxs)("button",{type:"button",onClick:()=>O(!1),className:"inline-flex shrink-0 items-center gap-1.5 rounded-full bg-blue-500/10 text-blue-600 dark:text-blue-400 px-2.5 py-0.5 text-xs font-medium hover:bg-blue-500/20 transition-colors",children:[W?(0,B.jsx)(a7,{className:"size-3 animate-spin"}):(0,B.jsx)(AY,{className:"size-3"}),"Translate",(0,B.jsx)(ro,{className:"size-3"})]})}),e5&&(0,B.jsx)("div",{className:"flex items-center pl-12 pr-2 pt-1.5 pb-0.5",children:(0,B.jsxs)("button",{type:"button",onClick:()=>e2(null),className:"inline-flex shrink-0 items-center gap-1.5 rounded-full bg-blue-500/10 text-blue-600 dark:text-blue-400 px-2.5 py-0.5 text-xs font-medium hover:bg-blue-500/20 transition-colors",children:[e3?(0,B.jsx)(a4,{className:"size-3"}):(0,B.jsx)(D_,{className:"size-3"}),e3?"Schedule":"Add task",(0,B.jsx)(ro,{className:"size-3"})]})}),(0,B.jsxs)("div",{className:"flex w-full items-center",children:[(0,B.jsxs)(AD,{children:[(0,B.jsx)(AR,{className:"ml-1"}),(0,B.jsxs)(AT,{children:[(0,B.jsx)(AS,{label:"Add files"}),ta&&(0,B.jsx)(Mp,{granted:to.granted,onToggle:to.toggle,sourceRemoteId:tl}),(0,B.jsxs)(AA,{role:"menuitemcheckbox","aria-checked":e3,onSelect:()=>e6("schedule"),children:[(0,B.jsx)(a4,{className:"mr-2 size-4"}),"Schedule",e3&&(0,B.jsx)(rj.Check,{className:"ml-auto size-4"})]}),(0,B.jsxs)(AA,{role:"menuitemcheckbox","aria-checked":e4,onSelect:()=>e6("task"),children:[(0,B.jsx)(D_,{className:"mr-2 size-4"}),"Add task",e4&&(0,B.jsx)(rj.Check,{className:"ml-auto size-4"})]}),(0,B.jsx)(My,{projectId:e,selected:e9,onToggle:te}),(0,B.jsxs)(AA,{onSelect:()=>{O(!z)},children:[(0,B.jsx)(AY,{className:"mr-2 size-4"}),z?"Disable translation":"Translate"]})]})]}),(0,B.jsx)("div",{ref:ed,className:"contents",children:(0,B.jsx)(Ak,{value:R,onChange:e=>T(e.target.value),onPasteText:tQ,onKeyDown:eu.handleKeyDown,placeholder:e3?ey?"Send to turn this session's work into a schedule. You can add requirements and when it should run":"What should run, and how often? e.g. every weekday at 9am, run the tests and report failures":e4?ey?"Send to record follow-up work from this session as a task. You can say what to include":"What should be recorded as a task for later?":ey?"Ask the agent to help with your code...":"Type your first message to start...",className:"pr-12",style:{fontSize:"var(--conv-font-size, 14px)"}})}),(0,B.jsx)("div",{className:"pointer-events-none absolute bottom-0 right-2 flex items-center text-base md:text-sm",style:{fontSize:"var(--conv-font-size, 14px)",height:"calc(1lh + 1.5rem)"},children:(0,B.jsx)(AM,{className:"pointer-events-auto",disabled:!R.trim()&&!(e5&&ey)&&!ej||W||U||t4.pending,status:U||W||t4.pending?"submitted":ej?"streaming":"ready"})})]})]})]})]})}),(0,B.jsx)(co,{open:null!==eQ,onOpenChange:e=>{e||eQ?.resolve(!1)},children:(0,B.jsxs)(cd,{children:[(0,B.jsxs)(cu,{children:[(0,B.jsx)(cf,{children:"Agent process limit reached"}),(0,B.jsxs)(cp,{children:["All ",eQ?.maxResidentAgentProcesses," resident agent processes for this workspace branch are running. Starting a new conversation will stop the least recently active running session in this branch."]})]}),(0,B.jsxs)(ch,{children:[(0,B.jsx)(cg,{children:"Cancel"}),(0,B.jsx)(cm,{onClick:()=>eQ?.resolve(!0),children:"Stop & start new"})]})]})})]}):(0,B.jsx)("div",{className:"h-full flex items-center justify-center text-muted-foreground",children:(0,B.jsxs)("div",{className:"text-center",children:[(0,B.jsx)("div",{className:"mx-auto w-10 h-10 rounded-xl bg-muted flex items-center justify-center mb-3",children:(0,B.jsx)(a3,{className:"h-5 w-5 text-muted-foreground/50"})}),(0,B.jsx)("p",{className:"text-sm",children:"Select a project to start coding"})]})})});function It({runId:e,entry:r,title:s,onOpenSource:n}){let i,[a,o]=(0,$.useState)(null),[l,c]=(0,$.useState)(0);(0,$.useEffect)(()=>{if(r)return;let s=!1;return rD.api.getWorkflowRun(e).then(r=>{s||o({runId:e,attempt:l,run:r})}).catch(r=>{s||o({runId:e,attempt:l,error:r instanceof Error?r.message:String(r)})}),()=>{s=!0}},[r,e,l]);let d=a?.runId===e&&a.attempt===l?a:null,u=!d||"error"in d?null:d,h=r?.run??u?.run??null;return i=r?(0,B.jsx)(MG,{phase:"preparing"===r.run.status?"distilling":"starting"}):d&&"error"in d?(0,B.jsx)(MJ,{error:d.error,title:"Could not read the review status",children:(0,B.jsx)(Z.Button,{variant:"outline",size:"sm",className:"mt-4",onClick:()=>c(e=>e+1),children:"Retry"})}):u?u.run?"failed"===u.run.status?(0,B.jsx)(MJ,{error:u.run.error}):"cancelled"===u.run.status||"completed"===u.run.status?(0,B.jsx)(MZ,{status:u.run.status}):(0,B.jsx)(MG,{phase:"starting"}):(0,B.jsx)(MZ,{status:"gone"}):(0,B.jsxs)("div",{className:"text-center py-16",children:[(0,B.jsx)(AL,{className:"h-6 w-6 mx-auto mb-4"}),(0,B.jsx)("h3",{className:"text-sm font-semibold mb-1 text-foreground",children:"Checking review status…"})]}),(0,B.jsxs)("div",{className:"flex flex-col h-full","data-testid":"preparing-review-view",children:[(0,B.jsxs)("div",{className:"flex items-center justify-between gap-2 px-3 py-2 border-b shrink-0",children:[(0,B.jsx)("span",{className:"text-sm font-medium truncate",title:s,children:s}),h&&(0,B.jsxs)(Z.Button,{variant:"ghost",size:"sm",className:"h-7 text-xs shrink-0",onClick:()=>n(h.source_session_id,h.branch),children:[(0,B.jsx)(lA.ArrowLeft,{className:"h-3 w-3 mr-1"}),"Source conversation"]})]}),(0,B.jsx)("div",{className:"flex-1 min-h-0 overflow-auto px-4",children:i})]})}function Ir(e){return e.title?.trim()||"New Session"}async function Is(e){let r=await (0,rD.listAliveSessions)(e);return r.complete?r.sessions.map(r=>({id:r.id,projectId:e,branch:r.branch,title:Ir(r),status:r.status,processAlive:!0})):"incomplete"}async function In(e,r){return 0===r.length?null:(await Promise.all(r.map(async r=>(await (0,rD.listBranchSessions)(e,r)).sessions.filter(e=>e.processAlive).map(s=>({id:s.id,projectId:e,branch:r,title:Ir(s),status:s.status,processAlive:!0,updated_at:s.updated_at}))))).flat()}function Ii(e,r,s){return"live"===r&&s&&"live"!==e}let Ia=new Map,Io="preparing-review",Il={preparing:0,waiting_reviewer:1,waiting_feedback:2,discussing:3,sending_feedback:4,waiting_rereview:1,running_task:1,waiting_resume:1,completed:9,cancelled:9,failed:9};function Ic(e){return 9===Il[e]}function Id(e){let r=Date.parse(e.updated_at);return(Il[e.status]??0)*1e13+(Number.isFinite(r)?r:0)}function Iu(e){return{projectId:e,entries:new Map,tombstones:new Map}}function Ih(e,r,s){let n=new Map(e.entries),i=new Map(e.tombstones);for(let e of r)n.delete(e),i.set(e,s+6e4);return{...e,entries:n,tombstones:i}}function If(e,r,s,n){if(!e.projectId||r.project_id!==e.projectId)return e;let i=e.tombstones.get(r.id);if(void 0!==i&&i>s)return e;let a=e.entries.get(r.id);if(Ic(r.status))return a?Ih(e,[r.id],s):e;if(!a){if("preparing"!==r.status||!r.reviewer_session_id)return e;let i=new Map(e.entries);return i.set(r.id,{kind:Io,runId:r.id,projectId:r.project_id,branch:r.branch??null,reviewerSessionId:r.reviewer_session_id,sourceSessionId:r.source_session_id,run:r,version:Id(r),titleHint:n??null,insertedAt:s,appearedAt:null}),{...e,entries:i}}let o=Id(r);if(o<a.version)return e;let l=new Map(e.entries);return l.set(r.id,{...a,branch:r.branch??null,reviewerSessionId:r.reviewer_session_id??a.reviewerSessionId,run:r,version:o,titleHint:n??a.titleHint}),{...e,entries:l}}function Ip(e,r,s){let n=null;for(let i of e.entries.values())null===i.appearedAt&&r.has(i.reviewerSessionId)&&(n??=new Map(e.entries)).set(i.runId,{...i,appearedAt:s});return n?{...e,entries:n}:e}function Im(e,r){let s=(e.titleHint??r??"").trim();return s&&"New Session"!==s?`Review - ${s}`:"Review"}let Ig=Object.freeze({session:null,messages:[],status:"stopped",isConnected:!1,isInitialized:!1,isLoading:!1,error:null,workflowRunUpdate:null,turnState:{status:"idle",waitingFor:[]},streamEpoch:0,draft:""});function Ix(){return"localhost"===window.location.hostname&&"3000"===window.location.port?"http://localhost:5173":""}async function Iv(e,r){let s=await (0,rD.authFetch)(`${Ix()}/api/projects/${e}/chat-sessions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branch:r})});if(!s.ok)throw Error("Failed to create chat session");return s.json()}async function Iy(e,r){if(!(await (0,rD.authFetch)(`${Ix()}/api/chat-sessions/${e}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:r})})).ok)throw Error("Failed to send message")}async function Ib(e){if(!(await (0,rD.authFetch)(`${Ix()}/api/chat-sessions/${e}/stop`,{method:"POST"})).ok)throw Error("Failed to stop generation")}function Iw(e,r){return`chat:${e}:${r??""}`}let I_=new Map,IS=new Map;function Ij(e,r){for(IS.delete(e),IS.set(e,r);IS.size>20;){let e=IS.keys().next().value;if(void 0===e)break;IS.delete(e)}}let Ik=new Map;function IC(e){let r=Math.min(3e4,1e3*Math.pow(2,e));return r+r*Math.random()*.25}class IN{projectId;branch;key;state;listeners;active;epoch;ws;container;replaying;finished;reconnectTimer;stabilityTimer;silenceTimer;reconnectAttempt;shortLivedConnections;connectionStartedAt;lastStartFailed;tokenRetryAttempt;authRejects;authRejectedSocket;metadataWrites;constructor(e,r){this.projectId=e,this.branch=r,this.listeners=new Set,this.active=!1,this.epoch=0,this.ws=null,this.container={entries:[],status:"stopped"},this.replaying=!1,this.finished=!1,this.reconnectTimer=null,this.stabilityTimer=null,this.silenceTimer=null,this.reconnectAttempt=0,this.shortLivedConnections=0,this.connectionStartedAt=null,this.lastStartFailed=!1,this.tokenRetryAttempt=0,this.authRejects=0,this.authRejectedSocket=null,this.metadataWrites=0,this.subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)}),this.getSnapshot=()=>this.state,this.onVisibilityChange=()=>{if("visible"!==document.visibilityState||!this.state.session?.id||this.finished)return;let e=this.ws;e&&e.readyState===WebSocket.OPEN&&e.close(4e3,"visibility-recovery")},this.onOnline=()=>{if(!this.state.session?.id||this.finished)return;let e=this.ws;e&&e.readyState!==WebSocket.CLOSED&&e.readyState!==WebSocket.CLOSING||(this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.reconnectAttempt=0,this.tokenRetryAttempt=0,this.connect(!0))},this.setDraft=e=>{e!==this.state.draft&&(Ik.set(this.key,e),this.set({draft:e}))},this.setEventListening=async e=>{let r=this.state.session;r&&(await rD.api.setChatEventListening(r.id,e),this.metadataWrites+=1,this.state.session?.id===r.id&&this.adoptSession({...r,eventListeningEnabled:e}))},this.sendMessage=async e=>{let r=this.state.session?.id,s=e.trim();if(r&&s)try{await Iy(r,s)}catch(r){let e=r instanceof Error?r.message:"Failed to send message";this.set({error:e}),xN.toast.error("Failed to send message",{description:e})}},this.stopGeneration=async()=>{let e=this.state.session?.id;if(e)try{await Ib(e)}catch(e){console.error("[ChatSession] Failed to stop generation:",e)}},this.restartSession=async()=>{let e=this.state.session?.id;if(e)try{await rD.api.resetChatSession(e),this.container={entries:[],status:"stopped"},this.flush()}catch(e){console.error("[ChatSession] Failed to reset session:",e),xN.toast.error("Failed to start new conversation")}},this.key=Iw(e,r);const s=IS.get(this.key),n=Ik.get(this.key)??"",i=s?.session??I_.get(this.key)??null;this.state=s?{...Ig,session:i,messages:s.messages,status:s.status,isInitialized:!0,draft:n}:{...Ig,session:i,draft:n}}subscribe;getSnapshot;set(e){for(let r of(this.state={...this.state,...e},this.listeners))r()}start(){this.active||(this.active=!0,this.finished=!1,"undefined"!=typeof document&&(document.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("online",this.onOnline)),this.startSession())}stop(){if(!this.active)return;this.active=!1,this.epoch+=1,"undefined"!=typeof document&&(document.removeEventListener("visibilitychange",this.onVisibilityChange),window.removeEventListener("online",this.onOnline));let e=this.ws;if(this.ws=null,e)try{e.close(1e3,"branch-switch")}catch{}this.clearTimers(),this.connectionStartedAt=null,this.state.isConnected&&this.set({isConnected:!1})}clearTimers(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.stabilityTimer&&(clearTimeout(this.stabilityTimer),this.stabilityTimer=null),this.clearSilenceTimer()}async startSession(){if(!this.active)return;let e=this.epoch;this.lastStartFailed=!1,this.set({error:null});let r=I_.get(this.key);if(r){this.set({session:r}),this.connect(),this.refreshSessionMetadata(e);return}this.set({isLoading:!0});try{let{session:r,messages:s}=await Iv(this.projectId,this.branch);if(e!==this.epoch)return;I_.set(this.key,r),this.set({session:r,status:r.status,messages:s??[],isInitialized:!0}),this.connect()}catch(r){if(e!==this.epoch)return;this.lastStartFailed=!0,this.set({error:r instanceof Error?r.message:"Failed to start session"})}finally{e===this.epoch&&this.set({isLoading:!1})}}async refreshSessionMetadata(e){let r=this.metadataWrites;try{let{session:s,messages:n}=await Iv(this.projectId,this.branch);if(e!==this.epoch||r!==this.metadataWrites||s.id!==this.state.session?.id)return;this.adoptSession(s),this.state.isInitialized||this.set({messages:n??[],isInitialized:!0})}catch{}}adoptSession(e){I_.set(this.key,e);let r=IS.get(this.key);r&&r.session.id===e.id&&Ij(this.key,{...r,session:e}),this.set({session:e})}connect(e=!1){if(!this.active||this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING))return;let r=this.epoch;Promise.race([(0,rD.getFreshToken)(e?{skipCache:!0}:void 0),new Promise(e=>setTimeout(e,5e3))]).catch(()=>void 0).then(()=>{if(r===this.epoch&&this.active){if(!(0,rD.hasUsableStreamToken)()){let e=IC(Math.min(this.tokenRetryAttempt,4));this.tokenRetryAttempt++,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.state.session?.id&&!this.finished&&this.connect(!0)},e);return}this.tokenRetryAttempt=0,this.openSocket()}})}openSocket(){if(this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING))return;let e=this.state.session?.id;if(!e)return;this.container={entries:[],status:"stopped"},this.finished=!1,this.replaying=!0;let r=new WebSocket((0,rD.getWebSocketUrl)(`/api/chat-sessions/${e}/stream`));this.ws=r;let s=()=>this.ws===r;r.onopen=()=>{s()&&(this.set({isConnected:!0,error:null}),this.connectionStartedAt=Date.now(),this.armSilenceTimer(r),this.stabilityTimer&&clearTimeout(this.stabilityTimer),this.stabilityTimer=setTimeout(()=>{this.reconnectAttempt=0,this.shortLivedConnections=0},5e3))},r.onmessage=e=>{if(s()){this.armSilenceTimer(r);try{this.handleFrame(r,JSON.parse(e.data))}catch(e){console.error("[ChatSession] Failed to parse message:",e)}}},r.onclose=e=>{if(!s())return;this.ws=null,this.set({isConnected:!1}),this.clearSilenceTimer(),this.stabilityTimer&&(clearTimeout(this.stabilityTimer),this.stabilityTimer=null);let n=4e3===e.code,i=this.connectionStartedAt?Date.now()-this.connectionStartedAt:0;if(this.connectionStartedAt=null,this.authRejectedSocket===r){if(this.authRejectedSocket=null,this.finished)return;let e=IC(Math.min(this.authRejects-1,4));this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.state.session?.id&&!this.finished&&this.connect(!0)},e);return}if(!n&&i>0&&i<5e3){if(this.shortLivedConnections++,this.shortLivedConnections>=3)return this.lastStartFailed?void this.set({error:"Unable to connect to remote server. Please check the server configuration."}):(I_.delete(this.key),this.reconnectAttempt=0,this.shortLivedConnections=0,this.set({session:null,error:null}),void this.startSession())}else i>=5e3&&(this.shortLivedConnections=0);if(this.finished||1e3===e.code)return;if(this.reconnectAttempt>=10)return void this.set({error:"Unable to connect to server."});let a=IC(this.reconnectAttempt);this.reconnectAttempt++,this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.state.session?.id&&!this.finished&&this.connect(!0)},a)},r.onerror=()=>{}}handleFrame(e,r){if("error"in r||(this.authRejects=0),!("keepalive"in r)){if("JsonPatch"in r){var s,n;this.container=(s=this.container,n=r.JsonPatch,EC(s,e=>{for(let r of n){let{op:s,path:n,value:i}=r;if("/entries"===n&&"replace"===s&&i?.type==="ENTRY"&&i.content?.type==="system"&&i.content?.content==="__CLEAR_ALL__"){e.entries=[];continue}if(n.startsWith("/entries/")){let r=parseInt(n.replace("/entries/",""),10);if(isNaN(r)||i?.type!=="ENTRY")continue;switch(s){case"add":for(;e.entries.length<=r;)e.entries.push(null);e.entries[r]=i.content;break;case"replace":r<e.entries.length&&(e.entries[r]=i.content);break;case"remove":r<e.entries.length&&e.entries.splice(r,1)}}else"/status"===n&&i?.type==="STATUS"&&(e.status=i.content)}})),this.replaying||this.flush();return}if("Ready"in r){this.replaying=!1,this.flush(),this.set({isInitialized:!0,streamEpoch:this.state.streamEpoch+1});return}if("finished"in r){this.finished=!0,e.close(1e3,"finished");return}if("openPreviewFrame"in r)return void(0,Cu.openPreviewFrame)(r.openPreviewFrame.projectId,r.openPreviewFrame.url);if("WorkflowRunUpdated"in r)return void this.set({workflowRunUpdate:r.WorkflowRunUpdated});if("TurnState"in r)return void this.set({turnState:r.TurnState});if("browserCommand"in r){let s=r.browserCommand;(0,Cu.sendCommandToIframe)(this.projectId,{type:"vibedeckx-command",...s}).then(r=>{r&&e.readyState===WebSocket.OPEN&&e.send(JSON.stringify({type:"browser_result",result:{id:s.id,success:r.success??!1,error:r.error,content:r.content,found:r.found,tag:r.tag,text:r.text}}))});return}if("error"in r){if((0,rD.isStreamAuthError)(r.error)){this.authRejectedSocket=e,this.authRejects++,this.authRejects>=rD.STREAM_AUTH_REJECTS_BEFORE_ERROR&&this.set({error:rD.STREAM_AUTH_FAILED_MESSAGE});return}this.set({error:r.error}),"Session not found"===r.error&&(I_.delete(this.key),IS.delete(this.key),this.finished=!0)}}}flush(){let e=this.container.entries.filter(Boolean),r=this.container.status;this.set({messages:e,status:r}),this.state.session&&Ij(this.key,{session:this.state.session,messages:e,status:r})}clearSilenceTimer(){this.silenceTimer&&(clearTimeout(this.silenceTimer),this.silenceTimer=null)}armSilenceTimer(e){this.silenceTimer&&clearTimeout(this.silenceTimer),this.silenceTimer=setTimeout(()=>{this.silenceTimer=null,e.readyState===WebSocket.OPEN&&(console.warn(`[ChatSession] No frames for 95000ms — assuming dead socket, forcing reconnect`),this.replaceSilentSocket(e))},95e3)}replaceSilentSocket(e){if(this.ws===e){this.ws=null,this.set({isConnected:!1}),this.stabilityTimer&&(clearTimeout(this.stabilityTimer),this.stabilityTimer=null),this.connectionStartedAt=null;try{e.close(4e3,"silence watchdog")}catch{}this.finished||this.connect(!0)}}onVisibilityChange;onOnline;setDraft;setEventListening;sendMessage;stopGeneration;restartSession}let IE=()=>()=>{},ID=()=>Ig,IR=async()=>{},IT=()=>{};function IA(e){return e&&"object"==typeof e&&"string"==typeof e.goal&&Array.isArray(e.completionCriteria)&&e.completionCriteria.every(e=>"string"==typeof e)&&Array.isArray(e.steps)&&e.steps.every(e=>e&&"string"==typeof e.id&&"string"==typeof e.title&&["pending","in_progress","completed","failed","skipped"].includes(e.status)&&(void 0===e.result||"string"==typeof e.result))&&(void 0===e.planId||"string"==typeof e.planId)&&(void 0===e.waitingOn||"string"==typeof e.waitingOn)?e:null}function IM(e){try{let r=JSON.parse(e);return r.success?IA(r.plan):null}catch{return null}}let II={pending:aw,in_progress:a7,completed:oC,failed:oE,skipped:(0,eA.default)("circle-minus",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}]])},IF={pending:"Pending",in_progress:"In progress",completed:"Completed",failed:"Failed",skipped:"Skipped"};function IP({plan:e,draft:r=!1}){let s=e.steps.filter(e=>"completed"===e.status||"skipped"===e.status).length;return(0,B.jsxs)("div",{className:"rounded-lg border bg-muted/20 p-3 space-y-3 text-sm",children:[(0,B.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,B.jsx)("span",{className:"font-medium break-words",children:e.goal}),(0,B.jsx)("span",{className:"shrink-0 text-xs text-muted-foreground",children:r?"Plan draft":`${s}/${e.steps.length}`})]}),e.waitingOn&&!r&&(0,B.jsxs)("div",{className:"rounded-md border border-amber-500/30 bg-amber-500/10 px-2 py-1.5 text-xs text-amber-700 dark:text-amber-300 break-words",children:["Waiting for you: ",e.waitingOn]}),(0,B.jsxs)("div",{className:"text-xs text-muted-foreground space-y-1",children:[(0,B.jsx)("div",{className:"font-medium",children:"Completion criteria"}),e.completionCriteria.map((e,r)=>(0,B.jsxs)("div",{className:"break-words",children:["• ",e]},r))]}),(0,B.jsx)("ol",{className:"space-y-2",children:e.steps.map(e=>{let r=II[e.status];return(0,B.jsxs)("li",{className:"flex gap-2",children:[(0,B.jsx)(r,{"aria-label":IF[e.status],className:`mt-0.5 h-4 w-4 shrink-0 ${"in_progress"===e.status?"animate-spin text-primary":"completed"===e.status?"text-emerald-600":"failed"===e.status?"text-destructive":"text-muted-foreground"}`}),(0,B.jsxs)("div",{className:"min-w-0",children:[(0,B.jsx)("div",{className:"break-words",children:e.title}),e.result&&(0,B.jsx)("div",{className:"text-xs text-muted-foreground whitespace-pre-wrap break-words",children:e.result})]})]},e.id)})}),r&&(0,B.jsx)("p",{className:"text-xs text-muted-foreground",children:"To change this plan, decline it and describe the changes in chat."})]})}function IL({sessionId:e,approvalId:r,tool:s,input:n,resolved:i,embedded:a=!1}){let[o,l]=(0,$.useState)(null),c="setPlan"===s?IA(n):null,[d,u]=(0,$.useState)(null),h=function(e){if(null!==e&&"object"==typeof e){if("string"==typeof e.message)return e.message;if("string"==typeof e.prompt)return e.prompt}return JSON.stringify(e)}(n),f=async s=>{if(!o&&!i){l(s?"approve":"deny"),u(null);try{await rD.api.chatToolApproval(e,r,s)}catch{u("Could not submit your decision. Please try again.")}finally{l(null)}}};return(0,B.jsx)("div",{className:a?"@container/approval min-w-0":"@container/approval min-w-0 mx-4 my-1",children:(0,B.jsxs)("div",{className:a?"space-y-2":"rounded-lg border border-amber-500/30 bg-amber-500/5 p-3 space-y-2",children:[(0,B.jsxs)("div",{className:"flex items-center gap-2",children:[(0,B.jsx)(a3,{className:"h-3.5 w-3.5 text-amber-500 shrink-0"}),(0,B.jsxs)("span",{className:"text-xs font-medium text-amber-600 dark:text-amber-400",children:["Approval needed · ","setPlan"===s?"Review task plan":"spawnAgentSession"===s?"Start a new coding agent":"Send to the coding agent"]})]}),c?(0,B.jsx)(IP,{plan:c,draft:!0}):(0,B.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all text-foreground/80",style:{fontSize:"var(--conv-font-size, 12px)"},children:h}),d&&(0,B.jsx)("p",{role:"alert",className:"text-xs text-destructive",children:d}),i?(0,B.jsxs)(sg,{variant:"default",className:"approved"===i?"bg-green-600 hover:bg-green-700 text-white":"bg-red-600 hover:bg-red-700 text-white",children:["approved"===i?(0,B.jsx)(oC,{className:"h-3 w-3 mr-1"}):(0,B.jsx)(oE,{className:"h-3 w-3 mr-1"}),c?"approved"===i?"Plan confirmed":"Plan declined — describe changes in chat":"approved"===i?"Approved — sent.":"Denied — not sent."]}):(0,B.jsxs)("div",{className:c?"grid grid-cols-1 gap-2 @min-[24rem]/approval:grid-cols-2":"flex flex-wrap gap-2",children:[(0,B.jsxs)(Z.Button,{onClick:()=>f(!0),disabled:null!==o,className:"h-auto min-h-8 min-w-0 whitespace-normal py-1.5 bg-green-600 hover:bg-green-700 text-white",size:"sm",children:["approve"===o?(0,B.jsx)(a7,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):(0,B.jsx)(oC,{className:"h-3.5 w-3.5 mr-1"}),c?"Confirm and execute":"Approve"]}),(0,B.jsxs)(Z.Button,{onClick:()=>f(!1),disabled:null!==o,variant:"destructive",className:"h-auto min-h-8 min-w-0 whitespace-normal py-1.5",size:"sm",children:["deny"===o?(0,B.jsx)(a7,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):(0,B.jsx)(oE,{className:"h-3.5 w-3.5 mr-1"}),c?"Decline and revise":"Deny"]})]})]})})}let Iz="[Plan Stalled]",IO="[Commander Stalled]",IB="[Plan Continuation]",I$=e=>e.steps.length>0&&e.steps.every(e=>"completed"===e.status||"skipped"===e.status);function IW({task:e,sessionId:r}){let{plan:s,approval:n}=e,i=(0,$.useId)(),a=s.steps.filter(e=>"completed"===e.status||"skipped"===e.status).length,o=!n&&s.steps.length>0&&a===s.steps.length,[l,c]=(0,$.useState)(null),d=l?.completed===o?l.expanded:!o,u=s.steps.find(e=>"in_progress"===e.status),h=s.steps.find(e=>"failed"===e.status),f=s.steps.find(e=>"pending"===e.status),p=n&&!n.resolved,m=!!e.stalled&&!o,g=p?"Needs confirmation":n?.resolved==="denied"?"Plan declined":n?.resolved==="approved"?"Confirmed":o?"Completed":m?"Stalled · send a message to continue":s.waitingOn?`Waiting for you: ${s.waitingOn}`:u?u.title:h?`Failed \xb7 ${h.title}`:f?`Next: ${f.title}`:"Task plan",x=p||n?.resolved==="denied"||h||m||s.waitingOn?oI:n?aw:o?oC:u?a7:aw;return(0,B.jsxs)("section",{"aria-label":"Current task plan",className:"mb-2 overflow-hidden rounded-lg border bg-muted/20",children:[(0,B.jsxs)("button",{type:"button",className:"flex w-full items-center gap-2 px-3 py-2 text-left hover:bg-muted/50","aria-label":d?"Collapse task plan":"Expand task plan","aria-expanded":d,"aria-controls":i,onClick:()=>c({completed:o,expanded:!d}),children:[d?(0,B.jsx)(aI,{className:"h-3.5 w-3.5 shrink-0"}):(0,B.jsx)(ab,{className:"h-3.5 w-3.5 shrink-0"}),(0,B.jsx)(x,{className:`h-3 w-3 shrink-0 ${x===a7?"animate-spin":""} ${p||m||s.waitingOn?"text-amber-500":o?"text-emerald-600":h?"text-destructive":""}`}),(0,B.jsx)("span",{className:"min-w-0 flex-1 truncate text-xs font-medium",title:s.goal,children:s.goal}),(0,B.jsx)("span",{className:"max-w-[45%] truncate text-xs text-muted-foreground","aria-live":"polite",title:g,children:g}),(0,B.jsxs)("span",{className:"shrink-0 text-xs text-muted-foreground",children:[a,"/",s.steps.length]})]}),d&&(0,B.jsx)("div",{id:i,className:"max-h-[min(16rem,35dvh)] overflow-y-auto overscroll-contain border-t p-2",children:n?(0,B.jsx)(IL,{sessionId:r,approvalId:n.approvalId,tool:"setPlan",input:n.input,resolved:n.resolved,embedded:!0},n.approvalId):(0,B.jsx)(IP,{plan:s})})]})}let IH={kind:"plan",label:"Plan file",description:"Work through a step-by-step plan in the repo, one step per session: implement, verify, commit.",fields:[{key:"planFile",label:"Plan file",placeholder:"docs/implementation-plan.md"},{key:"pendingMarker",label:"Pending marker",placeholder:"**Pass condition.** False"},{key:"doneMarker",label:"Done marker",placeholder:"**Pass condition.** True"},{key:"readDocs",label:"Docs to read every session",multiline:!0,placeholder:"AGENTS.md\ndocs/design.md\nOn conflicts, docs/design.md wins.",hint:"One per line; say which wins on a conflict."},{key:"constraints",label:"Constraints that must never be violated",multiline:!0,placeholder:"No new runtime dependencies\nAll DB access goes through the repository layer"},{key:"verifyCommands",label:"Verification commands (run by the agent)",multiline:!0,placeholder:"npm run typecheck\nnpm test",hint:"The agent runs these. The Check command below is a separate check the loop runs itself."},{key:"decisionsFile",label:"Decisions doc",placeholder:"docs/decisions.md"},{key:"readyResources",label:"Already available — not a blocker",multiline:!0,placeholder:"gh is logged in\nThe dev database is configured"}],defaults:{planFile:"docs/implementation-plan.md",pendingMarker:"**Pass condition.** False",doneMarker:"**Pass condition.** True",readDocs:"",constraints:"",verifyCommands:"",decisionsFile:"docs/decisions.md",readyResources:""},handoffByDefault:!0},IU={kind:"custom",label:"Custom",description:"Write the whole instruction yourself.",fields:[],defaults:{},handoffByDefault:!1},Iq=[IH,IU];function IK(e){return"plan"===e?IH:IU}let IV="\nThis instruction runs repeatedly, each time in a fresh session with no memory of the previous ones. Process exactly ONE item, then stop — the next session picks up the next item.\nEnd your final message with these lines:\nStatus: <exactly one of: continue / done / blocked>\n continue — you completed one item and more remain (or may remain)\n done — you checked, and there is nothing left to process\n blocked — you could not complete an item and need a human\nItem: <one short line identifying the item you processed; omit when done>\nRemaining: <how many items are left, if you know; otherwise omit>";function IX(e){return(e??"").split(/\r?\n/).map(e=>e.trim()).filter(Boolean)}function IY(e,r){return e[r]?.trim()||IH.defaults[r]||""}let IG=(e,r="")=>e.map(e=>`${r}- ${e}`).join("\n");function IJ(e,r){let s,n,i,a,o,l,c,d,u,h,f,p,m;return"plan"===e?(s=IY(r,"planFile"),n=IY(r,"pendingMarker"),i=IY(r,"doneMarker"),a=r.decisionsFile?.trim()??"",o=IX(r.readDocs),l=IX(r.constraints),c=IX(r.verifyCommands),d=IX(r.readyResources),(u=[]).push(`You are implementing this project by following the plan in \`${s}\`. Each session completes exactly ONE step: implement it, verify it, commit it, then stop.`),h=[`- \`${s}\` — the plan. Each step ends with a completion marker: \`${n}\` while pending, \`${i}\` once done.`],o.length&&h.push(`- Also read these every session:
|
|
37
|
-
${
|
|
36
|
+
${s}`:s:[...e,{type:"text",text:s}]}(f,e9),ey){let e;console.log(`[AgentConversation] handleSubmit: existing session ${ey.id}, status=${ew}`);try{e=await eL(f,void 0,to.selectedIds)}catch(e){return await w("Failed to send message",e)}if(!1===e){if(ev(r)&&(T(s),p(),M(A),F(I)),y(),n)throw Error("Failed to send message");return}b()}else{t2(m??t1.current)||await g();let e=m?.prepared??null;m=null;let i=to.selectedIds,a=e?await eW(e,f,i,to.adoptInto):await eB(f,P,ee,i,to.adoptInto);if(a)b(),console.log(`[AgentConversation] handleSubmit: started session ${a.session.id}`),ex(r)&&ei(a.session.id);else if(ev(r)&&(T(s),p(),M(A),F(I)),y(),n)throw Error("Failed to start session")}}finally{V.current===l&&(V.current=null,H(!1),q(!1))}},{settings:t9}=(0,dh.useConversationSettings)();return e?(0,B.jsxs)("div",{className:"h-full flex flex-col min-h-0",style:{"--conv-font-size":`${t9.agentFontSize}px`},children:[(0,B.jsxs)("div",{className:"flex-shrink-0 flex items-center justify-between px-4 h-10 border-b border-border/60 bg-muted/20",children:[(0,B.jsxs)("div",{className:"flex items-center gap-2",children:[J.length>1?(0,B.jsxs)(a_,{children:[(0,B.jsx)(aS,{asChild:!0,children:(0,B.jsxs)("button",{disabled:ej||"running"===ew&&eb.length>0,className:(0,eR.cn)("inline-flex items-center gap-1 rounded-md border bg-muted/50 px-2 py-0.5 text-xs font-medium transition-colors hover:bg-muted",(ej||"running"===ew&&eb.length>0)&&"opacity-50 cursor-not-allowed"),children:[(0,B.jsx)(ME,{type:X}),(0,B.jsx)(Mr,{candidates:J.map(e=>e.displayName),children:tw}),(0,B.jsx)(aI,{className:"h-3 w-3 text-muted-foreground"})]})}),(0,B.jsx)(aj,{align:"start",className:"min-w-[var(--radix-dropdown-menu-trigger-width)]",children:(0,B.jsx)(aN,{value:X,onValueChange:async e=>{if(!ey){e!==X&&et(null),Y(e);return}let r=await eV(e);r?xN.toast.error("Failed to switch agent",{description:r}):Y(e)},children:J.map(e=>(0,B.jsxs)(aE,{value:e.type,disabled:!e.available,className:"text-xs pl-2 [&>span:first-child]:hidden data-[state=checked]:bg-accent data-[state=checked]:text-accent-foreground",children:[(0,B.jsx)(ME,{type:e.type}),e.displayName]},e.type))})})]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(ME,{type:X,className:"h-4 w-4"}),(0,B.jsx)("span",{className:"text-sm font-medium",children:tw})]}),(0,B.jsx)(Mo,{models:J.find(e=>e.type===X)?.models??[],widthCandidates:J.flatMap(e=>e.models??[]),value:ey?ey.model??null:ee,onChange:ey?tg:et,locked:null!=ey&&"running"===ew&&eb.length>0}),(0,B.jsx)(MN,{mode:P,onModeChange:tm}),ef.length>=1&&o&&(0,B.jsx)(kV,{targets:ef,activeTarget:a?.agent_mode??"local",onTargetChange:o}),ey&&(C=ey.id.startsWith("remote-"),N="text-muted-foreground",E=(0,B.jsx)(dH,{className:"h-3 w-3"}),D="Disconnected",ek?(N="text-muted-foreground",E=(0,B.jsx)(a7,{className:"h-3 w-3 animate-spin"}),D="Checking for newer output..."):e_?C&&"connected"!==eN&&null!==eN?"reconnecting"===eN?(N="text-amber-500",E=(0,B.jsx)(AV,{className:"h-3 w-3 animate-pulse"}),D="Reconnecting..."):"disconnected"===eN&&(N="text-red-500",E=(0,B.jsx)(dH,{className:"h-3 w-3"}),D="Remote disconnected"):(N="text-green-500",E=(0,B.jsx)(AV,{className:"h-3 w-3"}),D="Connected"):tf||(N="text-amber-500",E=(0,B.jsx)(AV,{className:"h-3 w-3 animate-pulse"}),D="Connecting..."),(0,B.jsx)(Mt,{label:D,children:(0,B.jsx)("span",{className:`flex items-center ${N}`,role:"img","aria-label":D,children:E})}))]}),(0,B.jsxs)("div",{className:"flex items-center gap-1",children:[e&&(0,B.jsx)(MY,{projectId:e,branch:r,sessionId:ey?.id??null,currentAgentType:X,providers:J,shortcutEnabled:tX,onStarted:e=>b?.(e,tW)}),e&&(0,B.jsx)(MF,{projectId:e,branch:r,currentSessionId:ey?.id??null,refreshKey:er,pendingTitleSessionId:en,aiTitleOverride:ea,onSwitch:e=>{u?.(e),i?.(e)},onDelete:(e,r)=>{if(e===ey?.id){let e=r[0];i?.(e?e.id:null)}}}),(0,B.jsx)(Mt,{label:"New Conversation (⌘⇧O / Ctrl+Shift+O)",children:(0,B.jsx)("span",{className:"inline-flex",children:(0,B.jsx)(Z.Button,{variant:"ghost",size:"icon",onClick:tJ,disabled:ej||!ey,className:"h-7 w-7","aria-label":"New Conversation",children:(0,B.jsx)(AX,{className:"h-3.5 w-3.5"})})})}),(0,B.jsxs)(Z.Button,{variant:"ghost",size:"sm",onClick:()=>eK(),disabled:"running"!==ew,className:"h-7 text-xs",children:[(0,B.jsx)(cb,{className:"h-3 w-3 mr-1"}),"Stop"]})]})]}),t$&&(0,B.jsxs)("div",{className:"flex items-center gap-2 px-4 py-1.5 border-b bg-muted/40 text-xs text-muted-foreground shrink-0","data-testid":"source-preparing-review",children:[(0,B.jsx)(a7,{className:"h-3 w-3 animate-spin shrink-0"}),(0,B.jsx)("span",{className:"flex-1 truncate",children:"Preparing review — summarizing this conversation and starting the reviewer"}),w&&(0,B.jsx)("button",{type:"button",className:"shrink-0 font-medium text-foreground/80 hover:text-foreground underline-offset-2 hover:underline",onClick:()=>w(t$.runId),children:"View"})]}),(0,B.jsxs)("div",{className:"flex-1 min-h-0 relative",children:[(0,B.jsxs)(dc,{className:"h-full",initial:"instant",resize:tI?"smooth":"instant",children:[(0,B.jsx)(dd,{className:"gap-1 p-4 mx-auto w-full max-w-[1200px]",scrollClassName:"edge-scrollbar will-change-transform",children:tO?(0,B.jsx)(MG,{children:tH}):tB?(0,B.jsx)(MJ,{error:tP?.error,children:tH}):ey||0!==eb.length?(0,B.jsx)(M4.Provider,{value:{sendMessage:eL,messages:eb,acceptPlan:tx,permissionMode:ey?.permissionMode??P,agentType:ey?.agentType??X,sessionId:ey?.id??null,projectId:e,branch:r,target:ep,targetLabel:em,openSchedule:x,openTask:v},children:(0,B.jsxs)("div",{className:"space-y-1 outline-none",ref:el,tabIndex:-1,onKeyDown:ec,children:[ey?.lifecycleState==="activation_uncertain"&&(0,B.jsxs)("div",{className:"flex items-start gap-2 p-3 mb-2 rounded-lg border border-amber-500/40 bg-amber-500/10 text-sm text-amber-700 dark:text-amber-400",children:[(0,B.jsx)(a5,{className:"h-4 w-4 mt-0.5 shrink-0"}),(0,B.jsx)("span",{children:"First message delivery could not be confirmed for this session. Check whether the agent actually responded before resending — a resend may duplicate the task."})]}),eI&&(0,B.jsx)("div",{className:"flex justify-center pb-3",children:(0,B.jsxs)(Z.Button,{type:"button",variant:"ghost",size:"sm",disabled:eF,onClick:()=>void eP(),children:[eF?(0,B.jsx)(a7,{className:"h-3.5 w-3.5 animate-spin"}):(0,B.jsx)(aI,{className:"h-3.5 w-3.5 rotate-180"}),"Load earlier turns"]})}),eb.map((e,r)=>e?.type==="turn_end"?(0,B.jsx)(A2,{durationMs:e.durationMs,outcome:e.outcome,emphasis:r===tM?"normal":"subtle",agentType:X,currentAgentName:tw,alternateProviders:t_,onBranch:e=>tb(e,tt[r]??r),disabled:tv,showFinalize:r===tM&&tF?.status==="discussing",finalizeBusy:tU,onFinalize:tK,sendBack:tS&&(tt[r]??r)>tj?{available:!tD&&ey?.branchedFromAvailable!==!1,sent:tk.has(tt[r]??r),busy:tN===(tt[r]??r),onSend:()=>void tA(tt[r]??r,r)}:void 0},tt[r]??r):(0,B.jsx)("div",{"data-message-idx":r,..."user"===e.type?{"data-user-msg-idx":r}:{},className:"scroll-mt-2",children:(0,B.jsx)(Ae,{message:e,messageIndex:r,entryIndex:tt[r]??r,streaming:"assistant"===e.type&&tI&&r===eb.length-1})},tt[r]??r)),ej&&!ek&&(0,B.jsxs)("div",{className:"flex items-center gap-2 py-4 text-muted-foreground",children:[(0,B.jsx)(AL,{className:"h-4 w-4"}),(0,B.jsx)("span",{className:"text-sm",children:"Connecting to agent..."})]})]})}):(0,B.jsx)("div",{className:"text-center py-16",children:ej||e&&!eS?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(AL,{className:"h-6 w-6 mx-auto mb-4"}),(0,B.jsx)("h3",{className:"text-sm font-semibold mb-1 text-foreground",children:"Connecting to agent..."}),(0,B.jsx)("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"Setting up the session for this worktree"})]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)("div",{className:"mx-auto w-12 h-12 rounded-xl bg-primary/10 flex items-center justify-center mb-4",children:(0,B.jsx)(a3,{className:"h-6 w-6 text-primary/60"})}),(0,B.jsx)("h3",{className:"text-sm font-semibold mb-1 text-foreground",children:"Start a conversation"}),(0,B.jsx)("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"Ask the agent to help you with coding tasks in this worktree"})]})})}),(0,B.jsx)(du,{}),(0,B.jsx)(Mz,{messageCount:eb.length,turnInFlight:tI,sessionId:ey?.id??null})]}),(0,B.jsx)(MM,{messages:eb,contentRef:el}),(0,B.jsx)(M$,{containerRef:el,onQuote:tG})]}),(0,B.jsx)("div",{className:"flex-shrink-0 py-3 px-[14px]",children:(0,B.jsxs)("div",{className:"mx-auto w-full max-w-[1200px] px-4",children:[(0,B.jsx)(A9,{sessionId:tr,tasks:eD.tasks,turnParked:eD.turnParked,parkDeadlineAt:eD.parkDeadlineAt,canStopTasks:eD.canStopTasks,agentWorking:"running"===ew}),eC&&(0,B.jsxs)("div",{className:"flex items-center gap-2 p-3 mb-2 bg-red-500/10 rounded-lg text-red-500 text-sm",children:[(0,B.jsx)(a5,{className:"h-4 w-4 shrink-0"}),(0,B.jsx)("span",{className:"min-w-0 break-words",children:eC})]}),(0,B.jsxs)(Aj,{onSubmit:t8,maxFileSize:0x1400000,onError:t7,skipAttachmentConversion:!0,className:"w-full",children:[(0,B.jsx)(M3,{uploads:t4,workspaceKey:`${e}::${r}`,apiRef:t6}),(0,B.jsxs)("div",{className:"relative flex w-full flex-col",children:[ta&&(0,B.jsx)(Mm,{granted:to.granted,onRevoke:e=>to.toggle(e,!1)}),(0,B.jsx)(Mb,{tasks:e9,onRemove:e=>te(e,!1)}),z&&(0,B.jsx)("div",{className:"flex items-center pl-12 pr-2 pt-1.5 pb-0.5",children:(0,B.jsxs)("button",{type:"button",onClick:()=>O(!1),className:"inline-flex shrink-0 items-center gap-1.5 rounded-full bg-blue-500/10 text-blue-600 dark:text-blue-400 px-2.5 py-0.5 text-xs font-medium hover:bg-blue-500/20 transition-colors",children:[W?(0,B.jsx)(a7,{className:"size-3 animate-spin"}):(0,B.jsx)(AY,{className:"size-3"}),"Translate",(0,B.jsx)(ro,{className:"size-3"})]})}),e5&&(0,B.jsx)("div",{className:"flex items-center pl-12 pr-2 pt-1.5 pb-0.5",children:(0,B.jsxs)("button",{type:"button",onClick:()=>e2(null),className:"inline-flex shrink-0 items-center gap-1.5 rounded-full bg-blue-500/10 text-blue-600 dark:text-blue-400 px-2.5 py-0.5 text-xs font-medium hover:bg-blue-500/20 transition-colors",children:[e3?(0,B.jsx)(a4,{className:"size-3"}):(0,B.jsx)(D_,{className:"size-3"}),e3?"Schedule":"Add task",(0,B.jsx)(ro,{className:"size-3"})]})}),(0,B.jsxs)("div",{className:"flex w-full items-center",children:[(0,B.jsxs)(AD,{children:[(0,B.jsx)(AR,{className:"ml-1"}),(0,B.jsxs)(AT,{children:[(0,B.jsx)(AS,{label:"Add files"}),ta&&(0,B.jsx)(Mp,{granted:to.granted,onToggle:to.toggle,sourceRemoteId:tl}),(0,B.jsxs)(AA,{role:"menuitemcheckbox","aria-checked":e3,onSelect:()=>e6("schedule"),children:[(0,B.jsx)(a4,{className:"mr-2 size-4"}),"Schedule",e3&&(0,B.jsx)(rj.Check,{className:"ml-auto size-4"})]}),(0,B.jsxs)(AA,{role:"menuitemcheckbox","aria-checked":e4,onSelect:()=>e6("task"),children:[(0,B.jsx)(D_,{className:"mr-2 size-4"}),"Add task",e4&&(0,B.jsx)(rj.Check,{className:"ml-auto size-4"})]}),(0,B.jsx)(My,{projectId:e,selected:e9,onToggle:te}),(0,B.jsxs)(AA,{onSelect:()=>{O(!z)},children:[(0,B.jsx)(AY,{className:"mr-2 size-4"}),z?"Disable translation":"Translate"]})]})]}),(0,B.jsx)("div",{ref:ed,className:"contents",children:(0,B.jsx)(Ak,{value:R,onChange:e=>T(e.target.value),onPasteText:tQ,onKeyDown:eu.handleKeyDown,placeholder:e3?ey?"Send to turn this session's work into a schedule. You can add requirements and when it should run":"What should run, and how often? e.g. every weekday at 9am, run the tests and report failures":e4?ey?"Send to record follow-up work from this session as a task. You can say what to include":"What should be recorded as a task for later?":ey?"Ask the agent to help with your code...":"Type your first message to start...",className:"pr-12",style:{fontSize:"var(--conv-font-size, 14px)"}})}),(0,B.jsx)("div",{className:"pointer-events-none absolute bottom-0 right-2 flex items-center text-base md:text-sm",style:{fontSize:"var(--conv-font-size, 14px)",height:"calc(1lh + 1.5rem)"},children:(0,B.jsx)(AM,{className:"pointer-events-auto",disabled:!R.trim()&&!(e5&&ey)&&!ej||W||U||t4.pending,status:U||W||t4.pending?"submitted":ej?"streaming":"ready"})})]})]})]})]})}),(0,B.jsx)(co,{open:null!==eQ,onOpenChange:e=>{e||eQ?.resolve(!1)},children:(0,B.jsxs)(cd,{children:[(0,B.jsxs)(cu,{children:[(0,B.jsx)(cf,{children:"Agent process limit reached"}),(0,B.jsxs)(cp,{children:["All ",eQ?.maxResidentAgentProcesses," resident agent processes for this workspace branch are running. Starting a new conversation will stop the least recently active running session in this branch."]})]}),(0,B.jsxs)(ch,{children:[(0,B.jsx)(cg,{children:"Cancel"}),(0,B.jsx)(cm,{onClick:()=>eQ?.resolve(!0),children:"Stop & start new"})]})]})})]}):(0,B.jsx)("div",{className:"h-full flex items-center justify-center text-muted-foreground",children:(0,B.jsxs)("div",{className:"text-center",children:[(0,B.jsx)("div",{className:"mx-auto w-10 h-10 rounded-xl bg-muted flex items-center justify-center mb-3",children:(0,B.jsx)(a3,{className:"h-5 w-5 text-muted-foreground/50"})}),(0,B.jsx)("p",{className:"text-sm",children:"Select a project to start coding"})]})})});function It({runId:e,entry:r,title:s,onOpenSource:n}){let i,[a,o]=(0,$.useState)(null),[l,c]=(0,$.useState)(0);(0,$.useEffect)(()=>{if(r)return;let s=!1;return rD.api.getWorkflowRun(e).then(r=>{s||o({runId:e,attempt:l,run:r})}).catch(r=>{s||o({runId:e,attempt:l,error:r instanceof Error?r.message:String(r)})}),()=>{s=!0}},[r,e,l]);let d=a?.runId===e&&a.attempt===l?a:null,u=!d||"error"in d?null:d,h=r?.run??u?.run??null;return i=r?(0,B.jsx)(MG,{phase:"preparing"===r.run.status?"distilling":"starting"}):d&&"error"in d?(0,B.jsx)(MJ,{error:d.error,title:"Could not read the review status",children:(0,B.jsx)(Z.Button,{variant:"outline",size:"sm",className:"mt-4",onClick:()=>c(e=>e+1),children:"Retry"})}):u?u.run?"failed"===u.run.status?(0,B.jsx)(MJ,{error:u.run.error}):"cancelled"===u.run.status||"completed"===u.run.status?(0,B.jsx)(MZ,{status:u.run.status}):(0,B.jsx)(MG,{phase:"starting"}):(0,B.jsx)(MZ,{status:"gone"}):(0,B.jsxs)("div",{className:"text-center py-16",children:[(0,B.jsx)(AL,{className:"h-6 w-6 mx-auto mb-4"}),(0,B.jsx)("h3",{className:"text-sm font-semibold mb-1 text-foreground",children:"Checking review status…"})]}),(0,B.jsxs)("div",{className:"flex flex-col h-full","data-testid":"preparing-review-view",children:[(0,B.jsxs)("div",{className:"flex items-center justify-between gap-2 px-3 py-2 border-b shrink-0",children:[(0,B.jsx)("span",{className:"text-sm font-medium truncate",title:s,children:s}),h&&(0,B.jsxs)(Z.Button,{variant:"ghost",size:"sm",className:"h-7 text-xs shrink-0",onClick:()=>n(h.source_session_id,h.branch),children:[(0,B.jsx)(lA.ArrowLeft,{className:"h-3 w-3 mr-1"}),"Source conversation"]})]}),(0,B.jsx)("div",{className:"flex-1 min-h-0 overflow-auto px-4",children:i})]})}function Ir(e){return e.title?.trim()||"New Session"}async function Is(e){let r=await (0,rD.listAliveSessions)(e);return r.complete?r.sessions.map(r=>({id:r.id,projectId:e,branch:r.branch,title:Ir(r),status:r.status,processAlive:!0})):"incomplete"}async function In(e,r){return 0===r.length?null:(await Promise.all(r.map(async r=>(await (0,rD.listBranchSessions)(e,r)).sessions.filter(e=>e.processAlive).map(s=>({id:s.id,projectId:e,branch:r,title:Ir(s),status:s.status,processAlive:!0,updated_at:s.updated_at}))))).flat()}function Ii(e,r,s){return"live"===r&&s&&"live"!==e}let Ia=new Map,Io="preparing-review",Il={preparing:0,waiting_reviewer:1,waiting_feedback:2,discussing:3,sending_feedback:4,waiting_rereview:1,running_task:1,waiting_resume:1,completed:9,cancelled:9,failed:9};function Ic(e){return 9===Il[e]}function Id(e){let r=Date.parse(e.updated_at);return(Il[e.status]??0)*1e13+(Number.isFinite(r)?r:0)}function Iu(e){return{projectId:e,entries:new Map,tombstones:new Map}}function Ih(e,r,s){let n=new Map(e.entries),i=new Map(e.tombstones);for(let e of r)n.delete(e),i.set(e,s+6e4);return{...e,entries:n,tombstones:i}}function If(e,r,s,n){if(!e.projectId||r.project_id!==e.projectId)return e;let i=e.tombstones.get(r.id);if(void 0!==i&&i>s)return e;let a=e.entries.get(r.id);if(Ic(r.status))return a?Ih(e,[r.id],s):e;if(!a){if("preparing"!==r.status||!r.reviewer_session_id)return e;let i=new Map(e.entries);return i.set(r.id,{kind:Io,runId:r.id,projectId:r.project_id,branch:r.branch??null,reviewerSessionId:r.reviewer_session_id,sourceSessionId:r.source_session_id,run:r,version:Id(r),titleHint:n??null,insertedAt:s,appearedAt:null}),{...e,entries:i}}let o=Id(r);if(o<a.version)return e;let l=new Map(e.entries);return l.set(r.id,{...a,branch:r.branch??null,reviewerSessionId:r.reviewer_session_id??a.reviewerSessionId,run:r,version:o,titleHint:n??a.titleHint}),{...e,entries:l}}function Ip(e,r,s){let n=null;for(let i of e.entries.values())null===i.appearedAt&&r.has(i.reviewerSessionId)&&(n??=new Map(e.entries)).set(i.runId,{...i,appearedAt:s});return n?{...e,entries:n}:e}function Im(e,r){let s=(e.titleHint??r??"").trim();return s&&"New Session"!==s?`Review - ${s}`:"Review"}let Ig=Object.freeze({session:null,messages:[],status:"stopped",isConnected:!1,isInitialized:!1,isLoading:!1,error:null,workflowRunUpdate:null,turnState:{status:"idle",waitingFor:[]},streamEpoch:0,draft:""});function Ix(){return"localhost"===window.location.hostname&&"3000"===window.location.port?"http://localhost:5173":""}async function Iv(e,r){let s=await (0,rD.authFetch)(`${Ix()}/api/projects/${e}/chat-sessions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({branch:r})});if(!s.ok)throw Error("Failed to create chat session");return s.json()}async function Iy(e,r){if(!(await (0,rD.authFetch)(`${Ix()}/api/chat-sessions/${e}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:r})})).ok)throw Error("Failed to send message")}async function Ib(e){if(!(await (0,rD.authFetch)(`${Ix()}/api/chat-sessions/${e}/stop`,{method:"POST"})).ok)throw Error("Failed to stop generation")}function Iw(e,r){return`chat:${e}:${r??""}`}let I_=new Map,IS=new Map;function Ij(e,r){for(IS.delete(e),IS.set(e,r);IS.size>20;){let e=IS.keys().next().value;if(void 0===e)break;IS.delete(e)}}let Ik=new Map;function IC(e){let r=Math.min(3e4,1e3*Math.pow(2,e));return r+r*Math.random()*.25}class IN{projectId;branch;key;state;listeners;active;epoch;ws;container;replaying;finished;reconnectTimer;stabilityTimer;silenceTimer;reconnectAttempt;shortLivedConnections;connectionStartedAt;lastStartFailed;tokenRetryAttempt;authRejects;authRejectedSocket;metadataWrites;constructor(e,r){this.projectId=e,this.branch=r,this.listeners=new Set,this.active=!1,this.epoch=0,this.ws=null,this.container={entries:[],status:"stopped"},this.replaying=!1,this.finished=!1,this.reconnectTimer=null,this.stabilityTimer=null,this.silenceTimer=null,this.reconnectAttempt=0,this.shortLivedConnections=0,this.connectionStartedAt=null,this.lastStartFailed=!1,this.tokenRetryAttempt=0,this.authRejects=0,this.authRejectedSocket=null,this.metadataWrites=0,this.subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)}),this.getSnapshot=()=>this.state,this.onVisibilityChange=()=>{if("visible"!==document.visibilityState||!this.state.session?.id||this.finished)return;let e=this.ws;e&&e.readyState===WebSocket.OPEN&&e.close(4e3,"visibility-recovery")},this.onOnline=()=>{if(!this.state.session?.id||this.finished)return;let e=this.ws;e&&e.readyState!==WebSocket.CLOSED&&e.readyState!==WebSocket.CLOSING||(this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.reconnectAttempt=0,this.tokenRetryAttempt=0,this.connect(!0))},this.setDraft=e=>{e!==this.state.draft&&(Ik.set(this.key,e),this.set({draft:e}))},this.setEventListening=async e=>{let r=this.state.session;r&&(await rD.api.setChatEventListening(r.id,e),this.metadataWrites+=1,this.state.session?.id===r.id&&this.adoptSession({...r,eventListeningEnabled:e}))},this.sendMessage=async e=>{let r=this.state.session?.id,s=e.trim();if(r&&s)try{await Iy(r,s)}catch(r){let e=r instanceof Error?r.message:"Failed to send message";this.set({error:e}),xN.toast.error("Failed to send message",{description:e})}},this.stopGeneration=async()=>{let e=this.state.session?.id;if(e)try{await Ib(e)}catch(e){console.error("[ChatSession] Failed to stop generation:",e)}},this.restartSession=async()=>{let e=this.state.session?.id;if(e)try{await rD.api.resetChatSession(e),this.container={entries:[],status:"stopped"},this.flush()}catch(e){console.error("[ChatSession] Failed to reset session:",e),xN.toast.error("Failed to start new conversation")}},this.key=Iw(e,r);const s=IS.get(this.key),n=Ik.get(this.key)??"",i=s?.session??I_.get(this.key)??null;this.state=s?{...Ig,session:i,messages:s.messages,status:s.status,isInitialized:!0,draft:n}:{...Ig,session:i,draft:n}}subscribe;getSnapshot;set(e){for(let r of(this.state={...this.state,...e},this.listeners))r()}start(){this.active||(this.active=!0,this.finished=!1,"undefined"!=typeof document&&(document.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("online",this.onOnline)),this.startSession())}stop(){if(!this.active)return;this.active=!1,this.epoch+=1,"undefined"!=typeof document&&(document.removeEventListener("visibilitychange",this.onVisibilityChange),window.removeEventListener("online",this.onOnline));let e=this.ws;if(this.ws=null,e)try{e.close(1e3,"branch-switch")}catch{}this.clearTimers(),this.connectionStartedAt=null,this.state.isConnected&&this.set({isConnected:!1})}clearTimers(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.stabilityTimer&&(clearTimeout(this.stabilityTimer),this.stabilityTimer=null),this.clearSilenceTimer()}async startSession(){if(!this.active)return;let e=this.epoch;this.lastStartFailed=!1,this.set({error:null});let r=I_.get(this.key);if(r){this.set({session:r}),this.connect(),this.refreshSessionMetadata(e);return}this.set({isLoading:!0});try{let{session:r,messages:s}=await Iv(this.projectId,this.branch);if(e!==this.epoch)return;I_.set(this.key,r),this.set({session:r,status:r.status,messages:s??[],isInitialized:!0}),this.connect()}catch(r){if(e!==this.epoch)return;this.lastStartFailed=!0,this.set({error:r instanceof Error?r.message:"Failed to start session"})}finally{e===this.epoch&&this.set({isLoading:!1})}}async refreshSessionMetadata(e){let r=this.metadataWrites;try{let{session:s,messages:n}=await Iv(this.projectId,this.branch);if(e!==this.epoch||r!==this.metadataWrites||s.id!==this.state.session?.id)return;this.adoptSession(s),this.state.isInitialized||this.set({messages:n??[],isInitialized:!0})}catch{}}adoptSession(e){I_.set(this.key,e);let r=IS.get(this.key);r&&r.session.id===e.id&&Ij(this.key,{...r,session:e}),this.set({session:e})}connect(e=!1){if(!this.active||this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING))return;let r=this.epoch;Promise.race([(0,rD.getFreshToken)(e?{skipCache:!0}:void 0),new Promise(e=>setTimeout(e,5e3))]).catch(()=>void 0).then(()=>{if(r===this.epoch&&this.active){if(!(0,rD.hasUsableStreamToken)()){let e=IC(Math.min(this.tokenRetryAttempt,4));this.tokenRetryAttempt++,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.state.session?.id&&!this.finished&&this.connect(!0)},e);return}this.tokenRetryAttempt=0,this.openSocket()}})}openSocket(){if(this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING))return;let e=this.state.session?.id;if(!e)return;this.container={entries:[],status:"stopped"},this.finished=!1,this.replaying=!0;let r=new WebSocket((0,rD.getWebSocketUrl)(`/api/chat-sessions/${e}/stream`));this.ws=r;let s=()=>this.ws===r;r.onopen=()=>{s()&&(this.set({isConnected:!0,error:null}),this.connectionStartedAt=Date.now(),this.armSilenceTimer(r),this.stabilityTimer&&clearTimeout(this.stabilityTimer),this.stabilityTimer=setTimeout(()=>{this.reconnectAttempt=0,this.shortLivedConnections=0},5e3))},r.onmessage=e=>{if(s()){this.armSilenceTimer(r);try{this.handleFrame(r,JSON.parse(e.data))}catch(e){console.error("[ChatSession] Failed to parse message:",e)}}},r.onclose=e=>{if(!s())return;this.ws=null,this.set({isConnected:!1}),this.clearSilenceTimer(),this.stabilityTimer&&(clearTimeout(this.stabilityTimer),this.stabilityTimer=null);let n=4e3===e.code,i=this.connectionStartedAt?Date.now()-this.connectionStartedAt:0;if(this.connectionStartedAt=null,this.authRejectedSocket===r){if(this.authRejectedSocket=null,this.finished)return;let e=IC(Math.min(this.authRejects-1,4));this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.state.session?.id&&!this.finished&&this.connect(!0)},e);return}if(!n&&i>0&&i<5e3){if(this.shortLivedConnections++,this.shortLivedConnections>=3)return this.lastStartFailed?void this.set({error:"Unable to connect to remote server. Please check the server configuration."}):(I_.delete(this.key),this.reconnectAttempt=0,this.shortLivedConnections=0,this.set({session:null,error:null}),void this.startSession())}else i>=5e3&&(this.shortLivedConnections=0);if(this.finished||1e3===e.code)return;if(this.reconnectAttempt>=10)return void this.set({error:"Unable to connect to server."});let a=IC(this.reconnectAttempt);this.reconnectAttempt++,this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.state.session?.id&&!this.finished&&this.connect(!0)},a)},r.onerror=()=>{}}handleFrame(e,r){if("error"in r||(this.authRejects=0),!("keepalive"in r)){if("JsonPatch"in r){var s,n;this.container=(s=this.container,n=r.JsonPatch,EC(s,e=>{for(let r of n){let{op:s,path:n,value:i}=r;if("/entries"===n&&"replace"===s&&i?.type==="ENTRY"&&i.content?.type==="system"&&i.content?.content==="__CLEAR_ALL__"){e.entries=[];continue}if(n.startsWith("/entries/")){let r=parseInt(n.replace("/entries/",""),10);if(isNaN(r)||i?.type!=="ENTRY")continue;switch(s){case"add":for(;e.entries.length<=r;)e.entries.push(null);e.entries[r]=i.content;break;case"replace":r<e.entries.length&&(e.entries[r]=i.content);break;case"remove":r<e.entries.length&&e.entries.splice(r,1)}}else"/status"===n&&i?.type==="STATUS"&&(e.status=i.content)}})),this.replaying||this.flush();return}if("Ready"in r){this.replaying=!1,this.flush(),this.set({isInitialized:!0,streamEpoch:this.state.streamEpoch+1});return}if("finished"in r){this.finished=!0,e.close(1e3,"finished");return}if("openPreviewFrame"in r)return void(0,Cu.openPreviewFrame)(r.openPreviewFrame.projectId,r.openPreviewFrame.url);if("WorkflowRunUpdated"in r)return void this.set({workflowRunUpdate:r.WorkflowRunUpdated});if("TurnState"in r)return void this.set({turnState:r.TurnState});if("browserCommand"in r){let s=r.browserCommand;(0,Cu.sendCommandToIframe)(this.projectId,{type:"vibedeckx-command",...s}).then(r=>{r&&e.readyState===WebSocket.OPEN&&e.send(JSON.stringify({type:"browser_result",result:{id:s.id,success:r.success??!1,error:r.error,content:r.content,found:r.found,tag:r.tag,text:r.text}}))});return}if("error"in r){if((0,rD.isStreamAuthError)(r.error)){this.authRejectedSocket=e,this.authRejects++,this.authRejects>=rD.STREAM_AUTH_REJECTS_BEFORE_ERROR&&this.set({error:rD.STREAM_AUTH_FAILED_MESSAGE});return}this.set({error:r.error}),"Session not found"===r.error&&(I_.delete(this.key),IS.delete(this.key),this.finished=!0)}}}flush(){let e=this.container.entries.filter(Boolean),r=this.container.status;this.set({messages:e,status:r}),this.state.session&&Ij(this.key,{session:this.state.session,messages:e,status:r})}clearSilenceTimer(){this.silenceTimer&&(clearTimeout(this.silenceTimer),this.silenceTimer=null)}armSilenceTimer(e){this.silenceTimer&&clearTimeout(this.silenceTimer),this.silenceTimer=setTimeout(()=>{this.silenceTimer=null,e.readyState===WebSocket.OPEN&&(console.warn(`[ChatSession] No frames for 95000ms — assuming dead socket, forcing reconnect`),this.replaceSilentSocket(e))},95e3)}replaceSilentSocket(e){if(this.ws===e){this.ws=null,this.set({isConnected:!1}),this.stabilityTimer&&(clearTimeout(this.stabilityTimer),this.stabilityTimer=null),this.connectionStartedAt=null;try{e.close(4e3,"silence watchdog")}catch{}this.finished||this.connect(!0)}}onVisibilityChange;onOnline;setDraft;setEventListening;sendMessage;stopGeneration;restartSession}let IE=()=>()=>{},ID=()=>Ig,IR=async()=>{},IT=()=>{};function IA(e){return e&&"object"==typeof e&&"string"==typeof e.goal&&Array.isArray(e.completionCriteria)&&e.completionCriteria.every(e=>"string"==typeof e)&&Array.isArray(e.steps)&&e.steps.every(e=>e&&"string"==typeof e.id&&"string"==typeof e.title&&["pending","in_progress","completed","failed","skipped"].includes(e.status)&&(void 0===e.result||"string"==typeof e.result))&&(void 0===e.planId||"string"==typeof e.planId)&&(void 0===e.waitingOn||"string"==typeof e.waitingOn)?e:null}function IM(e){try{let r=JSON.parse(e);return r.success?IA(r.plan):null}catch{return null}}let II={pending:aw,in_progress:a7,completed:oC,failed:oE,skipped:(0,eA.default)("circle-minus",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}]])},IF={pending:"Pending",in_progress:"In progress",completed:"Completed",failed:"Failed",skipped:"Skipped"};function IP({plan:e,draft:r=!1}){let s=e.steps.filter(e=>"completed"===e.status||"skipped"===e.status).length;return(0,B.jsxs)("div",{className:"rounded-lg border bg-muted/20 p-3 space-y-3 text-sm",children:[(0,B.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,B.jsx)("span",{className:"font-medium break-words",children:e.goal}),(0,B.jsx)("span",{className:"shrink-0 text-xs text-muted-foreground",children:r?"Plan draft":`${s}/${e.steps.length}`})]}),e.waitingOn&&!r&&(0,B.jsxs)("div",{className:"rounded-md border border-amber-500/30 bg-amber-500/10 px-2 py-1.5 text-xs text-amber-700 dark:text-amber-300 break-words",children:["Waiting for you: ",e.waitingOn]}),(0,B.jsxs)("div",{className:"text-xs text-muted-foreground space-y-1",children:[(0,B.jsx)("div",{className:"font-medium",children:"Completion criteria"}),e.completionCriteria.map((e,r)=>(0,B.jsxs)("div",{className:"break-words",children:["• ",e]},r))]}),(0,B.jsx)("ol",{className:"space-y-2",children:e.steps.map(e=>{let r=II[e.status];return(0,B.jsxs)("li",{className:"flex gap-2",children:[(0,B.jsx)(r,{"aria-label":IF[e.status],className:`mt-0.5 h-4 w-4 shrink-0 ${"in_progress"===e.status?"animate-spin text-primary":"completed"===e.status?"text-emerald-600":"failed"===e.status?"text-destructive":"text-muted-foreground"}`}),(0,B.jsxs)("div",{className:"min-w-0",children:[(0,B.jsx)("div",{className:"break-words",children:e.title}),e.result&&(0,B.jsx)("div",{className:"text-xs text-muted-foreground whitespace-pre-wrap break-words",children:e.result})]})]},e.id)})}),r&&(0,B.jsx)("p",{className:"text-xs text-muted-foreground",children:"To change this plan, decline it and describe the changes in chat."})]})}function IL({sessionId:e,approvalId:r,tool:s,input:n,resolved:i,embedded:a=!1}){let[o,l]=(0,$.useState)(null),c="setPlan"===s?IA(n):null,[d,u]=(0,$.useState)(null),h=function(e){if(null!==e&&"object"==typeof e){if("string"==typeof e.message)return e.message;if("string"==typeof e.prompt)return e.prompt}return JSON.stringify(e)}(n),f=async s=>{if(!o&&!i){l(s?"approve":"deny"),u(null);try{await rD.api.chatToolApproval(e,r,s)}catch{u("Could not submit your decision. Please try again.")}finally{l(null)}}};return(0,B.jsx)("div",{className:a?"@container/approval min-w-0":"@container/approval min-w-0 mx-4 my-1",children:(0,B.jsxs)("div",{className:a?"space-y-2":"rounded-lg border border-amber-500/30 bg-amber-500/5 p-3 space-y-2",children:[(0,B.jsxs)("div",{className:"flex items-center gap-2",children:[(0,B.jsx)(a3,{className:"h-3.5 w-3.5 text-amber-500 shrink-0"}),(0,B.jsxs)("span",{className:"text-xs font-medium text-amber-600 dark:text-amber-400",children:["Approval needed · ","setPlan"===s?"Review task plan":"spawnAgentSession"===s?"Start a new coding agent":"Send to the coding agent"]})]}),c?(0,B.jsx)(IP,{plan:c,draft:!0}):(0,B.jsx)("pre",{className:"bg-muted/50 p-2 rounded overflow-x-auto max-w-full whitespace-pre-wrap break-all text-foreground/80",style:{fontSize:"var(--conv-font-size, 12px)"},children:h}),d&&(0,B.jsx)("p",{role:"alert",className:"text-xs text-destructive",children:d}),i?(0,B.jsxs)(sg,{variant:"default",className:"approved"===i?"bg-green-600 hover:bg-green-700 text-white":"bg-red-600 hover:bg-red-700 text-white",children:["approved"===i?(0,B.jsx)(oC,{className:"h-3 w-3 mr-1"}):(0,B.jsx)(oE,{className:"h-3 w-3 mr-1"}),c?"approved"===i?"Plan confirmed":"Plan declined — describe changes in chat":"approved"===i?"Approved — sent.":"Denied — not sent."]}):(0,B.jsxs)("div",{className:c?"grid grid-cols-1 gap-2 @min-[24rem]/approval:grid-cols-2":"flex flex-wrap gap-2",children:[(0,B.jsxs)(Z.Button,{onClick:()=>f(!0),disabled:null!==o,className:"h-auto min-h-8 min-w-0 whitespace-normal py-1.5 bg-green-600 hover:bg-green-700 text-white",size:"sm",children:["approve"===o?(0,B.jsx)(a7,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):(0,B.jsx)(oC,{className:"h-3.5 w-3.5 mr-1"}),c?"Confirm and execute":"Approve"]}),(0,B.jsxs)(Z.Button,{onClick:()=>f(!1),disabled:null!==o,variant:"destructive",className:"h-auto min-h-8 min-w-0 whitespace-normal py-1.5",size:"sm",children:["deny"===o?(0,B.jsx)(a7,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):(0,B.jsx)(oE,{className:"h-3.5 w-3.5 mr-1"}),c?"Decline and revise":"Deny"]})]})]})})}let Iz="[Plan Stalled]",IO="[Commander Stalled]",IB="[Plan Continuation]",I$=e=>e.steps.length>0&&e.steps.every(e=>"completed"===e.status||"skipped"===e.status);function IW({task:e,sessionId:r}){let{plan:s,approval:n}=e,i=(0,$.useId)(),a=s.steps.filter(e=>"completed"===e.status||"skipped"===e.status).length,o=!n&&s.steps.length>0&&a===s.steps.length,[l,c]=(0,$.useState)(null),d=l?.completed===o?l.expanded:!o,u=s.steps.find(e=>"in_progress"===e.status),h=s.steps.find(e=>"failed"===e.status),f=s.steps.find(e=>"pending"===e.status),p=n&&!n.resolved,m=!!e.stalled&&!o,g=p?"Needs confirmation":n?.resolved==="denied"?"Plan declined":n?.resolved==="approved"?"Confirmed":o?"Completed":m?"Stalled · send a message to continue":s.waitingOn?`Waiting for you: ${s.waitingOn}`:u?u.title:h?`Failed \xb7 ${h.title}`:f?`Next: ${f.title}`:"Task plan",x=p||n?.resolved==="denied"||h||m||s.waitingOn?oI:n?aw:o?oC:u?a7:aw;return(0,B.jsxs)("section",{"aria-label":"Current task plan",className:"mb-2 overflow-hidden rounded-lg border bg-muted/20",children:[(0,B.jsxs)("button",{type:"button",className:"flex w-full items-center gap-2 px-3 py-2 text-left hover:bg-muted/50","aria-label":d?"Collapse task plan":"Expand task plan","aria-expanded":d,"aria-controls":i,onClick:()=>c({completed:o,expanded:!d}),children:[d?(0,B.jsx)(aI,{className:"h-3.5 w-3.5 shrink-0"}):(0,B.jsx)(ab,{className:"h-3.5 w-3.5 shrink-0"}),(0,B.jsx)(x,{className:`h-3 w-3 shrink-0 ${x===a7?"animate-spin":""} ${p||m||s.waitingOn?"text-amber-500":o?"text-emerald-600":h?"text-destructive":""}`}),(0,B.jsx)("span",{className:"min-w-0 flex-1 truncate text-xs font-medium",title:s.goal,children:s.goal}),(0,B.jsx)("span",{className:"max-w-[45%] truncate text-xs text-muted-foreground","aria-live":"polite",title:g,children:g}),(0,B.jsxs)("span",{className:"shrink-0 text-xs text-muted-foreground",children:[a,"/",s.steps.length]})]}),d&&(0,B.jsx)("div",{id:i,className:"max-h-[min(16rem,35dvh)] overflow-y-auto overscroll-contain border-t p-2",children:n?(0,B.jsx)(IL,{sessionId:r,approvalId:n.approvalId,tool:"setPlan",input:n.input,resolved:n.resolved,embedded:!0},n.approvalId):(0,B.jsx)(IP,{plan:s})})]})}let IH={kind:"plan",label:"Plan file",description:"Work through a step-by-step plan in the repo, one step per session: implement, verify, commit. The loop keeps track of which steps are done.",fields:[{key:"planFile",label:"Plan file",placeholder:"docs/implementation-plan.md",hint:"Any numbered list of steps works; nothing in the file has to be ticked."},{key:"readDocs",label:"Docs to read every session",multiline:!0,placeholder:"AGENTS.md\ndocs/design.md\nOn conflicts, docs/design.md wins.",hint:"One per line; say which wins on a conflict."}],defaults:{planFile:"docs/implementation-plan.md",readDocs:""},handoffByDefault:!0},IU={kind:"custom",label:"Custom",description:"Write the whole instruction yourself.",fields:[],defaults:{},handoffByDefault:!1},Iq=[IH,IU];function IK(e){return"plan"===e?IH:IU}function IV(e,r){return"plan"===e?function(e){var r;let s=(r="planFile",e[r]?.trim()||IH.defaults[r]||""),n=(e.readDocs??"").split(/\r?\n/).map(e=>e.trim()).filter(Boolean),i=[];i.push(`You are implementing this project by following the plan in \`${s}\`. Each session completes exactly ONE step: implement it, verify it, commit it, then stop.`);let a=[`- \`${s}\` — the plan, a sequence of numbered steps.`,'- The loop records which steps earlier sessions completed and lists them at the top of this message ("已完成的项"). No list means no step has been recorded yet — this is the first session, or a restart.'];return n.length&&a.push(`- Also read these every session:
|
|
37
|
+
${((e,r="")=>e.map(e=>`${r}- ${e}`).join("\n"))(n," ")}`),i.push(`## 1. Read first
|
|
38
38
|
|
|
39
|
-
${
|
|
39
|
+
${a.join("\n")}`),i.push("## 2. Pick the step\n\nGo through the steps in order and pick the first one that is NOT in the completed list and whose dependencies are all done. Do only that one; do not start later steps early.\nBefore you change anything, check whether the step is in fact already done — an earlier session may have finished it without the loop recording it (a restart, an interrupted session), or the plan file may already mark it done. If its acceptance criteria are met and its verification passes, do not redo it: report it as this session's item (section 7) and stop.\nIf the step was attempted before and left unfinished, find out why before you start, and do not repeat an approach that already failed."),i.push(`## 3. Implement
|
|
40
40
|
|
|
41
|
-
|
|
42
|
-
If the step was attempted before and left unfinished, find out why before you start, and do not repeat an approach that already failed.`),f=["- Before changing anything, read the design sections the step references and the existing code around it. Implement what is written, reuse the existing abstractions, and do not build a parallel one.","- Change only what is in scope for this step; the main branch must always build and run."],l.length&&f.push(`- Constraints that must never be violated — breaking any of them means the step is not done:
|
|
43
|
-
${IG(l," ")}`),u.push(`## 3. Implement
|
|
44
|
-
|
|
45
|
-
${f.join("\n")}`),p=["Meet every acceptance criterion of the step, and actually RUN the verification — do not just claim it passes.",""],c.length&&p.push(`- Run these every session:
|
|
46
|
-
${c.map(e=>` - \`${e}\``).join("\n")}`),p.push("- If the environment truly cannot satisfy a check, use the fallback the plan gives, and say which check, why, and when it will be made up — in your final message and in the commit message.",`- A threshold or parameter the plan does not specify is not a blocker: pick a defensible default, keep it in one configurable place (a constants module or config), record the value and the reason in ${a?`\`${a}\``:"the project's docs"}, and carry on.`),u.push(`## 4. Verify
|
|
47
|
-
|
|
48
|
-
${p.join("\n")}`),u.push(`## 5. Mark it done
|
|
49
|
-
|
|
50
|
-
Only once the acceptance criteria are really met and the verification really passed, change the step's marker to \`${i}\`. If you cannot finish it, leave it pending and say why in your final message.`),u.push("## 6. Commit\n\nCommit everything from this session — the code and the plan's marker — in ONE git commit:\n- Title like `<step number>: <summary>`.\n- Body: what was done, the key decisions, and the verification commands actually run with their results.\n\nThe session is not over until the commit is made. Do not push."),m=[`- Every step in the plan is done (no \`${n}\` left): end with \`Status: done\`.`,"- Something only a human can provide blocks the way (secrets, credentials, external accounts, a decision only a person can make): commit as usual, then end with `Status: blocked` and say exactly what is needed and where it goes (which environment variable or file). Do not work around it, do not fake secrets, and never write secrets into the repository."],d.length&&m.push(` Already available — not a blocker:
|
|
51
|
-
${IG(d," ")}`),m.push("- Otherwise: end with `Status: continue`, and set `Item:` to the step number."),u.push(`## 7. Report
|
|
52
|
-
|
|
53
|
-
${m.join("\n")}`),u.join("\n\n")):""}let IZ=e=>`loop-draft:${e}`,IQ=(0,$.createContext)({markReviewRunRead:()=>{}}),I0=IQ.Provider,I1=(0,eA.default)("alarm-clock",[["circle",{cx:"12",cy:"13",r:"8",key:"3y4lt7"}],["path",{d:"M12 9v4l2 2",key:"1c63tq"}],["path",{d:"M5 3 2 6",key:"18tl5t"}],["path",{d:"m22 6-3-3",key:"1opdir"}],["path",{d:"M6.38 18.7 4 21",key:"17xu3x"}],["path",{d:"M17.64 18.67 20 21",key:"kv2oe2"}]]),I2=(0,eA.default)("pause",[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1",key:"kaeet6"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1",key:"1wsw3u"}]]),I5=new Set(["preparing","waiting_reviewer","waiting_feedback","discussing","sending_feedback","waiting_rereview","running_task","waiting_resume"]),I3={ship:{text:"ship",className:"border-emerald-500/40 bg-emerald-500/10 text-emerald-700 dark:text-emerald-400"},"needs-changes":{text:"needs-changes",className:"border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-400"},"cannot-verify":{text:"cannot-verify",className:"border-border bg-muted text-muted-foreground"}};function I4(e){if(!e.loop_id)return null;let r=e.round??1,s=e.max_rounds?`第 ${r} / ${e.max_rounds} 轮`:`第 ${r} 轮`;return e.loop_manual?`${s} \xb7 已转人工`:s}function I6(e){return null!=e.max_rounds&&(e.round??1)>e.max_rounds}function I7(e){return e.map(e=>e.id).sort().join(",")}function I8({projectId:e,branch:r,runUpdate:s,streamEpoch:n,onRunsChange:i}){let[a,o]=(0,$.useState)([]),[l,c]=(0,$.useState)({}),[d,u]=(0,$.useState)({}),[h,f]=(0,$.useState)(null),[p,m]=(0,$.useState)(null),g=(0,$.useRef)(0),{markReviewRunRead:x}=(0,$.useContext)(IQ),[v,y]=(0,$.useState)(()=>({projectId:e,branch:r}));(v.projectId!==e||v.branch!==r)&&(y({projectId:e,branch:r}),m(null));let b=(0,$.useRef)(0),w=(0,$.useRef)(null),_=(0,$.useRef)({projectId:e,branch:r});(0,$.useEffect)(()=>{_.current={projectId:e,branch:r}},[e,r]);let S=(0,$.useCallback)(async s=>{if(!e)return;let n=++b.current,a=Aq(e,r,s);try{let e=await a.request;if(n!==b.current)return;w.current={at:a.issuedAt,runs:e},o(e),i?.(e),m(r=>{if(!r)return r;let s=e.find(e=>e.id===r.runId)??null;return(s?.status??null)===r.status&&(s||I7(e)===r.signature)?r:null})}catch{}},[e,r,i]),j=(0,$.useRef)(null);(0,$.useEffect)(()=>{let e=null!==j.current&&j.current!==n;j.current=n,S({force:e})},[S,n]),(0,$.useEffect)(()=>{s&&S({force:!0})},[s,S]),(0,$.useEffect)(()=>{if(0===a.length)return;let e=setInterval(()=>void S({force:!0}),5e3);return()=>clearInterval(e)},[a.length,S]),(0,$.useEffect)(()=>{let e=()=>{"visible"===document.visibilityState&&S({force:!0})};return document.addEventListener("visibilitychange",e),window.addEventListener("online",e),()=>{document.removeEventListener("visibilitychange",e),window.removeEventListener("online",e)}},[S]);let k=async(s,n,i)=>{let a=++g.current;f(s),m(null);let o=null;try{await i()}catch(e){o=e instanceof Error?e.message:String(e)}finally{f(null),S({force:!0})}if(!o)return void x(s,{runEnded:"finalize"!==n&&"rereview"!==n&&"schedule"!==n});let l=null;if(e){let s=Aq(e,r,{force:!0}),n=await s.request.catch(()=>null),i=w.current;l=i&&i.at>=s.issuedAt?i.runs:n}if(_.current.projectId!==e||_.current.branch!==r||a!==g.current)return;let c=l?.find(e=>e.id===s)??null;m({runId:s,status:c?.status??null,message:(l?function(e,r){if("cancel"===e||"pause"===e||"resume"===e||"schedule"===e)return null;if(!r)return"这次 review 已经结束了 —— 反馈可能已经发出,或者 run 已被取消。";if("approve"===e){if("discussing"===r.status)return"reviewer 已进入讨论:先点「生成终稿」拿到新的结论,再发送反馈。";if("waiting_reviewer"===r.status)return"reviewer 正在重新出稿,等它完成后再发送。";if("sending_feedback"===r.status)return"反馈正在发送中。"}if("finalize"===e){if("waiting_feedback"===r.status)return"终稿已经出来了,直接发送反馈即可。";if("waiting_reviewer"===r.status)return"reviewer 正在出稿,稍候再试。"}if("accept"===e){if("discussing"===r.status)return"reviewer 已进入讨论:先点「生成终稿」拿到新的结论。";if("waiting_reviewer"===r.status)return"reviewer 正在重新出稿,等它完成后再决定。";if("sending_feedback"===r.status)return"反馈正在发送中。"}if("rereview"===e){if("waiting_rereview"===r.status)return null;if("waiting_reviewer"===r.status)return"复审已经发起,reviewer 正在审查。";if("waiting_feedback"===r.status)return"这一轮复审已经出结论了。"}return null}(n,c):null)??o,signature:I7(l??[])})},C=a.filter(e=>I5.has(e.status)),N=p&&!C.some(e=>e.id===p.runId)?p:null;return 0!==C.length||N?(0,B.jsxs)("div",{className:"shrink-0 border-b bg-muted/30 px-4 py-2 space-y-2 max-h-[50vh] overflow-y-auto",children:[N&&(0,B.jsxs)("div",{className:"flex items-start justify-between gap-2 text-destructive",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,B.jsx)("span",{children:N.message}),(0,B.jsx)(Z.Button,{variant:"ghost",size:"icon-sm","aria-label":"关闭提示",onClick:()=>m(null),children:(0,B.jsx)(ro,{className:"h-3 w-3"})})]}),C.map(e=>"repeat"===e.kind?(0,B.jsx)(Fr,{run:e,busy:h===e.id,error:p?.runId===e.id?p.message:null,onAction:r=>k(e.id,r,()=>"cancel"===r?rD.api.cancelWorkflowRun(e.id):rD.api.workflowRunGate(e.id,r)),onScheduleResume:r=>k(e.id,"schedule",()=>rD.api.scheduleResume(e.id,r))},e.id):(0,B.jsxs)("div",{className:"space-y-2",style:{fontSize:"var(--conv-font-size, 14px)"},children:[(0,B.jsxs)("div",{className:"flex items-center justify-between",children:[(0,B.jsxs)("span",{className:"font-medium",children:["Review",e.review_focus?` — ${e.review_focus}`:"",(0,B.jsxs)("span",{className:"ml-2 text-muted-foreground",children:["preparing"===e.status&&"准备中…","waiting_reviewer"===e.status&&"reviewer 审查中…","waiting_feedback"===e.status&&"等你确认反馈","discussing"===e.status&&"讨论中","sending_feedback"===e.status&&"发送中…","waiting_rereview"===e.status&&"等你确认复审"]}),I4(e)&&(0,B.jsx)("span",{className:"ml-2 text-muted-foreground",children:I4(e)})]}),(0,B.jsxs)(Z.Button,{variant:"ghost",size:"sm",disabled:h===e.id,onClick:()=>k(e.id,"cancel",()=>rD.api.cancelWorkflowRun(e.id)),children:[(0,B.jsx)(ro,{className:"h-3 w-3 mr-1"}),"结束"]})]}),e.error&&(0,B.jsx)("div",{className:"text-amber-600",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.error}),"preparing"===e.status&&(0,B.jsxs)("div",{className:"flex items-center text-muted-foreground",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,B.jsx)(a7,{className:"h-3 w-3 mr-1 animate-spin"})," 正在蒸馏上下文并启动 reviewer"]}),"waiting_reviewer"===e.status&&(0,B.jsxs)("div",{className:"flex items-center text-muted-foreground",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,B.jsx)(a7,{className:"h-3 w-3 mr-1 animate-spin"})," reviewer session 正在工作"]}),"discussing"===e.status&&(0,B.jsxs)("div",{className:"flex items-center gap-2",children:[(0,B.jsx)("span",{className:"text-muted-foreground",style:{fontSize:"var(--conv-font-size, 12px)"},children:"与 reviewer 讨论后,生成终稿再发送"}),(0,B.jsx)(Z.Button,{size:"icon-sm",variant:"outline","aria-label":"生成 review 终稿",disabled:h===e.id,onClick:()=>k(e.id,"finalize",()=>rD.api.workflowRunGate(e.id,"finalize")),children:(0,B.jsx)(Dm,{className:"h-3 w-3"})})]}),"waiting_rereview"===e.status&&(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)("div",{className:"text-muted-foreground",style:{fontSize:"var(--conv-font-size, 12px)"},children:I6(e)?`source 已按反馈完成修改。已达上限 ${e.max_rounds} 轮——要再加一轮吗?`:"source 已按反馈完成修改。由同一个 reviewer 复审这次修改?"}),(0,B.jsxs)("div",{className:"flex gap-2",children:[(0,B.jsx)(Z.Button,{size:"sm",disabled:h===e.id,onClick:()=>k(e.id,"rereview",()=>rD.api.workflowRunGate(e.id,"rereview",void 0,{extend:I6(e)})),children:I6(e)?"再加一轮":`发起第 ${e.round??2} 轮复审`}),(0,B.jsx)(Z.Button,{variant:"outline",size:"sm",disabled:h===e.id,onClick:()=>k(e.id,"cancel",()=>rD.api.cancelWorkflowRun(e.id)),children:"结束循环"})]})]}),"waiting_feedback"===e.status&&(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)("div",{className:"flex items-center gap-2",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,B.jsx)("span",{className:"text-muted-foreground",children:"reviewer 结论"}),e.verdict?(0,B.jsx)("span",{className:`rounded border px-1.5 py-px font-mono ${I3[e.verdict].className}`,children:I3[e.verdict].text}):(0,B.jsx)("span",{className:"rounded border border-dashed px-1.5 py-px text-muted-foreground",children:"未识别,请自行判断"})]}),d[e.id]?(0,B.jsx)(ry,{className:"font-mono min-h-28 max-h-72",style:{fontSize:"var(--conv-font-size, 12px)"},value:l[e.id]??e.feedback_snapshot??"",onChange:r=>c(s=>({...s,[e.id]:r.target.value}))}):(0,B.jsx)("div",{className:"border rounded-md bg-background px-3 py-2 max-h-72 overflow-y-auto",style:{fontSize:"var(--conv-font-size, 12px)"},children:(0,B.jsx)(c6,{children:l[e.id]??e.feedback_snapshot??""})}),(0,B.jsxs)("div",{className:"flex gap-2",children:["ship"===e.verdict&&(0,B.jsx)(Z.Button,{size:"sm",disabled:h===e.id,onClick:()=>k(e.id,"accept",()=>rD.api.workflowRunGate(e.id,"accept")),children:"接受并结束"}),(0,B.jsx)(Z.Button,{size:"sm",variant:"ship"===e.verdict?"outline":"default",disabled:h===e.id,onClick:()=>k(e.id,"approve",()=>rD.api.workflowRunGate(e.id,"approve",l[e.id]??void 0)),children:"ship"===e.verdict?"仍发送反馈":"发送反馈给原 session"}),(0,B.jsx)(Z.Button,{variant:"outline",size:"sm",disabled:h===e.id,onClick:()=>u(r=>({...r,[e.id]:!r[e.id]})),children:d[e.id]?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(SB,{className:"h-3 w-3 mr-1"}),"预览"]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(rN,{className:"h-3 w-3 mr-1"}),"编辑"]})})]})]}),p?.runId===e.id&&(0,B.jsx)("div",{className:"text-destructive",style:{fontSize:"var(--conv-font-size, 12px)"},children:p.message})]},e.id))]}):null}let I9=e=>String(e).padStart(2,"0");function Fe(e){let r=new Date(e);return`${r.getFullYear()}-${I9(r.getMonth()+1)}-${I9(r.getDate())}T${I9(r.getHours())}:${I9(r.getMinutes())}`}function Ft({busy:e,onSchedule:r,onClose:s}){let[n,i]=(0,$.useState)(""),[a,o]=(0,$.useState)(null),[l]=(0,$.useState)(()=>Date.now());return(0,B.jsxs)("div",{className:"space-y-1.5",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,B.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,B.jsx)("span",{className:"text-muted-foreground",children:"多久后继续:"}),(0,B.jsx)(Z.Button,{size:"sm",variant:"outline",disabled:e,onClick:()=>r(Date.now()+36e5),children:"+1h"}),(0,B.jsx)(Z.Button,{size:"sm",variant:"outline",disabled:e,onClick:()=>r(Date.now()+18e6),children:"+5h"}),(0,B.jsx)("input",{type:"datetime-local","aria-label":"自定继续时间",value:n,min:Fe(l),max:Fe(l+6048e5),onChange:e=>{i(e.target.value),o(null)},className:"h-7 rounded-md border bg-background px-1.5 text-xs"}),(0,B.jsx)(Z.Button,{size:"sm",variant:"outline",disabled:e||!n,onClick:()=>{let e=new Date(n).getTime(),s=Date.now();return n&&Number.isFinite(e)?e<=s?o("这个时间已经过去了"):e-s>6048e5?o("最多只能定在 7 天之内"):void r(e):o("先选一个时间")},children:"定在这个时间"}),(0,B.jsx)(Z.Button,{size:"sm",variant:"ghost",disabled:e,onClick:s,children:"取消"})]}),a&&(0,B.jsx)("div",{className:"text-destructive",children:a})]})}function Fr({run:e,busy:r,error:s,onAction:n,onScheduleResume:i}){let[a,o]=(0,$.useState)(!1),[l,c]=(0,$.useState)(!1),d=(0,rD.repeatLoopParams)(e),u=e.round??1,h="waiting_resume"===e.status,f=h&&d?.dispatchFailed===!0,p=h&&!f?Math.max(1,u-1):u,m=d?.stopAfterCurrent===!0,g=function(e){if(!e)return null;let r="plan"===e.kind?`Plan: ${e.fields?.planFile?.trim()||IH.defaults.planFile}`:"custom"===e.kind?"Custom":null;return r?e.edited?`${r}(已手改)`:r:null}(d?.preset),x=d?.handoffNote?.trim()||null,v=h&&"number"==typeof d?.resumeAt?d.resumeAt:null,y=async e=>{await i(e),c(!1)};return(0,B.jsxs)("div",{className:"space-y-2",style:{fontSize:"var(--conv-font-size, 14px)"},children:[(0,B.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,B.jsxs)("span",{className:"font-medium min-w-0 truncate",children:["Loop — ",d?.name??"Loop",(0,B.jsxs)("span",{className:"ml-2 text-muted-foreground",children:["preparing"===e.status&&"正在启动下一个 session…","running_task"===e.status&&(m?"做完这一项后暂停…":"处理中…"),h&&"已停下,等你决定"]}),(0,B.jsxs)("span",{className:"ml-2 text-muted-foreground",children:["第 ",p,e.max_rounds?` / ${e.max_rounds}`:""," 次"]})]}),(0,B.jsxs)(Z.Button,{variant:"ghost",size:"sm",disabled:r,onClick:()=>n("cancel"),title:"立即结束循环,并停掉正在运行的 session",children:[(0,B.jsx)(ro,{className:"h-3 w-3 mr-1"}),"结束"]})]}),g&&(0,B.jsx)("div",{className:"text-muted-foreground min-w-0 truncate",style:{fontSize:"var(--conv-font-size, 12px)"},title:g,children:g}),(d?.prevItem||d?.remaining)&&(0,B.jsxs)("div",{className:"text-muted-foreground",style:{fontSize:"var(--conv-font-size, 12px)"},children:[d.prevItem&&(0,B.jsxs)(B.Fragment,{children:["上一项:",d.prevItem]}),d.prevItem&&d.remaining&&" · ",d.remaining&&(0,B.jsxs)(B.Fragment,{children:["剩余:",d.remaining]})]}),x&&(0,B.jsxs)("div",{style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,B.jsxs)("button",{type:"button","aria-expanded":a,onClick:()=>o(e=>!e),className:"flex items-center text-muted-foreground hover:text-foreground",children:[a?(0,B.jsx)(aI,{className:"h-3 w-3 mr-1"}):(0,B.jsx)(ab,{className:"h-3 w-3 mr-1"}),"上一轮交接"]}),a&&(0,B.jsx)("pre",{"data-testid":"loop-handoff-note",className:"mt-1 max-h-60 overflow-y-auto whitespace-pre-wrap break-words rounded-md border bg-background px-3 py-2 font-mono text-muted-foreground",children:x})]}),e.error&&(0,B.jsx)("div",{className:"text-amber-600",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.error}),"running_task"===e.status&&(0,B.jsxs)("div",{className:"flex items-center gap-2",children:[(0,B.jsxs)("span",{className:"flex items-center text-muted-foreground",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,B.jsx)(a7,{className:"h-3 w-3 mr-1 animate-spin"})," session「",d?.name??"Loop"," #",u,"」正在工作"]}),!m&&(0,B.jsxs)(Z.Button,{size:"sm",variant:"outline",disabled:r,onClick:()=>n("pause"),children:[(0,B.jsx)(I2,{className:"h-3 w-3 mr-1"}),"做完这项后停"]})]}),h&&(0,B.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,B.jsxs)(Z.Button,{size:"sm",disabled:r,onClick:()=>n("resume"),children:[(0,B.jsx)(rS,{className:"h-3 w-3 mr-1"}),"继续循环"]}),null===v&&!l&&(0,B.jsxs)(Z.Button,{size:"sm",variant:"outline",disabled:r,onClick:()=>c(!0),children:[(0,B.jsx)(I1,{className:"h-3 w-3 mr-1"}),"定时继续"]}),(0,B.jsx)("span",{className:"text-muted-foreground",style:{fontSize:"var(--conv-font-size, 12px)"},children:f?`第 ${u} 次迭代没能启动,没有对应的 session`:`相关 session:「${d?.name??"Loop"} #${p}」(见侧栏)`})]}),null!==v&&(0,B.jsxs)("div",{className:"flex items-center gap-1 text-muted-foreground",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,B.jsx)(I1,{className:"h-3 w-3"}),(0,B.jsxs)("span",{children:["将于 ",function(e,r=Date.now()){let s=new Date(e),n=`${I9(s.getHours())}:${I9(s.getMinutes())}`;return s.toDateString()===new Date(r).toDateString()?n:`${s.getMonth()+1}/${s.getDate()} ${n}`}(v)," 自动继续 ·"]}),(0,B.jsx)("button",{type:"button",disabled:r,onClick:()=>void y(null),className:"underline-offset-2 hover:text-foreground hover:underline disabled:opacity-50",children:"取消"})]}),h&&null===v&&l&&(0,B.jsx)(Ft,{busy:r,onSchedule:e=>void y(e),onClose:()=>c(!1)}),s&&(0,B.jsx)("div",{className:"text-destructive",style:{fontSize:"var(--conv-font-size, 12px)"},children:s})]})}let Fs=(0,eA.default)("repeat",[["path",{d:"m17 2 4 4-4 4",key:"nntrym"}],["path",{d:"M3 11v-1a4 4 0 0 1 4-4h14",key:"84bu3i"}],["path",{d:"m7 22-4-4 4-4",key:"1wqhfi"}],["path",{d:"M21 13v1a4 4 0 0 1-4 4H3",key:"1rx37r"}]]),Fn=()=>()=>{},Fi={"claude-code":"Claude Code",codex:"Codex"};function Fa(e,r,s){let n=Math.round(Number(e));return Number.isFinite(n)&&""!==e.trim()?Math.min(s,Math.max(1,n)):r}function Fo({projectId:e,branch:r,disabled:s,onStarted:n}){let[i,a]=(0,$.useState)(!1),[o,l]=(0,$.useState)(""),[c,d]=(0,$.useState)("plan"),[u,h]=(0,$.useState)(()=>({...IK("plan").defaults})),[f,p]=(0,$.useState)(()=>IJ("plan",IK("plan").defaults)),[m,g]=(0,$.useState)(!1),[x,v]=(0,$.useState)("form"),[y,b]=(0,$.useState)(null),[w,_]=(0,$.useState)("claude-code"),[S,j]=(0,$.useState)(String(rD.REPEAT_LOOP_DEFAULT_ITERATIONS)),[k,C]=(0,$.useState)(String(rD.REPEAT_LOOP_DEFAULT_MINUTES)),[N,E]=(0,$.useState)(""),[D,R]=(0,$.useState)(!1),[T,A]=(0,$.useState)(()=>IK("plan").handoffByDefault),[M,I]=(0,$.useState)(!1),[F,P]=(0,$.useState)(null),[L,z]=(0,$.useState)(!1),[O,W]=(0,$.useState)(null),H=IK(c),q=H.fields.length>0,K=q&&m||!q&&""!==f.trim(),V=e=>{let r=IK(e);if(d(e),b(null),g(!1),A(r.handoffByDefault),0===r.fields.length)return void v("instruction");let s={...r.defaults,...u};h(s),p(IJ(e,s)),v("form")},X=(e,r)=>{let s={...u,[e]:r};h(s),m||p(IJ(c,s))},Y=r=>{r?(P(null),z(!1),b(null),W(null),R(!1),e&&(e=>{let r=function(e){try{let r=window.localStorage.getItem(IZ(e));if(!r)return null;let s=JSON.parse(r);return s&&"object"==typeof s?s:null}catch{return null}}(e);if(!r)return;let s="custom"===r.kind?"custom":"plan",n=IK(s),i={...n.defaults,...r.fields??{}},a=n.fields.length>0&&!0===r.edited;d(s),h(i),g(a),p(n.fields.length>0&&!a?IJ(s,i):r.prompt??""),v(n.fields.length>0&&!a?"form":"instruction"),("claude-code"===r.agentType||"codex"===r.agentType)&&_(r.agentType),"string"==typeof r.iterations&&j(r.iterations),"string"==typeof r.minutes&&C(r.minutes),"string"==typeof r.checkCommand&&E(r.checkCommand),A("boolean"==typeof r.handoff?r.handoff:n.handoffByDefault)})(e)):e&&function(e,r){try{window.localStorage.setItem(IZ(e),JSON.stringify(r))}catch{}}(e,{kind:c,fields:u,prompt:f,edited:m,agentType:w,iterations:S,minutes:k,checkCommand:N,handoff:T}),a(r)},G=async e=>{try{return await rD.api.workflowRunGate(e.id,"pause"),!0}catch(r){return W({run:e,message:r instanceof Error?r.message:String(r)}),!1}},J=async()=>{if(O&&!M){I(!0);try{await G(O.run)&&(W(null),xN.toast.success("The loop will stop after its first item"),Y(!1))}finally{I(!1)}}},Q=async(s=T)=>{if(!e||!f.trim()||M||O)return;I(!0),P(null),z(!1);let i=function(e,r){let s=IK(e).fields.map(e=>e.key),n={};for(let e of s)r[e]?.trim()&&(n[e]=r[e]);return Object.keys(n).length?n:void 0}(c,u),a={kind:c,...i?{fields:i}:{},...q&&m?{edited:!0}:{}};try{let i=await rD.api.createRepeatLoop({projectId:e,branch:r,prompt:f.trim(),agentType:w,...o.trim()?{name:o.trim()}:{},maxIterations:Fa(S,rD.REPEAT_LOOP_DEFAULT_ITERATIONS,rD.REPEAT_LOOP_MAX_ITERATIONS),maxMinutes:Fa(k,rD.REPEAT_LOOP_DEFAULT_MINUTES,rD.REPEAT_LOOP_MAX_MINUTES),...N.trim()?{checkCommand:N.trim()}:{},preset:a,handoff:s});if(n?.(i),D&&!await G(i))return;l(""),Y(!1),xN.toast.success(D?"Loop started — it will stop after the first item":"Loop started")}catch(e){P(e instanceof Error?e.message:String(e)),z(s&&e?.code==="worker_unsupported")}finally{I(!1)}},ee=(0,$.useSyncExternalStore)(Fn,U,()=>!1),et=!f.trim()||M||null!==O;return(0,B.jsxs)(rl,{open:i,onOpenChange:Y,children:[(0,B.jsx)(rc,{asChild:!0,children:(0,B.jsx)(Z.Button,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:!e||s,title:s?"A loop is already running on this workspace":"New loop — repeat one instruction, a fresh session per item, until done","aria-label":"New loop",children:(0,B.jsx)(Fs,{className:"h-3.5 w-3.5"})})}),(0,B.jsxs)(rf,{showCloseButton:!1,className:"max-h-[calc(100dvh-2rem)] w-[calc(100%-2rem)] min-w-0 gap-0 overflow-hidden bg-card p-0 grid-rows-[auto_minmax(0,1fr)_auto] sm:w-full sm:max-w-[560px]",onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&!et&&(e.preventDefault(),Q())},children:[(0,B.jsxs)("div",{className:"flex items-start gap-3 border-b bg-secondary px-4 py-3.5",children:[(0,B.jsx)("span",{className:"grid size-7 shrink-0 place-items-center rounded-lg border border-primary/20 bg-accent text-accent-foreground",children:(0,B.jsx)(Fs,{className:"size-[15px]"})}),(0,B.jsxs)("div",{className:"min-w-0",children:[(0,B.jsx)(rg,{className:"text-[14.5px] font-semibold tracking-tight",children:"New loop"}),(0,B.jsx)(rx,{className:"mt-0.5 max-w-[46ch] text-[11.5px] leading-snug",children:"Runs the same instruction again and again, each time in a fresh session that handles one item, until a session reports there is nothing left."})]}),(0,B.jsxs)(ru,{className:"ml-auto grid size-6 shrink-0 place-items-center rounded-md border border-transparent text-muted-foreground/70 transition-colors hover:border-border hover:bg-muted hover:text-foreground",children:[(0,B.jsx)(ro,{className:"size-3.5"}),(0,B.jsx)("span",{className:"sr-only",children:"Close"})]})]}),(0,B.jsxs)("div",{className:"flex min-h-0 min-w-0 flex-col gap-[13px] overflow-x-hidden overflow-y-auto px-4 pt-3.5 pb-1",children:[(0,B.jsxs)("div",{className:"flex min-w-0 flex-col gap-[7px]",children:[(0,B.jsx)(mi,{trailing:(0,B.jsx)(ma,{label:"Preset",value:c,onChange:e=>{e!==c&&(IK(e).fields.length>0&&K?b({action:"switch",to:e}):V(e))},options:Iq.map(e=>({value:e.kind,label:e.label}))}),children:"Preset"}),(0,B.jsx)(mo,{children:H.description})]}),y&&(0,B.jsxs)(mc,{tone:"rose",icon:(0,B.jsx)(oI,{}),children:["regenerate"===y.action?"Regenerating replaces the instruction with the form's version — your edits are lost.":`Switching to ${IK(y.to).label} replaces the instruction — your text is lost.`," ",(0,B.jsxs)("span",{className:"inline-flex gap-2",children:[(0,B.jsx)(ml,{onClick:()=>"regenerate"===y.action?void(g(!1),b(null),p(IJ(c,u))):V(y.to),children:"Discard my text"}),(0,B.jsx)(ml,{onClick:()=>b(null),children:"Keep it"})]})]}),q&&(0,B.jsx)("div",{role:"tablist","aria-label":"Instruction view",className:"flex min-w-0 gap-3 border-b",children:["form","instruction"].map(e=>(0,B.jsx)("button",{type:"button",role:"tab","aria-selected":x===e,onClick:()=>v(e),className:(0,eR.cn)("-mb-px border-b-2 px-0.5 pb-1.5 text-[12px] font-medium transition-colors",x===e?"border-primary text-foreground":"border-transparent text-muted-foreground hover:text-foreground"),children:"form"===e?"Form":"Instruction"},e))}),q&&m&&(0,B.jsxs)("div",{className:"flex items-start gap-2 rounded-lg border border-amber-500/30 bg-amber-500/10 px-2.5 py-2 text-[11.5px] leading-snug text-amber-700 dark:text-amber-300",children:[(0,B.jsx)(DS,{className:"mt-px size-[13px] shrink-0"}),(0,B.jsx)("span",{className:"min-w-0 flex-1",children:"Edited by hand — the form no longer applies; the instruction text is what runs."}),(0,B.jsxs)("button",{type:"button",onClick:()=>b({action:"regenerate"}),className:"inline-flex shrink-0 items-center gap-1 whitespace-nowrap underline-offset-2 hover:underline",children:[(0,B.jsx)(oP,{className:"size-3"}),"Regenerate from form"]})]}),q&&"form"===x&&(0,B.jsx)("fieldset",{disabled:m,className:"grid min-w-0 grid-cols-2 gap-x-2.5 gap-y-[13px] disabled:opacity-60",children:H.fields.map(e=>{let r=`loop-field-${e.key}`,s=e.multiline||"planFile"===e.key;return(0,B.jsxs)("div",{className:(0,eR.cn)("flex min-w-0 flex-col gap-[7px]",s&&"col-span-2"),children:[(0,B.jsx)(mi,{children:(0,B.jsx)("label",{htmlFor:r,children:e.label})}),e.multiline?(0,B.jsx)(ry,{id:r,value:u[e.key]??"",onChange:r=>X(e.key,r.target.value),placeholder:e.placeholder,spellCheck:!1,className:(0,eR.cn)(mr,"field-sizing-fixed min-h-[58px] min-w-0 max-w-full resize-y px-[11px] py-1.5 font-mono text-xs leading-[1.5] md:text-xs")}):(0,B.jsx)(rv,{id:r,value:u[e.key]??"",onChange:r=>X(e.key,r.target.value),placeholder:e.placeholder,spellCheck:!1,className:(0,eR.cn)(mr,"h-[34px] px-[11px] font-mono text-xs md:text-xs")}),e.hint&&(0,B.jsx)(mo,{children:e.hint})]},e.key)})}),(!q||"instruction"===x)&&(0,B.jsxs)("div",{className:"flex min-w-0 flex-col gap-[7px]",children:[(0,B.jsx)(mi,{note:f.trim()?void 0:"Required",children:(0,B.jsx)("label",{htmlFor:"loop-prompt",children:"Instruction"})}),(0,B.jsx)(ry,{id:"loop-prompt",value:f,onChange:e=>{p(e.target.value),q&&g(!0)},placeholder:"Fetch the unprocessed items from …, pick the first one, handle it, and mark it processed.\nIf none are left, say so.",className:(0,eR.cn)(mr,"field-sizing-fixed min-h-[118px] min-w-0 max-w-full resize-y overflow-auto px-[11px] py-2 font-mono text-xs leading-[1.55] md:text-xs",q&&"min-h-[220px]")}),!q&&(0,B.jsx)(mo,{children:"No session remembers the previous one: say where the next unprocessed item is found and how an item is marked done. Make handling an item safe to repeat — an interrupted item may be picked up again."}),(0,B.jsxs)("div",{className:"min-w-0 rounded-lg border border-dashed bg-secondary/60 px-2.5 py-2",children:[(0,B.jsx)("div",{className:"text-[10.5px] text-muted-foreground/80",children:"The loop appends this after your instruction (read-only — it is how the loop reads each session's result):"}),(0,B.jsx)("pre",{"data-testid":"loop-protocol",className:"mt-1 max-h-[96px] overflow-auto font-mono text-[10.5px] leading-[1.5] whitespace-pre-wrap text-muted-foreground",children:(T?IV+'\n\nThen, as the very last part of your message, write a handoff note for the next session:\nHandoff:\n<rewrite the whole note each time: a short "known lessons" list (project quirks, dead ends,\nconventions) plus the last few handoffs (step, result, decisions, what to watch). Keep it\nunder ~40 lines; drop what no longer applies. Do not start any line of it with\n"Status:", "Item:" or "Remaining:".>':IV).trim()})]})]}),(0,B.jsxs)("div",{className:"grid min-w-0 grid-cols-2 gap-x-2.5 gap-y-[13px]",children:[(0,B.jsxs)("div",{className:"flex min-w-0 flex-col gap-[7px]",children:[(0,B.jsx)(mi,{note:"Optional",children:(0,B.jsx)("label",{htmlFor:"loop-name",children:"Name"})}),(0,B.jsx)(rv,{id:"loop-name",value:o,onChange:e=>l(e.target.value),placeholder:"Loop",maxLength:80,className:(0,eR.cn)(mr,"h-[34px] px-[11px]")})]}),(0,B.jsxs)("div",{className:"flex min-w-0 flex-col gap-[7px]",children:[(0,B.jsx)(mi,{children:"Agent"}),(0,B.jsx)("div",{role:"radiogroup","aria-label":"Agent",className:"grid h-[34px] min-w-0 grid-cols-2 gap-0.5 rounded-[9px] border bg-secondary p-[3px]",children:Object.keys(Fi).map(e=>{let r=w===e;return(0,B.jsx)("button",{type:"button",role:"radio","aria-checked":r,onClick:()=>_(e),className:(0,eR.cn)("min-w-0 truncate rounded-md border border-transparent px-2 text-[12px] font-medium transition-colors",r?"border-border bg-card text-foreground shadow-xs":"text-muted-foreground hover:text-foreground"),children:Fi[e]},e)})})]}),(0,B.jsxs)("div",{className:"flex min-w-0 flex-col gap-[7px]",children:[(0,B.jsx)(mi,{children:(0,B.jsx)("label",{htmlFor:"loop-iterations",children:"Stop after"})}),(0,B.jsxs)(mn,{children:[(0,B.jsx)("input",{id:"loop-iterations",inputMode:"numeric",value:S,onChange:e=>j(e.target.value),"aria-label":"Stop after (items)",className:ms}),(0,B.jsx)("span",{className:"text-[11px] whitespace-nowrap text-muted-foreground/70",children:"items"})]})]}),(0,B.jsxs)("div",{className:"flex min-w-0 flex-col gap-[7px]",children:[(0,B.jsx)(mi,{children:(0,B.jsx)("label",{htmlFor:"loop-minutes",children:"Stop after"})}),(0,B.jsxs)(mn,{children:[(0,B.jsx)("input",{id:"loop-minutes",inputMode:"numeric",value:k,onChange:e=>C(e.target.value),"aria-label":"Stop after (minutes)",className:ms}),(0,B.jsx)("span",{className:"text-[11px] whitespace-nowrap text-muted-foreground/70",children:"minutes"})]})]})]}),(0,B.jsxs)("div",{className:"flex min-w-0 flex-col gap-[7px]",children:[(0,B.jsx)(mi,{note:"Optional",children:(0,B.jsx)("label",{htmlFor:"loop-check",children:"Check command"})}),(0,B.jsxs)(mn,{children:[(0,B.jsx)(mL,{}),(0,B.jsx)("input",{id:"loop-check",value:N,onChange:e=>E(e.target.value),placeholder:"npm test",spellCheck:!1,className:(0,eR.cn)(ms,"font-mono text-xs tracking-tight")})]}),(0,B.jsx)(mo,{children:"Runs in the worktree after each item; a non-zero exit stops the loop."})]}),(0,B.jsxs)("label",{className:"flex min-w-0 items-start gap-2 text-[12px] leading-snug",children:[(0,B.jsx)("input",{type:"checkbox",id:"loop-handoff",checked:T,onChange:e=>A(e.target.checked),className:"mt-0.5 size-3.5 shrink-0 accent-primary"}),(0,B.jsxs)("span",{className:"min-w-0",children:["Keep a handoff note between sessions",(0,B.jsx)("span",{className:"block text-[10.5px] text-muted-foreground/80",children:"Each session ends with a short note — lessons learned, what it did, what to watch — and the loop hands it to the next session. Nothing is written to the repo."})]})]}),(0,B.jsxs)("label",{className:"flex min-w-0 items-start gap-2 text-[12px] leading-snug",children:[(0,B.jsx)("input",{type:"checkbox",id:"loop-run-once",checked:D,onChange:e=>R(e.target.checked),className:"mt-0.5 size-3.5 shrink-0 accent-primary"}),(0,B.jsxs)("span",{className:"min-w-0",children:["Run one item first, then decide",(0,B.jsx)("span",{className:"block text-[10.5px] text-muted-foreground/80",children:"The loop stops at a gate after the first item; read its session, then continue or end the loop."})]})]}),(0,B.jsxs)("div",{className:"flex items-start gap-2 rounded-lg border border-amber-500/30 bg-amber-500/10 px-2.5 py-2 text-[11.5px] leading-snug text-amber-700 dark:text-amber-300",children:[(0,B.jsx)(oI,{className:"mt-px size-[13px] shrink-0"}),(0,B.jsx)("span",{className:"min-w-0",children:"Sessions run in edit mode with no confirmation between items. The loop stops on its own when an item is blocked, fails, or a limit is reached — and you can stop it any time."})]}),F&&(0,B.jsxs)(mc,{tone:"rose",icon:(0,B.jsx)(oI,{}),children:[F,L&&(0,B.jsxs)(B.Fragment,{children:[" ",(0,B.jsx)(ml,{onClick:()=>{A(!1),Q(!1)},disabled:M,children:"Turn off handoff note and retry"})]})]}),O&&(0,B.jsxs)(mc,{tone:"rose",icon:(0,B.jsx)(oI,{}),children:["The loop started, but the pause could not be set — it is still running item after item. (",O.message,")"," ",(0,B.jsx)(ml,{onClick:()=>void J(),disabled:M,children:"Retry pause"})]})]}),(0,B.jsxs)("div",{className:"mt-2.5 flex min-w-0 items-center gap-2.5 overflow-hidden border-t bg-secondary px-4 py-2.5",children:[(0,B.jsxs)("span",{className:"flex min-w-0 flex-1 items-center gap-1.5 overflow-hidden text-[11px] text-muted-foreground",children:[(0,B.jsx)(aF,{className:"size-3 shrink-0 text-muted-foreground/70"}),(0,B.jsxs)("span",{className:"truncate",children:["Runs on ",(0,B.jsx)("span",{className:"font-mono",children:r??"main"})]})]}),(0,B.jsx)(ru,{asChild:!0,children:(0,B.jsx)(Z.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",children:O?"Close":"Cancel"})}),(0,B.jsx)(Z.Button,{size:"sm",className:"h-7 gap-1.5 text-xs","aria-label":"Start loop",onClick:()=>void Q(),disabled:et,children:M?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(a7,{className:"size-3 animate-spin"}),"Starting…"]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(Fs,{className:"size-3"}),"Start loop",(0,B.jsx)("kbd",{className:"rounded border border-background/30 bg-background/15 px-1 font-mono text-[10px] leading-[1.4] text-background/90",title:ee?"Command+Enter":"Ctrl+Enter",children:ee?"⌘⏎":"Ctrl⏎"})]})})]})]})]})}let Fl=(0,eA.default)("radio",[["path",{d:"M16.247 7.761a6 6 0 0 1 0 8.478",key:"1fwjs5"}],["path",{d:"M19.075 4.933a10 10 0 0 1 0 14.134",key:"ehdyv1"}],["path",{d:"M4.925 19.067a10 10 0 0 1 0-14.134",key:"1q22gi"}],["path",{d:"M7.753 16.239a6 6 0 0 1 0-8.478",key:"r2q7qm"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]]),Fc=(0,eA.default)("hourglass",[["path",{d:"M5 22h14",key:"ehvnwv"}],["path",{d:"M5 2h14",key:"pdyrp9"}],["path",{d:"M17 22v-4.172a2 2 0 0 0-.586-1.414L12 12l-4.414 4.414A2 2 0 0 0 7 17.828V22",key:"1d314k"}],["path",{d:"M7 2v4.172a2 2 0 0 0 .586 1.414L12 12l4.414-4.414A2 2 0 0 0 17 6.172V2",key:"1vvvr6"}]]);function Fd({messages:e}){let{scrollToBottom:r}=dl(),s=(0,$.useRef)(e.length);return(0,$.useEffect)(()=>{let n=s.current;if(s.current=e.length,!(e.length<=n))for(let s=n;s<e.length;s++){let n=e[s];if("user"===n.type&&n.content.startsWith("[Executor Event:"))return void r({animation:"instant"})}},[e,r]),null}let Fu=(0,$.forwardRef)(function({projectId:e,branch:r},s){let{session:n,messages:i,status:a,isInitialized:o,isLoading:l,error:c,sendMessage:d,stopGeneration:u,restartSession:h,workflowRunUpdate:f,turnState:p,streamEpoch:m,draft:g,setDraft:x,setEventListening:v}=function(e,r){let s=e?Iw(e,r):null,[n,i]=(0,$.useState)(()=>e?new IN(e,r):null);return(n?.key??null)!==s&&i(e?new IN(e,r):null),(0,$.useEffect)(()=>{if(n)return n.start(),()=>n.stop()},[n]),{...(0,$.useSyncExternalStore)(n?.subscribe??IE,n?.getSnapshot??ID,n?.getSnapshot??ID),sendMessage:n?.sendMessage??IR,stopGeneration:n?.stopGeneration??IR,restartSession:n?.restartSession??IR,setDraft:n?.setDraft??IT,setEventListening:n?.setEventListening??IR}}(e,r),{settings:y}=(0,dh.useConversationSettings)(),[b,w]=(0,$.useState)([]),_=(0,$.useMemo)(()=>(function(e){let r=new Map,s=null,n=!1,i=!1;for(let[a,o]of e.entries())if("tool_result"===o.type&&"setPlan"===o.tool){let e=IM(o.output);if(!e?.planId)continue;r.set(e.planId,{plan:e,firstIndex:r.get(e.planId)?.firstIndex??a}),s={key:`plan:${e.planId}`,plan:e},n=!1,i=!1}else if("tool_approval_request"===o.type&&"setPlan"===o.tool){let e=IA(o.input);e&&(s={key:`approval:${o.approvalId}`,plan:e,approval:o}),n=!1}else"system"===o.type&&o.content.startsWith(Iz)?n=!0:"user"===o.type&&"commander"!==o.origin&&(n=!1,i=!0,s&&!s.approval&&I$(s.plan)&&(s=null));if(s&&n&&!s.approval&&(s={...s,stalled:!0}),s&&i&&!s.approval&&s.plan.waitingOn){let{waitingOn:e,...r}=s.plan;s={...s,plan:r}}return{current:s,history:r}})(i),[i]);(0,$.useImperativeHandle)(s,()=>({sendMessage:async e=>{let r=e.trim();r&&await d(r)}}),[d]);let S=n?.eventListeningEnabled??!1,j="running"===a,k="waiting"===a,C=kq(e),N=(0,$.useMemo)(()=>[...C.values()].filter(e=>(e.branch??null)===(r??null)),[C,r]),E=(0,$.useCallback)(async e=>{try{await rD.api.startExecutor(e.executorId,e.remoteServerId,"retrying"===e.state?e.processId:void 0)}catch(e){if(e instanceof rD.ExecutorProcessRequestError&&"start_unknown"===e.body.code&&e.body.retrying)return;if(e instanceof rD.ExecutorProcessRequestError&&"retry_ended"===e.body.code)return void xN.toast.info("Already settled",{description:e.message});xN.toast.error("Executor not started",{description:e instanceof Error?e.message:String(e)})}},[]),D=(0,$.useCallback)(async e=>{let r=e.text.trim();r&&(x(""),await d(r))},[d,x]);return e?(0,B.jsxs)("div",{className:"h-full flex flex-col min-h-0",style:{"--conv-font-size":`${y.chatFontSize}px`},children:[(0,B.jsxs)("div",{className:"flex-shrink-0 flex items-center justify-between px-4 h-10 border-b border-border/60 bg-muted/20",children:[(0,B.jsxs)("div",{className:"flex items-center gap-2",children:[(0,B.jsx)(sx,{className:"h-3.5 w-3.5 text-primary"}),(0,B.jsx)("span",{className:"text-xs font-medium text-foreground",children:"Main Chat"}),j&&(0,B.jsx)(a7,{className:"h-3 w-3 animate-spin text-primary/60"}),k&&(0,B.jsx)(Fc,{className:"h-3 w-3 text-primary/60","aria-label":"Waiting for results"})]}),n&&(0,B.jsxs)("div",{className:"flex items-center gap-1",children:[(0,B.jsx)(Z.Button,{variant:"ghost",size:"icon",onClick:async()=>{try{await v(!S)}catch{xN.toast.error("Failed to toggle event listening")}},className:`h-7 w-7 ${S?"text-amber-500":""}`,title:S?"Listening to events from runs Commander did not start (click to disable)":"Also listen to events from runs Commander did not start (click to enable)",children:(0,B.jsx)(Fl,{className:"h-3.5 w-3.5"})}),(0,B.jsx)(Fo,{projectId:e,branch:r,disabled:b.some(e=>"repeat"===e.kind)}),(0,B.jsx)(Z.Button,{variant:"ghost",size:"icon",onClick:()=>h(),disabled:j,className:"h-7 w-7",title:"New Conversation",children:(0,B.jsx)(AX,{className:"h-3.5 w-3.5"})})]})]}),(0,B.jsx)(I8,{projectId:e,branch:r,runUpdate:f,streamEpoch:m,onRunsChange:w}),(0,B.jsxs)(dc,{className:"flex-1 min-h-0",initial:"instant",children:[(0,B.jsx)(Fd,{messages:i}),(0,B.jsxs)(dd,{className:"gap-4 p-4",children:[l&&0===i.length&&(0,B.jsx)("div",{className:"flex items-center justify-center py-8",children:(0,B.jsx)(a7,{className:"h-6 w-6 animate-spin text-muted-foreground"})}),!l&&o&&0===i.length&&(0,B.jsxs)("div",{className:"text-center py-16",children:[(0,B.jsx)("div",{className:"mx-auto w-12 h-12 rounded-xl bg-primary/10 flex items-center justify-center mb-4",children:(0,B.jsx)(sx,{className:"h-6 w-6 text-primary/60"})}),(0,B.jsx)("h3",{className:"text-sm font-semibold mb-1 text-foreground",children:"Start a conversation"}),(0,B.jsx)("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"Chat with the AI assistant about your project"})]}),i.map((s,i)=>{if("turn_end"===s.type)return(0,B.jsxs)("div",{className:"mx-4 my-3 flex items-center gap-2","aria-hidden":!0,children:[(0,B.jsx)("div",{className:"h-px flex-1 bg-border"}),(0,B.jsx)("div",{className:"h-1 w-1 shrink-0 rounded-full bg-border"}),(0,B.jsx)("div",{className:"h-px flex-1 bg-border"})]},i);if("user"===s.type&&(s.content.startsWith("[System Invariant Violation]")||s.content.startsWith(IB))){let e=s.content.startsWith(IB),r=s.content.replace(/^\[(System Invariant Violation|Plan Continuation)\]\n?/,"");return(0,B.jsxs)("div",{className:"mx-4 my-2 flex gap-2 rounded-md border border-amber-500/30 bg-amber-500/10 px-3 py-2",children:[(0,B.jsx)(oI,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-500"}),(0,B.jsxs)("div",{className:"min-w-0",children:[(0,B.jsx)("div",{className:"text-xs font-medium text-amber-600 dark:text-amber-400",children:e?"Plan continuation":"System invariant correction"}),(0,B.jsx)("div",{className:"mt-0.5 whitespace-pre-wrap text-muted-foreground",style:{fontSize:"var(--conv-font-size, 12px)"},children:r})]})]},i)}if("user"===s.type){let n=s.event,a=n?.kind==="agent_task_completed"&&b.some(e=>e.source_session_id===n.sessionId||e.reviewer_session_id===n.sessionId);return(0,B.jsxs)("div",{children:[(0,B.jsx)(c3,{from:"user",children:(0,B.jsx)(c4,{style:{fontSize:"var(--conv-font-size, 14px)"},children:s.content})}),n?.kind==="agent_task_completed"&&(0,B.jsx)("div",{className:"mt-1 flex justify-end",children:(0,B.jsx)(Z.Button,{variant:"outline",size:"sm",disabled:a,title:a?"该 session 已在一个进行中的 review 里":void 0,onClick:async()=>{if(e)try{await rD.api.createWorkflowRun({projectId:e,branch:r,sourceSessionId:n.sessionId,sourceTurnEndIndex:n.turnEndEntryIndex})}catch(e){alert(e instanceof Error?e.message:String(e))}},children:"Review"})})]},i)}if("assistant"===s.type)return(0,B.jsx)(c3,{from:"assistant",children:(0,B.jsx)(c4,{style:{fontSize:"var(--conv-font-size, 14px)"},children:(0,B.jsx)(c6,{children:s.content})})},i);if("tool_use"===s.type)return"setPlan"===s.tool?null:(0,B.jsxs)("div",{className:"flex items-center gap-2 px-4 py-2 text-xs text-muted-foreground",children:[(0,B.jsx)(oo,{className:"w-3.5 h-3.5 animate-pulse"}),(0,B.jsx)("span",{children:function(e){switch(e){case"getExecutorStatus":return"Checking executor status...";case"getAgentConversation":return"Checking agent conversation...";case"listTerminals":return"Listing terminals...";case"runInTerminal":return"Sending command to terminal...";case"spawnAgentSession":return"Starting a coding agent...";case"sendToAgentSession":return"Sending a message to the agent...";default:return`Running ${e}...`}}(s.tool)})]},i);if("tool_result"===s.type){if("setPlan"===s.tool){let e=IM(s.output);if(e?.planId){if(_.current?.plan.planId===e.planId)return null;let r=_.history.get(e.planId);return r&&r.firstIndex===i?(0,B.jsx)("div",{className:"mx-4 my-2",children:(0,B.jsx)(IP,{plan:r.plan})},i):null}}return(0,B.jsx)("div",{className:"px-4 py-2",children:(0,B.jsxs)("details",{className:"text-xs text-muted-foreground",children:[(0,B.jsx)("summary",{className:"cursor-pointer hover:text-foreground",children:"Tool result"}),(0,B.jsx)("pre",{className:"mt-1 p-2 bg-muted/50 rounded overflow-x-auto whitespace-pre-wrap",style:{fontSize:"var(--conv-font-size, 12px)"},children:s.output})]})},i)}if("tool_approval_request"===s.type)return("setPlan"!==s.tool||"approved"!==s.resolved&&_.current?.approval?.approvalId!==s.approvalId)&&n?(0,B.jsx)(IL,{sessionId:n.id,approvalId:s.approvalId,tool:s.tool,input:s.input,resolved:s.resolved},i):null;if("system"===s.type&&(s.content.startsWith(Iz)||s.content.startsWith(IO))){let e=s.content.startsWith(Iz)?Iz:IO;return(0,B.jsxs)("div",{className:"mx-4 my-2 flex gap-2 rounded-md border border-amber-500/40 bg-amber-500/10 px-3 py-2",children:[(0,B.jsx)(oI,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-500"}),(0,B.jsxs)("div",{className:"min-w-0",children:[(0,B.jsx)("div",{className:"text-xs font-medium text-amber-600 dark:text-amber-400",children:e===Iz?"Plan stalled":"Commander stalled"}),(0,B.jsx)("div",{className:"mt-0.5 whitespace-pre-wrap text-muted-foreground",style:{fontSize:"var(--conv-font-size, 12px)"},children:s.content.slice(e.length).trim()})]})]},i)}return"error"===s.type?(0,B.jsx)("div",{className:"mx-auto max-w-[90%] rounded-lg border border-destructive/50 bg-destructive/10 px-4 py-3 text-destructive",style:{fontSize:"var(--conv-font-size, 14px)"},children:s.message},i):null}),c&&(0,B.jsx)("div",{className:"mx-auto max-w-[90%] rounded-lg border border-destructive/50 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:c})]}),(0,B.jsx)(du,{})]}),(0,B.jsxs)("div",{className:"flex-shrink-0 py-3 px-[22px]",children:[N.map(e=>(0,B.jsx)(kK,{delivery:e,showExecutorName:!0,onRetry:()=>E(e),className:"mb-2"},e.processId)),k&&p.waitingFor.length>0&&(0,B.jsxs)("div",{className:"mb-2 flex items-start gap-1.5 text-xs text-muted-foreground","data-testid":"turn-waiting-for",children:[(0,B.jsx)(Fc,{className:"mt-0.5 h-3 w-3 shrink-0"}),(0,B.jsxs)("span",{children:["Waiting for ",p.waitingFor.join(", ")]})]}),_.current&&n&&(0,B.jsx)(IW,{task:_.current,sessionId:n.id},_.current.key),(j||k)&&(0,B.jsx)("div",{className:"flex justify-center mb-2",children:(0,B.jsxs)(Z.Button,{variant:"outline",size:"sm",onClick:u,className:"gap-1.5",children:[(0,B.jsx)(cb,{className:"h-3 w-3"}),j?"Stop generating":"Stop"]})}),(0,B.jsxs)(Aj,{onSubmit:D,className:"w-full",children:[(0,B.jsx)(Ak,{disabled:!o||j,placeholder:o?j?"Waiting for response...":k?"Still on it — add to the task...":"Type a message...":"Connecting...",className:"pr-12",style:{fontSize:"var(--conv-font-size, 14px)"},value:g,onChange:e=>x(e.currentTarget.value)}),(0,B.jsx)("div",{className:"pointer-events-none absolute bottom-0 right-2 flex items-center text-base md:text-sm",style:{fontSize:"var(--conv-font-size, 14px)",height:"calc(1lh + 1.5rem)"},children:(0,B.jsx)(AM,{className:"pointer-events-auto",disabled:!o||j||!g.trim()})})]})]})]}):(0,B.jsx)("div",{className:"h-full flex items-center justify-center text-muted-foreground",children:(0,B.jsxs)("div",{className:"text-center",children:[(0,B.jsx)("div",{className:"mx-auto w-10 h-10 rounded-xl bg-muted flex items-center justify-center mb-3",children:(0,B.jsx)(sx,{className:"h-5 w-5 text-muted-foreground/50"})}),(0,B.jsx)("p",{className:"text-sm",children:"Select a project to start chatting"})]})})}),Fh=(0,eA.default)("archive-restore",[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h2",key:"tvwodi"}],["path",{d:"M20 8v11a2 2 0 0 1-2 2h-2",key:"1gkqxj"}],["path",{d:"m9 15 3-3 3 3",key:"1pd0qc"}],["path",{d:"M12 12v9",key:"192myk"}]]),Ff="grid-cols-[minmax(0,1fr)_88px_176px_44px_56px] @max-3xl:grid-cols-[minmax(0,1fr)_88px_44px_56px] @max-lg:grid-cols-[minmax(0,1fr)_44px_56px]",Fp="@max-3xl:hidden",Fm="@max-lg:hidden",Fg="relative grid items-center gap-x-3 rounded-[7px] px-2";function Fx({task:e,onUpdate:r,onDelete:s,onArchive:n,onUnarchive:i,archivedView:a,onClick:o,worktrees:l,assignedBranches:c,onAssign:d,onOpenSourceSession:u,selected:h,flash:f,compact:p,depth:m=0,progress:g}){let x="done"===e.status||"cancelled"===e.status,v=m>0,y=!p&&!v&&(e.description||e.source_session),b=e=>e.stopPropagation();return(0,B.jsxs)("div",{role:"row","data-task-id":e.id,"data-state":h?"selected":void 0,onClick:()=>o?.(e),className:(0,eR.cn)(Fg,"group cursor-pointer hover:bg-muted",p?"min-h-[34px] grid-cols-[minmax(0,1fr)_auto]":Ff,!p&&(v?"min-h-[34px] py-[3px]":"min-h-[46px] py-1.5"),"data-[state=selected]:bg-accent data-[state=selected]:hover:bg-accent data-[state=selected]:shadow-[inset_0_0_0_1px_color-mix(in_oklab,var(--primary)_14%,transparent)]",f&&"animate-task-row-flash"),children:[(0,B.jsxs)("div",{className:(0,eR.cn)("flex min-w-0 gap-[9px]",p||!y?"items-center":"items-start"),style:v?{paddingLeft:23+(m-1)*20}:void 0,children:[(0,B.jsx)(aB,{status:e.status,onChange:s=>r(e.id,{status:s}),children:(0,B.jsx)("button",{type:"button","aria-label":`Status: ${e.status}`,onClick:b,className:(0,eR.cn)("shrink-0 rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring/50",y&&"mt-[2.5px]"),children:(0,B.jsx)(aP,{status:e.status})})}),(0,B.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,B.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,B.jsx)("span",{className:(0,eR.cn)("min-w-0 truncate text-[13px]",x?"font-[450] text-muted-foreground line-through decoration-border":v?"font-[450] text-secondary-foreground":"font-medium"),children:e.title}),g&&g.total>0&&(0,B.jsx)(aO,{done:g.done,total:g.total}),f&&(0,B.jsx)("span",{className:"shrink-0 rounded px-[5px] font-mono text-[10px] font-medium text-[oklch(0.6_0.14_152)] bg-[oklch(0.94_0.05_152)] dark:bg-[oklch(0.6_0.14_152/0.18)]",children:"new"})]}),y&&(0,B.jsxs)("div",{className:"mt-px flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground",children:[e.description&&(0,B.jsx)("span",{className:"min-w-0 truncate",children:sN(e.description,240)}),e.description&&e.source_session&&(0,B.jsx)("span",{className:"shrink-0 text-border","aria-hidden":!0,children:"·"}),e.source_session&&(0,B.jsx)("span",{className:"flex min-w-0 max-w-[210px] shrink-0 [&_svg]:size-[11px]",onClick:b,children:(0,B.jsx)(sv,{source:e.source_session,onOpen:u?()=>u(e):void 0})})]})]})]}),p?(0,B.jsxs)("div",{className:"flex items-center gap-2.5 text-muted-foreground/70",children:[null!==e.assigned_branch&&(0,B.jsx)("span",{title:sk(e.assigned_branch),className:"inline-flex",children:(0,B.jsx)(aF,{className:"size-3","aria-label":`Branch ${sk(e.assigned_branch)}`})}),(0,B.jsx)(az,{priority:e.priority})]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(a$,{priority:e.priority,onChange:s=>r(e.id,{priority:s}),children:(0,B.jsxs)("button",{type:"button",onClick:b,className:(0,eR.cn)("-mx-1.5 flex w-fit items-center gap-[7px] rounded-md px-1.5 py-1 text-xs text-secondary-foreground outline-none hover:bg-background hover:shadow-[inset_0_0_0_1px_var(--border)] data-[state=open]:bg-background data-[state=open]:shadow-[inset_0_0_0_1px_var(--border)]",Fm),children:[(0,B.jsx)(az,{priority:e.priority}),s_[e.priority].label]})}),(0,B.jsx)("div",{className:(0,eR.cn)("flex min-w-0",Fp),children:(0,B.jsx)(aY,{current:e.assigned_branch,onAssign:r=>d(e.id,r),worktrees:l,assignedBranches:c,children:(0,B.jsx)("button",{type:"button",onClick:b,className:"flex min-w-0 max-w-full rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ring/50",title:null!==e.assigned_branch?void 0:"Assign a branch",children:null!==e.assigned_branch?(0,B.jsx)(aX,{branch:e.assigned_branch,className:"hover:border-border"}):(0,B.jsx)("span",{className:"text-xs text-muted-foreground/70 hover:text-muted-foreground",children:"—"})})})}),(0,B.jsx)("span",{className:"text-right font-mono text-[11px] text-muted-foreground/70",title:new Date(e.created_at).toLocaleString(),children:sD(e.created_at)}),(0,B.jsxs)("div",{className:"flex justify-end gap-0.5 opacity-0 transition-opacity group-hover:opacity-100 focus-within:opacity-100",onClick:b,children:[a?(0,B.jsx)(Fv,{title:"Unarchive",onClick:()=>i(e.id),children:(0,B.jsx)(Fh,{className:"size-[13px]"})}):(0,B.jsx)(Fv,{title:"Archive",onClick:()=>n(e.id),children:(0,B.jsx)(on,{className:"size-[13px]"})}),(0,B.jsx)(Fv,{title:"Delete",onClick:()=>s(e.id),children:(0,B.jsx)(rb,{className:"size-[13px]"})})]})]})]})}function Fv({title:e,onClick:r,children:s}){return(0,B.jsx)("button",{type:"button",title:e,"aria-label":e,onClick:r,className:"grid size-[26px] place-items-center rounded-md text-muted-foreground outline-none hover:bg-border/60 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50",children:s})}function Fy({pending:e,compact:r}){return(0,B.jsxs)("div",{role:"row","data-pending-task":!0,"aria-busy":!0,className:(0,eR.cn)(Fg,"cursor-default",r?"min-h-[34px] grid-cols-[minmax(0,1fr)_auto]":(0,eR.cn)(Ff,"min-h-[46px] py-1.5")),children:[(0,B.jsxs)("div",{className:(0,eR.cn)("flex min-w-0 gap-[9px]",r?"items-center":"items-start"),children:[(0,B.jsx)(aP,{status:e.status,pending:!0,className:r?void 0:"mt-[2.5px]"}),(0,B.jsxs)("div",{className:"min-w-0 flex-1",children:[null!==e.title?(0,B.jsx)("span",{className:"block truncate text-[13px] font-medium",children:e.title}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(C6,{className:"my-[5px] h-[9px] w-[46%] max-w-64"}),(0,B.jsx)("span",{className:"sr-only",children:"Generating title…"})]}),!r&&(0,B.jsx)("div",{className:"mt-px truncate text-xs text-muted-foreground",children:sN(e.description,1/0)})]})]}),r?(0,B.jsx)(az,{priority:e.priority,className:"opacity-55"}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)("div",{className:(0,eR.cn)("flex items-center gap-[7px] text-xs text-secondary-foreground opacity-55",Fm),children:[(0,B.jsx)(az,{priority:e.priority}),s_[e.priority].label]}),(0,B.jsx)(C6,{className:(0,eR.cn)("h-[9px] w-[90px]",Fp)}),(0,B.jsx)(C6,{className:"h-[9px] w-[26px] justify-self-end"}),(0,B.jsx)("span",{})]})]})}function Fb({rows:e,allTasks:r,sort:s,onSortChange:n,onUpdate:i,onDelete:a,onArchive:o,onUnarchive:l,archivedView:c,worktrees:d,onAssign:u,onOpenSourceSession:h,panelOpen:f,selectedTaskId:p,onSelect:m,onStep:g,pendingTasks:x,flashTaskId:v,keyboardActive:y,assignedBranches:b}){let w=(0,$.useRef)(null),_=e=>{s?.field!==e?n({field:e,dir:"asc"}):"asc"===s.dir?n({field:e,dir:"desc"}):n(null)},S=(0,$.useMemo)(()=>{let e=new Map;for(let s of r){if(!s.parent_id||null!==s.archived_at||"cancelled"===s.status)continue;let r=e.get(s.parent_id)??{done:0,total:0};r.total+=1,"done"===s.status&&(r.done+=1),e.set(s.parent_id,r)}return e},[r]),j=(0,$.useMemo)(()=>{let r=[];for(let s of e){let e=r[r.length-1];s.depth>0&&e?e.kids.push(s):r.push({root:s,kids:[]})}return r},[e]);(0,$.useEffect)(()=>{if(!f||!y)return;let r=r=>{if(!(r.defaultPrevented||r.metaKey||r.ctrlKey||r.altKey||d3(r.target)||uo())){if("Escape"===r.key){r.preventDefault(),m(null);return}null===p||"ArrowDown"!==r.key&&"ArrowUp"!==r.key||0!==e.length&&(r.preventDefault(),g("ArrowDown"===r.key?1:-1))}};return window.addEventListener("keydown",r,!0),()=>window.removeEventListener("keydown",r,!0)},[f,p,m,g,e.length,y]);let k=v??p;(0,$.useEffect)(()=>{if(null===k)return;let e=w.current?.querySelectorAll("[data-task-id]")??[];Array.from(e).find(e=>e.dataset.taskId===k)?.scrollIntoView({block:"nearest"})},[k]);let C=({task:e,depth:r})=>(0,B.jsx)(Fx,{task:e,depth:r,progress:S.get(e.id),onUpdate:i,onDelete:a,onArchive:o,onUnarchive:l,archivedView:c,onClick:e=>m(e.id===p?null:e.id),selected:e.id===p,flash:e.id===v,compact:f,worktrees:d,assignedBranches:b,onAssign:u,onOpenSourceSession:h},e.id);return(0,B.jsxs)("div",{ref:w,role:"grid","aria-label":"Tasks",className:"flex flex-col gap-px px-3 pt-2 pb-4",children:[!f&&(0,B.jsxs)("div",{role:"row",className:(0,eR.cn)("mb-1 grid h-[30px] items-center gap-x-3 border-b border-border/60 px-2 text-[11px] font-medium text-muted-foreground/70",Ff),children:[(0,B.jsx)(Fw,{field:"title",sort:s,onToggle:_,children:"Title"}),(0,B.jsx)(Fw,{field:"priority",sort:s,onToggle:_,className:Fm,children:"Priority"}),(0,B.jsx)("span",{className:Fp,children:"Branch"}),(0,B.jsx)(Fw,{field:"created_at",sort:s,onToggle:_,className:"justify-self-end",children:"Created"}),(0,B.jsx)("span",{})]}),j.map(({root:e,kids:r})=>(0,B.jsxs)("div",{className:"contents",children:[C(e),r.length>0&&(0,B.jsx)("div",{className:"relative flex flex-col gap-px before:absolute before:top-[-2px] before:bottom-3 before:left-[15px] before:w-px before:bg-border",children:r.map(C)})]},e.task.id)),x.map(e=>(0,B.jsx)(Fy,{pending:e,compact:f},e.key)),0===e.length&&0===x.length&&(0,B.jsxs)("div",{className:"flex flex-col items-center gap-1 py-12 text-center",children:[(0,B.jsx)("p",{className:"text-sm font-medium text-foreground/60",children:"No tasks yet"}),(0,B.jsx)("p",{className:"text-xs text-muted-foreground",children:"Create one to get started."})]})]})}function Fw({field:e,sort:r,onToggle:s,className:n,children:i}){let a=r?.field===e,o=a?"asc"===r.dir?Ah:c7:gE;return(0,B.jsxs)("button",{type:"button",onClick:()=>s(e),className:(0,eR.cn)("group/sh inline-flex w-fit items-center gap-[3px] outline-none hover:text-muted-foreground",a&&"text-muted-foreground",n),children:[i,(0,B.jsx)(o,{className:(0,eR.cn)("size-2.5",!a&&"opacity-0 group-hover/sh:opacity-100"),"aria-hidden":!0})]})}let F_=(0,eA.default)("message-square-plus",[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}],["path",{d:"M12 8v6",key:"1ib9pf"}],["path",{d:"M9 11h6",key:"1fldmi"}]]);var sb=sy;let FS=["boxSizing","width","paddingTop","paddingRight","paddingBottom","paddingLeft","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","fontFamily","fontSize","fontWeight","lineHeight","letterSpacing","tabSize","wordBreak","overflowWrap"];function Fj({value:e,label:r,className:s,onOpenFile:n,children:i}){let[a,o]=(0,$.useState)(!1),l=(0,$.useRef)(null),c=(0,$.useRef)(null),d=(r,s)=>{let n=function(e){for(let r=e.parentElement;r;r=r.parentElement){let{overflowY:e}=getComputedStyle(r);if(("auto"===e||"scroll"===e)&&r.scrollHeight>r.clientHeight)return r}return null}(r);c.current={caret:s?function(e,r,s,n){let i=null,a=0;if(document.caretPositionFromPoint){let e=document.caretPositionFromPoint(r,s);i=e?.offsetNode??null,a=e?.offset??0}else if(document.caretRangeFromPoint){let e=document.caretRangeFromPoint(r,s);i=e?.startContainer??null,a=e?.startOffset??0}if(!i||i.nodeType!==Node.TEXT_NODE||!e.contains(i))return null;let o=0,l=document.createTreeWalker(e,NodeFilter.SHOW_TEXT);for(let e=l.nextNode();e;e=l.nextNode()){let r=e.textContent??"",s=r.trim()?n.indexOf(r,o):-1;if(e===i)return -1===s?null:s+a;-1!==s&&(o=s+r.length)}return null}(r,s.x,s.y,e):null,clientY:s?.y??null,scroller:n,scrollTop:n?.scrollTop??0},o(!0)};return((0,$.useLayoutEffect)(()=>{let e=l.current?.querySelector("textarea"),r=c.current;if(c.current=null,!a||!e)return;let s=r?.caret??e.value.length;e.focus({preventScroll:!0}),e.setSelectionRange(s,s),r?.scroller&&(r.scroller.scrollTop=r.scrollTop,null!==r.caret&&null!==r.clientY&&(r.scroller.scrollTop+=function(e,r){let s=getComputedStyle(e),n=document.createElement("div");for(let e of FS)n.style[e]=s[e];Object.assign(n.style,{position:"absolute",top:"0",left:"-9999px",visibility:"hidden",whiteSpace:"pre-wrap",borderStyle:"solid"}),n.textContent=e.value.slice(0,r);let i=document.createElement("span");i.textContent="",n.appendChild(i),document.body.appendChild(n);let a=e.getBoundingClientRect().top-e.scrollTop+i.offsetTop+i.offsetHeight/2;return n.remove(),a}(e,s)-r.clientY))},[a]),!a&&e.trim())?(0,B.jsx)("div",{tabIndex:0,"data-markdown-field":r,title:"Click to edit",onClick:e=>{e.target.closest("a, button")||window.getSelection()?.isCollapsed&&d(e.currentTarget,{x:e.clientX,y:e.clientY})},onKeyDown:e=>{"Enter"===e.key&&e.target===e.currentTarget&&(e.preventDefault(),d(e.currentTarget))},className:`cursor-text outline-none ${s??""}`,children:(0,B.jsx)(Ti,{value:n??null,children:(0,B.jsx)(sb.i,{mode:"static",className:aq,rehypePlugins:Tl,components:Td,children:e})})}):(0,B.jsx)("div",{ref:l,className:"contents",onFocus:()=>o(!0),onBlur:()=>o(!1),children:i})}function Fk({task:e,onUpdate:r,onAssign:s,onArchive:n,onUnarchive:i,onDelete:a,onClose:o,worktrees:l,assignedBranches:c,onOpenSourceSession:d,onStartSession:u,onOpenFile:h,tasks:f,onSelectTask:p,onAddSubtask:m,position:g,onStep:x}){let v=null!==e.archived_at,y=(0,$.useMemo)(()=>new Map(f.map(e=>[e.id,e])),[f]),b=(0,$.useMemo)(()=>{let r=[],s=new Set([e.id]),n=e.parent_id?y.get(e.parent_id):void 0;for(;n&&!s.has(n.id);)r.unshift(n),s.add(n.id),n=n.parent_id?y.get(n.parent_id):void 0;return r},[e,y]),w=(0,$.useMemo)(()=>f.filter(r=>r.parent_id===e.id&&null===r.archived_at),[f,e.id]),_=(0,$.useMemo)(()=>(function(e,r){let s=0,n=0;for(let i of r)i.parent_id===e&&null===i.archived_at&&"cancelled"!==i.status&&(n+=1,"done"===i.status&&(s+=1));return{done:s,total:n}})(e.id,f),[f,e.id]),S=(0,$.useMemo)(()=>(function(e,r){let s=new Set([e]),n=!0;for(;n;)for(let e of(n=!1,r))e.parent_id&&s.has(e.parent_id)&&!s.has(e.id)&&(s.add(e.id),n=!0);return s})(e.id,f),[f,e.id]),j=(0,$.useMemo)(()=>{let e=w.filter(e=>"cancelled"!==e.status),r=e.filter(e=>"done"===e.status).length,s=e.filter(e=>"in_progress"===e.status).length;return e.map((e,n)=>n<r?"done":n<r+s?"doing":"todo")},[w]),[k,C]=(0,$.useState)(!1);return(0,B.jsxs)("div",{className:"flex h-full min-w-0 flex-col bg-card",children:[(0,B.jsxs)("div",{className:"flex h-[42px] shrink-0 items-center gap-0.5 border-b border-border/60 pr-2 pl-3",children:[x&&(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(Fv,{title:"Previous (↑)",onClick:()=>x(-1),children:(0,B.jsx)(lS,{className:"size-3.5"})}),(0,B.jsx)(Fv,{title:"Next (↓)",onClick:()=>x(1),children:(0,B.jsx)(aI,{className:"size-3.5"})})]}),g&&(0,B.jsxs)("span",{className:"mx-1.5 font-mono text-[10.5px] tabular-nums text-muted-foreground/70",children:[g.index+1," / ",g.total]}),(0,B.jsx)("span",{className:"flex-1"}),u&&!v&&(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(FC,{worktrees:l,onPick:r=>u(e,r)}),(0,B.jsx)("span",{className:"mx-1 h-4 w-px bg-border","aria-hidden":!0})]}),!v&&(0,B.jsx)(Fv,{title:"Archive",onClick:()=>n(e.id),children:(0,B.jsx)(on,{className:"size-[13px]"})}),(0,B.jsx)(Fv,{title:"Delete",onClick:()=>a(e.id),children:(0,B.jsx)(rb,{className:"size-[13px]"})}),(0,B.jsx)("span",{className:"mx-1 h-4 w-px bg-border","aria-hidden":!0}),(0,B.jsx)(Fv,{title:"Close (Esc)",onClick:o,children:(0,B.jsx)(ro,{className:"size-3.5"})})]}),v&&(0,B.jsxs)("div",{className:"flex shrink-0 items-center gap-2 border-b border-border/60 bg-secondary py-2 pr-3 pl-3.5 text-xs text-muted-foreground",children:[(0,B.jsx)(on,{className:"size-[13px] shrink-0","aria-hidden":!0}),(0,B.jsxs)("span",{className:"min-w-0 truncate",children:["Archived ",new Date(e.archived_at).toLocaleDateString(void 0,{month:"short",day:"numeric"})," — hidden from the list and the sidebar"]}),(0,B.jsxs)(Z.Button,{variant:"outline",size:"sm",className:"ml-auto h-6 gap-1 px-2 text-[11.5px]",onClick:()=>i(e.id),children:[(0,B.jsx)(Fh,{className:"size-3"}),"Unarchive"]})]}),(0,B.jsxs)("div",{className:(0,eR.cn)("flex min-h-0 flex-1 flex-col overflow-auto [&>*]:shrink-0 px-6 pt-[18px] pb-[22px] edge-scrollbar",v&&"opacity-[.78]"),children:[b.length>0&&(0,B.jsx)("nav",{"aria-label":"Parent tasks",className:"mb-1 -ml-[5px] flex min-w-0 flex-wrap items-center gap-px text-[11.5px] text-muted-foreground/70",children:b.map(e=>(0,B.jsxs)("span",{className:"flex min-w-0 items-center gap-px",children:[(0,B.jsx)("button",{type:"button",className:"max-w-[280px] truncate rounded-[5px] px-[5px] py-0.5 text-muted-foreground hover:bg-muted hover:text-foreground",onClick:()=>p(e.id),children:e.title}),(0,B.jsx)(ab,{className:"size-[11px] shrink-0","aria-hidden":!0})]},e.id))}),(0,B.jsx)(FR,{value:e.title,onCommit:s=>{let n=s.trim();n&&n!==e.title&&r(e.id,{title:n})},singleLine:!0,"aria-label":"Title",className:"mb-3.5 text-lg leading-[1.32] font-semibold tracking-[-0.02em] hover:bg-muted focus:bg-muted/60"}),(0,B.jsxs)(aG,{status:e.status,priority:e.priority,assignedBranch:e.assigned_branch,onStatusChange:s=>r(e.id,{status:s}),onPriorityChange:s=>r(e.id,{priority:s}),onAssign:r=>s(e.id,r),worktrees:l,assignedBranches:c,readOnlyBranch:v,children:[!(v&&!e.parent_id)&&(0,B.jsx)(aJ,{label:"Parent",children:(0,B.jsx)(Ts,{tasks:f,value:e.parent_id??null,onChange:s=>r(e.id,{parent_id:s}),excludeIds:S,field:!0})}),e.source_session&&(0,B.jsx)(aJ,{label:"From session",children:e.source_session.exists?(0,B.jsxs)("button",{type:"button",disabled:!d,onClick:()=>d?.(e),title:e.source_session.title?.trim()||"Untitled session",className:"-ml-2 inline-flex h-[30px] min-w-0 max-w-full items-center gap-2 rounded-md px-2 text-primary hover:bg-muted disabled:text-foreground",children:[(0,B.jsx)(sx,{className:"size-[13px] shrink-0","aria-hidden":!0}),(0,B.jsx)("span",{className:"truncate",children:e.source_session.title?.trim()||"Untitled session"})]}):(0,B.jsx)("span",{className:"inline-flex h-[30px] items-center italic text-muted-foreground",children:"Source session deleted"})})]}),(0,B.jsxs)(FN,{title:"Description",className:"flex flex-[1_0_auto] flex-col",hint:!k&&e.description?.trim()?"Click to edit · Markdown":void 0,children:[(0,B.jsx)(Fj,{value:e.description??"",label:"Description",onOpenFile:h?(r,s)=>h(e.source_session?.branch??null,r,s):void 0,className:`-mx-1.5 flex-1 rounded-md px-1.5 py-1 text-secondary-foreground hover:bg-secondary focus-visible:bg-muted/40 ${aH}`,children:(0,B.jsx)(FR,{value:e.description??"",onCommit:s=>{let n=s.trim()?s:null;n!==e.description&&r(e.id,{description:n})},onEditingChange:C,placeholder:"Add a description…","aria-label":"Description",className:`${aU} focus:border focus:border-primary focus:bg-card focus:px-3 focus:py-2.5 focus:font-mono focus:text-xs focus:leading-[1.65] focus:shadow-[0_0_0_3px_var(--accent)]`})}),k&&(0,B.jsxs)("div",{className:"mt-2 flex items-center gap-2.5 text-[11px] text-muted-foreground/70",children:[(0,B.jsx)(FD,{keys:["⌘","↵"],children:"save"}),(0,B.jsx)(FD,{keys:["Esc"],children:"cancel"}),(0,B.jsx)("span",{className:"flex-1"}),(0,B.jsx)("span",{children:"Saves on blur"})]})]}),(0,B.jsxs)(FN,{title:"Sub-tasks","aria-label":"Sub-tasks",compact:!0,hint:v&&0===w.length?"None":void 0,extra:_.total>0&&(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)("span",{className:"ml-0.5 flex gap-[3px]","aria-hidden":!0,children:j.map((e,r)=>(0,B.jsx)("i",{className:(0,eR.cn)("h-1 w-[18px] rounded-sm","done"===e?"bg-[oklch(0.6_0.14_152)]":"doing"===e?"bg-[oklch(0.58_0.16_245)]":"bg-border")},r))}),(0,B.jsxs)("span",{className:"font-mono text-[10.5px] font-normal tabular-nums text-muted-foreground/70",children:[_.done,"/",_.total]})]}),children:[w.length>0&&(0,B.jsx)("ul",{className:"-mx-2 flex flex-col",children:w.map(e=>{let r="done"===e.status||"cancelled"===e.status;return(0,B.jsx)("li",{children:(0,B.jsxs)("button",{type:"button",className:"flex h-7 w-full min-w-0 items-center gap-[9px] rounded-md px-2 text-left hover:bg-muted",onClick:()=>p(e.id),children:[(0,B.jsx)(aP,{status:e.status}),(0,B.jsx)("span",{className:(0,eR.cn)("min-w-0 flex-1 truncate text-[12.5px] font-[450]",r&&"text-muted-foreground line-through decoration-border"),children:e.title}),(0,B.jsx)(az,{priority:e.priority})]})},e.id)})}),!v&&(0,B.jsxs)("button",{type:"button",className:"-mx-2 flex h-7 w-[calc(100%+1rem)] items-center gap-[9px] rounded-md px-2 text-[12.5px] text-muted-foreground hover:bg-muted hover:text-foreground",onClick:()=>m(e.id),children:[(0,B.jsx)("span",{className:"grid size-3.5 place-items-center rounded-full border-[1.5px] border-dashed border-border text-muted-foreground/70",children:(0,B.jsx)(eM,{className:"size-2",strokeWidth:3})}),"Add sub-task"]})]})]}),(0,B.jsxs)("div",{className:"flex h-9 shrink-0 items-center gap-1.5 border-t border-border/60 bg-secondary px-4 text-[11px] text-muted-foreground",children:[(0,B.jsxs)("span",{title:new Date(e.created_at).toLocaleString(),children:["Created ",function(e,r=new Date){let s=new Date(e),n=s.toLocaleDateString(void 0,{month:"short",day:"numeric",...s.getFullYear()!==r.getFullYear()?{year:"numeric"}:{}}),i=s.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1});return`${n}, ${i}`}(e.created_at)]}),(0,B.jsx)("span",{className:"text-border","aria-hidden":!0,children:"·"}),(0,B.jsxs)("span",{title:new Date(e.updated_at).toLocaleString(),children:["Updated ",function(e,r=Date.now()){let s=sD(e,r);return"now"===s?"just now":`${s} ago`}(e.updated_at)]}),(0,B.jsx)("span",{className:"flex-1"}),g&&(0,B.jsx)(FD,{keys:["↑","↓"],children:"switch"}),(0,B.jsx)(FD,{keys:["Esc"],className:"ml-2",children:"close"})]})]})}function FC({worktrees:e,onPick:r}){return(0,B.jsxs)(a_,{children:[(0,B.jsx)(aS,{asChild:!0,children:(0,B.jsxs)("button",{type:"button",className:"inline-flex h-[26px] items-center gap-1.5 rounded-md px-2 text-[12px] font-medium text-muted-foreground outline-none hover:bg-border/60 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50 data-[state=open]:bg-border/60 data-[state=open]:text-foreground",children:[(0,B.jsx)(F_,{className:"size-[13px]","aria-hidden":!0}),"Start session",(0,B.jsx)(aI,{className:"size-3 text-muted-foreground/70","aria-hidden":!0})]})}),(0,B.jsxs)(aj,{align:"end",className:"max-h-72 w-(--radix-dropdown-menu-trigger-width) min-w-0 overflow-y-auto",children:[(0,B.jsx)(aD,{className:"text-[11px] font-normal text-muted-foreground",children:"Select workspace"}),(0,B.jsx)(aR,{}),e.map(e=>(0,B.jsxs)(ak,{onClick:()=>r(e.branch),title:e.branch??"main",className:"gap-2 font-mono text-[12px]",children:[(0,B.jsx)(aF,{className:"size-3 shrink-0 text-muted-foreground"}),(0,B.jsx)("span",{className:"min-w-0 truncate",children:e.branch??"main"})]},e.branch??"")),0===e.length&&(0,B.jsx)("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"No workspaces"})]})]})}function FN({title:e,hint:r,extra:s,compact:n,className:i,children:a,...o}){return(0,B.jsxs)("section",{className:(0,eR.cn)("mt-[18px] border-t border-border/60",n?"pt-3":"pt-3.5",i),...o,children:[(0,B.jsxs)("div",{className:(0,eR.cn)("flex h-5 items-center gap-2 text-[11.5px] font-medium text-muted-foreground",n?"mb-1":"mb-2"),children:[e,s,r&&(0,B.jsx)("span",{className:"ml-auto text-[11px] font-normal text-muted-foreground/70",children:r})]}),a]})}function FE({children:e,className:r}){return(0,B.jsx)("kbd",{className:(0,eR.cn)("inline-grid h-[17px] min-w-[17px] place-items-center rounded border border-b-[1.5px] border-border bg-card px-1 font-mono text-[10px] leading-none text-secondary-foreground",r),children:e})}function FD({keys:e,className:r,children:s}){return(0,B.jsxs)("span",{className:(0,eR.cn)("inline-flex items-center gap-1",r),children:[e.map(e=>(0,B.jsx)(FE,{children:e},e)),s]})}function FR({value:e,onCommit:r,singleLine:s,onEditingChange:n,className:i,...a}){let[o,l]=(0,$.useState)(null),c=(0,$.useRef)(!1);return(0,B.jsx)("textarea",{rows:1,value:o??e,onFocus:()=>{l(e),n?.(!0)},onChange:e=>l(s?e.target.value.replace(/\n/g," "):e.target.value),onBlur:()=>{null===o||c.current||r(o),c.current=!1,l(null),n?.(!1)},onKeyDown:e=>{if(!e.nativeEvent.isComposing&&229!==e.keyCode){if("Escape"===e.key){e.preventDefault(),c.current=!0,e.currentTarget.blur();return}"Enter"===e.key&&(s||e.metaKey||e.ctrlKey)&&(e.preventDefault(),e.currentTarget.blur())}},className:`${aW} ${i??""}`,...a})}let FT={title:"",description:"",status:"todo",priority:"medium",assigned_branch:null,parent_id:null},FA=e=>!e.title.trim()&&!e.description.trim(),FM=e=>e.nativeEvent.isComposing||229===e.keyCode;function FI({draft:e,onChange:r,onCreate:s,onDiscard:n,onClose:i,createMore:a,onCreateMoreChange:o,error:l,focusNonce:c,worktrees:d,assignedBranches:u,tasks:h}){let f=(0,$.useRef)(null),p=(0,$.useRef)(null),m=e.description.trim().length>0;return(0,$.useEffect)(()=>{f.current?.focus()},[c]),(0,B.jsxs)("div",{className:"flex h-full flex-col bg-card",onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&!FM(e)&&(e.preventDefault(),m&&s())},children:[(0,B.jsxs)("div",{className:"flex h-[42px] shrink-0 items-center justify-between border-b border-border/60 pr-2 pl-6",children:[(0,B.jsxs)("span",{className:"text-[11px] font-medium uppercase tracking-wide text-muted-foreground",children:["New task ",(0,B.jsx)("span",{className:"normal-case tracking-normal text-muted-foreground/70",children:"· Draft"})]}),(0,B.jsx)(Fv,{title:"Close (Esc) — keeps the draft",onClick:i,children:(0,B.jsx)(ro,{className:"size-3.5"})})]}),(0,B.jsxs)("div",{className:"flex-1 overflow-auto px-6 pt-[18px] pb-6 edge-scrollbar",children:[(0,B.jsx)("textarea",{ref:f,rows:1,value:e.title,onChange:e=>r({title:e.target.value.replace(/\n/g," ")}),onKeyDown:e=>{"Enter"!==e.key||e.metaKey||e.ctrlKey||FM(e)||(e.preventDefault(),p.current?.focus())},placeholder:"Untitled","aria-label":"Title",className:`${aW} text-lg leading-[1.32] font-semibold tracking-[-0.02em]`}),(0,B.jsx)("p",{className:"mt-0.5 mb-3 min-h-4 text-[11px] text-muted-foreground/70",children:!e.title.trim()&&"Leave empty to generate a title from the description."}),(0,B.jsx)(aG,{status:e.status,priority:e.priority,assignedBranch:e.assigned_branch,onStatusChange:e=>r({status:e}),onPriorityChange:e=>r({priority:e}),onAssign:e=>r({assigned_branch:e}),worktrees:d,assignedBranches:u,children:(0,B.jsx)(aJ,{label:"Parent",children:(0,B.jsx)(Ts,{tasks:h,value:e.parent_id,onChange:e=>r({parent_id:e}),field:!0})})}),(0,B.jsx)("div",{className:"mt-[18px] border-t border-border/60 pt-3.5",children:(0,B.jsx)("textarea",{ref:p,rows:1,value:e.description,onChange:e=>r({description:e.target.value}),placeholder:"Describe the task…","aria-label":"Description",className:`${aW} ${aU}`})})]}),l&&(0,B.jsxs)("div",{role:"alert",className:"mx-6 mb-3 flex shrink-0 items-center gap-2 rounded-md bg-destructive/10 px-3 py-2 text-xs text-destructive",children:[(0,B.jsx)(a5,{className:"size-3.5 shrink-0"}),l]}),(0,B.jsxs)("div",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-border/60 bg-secondary px-6 py-2.5",children:[(0,B.jsxs)("label",{className:"mr-auto flex cursor-pointer items-center gap-2 text-xs text-muted-foreground",children:[(0,B.jsx)(eT,{checked:a,onCheckedChange:e=>o(!0===e)}),"Create more"]}),(0,B.jsx)(Z.Button,{variant:"ghost",size:"sm",onClick:n,disabled:FA(e),children:"Discard"}),(0,B.jsxs)(Z.Button,{size:"sm",onClick:s,disabled:!m,children:["Create",(0,B.jsx)("kbd",{className:"ml-1.5 rounded bg-background/15 px-1 font-sans text-[10px]",children:"⌘↵"})]})]})]})}let FF="vibedeckx:tasks:create-more",FP=[{value:"all",label:"All"},{value:"todo",label:"Todo"},{value:"in_progress",label:"Doing"},{value:"done",label:"Done"},{value:"cancelled",label:"Cancelled"},{value:"archived",label:"Archived"}];function FL({active:e=!0,projectId:r,tasks:s,loading:n,worktrees:i,onCreateTask:a,onUpdateTask:o,onDeleteTask:l,onArchiveTask:c,onUnarchiveTask:d,onOpenSourceSession:u,onStartSession:h,onOpenFile:f,openRequest:p,onSelectedTaskChange:m}){let{settings:g}=(0,dh.useConversationSettings)(),[x,v]=(0,$.useState)("all"),[y,b]=(0,$.useState)(null),[w,_]=(0,$.useState)(null),S=w?.projectId===r?w.panel:null,j=S?.kind==="task"?S.taskId:null,k=j?s.find(e=>e.id===j)??null:null,C=S?.kind==="draft",N=(0,$.useCallback)(e=>_(e?{projectId:r,panel:{kind:"task",taskId:e}}:null),[r]),[E,D]=(0,$.useState)(null),R=E?.projectId===r?E.draft:FT,[T,A]=(0,$.useState)(null),[M,I]=(0,$.useState)(0),[F,P]=(0,$.useState)(()=>"1"===window.localStorage.getItem(FF)),[L,z]=(0,$.useState)([]),[O,W]=(0,$.useState)(null),H=O?.projectId===r?O.taskId:null,U=(0,$.useRef)(0);(0,$.useEffect)(()=>{if(!O)return;let e=setTimeout(()=>W(null),1600);return()=>clearTimeout(e)},[O]),(0,$.useEffect)(()=>{if(!p)return;if("draft"===p.kind){_({projectId:r,panel:{kind:"draft"}}),I(e=>e+1);return}_({projectId:r,panel:{kind:"task",taskId:p.taskId}});let{status:e}=p;v(r=>"all"===r||r===e?r:"all")},[p]);let q=k?.id??null;(0,$.useEffect)(()=>{m?.(q)},[q,m]);let K=async()=>{let e=R.description.trim();if(!e)return;let s=`pending-${++U.current}`,n=R.title.trim()||null;z(i=>[...i,{key:s,projectId:r,title:n,description:e,status:R.status,priority:R.priority}]),A(null),D(F&&R.parent_id?{projectId:r,draft:{...FT,parent_id:R.parent_id}}:null),F?I(e=>e+1):_(null);let i=await a({title:n??void 0,description:e,status:R.status,priority:R.priority,assigned_branch:R.assigned_branch,parent_id:R.parent_id});(z(e=>e.filter(e=>e.key!==s)),i)?W({projectId:r,taskId:i.id}):(D(e=>e&&e.projectId===r&&!FA(e.draft)?e:{projectId:r,draft:R}),_(e=>e??{projectId:r,panel:{kind:"draft"}}),A("Couldn't create the task. Your draft is restored, try again."))},V=(e,r)=>{o(e,{assigned_branch:r})},X=(0,$.useMemo)(()=>s.filter(e=>null===e.archived_at),[s]),Y=(0,$.useMemo)(()=>s.filter(e=>null!==e.archived_at),[s]),G=(0,$.useMemo)(()=>{let e={all:X.length,todo:0,in_progress:0,done:0,cancelled:0,archived:Y.length};for(let r of X)e[r.status]++;return e},[X,Y]),J=(0,$.useMemo)(()=>"archived"===x?Y:"all"===x?X:X.filter(e=>e.status===x),[X,Y,x]),Q="archived"===x,ee=(0,$.useMemo)(()=>(function(e){let r=new Set(e.map(e=>e.id)),s=new Map,n=[];for(let i of e)if(i.parent_id&&i.parent_id!==i.id&&r.has(i.parent_id)){let e=s.get(i.parent_id)??[];e.push(i),s.set(i.parent_id,e)}else n.push(i);let i=[],a=new Set,o=(e,r)=>{if(!a.has(e.id))for(let n of(a.add(e.id),i.push({task:e,depth:r}),s.get(e.id)??[]))o(n,r+1)};for(let e of n)o(e,0);for(let r of e)o(r,0);return i})(function(e,r){if(!r)return e;let s="asc"===r.dir?1:-1;return[...e].sort((e,n)=>{switch(r.field){case"title":return s*e.title.localeCompare(n.title);case"priority":return s*(sE[e.priority]-sE[n.priority]);case"created_at":return s*(new Date(e.created_at).getTime()-new Date(n.created_at).getTime())}})}(J,y)),[J,y]),et=k?ee.findIndex(e=>e.task.id===k.id):-1,er=(0,$.useCallback)(e=>{if(0===ee.length)return;let r=-1===et?0:Math.min(Math.max(et+e,0),ee.length-1);N(ee[r].task.id)},[ee,et,N]),es=(0,$.useMemo)(()=>L.filter(e=>e.projectId===r&&("all"===x||x===e.status)),[L,r,x]),en=(0,$.useMemo)(()=>C?{kind:"draft",draft:R}:k?{kind:"task",task:k}:null,[C,R,k]),[ei,ea]=(0,$.useState)(null);en&&en!==ei?ea(en):!en&&ei&&("function"!=typeof window.matchMedia||window.matchMedia("(prefers-reduced-motion: reduce)").matches)&&ea(null);let eo=!en&&null!==ei,el=en??ei;(0,$.useEffect)(()=>{if(!eo)return;let e=setTimeout(()=>ea(null),400);return()=>clearTimeout(e)},[eo]);let ec=(0,$.useMemo)(()=>new Set(s.filter(e=>null!==e.assigned_branch).map(e=>e.assigned_branch)),[s]);return r?(0,B.jsxs)("div",{className:"flex flex-col h-full",children:[(0,B.jsx)(ug,{title:"Tasks",count:X.length,actions:(0,B.jsxs)(Z.Button,{size:"sm",onClick:()=>{_({projectId:r,panel:{kind:"draft"}}),I(e=>e+1)},className:"shadow-sm",children:[(0,B.jsx)(eM,{className:"h-3.5 w-3.5 mr-1.5"}),"New Task"]})}),(0,B.jsx)(ux,{children:FP.map(e=>(0,B.jsx)(uv,{active:x===e.value,count:G[e.value],onClick:()=>v(e.value),children:e.label},e.value))}),(0,B.jsx)("div",{className:"flex-1 min-h-0",children:(0,B.jsxs)(hD,{direction:"horizontal",autoSaveId:"task-detail-panels",children:[(0,B.jsx)(uT,{id:"task-list",order:1,minSize:30,children:(0,B.jsx)("div",{className:"@container h-full overflow-y-auto overflow-x-hidden edge-scrollbar",children:n?(0,B.jsx)("div",{className:"flex items-center justify-center py-12 text-muted-foreground text-sm",children:"Loading tasks..."}):(0,B.jsx)(Fb,{rows:ee,allTasks:s,sort:y,onSortChange:b,onStep:er,onUpdate:o,onDelete:l,onArchive:c,onUnarchive:d,archivedView:Q,worktrees:i,onAssign:V,onOpenSourceSession:u,panelOpen:null!==k||C,selectedTaskId:k?.id??null,keyboardActive:e,onSelect:N,pendingTasks:es,flashTaskId:H,assignedBranches:ec})})}),el&&(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(hR,{}),(0,B.jsx)(uT,{id:"task-detail",order:2,defaultSize:40,minSize:25,className:eo?"motion-safe:animate-side-panel-out":"motion-safe:animate-side-panel-in",onAnimationEnd:e=>{e.target===e.currentTarget&&eo&&ea(null)},children:(0,B.jsx)("div",{className:"h-full",inert:eo,style:{"--task-body-font-size":`${g.tasksFontSize}px`},children:"draft"===el.kind?(0,B.jsx)(FI,{draft:el.draft,onChange:e=>D({projectId:r,draft:{...R,...e}}),onCreate:K,onDiscard:()=>{D(null),A(null),_(null)},onClose:()=>N(null),createMore:F,onCreateMoreChange:e=>{P(e),window.localStorage.setItem(FF,e?"1":"0")},error:T,focusNonce:M,worktrees:i,assignedBranches:ec,tasks:s}):(0,B.jsx)(Fk,{task:el.task,onUpdate:o,onAssign:V,onArchive:c,onUnarchive:d,onDelete:l,onClose:()=>N(null),worktrees:i,assignedBranches:ec,onOpenSourceSession:u,onStartSession:h,onOpenFile:f,tasks:s,onSelectTask:N,onAddSubtask:e=>{D({projectId:r,draft:{...R,parent_id:e}}),A(null),_({projectId:r,panel:{kind:"draft"}}),I(e=>e+1)},position:-1===et||el.task.id!==k?.id?null:{index:et,total:ee.length},onStep:er},el.task.id)})})]})]})})]}):(0,B.jsx)("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:(0,B.jsxs)("div",{className:"text-center",children:[(0,B.jsx)("div",{className:"mx-auto w-10 h-10 rounded-xl bg-muted flex items-center justify-center mb-3",children:(0,B.jsx)(eM,{className:"h-5 w-5 text-muted-foreground/50"})}),(0,B.jsx)("p",{className:"text-sm",children:"Select a project to view tasks."})]})})}var Fz=e.i(115796);let FO=[5e3,1e4,2e4,4e4];function FB({open:e,onOpenChange:r,onNavigateProject:s,onNavigateWorkspace:n,onNavigateSession:i}){let[a,o]=(0,$.useState)(""),[l,c]=(0,$.useState)(null),[d,u]=(0,$.useState)(!1),h=(0,$.useRef)(null),f=(0,$.useRef)(null),p=(0,$.useRef)("");(0,$.useLayoutEffect)(()=>{p.current=a},[a]),(0,a8.useGlobalEventStream)(e=>{if("session:title"!==e.type||"string"!=typeof e.sessionId)return;let r="string"==typeof e.title?e.title.trim():"";(0,Fz.updateCachedSessionTitle)(e.sessionId,r||null)});let[m,g]=(0,$.useState)(e);e!==m&&(g(e),e&&(o(""),c((0,Fz.getCachedEmptyResults)()),u(!1)));let x=(0,$.useCallback)(async e=>{h.current?.abort();let r=new AbortController;h.current=r;let s=""===e?(0,Fz.beginEmptyQuerySearch)():null;for(let n=0;;n++){let i=Date.now();try{let i=await (0,rD.searchAll)(e,{signal:AbortSignal.any([r.signal,AbortSignal.timeout(FO[n])])});r.signal.aborted||(null!==s&&(0,Fz.commitEmptyQueryResults)(s,i),c(i),u(!1));return}catch{if(r.signal.aborted)return;if(n===FO.length-1)return void u(!0);let e=1e3*2**n-(Date.now()-i);if(e>0&&await function(e,r){return new Promise(s=>{let n=setTimeout(s,e);r.addEventListener("abort",()=>{clearTimeout(n),s()},{once:!0})})}(e,r.signal),r.signal.aborted)return}}},[]),v=(0,$.useRef)(!1);(0,$.useEffect)(()=>{let r=e&&!v.current;if(v.current=e,e)return f.current&&clearTimeout(f.current),f.current=setTimeout(()=>void x(a),150*!r),()=>{f.current&&clearTimeout(f.current)}},[a,e,x]),(0,$.useEffect)(()=>{if(!e)return;let r=!1;return(0,rD.refreshSearchCache)().then(()=>{r||x(p.current)}).catch(()=>{}),()=>{r=!0,h.current?.abort()}},[e,x]);let y=l?a.trim()?{sessions:l.sessions,favorites:l.favorites}:(0,Fz.overlayRecents)(l):null,b=null===l,w=!!y&&0===l.projects.length&&0===l.workspaces.length&&0===y.sessions.length&&0===y.favorites.length,_=l?.cacheState==="cold",S=e=>(0,B.jsxs)(me,{value:`session-${e.sessionId}`,onSelect:()=>i(e),children:[(0,B.jsx)(sx,{}),(0,B.jsx)("span",{className:"truncate",children:e.title??"Untitled session"}),e.favoritedAt&&(0,B.jsx)(oz,{className:"h-3.5 w-3.5 shrink-0 fill-current text-amber-500"}),(0,B.jsxs)("span",{className:"ml-auto shrink-0 text-xs text-muted-foreground",children:[e.projectName," · ",e.branch??"main"," · ",function(e){if(!e)return"";let r=Date.now()-e;return r<6e4?"just now":r<36e5?`${Math.floor(r/6e4)}m ago`:r<864e5?`${Math.floor(r/36e5)}h ago`:`${Math.floor(r/864e5)}d ago`}(e.lastActiveAt)]})]},e.sessionId);return(0,B.jsxs)(p4,{open:e,onOpenChange:r,title:"Quick Switcher",description:"Search projects, workspaces, and sessions",shouldFilter:!1,instantClose:!0,className:"top-[max(1rem,calc(50%_-_175px))] translate-y-0",children:[(0,B.jsx)(p6,{placeholder:"Search projects, workspaces, sessions…",value:a,onValueChange:o}),(0,B.jsxs)(p7,{children:[d&&(0,B.jsxs)("div",{className:"flex items-center justify-between gap-2 px-4 py-3 text-sm text-destructive",children:[(0,B.jsx)("span",{children:"Search failed."}),(0,B.jsx)(Z.Button,{variant:"link",size:"sm",className:"h-auto p-0 text-destructive",onClick:()=>void x(p.current),children:"Retry"})]}),!d&&b&&(0,B.jsxs)("div",{className:"flex items-center justify-center gap-2 py-6 text-sm text-muted-foreground",children:[(0,B.jsx)(a7,{className:"h-4 w-4 animate-spin"}),"Searching…"]}),!d&&!b&&w&&_&&(0,B.jsxs)("div",{className:"flex items-center justify-center gap-2 py-6 text-sm text-muted-foreground",children:[(0,B.jsx)(a7,{className:"h-4 w-4 animate-spin"}),"Syncing history…"]}),!d&&!b&&w&&!_&&(0,B.jsx)(p8,{children:"No results found."}),l&&l.projects.length>0&&(0,B.jsx)(p9,{heading:"Projects",children:l.projects.map(e=>(0,B.jsxs)(me,{value:`project-${e.id}`,onSelect:()=>s(e.id),children:[(0,B.jsx)(dq,{name:e.name,size:"md"}),(0,B.jsx)("span",{children:e.name}),e.path&&(0,B.jsx)("span",{className:"truncate text-xs text-muted-foreground",children:e.path})]},e.id))}),l&&l.workspaces.length>0&&(0,B.jsx)(p9,{heading:"Workspaces",children:l.workspaces.map(e=>(0,B.jsxs)(me,{value:`ws-${e.projectId}-${e.branch??""}`,onSelect:()=>n(e),children:[(0,B.jsx)(aF,{}),(0,B.jsx)("span",{children:e.branch??"main"}),(0,B.jsx)("span",{className:"text-xs text-muted-foreground",children:e.projectName})]},`${e.projectId}-${e.branch??""}`))}),y&&y.sessions.length>0&&(0,B.jsx)(p9,{heading:a.trim()?"Sessions":"Recent",children:y.sessions.map(S)}),y&&y.favorites.length>0&&(0,B.jsx)(p9,{heading:"Favorites",children:y.favorites.map(S)})]})]})}let F$={session_result_ready:"/sounds/sound1.mp3",review_ready:"/sounds/sound2.mp3",session_failed:"/sounds/failure.mp3",workflow_failed:"/sounds/failure.mp3",loop_done:"/sounds/sound1.mp3",commander_stalled:"/sounds/sound2.mp3",cross_remote_token_expired:"/sounds/sound2.mp3"},FW=[2e3,5e3,15e3];function FH(e,r){let s=[...e.filter(e=>e.id!==r.id),r];return s.sort((e,r)=>r.created_at-e.created_at||(e.id<r.id?1:-1)),s}let FU=new Set(["session_result_ready","session_failed"]);function Fq(e){return FU.has(e.kind)&&e.session_id?`${e.kind}:${e.session_id}`:e.id}function FK(e){let r=new Map;for(let s of e){let e=null===s.read_at,n=r.get(Fq(s));n?(n.ids.push(s.id),n.count+=1,e&&(n.unreadCount+=1,n.unread=!0)):r.set(Fq(s),{latest:s,ids:[s.id],count:1,unreadCount:+!!e,unread:e})}return[...r.values()]}let FV=new Map,FX=new Set,FY=new Set(["session_result_ready","session_failed"]);function FG(e,r){return FY.has(e.kind)?null!==r.turnEndAt&&r.turnEndAt>=e.created_at:null!==r.resultAt&&r.resultAt>=e.created_at}function FJ(e){let r=FV.get(e);r||((r=new Audio(e)).preload="auto",FV.set(e,r)),r.currentTime=0,r.play().catch(()=>{})}let FZ=(0,eA.default)("bell",[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]]);async function FQ(e,r){let s=e.session_id;if("commander_stalled"===e.kind&&(s=null),e.workflow_run_id&&("workflow_failed"===e.kind||"loop_done"===e.kind)){let r=await rD.api.getWorkflowRun(e.workflow_run_id).catch(()=>null);r?.kind==="repeat"&&(s=r.source_session_id)}r(e.project_id,e.branch,s)}let F0={session_result_ready:{label:"Session result is ready",dot:"bg-lime-400"},review_ready:{label:"Review feedback is ready",dot:"bg-emerald-500"},session_failed:{label:"Session failed",dot:"bg-destructive"},workflow_failed:{label:"Workflow needs attention",dot:"bg-destructive"},loop_done:{label:"Loop finished — nothing left to process",dot:"bg-emerald-500"},commander_stalled:{label:"Commander stalled — the task needs you to continue it",dot:"bg-amber-500"},cross_remote_token_expired:{label:"Cross-remote expired — stop & send a message to renew",dot:"bg-amber-500"}};function F1({notifications:e,unreadCount:r,projects:s,onNavigate:n,markRead:i,markAllRead:a,remove:o,clear:l}){let[c,d]=(0,$.useState)(!1);return(0,$.useEffect)(()=>{let e=e=>{"j"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),d(e=>!e))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[]),(0,B.jsxs)(a_,{open:c,onOpenChange:d,children:[(0,B.jsx)(aS,{asChild:!0,children:(0,B.jsxs)(Z.Button,{variant:"ghost",size:"icon-sm",className:"relative",title:"Notifications (⌘J)","aria-label":r>0?`${r} unread notifications`:"Notifications",children:[(0,B.jsx)(FZ,{className:"h-4 w-4"}),r>0&&(0,B.jsx)("span",{className:"absolute -top-0.5 -right-0.5 flex h-4 min-w-4 items-center justify-center rounded-full bg-primary px-1 text-[9px] font-semibold leading-none text-primary-foreground",children:r>9?"9+":r})]})}),(0,B.jsxs)(aj,{align:"end",className:"w-80 p-0",children:[(0,B.jsxs)("div",{className:"flex items-center justify-between px-3 py-2",children:[(0,B.jsx)("span",{className:"text-[12.5px] font-semibold text-foreground",children:"Notifications"}),e.length>0&&(0,B.jsxs)("div",{className:"flex items-center gap-1",children:[(0,B.jsxs)("button",{onClick:a,disabled:0===r,className:"flex items-center gap-1 rounded px-1.5 py-0.5 text-[11px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:pointer-events-none disabled:opacity-40",title:"Mark all read",children:[(0,B.jsx)(dK,{className:"h-3 w-3"}),"Mark all read"]}),(0,B.jsx)("button",{onClick:l,className:"rounded px-1.5 py-0.5 text-[11px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",title:"Dismiss all (marks them read)",children:"Clear"})]})]}),(0,B.jsx)("div",{className:"max-h-[60vh] overflow-y-auto border-t border-border",children:0===e.length?(0,B.jsx)("div",{className:"px-3 py-8 text-center text-[12px] text-muted-foreground/70",children:"Nothing needs your attention."}):FK(e).map(e=>{let r,a=e.latest,l=F0[a.kind],c=e.unread;return(0,B.jsxs)(ak,{onSelect:()=>{for(let r of e.ids)i(r);FQ(a,n)},className:(0,eR.cn)("group flex flex-col items-start gap-0.5 rounded-none px-3 py-2",c&&"bg-primary/[0.08]"),children:[(0,B.jsxs)("div",{className:"flex w-full items-center gap-2",children:[(0,B.jsx)("span",{className:(0,eR.cn)("h-[7px] w-[7px] shrink-0 rounded-full",l?.dot)}),(0,B.jsx)("span",{className:(0,eR.cn)("min-w-0 flex-1 truncate text-[12.5px]",c?"font-medium text-foreground":"text-foreground/70"),children:a.body??(r=a.project_id,s.find(e=>e.id===r)?.name??"Unknown project")}),e.unreadCount>1&&(0,B.jsxs)("span",{className:"shrink-0 rounded-full bg-muted px-1.5 text-[10px] font-medium leading-4 text-muted-foreground",title:`${e.unreadCount} new notifications, showing the latest`,children:["×",e.unreadCount]}),(0,B.jsx)("span",{className:"shrink-0 text-[10.5px] text-muted-foreground/70",children:function(e){let r=Math.max(0,Math.round((Date.now()-e)/1e3));if(r<60)return"just now";let s=Math.round(r/60);if(s<60)return`${s}m ago`;let n=Math.round(s/60);if(n<24)return`${n}h ago`;let i=Math.round(n/24);return`${i}d ago`}(a.created_at)}),(0,B.jsx)("button",{onClick:r=>{for(let s of(r.stopPropagation(),e.ids))o(s)},className:"shrink-0 rounded p-0.5 text-muted-foreground/60 opacity-0 transition-all hover:bg-muted hover:text-foreground group-hover:opacity-100",title:"Dismiss (marks it read)",children:(0,B.jsx)(ro,{className:"h-3 w-3"})})]}),(0,B.jsxs)("div",{className:"flex w-full items-center gap-1.5 pl-[15px] text-[11px] text-muted-foreground",children:[(0,B.jsx)("span",{className:"font-mono truncate",children:a.branch??"main"}),(0,B.jsx)("span",{className:"text-muted-foreground/50",children:"·"}),(0,B.jsx)("span",{className:"shrink-0",children:l?.label??a.title})]})]},a.id)})})]})]})}let F2=(0,eA.default)("keyboard",[["path",{d:"M10 8h.01",key:"1r9ogq"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M14 8h.01",key:"1primd"}],["path",{d:"M16 12h.01",key:"1l6xoz"}],["path",{d:"M18 8h.01",key:"emo2bl"}],["path",{d:"M6 8h.01",key:"x9i8wu"}],["path",{d:"M7 16h10",key:"wp8him"}],["path",{d:"M8 12h.01",key:"czm47f"}],["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}]]),F5=(e,r)=>e?`⌘${r}`:`Ctrl+${r}`,F3=()=>()=>{};function F4(){let[e,r]=(0,$.useState)(!1),s=(0,$.useSyncExternalStore)(F3,U,()=>!1);return(0,$.useEffect)(()=>{let e=e=>{let s="/"===e.key&&(e.metaKey||e.ctrlKey)&&!e.shiftKey&&!e.altKey,n="?"===e.key&&!e.metaKey&&!e.ctrlKey&&!e.altKey&&!d3(e.target);(s||n)&&(e.preventDefault(),r(e=>!e))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[]),(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(Z.Button,{variant:"ghost",size:"icon-sm","aria-label":"Keyboard shortcuts",title:"Keyboard shortcuts (?)",onClick:()=>r(!0),children:(0,B.jsx)(F2,{className:"h-4 w-4"})}),(0,B.jsx)(rl,{open:e,onOpenChange:r,children:(0,B.jsxs)(rf,{className:"sm:max-w-xl",children:[(0,B.jsx)(rp,{children:(0,B.jsx)(rg,{children:"Keyboard shortcuts"})}),(0,B.jsx)("div",{className:"grid gap-x-8 gap-y-5 sm:grid-cols-2",children:[{title:"Global",entries:[{hints:[F5(s,"K")],description:"Quick switcher"},{hints:[F5(s,"J")],description:"Notifications"},{hints:[F5(s,"B")],description:"Toggle sidebar"},{hints:[s?`⌘⇧O`:"Ctrl+Shift+O"],description:"New agent conversation"},{hints:[J(s,V)],description:"Show / hide Main Chat"},{hints:[J(s,q)],description:"Start review of this session"},{hints:[J(s,K)],description:"Read aloud the lowest reply on screen (again to stop)"},{hints:["a…z"],description:"Locate workspace (type, ↑↓ cycle, ↵ jump)"},{hints:["Esc"],description:"Clear locate query / unfocus right panel"},{hints:["?",F5(s,"/")],description:"This dialog"}]},{title:"Workspace tabs",entries:[...W.map(e=>({hints:[J(s,e.code)],description:`Open ${e.label}`})),{hints:["←","→"],description:"Switch executor target (Executors focused)"}]}].map(e=>(0,B.jsxs)("section",{children:[(0,B.jsx)("h3",{className:"mb-2 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:e.title}),(0,B.jsx)("ul",{className:"space-y-1.5",children:e.entries.map(e=>(0,B.jsxs)("li",{className:"flex items-center justify-between gap-3 text-[13px]",children:[(0,B.jsx)("span",{className:"text-foreground/90",children:e.description}),(0,B.jsx)("span",{className:"flex shrink-0 items-center gap-1",children:e.hints.map(e=>(0,B.jsx)("kbd",{className:"rounded-md border border-border bg-muted px-1.5 py-0.5 font-mono text-[11px] leading-none text-foreground/80",children:e},e))})]},e.description))})]},e.title))})]})})]})}function F6(e){if(null===e)return"尚未连接";let r=Math.max(0,Math.round((Date.now()-e)/1e3));if(r<60)return`${r} 秒前`;let s=Math.floor(r/60);return s<60?`${s} 分钟前`:`${Math.floor(s/60)} 小时前`}function F7(){let{state:e,lastEventAt:r,updateAvailable:s,reconnect:n}=(0,a8.useConnectionStatus)(),[,i]=(0,$.useState)(0);if((0,$.useEffect)(()=>{let e=setInterval(()=>i(e=>e+1),5e3);return()=>clearInterval(e)},[]),"stale"===e)return(0,B.jsxs)("button",{type:"button",onClick:n,title:`实时更新已断开 \xb7 上次更新 ${F6(r)} \xb7 点击重新连接`,className:"flex items-center gap-1.5 rounded-full border border-amber-500/40 bg-amber-500/10 px-2 py-0.5 text-[11px] font-medium text-amber-600 transition-colors hover:bg-amber-500/20",children:[(0,B.jsx)("span",{className:"h-1.5 w-1.5 rounded-full bg-amber-500"}),"实时更新已断开"]});if(s)return(0,B.jsxs)("button",{type:"button",onClick:()=>window.location.reload(),title:"服务器已更新到新版本 · 点击刷新页面加载",className:"flex items-center gap-1.5 rounded-full border border-sky-500/40 bg-sky-500/10 px-2 py-0.5 text-[11px] font-medium text-sky-600 transition-colors hover:bg-sky-500/20",children:[(0,B.jsx)("span",{className:"h-1.5 w-1.5 rounded-full bg-sky-500"}),"有新版本 · 点击刷新"]});let a="live"===e;return(0,B.jsx)("span",{title:a?`实时更新正常 \xb7 上次更新 ${F6(r)}`:"正在连接实时更新…",className:"flex items-center px-1","aria-label":a?"实时更新正常":"正在连接实时更新",children:(0,B.jsx)("span",{className:a?"h-1.5 w-1.5 rounded-full bg-emerald-500":"h-1.5 w-1.5 animate-pulse rounded-full bg-muted-foreground/40"})})}var F8=e.i(63833);function F9(e){return null===e?"":e}function Pe(e,r){let s=e?.machines?.find(e=>e.serverId===r);return e?.branch&&s?.state==="absent"?{kind:"absent",missing:{branch:e.branch,current:s,presentOn:e.machines.filter(e=>"present"===e.state)}}:s?.state==="creating"?{kind:"creating",machineName:s.name}:{kind:"present"}}let Pt=()=>()=>{};function Pr(){var e,r,s,n,i,a,o,l,c;let d,u,h,f,p,m,g,x,v,y,b,w,_,S,j,k,C,{projectId:N,tab:E,branch:D,threadId:R}=function(){let[e,r]=(0,$.useState)(()=>((0,F8.restoreLastLocation)(),Mh()));return(0,$.useEffect)(()=>{let e=()=>r(Mh());return window.addEventListener("popstate",e),()=>window.removeEventListener("popstate",e)},[]),e}(),{config:T}=(0,oU.useAppConfig)(),[A,M]=(0,$.useState)(()=>({branch:D,sessionId:new URLSearchParams(window.location.search).get("session")})),I=A.branch,F=A.sessionId,P=(0,$.useCallback)(e=>{M({branch:e,sessionId:null}),en(null)},[]),L=(0,$.useCallback)(e=>{M(r=>r.sessionId===e?r:{...r,sessionId:e})},[]),[z,O]=(0,$.useState)(null),[W,H]=(0,$.useState)(null),[q,K]=(0,$.useState)(null),[X,Y]=(0,$.useState)(void 0),[Q,ee]=(0,$.useState)(void 0),[et,er]=(0,$.useState)(null),[es,en]=(0,$.useState)(null);(0,$.useEffect)(()=>{let e=()=>{let e=new URLSearchParams(window.location.search).get("session");M(r=>r.sessionId===e?r:{...r,sessionId:e})};return window.addEventListener("popstate",e),()=>window.removeEventListener("popstate",e)},[]),(0,$.useEffect)(()=>{if(new URLSearchParams(window.location.search).has("project")){let e=Mf({projectId:N,tab:E,branch:D,threadId:R});window.history.replaceState(null,"",e)}},[]);let[ei,ea]=(0,$.useState)(!1),[eo,el]=(0,$.useState)(!1),[ec,ed]=(0,$.useState)(!1),[eu,eh]=(0,$.useState)(null),[ef,ep]=(0,$.useState)(E),[em,eg]=(0,$.useState)(R),[ex,ev]=(0,$.useState)(0),[ey,eb]=(0,$.useState)(0),[ew,e_]=(0,$.useState)(!1),[eS,ej]=(0,$.useState)(!1),ek=(0,$.useRef)(null),[eC,eN]=(0,$.useState)(void 0),[eE,eD]=(0,$.useTransition)(),{projects:eR,currentProject:eT,loading:eA,addProject:eI,createProject:eF,updateProject:eP,deleteProject:eL,selectProject:ez,routeProjectPending:eO,routeProjectNotFound:eB}=function(e){let[r,s]=(0,$.useState)([]),[n,i]=(0,$.useState)(null),[a,o]=(0,$.useState)(!0),[l,c]=(0,$.useState)(e),d=(0,$.useRef)(n),u=(0,$.useRef)(e);d.current=n,u.current=e;let h=l!==e,f=a||h,p=!f&&!!e&&!r.some(r=>r.id===e),m=(0,$.useCallback)(async()=>{o(!0);try{let e=await rD.api.getProjects();if(s(e),e.length>0&&!d.current){let r=u.current?e.find(e=>e.id===u.current):e[0];i(r??null)}}finally{o(!1)}},[]);(0,$.useEffect)(()=>{m()},[m]),(0,$.useEffect)(()=>{h&&!a&&(c(e),i(e?r.find(r=>r.id===e)??null:r[0]??null))},[e,a,r,h]);let g=async e=>{let r=await rD.api.createProject(e);return s(e=>[r,...e]),i(r),r},x=(0,$.useCallback)((e,r)=>{let n=e=>"function"==typeof r?r(e):r;s(r=>r.map(r=>r.id===e?n(r):r)),i(r=>r?.id===e?n(r):r)},[]),v=(0,$.useRef)(new Map),y=async(e,s)=>{let n,i={};if(void 0!==s.agentMode&&(i.agent_mode=s.agentMode),void 0!==s.executorMode&&(i.executor_mode=s.executorMode),Object.keys(i).length>0){let s=r.find(r=>r.id===e)??d.current;(n=v.current.get(e))||!s||s.id!==e||(n={seq:0,baseline:s},v.current.set(e,n)),n&&(n.seq+=1),x(e,e=>({...e,...i}))}let a=n?.seq,o=()=>!n||n.seq===a;try{let r=await rD.api.updateProject(e,s);return o()&&(n&&v.current.delete(e),x(e,r)),r}catch(r){throw n&&o()&&(v.current.delete(e),x(e,n.baseline)),r}},b=async e=>{await rD.api.deleteProject(e),s(r=>r.filter(r=>r.id!==e)),n?.id===e&&i(r.find(r=>r.id!==e)??null)};return{projects:r,currentProject:h?null:n,routeProjectPending:f,routeProjectNotFound:p,loading:a,addProject:e=>{s(r=>[e,...r]),i(e)},createProject:g,updateProject:y,deleteProject:b,selectProject:e=>{i(e)},refresh:m}}(N),e$=(0,$.useRef)(void 0);if(eT?.id!==eC){if(void 0!==eC){let s=(e=e$.current,r=eT?.id,e&&!e.checkPlacement&&void 0!==r&&e.projectId===r?{branch:e.branch,sessionId:e.sessionId}:{branch:null,sessionId:null});M(s),s.sessionId&&ev(e=>e+1)}eN(eT?.id)}let{worktrees:eW,loading:eH,stale:eU,listWarning:eq,refetch:eK}=function(e,r,s){let n=e?`${e}::${s??"local"}`:null,[i,a]=(0,$.useState)([]),[o,l]=(0,$.useState)(dA),[c,d]=(0,$.useState)(!0),[u,h]=(0,$.useState)(null),[f,p]=(0,$.useState)(null),m=(0,$.useRef)(null),g=e=>{m.current=e,h(e)},[x,v]=(0,$.useState)(null);if(n!==x){v(n),p(null);let e=n?dT.get(n):void 0;e&&(a(e),g(n),d(!0))}let y=(0,$.useRef)(0),b=(0,$.useRef)(null),w=(0,$.useRef)(0),_=(0,$.useRef)(null),S=(0,$.useRef)(r);S.current=r;let j=(0,$.useCallback)(async(r=!1)=>{if(r&&b.current)return;b.current?.abort();let s=new AbortController;b.current=s,w.current=0;let i=y.current;if(!e||!n){b.current=null,a([]),l(dA),g(null),p(null),d(!1);return}r||d(!0);let o=!1;try{let c=await rD.api.getProjectWorktreeList(e,void 0,s.signal);if(i!==y.current)return;let d=c.worktrees;dT.set(n,d),p(n),l(e=>{let r={staleRemote:c.stale??null,activeRemoteInvalid:!0===c.activeRemoteInvalid};return e.staleRemote?.serverId===r.staleRemote?.serverId&&e.activeRemoteInvalid===r.activeRemoteInvalid?e:r}),o=!0,a(e=>{let s=r?function(e,r,s){if(void 0===s||r.some(e=>e.branch===s))return r;let n=e.findIndex(e=>e.branch===s);if(n<0)return r;let i=[...r];return i.splice(Math.min(n,i.length),0,e[n]),i}(e,d,S.current):d;return e.length===s.length&&e.every((e,r)=>e.branch===s[r].branch&&e.currentBranch===s[r].currentBranch&&e.expectedBranch===s[r].expectedBranch&&dR(e)===dR(s[r]))?e:s})}catch(e){if(i!==y.current||e instanceof Error&&"AbortError"===e.name)return;console.error("Failed to fetch worktrees:",e),r||m.current===n||a([{branch:null}])}finally{if(i!==y.current||b.current!==s)return;o&&(w.current=Date.now()),g(n),r||d(!1),b.current=null}},[e,n]),k=(0,$.useCallback)(()=>{Date.now()-w.current<5e3||j(!0)},[j]);return(0,$.useEffect)(()=>(j(),()=>{b.current?.abort(),b.current=null,y.current+=1}),[j]),(0,$.useEffect)(()=>{let e=_.current;_.current={projectId:n,branch:r},e&&e.projectId===n&&e.branch!==r&&j(!0)},[n,r,j]),(0,a8.useGlobalEventStream)(r=>{if(!e||r.projectId!==e)return;let s="session:status"===r.type&&("stopped"===r.status||"error"===r.status);("session:taskCompleted"===r.type||"executor:stopped"===r.type||s)&&j(!0)}),(0,$.useEffect)(()=>{let e=null,r=()=>{null!==e&&(window.clearInterval(e),e=null)},s=()=>{r(),e=window.setInterval(()=>void j(!0),3e5)},n=()=>k(),i=()=>{"visible"===document.visibilityState?(k(),s()):r()};return window.addEventListener("focus",n),document.addEventListener("visibilitychange",i),"visible"===document.visibilityState&&s(),()=>{r(),window.removeEventListener("focus",n),document.removeEventListener("visibilitychange",i)}},[j,k]),{worktrees:i,loading:c||f!==n,stale:u!==n,listWarning:o,refetch:(0,$.useCallback)(()=>j(!1),[j])}}(eT?.id??null,I,eT?.agent_mode??null),{statuses:eV,rootDirty:eX,defaultTarget:eY,repositoryLabel:eG,repositoryServerId:eJ,setTarget:eZ,refetch:eQ}=function(e,r){let[s,n]=(0,$.useState)(new Map),[i,a]=(0,$.useState)(!1),[o,l]=(0,$.useState)(null),[c,d]=(0,$.useState)(null),[u,h]=(0,$.useState)(null),[f,p]=(0,$.useState)(0),[m,g]=(0,$.useState)(e);e!==m&&(g(e),n(new Map),a(!1),l(null),d(null));let x=(0,$.useCallback)(()=>p(e=>e+1),[]);return(0,$.useEffect)(()=>{let s,i=r.map(e=>e.branch).filter(e=>null!==e),o=new Set(i),c=(s=r.find(e=>null===e.branch))?(void 0===s.currentBranch?s.expectedBranch:s.currentBranch)??null:null,u=i.map(e=>({branch:e}));null===c||o.has(c)||u.push({branch:c});let f=!1;return(async()=>{if(!e||0===u.length){f||(n(new Map),a(!1),l(null),d(null));return}if(dI(e).length>0&&(await function(e){let r=dF.get(e);if(r)return r;let s=(async()=>{let r=new Map;for(;;){let s=dI(e).filter(({key:e,target:s})=>r.get(e)!==s);if(0===s.length)break;for(let{key:n,branch:i,target:a}of s){r.set(n,a);let s=!1;try{s=await rD.api.setMergeTarget(e,i,a,{ifAbsent:!0})}catch{}if(s)try{localStorage.getItem(n)===a&&localStorage.removeItem(n)}catch{}}}})();return dF.set(e,s),s.finally(()=>{dF.get(e)===s&&dF.delete(e)}),s}(e),f))return;let r=await rD.api.getMergeStatus(e,u);f||r.ok&&(n(function(e){let r=new Map;for(let s of e){if("target-not-found"===s.error&&s.requestedTarget){r.set(s.branch,{branch:s.branch,error:s.error,requestedTarget:s.requestedTarget,targetSource:s.targetSource});continue}!s.error&&s.target&&s.status&&r.set(s.branch,{branch:s.branch,status:s.status,unmergedCount:s.unmergedCount??0,dirty:s.dirty??!1,target:s.target})}return r}(r.entries.filter(e=>o.has(e.branch)).map(e=>e.branch===c?{...e,dirty:!1}:e))),a(null!==c&&(r.entries.find(e=>e.branch===c)?.dirty??!1)),l(function(e){for(let r of e)if("default"===r.targetSource&&r.target)return r.target;return null}(r.entries)),d(r.repository.label),h("local"===r.repository.kind?"local":r.repository.remoteServerId))})(),()=>{f=!0}},[e,r,f,x]),{statuses:s,rootDirty:i,defaultTarget:o,repositoryLabel:c,repositoryServerId:u,setTarget:(0,$.useCallback)((r,s)=>{e&&rD.api.setMergeTarget(e,r,s).then(e=>{e&&x()})},[e,x]),refetch:x}}(eT?.id??null,eW),e0=function(e,r){let[s,n]=(0,$.useState)(()=>Iu(e));s.projectId!==e&&n(Iu(e));let i=(0,$.useRef)(e);(0,$.useEffect)(()=>{i.current=e},[e]);let a=(0,$.useRef)(new Map),o=(0,$.useRef)(new Map),[l,c]=(0,$.useState)(0),d=(0,$.useRef)(new Set),u=(0,$.useCallback)(e=>{n(r=>{let s=Date.now();return Ip(e(r,s),d.current,s)})},[]),h=(0,$.useCallback)((e,r)=>{let s=i.current;if(!s)return;let n=`${s}\0${e??""}`,l=(a.current.get(n)??0)+1;a.current.set(n,l);let{request:c,issuedAt:d}=Aq(s,e,{force:r});c.then(r=>{i.current!==s||(o.current.get(n)??0)>=l||(o.current.set(n,l),u((s,n)=>(function(e,r,s,n,i=n){let a=e;for(let e of s)a=If(a,e,n);let o=new Set(s.map(e=>e.id)),l=[];for(let e of a.entries.values())(e.branch??null)===(r??null)&&(o.has(e.runId)||e.insertedAt>i||l.push(e.runId));return l.length>0?Ih(a,l,n):a})(s,e,r,n,d)))}).catch(()=>{})},[u]);(0,$.useEffect)(()=>{e&&h(r,!1)},[e,r,h]);let{state:f}=(0,a8.useConnectionStatus)(),p=(0,$.useRef)(null),m=(0,$.useRef)(!1);(0,$.useEffect)(()=>{let s=p.current;p.current=f;let n=Ii(s,f,m.current);"live"===f&&(m.current=!0),n&&e&&h(r,!0)},[f,e,r,h]),(0,a8.useGlobalEventStream)(r=>{if("workflow:run-updated"!==r.type||!e||r.projectId!==e)return;let s=r.run;s&&"string"==typeof s.id&&u((e,r)=>If(e,s,r))});let g=(0,$.useCallback)((e,r)=>{u((s,n)=>If(s,e,n,r))},[u]),x=(0,$.useCallback)(e=>{d.current=e,n(r=>Ip(r,e,Date.now()))},[]),v=(0,$.useMemo)(()=>[...s.entries.values()],[s]),y=JSON.stringify([...new Set(v.filter(e=>null===e.appearedAt).map(e=>e.branch??""))].sort());(0,$.useEffect)(()=>{let e=JSON.parse(y);if(0===e.length)return;let r=setInterval(()=>{for(let r of(n(e=>(function(e,r){let s=[];for(let n of e.entries.values())n.insertedAt+72e4<=r&&s.push(n.runId);let n=s.length>0?Ih(e,s,r):e,i=!1;for(let e of n.tombstones.values())if(e<=r){i=!0;break}if(i){let e=new Map;for(let[s,i]of n.tombstones)i>r&&e.set(s,i);n={...n,tombstones:e}}return n})(e,Date.now())),e))h(""===r?null:r,!0);c(e=>e+1)},5e3);return()=>clearInterval(r)},[y,h]);let b=(0,$.useMemo)(()=>v.filter(e=>null===e.appearedAt&&"preparing"!==e.run.status&&!Ic(e.run.status)).map(e=>e.reviewerSessionId),[v]);return(0,$.useMemo)(()=>({entries:v,addRun:g,awaitedSessionIds:b,pollTick:l,markAppeared:x}),[v,g,b,l,x])}(eT?.id??null,I),e1=function(e,r,s,n){let i=JSON.stringify((r??[]).map(e=>e.branch)),a=(0,$.useMemo)(()=>JSON.parse(i),[i]),[o,l]=(0,$.useState)([]),[c,d]=(0,$.useState)(null);e!==c&&(d(e),l(e?Ia.get(e)??[]:[]));let u=(0,$.useRef)(e);u.current=e;let h=(0,$.useRef)(new Map),f=(0,$.useRef)(0),p=(0,$.useRef)(0),m=(0,$.useRef)(0),g=(0,$.useCallback)(e=>!(e<m.current)&&(m.current=e,!0),[]);(0,$.useEffect)(()=>{e&&Ia.set(e,o)},[e,o]);let[x,v]=(0,$.useState)(null),y=(0,$.useCallback)((e,r,s,n=1/0)=>{if(null===r||u.current!==e)return;let i=r.filter(e=>{let r=h.current.get(e.id);return void 0===r||r<=n});l(e=>{let r,n=(r=new Map(e.map(e=>[e.id,e])),i.map(e=>{let s=r.get(e.id);return s&&"New Session"===e.title&&"New Session"!==s.title?{...e,title:s.title}:e}));if(!s||n.some(e=>e.id===s))return n;let a=e.find(e=>e.id===s);return a?[a,...n]:n})},[]),b=(0,$.useCallback)(async r=>{if(!e)return void l([]);let s=f.current,n=++p.current,i=await Is(e);if(u.current===e&&g(n)){if("incomplete"===i)return void v(r=>({projectId:e,gen:(r?.gen??0)+1}));v(r=>r?.projectId===e?null:r),y(e,i,r?.keepSessionId,s)}},[e,y,g]);(0,$.useEffect)(()=>{let e=!1;return b().catch(r=>{e||console.warn("[ResidentSessions] refresh failed:",r)}),()=>{e=!0}},[b]),(0,$.useEffect)(()=>{if(!e||x?.projectId!==e)return;let r=!1,s=f.current,n=++p.current;return In(e,a).then(i=>{!r&&g(n)&&y(e,i,void 0,s)}).catch(e=>{r||console.warn("[ResidentSessions] fallback refresh failed:",e)}),()=>{r=!0}},[e,x,a,y,g]);let{state:w}=(0,a8.useConnectionStatus)(),_=(0,$.useRef)(null),S=(0,$.useRef)(!1);(0,$.useEffect)(()=>{let e=_.current;_.current=w;let r=Ii(e,w,S.current);"live"===w&&(S.current=!0),r&&b().catch(e=>console.warn("[ResidentSessions] reconnect refresh failed:",e))},[w,b]);let j=n&&n.sessionIds.length>0?`${n.tick}#${n.sessionIds.join("\0")}`:"",k=(0,$.useRef)(o);return(0,$.useEffect)(()=>{k.current=o},[o]),(0,$.useEffect)(()=>{!j||j.slice(j.indexOf("#")+1).split("\0").every(e=>k.current.some(r=>r.id===e))||b().catch(e=>console.warn("[ResidentSessions] awaited refresh failed:",e))},[j,b]),(0,$.useEffect)(()=>{if(!s||!s.processAlive||!e||s.projectId!==e||h.current.has(s.id))return;let r=!k.current.some(e=>e.id===s.id);l(e=>(function(e,r){let s=e.findIndex(e=>e.id===r.id);if(-1===s)return[r,...e];let n=e[s],i="New Session"===r.title&&"New Session"!==n.title?n.title:r.title,a=[...e];return a[s]={...r,title:i,status:n.status},a})(e,s)),r&&b({keepSessionId:s.id}).catch(e=>console.warn("[ResidentSessions] seed refresh failed:",e))},[e,s,b]),(0,a8.useGlobalEventStream)(r=>{if(e&&r.projectId===e){if("session:process"===r.type){let e="string"==typeof r.sessionId?r.sessionId:null,s="boolean"==typeof r.alive?r.alive:null,n="string"==typeof r.branch?r.branch:null;if(!e||null===s)return;if(!s){h.current.set(e,++f.current),l(r=>r.filter(r=>r.id!==e));return}h.current.delete(e),b().catch(e=>console.warn("[ResidentSessions] process refresh failed:",e)),null!==n&&l(r=>r.map(r=>r.id===e?{...r,branch:n}:r))}if("session:status"===r.type){let e="string"==typeof r.sessionId?r.sessionId:null,s="string"==typeof r.status?r.status:null;if(!e||!s)return;l(r=>r.map(r=>r.id===e?{...r,status:s}:r))}if("session:title"===r.type){let e="string"==typeof r.sessionId?r.sessionId:null;if(!e)return;l(s=>{var n,i;return i=("string"==typeof(n=r.title)?n.trim():"")||"New Session",s.map(r=>r.id===e?{...r,title:i}:r)})}}}),(0,$.useMemo)(()=>{let e=new Map;for(let r of o){let s=r.branch??"",n=e.get(s)??[];n.push(r),e.set(s,n)}for(let r of e.values())r.sort((e,r)=>(r.updated_at??"").localeCompare(e.updated_at??""));return e},[o])}(eT?.id??null,eW,z,{sessionIds:e0.awaitedSessionIds,tick:e0.pollTick}),e2=(0,$.useMemo)(()=>{let e=new Set;for(let r of e1.values())for(let s of r)e.add(s.id);return e},[e1]),e5=(0,$.useCallback)(e=>{for(let r of e1.values()){let s=r.find(r=>r.id===e);if(s)return s.title}return null},[e1]),e3=(0,$.useMemo)(()=>(function(e,r,s){if(0===r.length)return e;let n=new Map(e),i=new Set;for(let r of e.values())for(let e of r)i.add(e.id);for(let e of r){var a;if(null!==e.appearedAt||i.has(e.reviewerSessionId))continue;let r=e.branch??"",o=n.get(r)??[];n.set(r,[(a=s(e.sourceSessionId),{id:e.reviewerSessionId,projectId:e.projectId,branch:e.branch,title:Im(e,a),status:"preparing",processAlive:!1,updated_at:e.run.created_at,kind:Io,runId:e.runId}),...o])}return n})(e1,e0.entries,e5),[e1,e0.entries,e5]),e4=null!==es&&es.projectId===eT?.id,e6=e4?e0.entries.find(e=>e.runId===es.runId):void 0,{tasks:e7,loading:e8,createTask:e9,updateTask:te,deleteTask:tt,archive:tr,unarchive:ts,refetch:tn}=function(e){let[r,s]=(0,$.useState)([]),[n,i]=(0,$.useState)(!0),a=(0,$.useCallback)(async()=>{if(!e){s([]),i(!1);return}try{let r=await rD.api.getTasks(e,{includeArchived:!0});s(r)}catch(e){console.error("Failed to fetch tasks:",e)}finally{i(!1)}},[e]);(0,$.useEffect)(()=>{a()},[a]);let o=(0,$.useCallback)(async r=>{if(!e)return null;try{let n=await rD.api.createTask(e,r);return s(e=>[...e,n]),n}catch(e){return console.error("Failed to create task:",e),null}},[e]),l=(0,$.useCallback)(async(e,n)=>{s(r=>r.map(r=>r.id===e?{...r,...n,updated_at:new Date().toISOString()}:r));try{let r=await rD.api.updateTask(e,n);return s(s=>s.map(s=>s.id===e?r:s)),r}catch(e){return console.error("Failed to update task:",e),s(r),null}},[r]),c=(0,$.useCallback)(async e=>{s(r=>r.filter(r=>r.id!==e));try{await rD.api.deleteTask(e)}catch(e){console.error("Failed to delete task:",e),s(r)}},[r]),d=(0,$.useCallback)(async e=>{s(r=>r.map(r=>r.id===e?{...r,archived_at:Date.now()}:r));try{let r=await rD.api.archiveTask(e);s(s=>s.map(s=>s.id===e?r:s))}catch(e){console.error("Failed to archive task:",e),s(r)}},[r]),u=(0,$.useCallback)(async e=>{s(r=>r.map(r=>r.id===e?{...r,archived_at:null}:r));try{let r=await rD.api.unarchiveTask(e);s(s=>s.map(s=>s.id===e?r:s))}catch(e){console.error("Failed to unarchive task:",e),s(r)}},[r]),h=(0,$.useCallback)(async n=>{if(e){s(n.map(e=>r.find(r=>r.id===e)).filter(e=>void 0!==e));try{await rD.api.reorderTasks(e,n)}catch(e){console.error("Failed to reorder tasks:",e),s(r)}}},[e,r]);return{tasks:r,loading:n,createTask:o,updateTask:l,deleteTask:c,archive:d,unarchive:u,reorderTasks:h,refetch:a}}(eT?.id??null),{schedules:ti,loading:ta,createSchedule:to,updateSchedule:tl,deleteSchedule:tc,runNow:td}=function(e){let[r,s]=(0,$.useState)([]),[n,i]=(0,$.useState)(!1),[a,o]=(0,$.useState)(null);e!==a&&(o(e),s(e?dL.get(e)??[]:[])),(0,$.useEffect)(()=>{e&&dL.set(e,r)},[e,r]);let l=(0,$.useRef)(e),c=(0,$.useRef)(0),d=(0,$.useCallback)(async(e,r,n)=>{if(!e){c.current===r&&(s([]),i(!1));return}n&&i(!0);try{let n=await rD.api.getSchedules(e);c.current===r&&s(n)}catch(e){console.error("Failed to fetch schedules:",e)}finally{n&&c.current===r&&i(!1)}},[]);(0,$.useEffect)(()=>{l.current=e,c.current+=1,d(e,c.current,!0)},[e,d]);let u=(0,$.useCallback)(async()=>{let e=l.current;e&&await d(e,c.current,!1)},[d]),h=(0,$.useRef)(u);(0,$.useEffect)(()=>{h.current=u},[u]),(0,a8.useGlobalEventStream)(e=>{!e.type?.startsWith("schedule:")||l.current&&e.projectId===l.current&&h.current()});let f=(0,$.useCallback)(async r=>{if(!e)throw Error("No project selected");let s=await rD.api.createSchedule(e,r);return await u(),s},[e,u]),p=(0,$.useCallback)(async(e,r)=>{let s=await rD.api.updateSchedule(e,r);return await u(),s},[u]),m=(0,$.useCallback)(async e=>{await rD.api.deleteSchedule(e),await u()},[u]),g=(0,$.useCallback)(async(e,r)=>{let s=r;if(!s){let e=crypto.randomUUID();s={requestId:e,runId:e}}let n=await rD.api.runScheduleNow(e,s);return await u(),n},[u]);return{schedules:r,loading:n,refetch:u,createSchedule:f,updateSchedule:p,deleteSchedule:m,runNow:g}}(eT?.id??null),[tu,th]=(0,$.useState)(null),[tf,tp]=(0,$.useState)(null),[tm,tg]=(0,$.useState)(null),[tx,tv]=(0,$.useState)(null),[ty,tb]=(0,$.useState)(!1),[tw,t_]=(0,$.useState)(null),tS=(0,$.useCallback)(e=>{tp({kind:"task",taskId:e.id,status:e.status}),ep("tasks")},[ep]),{activity:tj,since:tk,refetch:tC,setOptimisticActivity:tN}=function(e){let[r,s]=(0,$.useState)(new Map),[n,i]=(0,$.useState)(new Map),a=(0,$.useRef)(new Map),o=(0,$.useRef)(new Map),l=(0,$.useRef)(null),c=(0,$.useCallback)(async()=>{if(!e){s(new Map),i(new Map),o.current=new Map,l.current=null,a.current=new Map;return}try{let r=await (0,rD.authFetch)(`${"localhost"===window.location.hostname&&"3000"===window.location.port?"http://localhost:5173":""}/api/projects/${e}/branches/activity`);if(!r.ok)return;let n=await r.json(),c=l.current!==e,{nextActivity:d,nextSince:u}=function(e,r,s,n){let i=new Map,a=new Map,o=[];for(let l of e){let e=l.branch??"",c=s.get(e)??0;if(!n&&l.since<c){let s=r.get(e);if(void 0!==s){i.set(e,s),a.set(e,c);continue}}i.set(e,l.activity),a.set(e,l.since),n||r.get(e)===l.activity||o.push(l.branch)}return{nextActivity:i,nextSince:a,transitions:o}}(n.branches,o.current,a.current,c);s(d),i(u),o.current=d,l.current=e,a.current=u}catch{}},[e]);return(0,$.useEffect)(()=>{c()},[c]),(0,a8.useGlobalEventStream)(r=>{var n,l,c;let d,u;if("branch:activity"!==r.type||!e||r.projectId!==e)return;let h=(n=r,l=o.current,c=a.current,d=n.branch??"",u=c.get(d)??0,n.since<u?{kind:"stale"}:l.get(d)===n.activity?{kind:"redundant",key:d}:{kind:"transition",key:d});"stale"===h.kind||(a.current.set(h.key,r.since),i(new Map(a.current)),"redundant"!==h.kind&&s(e=>{let s=new Map(e);return s.set(h.key,r.activity),o.current=s,s}))}),{activity:r,since:n,refetch:c,setOptimisticActivity:(0,$.useCallback)((e,r)=>{s(s=>{let n=function(e,r,s){let n=r??"";if(e.get(n)===s)return e;let i=new Map(e);return i.set(n,s),i}(s,e,r);return o.current=n,n})},[])}}(eT?.id??null),{rules:tE,createRule:tD,updateRule:tR,deleteRule:tT}=function(e,r){let[s,n]=(0,$.useState)([]),[i,a]=(0,$.useState)(!0),o=(0,$.useCallback)(async()=>{if(!e){n([]),a(!1);return}try{let s=await rD.api.getRules(e,r);n(s)}catch(e){console.error("Failed to fetch rules:",e)}finally{a(!1)}},[e,r]);(0,$.useEffect)(()=>{o()},[o]);let l=(0,$.useCallback)(async s=>{if(!e)return null;try{let i=await rD.api.createRule(e,{...s,branch:r});return n(e=>[...e,i]),i}catch(e){return console.error("Failed to create rule:",e),null}},[e,r]),c=(0,$.useCallback)(async(e,r)=>{n(s=>s.map(s=>s.id===e?{...s,...r,enabled:void 0!==r.enabled?+!!r.enabled:s.enabled,updated_at:new Date().toISOString()}:s));try{let s=await rD.api.updateRule(e,r);return n(r=>r.map(r=>r.id===e?s:r)),s}catch(e){return console.error("Failed to update rule:",e),n(s),null}},[s]),d=(0,$.useCallback)(async e=>{n(r=>r.filter(r=>r.id!==e));try{await rD.api.deleteRule(e)}catch(e){console.error("Failed to delete rule:",e),n(s)}},[s]);return{rules:s,loading:i,createRule:l,updateRule:c,deleteRule:d,refetch:o}}(eT?.id??null,I),{commands:tA,createCommand:tM,updateCommand:tI,deleteCommand:tF}=function(e,r){let[s,n]=(0,$.useState)([]),[i,a]=(0,$.useState)(!0),o=(0,$.useCallback)(async()=>{if(!e){n([]),a(!1);return}try{let s=await rD.api.getCommands(e,r);n(s)}catch(e){console.error("Failed to fetch commands:",e)}finally{a(!1)}},[e,r]);(0,$.useEffect)(()=>{o()},[o]);let l=(0,$.useCallback)(async s=>{if(!e)return null;try{let i=await rD.api.createCommand(e,{...s,branch:r});return n(e=>[...e,i]),i}catch(e){return console.error("Failed to create command:",e),null}},[e,r]),c=(0,$.useCallback)(async(e,r)=>{n(s=>s.map(s=>s.id===e?{...s,...r,updated_at:new Date().toISOString()}:s));try{let s=await rD.api.updateCommand(e,r);return n(r=>r.map(r=>r.id===e?s:r)),s}catch(e){return console.error("Failed to update command:",e),n(s),null}},[s]),d=(0,$.useCallback)(async e=>{n(r=>r.filter(r=>r.id!==e));try{await rD.api.deleteCommand(e)}catch(e){console.error("Failed to delete command:",e),n(s)}},[s]);return{commands:s,loading:i,createCommand:l,updateCommand:c,deleteCommand:d,refetch:o}}(eT?.id??null,I),tP=(0,$.useRef)(null),tL=(0,$.useRef)(null),[tz,tO]=(0,$.useState)(!1),tB=(0,$.useCallback)(()=>{let e=tL.current;e&&(e.isCollapsed()?e.expand():e.collapse())},[]),t$=(0,$.useSyncExternalStore)(Pt,U,()=>!1),tW=`${tz?"Show":"Hide"} Main Chat`,tH=(0,$.useSyncExternalStore)(EO,EB,E$),tU=eT?.id??null,tq=eT?.agent_mode??null,tK=(0,$.useCallback)(e=>!!tU&&tH.has(EW(tU,e,tq)),[tH,tU,tq]),tV=(0,$.useCallback)(e=>{if(tU)return tH.get(EW(tU,e,tq))},[tH,tU,tq]),tX=(0,$.useCallback)(e=>tk.get(F9(e)),[tk]),tY=(0,$.useMemo)(()=>(function(e,r,s,n){let i=new Map;if(!e)return i;for(let a of e){let e=F9(a.branch),o=r.get(e);if(!s?.(a.branch)){i.set(e,o??"idle");continue}if("main-running"===o||"main-waiting"===o)i.set(e,o);else if("main-completed"===o){let r=n?.backendSince?.(a.branch)??0,s=n?.placeholderSince?.(a.branch)??0;i.set(e,s>r?"idle":"main-completed")}else i.set(e,"idle")}return i})(eW,tj,tK,{backendSince:tX,placeholderSince:tV}),[eW,tj,tK,tX,tV]);o=eQ,l=tY,c=eT?.id??null,d=(0,$.useRef)(new Set),h=(u=function(e){let r=new Set;if(!e)return r;for(let[s,n]of e)dP.has(n)&&r.add(s);return r}(l)).size>0,f=JSON.stringify(Array.from(u).sort()),(0,$.useEffect)(()=>{let e=new Set(JSON.parse(f)),r=d.current;d.current=e,function(e,r){for(let s of e)if(!r.has(s))return!0;return!1}(r,e)&&o()},[f,o]),(0,$.useEffect)(()=>{let e=()=>o();return window.addEventListener("focus",e),()=>window.removeEventListener("focus",e)},[o]),(0,a8.useGlobalEventStream)(e=>{"executor:stopped"===e.type&&e.projectId===c&&o(),"merge-target:updated"===e.type&&null!==c&&e.projectId===c&&o(),"files:changed"===e.type&&null!==c&&e.projectId===c&&o()}),(0,$.useEffect)(()=>{let e=null,r=()=>{null!==e&&(clearInterval(e),e=null)},s=()=>{r(),e=setInterval(o,h?3e4:6e4)},n=()=>{"visible"===document.visibilityState?s():r()};return"visible"===document.visibilityState&&s(),document.addEventListener("visibilitychange",n),()=>{r(),document.removeEventListener("visibilitychange",n)}},[o,h]);let[tG,tJ]=(0,$.useState)(null),[tZ,tQ]=(0,$.useState)(null),[t0,t1]=(0,$.useState)(null),[t2,t5]=(0,$.useState)(!1),t3="workspace"===ef&&t2&&null!==tZ,{notifications:t4,unreadCount:t6,markRead:t7,markAllRead:t8,remove:t9,clear:re,markReviewRunRead:rt}=function(e,r=null,s=null){let[n,i]=(0,$.useState)([]),a=(0,$.useRef)(new Set),o=(0,$.useRef)(new Set),l=(0,$.useRef)(n);(0,$.useEffect)(()=>{l.current=n},[n]);let c=(0,$.useRef)(new Set);(0,$.useEffect)(()=>{for(let e of new Set(Object.values(F$)))FV.has(e)||FX.has(e)||(FX.add(e),(async()=>{try{let r=await fetch(e),s=await r.blob(),n=new Audio(URL.createObjectURL(s));n.preload="auto",n.load(),FV.set(e,n)}catch{}finally{FX.delete(e)}})())},[]);let d=(0,$.useRef)(e),u=(0,$.useRef)({resultAt:r,turnEndAt:s});(0,$.useEffect)(()=>{d.current=e,u.current={resultAt:r,turnEndAt:s}},[e,r,s]);let h=(0,$.useRef)(new Map);(0,$.useEffect)(()=>{if(!e||null===r)return;let n=()=>{if("visible"!==document.visibilityState)return;let n=h.current.get(e),i=(e,r)=>null==e?r:null===r?e:Math.max(e,r);h.current.set(e,{resultAt:i(n?.resultAt,r),turnEndAt:i(n?.turnEndAt,s)})};return n(),document.addEventListener("visibilitychange",n),()=>document.removeEventListener("visibilitychange",n)},[e,r,s]);let f=(0,$.useCallback)(e=>{if(null===e.session_id)return!1;let r=h.current.get(e.session_id);return void 0!==r&&FG(e,r)},[]),p=(0,$.useCallback)(e=>{if(o.current.has(e))return;o.current.add(e);let r=Date.now();i(s=>s.map(s=>s.id===e&&null===s.read_at?{...s,read_at:r}:s)),(0,rD.markNotificationRead)(e).catch(()=>{i(s=>s.map(s=>s.id===e&&s.read_at===r?{...s,read_at:null}:s))}).finally(()=>{o.current.delete(e)})},[]),m=(0,$.useCallback)(e=>null===e.read_at&&null!==e.workflow_run_id&&c.current.has(e.workflow_run_id)?((0,rD.markNotificationRead)(e.id).catch(()=>{}),{...e,read_at:Date.now()}):e,[]);(0,$.useEffect)(()=>{let e=!1;return(0,rD.getNotifications)({limit:100}).then(r=>{if(e)return;for(let e of r)a.current.add(e.id);let s=r.map(m);i(e=>{let r=[];for(let e of s)r=FH(r,e);for(let n of e)s.some(e=>e.id===n.id)||(r=FH(r,n));return r});try{window.localStorage.removeItem("vibedeckx:completion-notifications")}catch{}}).catch(e=>{console.warn("[notifications] hydration failed:",e)}),()=>{e=!0}},[m]);let g=(0,$.useCallback)((e,r=!1)=>{let s=!a.current.has(e.id);a.current.add(e.id);let n=d.current,o=null!==e.session_id&&e.session_id===n&&FG(e,u.current),l=null!==e.workflow_run_id&&c.current.has(e.workflow_run_id),h=o||l||r;return i(r=>FH(r,h?{...e,read_at:e.read_at??Date.now()}:e)),h&&null===e.read_at&&(0,rD.markNotificationRead)(e.id).catch(()=>{}),s&&!l&&!r},[]),x=(0,$.useRef)(null),v=(0,$.useRef)(!1);(0,$.useEffect)(()=>(v.current=!1,()=>{v.current=!0,x.current&&clearTimeout(x.current)}),[]);let y=(0,$.useCallback)(()=>{x.current&&(clearTimeout(x.current),x.current=null);let e=r=>{(0,rD.getNotifications)({limit:100}).then(e=>{let r=Date.now(),s=null;for(let n of e){if(a.current.has(n.id))continue;let e=g(n,f(n)),i=null===n.read_at&&r-n.created_at<=12e4;e&&i&&(!s||n.created_at>s.created_at)&&(s=n)}s&&FJ(F$[s.kind])}).catch(s=>{let n=FW[r];console.warn(`[notifications] reconnect catch-up failed${void 0===n?", giving up":`, retrying in ${n}ms`}:`,s),void 0===n||v.current||(x.current=setTimeout(()=>{x.current=null,e(r+1)},n))})};e(0)},[g,f]);(0,a8.useGlobalEventStream)(e=>{if(e.type===a8.STREAM_RECONNECTED_EVENT)return void y();if("notification:created"!==e.type)return;let r=e.notification;r?.id&&g(r)&&FJ(F$[r.kind])}),(0,$.useEffect)(()=>{if(e&&null!==r)for(let a of n){if(a.session_id!==e||null!==a.read_at||!FG(a,{resultAt:r,turnEndAt:s})||o.current.has(a.id))continue;let{id:n}=a;o.current.add(n),(0,rD.markNotificationRead)(n).then(()=>{i(e=>e.map(e=>e.id===n&&null===e.read_at?{...e,read_at:Date.now()}:e))}).catch(()=>{}).finally(()=>{o.current.delete(n)})}},[e,r,s,n]);let b=(0,$.useCallback)(e=>p(e),[p]),w=(0,$.useCallback)((e,r)=>{for(let s of(r?.runEnded&&c.current.add(e),l.current))s.workflow_run_id===e&&null===s.read_at&&p(s.id)},[p]),_=(0,$.useCallback)(()=>{let e=Date.now();i(r=>r.some(e=>null===e.read_at)?r.map(r=>null===r.read_at?{...r,read_at:e}:r):r),(0,rD.markAllNotificationsRead)().catch(()=>i(n))},[n]),S=(0,$.useCallback)(e=>{p(e),i(r=>r.filter(r=>r.id!==e))},[p]),j=(0,$.useCallback)(()=>{(0,rD.markAllNotificationsRead)().catch(e=>console.warn("[notifications] read-all failed:",e)),i(e=>e.length?[]:e)},[]),k=FK(n).reduce((e,r)=>e+ +!!r.unread,0);return{notifications:n,unreadCount:k,markRead:b,markAllRead:_,remove:S,clear:j,markReviewRunRead:w}}(t3?tG:null,t3?tZ:null,t3?t0:null),rr=(0,$.useMemo)(()=>({markReviewRunRead:rt}),[rt]),rs=(0,$.useMemo)(()=>t4.filter(e=>e.project_id===eT?.id&&null===e.read_at).length,[t4,eT?.id]),rn=(0,$.useCallback)(()=>{tN(I,"working")},[I,tN]),ri=(0,$.useCallback)(()=>{tn()},[tn]),ra=(0,$.useCallback)((e,r)=>{M({branch:e,sessionId:r}),en(null),ev(e=>e+1),e_(!1),(0,Fz.touchRecentSessionOpen)(r)},[]),ro=(0,$.useRef)(0),rl=(0,$.useCallback)((e,r,s)=>{ep("workspace"),P(e),K({branch:e,path:r,line:s,nonce:++ro.current})},[P]),rc=(0,$.useCallback)((e,r,s)=>{en({projectId:e,runId:r}),M({branch:s,sessionId:null}),ev(e=>e+1),e_(!1),ep("workspace")},[]),rd=(0,$.useCallback)(e=>{"preparing-review"===e.kind&&e.runId?rc(e.projectId,e.runId,e.branch):(ra(e.branch,e.id),ep("workspace"))},[ra,rc]),ru=(0,$.useCallback)(e=>{let r=e0.entries.find(r=>r.runId===e);r&&rc(r.projectId,r.runId,r.branch)},[e0.entries,rc]),rh=e0.markAppeared;(0,$.useEffect)(()=>{rh(e2)},[e2,rh]),(0,$.useEffect)(()=>{if(!es)return;if(es.projectId!==eT?.id)return void en(null);let e=e6?null!==e6.appearedAt?{kind:"switch",branch:e6.branch,sessionId:e6.reviewerSessionId}:"preparing"===e6.run.status?{kind:"wait"}:Ic(e6.run.status)?{kind:"gone"}:e2.has(e6.reviewerSessionId)?{kind:"switch",branch:e6.branch,sessionId:e6.reviewerSessionId}:{kind:"wait"}:{kind:"gone"};"switch"===e.kind&&ra(e.branch,e.sessionId)},[es,e6,e2,eT?.id,ra]);let rf=(0,$.useCallback)(e=>{tC();let r=eR.find(r=>r.id===e.projectId);(0,Fz.touchSessionStarted)({sessionId:e.id,projectId:e.projectId,projectName:r?.name??"",targetId:r?.agent_mode??"local",branch:e.branch});let s=function(e,r=new Date){return!0!==e.processAlive?null:{id:e.id,projectId:e.projectId,branch:e.branch,title:"New Session",status:e.status,processAlive:!0,updated_at:r.toISOString()}}(e);s&&O(s)},[tC,eR]),rp=(0,$.useCallback)((e,r)=>{r.trim()&&(0,Fz.updateCachedSessionTitle)(e,r.trim())},[]),rm=(0,$.useCallback)(()=>{tN(I,"idle")},[I,tN]),rg=(0,$.useCallback)(()=>{tn()},[tn]);s=eT?.id??null,n={onTaskChanged:rg},p=(0,$.useRef)(n.onTaskChanged),(0,$.useEffect)(()=>{p.current=n.onTaskChanged}),(0,a8.useGlobalEventStream)(e=>{s&&e.projectId===s&&("task:created"===e.type||"task:updated"===e.type||"task:deleted"===e.type)&&p.current?.()});let rx=(0,$.useMemo)(()=>{let e=F9(I);return e7.find(r=>r.assigned_branch===e)??null},[e7,I]);(0,$.useCallback)(e=>{eD(async()=>{await ek.current?.submitMessage(e.description??e.title)})},[]);let[rv,ry]=(0,$.useState)(null),rb=(0,$.useCallback)((e,r)=>{eT&&(EU(EW(eT.id,r,eT.agent_mode)),ry({projectId:eT.id,branch:r,tasks:[{...e,subtasks:T9(e7,e.id)}],nonce:Date.now()}),ep("workspace"),P(r),ev(e=>e+1))},[eT,e7,P]);(0,$.useCallback)(e=>{te(e,{assigned_branch:null})},[te]),(0,$.useEffect)(()=>{let e=e$.current;if(void 0!==e&&e.projectId!==eT?.id&&(e$.current=void 0,e_(!1),ej(!1)),!eU&&0!==eW.length){if(void 0!==e&&e.projectId===eT?.id){let r=eW.find(r=>r.branch===e.branch);if(r&&e.checkPlacement){e$.current=void 0,e_(!1),ej(!1);let s=Pe(r,eT?.agent_mode??"local");return"absent"===s.kind?void er(s.missing):("creating"===s.kind&&xN.toast.info(`'${e.branch}' is still being created on ${s.machineName}`),void P(e.branch))}if(r){e$.current=void 0,I!==e.branch||F!==e.sessionId?e.sessionId?ra(e.branch,e.sessionId):P(e.branch):e.sessionId&&(0,Fz.touchRecentSessionOpen)(e.sessionId),ej(!1),e_(!1);return}return void(eH||(e$.current=void 0,e_(!1),ej(!1),xN.toast.warning(`Workspace "${e.branch??"main"}" no longer exists`),P(eW[0].branch)))}!eH&&(eW.some(e=>e.branch===I)||(F&&xN.toast.warning(`Workspace "${I??"main"}" no longer exists`),P(eW[0].branch)))}},[eW,eH,eU,I,F,eT?.id,eT?.agent_mode,ra,P]),(0,$.useEffect)(()=>{(ew||eS)&&(null===I&&(eH||0!==eW.length)||(e_(!1),ej(!1)))},[ew,eS,I,eH,eW]);let rw=(0,$.useCallback)((e,r,s=null)=>{if(ep("workspace"),e===eT?.id)return void(s?ra(r,s):P(r));let n=eR.find(r=>r.id===e);n&&(s?e_(!0):ej(!0),e$.current={projectId:e,branch:r,sessionId:s},ez(n))},[eT?.id,eR,ez,ra,P]),[r_,rS]=(0,$.useState)(!1),rj=!!eT;(0,$.useEffect)(()=>{let e=e=>{if("k"===e.key&&(e.metaKey||e.ctrlKey)){e.preventDefault(),rS(e=>!e);return}if(G(e,V)){if("workspace"!==ef||!rj)return;e.preventDefault(),e.repeat||tB();return}"o"===e.key.toLowerCase()&&e.shiftKey&&(e.metaKey||e.ctrlKey)&&"workspace"===ef&&(e.preventDefault(),ev(e=>e+1),ek.current?.startNewConversation())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[ef,rj,tB]);let rk=(0,$.useRef)(!1),rC=(0,$.useCallback)(async(e,r)=>{let s=eR.find(r=>r.id===e);if(!s)return null;let n="local"===r?"local":r;return(s.agent_mode??"local")!==n?eP(s.id,{agentMode:n}):s},[eR,eP]),rN=(i={projectId:eT?.id??null,resolveProjectForTarget:rC,getScheduleRun:rD.api.getScheduleRun,getSchedules:rD.api.getSchedules,runScheduleNow:td,selectAgentSession:(e,r)=>{ep("workspace"),ra(e,r)},openScheduleRun:(e,r)=>{th(e),tv(r),ep("schedules")},onRerunResult:e=>{e.replay&&e.status&&"starting"!==e.status&&"running"!==e.status?"completed"===e.status?xN.toast.success("Schedule run already completed"):xN.toast.error(`Schedule run already ${e.status}`):xN.toast.success("Schedule run started")},onError:(e,r)=>{console.error(`Project activity ${e} failed:`,r),"session-navigation"===e?xN.toast.error("Failed to open agent session"):"schedule-navigation"===e?xN.toast.error("Failed to open schedule run"):xN.toast.error(r instanceof Error?r.message:"Failed to start schedule run")}},(m=(0,$.useRef)(i)).current=i,(g=(0,$.useRef)({projectId:i.projectId,generation:0})).current.projectId!==i.projectId&&(g.current={projectId:i.projectId,generation:g.current.generation+1}),x=(0,$.useRef)(new Map),v=(0,$.useRef)(new Map),y=(0,$.useCallback)(e=>g.current.projectId===e.projectId&&g.current.generation===e.generation,[]),b=(0,$.useCallback)(async(e,r)=>{if(!e.projectId)return null;let s=m.current,n=await s.getScheduleRun(r);if(!y(e))return null;if(n.project_id!==e.projectId)throw Error("Schedule run does not belong to the active project");let i=await s.getSchedules(e.projectId);if(!y(e))return null;let a=i.find(e=>e.id===n.schedule_id);if(!a||a.project_id!==e.projectId)throw Error("Schedule does not belong to the active project");return{run:n,schedule:a}},[y]),w=(0,$.useCallback)(async(e,r,s)=>{let n={...g.current};if(n.projectId)try{let i=await m.current.resolveProjectForTarget(n.projectId,r);if(!y(n)||!i||i.id!==n.projectId)return;m.current.selectAgentSession(s,e,i.id)}catch(e){y(n)&&m.current.onError("session-navigation",e)}},[y]),_=(0,$.useCallback)(async(e,r)=>{let s={...g.current};try{let n=await b(s,e);if(!n||!y(s))return;if(r&&r!==n.schedule.id)throw Error("Schedule run target changed while opening");m.current.openScheduleRun(n.schedule.id,e)}catch(e){y(s)&&m.current.onError("schedule-navigation",e)}},[y,b]),S=(0,$.useCallback)(e=>{let r={...g.current};if(!r.projectId)return Promise.resolve();let s=`${r.projectId}:${e}`,n=v.current.get(s);if(n)return n;let i=(async()=>{try{let n,i=dz(r.projectId,e),a=x.current.get(i)??function(e,r,s){try{let n=window.sessionStorage.getItem(e);if(!n)return;let i=JSON.parse(n);return"string"==typeof i.requestId&&"string"==typeof i.runId&&i.projectId===r&&"string"==typeof i.scheduleId&&i.scheduleId.length>0&&i.sourceRunId===s?i:void 0}catch{return}}(i,r.projectId,e);if(a){let e=await m.current.getSchedules(r.projectId);if(!y(r))return;let s=a.scheduleId,o=e.find(e=>e.id===s);if(!o||o.project_id!==r.projectId)throw Error("Schedule does not belong to the active project");n=o,x.current.set(i,a)}else{let o=await b(r,e);if(!o||!y(r))return;n=o.schedule;let l=crypto.randomUUID();a={projectId:r.projectId,scheduleId:n.id,requestId:l,runId:l,sourceRunId:e},x.current.set(i,a);var s=a;try{window.sessionStorage.setItem(i,JSON.stringify(s))}catch{}}let o={requestId:a.requestId,runId:a.runId,sourceRunId:a.sourceRunId},l=await m.current.runScheduleNow(n.id,o);if(x.current.delete(i),dO(i),!y(r))return;m.current.onRerunResult(l)}catch(s){if(r.projectId&&("object"==typeof s&&null!==s&&"status"in s&&409===s.status||"object"==typeof s&&null!==s&&"durable"in s&&!0===s.durable)){let s=dz(r.projectId,e);x.current.delete(s),dO(s)}throw y(r)&&m.current.onError("schedule-rerun",s),s}})().finally(()=>{v.current.get(s)===i&&v.current.delete(s)});return v.current.set(s,i),i},[y,b]),{openAgentSession:w,openScheduleRun:_,runScheduleAgain:S}),rR=(a={projectId:eT?.id??null,schedules:ti,getTask:rD.api.getTask,resolveProjectForTarget:rC,openTask:t_,selectAgentSession:(e,r)=>{ep("workspace"),ra(e,r)},selectWorkspace:e=>{P(e),ep("workspace")},selectSchedule:e=>{th(e),ep("schedules")},openScheduleRun:rN.openScheduleRun,onError:e=>{xN.toast.error(e instanceof Error?e.message:"Unable to open Context item")}},(j=(0,$.useRef)(a)).current=a,(k=(0,$.useRef)({projectId:a.projectId,generation:0})).current.projectId!==a.projectId&&(k.current={projectId:a.projectId,generation:k.current.generation+1}),C=(0,$.useCallback)(e=>e.projectId===k.current.projectId&&e.generation===k.current.generation,[]),{open:(0,$.useCallback)(async e=>{let r={...k.current},s=e.navigation;if(!r.projectId||e.deleted||!s){C(r)&&j.current.onError(Error("This Context item is no longer available"));return}try{if("task"===s.kind){let e=await j.current.getTask(r.projectId,s.taskId);if(!C(r))return;if(e.id!==s.taskId||e.project_id!==r.projectId)throw Error("Task is no longer available in this project");j.current.openTask(e);return}if("agent_session"===s.kind||"workspace"===s.kind){let e=await j.current.resolveProjectForTarget(r.projectId,s.target);if(!C(r))return;if(!e||e.id!==r.projectId)throw Error("Workspace target is no longer available");"agent_session"===s.kind?j.current.selectAgentSession(s.branch,s.sessionId,e.id):j.current.selectWorkspace(s.branch,e.id);return}if("schedule"===s.kind){let e=j.current.schedules.find(e=>e.id===s.scheduleId&&e.project_id===r.projectId);if(!e)throw Error("Schedule is no longer available in this project");j.current.selectSchedule(e.id);return}await j.current.openScheduleRun(s.runId,s.scheduleId)}catch(e){C(r)&&j.current.onError(e)}},[C])}),rT=(0,$.useCallback)(e=>{eg(e),P(null),ep("project-chat")},[P]),rA=(0,$.useCallback)(()=>{eg(null),ep("project-info")},[]);(0,$.useEffect)(()=>{ep(E),eg("project-chat"===E?R:null),"project-chat"===E&&P(null)},[E,R,P]);let rM=(0,$.useCallback)(e=>{tv(r=>r===e?null:r)},[]),rI=(0,$.useCallback)(e=>{if(rk.current)return;let r=eR.find(r=>r.id===e);r&&(rS(!1),ez(r),ep("project-info"))},[eR,ez]),rF=(0,$.useCallback)(async e=>{if(!rk.current){rk.current=!0,rS(!1);try{let r=await rC(e.projectId,e.targetId);if(!r)return;(0,Fz.touchRecentSessionOpen)(e.sessionId,e),ep("workspace"),r.id===eT?.id?ra(e.branch,e.sessionId):(e_(!0),e$.current={projectId:r.id,branch:e.branch,sessionId:e.sessionId},ez(r))}catch(e){console.error("Quick switcher navigation failed:",e),xN.toast.error("Failed to open session")}finally{rk.current=!1}}},[eT?.id,rC,ez,ra]);(0,$.useEffect)(()=>{if(eA||eO||eB)return;let e=Mf({projectId:eT?.id,tab:ef,branch:I,threadId:em}),r=e;if(F){let s=new URL(e,window.location.origin);s.searchParams.set("session",F),r=s.pathname+s.search}window.history.replaceState(null,"",r),(0,F8.saveLastLocation)(r)},[eT?.id,ef,I,em,eA,eO,eB,F]),(0,$.useEffect)(()=>{eO||(0,F8.settleRestoredLocation)(!eB)&&(P(null),window.history.replaceState(null,"","/"),window.dispatchEvent(new PopStateEvent("popstate")))},[eO,eB,P]);let rP=(0,$.useCallback)(e=>{eK(),P(e)},[eK,P]),rL=(0,$.useCallback)((e,r)=>{e.branch&&(Y(e),ee(r),el(!0))},[]),rz=(0,$.useCallback)(e=>{let r=Pe(null===e?void 0:eW.find(r=>r.branch===e),eT?.agent_mode??"local");"absent"===r.kind?er(r.missing):("creating"===r.kind&&xN.toast.info(`'${e}' is still being created on ${r.machineName}`),P(e))},[eW,eT?.agent_mode,P]),rO=(0,$.useCallback)(e=>{if(rS(!1),ep("workspace"),e.projectId===eT?.id)return void rz(e.branch);let r=eR.find(r=>r.id===e.projectId);r&&(ej(!0),e$.current={projectId:e.projectId,branch:e.branch,sessionId:null,checkPlacement:!0},ez(r))},[eT?.id,eR,rz,ez]),rB=(0,$.useRef)({content:"",at:0}),r$=(0,$.useCallback)(e=>{let r=Date.now(),s=rB.current;s.content===e&&r-s.at<600||(rB.current={content:e,at:r},tP.current?.sendMessage(e))},[]),rW=(0,$.useCallback)(()=>{let e=`Please perform the following git operations for this worktree:
|
|
41
|
+
- Before changing anything, read the design sections the step references and the existing code around it. Implement what is written, reuse the existing abstractions, and do not build a parallel one.
|
|
42
|
+
- Change only what is in scope for this step; the main branch must always build and run.`),i.push("## 4. Verify\n\nMeet every acceptance criterion of the step, and actually RUN the verification — do not just claim it passes.\n\n- Also run the project's own checks every session — typecheck, tests, lint, whatever its docs or scripts define.\n- If the environment truly cannot satisfy a check, use the fallback the plan gives, and say which check, why, and when it will be made up — in your final message and in the commit message.\n- A threshold or parameter the plan does not specify is not a blocker: pick a defensible default, keep it in one configurable place (a constants module or config), note the value and the reason in the commit body, and carry on."),i.push("## 5. Mark it done\n\nThe loop records completion from the `Item:` line of your final message (section 7); you do not have to edit the plan for that.\nIf the plan file itself tracks per-step status — a checkbox, a status line, a pass-condition flag — update that step's entry in the file's own convention once the criteria are really met. Otherwise leave the plan file alone.\nIf you cannot finish the step, do not report it as done; say why in your final message."),i.push("## 6. Commit\n\nCommit everything from this session — the code, and the plan file if you updated it — in ONE git commit:\n- Title like `<step number>: <summary>`.\n- Body: what was done, the key decisions, and the verification commands actually run with their results.\n\nThe session is not over until the commit is made. Do not push."),i.push("## 7. Report\n\n- Every step in the plan is done (none left outside the completed list): end with `Status: done`.\n- Something only a human can provide blocks the way (secrets, credentials, external accounts, a decision only a person can make): commit as usual, then end with `Status: blocked` and say exactly what is needed and where it goes (which environment variable or file). Do not work around it, do not fake secrets, and never write secrets into the repository.\n- Otherwise: end with `Status: continue`, set `Item:` to the step number, and `Remaining:` to the number of steps still not done."),i.join("\n\n")}(r):""}let IX=e=>`loop-draft:${e}`,IY=(0,$.createContext)({markReviewRunRead:()=>{}}),IG=IY.Provider,IJ=(0,eA.default)("alarm-clock",[["circle",{cx:"12",cy:"13",r:"8",key:"3y4lt7"}],["path",{d:"M12 9v4l2 2",key:"1c63tq"}],["path",{d:"M5 3 2 6",key:"18tl5t"}],["path",{d:"m22 6-3-3",key:"1opdir"}],["path",{d:"M6.38 18.7 4 21",key:"17xu3x"}],["path",{d:"M17.64 18.67 20 21",key:"kv2oe2"}]]),IZ=(0,eA.default)("pause",[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1",key:"kaeet6"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1",key:"1wsw3u"}]]),IQ=new Set(["preparing","waiting_reviewer","waiting_feedback","discussing","sending_feedback","waiting_rereview","running_task","waiting_resume"]),I0={ship:{text:"ship",className:"border-emerald-500/40 bg-emerald-500/10 text-emerald-700 dark:text-emerald-400"},"needs-changes":{text:"needs-changes",className:"border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-400"},"cannot-verify":{text:"cannot-verify",className:"border-border bg-muted text-muted-foreground"}};function I1(e){if(!e.loop_id)return null;let r=e.round??1,s=e.max_rounds?`第 ${r} / ${e.max_rounds} 轮`:`第 ${r} 轮`;return e.loop_manual?`${s} \xb7 已转人工`:s}function I2(e){return null!=e.max_rounds&&(e.round??1)>e.max_rounds}function I5(e){return e.map(e=>e.id).sort().join(",")}function I3({projectId:e,branch:r,runUpdate:s,streamEpoch:n,onRunsChange:i}){let[a,o]=(0,$.useState)([]),[l,c]=(0,$.useState)({}),[d,u]=(0,$.useState)({}),[h,f]=(0,$.useState)(null),[p,m]=(0,$.useState)(null),g=(0,$.useRef)(0),{markReviewRunRead:x}=(0,$.useContext)(IY),[v,y]=(0,$.useState)(()=>({projectId:e,branch:r}));(v.projectId!==e||v.branch!==r)&&(y({projectId:e,branch:r}),m(null));let b=(0,$.useRef)(0),w=(0,$.useRef)(null),_=(0,$.useRef)({projectId:e,branch:r});(0,$.useEffect)(()=>{_.current={projectId:e,branch:r}},[e,r]);let S=(0,$.useCallback)(async s=>{if(!e)return;let n=++b.current,a=Aq(e,r,s);try{let e=await a.request;if(n!==b.current)return;w.current={at:a.issuedAt,runs:e},o(e),i?.(e),m(r=>{if(!r)return r;let s=e.find(e=>e.id===r.runId)??null;return(s?.status??null)===r.status&&(s||I5(e)===r.signature)?r:null})}catch{}},[e,r,i]),j=(0,$.useRef)(null);(0,$.useEffect)(()=>{let e=null!==j.current&&j.current!==n;j.current=n,S({force:e})},[S,n]),(0,$.useEffect)(()=>{s&&S({force:!0})},[s,S]),(0,$.useEffect)(()=>{if(0===a.length)return;let e=setInterval(()=>void S({force:!0}),5e3);return()=>clearInterval(e)},[a.length,S]),(0,$.useEffect)(()=>{let e=()=>{"visible"===document.visibilityState&&S({force:!0})};return document.addEventListener("visibilitychange",e),window.addEventListener("online",e),()=>{document.removeEventListener("visibilitychange",e),window.removeEventListener("online",e)}},[S]);let k=async(s,n,i)=>{let a=++g.current;f(s),m(null);let o=null;try{await i()}catch(e){o=e instanceof Error?e.message:String(e)}finally{f(null),S({force:!0})}if(!o)return void x(s,{runEnded:"finalize"!==n&&"rereview"!==n&&"schedule"!==n});let l=null;if(e){let s=Aq(e,r,{force:!0}),n=await s.request.catch(()=>null),i=w.current;l=i&&i.at>=s.issuedAt?i.runs:n}if(_.current.projectId!==e||_.current.branch!==r||a!==g.current)return;let c=l?.find(e=>e.id===s)??null;m({runId:s,status:c?.status??null,message:(l?function(e,r){if("cancel"===e||"pause"===e||"resume"===e||"schedule"===e)return null;if(!r)return"这次 review 已经结束了 —— 反馈可能已经发出,或者 run 已被取消。";if("approve"===e){if("discussing"===r.status)return"reviewer 已进入讨论:先点「生成终稿」拿到新的结论,再发送反馈。";if("waiting_reviewer"===r.status)return"reviewer 正在重新出稿,等它完成后再发送。";if("sending_feedback"===r.status)return"反馈正在发送中。"}if("finalize"===e){if("waiting_feedback"===r.status)return"终稿已经出来了,直接发送反馈即可。";if("waiting_reviewer"===r.status)return"reviewer 正在出稿,稍候再试。"}if("accept"===e){if("discussing"===r.status)return"reviewer 已进入讨论:先点「生成终稿」拿到新的结论。";if("waiting_reviewer"===r.status)return"reviewer 正在重新出稿,等它完成后再决定。";if("sending_feedback"===r.status)return"反馈正在发送中。"}if("rereview"===e){if("waiting_rereview"===r.status)return null;if("waiting_reviewer"===r.status)return"复审已经发起,reviewer 正在审查。";if("waiting_feedback"===r.status)return"这一轮复审已经出结论了。"}return null}(n,c):null)??o,signature:I5(l??[])})},C=a.filter(e=>IQ.has(e.status)),N=p&&!C.some(e=>e.id===p.runId)?p:null;return 0!==C.length||N?(0,B.jsxs)("div",{className:"shrink-0 border-b bg-muted/30 px-4 py-2 space-y-2 max-h-[50vh] overflow-y-auto",children:[N&&(0,B.jsxs)("div",{className:"flex items-start justify-between gap-2 text-destructive",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,B.jsx)("span",{children:N.message}),(0,B.jsx)(Z.Button,{variant:"ghost",size:"icon-sm","aria-label":"关闭提示",onClick:()=>m(null),children:(0,B.jsx)(ro,{className:"h-3 w-3"})})]}),C.map(e=>"repeat"===e.kind?(0,B.jsx)(I8,{run:e,busy:h===e.id,error:p?.runId===e.id?p.message:null,onAction:r=>k(e.id,r,()=>"cancel"===r?rD.api.cancelWorkflowRun(e.id):rD.api.workflowRunGate(e.id,r)),onScheduleResume:r=>k(e.id,"schedule",()=>rD.api.scheduleResume(e.id,r))},e.id):(0,B.jsxs)("div",{className:"space-y-2",style:{fontSize:"var(--conv-font-size, 14px)"},children:[(0,B.jsxs)("div",{className:"flex items-center justify-between",children:[(0,B.jsxs)("span",{className:"font-medium",children:["Review",e.review_focus?` — ${e.review_focus}`:"",(0,B.jsxs)("span",{className:"ml-2 text-muted-foreground",children:["preparing"===e.status&&"准备中…","waiting_reviewer"===e.status&&"reviewer 审查中…","waiting_feedback"===e.status&&"等你确认反馈","discussing"===e.status&&"讨论中","sending_feedback"===e.status&&"发送中…","waiting_rereview"===e.status&&"等你确认复审"]}),I1(e)&&(0,B.jsx)("span",{className:"ml-2 text-muted-foreground",children:I1(e)})]}),(0,B.jsxs)(Z.Button,{variant:"ghost",size:"sm",disabled:h===e.id,onClick:()=>k(e.id,"cancel",()=>rD.api.cancelWorkflowRun(e.id)),children:[(0,B.jsx)(ro,{className:"h-3 w-3 mr-1"}),"结束"]})]}),e.error&&(0,B.jsx)("div",{className:"text-amber-600",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.error}),"preparing"===e.status&&(0,B.jsxs)("div",{className:"flex items-center text-muted-foreground",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,B.jsx)(a7,{className:"h-3 w-3 mr-1 animate-spin"})," 正在蒸馏上下文并启动 reviewer"]}),"waiting_reviewer"===e.status&&(0,B.jsxs)("div",{className:"flex items-center text-muted-foreground",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,B.jsx)(a7,{className:"h-3 w-3 mr-1 animate-spin"})," reviewer session 正在工作"]}),"discussing"===e.status&&(0,B.jsxs)("div",{className:"flex items-center gap-2",children:[(0,B.jsx)("span",{className:"text-muted-foreground",style:{fontSize:"var(--conv-font-size, 12px)"},children:"与 reviewer 讨论后,生成终稿再发送"}),(0,B.jsx)(Z.Button,{size:"icon-sm",variant:"outline","aria-label":"生成 review 终稿",disabled:h===e.id,onClick:()=>k(e.id,"finalize",()=>rD.api.workflowRunGate(e.id,"finalize")),children:(0,B.jsx)(Dm,{className:"h-3 w-3"})})]}),"waiting_rereview"===e.status&&(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)("div",{className:"text-muted-foreground",style:{fontSize:"var(--conv-font-size, 12px)"},children:I2(e)?`source 已按反馈完成修改。已达上限 ${e.max_rounds} 轮——要再加一轮吗?`:"source 已按反馈完成修改。由同一个 reviewer 复审这次修改?"}),(0,B.jsxs)("div",{className:"flex gap-2",children:[(0,B.jsx)(Z.Button,{size:"sm",disabled:h===e.id,onClick:()=>k(e.id,"rereview",()=>rD.api.workflowRunGate(e.id,"rereview",void 0,{extend:I2(e)})),children:I2(e)?"再加一轮":`发起第 ${e.round??2} 轮复审`}),(0,B.jsx)(Z.Button,{variant:"outline",size:"sm",disabled:h===e.id,onClick:()=>k(e.id,"cancel",()=>rD.api.cancelWorkflowRun(e.id)),children:"结束循环"})]})]}),"waiting_feedback"===e.status&&(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)("div",{className:"flex items-center gap-2",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,B.jsx)("span",{className:"text-muted-foreground",children:"reviewer 结论"}),e.verdict?(0,B.jsx)("span",{className:`rounded border px-1.5 py-px font-mono ${I0[e.verdict].className}`,children:I0[e.verdict].text}):(0,B.jsx)("span",{className:"rounded border border-dashed px-1.5 py-px text-muted-foreground",children:"未识别,请自行判断"})]}),d[e.id]?(0,B.jsx)(ry,{className:"font-mono min-h-28 max-h-72",style:{fontSize:"var(--conv-font-size, 12px)"},value:l[e.id]??e.feedback_snapshot??"",onChange:r=>c(s=>({...s,[e.id]:r.target.value}))}):(0,B.jsx)("div",{className:"border rounded-md bg-background px-3 py-2 max-h-72 overflow-y-auto",style:{fontSize:"var(--conv-font-size, 12px)"},children:(0,B.jsx)(c6,{children:l[e.id]??e.feedback_snapshot??""})}),(0,B.jsxs)("div",{className:"flex gap-2",children:["ship"===e.verdict&&(0,B.jsx)(Z.Button,{size:"sm",disabled:h===e.id,onClick:()=>k(e.id,"accept",()=>rD.api.workflowRunGate(e.id,"accept")),children:"接受并结束"}),(0,B.jsx)(Z.Button,{size:"sm",variant:"ship"===e.verdict?"outline":"default",disabled:h===e.id,onClick:()=>k(e.id,"approve",()=>rD.api.workflowRunGate(e.id,"approve",l[e.id]??void 0)),children:"ship"===e.verdict?"仍发送反馈":"发送反馈给原 session"}),(0,B.jsx)(Z.Button,{variant:"outline",size:"sm",disabled:h===e.id,onClick:()=>u(r=>({...r,[e.id]:!r[e.id]})),children:d[e.id]?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(SB,{className:"h-3 w-3 mr-1"}),"预览"]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(rN,{className:"h-3 w-3 mr-1"}),"编辑"]})})]})]}),p?.runId===e.id&&(0,B.jsx)("div",{className:"text-destructive",style:{fontSize:"var(--conv-font-size, 12px)"},children:p.message})]},e.id))]}):null}let I4=e=>String(e).padStart(2,"0");function I6(e){let r=new Date(e);return`${r.getFullYear()}-${I4(r.getMonth()+1)}-${I4(r.getDate())}T${I4(r.getHours())}:${I4(r.getMinutes())}`}function I7({busy:e,onSchedule:r,onClose:s}){let[n,i]=(0,$.useState)(""),[a,o]=(0,$.useState)(null),[l]=(0,$.useState)(()=>Date.now());return(0,B.jsxs)("div",{className:"space-y-1.5",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,B.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,B.jsx)("span",{className:"text-muted-foreground",children:"多久后继续:"}),(0,B.jsx)(Z.Button,{size:"sm",variant:"outline",disabled:e,onClick:()=>r(Date.now()+36e5),children:"+1h"}),(0,B.jsx)(Z.Button,{size:"sm",variant:"outline",disabled:e,onClick:()=>r(Date.now()+18e6),children:"+5h"}),(0,B.jsx)("input",{type:"datetime-local","aria-label":"自定继续时间",value:n,min:I6(l),max:I6(l+6048e5),onChange:e=>{i(e.target.value),o(null)},className:"h-7 rounded-md border bg-background px-1.5 text-xs"}),(0,B.jsx)(Z.Button,{size:"sm",variant:"outline",disabled:e||!n,onClick:()=>{let e=new Date(n).getTime(),s=Date.now();return n&&Number.isFinite(e)?e<=s?o("这个时间已经过去了"):e-s>6048e5?o("最多只能定在 7 天之内"):void r(e):o("先选一个时间")},children:"定在这个时间"}),(0,B.jsx)(Z.Button,{size:"sm",variant:"ghost",disabled:e,onClick:s,children:"取消"})]}),a&&(0,B.jsx)("div",{className:"text-destructive",children:a})]})}function I8({run:e,busy:r,error:s,onAction:n,onScheduleResume:i}){let[a,o]=(0,$.useState)(!1),[l,c]=(0,$.useState)(!1),[d,u]=(0,$.useState)(!1),h=(0,rD.repeatLoopParams)(e),f=Array.isArray(h?.doneItems)?h.doneItems:[],p=e.round??1,m="waiting_resume"===e.status,g=m&&h?.dispatchFailed===!0,x=m&&!g?Math.max(1,p-1):p,v=h?.stopAfterCurrent===!0,y=function(e){if(!e)return null;let r="plan"===e.kind?`Plan: ${e.fields?.planFile?.trim()||IH.defaults.planFile}`:"custom"===e.kind?"Custom":null;return r?e.edited?`${r}(已手改)`:r:null}(h?.preset),b=h?.handoffNote?.trim()||null,w=m&&"number"==typeof h?.resumeAt?h.resumeAt:null,_=async e=>{await i(e),u(!1)};return(0,B.jsxs)("div",{className:"space-y-2",style:{fontSize:"var(--conv-font-size, 14px)"},children:[(0,B.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,B.jsxs)("span",{className:"font-medium min-w-0 truncate",children:["Loop — ",h?.name??"Loop",(0,B.jsxs)("span",{className:"ml-2 text-muted-foreground",children:["preparing"===e.status&&"正在启动下一个 session…","running_task"===e.status&&(v?"做完这一项后暂停…":"处理中…"),m&&"已停下,等你决定"]}),(0,B.jsxs)("span",{className:"ml-2 text-muted-foreground",children:["第 ",x,e.max_rounds?` / ${e.max_rounds}`:""," 次"]})]}),(0,B.jsxs)(Z.Button,{variant:"ghost",size:"sm",disabled:r,onClick:()=>n("cancel"),title:"立即结束循环,并停掉正在运行的 session",children:[(0,B.jsx)(ro,{className:"h-3 w-3 mr-1"}),"结束"]})]}),y&&(0,B.jsx)("div",{className:"text-muted-foreground min-w-0 truncate",style:{fontSize:"var(--conv-font-size, 12px)"},title:y,children:y}),(f.length>0||h?.prevItem||h?.remaining)&&(0,B.jsxs)("div",{style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,B.jsxs)("div",{className:"flex flex-wrap items-center gap-x-1 text-muted-foreground",children:[f.length>0&&(0,B.jsxs)("button",{type:"button","aria-expanded":l,onClick:()=>c(e=>!e),className:"flex items-center hover:text-foreground",children:[l?(0,B.jsx)(aI,{className:"h-3 w-3 mr-1"}):(0,B.jsx)(ab,{className:"h-3 w-3 mr-1"}),"已完成 ",f.length," 项"]}),f.length>0&&h?.prevItem&&(0,B.jsx)("span",{children:"·"}),h?.prevItem&&(0,B.jsxs)("span",{children:["上一项:",h.prevItem]}),(f.length>0||h?.prevItem)&&h?.remaining&&(0,B.jsx)("span",{children:"·"}),h?.remaining&&(0,B.jsxs)("span",{children:["剩余:",h.remaining]})]}),l&&f.length>0&&(0,B.jsx)("ol",{"data-testid":"loop-done-items",className:"mt-1 max-h-60 list-decimal overflow-y-auto rounded-md border bg-background py-2 pl-8 pr-3 font-mono text-muted-foreground",children:f.map((e,r)=>(0,B.jsx)("li",{className:"break-words",children:e},r))})]}),b&&(0,B.jsxs)("div",{style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,B.jsxs)("button",{type:"button","aria-expanded":a,onClick:()=>o(e=>!e),className:"flex items-center text-muted-foreground hover:text-foreground",children:[a?(0,B.jsx)(aI,{className:"h-3 w-3 mr-1"}):(0,B.jsx)(ab,{className:"h-3 w-3 mr-1"}),"上一轮交接"]}),a&&(0,B.jsx)("pre",{"data-testid":"loop-handoff-note",className:"mt-1 max-h-60 overflow-y-auto whitespace-pre-wrap break-words rounded-md border bg-background px-3 py-2 font-mono text-muted-foreground",children:b})]}),e.error&&(0,B.jsx)("div",{className:"text-amber-600",style:{fontSize:"var(--conv-font-size, 12px)"},children:e.error}),"running_task"===e.status&&(0,B.jsxs)("div",{className:"flex items-center gap-2",children:[(0,B.jsxs)("span",{className:"flex items-center text-muted-foreground",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,B.jsx)(a7,{className:"h-3 w-3 mr-1 animate-spin"})," session「",h?.name??"Loop"," #",p,"」正在工作"]}),!v&&(0,B.jsxs)(Z.Button,{size:"sm",variant:"outline",disabled:r,onClick:()=>n("pause"),children:[(0,B.jsx)(IZ,{className:"h-3 w-3 mr-1"}),"做完这项后停"]})]}),m&&(0,B.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,B.jsxs)(Z.Button,{size:"sm",disabled:r,onClick:()=>n("resume"),children:[(0,B.jsx)(rS,{className:"h-3 w-3 mr-1"}),"继续循环"]}),null===w&&!d&&(0,B.jsxs)(Z.Button,{size:"sm",variant:"outline",disabled:r,onClick:()=>u(!0),children:[(0,B.jsx)(IJ,{className:"h-3 w-3 mr-1"}),"定时继续"]}),(0,B.jsx)("span",{className:"text-muted-foreground",style:{fontSize:"var(--conv-font-size, 12px)"},children:g?`第 ${p} 次迭代没能启动,没有对应的 session`:`相关 session:「${h?.name??"Loop"} #${x}」(见侧栏)`})]}),null!==w&&(0,B.jsxs)("div",{className:"flex items-center gap-1 text-muted-foreground",style:{fontSize:"var(--conv-font-size, 12px)"},children:[(0,B.jsx)(IJ,{className:"h-3 w-3"}),(0,B.jsxs)("span",{children:["将于 ",function(e,r=Date.now()){let s=new Date(e),n=`${I4(s.getHours())}:${I4(s.getMinutes())}`;return s.toDateString()===new Date(r).toDateString()?n:`${s.getMonth()+1}/${s.getDate()} ${n}`}(w)," 自动继续 ·"]}),(0,B.jsx)("button",{type:"button",disabled:r,onClick:()=>void _(null),className:"underline-offset-2 hover:text-foreground hover:underline disabled:opacity-50",children:"取消"})]}),m&&null===w&&d&&(0,B.jsx)(I7,{busy:r,onSchedule:e=>void _(e),onClose:()=>u(!1)}),s&&(0,B.jsx)("div",{className:"text-destructive",style:{fontSize:"var(--conv-font-size, 12px)"},children:s})]})}let I9=(0,eA.default)("repeat",[["path",{d:"m17 2 4 4-4 4",key:"nntrym"}],["path",{d:"M3 11v-1a4 4 0 0 1 4-4h14",key:"84bu3i"}],["path",{d:"m7 22-4-4 4-4",key:"1wqhfi"}],["path",{d:"M21 13v1a4 4 0 0 1-4 4H3",key:"1rx37r"}]]),Fe=()=>()=>{},Ft={"claude-code":"Claude Code",codex:"Codex"};function Fr(e,r,s){let n=Math.round(Number(e));return Number.isFinite(n)&&""!==e.trim()?Math.min(s,Math.max(1,n)):r}function Fs({projectId:e,branch:r,disabled:s,onStarted:n}){let[i,a]=(0,$.useState)(!1),[o,l]=(0,$.useState)(""),[c,d]=(0,$.useState)("plan"),[u,h]=(0,$.useState)(()=>({...IK("plan").defaults})),[f,p]=(0,$.useState)(()=>IV("plan",IK("plan").defaults)),[m,g]=(0,$.useState)(!1),[x,v]=(0,$.useState)("form"),[y,b]=(0,$.useState)(null),[w,_]=(0,$.useState)("claude-code"),[S,j]=(0,$.useState)(String(rD.REPEAT_LOOP_DEFAULT_ITERATIONS)),[k,C]=(0,$.useState)(String(rD.REPEAT_LOOP_DEFAULT_MINUTES)),[N,E]=(0,$.useState)(""),[D,R]=(0,$.useState)(!1),[T,A]=(0,$.useState)(()=>IK("plan").handoffByDefault),[M,I]=(0,$.useState)(!1),[F,P]=(0,$.useState)(null),[L,z]=(0,$.useState)(!1),[O,W]=(0,$.useState)(null),H=IK(c),q=H.fields.length>0,K=q&&m||!q&&""!==f.trim(),V=e=>{let r=IK(e);if(d(e),b(null),g(!1),A(r.handoffByDefault),0===r.fields.length)return void v("instruction");let s={...r.defaults,...u};h(s),p(IV(e,s)),v("form")},X=(e,r)=>{let s={...u,[e]:r};h(s),m||p(IV(c,s))},Y=r=>{r?(P(null),z(!1),b(null),W(null),R(!1),e&&(e=>{let r=function(e){try{let r=window.localStorage.getItem(IX(e));if(!r)return null;let s=JSON.parse(r);return s&&"object"==typeof s?s:null}catch{return null}}(e);if(!r)return;let s="custom"===r.kind?"custom":"plan",n=IK(s),i={...n.defaults,...r.fields??{}},a=n.fields.length>0&&!0===r.edited;d(s),h(i),g(a),p(n.fields.length>0&&!a?IV(s,i):r.prompt??""),v(n.fields.length>0&&!a?"form":"instruction"),("claude-code"===r.agentType||"codex"===r.agentType)&&_(r.agentType),"string"==typeof r.iterations&&j(r.iterations),"string"==typeof r.minutes&&C(r.minutes),"string"==typeof r.checkCommand&&E(r.checkCommand),A("boolean"==typeof r.handoff?r.handoff:n.handoffByDefault)})(e)):e&&function(e,r){try{window.localStorage.setItem(IX(e),JSON.stringify(r))}catch{}}(e,{kind:c,fields:u,prompt:f,edited:m,agentType:w,iterations:S,minutes:k,checkCommand:N,handoff:T}),a(r)},G=async e=>{try{return await rD.api.workflowRunGate(e.id,"pause"),!0}catch(r){return W({run:e,message:r instanceof Error?r.message:String(r)}),!1}},J=async()=>{if(O&&!M){I(!0);try{await G(O.run)&&(W(null),xN.toast.success("The loop will stop after its first item"),Y(!1))}finally{I(!1)}}},Q=async(s=T)=>{if(!e||!f.trim()||M||O)return;I(!0),P(null),z(!1);let i=function(e,r){let s=IK(e).fields.map(e=>e.key),n={};for(let e of s)r[e]?.trim()&&(n[e]=r[e]);return Object.keys(n).length?n:void 0}(c,u),a={kind:c,...i?{fields:i}:{},...q&&m?{edited:!0}:{}};try{let i=await rD.api.createRepeatLoop({projectId:e,branch:r,prompt:f.trim(),agentType:w,...o.trim()?{name:o.trim()}:{},maxIterations:Fr(S,rD.REPEAT_LOOP_DEFAULT_ITERATIONS,rD.REPEAT_LOOP_MAX_ITERATIONS),maxMinutes:Fr(k,rD.REPEAT_LOOP_DEFAULT_MINUTES,rD.REPEAT_LOOP_MAX_MINUTES),...N.trim()?{checkCommand:N.trim()}:{},preset:a,handoff:s});if(n?.(i),D&&!await G(i))return;l(""),Y(!1),xN.toast.success(D?"Loop started — it will stop after the first item":"Loop started")}catch(e){P(e instanceof Error?e.message:String(e)),z(s&&e?.code==="worker_unsupported")}finally{I(!1)}},ee=(0,$.useSyncExternalStore)(Fe,U,()=>!1),et=!f.trim()||M||null!==O;return(0,B.jsxs)(rl,{open:i,onOpenChange:Y,children:[(0,B.jsx)(rc,{asChild:!0,children:(0,B.jsx)(Z.Button,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:!e||s,title:s?"A loop is already running on this workspace":"New loop — repeat one instruction, a fresh session per item, until done","aria-label":"New loop",children:(0,B.jsx)(I9,{className:"h-3.5 w-3.5"})})}),(0,B.jsxs)(rf,{showCloseButton:!1,className:"max-h-[calc(100dvh-2rem)] w-[calc(100%-2rem)] min-w-0 gap-0 overflow-hidden bg-card p-0 grid-rows-[auto_minmax(0,1fr)_auto] sm:w-full sm:max-w-[560px]",onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&!et&&(e.preventDefault(),Q())},children:[(0,B.jsxs)("div",{className:"flex items-start gap-3 border-b bg-secondary px-4 py-3.5",children:[(0,B.jsx)("span",{className:"grid size-7 shrink-0 place-items-center rounded-lg border border-primary/20 bg-accent text-accent-foreground",children:(0,B.jsx)(I9,{className:"size-[15px]"})}),(0,B.jsxs)("div",{className:"min-w-0",children:[(0,B.jsx)(rg,{className:"text-[14.5px] font-semibold tracking-tight",children:"New loop"}),(0,B.jsx)(rx,{className:"mt-0.5 max-w-[46ch] text-[11.5px] leading-snug",children:"Runs the same instruction again and again, each time in a fresh session that handles one item, until a session reports there is nothing left."})]}),(0,B.jsxs)(ru,{className:"ml-auto grid size-6 shrink-0 place-items-center rounded-md border border-transparent text-muted-foreground/70 transition-colors hover:border-border hover:bg-muted hover:text-foreground",children:[(0,B.jsx)(ro,{className:"size-3.5"}),(0,B.jsx)("span",{className:"sr-only",children:"Close"})]})]}),(0,B.jsxs)("div",{className:"flex min-h-0 min-w-0 flex-col gap-[13px] overflow-x-hidden overflow-y-auto px-4 pt-3.5 pb-1",children:[(0,B.jsxs)("div",{className:"flex min-w-0 flex-col gap-[7px]",children:[(0,B.jsx)(mi,{trailing:(0,B.jsx)(ma,{label:"Preset",value:c,onChange:e=>{e!==c&&(IK(e).fields.length>0&&K?b({action:"switch",to:e}):V(e))},options:Iq.map(e=>({value:e.kind,label:e.label}))}),children:"Preset"}),(0,B.jsx)(mo,{children:H.description})]}),y&&(0,B.jsxs)(mc,{tone:"rose",icon:(0,B.jsx)(oI,{}),children:["regenerate"===y.action?"Regenerating replaces the instruction with the form's version — your edits are lost.":`Switching to ${IK(y.to).label} replaces the instruction — your text is lost.`," ",(0,B.jsxs)("span",{className:"inline-flex gap-2",children:[(0,B.jsx)(ml,{onClick:()=>"regenerate"===y.action?void(g(!1),b(null),p(IV(c,u))):V(y.to),children:"Discard my text"}),(0,B.jsx)(ml,{onClick:()=>b(null),children:"Keep it"})]})]}),q&&(0,B.jsx)("div",{role:"tablist","aria-label":"Instruction view",className:"flex min-w-0 gap-3 border-b",children:["form","instruction"].map(e=>(0,B.jsx)("button",{type:"button",role:"tab","aria-selected":x===e,onClick:()=>v(e),className:(0,eR.cn)("-mb-px border-b-2 px-0.5 pb-1.5 text-[12px] font-medium transition-colors",x===e?"border-primary text-foreground":"border-transparent text-muted-foreground hover:text-foreground"),children:"form"===e?"Form":"Instruction"},e))}),q&&m&&(0,B.jsxs)("div",{className:"flex items-start gap-2 rounded-lg border border-amber-500/30 bg-amber-500/10 px-2.5 py-2 text-[11.5px] leading-snug text-amber-700 dark:text-amber-300",children:[(0,B.jsx)(DS,{className:"mt-px size-[13px] shrink-0"}),(0,B.jsx)("span",{className:"min-w-0 flex-1",children:"Edited by hand — the form no longer applies; the instruction text is what runs."}),(0,B.jsxs)("button",{type:"button",onClick:()=>b({action:"regenerate"}),className:"inline-flex shrink-0 items-center gap-1 whitespace-nowrap underline-offset-2 hover:underline",children:[(0,B.jsx)(oP,{className:"size-3"}),"Regenerate from form"]})]}),q&&"form"===x&&(0,B.jsx)("fieldset",{disabled:m,className:"grid min-w-0 grid-cols-2 gap-x-2.5 gap-y-[13px] disabled:opacity-60",children:H.fields.map(e=>{let r=`loop-field-${e.key}`,s=e.multiline||"planFile"===e.key;return(0,B.jsxs)("div",{className:(0,eR.cn)("flex min-w-0 flex-col gap-[7px]",s&&"col-span-2"),children:[(0,B.jsx)(mi,{children:(0,B.jsx)("label",{htmlFor:r,children:e.label})}),e.multiline?(0,B.jsx)(ry,{id:r,value:u[e.key]??"",onChange:r=>X(e.key,r.target.value),placeholder:e.placeholder,spellCheck:!1,className:(0,eR.cn)(mr,"field-sizing-fixed min-h-[58px] min-w-0 max-w-full resize-y px-[11px] py-1.5 font-mono text-xs leading-[1.5] md:text-xs")}):(0,B.jsx)(rv,{id:r,value:u[e.key]??"",onChange:r=>X(e.key,r.target.value),placeholder:e.placeholder,spellCheck:!1,className:(0,eR.cn)(mr,"h-[34px] px-[11px] font-mono text-xs md:text-xs")}),e.hint&&(0,B.jsx)(mo,{children:e.hint})]},e.key)})}),(!q||"instruction"===x)&&(0,B.jsxs)("div",{className:"flex min-w-0 flex-col gap-[7px]",children:[(0,B.jsx)(mi,{note:f.trim()?void 0:"Required",children:(0,B.jsx)("label",{htmlFor:"loop-prompt",children:"Instruction"})}),(0,B.jsx)(ry,{id:"loop-prompt",value:f,onChange:e=>{p(e.target.value),q&&g(!0)},placeholder:"Fetch the unprocessed items from …, pick the first one, handle it, and mark it processed.\nIf none are left, say so.",className:(0,eR.cn)(mr,"field-sizing-fixed min-h-[118px] min-w-0 max-w-full resize-y overflow-auto px-[11px] py-2 font-mono text-xs leading-[1.55] md:text-xs",q&&"min-h-[220px]")}),!q&&(0,B.jsx)(mo,{children:"No session remembers the previous one: say where the next unprocessed item is found and how an item is marked done. Make handling an item safe to repeat — an interrupted item may be picked up again."})]}),(0,B.jsxs)("div",{className:"grid min-w-0 grid-cols-2 gap-x-2.5 gap-y-[13px]",children:[(0,B.jsxs)("div",{className:"flex min-w-0 flex-col gap-[7px]",children:[(0,B.jsx)(mi,{note:"Optional",children:(0,B.jsx)("label",{htmlFor:"loop-name",children:"Name"})}),(0,B.jsx)(rv,{id:"loop-name",value:o,onChange:e=>l(e.target.value),placeholder:"Loop",maxLength:80,className:(0,eR.cn)(mr,"h-[34px] px-[11px]")})]}),(0,B.jsxs)("div",{className:"flex min-w-0 flex-col gap-[7px]",children:[(0,B.jsx)(mi,{children:"Agent"}),(0,B.jsx)("div",{role:"radiogroup","aria-label":"Agent",className:"grid h-[34px] min-w-0 grid-cols-2 gap-0.5 rounded-[9px] border bg-secondary p-[3px]",children:Object.keys(Ft).map(e=>{let r=w===e;return(0,B.jsx)("button",{type:"button",role:"radio","aria-checked":r,onClick:()=>_(e),className:(0,eR.cn)("min-w-0 truncate rounded-md border border-transparent px-2 text-[12px] font-medium transition-colors",r?"border-border bg-card text-foreground shadow-xs":"text-muted-foreground hover:text-foreground"),children:Ft[e]},e)})})]}),(0,B.jsxs)("div",{className:"flex min-w-0 flex-col gap-[7px]",children:[(0,B.jsx)(mi,{children:(0,B.jsx)("label",{htmlFor:"loop-iterations",children:"Stop after"})}),(0,B.jsxs)(mn,{children:[(0,B.jsx)("input",{id:"loop-iterations",inputMode:"numeric",value:S,onChange:e=>j(e.target.value),"aria-label":"Stop after (items)",className:ms}),(0,B.jsx)("span",{className:"text-[11px] whitespace-nowrap text-muted-foreground/70",children:"items"})]})]}),(0,B.jsxs)("div",{className:"flex min-w-0 flex-col gap-[7px]",children:[(0,B.jsx)(mi,{children:(0,B.jsx)("label",{htmlFor:"loop-minutes",children:"Stop after"})}),(0,B.jsxs)(mn,{children:[(0,B.jsx)("input",{id:"loop-minutes",inputMode:"numeric",value:k,onChange:e=>C(e.target.value),"aria-label":"Stop after (minutes)",className:ms}),(0,B.jsx)("span",{className:"text-[11px] whitespace-nowrap text-muted-foreground/70",children:"minutes"})]})]})]}),(0,B.jsxs)("div",{className:"flex min-w-0 flex-col gap-[7px]",children:[(0,B.jsx)(mi,{note:"Optional",children:(0,B.jsx)("label",{htmlFor:"loop-check",children:"Check command"})}),(0,B.jsxs)(mn,{children:[(0,B.jsx)(mL,{}),(0,B.jsx)("input",{id:"loop-check",value:N,onChange:e=>E(e.target.value),placeholder:"npm test",spellCheck:!1,className:(0,eR.cn)(ms,"font-mono text-xs tracking-tight")})]}),(0,B.jsx)(mo,{children:"Runs in the worktree after each item; a non-zero exit stops the loop."})]}),(0,B.jsxs)("label",{className:"flex min-w-0 items-start gap-2 text-[12px] leading-snug",children:[(0,B.jsx)("input",{type:"checkbox",id:"loop-handoff",checked:T,onChange:e=>A(e.target.checked),className:"mt-0.5 size-3.5 shrink-0 accent-primary"}),(0,B.jsxs)("span",{className:"min-w-0",children:["Keep a handoff note between sessions",(0,B.jsx)("span",{className:"block text-[10.5px] text-muted-foreground/80",children:"Each session ends with a short note — lessons learned, what it did, what to watch — and the loop hands it to the next session. Nothing is written to the repo."})]})]}),(0,B.jsxs)("label",{className:"flex min-w-0 items-start gap-2 text-[12px] leading-snug",children:[(0,B.jsx)("input",{type:"checkbox",id:"loop-run-once",checked:D,onChange:e=>R(e.target.checked),className:"mt-0.5 size-3.5 shrink-0 accent-primary"}),(0,B.jsxs)("span",{className:"min-w-0",children:["Run one item first, then decide",(0,B.jsx)("span",{className:"block text-[10.5px] text-muted-foreground/80",children:"The loop stops at a gate after the first item; read its session, then continue or end the loop."})]})]}),(0,B.jsxs)("div",{className:"flex items-start gap-2 rounded-lg border border-amber-500/30 bg-amber-500/10 px-2.5 py-2 text-[11.5px] leading-snug text-amber-700 dark:text-amber-300",children:[(0,B.jsx)(oI,{className:"mt-px size-[13px] shrink-0"}),(0,B.jsx)("span",{className:"min-w-0",children:"Sessions run in edit mode with no confirmation between items. The loop stops on its own when an item is blocked, fails, or a limit is reached — and you can stop it any time."})]}),F&&(0,B.jsxs)(mc,{tone:"rose",icon:(0,B.jsx)(oI,{}),children:[F,L&&(0,B.jsxs)(B.Fragment,{children:[" ",(0,B.jsx)(ml,{onClick:()=>{A(!1),Q(!1)},disabled:M,children:"Turn off handoff note and retry"})]})]}),O&&(0,B.jsxs)(mc,{tone:"rose",icon:(0,B.jsx)(oI,{}),children:["The loop started, but the pause could not be set — it is still running item after item. (",O.message,")"," ",(0,B.jsx)(ml,{onClick:()=>void J(),disabled:M,children:"Retry pause"})]})]}),(0,B.jsxs)("div",{className:"mt-2.5 flex min-w-0 items-center gap-2.5 overflow-hidden border-t bg-secondary px-4 py-2.5",children:[(0,B.jsxs)("span",{className:"flex min-w-0 flex-1 items-center gap-1.5 overflow-hidden text-[11px] text-muted-foreground",children:[(0,B.jsx)(aF,{className:"size-3 shrink-0 text-muted-foreground/70"}),(0,B.jsxs)("span",{className:"truncate",children:["Runs on ",(0,B.jsx)("span",{className:"font-mono",children:r??"main"})]})]}),(0,B.jsx)(ru,{asChild:!0,children:(0,B.jsx)(Z.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",children:O?"Close":"Cancel"})}),(0,B.jsx)(Z.Button,{size:"sm",className:"h-7 gap-1.5 text-xs","aria-label":"Start loop",onClick:()=>void Q(),disabled:et,children:M?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(a7,{className:"size-3 animate-spin"}),"Starting…"]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(I9,{className:"size-3"}),"Start loop",(0,B.jsx)("kbd",{className:"rounded border border-background/30 bg-background/15 px-1 font-mono text-[10px] leading-[1.4] text-background/90",title:ee?"Command+Enter":"Ctrl+Enter",children:ee?"⌘⏎":"Ctrl⏎"})]})})]})]})]})}let Fn=(0,eA.default)("radio",[["path",{d:"M16.247 7.761a6 6 0 0 1 0 8.478",key:"1fwjs5"}],["path",{d:"M19.075 4.933a10 10 0 0 1 0 14.134",key:"ehdyv1"}],["path",{d:"M4.925 19.067a10 10 0 0 1 0-14.134",key:"1q22gi"}],["path",{d:"M7.753 16.239a6 6 0 0 1 0-8.478",key:"r2q7qm"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]]),Fi=(0,eA.default)("hourglass",[["path",{d:"M5 22h14",key:"ehvnwv"}],["path",{d:"M5 2h14",key:"pdyrp9"}],["path",{d:"M17 22v-4.172a2 2 0 0 0-.586-1.414L12 12l-4.414 4.414A2 2 0 0 0 7 17.828V22",key:"1d314k"}],["path",{d:"M7 2v4.172a2 2 0 0 0 .586 1.414L12 12l4.414-4.414A2 2 0 0 0 17 6.172V2",key:"1vvvr6"}]]);function Fa({messages:e}){let{scrollToBottom:r}=dl(),s=(0,$.useRef)(e.length);return(0,$.useEffect)(()=>{let n=s.current;if(s.current=e.length,!(e.length<=n))for(let s=n;s<e.length;s++){let n=e[s];if("user"===n.type&&n.content.startsWith("[Executor Event:"))return void r({animation:"instant"})}},[e,r]),null}let Fo=(0,$.forwardRef)(function({projectId:e,branch:r},s){let{session:n,messages:i,status:a,isInitialized:o,isLoading:l,error:c,sendMessage:d,stopGeneration:u,restartSession:h,workflowRunUpdate:f,turnState:p,streamEpoch:m,draft:g,setDraft:x,setEventListening:v}=function(e,r){let s=e?Iw(e,r):null,[n,i]=(0,$.useState)(()=>e?new IN(e,r):null);return(n?.key??null)!==s&&i(e?new IN(e,r):null),(0,$.useEffect)(()=>{if(n)return n.start(),()=>n.stop()},[n]),{...(0,$.useSyncExternalStore)(n?.subscribe??IE,n?.getSnapshot??ID,n?.getSnapshot??ID),sendMessage:n?.sendMessage??IR,stopGeneration:n?.stopGeneration??IR,restartSession:n?.restartSession??IR,setDraft:n?.setDraft??IT,setEventListening:n?.setEventListening??IR}}(e,r),{settings:y}=(0,dh.useConversationSettings)(),[b,w]=(0,$.useState)([]),_=(0,$.useMemo)(()=>(function(e){let r=new Map,s=null,n=!1,i=!1;for(let[a,o]of e.entries())if("tool_result"===o.type&&"setPlan"===o.tool){let e=IM(o.output);if(!e?.planId)continue;r.set(e.planId,{plan:e,firstIndex:r.get(e.planId)?.firstIndex??a}),s={key:`plan:${e.planId}`,plan:e},n=!1,i=!1}else if("tool_approval_request"===o.type&&"setPlan"===o.tool){let e=IA(o.input);e&&(s={key:`approval:${o.approvalId}`,plan:e,approval:o}),n=!1}else"system"===o.type&&o.content.startsWith(Iz)?n=!0:"user"===o.type&&"commander"!==o.origin&&(n=!1,i=!0,s&&!s.approval&&I$(s.plan)&&(s=null));if(s&&n&&!s.approval&&(s={...s,stalled:!0}),s&&i&&!s.approval&&s.plan.waitingOn){let{waitingOn:e,...r}=s.plan;s={...s,plan:r}}return{current:s,history:r}})(i),[i]);(0,$.useImperativeHandle)(s,()=>({sendMessage:async e=>{let r=e.trim();r&&await d(r)}}),[d]);let S=n?.eventListeningEnabled??!1,j="running"===a,k="waiting"===a,C=kq(e),N=(0,$.useMemo)(()=>[...C.values()].filter(e=>(e.branch??null)===(r??null)),[C,r]),E=(0,$.useCallback)(async e=>{try{await rD.api.startExecutor(e.executorId,e.remoteServerId,"retrying"===e.state?e.processId:void 0)}catch(e){if(e instanceof rD.ExecutorProcessRequestError&&"start_unknown"===e.body.code&&e.body.retrying)return;if(e instanceof rD.ExecutorProcessRequestError&&"retry_ended"===e.body.code)return void xN.toast.info("Already settled",{description:e.message});xN.toast.error("Executor not started",{description:e instanceof Error?e.message:String(e)})}},[]),D=(0,$.useCallback)(async e=>{let r=e.text.trim();r&&(x(""),await d(r))},[d,x]);return e?(0,B.jsxs)("div",{className:"h-full flex flex-col min-h-0",style:{"--conv-font-size":`${y.chatFontSize}px`},children:[(0,B.jsxs)("div",{className:"flex-shrink-0 flex items-center justify-between px-4 h-10 border-b border-border/60 bg-muted/20",children:[(0,B.jsxs)("div",{className:"flex items-center gap-2",children:[(0,B.jsx)(sx,{className:"h-3.5 w-3.5 text-primary"}),(0,B.jsx)("span",{className:"text-xs font-medium text-foreground",children:"Main Chat"}),j&&(0,B.jsx)(a7,{className:"h-3 w-3 animate-spin text-primary/60"}),k&&(0,B.jsx)(Fi,{className:"h-3 w-3 text-primary/60","aria-label":"Waiting for results"})]}),n&&(0,B.jsxs)("div",{className:"flex items-center gap-1",children:[(0,B.jsx)(Z.Button,{variant:"ghost",size:"icon",onClick:async()=>{try{await v(!S)}catch{xN.toast.error("Failed to toggle event listening")}},className:`h-7 w-7 ${S?"text-amber-500":""}`,title:S?"Listening to events from runs Commander did not start (click to disable)":"Also listen to events from runs Commander did not start (click to enable)",children:(0,B.jsx)(Fn,{className:"h-3.5 w-3.5"})}),(0,B.jsx)(Fs,{projectId:e,branch:r,disabled:b.some(e=>"repeat"===e.kind)}),(0,B.jsx)(Z.Button,{variant:"ghost",size:"icon",onClick:()=>h(),disabled:j,className:"h-7 w-7",title:"New Conversation",children:(0,B.jsx)(AX,{className:"h-3.5 w-3.5"})})]})]}),(0,B.jsx)(I3,{projectId:e,branch:r,runUpdate:f,streamEpoch:m,onRunsChange:w}),(0,B.jsxs)(dc,{className:"flex-1 min-h-0",initial:"instant",children:[(0,B.jsx)(Fa,{messages:i}),(0,B.jsxs)(dd,{className:"gap-4 p-4",children:[l&&0===i.length&&(0,B.jsx)("div",{className:"flex items-center justify-center py-8",children:(0,B.jsx)(a7,{className:"h-6 w-6 animate-spin text-muted-foreground"})}),!l&&o&&0===i.length&&(0,B.jsxs)("div",{className:"text-center py-16",children:[(0,B.jsx)("div",{className:"mx-auto w-12 h-12 rounded-xl bg-primary/10 flex items-center justify-center mb-4",children:(0,B.jsx)(sx,{className:"h-6 w-6 text-primary/60"})}),(0,B.jsx)("h3",{className:"text-sm font-semibold mb-1 text-foreground",children:"Start a conversation"}),(0,B.jsx)("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"Chat with the AI assistant about your project"})]}),i.map((s,i)=>{if("turn_end"===s.type)return(0,B.jsxs)("div",{className:"mx-4 my-3 flex items-center gap-2","aria-hidden":!0,children:[(0,B.jsx)("div",{className:"h-px flex-1 bg-border"}),(0,B.jsx)("div",{className:"h-1 w-1 shrink-0 rounded-full bg-border"}),(0,B.jsx)("div",{className:"h-px flex-1 bg-border"})]},i);if("user"===s.type&&(s.content.startsWith("[System Invariant Violation]")||s.content.startsWith(IB))){let e=s.content.startsWith(IB),r=s.content.replace(/^\[(System Invariant Violation|Plan Continuation)\]\n?/,"");return(0,B.jsxs)("div",{className:"mx-4 my-2 flex gap-2 rounded-md border border-amber-500/30 bg-amber-500/10 px-3 py-2",children:[(0,B.jsx)(oI,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-500"}),(0,B.jsxs)("div",{className:"min-w-0",children:[(0,B.jsx)("div",{className:"text-xs font-medium text-amber-600 dark:text-amber-400",children:e?"Plan continuation":"System invariant correction"}),(0,B.jsx)("div",{className:"mt-0.5 whitespace-pre-wrap text-muted-foreground",style:{fontSize:"var(--conv-font-size, 12px)"},children:r})]})]},i)}if("user"===s.type){let n=s.event,a=n?.kind==="agent_task_completed"&&b.some(e=>e.source_session_id===n.sessionId||e.reviewer_session_id===n.sessionId);return(0,B.jsxs)("div",{children:[(0,B.jsx)(c3,{from:"user",children:(0,B.jsx)(c4,{style:{fontSize:"var(--conv-font-size, 14px)"},children:s.content})}),n?.kind==="agent_task_completed"&&(0,B.jsx)("div",{className:"mt-1 flex justify-end",children:(0,B.jsx)(Z.Button,{variant:"outline",size:"sm",disabled:a,title:a?"该 session 已在一个进行中的 review 里":void 0,onClick:async()=>{if(e)try{await rD.api.createWorkflowRun({projectId:e,branch:r,sourceSessionId:n.sessionId,sourceTurnEndIndex:n.turnEndEntryIndex})}catch(e){alert(e instanceof Error?e.message:String(e))}},children:"Review"})})]},i)}if("assistant"===s.type)return(0,B.jsx)(c3,{from:"assistant",children:(0,B.jsx)(c4,{style:{fontSize:"var(--conv-font-size, 14px)"},children:(0,B.jsx)(c6,{children:s.content})})},i);if("tool_use"===s.type)return"setPlan"===s.tool?null:(0,B.jsxs)("div",{className:"flex items-center gap-2 px-4 py-2 text-xs text-muted-foreground",children:[(0,B.jsx)(oo,{className:"w-3.5 h-3.5 animate-pulse"}),(0,B.jsx)("span",{children:function(e){switch(e){case"getExecutorStatus":return"Checking executor status...";case"getAgentConversation":return"Checking agent conversation...";case"listTerminals":return"Listing terminals...";case"runInTerminal":return"Sending command to terminal...";case"spawnAgentSession":return"Starting a coding agent...";case"sendToAgentSession":return"Sending a message to the agent...";default:return`Running ${e}...`}}(s.tool)})]},i);if("tool_result"===s.type){if("setPlan"===s.tool){let e=IM(s.output);if(e?.planId){if(_.current?.plan.planId===e.planId)return null;let r=_.history.get(e.planId);return r&&r.firstIndex===i?(0,B.jsx)("div",{className:"mx-4 my-2",children:(0,B.jsx)(IP,{plan:r.plan})},i):null}}return(0,B.jsx)("div",{className:"px-4 py-2",children:(0,B.jsxs)("details",{className:"text-xs text-muted-foreground",children:[(0,B.jsx)("summary",{className:"cursor-pointer hover:text-foreground",children:"Tool result"}),(0,B.jsx)("pre",{className:"mt-1 p-2 bg-muted/50 rounded overflow-x-auto whitespace-pre-wrap",style:{fontSize:"var(--conv-font-size, 12px)"},children:s.output})]})},i)}if("tool_approval_request"===s.type)return("setPlan"!==s.tool||"approved"!==s.resolved&&_.current?.approval?.approvalId!==s.approvalId)&&n?(0,B.jsx)(IL,{sessionId:n.id,approvalId:s.approvalId,tool:s.tool,input:s.input,resolved:s.resolved},i):null;if("system"===s.type&&(s.content.startsWith(Iz)||s.content.startsWith(IO))){let e=s.content.startsWith(Iz)?Iz:IO;return(0,B.jsxs)("div",{className:"mx-4 my-2 flex gap-2 rounded-md border border-amber-500/40 bg-amber-500/10 px-3 py-2",children:[(0,B.jsx)(oI,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-500"}),(0,B.jsxs)("div",{className:"min-w-0",children:[(0,B.jsx)("div",{className:"text-xs font-medium text-amber-600 dark:text-amber-400",children:e===Iz?"Plan stalled":"Commander stalled"}),(0,B.jsx)("div",{className:"mt-0.5 whitespace-pre-wrap text-muted-foreground",style:{fontSize:"var(--conv-font-size, 12px)"},children:s.content.slice(e.length).trim()})]})]},i)}return"error"===s.type?(0,B.jsx)("div",{className:"mx-auto max-w-[90%] rounded-lg border border-destructive/50 bg-destructive/10 px-4 py-3 text-destructive",style:{fontSize:"var(--conv-font-size, 14px)"},children:s.message},i):null}),c&&(0,B.jsx)("div",{className:"mx-auto max-w-[90%] rounded-lg border border-destructive/50 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:c})]}),(0,B.jsx)(du,{})]}),(0,B.jsxs)("div",{className:"flex-shrink-0 py-3 px-[22px]",children:[N.map(e=>(0,B.jsx)(kK,{delivery:e,showExecutorName:!0,onRetry:()=>E(e),className:"mb-2"},e.processId)),k&&p.waitingFor.length>0&&(0,B.jsxs)("div",{className:"mb-2 flex items-start gap-1.5 text-xs text-muted-foreground","data-testid":"turn-waiting-for",children:[(0,B.jsx)(Fi,{className:"mt-0.5 h-3 w-3 shrink-0"}),(0,B.jsxs)("span",{children:["Waiting for ",p.waitingFor.join(", ")]})]}),_.current&&n&&(0,B.jsx)(IW,{task:_.current,sessionId:n.id},_.current.key),(j||k)&&(0,B.jsx)("div",{className:"flex justify-center mb-2",children:(0,B.jsxs)(Z.Button,{variant:"outline",size:"sm",onClick:u,className:"gap-1.5",children:[(0,B.jsx)(cb,{className:"h-3 w-3"}),j?"Stop generating":"Stop"]})}),(0,B.jsxs)(Aj,{onSubmit:D,className:"w-full",children:[(0,B.jsx)(Ak,{disabled:!o||j,placeholder:o?j?"Waiting for response...":k?"Still on it — add to the task...":"Type a message...":"Connecting...",className:"pr-12",style:{fontSize:"var(--conv-font-size, 14px)"},value:g,onChange:e=>x(e.currentTarget.value)}),(0,B.jsx)("div",{className:"pointer-events-none absolute bottom-0 right-2 flex items-center text-base md:text-sm",style:{fontSize:"var(--conv-font-size, 14px)",height:"calc(1lh + 1.5rem)"},children:(0,B.jsx)(AM,{className:"pointer-events-auto",disabled:!o||j||!g.trim()})})]})]})]}):(0,B.jsx)("div",{className:"h-full flex items-center justify-center text-muted-foreground",children:(0,B.jsxs)("div",{className:"text-center",children:[(0,B.jsx)("div",{className:"mx-auto w-10 h-10 rounded-xl bg-muted flex items-center justify-center mb-3",children:(0,B.jsx)(sx,{className:"h-5 w-5 text-muted-foreground/50"})}),(0,B.jsx)("p",{className:"text-sm",children:"Select a project to start chatting"})]})})}),Fl=(0,eA.default)("archive-restore",[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h2",key:"tvwodi"}],["path",{d:"M20 8v11a2 2 0 0 1-2 2h-2",key:"1gkqxj"}],["path",{d:"m9 15 3-3 3 3",key:"1pd0qc"}],["path",{d:"M12 12v9",key:"192myk"}]]),Fc="grid-cols-[minmax(0,1fr)_88px_176px_44px_56px] @max-3xl:grid-cols-[minmax(0,1fr)_88px_44px_56px] @max-lg:grid-cols-[minmax(0,1fr)_44px_56px]",Fd="@max-3xl:hidden",Fu="@max-lg:hidden",Fh="relative grid items-center gap-x-3 rounded-[7px] px-2";function Ff({task:e,onUpdate:r,onDelete:s,onArchive:n,onUnarchive:i,archivedView:a,onClick:o,worktrees:l,assignedBranches:c,onAssign:d,onOpenSourceSession:u,selected:h,flash:f,compact:p,depth:m=0,progress:g}){let x="done"===e.status||"cancelled"===e.status,v=m>0,y=!p&&!v&&(e.description||e.source_session),b=e=>e.stopPropagation();return(0,B.jsxs)("div",{role:"row","data-task-id":e.id,"data-state":h?"selected":void 0,onClick:()=>o?.(e),className:(0,eR.cn)(Fh,"group cursor-pointer hover:bg-muted",p?"min-h-[34px] grid-cols-[minmax(0,1fr)_auto]":Fc,!p&&(v?"min-h-[34px] py-[3px]":"min-h-[46px] py-1.5"),"data-[state=selected]:bg-accent data-[state=selected]:hover:bg-accent data-[state=selected]:shadow-[inset_0_0_0_1px_color-mix(in_oklab,var(--primary)_14%,transparent)]",f&&"animate-task-row-flash"),children:[(0,B.jsxs)("div",{className:(0,eR.cn)("flex min-w-0 gap-[9px]",p||!y?"items-center":"items-start"),style:v?{paddingLeft:23+(m-1)*20}:void 0,children:[(0,B.jsx)(aB,{status:e.status,onChange:s=>r(e.id,{status:s}),children:(0,B.jsx)("button",{type:"button","aria-label":`Status: ${e.status}`,onClick:b,className:(0,eR.cn)("shrink-0 rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring/50",y&&"mt-[2.5px]"),children:(0,B.jsx)(aP,{status:e.status})})}),(0,B.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,B.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,B.jsx)("span",{className:(0,eR.cn)("min-w-0 truncate text-[13px]",x?"font-[450] text-muted-foreground line-through decoration-border":v?"font-[450] text-secondary-foreground":"font-medium"),children:e.title}),g&&g.total>0&&(0,B.jsx)(aO,{done:g.done,total:g.total}),f&&(0,B.jsx)("span",{className:"shrink-0 rounded px-[5px] font-mono text-[10px] font-medium text-[oklch(0.6_0.14_152)] bg-[oklch(0.94_0.05_152)] dark:bg-[oklch(0.6_0.14_152/0.18)]",children:"new"})]}),y&&(0,B.jsxs)("div",{className:"mt-px flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground",children:[e.description&&(0,B.jsx)("span",{className:"min-w-0 truncate",children:sN(e.description,240)}),e.description&&e.source_session&&(0,B.jsx)("span",{className:"shrink-0 text-border","aria-hidden":!0,children:"·"}),e.source_session&&(0,B.jsx)("span",{className:"flex min-w-0 max-w-[210px] shrink-0 [&_svg]:size-[11px]",onClick:b,children:(0,B.jsx)(sv,{source:e.source_session,onOpen:u?()=>u(e):void 0})})]})]})]}),p?(0,B.jsxs)("div",{className:"flex items-center gap-2.5 text-muted-foreground/70",children:[null!==e.assigned_branch&&(0,B.jsx)("span",{title:sk(e.assigned_branch),className:"inline-flex",children:(0,B.jsx)(aF,{className:"size-3","aria-label":`Branch ${sk(e.assigned_branch)}`})}),(0,B.jsx)(az,{priority:e.priority})]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(a$,{priority:e.priority,onChange:s=>r(e.id,{priority:s}),children:(0,B.jsxs)("button",{type:"button",onClick:b,className:(0,eR.cn)("-mx-1.5 flex w-fit items-center gap-[7px] rounded-md px-1.5 py-1 text-xs text-secondary-foreground outline-none hover:bg-background hover:shadow-[inset_0_0_0_1px_var(--border)] data-[state=open]:bg-background data-[state=open]:shadow-[inset_0_0_0_1px_var(--border)]",Fu),children:[(0,B.jsx)(az,{priority:e.priority}),s_[e.priority].label]})}),(0,B.jsx)("div",{className:(0,eR.cn)("flex min-w-0",Fd),children:(0,B.jsx)(aY,{current:e.assigned_branch,onAssign:r=>d(e.id,r),worktrees:l,assignedBranches:c,children:(0,B.jsx)("button",{type:"button",onClick:b,className:"flex min-w-0 max-w-full rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ring/50",title:null!==e.assigned_branch?void 0:"Assign a branch",children:null!==e.assigned_branch?(0,B.jsx)(aX,{branch:e.assigned_branch,className:"hover:border-border"}):(0,B.jsx)("span",{className:"text-xs text-muted-foreground/70 hover:text-muted-foreground",children:"—"})})})}),(0,B.jsx)("span",{className:"text-right font-mono text-[11px] text-muted-foreground/70",title:new Date(e.created_at).toLocaleString(),children:sD(e.created_at)}),(0,B.jsxs)("div",{className:"flex justify-end gap-0.5 opacity-0 transition-opacity group-hover:opacity-100 focus-within:opacity-100",onClick:b,children:[a?(0,B.jsx)(Fp,{title:"Unarchive",onClick:()=>i(e.id),children:(0,B.jsx)(Fl,{className:"size-[13px]"})}):(0,B.jsx)(Fp,{title:"Archive",onClick:()=>n(e.id),children:(0,B.jsx)(on,{className:"size-[13px]"})}),(0,B.jsx)(Fp,{title:"Delete",onClick:()=>s(e.id),children:(0,B.jsx)(rb,{className:"size-[13px]"})})]})]})]})}function Fp({title:e,onClick:r,children:s}){return(0,B.jsx)("button",{type:"button",title:e,"aria-label":e,onClick:r,className:"grid size-[26px] place-items-center rounded-md text-muted-foreground outline-none hover:bg-border/60 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50",children:s})}function Fm({pending:e,compact:r}){return(0,B.jsxs)("div",{role:"row","data-pending-task":!0,"aria-busy":!0,className:(0,eR.cn)(Fh,"cursor-default",r?"min-h-[34px] grid-cols-[minmax(0,1fr)_auto]":(0,eR.cn)(Fc,"min-h-[46px] py-1.5")),children:[(0,B.jsxs)("div",{className:(0,eR.cn)("flex min-w-0 gap-[9px]",r?"items-center":"items-start"),children:[(0,B.jsx)(aP,{status:e.status,pending:!0,className:r?void 0:"mt-[2.5px]"}),(0,B.jsxs)("div",{className:"min-w-0 flex-1",children:[null!==e.title?(0,B.jsx)("span",{className:"block truncate text-[13px] font-medium",children:e.title}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(C6,{className:"my-[5px] h-[9px] w-[46%] max-w-64"}),(0,B.jsx)("span",{className:"sr-only",children:"Generating title…"})]}),!r&&(0,B.jsx)("div",{className:"mt-px truncate text-xs text-muted-foreground",children:sN(e.description,1/0)})]})]}),r?(0,B.jsx)(az,{priority:e.priority,className:"opacity-55"}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)("div",{className:(0,eR.cn)("flex items-center gap-[7px] text-xs text-secondary-foreground opacity-55",Fu),children:[(0,B.jsx)(az,{priority:e.priority}),s_[e.priority].label]}),(0,B.jsx)(C6,{className:(0,eR.cn)("h-[9px] w-[90px]",Fd)}),(0,B.jsx)(C6,{className:"h-[9px] w-[26px] justify-self-end"}),(0,B.jsx)("span",{})]})]})}function Fg({rows:e,allTasks:r,sort:s,onSortChange:n,onUpdate:i,onDelete:a,onArchive:o,onUnarchive:l,archivedView:c,worktrees:d,onAssign:u,onOpenSourceSession:h,panelOpen:f,selectedTaskId:p,onSelect:m,onStep:g,pendingTasks:x,flashTaskId:v,keyboardActive:y,assignedBranches:b}){let w=(0,$.useRef)(null),_=e=>{s?.field!==e?n({field:e,dir:"asc"}):"asc"===s.dir?n({field:e,dir:"desc"}):n(null)},S=(0,$.useMemo)(()=>{let e=new Map;for(let s of r){if(!s.parent_id||null!==s.archived_at||"cancelled"===s.status)continue;let r=e.get(s.parent_id)??{done:0,total:0};r.total+=1,"done"===s.status&&(r.done+=1),e.set(s.parent_id,r)}return e},[r]),j=(0,$.useMemo)(()=>{let r=[];for(let s of e){let e=r[r.length-1];s.depth>0&&e?e.kids.push(s):r.push({root:s,kids:[]})}return r},[e]);(0,$.useEffect)(()=>{if(!f||!y)return;let r=r=>{if(!(r.defaultPrevented||r.metaKey||r.ctrlKey||r.altKey||d3(r.target)||uo())){if("Escape"===r.key){r.preventDefault(),m(null);return}null===p||"ArrowDown"!==r.key&&"ArrowUp"!==r.key||0!==e.length&&(r.preventDefault(),g("ArrowDown"===r.key?1:-1))}};return window.addEventListener("keydown",r,!0),()=>window.removeEventListener("keydown",r,!0)},[f,p,m,g,e.length,y]);let k=v??p;(0,$.useEffect)(()=>{if(null===k)return;let e=w.current?.querySelectorAll("[data-task-id]")??[];Array.from(e).find(e=>e.dataset.taskId===k)?.scrollIntoView({block:"nearest"})},[k]);let C=({task:e,depth:r})=>(0,B.jsx)(Ff,{task:e,depth:r,progress:S.get(e.id),onUpdate:i,onDelete:a,onArchive:o,onUnarchive:l,archivedView:c,onClick:e=>m(e.id===p?null:e.id),selected:e.id===p,flash:e.id===v,compact:f,worktrees:d,assignedBranches:b,onAssign:u,onOpenSourceSession:h},e.id);return(0,B.jsxs)("div",{ref:w,role:"grid","aria-label":"Tasks",className:"flex flex-col gap-px px-3 pt-2 pb-4",children:[!f&&(0,B.jsxs)("div",{role:"row",className:(0,eR.cn)("mb-1 grid h-[30px] items-center gap-x-3 border-b border-border/60 px-2 text-[11px] font-medium text-muted-foreground/70",Fc),children:[(0,B.jsx)(Fx,{field:"title",sort:s,onToggle:_,children:"Title"}),(0,B.jsx)(Fx,{field:"priority",sort:s,onToggle:_,className:Fu,children:"Priority"}),(0,B.jsx)("span",{className:Fd,children:"Branch"}),(0,B.jsx)(Fx,{field:"created_at",sort:s,onToggle:_,className:"justify-self-end",children:"Created"}),(0,B.jsx)("span",{})]}),j.map(({root:e,kids:r})=>(0,B.jsxs)("div",{className:"contents",children:[C(e),r.length>0&&(0,B.jsx)("div",{className:"relative flex flex-col gap-px before:absolute before:top-[-2px] before:bottom-3 before:left-[15px] before:w-px before:bg-border",children:r.map(C)})]},e.task.id)),x.map(e=>(0,B.jsx)(Fm,{pending:e,compact:f},e.key)),0===e.length&&0===x.length&&(0,B.jsxs)("div",{className:"flex flex-col items-center gap-1 py-12 text-center",children:[(0,B.jsx)("p",{className:"text-sm font-medium text-foreground/60",children:"No tasks yet"}),(0,B.jsx)("p",{className:"text-xs text-muted-foreground",children:"Create one to get started."})]})]})}function Fx({field:e,sort:r,onToggle:s,className:n,children:i}){let a=r?.field===e,o=a?"asc"===r.dir?Ah:c7:gE;return(0,B.jsxs)("button",{type:"button",onClick:()=>s(e),className:(0,eR.cn)("group/sh inline-flex w-fit items-center gap-[3px] outline-none hover:text-muted-foreground",a&&"text-muted-foreground",n),children:[i,(0,B.jsx)(o,{className:(0,eR.cn)("size-2.5",!a&&"opacity-0 group-hover/sh:opacity-100"),"aria-hidden":!0})]})}let Fv=(0,eA.default)("message-square-plus",[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}],["path",{d:"M12 8v6",key:"1ib9pf"}],["path",{d:"M9 11h6",key:"1fldmi"}]]);var sb=sy;let Fy=["boxSizing","width","paddingTop","paddingRight","paddingBottom","paddingLeft","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","fontFamily","fontSize","fontWeight","lineHeight","letterSpacing","tabSize","wordBreak","overflowWrap"];function Fb({value:e,label:r,className:s,onOpenFile:n,children:i}){let[a,o]=(0,$.useState)(!1),l=(0,$.useRef)(null),c=(0,$.useRef)(null),d=(r,s)=>{let n=function(e){for(let r=e.parentElement;r;r=r.parentElement){let{overflowY:e}=getComputedStyle(r);if(("auto"===e||"scroll"===e)&&r.scrollHeight>r.clientHeight)return r}return null}(r);c.current={caret:s?function(e,r,s,n){let i=null,a=0;if(document.caretPositionFromPoint){let e=document.caretPositionFromPoint(r,s);i=e?.offsetNode??null,a=e?.offset??0}else if(document.caretRangeFromPoint){let e=document.caretRangeFromPoint(r,s);i=e?.startContainer??null,a=e?.startOffset??0}if(!i||i.nodeType!==Node.TEXT_NODE||!e.contains(i))return null;let o=0,l=document.createTreeWalker(e,NodeFilter.SHOW_TEXT);for(let e=l.nextNode();e;e=l.nextNode()){let r=e.textContent??"",s=r.trim()?n.indexOf(r,o):-1;if(e===i)return -1===s?null:s+a;-1!==s&&(o=s+r.length)}return null}(r,s.x,s.y,e):null,clientY:s?.y??null,scroller:n,scrollTop:n?.scrollTop??0},o(!0)};return((0,$.useLayoutEffect)(()=>{let e=l.current?.querySelector("textarea"),r=c.current;if(c.current=null,!a||!e)return;let s=r?.caret??e.value.length;e.focus({preventScroll:!0}),e.setSelectionRange(s,s),r?.scroller&&(r.scroller.scrollTop=r.scrollTop,null!==r.caret&&null!==r.clientY&&(r.scroller.scrollTop+=function(e,r){let s=getComputedStyle(e),n=document.createElement("div");for(let e of Fy)n.style[e]=s[e];Object.assign(n.style,{position:"absolute",top:"0",left:"-9999px",visibility:"hidden",whiteSpace:"pre-wrap",borderStyle:"solid"}),n.textContent=e.value.slice(0,r);let i=document.createElement("span");i.textContent="",n.appendChild(i),document.body.appendChild(n);let a=e.getBoundingClientRect().top-e.scrollTop+i.offsetTop+i.offsetHeight/2;return n.remove(),a}(e,s)-r.clientY))},[a]),!a&&e.trim())?(0,B.jsx)("div",{tabIndex:0,"data-markdown-field":r,title:"Click to edit",onClick:e=>{e.target.closest("a, button")||window.getSelection()?.isCollapsed&&d(e.currentTarget,{x:e.clientX,y:e.clientY})},onKeyDown:e=>{"Enter"===e.key&&e.target===e.currentTarget&&(e.preventDefault(),d(e.currentTarget))},className:`cursor-text outline-none ${s??""}`,children:(0,B.jsx)(Ti,{value:n??null,children:(0,B.jsx)(sb.i,{mode:"static",className:aq,rehypePlugins:Tl,components:Td,children:e})})}):(0,B.jsx)("div",{ref:l,className:"contents",onFocus:()=>o(!0),onBlur:()=>o(!1),children:i})}function Fw({task:e,onUpdate:r,onAssign:s,onArchive:n,onUnarchive:i,onDelete:a,onClose:o,worktrees:l,assignedBranches:c,onOpenSourceSession:d,onStartSession:u,onOpenFile:h,tasks:f,onSelectTask:p,onAddSubtask:m,position:g,onStep:x}){let v=null!==e.archived_at,y=(0,$.useMemo)(()=>new Map(f.map(e=>[e.id,e])),[f]),b=(0,$.useMemo)(()=>{let r=[],s=new Set([e.id]),n=e.parent_id?y.get(e.parent_id):void 0;for(;n&&!s.has(n.id);)r.unshift(n),s.add(n.id),n=n.parent_id?y.get(n.parent_id):void 0;return r},[e,y]),w=(0,$.useMemo)(()=>f.filter(r=>r.parent_id===e.id&&null===r.archived_at),[f,e.id]),_=(0,$.useMemo)(()=>(function(e,r){let s=0,n=0;for(let i of r)i.parent_id===e&&null===i.archived_at&&"cancelled"!==i.status&&(n+=1,"done"===i.status&&(s+=1));return{done:s,total:n}})(e.id,f),[f,e.id]),S=(0,$.useMemo)(()=>(function(e,r){let s=new Set([e]),n=!0;for(;n;)for(let e of(n=!1,r))e.parent_id&&s.has(e.parent_id)&&!s.has(e.id)&&(s.add(e.id),n=!0);return s})(e.id,f),[f,e.id]),j=(0,$.useMemo)(()=>{let e=w.filter(e=>"cancelled"!==e.status),r=e.filter(e=>"done"===e.status).length,s=e.filter(e=>"in_progress"===e.status).length;return e.map((e,n)=>n<r?"done":n<r+s?"doing":"todo")},[w]),[k,C]=(0,$.useState)(!1);return(0,B.jsxs)("div",{className:"flex h-full min-w-0 flex-col bg-card",children:[(0,B.jsxs)("div",{className:"flex h-[42px] shrink-0 items-center gap-0.5 border-b border-border/60 pr-2 pl-3",children:[x&&(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(Fp,{title:"Previous (↑)",onClick:()=>x(-1),children:(0,B.jsx)(lS,{className:"size-3.5"})}),(0,B.jsx)(Fp,{title:"Next (↓)",onClick:()=>x(1),children:(0,B.jsx)(aI,{className:"size-3.5"})})]}),g&&(0,B.jsxs)("span",{className:"mx-1.5 font-mono text-[10.5px] tabular-nums text-muted-foreground/70",children:[g.index+1," / ",g.total]}),(0,B.jsx)("span",{className:"flex-1"}),u&&!v&&(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(F_,{worktrees:l,onPick:r=>u(e,r)}),(0,B.jsx)("span",{className:"mx-1 h-4 w-px bg-border","aria-hidden":!0})]}),!v&&(0,B.jsx)(Fp,{title:"Archive",onClick:()=>n(e.id),children:(0,B.jsx)(on,{className:"size-[13px]"})}),(0,B.jsx)(Fp,{title:"Delete",onClick:()=>a(e.id),children:(0,B.jsx)(rb,{className:"size-[13px]"})}),(0,B.jsx)("span",{className:"mx-1 h-4 w-px bg-border","aria-hidden":!0}),(0,B.jsx)(Fp,{title:"Close (Esc)",onClick:o,children:(0,B.jsx)(ro,{className:"size-3.5"})})]}),v&&(0,B.jsxs)("div",{className:"flex shrink-0 items-center gap-2 border-b border-border/60 bg-secondary py-2 pr-3 pl-3.5 text-xs text-muted-foreground",children:[(0,B.jsx)(on,{className:"size-[13px] shrink-0","aria-hidden":!0}),(0,B.jsxs)("span",{className:"min-w-0 truncate",children:["Archived ",new Date(e.archived_at).toLocaleDateString(void 0,{month:"short",day:"numeric"})," — hidden from the list and the sidebar"]}),(0,B.jsxs)(Z.Button,{variant:"outline",size:"sm",className:"ml-auto h-6 gap-1 px-2 text-[11.5px]",onClick:()=>i(e.id),children:[(0,B.jsx)(Fl,{className:"size-3"}),"Unarchive"]})]}),(0,B.jsxs)("div",{className:(0,eR.cn)("flex min-h-0 flex-1 flex-col overflow-auto [&>*]:shrink-0 px-6 pt-[18px] pb-[22px] edge-scrollbar",v&&"opacity-[.78]"),children:[b.length>0&&(0,B.jsx)("nav",{"aria-label":"Parent tasks",className:"mb-1 -ml-[5px] flex min-w-0 flex-wrap items-center gap-px text-[11.5px] text-muted-foreground/70",children:b.map(e=>(0,B.jsxs)("span",{className:"flex min-w-0 items-center gap-px",children:[(0,B.jsx)("button",{type:"button",className:"max-w-[280px] truncate rounded-[5px] px-[5px] py-0.5 text-muted-foreground hover:bg-muted hover:text-foreground",onClick:()=>p(e.id),children:e.title}),(0,B.jsx)(ab,{className:"size-[11px] shrink-0","aria-hidden":!0})]},e.id))}),(0,B.jsx)(FC,{value:e.title,onCommit:s=>{let n=s.trim();n&&n!==e.title&&r(e.id,{title:n})},singleLine:!0,"aria-label":"Title",className:"mb-3.5 text-lg leading-[1.32] font-semibold tracking-[-0.02em] hover:bg-muted focus:bg-muted/60"}),(0,B.jsxs)(aG,{status:e.status,priority:e.priority,assignedBranch:e.assigned_branch,onStatusChange:s=>r(e.id,{status:s}),onPriorityChange:s=>r(e.id,{priority:s}),onAssign:r=>s(e.id,r),worktrees:l,assignedBranches:c,readOnlyBranch:v,children:[!(v&&!e.parent_id)&&(0,B.jsx)(aJ,{label:"Parent",children:(0,B.jsx)(Ts,{tasks:f,value:e.parent_id??null,onChange:s=>r(e.id,{parent_id:s}),excludeIds:S,field:!0})}),e.source_session&&(0,B.jsx)(aJ,{label:"From session",children:e.source_session.exists?(0,B.jsxs)("button",{type:"button",disabled:!d,onClick:()=>d?.(e),title:e.source_session.title?.trim()||"Untitled session",className:"-ml-2 inline-flex h-[30px] min-w-0 max-w-full items-center gap-2 rounded-md px-2 text-primary hover:bg-muted disabled:text-foreground",children:[(0,B.jsx)(sx,{className:"size-[13px] shrink-0","aria-hidden":!0}),(0,B.jsx)("span",{className:"truncate",children:e.source_session.title?.trim()||"Untitled session"})]}):(0,B.jsx)("span",{className:"inline-flex h-[30px] items-center italic text-muted-foreground",children:"Source session deleted"})})]}),(0,B.jsxs)(FS,{title:"Description",className:"flex flex-[1_0_auto] flex-col",hint:!k&&e.description?.trim()?"Click to edit · Markdown":void 0,children:[(0,B.jsx)(Fb,{value:e.description??"",label:"Description",onOpenFile:h?(r,s)=>h(e.source_session?.branch??null,r,s):void 0,className:`-mx-1.5 flex-1 rounded-md px-1.5 py-1 text-secondary-foreground hover:bg-secondary focus-visible:bg-muted/40 ${aH}`,children:(0,B.jsx)(FC,{value:e.description??"",onCommit:s=>{let n=s.trim()?s:null;n!==e.description&&r(e.id,{description:n})},onEditingChange:C,placeholder:"Add a description…","aria-label":"Description",className:`${aU} focus:border focus:border-primary focus:bg-card focus:px-3 focus:py-2.5 focus:font-mono focus:text-xs focus:leading-[1.65] focus:shadow-[0_0_0_3px_var(--accent)]`})}),k&&(0,B.jsxs)("div",{className:"mt-2 flex items-center gap-2.5 text-[11px] text-muted-foreground/70",children:[(0,B.jsx)(Fk,{keys:["⌘","↵"],children:"save"}),(0,B.jsx)(Fk,{keys:["Esc"],children:"cancel"}),(0,B.jsx)("span",{className:"flex-1"}),(0,B.jsx)("span",{children:"Saves on blur"})]})]}),(0,B.jsxs)(FS,{title:"Sub-tasks","aria-label":"Sub-tasks",compact:!0,hint:v&&0===w.length?"None":void 0,extra:_.total>0&&(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)("span",{className:"ml-0.5 flex gap-[3px]","aria-hidden":!0,children:j.map((e,r)=>(0,B.jsx)("i",{className:(0,eR.cn)("h-1 w-[18px] rounded-sm","done"===e?"bg-[oklch(0.6_0.14_152)]":"doing"===e?"bg-[oklch(0.58_0.16_245)]":"bg-border")},r))}),(0,B.jsxs)("span",{className:"font-mono text-[10.5px] font-normal tabular-nums text-muted-foreground/70",children:[_.done,"/",_.total]})]}),children:[w.length>0&&(0,B.jsx)("ul",{className:"-mx-2 flex flex-col",children:w.map(e=>{let r="done"===e.status||"cancelled"===e.status;return(0,B.jsx)("li",{children:(0,B.jsxs)("button",{type:"button",className:"flex h-7 w-full min-w-0 items-center gap-[9px] rounded-md px-2 text-left hover:bg-muted",onClick:()=>p(e.id),children:[(0,B.jsx)(aP,{status:e.status}),(0,B.jsx)("span",{className:(0,eR.cn)("min-w-0 flex-1 truncate text-[12.5px] font-[450]",r&&"text-muted-foreground line-through decoration-border"),children:e.title}),(0,B.jsx)(az,{priority:e.priority})]})},e.id)})}),!v&&(0,B.jsxs)("button",{type:"button",className:"-mx-2 flex h-7 w-[calc(100%+1rem)] items-center gap-[9px] rounded-md px-2 text-[12.5px] text-muted-foreground hover:bg-muted hover:text-foreground",onClick:()=>m(e.id),children:[(0,B.jsx)("span",{className:"grid size-3.5 place-items-center rounded-full border-[1.5px] border-dashed border-border text-muted-foreground/70",children:(0,B.jsx)(eM,{className:"size-2",strokeWidth:3})}),"Add sub-task"]})]})]}),(0,B.jsxs)("div",{className:"flex h-9 shrink-0 items-center gap-1.5 border-t border-border/60 bg-secondary px-4 text-[11px] text-muted-foreground",children:[(0,B.jsxs)("span",{title:new Date(e.created_at).toLocaleString(),children:["Created ",function(e,r=new Date){let s=new Date(e),n=s.toLocaleDateString(void 0,{month:"short",day:"numeric",...s.getFullYear()!==r.getFullYear()?{year:"numeric"}:{}}),i=s.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1});return`${n}, ${i}`}(e.created_at)]}),(0,B.jsx)("span",{className:"text-border","aria-hidden":!0,children:"·"}),(0,B.jsxs)("span",{title:new Date(e.updated_at).toLocaleString(),children:["Updated ",function(e,r=Date.now()){let s=sD(e,r);return"now"===s?"just now":`${s} ago`}(e.updated_at)]}),(0,B.jsx)("span",{className:"flex-1"}),g&&(0,B.jsx)(Fk,{keys:["↑","↓"],children:"switch"}),(0,B.jsx)(Fk,{keys:["Esc"],className:"ml-2",children:"close"})]})]})}function F_({worktrees:e,onPick:r}){return(0,B.jsxs)(a_,{children:[(0,B.jsx)(aS,{asChild:!0,children:(0,B.jsxs)("button",{type:"button",className:"inline-flex h-[26px] items-center gap-1.5 rounded-md px-2 text-[12px] font-medium text-muted-foreground outline-none hover:bg-border/60 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50 data-[state=open]:bg-border/60 data-[state=open]:text-foreground",children:[(0,B.jsx)(Fv,{className:"size-[13px]","aria-hidden":!0}),"Start session",(0,B.jsx)(aI,{className:"size-3 text-muted-foreground/70","aria-hidden":!0})]})}),(0,B.jsxs)(aj,{align:"end",className:"max-h-72 w-(--radix-dropdown-menu-trigger-width) min-w-0 overflow-y-auto",children:[(0,B.jsx)(aD,{className:"text-[11px] font-normal text-muted-foreground",children:"Select workspace"}),(0,B.jsx)(aR,{}),e.map(e=>(0,B.jsxs)(ak,{onClick:()=>r(e.branch),title:e.branch??"main",className:"gap-2 font-mono text-[12px]",children:[(0,B.jsx)(aF,{className:"size-3 shrink-0 text-muted-foreground"}),(0,B.jsx)("span",{className:"min-w-0 truncate",children:e.branch??"main"})]},e.branch??"")),0===e.length&&(0,B.jsx)("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"No workspaces"})]})]})}function FS({title:e,hint:r,extra:s,compact:n,className:i,children:a,...o}){return(0,B.jsxs)("section",{className:(0,eR.cn)("mt-[18px] border-t border-border/60",n?"pt-3":"pt-3.5",i),...o,children:[(0,B.jsxs)("div",{className:(0,eR.cn)("flex h-5 items-center gap-2 text-[11.5px] font-medium text-muted-foreground",n?"mb-1":"mb-2"),children:[e,s,r&&(0,B.jsx)("span",{className:"ml-auto text-[11px] font-normal text-muted-foreground/70",children:r})]}),a]})}function Fj({children:e,className:r}){return(0,B.jsx)("kbd",{className:(0,eR.cn)("inline-grid h-[17px] min-w-[17px] place-items-center rounded border border-b-[1.5px] border-border bg-card px-1 font-mono text-[10px] leading-none text-secondary-foreground",r),children:e})}function Fk({keys:e,className:r,children:s}){return(0,B.jsxs)("span",{className:(0,eR.cn)("inline-flex items-center gap-1",r),children:[e.map(e=>(0,B.jsx)(Fj,{children:e},e)),s]})}function FC({value:e,onCommit:r,singleLine:s,onEditingChange:n,className:i,...a}){let[o,l]=(0,$.useState)(null),c=(0,$.useRef)(!1);return(0,B.jsx)("textarea",{rows:1,value:o??e,onFocus:()=>{l(e),n?.(!0)},onChange:e=>l(s?e.target.value.replace(/\n/g," "):e.target.value),onBlur:()=>{null===o||c.current||r(o),c.current=!1,l(null),n?.(!1)},onKeyDown:e=>{if(!e.nativeEvent.isComposing&&229!==e.keyCode){if("Escape"===e.key){e.preventDefault(),c.current=!0,e.currentTarget.blur();return}"Enter"===e.key&&(s||e.metaKey||e.ctrlKey)&&(e.preventDefault(),e.currentTarget.blur())}},className:`${aW} ${i??""}`,...a})}let FN={title:"",description:"",status:"todo",priority:"medium",assigned_branch:null,parent_id:null},FE=e=>!e.title.trim()&&!e.description.trim(),FD=e=>e.nativeEvent.isComposing||229===e.keyCode;function FR({draft:e,onChange:r,onCreate:s,onDiscard:n,onClose:i,createMore:a,onCreateMoreChange:o,error:l,focusNonce:c,worktrees:d,assignedBranches:u,tasks:h}){let f=(0,$.useRef)(null),p=(0,$.useRef)(null),m=e.description.trim().length>0;return(0,$.useEffect)(()=>{f.current?.focus()},[c]),(0,B.jsxs)("div",{className:"flex h-full flex-col bg-card",onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&!FD(e)&&(e.preventDefault(),m&&s())},children:[(0,B.jsxs)("div",{className:"flex h-[42px] shrink-0 items-center justify-between border-b border-border/60 pr-2 pl-6",children:[(0,B.jsxs)("span",{className:"text-[11px] font-medium uppercase tracking-wide text-muted-foreground",children:["New task ",(0,B.jsx)("span",{className:"normal-case tracking-normal text-muted-foreground/70",children:"· Draft"})]}),(0,B.jsx)(Fp,{title:"Close (Esc) — keeps the draft",onClick:i,children:(0,B.jsx)(ro,{className:"size-3.5"})})]}),(0,B.jsxs)("div",{className:"flex-1 overflow-auto px-6 pt-[18px] pb-6 edge-scrollbar",children:[(0,B.jsx)("textarea",{ref:f,rows:1,value:e.title,onChange:e=>r({title:e.target.value.replace(/\n/g," ")}),onKeyDown:e=>{"Enter"!==e.key||e.metaKey||e.ctrlKey||FD(e)||(e.preventDefault(),p.current?.focus())},placeholder:"Untitled","aria-label":"Title",className:`${aW} text-lg leading-[1.32] font-semibold tracking-[-0.02em]`}),(0,B.jsx)("p",{className:"mt-0.5 mb-3 min-h-4 text-[11px] text-muted-foreground/70",children:!e.title.trim()&&"Leave empty to generate a title from the description."}),(0,B.jsx)(aG,{status:e.status,priority:e.priority,assignedBranch:e.assigned_branch,onStatusChange:e=>r({status:e}),onPriorityChange:e=>r({priority:e}),onAssign:e=>r({assigned_branch:e}),worktrees:d,assignedBranches:u,children:(0,B.jsx)(aJ,{label:"Parent",children:(0,B.jsx)(Ts,{tasks:h,value:e.parent_id,onChange:e=>r({parent_id:e}),field:!0})})}),(0,B.jsx)("div",{className:"mt-[18px] border-t border-border/60 pt-3.5",children:(0,B.jsx)("textarea",{ref:p,rows:1,value:e.description,onChange:e=>r({description:e.target.value}),placeholder:"Describe the task…","aria-label":"Description",className:`${aW} ${aU}`})})]}),l&&(0,B.jsxs)("div",{role:"alert",className:"mx-6 mb-3 flex shrink-0 items-center gap-2 rounded-md bg-destructive/10 px-3 py-2 text-xs text-destructive",children:[(0,B.jsx)(a5,{className:"size-3.5 shrink-0"}),l]}),(0,B.jsxs)("div",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-border/60 bg-secondary px-6 py-2.5",children:[(0,B.jsxs)("label",{className:"mr-auto flex cursor-pointer items-center gap-2 text-xs text-muted-foreground",children:[(0,B.jsx)(eT,{checked:a,onCheckedChange:e=>o(!0===e)}),"Create more"]}),(0,B.jsx)(Z.Button,{variant:"ghost",size:"sm",onClick:n,disabled:FE(e),children:"Discard"}),(0,B.jsxs)(Z.Button,{size:"sm",onClick:s,disabled:!m,children:["Create",(0,B.jsx)("kbd",{className:"ml-1.5 rounded bg-background/15 px-1 font-sans text-[10px]",children:"⌘↵"})]})]})]})}let FT="vibedeckx:tasks:create-more",FA=[{value:"all",label:"All"},{value:"todo",label:"Todo"},{value:"in_progress",label:"Doing"},{value:"done",label:"Done"},{value:"cancelled",label:"Cancelled"},{value:"archived",label:"Archived"}];function FM({active:e=!0,projectId:r,tasks:s,loading:n,worktrees:i,onCreateTask:a,onUpdateTask:o,onDeleteTask:l,onArchiveTask:c,onUnarchiveTask:d,onOpenSourceSession:u,onStartSession:h,onOpenFile:f,openRequest:p,onSelectedTaskChange:m}){let{settings:g}=(0,dh.useConversationSettings)(),[x,v]=(0,$.useState)("all"),[y,b]=(0,$.useState)(null),[w,_]=(0,$.useState)(null),S=w?.projectId===r?w.panel:null,j=S?.kind==="task"?S.taskId:null,k=j?s.find(e=>e.id===j)??null:null,C=S?.kind==="draft",N=(0,$.useCallback)(e=>_(e?{projectId:r,panel:{kind:"task",taskId:e}}:null),[r]),[E,D]=(0,$.useState)(null),R=E?.projectId===r?E.draft:FN,[T,A]=(0,$.useState)(null),[M,I]=(0,$.useState)(0),[F,P]=(0,$.useState)(()=>"1"===window.localStorage.getItem(FT)),[L,z]=(0,$.useState)([]),[O,W]=(0,$.useState)(null),H=O?.projectId===r?O.taskId:null,U=(0,$.useRef)(0);(0,$.useEffect)(()=>{if(!O)return;let e=setTimeout(()=>W(null),1600);return()=>clearTimeout(e)},[O]),(0,$.useEffect)(()=>{if(!p)return;if("draft"===p.kind){_({projectId:r,panel:{kind:"draft"}}),I(e=>e+1);return}_({projectId:r,panel:{kind:"task",taskId:p.taskId}});let{status:e}=p;v(r=>"all"===r||r===e?r:"all")},[p]);let q=k?.id??null;(0,$.useEffect)(()=>{m?.(q)},[q,m]);let K=async()=>{let e=R.description.trim();if(!e)return;let s=`pending-${++U.current}`,n=R.title.trim()||null;z(i=>[...i,{key:s,projectId:r,title:n,description:e,status:R.status,priority:R.priority}]),A(null),D(F&&R.parent_id?{projectId:r,draft:{...FN,parent_id:R.parent_id}}:null),F?I(e=>e+1):_(null);let i=await a({title:n??void 0,description:e,status:R.status,priority:R.priority,assigned_branch:R.assigned_branch,parent_id:R.parent_id});(z(e=>e.filter(e=>e.key!==s)),i)?W({projectId:r,taskId:i.id}):(D(e=>e&&e.projectId===r&&!FE(e.draft)?e:{projectId:r,draft:R}),_(e=>e??{projectId:r,panel:{kind:"draft"}}),A("Couldn't create the task. Your draft is restored, try again."))},V=(e,r)=>{o(e,{assigned_branch:r})},X=(0,$.useMemo)(()=>s.filter(e=>null===e.archived_at),[s]),Y=(0,$.useMemo)(()=>s.filter(e=>null!==e.archived_at),[s]),G=(0,$.useMemo)(()=>{let e={all:X.length,todo:0,in_progress:0,done:0,cancelled:0,archived:Y.length};for(let r of X)e[r.status]++;return e},[X,Y]),J=(0,$.useMemo)(()=>"archived"===x?Y:"all"===x?X:X.filter(e=>e.status===x),[X,Y,x]),Q="archived"===x,ee=(0,$.useMemo)(()=>(function(e){let r=new Set(e.map(e=>e.id)),s=new Map,n=[];for(let i of e)if(i.parent_id&&i.parent_id!==i.id&&r.has(i.parent_id)){let e=s.get(i.parent_id)??[];e.push(i),s.set(i.parent_id,e)}else n.push(i);let i=[],a=new Set,o=(e,r)=>{if(!a.has(e.id))for(let n of(a.add(e.id),i.push({task:e,depth:r}),s.get(e.id)??[]))o(n,r+1)};for(let e of n)o(e,0);for(let r of e)o(r,0);return i})(function(e,r){if(!r)return e;let s="asc"===r.dir?1:-1;return[...e].sort((e,n)=>{switch(r.field){case"title":return s*e.title.localeCompare(n.title);case"priority":return s*(sE[e.priority]-sE[n.priority]);case"created_at":return s*(new Date(e.created_at).getTime()-new Date(n.created_at).getTime())}})}(J,y)),[J,y]),et=k?ee.findIndex(e=>e.task.id===k.id):-1,er=(0,$.useCallback)(e=>{if(0===ee.length)return;let r=-1===et?0:Math.min(Math.max(et+e,0),ee.length-1);N(ee[r].task.id)},[ee,et,N]),es=(0,$.useMemo)(()=>L.filter(e=>e.projectId===r&&("all"===x||x===e.status)),[L,r,x]),en=(0,$.useMemo)(()=>C?{kind:"draft",draft:R}:k?{kind:"task",task:k}:null,[C,R,k]),[ei,ea]=(0,$.useState)(null);en&&en!==ei?ea(en):!en&&ei&&("function"!=typeof window.matchMedia||window.matchMedia("(prefers-reduced-motion: reduce)").matches)&&ea(null);let eo=!en&&null!==ei,el=en??ei;(0,$.useEffect)(()=>{if(!eo)return;let e=setTimeout(()=>ea(null),400);return()=>clearTimeout(e)},[eo]);let ec=(0,$.useMemo)(()=>new Set(s.filter(e=>null!==e.assigned_branch).map(e=>e.assigned_branch)),[s]);return r?(0,B.jsxs)("div",{className:"flex flex-col h-full",children:[(0,B.jsx)(ug,{title:"Tasks",count:X.length,actions:(0,B.jsxs)(Z.Button,{size:"sm",onClick:()=>{_({projectId:r,panel:{kind:"draft"}}),I(e=>e+1)},className:"shadow-sm",children:[(0,B.jsx)(eM,{className:"h-3.5 w-3.5 mr-1.5"}),"New Task"]})}),(0,B.jsx)(ux,{children:FA.map(e=>(0,B.jsx)(uv,{active:x===e.value,count:G[e.value],onClick:()=>v(e.value),children:e.label},e.value))}),(0,B.jsx)("div",{className:"flex-1 min-h-0",children:(0,B.jsxs)(hD,{direction:"horizontal",autoSaveId:"task-detail-panels",children:[(0,B.jsx)(uT,{id:"task-list",order:1,minSize:30,children:(0,B.jsx)("div",{className:"@container h-full overflow-y-auto overflow-x-hidden edge-scrollbar",children:n?(0,B.jsx)("div",{className:"flex items-center justify-center py-12 text-muted-foreground text-sm",children:"Loading tasks..."}):(0,B.jsx)(Fg,{rows:ee,allTasks:s,sort:y,onSortChange:b,onStep:er,onUpdate:o,onDelete:l,onArchive:c,onUnarchive:d,archivedView:Q,worktrees:i,onAssign:V,onOpenSourceSession:u,panelOpen:null!==k||C,selectedTaskId:k?.id??null,keyboardActive:e,onSelect:N,pendingTasks:es,flashTaskId:H,assignedBranches:ec})})}),el&&(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(hR,{}),(0,B.jsx)(uT,{id:"task-detail",order:2,defaultSize:40,minSize:25,className:eo?"motion-safe:animate-side-panel-out":"motion-safe:animate-side-panel-in",onAnimationEnd:e=>{e.target===e.currentTarget&&eo&&ea(null)},children:(0,B.jsx)("div",{className:"h-full",inert:eo,style:{"--task-body-font-size":`${g.tasksFontSize}px`},children:"draft"===el.kind?(0,B.jsx)(FR,{draft:el.draft,onChange:e=>D({projectId:r,draft:{...R,...e}}),onCreate:K,onDiscard:()=>{D(null),A(null),_(null)},onClose:()=>N(null),createMore:F,onCreateMoreChange:e=>{P(e),window.localStorage.setItem(FT,e?"1":"0")},error:T,focusNonce:M,worktrees:i,assignedBranches:ec,tasks:s}):(0,B.jsx)(Fw,{task:el.task,onUpdate:o,onAssign:V,onArchive:c,onUnarchive:d,onDelete:l,onClose:()=>N(null),worktrees:i,assignedBranches:ec,onOpenSourceSession:u,onStartSession:h,onOpenFile:f,tasks:s,onSelectTask:N,onAddSubtask:e=>{D({projectId:r,draft:{...R,parent_id:e}}),A(null),_({projectId:r,panel:{kind:"draft"}}),I(e=>e+1)},position:-1===et||el.task.id!==k?.id?null:{index:et,total:ee.length},onStep:er},el.task.id)})})]})]})})]}):(0,B.jsx)("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:(0,B.jsxs)("div",{className:"text-center",children:[(0,B.jsx)("div",{className:"mx-auto w-10 h-10 rounded-xl bg-muted flex items-center justify-center mb-3",children:(0,B.jsx)(eM,{className:"h-5 w-5 text-muted-foreground/50"})}),(0,B.jsx)("p",{className:"text-sm",children:"Select a project to view tasks."})]})})}var FI=e.i(115796);let FF=[5e3,1e4,2e4,4e4];function FP({open:e,onOpenChange:r,onNavigateProject:s,onNavigateWorkspace:n,onNavigateSession:i}){let[a,o]=(0,$.useState)(""),[l,c]=(0,$.useState)(null),[d,u]=(0,$.useState)(!1),h=(0,$.useRef)(null),f=(0,$.useRef)(null),p=(0,$.useRef)("");(0,$.useLayoutEffect)(()=>{p.current=a},[a]),(0,a8.useGlobalEventStream)(e=>{if("session:title"!==e.type||"string"!=typeof e.sessionId)return;let r="string"==typeof e.title?e.title.trim():"";(0,FI.updateCachedSessionTitle)(e.sessionId,r||null)});let[m,g]=(0,$.useState)(e);e!==m&&(g(e),e&&(o(""),c((0,FI.getCachedEmptyResults)()),u(!1)));let x=(0,$.useCallback)(async e=>{h.current?.abort();let r=new AbortController;h.current=r;let s=""===e?(0,FI.beginEmptyQuerySearch)():null;for(let n=0;;n++){let i=Date.now();try{let i=await (0,rD.searchAll)(e,{signal:AbortSignal.any([r.signal,AbortSignal.timeout(FF[n])])});r.signal.aborted||(null!==s&&(0,FI.commitEmptyQueryResults)(s,i),c(i),u(!1));return}catch{if(r.signal.aborted)return;if(n===FF.length-1)return void u(!0);let e=1e3*2**n-(Date.now()-i);if(e>0&&await function(e,r){return new Promise(s=>{let n=setTimeout(s,e);r.addEventListener("abort",()=>{clearTimeout(n),s()},{once:!0})})}(e,r.signal),r.signal.aborted)return}}},[]),v=(0,$.useRef)(!1);(0,$.useEffect)(()=>{let r=e&&!v.current;if(v.current=e,e)return f.current&&clearTimeout(f.current),f.current=setTimeout(()=>void x(a),150*!r),()=>{f.current&&clearTimeout(f.current)}},[a,e,x]),(0,$.useEffect)(()=>{if(!e)return;let r=!1;return(0,rD.refreshSearchCache)().then(()=>{r||x(p.current)}).catch(()=>{}),()=>{r=!0,h.current?.abort()}},[e,x]);let y=l?a.trim()?{sessions:l.sessions,favorites:l.favorites}:(0,FI.overlayRecents)(l):null,b=null===l,w=!!y&&0===l.projects.length&&0===l.workspaces.length&&0===y.sessions.length&&0===y.favorites.length,_=l?.cacheState==="cold",S=e=>(0,B.jsxs)(me,{value:`session-${e.sessionId}`,onSelect:()=>i(e),children:[(0,B.jsx)(sx,{}),(0,B.jsx)("span",{className:"truncate",children:e.title??"Untitled session"}),e.favoritedAt&&(0,B.jsx)(oz,{className:"h-3.5 w-3.5 shrink-0 fill-current text-amber-500"}),(0,B.jsxs)("span",{className:"ml-auto shrink-0 text-xs text-muted-foreground",children:[e.projectName," · ",e.branch??"main"," · ",function(e){if(!e)return"";let r=Date.now()-e;return r<6e4?"just now":r<36e5?`${Math.floor(r/6e4)}m ago`:r<864e5?`${Math.floor(r/36e5)}h ago`:`${Math.floor(r/864e5)}d ago`}(e.lastActiveAt)]})]},e.sessionId);return(0,B.jsxs)(p4,{open:e,onOpenChange:r,title:"Quick Switcher",description:"Search projects, workspaces, and sessions",shouldFilter:!1,instantClose:!0,className:"top-[max(1rem,calc(50%_-_175px))] translate-y-0",children:[(0,B.jsx)(p6,{placeholder:"Search projects, workspaces, sessions…",value:a,onValueChange:o}),(0,B.jsxs)(p7,{children:[d&&(0,B.jsxs)("div",{className:"flex items-center justify-between gap-2 px-4 py-3 text-sm text-destructive",children:[(0,B.jsx)("span",{children:"Search failed."}),(0,B.jsx)(Z.Button,{variant:"link",size:"sm",className:"h-auto p-0 text-destructive",onClick:()=>void x(p.current),children:"Retry"})]}),!d&&b&&(0,B.jsxs)("div",{className:"flex items-center justify-center gap-2 py-6 text-sm text-muted-foreground",children:[(0,B.jsx)(a7,{className:"h-4 w-4 animate-spin"}),"Searching…"]}),!d&&!b&&w&&_&&(0,B.jsxs)("div",{className:"flex items-center justify-center gap-2 py-6 text-sm text-muted-foreground",children:[(0,B.jsx)(a7,{className:"h-4 w-4 animate-spin"}),"Syncing history…"]}),!d&&!b&&w&&!_&&(0,B.jsx)(p8,{children:"No results found."}),l&&l.projects.length>0&&(0,B.jsx)(p9,{heading:"Projects",children:l.projects.map(e=>(0,B.jsxs)(me,{value:`project-${e.id}`,onSelect:()=>s(e.id),children:[(0,B.jsx)(dq,{name:e.name,size:"md"}),(0,B.jsx)("span",{children:e.name}),e.path&&(0,B.jsx)("span",{className:"truncate text-xs text-muted-foreground",children:e.path})]},e.id))}),l&&l.workspaces.length>0&&(0,B.jsx)(p9,{heading:"Workspaces",children:l.workspaces.map(e=>(0,B.jsxs)(me,{value:`ws-${e.projectId}-${e.branch??""}`,onSelect:()=>n(e),children:[(0,B.jsx)(aF,{}),(0,B.jsx)("span",{children:e.branch??"main"}),(0,B.jsx)("span",{className:"text-xs text-muted-foreground",children:e.projectName})]},`${e.projectId}-${e.branch??""}`))}),y&&y.sessions.length>0&&(0,B.jsx)(p9,{heading:a.trim()?"Sessions":"Recent",children:y.sessions.map(S)}),y&&y.favorites.length>0&&(0,B.jsx)(p9,{heading:"Favorites",children:y.favorites.map(S)})]})]})}let FL={session_result_ready:"/sounds/sound1.mp3",review_ready:"/sounds/sound2.mp3",session_failed:"/sounds/failure.mp3",workflow_failed:"/sounds/failure.mp3",loop_done:"/sounds/sound1.mp3",commander_stalled:"/sounds/sound2.mp3",cross_remote_token_expired:"/sounds/sound2.mp3"},Fz=[2e3,5e3,15e3];function FO(e,r){let s=[...e.filter(e=>e.id!==r.id),r];return s.sort((e,r)=>r.created_at-e.created_at||(e.id<r.id?1:-1)),s}let FB=new Set(["session_result_ready","session_failed"]);function F$(e){return FB.has(e.kind)&&e.session_id?`${e.kind}:${e.session_id}`:e.id}function FW(e){let r=new Map;for(let s of e){let e=null===s.read_at,n=r.get(F$(s));n?(n.ids.push(s.id),n.count+=1,e&&(n.unreadCount+=1,n.unread=!0)):r.set(F$(s),{latest:s,ids:[s.id],count:1,unreadCount:+!!e,unread:e})}return[...r.values()]}let FH=new Map,FU=new Set,Fq=new Set(["session_result_ready","session_failed"]);function FK(e,r){return Fq.has(e.kind)?null!==r.turnEndAt&&r.turnEndAt>=e.created_at:null!==r.resultAt&&r.resultAt>=e.created_at}function FV(e){let r=FH.get(e);r||((r=new Audio(e)).preload="auto",FH.set(e,r)),r.currentTime=0,r.play().catch(()=>{})}let FX=(0,eA.default)("bell",[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]]);async function FY(e,r){let s=e.session_id;if("commander_stalled"===e.kind&&(s=null),e.workflow_run_id&&("workflow_failed"===e.kind||"loop_done"===e.kind)){let r=await rD.api.getWorkflowRun(e.workflow_run_id).catch(()=>null);r?.kind==="repeat"&&(s=r.source_session_id)}r(e.project_id,e.branch,s)}let FG={session_result_ready:{label:"Session result is ready",dot:"bg-lime-400"},review_ready:{label:"Review feedback is ready",dot:"bg-emerald-500"},session_failed:{label:"Session failed",dot:"bg-destructive"},workflow_failed:{label:"Workflow needs attention",dot:"bg-destructive"},loop_done:{label:"Loop finished — nothing left to process",dot:"bg-emerald-500"},commander_stalled:{label:"Commander stalled — the task needs you to continue it",dot:"bg-amber-500"},cross_remote_token_expired:{label:"Cross-remote expired — stop & send a message to renew",dot:"bg-amber-500"}};function FJ({notifications:e,unreadCount:r,projects:s,onNavigate:n,markRead:i,markAllRead:a,remove:o,clear:l}){let[c,d]=(0,$.useState)(!1);return(0,$.useEffect)(()=>{let e=e=>{"j"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),d(e=>!e))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[]),(0,B.jsxs)(a_,{open:c,onOpenChange:d,children:[(0,B.jsx)(aS,{asChild:!0,children:(0,B.jsxs)(Z.Button,{variant:"ghost",size:"icon-sm",className:"relative",title:"Notifications (⌘J)","aria-label":r>0?`${r} unread notifications`:"Notifications",children:[(0,B.jsx)(FX,{className:"h-4 w-4"}),r>0&&(0,B.jsx)("span",{className:"absolute -top-0.5 -right-0.5 flex h-4 min-w-4 items-center justify-center rounded-full bg-primary px-1 text-[9px] font-semibold leading-none text-primary-foreground",children:r>9?"9+":r})]})}),(0,B.jsxs)(aj,{align:"end",className:"w-80 p-0",children:[(0,B.jsxs)("div",{className:"flex items-center justify-between px-3 py-2",children:[(0,B.jsx)("span",{className:"text-[12.5px] font-semibold text-foreground",children:"Notifications"}),e.length>0&&(0,B.jsxs)("div",{className:"flex items-center gap-1",children:[(0,B.jsxs)("button",{onClick:a,disabled:0===r,className:"flex items-center gap-1 rounded px-1.5 py-0.5 text-[11px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:pointer-events-none disabled:opacity-40",title:"Mark all read",children:[(0,B.jsx)(dK,{className:"h-3 w-3"}),"Mark all read"]}),(0,B.jsx)("button",{onClick:l,className:"rounded px-1.5 py-0.5 text-[11px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",title:"Dismiss all (marks them read)",children:"Clear"})]})]}),(0,B.jsx)("div",{className:"max-h-[60vh] overflow-y-auto border-t border-border",children:0===e.length?(0,B.jsx)("div",{className:"px-3 py-8 text-center text-[12px] text-muted-foreground/70",children:"Nothing needs your attention."}):FW(e).map(e=>{let r,a=e.latest,l=FG[a.kind],c=e.unread;return(0,B.jsxs)(ak,{onSelect:()=>{for(let r of e.ids)i(r);FY(a,n)},className:(0,eR.cn)("group flex flex-col items-start gap-0.5 rounded-none px-3 py-2",c&&"bg-primary/[0.08]"),children:[(0,B.jsxs)("div",{className:"flex w-full items-center gap-2",children:[(0,B.jsx)("span",{className:(0,eR.cn)("h-[7px] w-[7px] shrink-0 rounded-full",l?.dot)}),(0,B.jsx)("span",{className:(0,eR.cn)("min-w-0 flex-1 truncate text-[12.5px]",c?"font-medium text-foreground":"text-foreground/70"),children:a.body??(r=a.project_id,s.find(e=>e.id===r)?.name??"Unknown project")}),e.unreadCount>1&&(0,B.jsxs)("span",{className:"shrink-0 rounded-full bg-muted px-1.5 text-[10px] font-medium leading-4 text-muted-foreground",title:`${e.unreadCount} new notifications, showing the latest`,children:["×",e.unreadCount]}),(0,B.jsx)("span",{className:"shrink-0 text-[10.5px] text-muted-foreground/70",children:function(e){let r=Math.max(0,Math.round((Date.now()-e)/1e3));if(r<60)return"just now";let s=Math.round(r/60);if(s<60)return`${s}m ago`;let n=Math.round(s/60);if(n<24)return`${n}h ago`;let i=Math.round(n/24);return`${i}d ago`}(a.created_at)}),(0,B.jsx)("button",{onClick:r=>{for(let s of(r.stopPropagation(),e.ids))o(s)},className:"shrink-0 rounded p-0.5 text-muted-foreground/60 opacity-0 transition-all hover:bg-muted hover:text-foreground group-hover:opacity-100",title:"Dismiss (marks it read)",children:(0,B.jsx)(ro,{className:"h-3 w-3"})})]}),(0,B.jsxs)("div",{className:"flex w-full items-center gap-1.5 pl-[15px] text-[11px] text-muted-foreground",children:[(0,B.jsx)("span",{className:"font-mono truncate",children:a.branch??"main"}),(0,B.jsx)("span",{className:"text-muted-foreground/50",children:"·"}),(0,B.jsx)("span",{className:"shrink-0",children:l?.label??a.title})]})]},a.id)})})]})]})}let FZ=(0,eA.default)("keyboard",[["path",{d:"M10 8h.01",key:"1r9ogq"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M14 8h.01",key:"1primd"}],["path",{d:"M16 12h.01",key:"1l6xoz"}],["path",{d:"M18 8h.01",key:"emo2bl"}],["path",{d:"M6 8h.01",key:"x9i8wu"}],["path",{d:"M7 16h10",key:"wp8him"}],["path",{d:"M8 12h.01",key:"czm47f"}],["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}]]),FQ=(e,r)=>e?`⌘${r}`:`Ctrl+${r}`,F0=()=>()=>{};function F1(){let[e,r]=(0,$.useState)(!1),s=(0,$.useSyncExternalStore)(F0,U,()=>!1);return(0,$.useEffect)(()=>{let e=e=>{let s="/"===e.key&&(e.metaKey||e.ctrlKey)&&!e.shiftKey&&!e.altKey,n="?"===e.key&&!e.metaKey&&!e.ctrlKey&&!e.altKey&&!d3(e.target);(s||n)&&(e.preventDefault(),r(e=>!e))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[]),(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(Z.Button,{variant:"ghost",size:"icon-sm","aria-label":"Keyboard shortcuts",title:"Keyboard shortcuts (?)",onClick:()=>r(!0),children:(0,B.jsx)(FZ,{className:"h-4 w-4"})}),(0,B.jsx)(rl,{open:e,onOpenChange:r,children:(0,B.jsxs)(rf,{className:"sm:max-w-xl",children:[(0,B.jsx)(rp,{children:(0,B.jsx)(rg,{children:"Keyboard shortcuts"})}),(0,B.jsx)("div",{className:"grid gap-x-8 gap-y-5 sm:grid-cols-2",children:[{title:"Global",entries:[{hints:[FQ(s,"K")],description:"Quick switcher"},{hints:[FQ(s,"J")],description:"Notifications"},{hints:[FQ(s,"B")],description:"Toggle sidebar"},{hints:[s?`⌘⇧O`:"Ctrl+Shift+O"],description:"New agent conversation"},{hints:[J(s,V)],description:"Show / hide Main Chat"},{hints:[J(s,q)],description:"Start review of this session"},{hints:[J(s,K)],description:"Read aloud the lowest reply on screen (again to stop)"},{hints:["a…z"],description:"Locate workspace (type, ↑↓ cycle, ↵ jump)"},{hints:["Esc"],description:"Clear locate query / unfocus right panel"},{hints:["?",FQ(s,"/")],description:"This dialog"}]},{title:"Workspace tabs",entries:[...W.map(e=>({hints:[J(s,e.code)],description:`Open ${e.label}`})),{hints:["←","→"],description:"Switch executor target (Executors focused)"}]}].map(e=>(0,B.jsxs)("section",{children:[(0,B.jsx)("h3",{className:"mb-2 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:e.title}),(0,B.jsx)("ul",{className:"space-y-1.5",children:e.entries.map(e=>(0,B.jsxs)("li",{className:"flex items-center justify-between gap-3 text-[13px]",children:[(0,B.jsx)("span",{className:"text-foreground/90",children:e.description}),(0,B.jsx)("span",{className:"flex shrink-0 items-center gap-1",children:e.hints.map(e=>(0,B.jsx)("kbd",{className:"rounded-md border border-border bg-muted px-1.5 py-0.5 font-mono text-[11px] leading-none text-foreground/80",children:e},e))})]},e.description))})]},e.title))})]})})]})}function F2(e){if(null===e)return"尚未连接";let r=Math.max(0,Math.round((Date.now()-e)/1e3));if(r<60)return`${r} 秒前`;let s=Math.floor(r/60);return s<60?`${s} 分钟前`:`${Math.floor(s/60)} 小时前`}function F5(){let{state:e,lastEventAt:r,updateAvailable:s,reconnect:n}=(0,a8.useConnectionStatus)(),[,i]=(0,$.useState)(0);if((0,$.useEffect)(()=>{let e=setInterval(()=>i(e=>e+1),5e3);return()=>clearInterval(e)},[]),"stale"===e)return(0,B.jsxs)("button",{type:"button",onClick:n,title:`实时更新已断开 \xb7 上次更新 ${F2(r)} \xb7 点击重新连接`,className:"flex items-center gap-1.5 rounded-full border border-amber-500/40 bg-amber-500/10 px-2 py-0.5 text-[11px] font-medium text-amber-600 transition-colors hover:bg-amber-500/20",children:[(0,B.jsx)("span",{className:"h-1.5 w-1.5 rounded-full bg-amber-500"}),"实时更新已断开"]});if(s)return(0,B.jsxs)("button",{type:"button",onClick:()=>window.location.reload(),title:"服务器已更新到新版本 · 点击刷新页面加载",className:"flex items-center gap-1.5 rounded-full border border-sky-500/40 bg-sky-500/10 px-2 py-0.5 text-[11px] font-medium text-sky-600 transition-colors hover:bg-sky-500/20",children:[(0,B.jsx)("span",{className:"h-1.5 w-1.5 rounded-full bg-sky-500"}),"有新版本 · 点击刷新"]});let a="live"===e;return(0,B.jsx)("span",{title:a?`实时更新正常 \xb7 上次更新 ${F2(r)}`:"正在连接实时更新…",className:"flex items-center px-1","aria-label":a?"实时更新正常":"正在连接实时更新",children:(0,B.jsx)("span",{className:a?"h-1.5 w-1.5 rounded-full bg-emerald-500":"h-1.5 w-1.5 animate-pulse rounded-full bg-muted-foreground/40"})})}var F3=e.i(63833);function F4(e){return null===e?"":e}function F6(e,r){let s=e?.machines?.find(e=>e.serverId===r);return e?.branch&&s?.state==="absent"?{kind:"absent",missing:{branch:e.branch,current:s,presentOn:e.machines.filter(e=>"present"===e.state)}}:s?.state==="creating"?{kind:"creating",machineName:s.name}:{kind:"present"}}let F7=()=>()=>{};function F8(){var e,r,s,n,i,a,o,l,c;let d,u,h,f,p,m,g,x,v,y,b,w,_,S,j,k,C,{projectId:N,tab:E,branch:D,threadId:R}=function(){let[e,r]=(0,$.useState)(()=>((0,F3.restoreLastLocation)(),Mh()));return(0,$.useEffect)(()=>{let e=()=>r(Mh());return window.addEventListener("popstate",e),()=>window.removeEventListener("popstate",e)},[]),e}(),{config:T}=(0,oU.useAppConfig)(),[A,M]=(0,$.useState)(()=>({branch:D,sessionId:new URLSearchParams(window.location.search).get("session")})),I=A.branch,F=A.sessionId,P=(0,$.useCallback)(e=>{M({branch:e,sessionId:null}),en(null)},[]),L=(0,$.useCallback)(e=>{M(r=>r.sessionId===e?r:{...r,sessionId:e})},[]),[z,O]=(0,$.useState)(null),[W,H]=(0,$.useState)(null),[q,K]=(0,$.useState)(null),[X,Y]=(0,$.useState)(void 0),[Q,ee]=(0,$.useState)(void 0),[et,er]=(0,$.useState)(null),[es,en]=(0,$.useState)(null);(0,$.useEffect)(()=>{let e=()=>{let e=new URLSearchParams(window.location.search).get("session");M(r=>r.sessionId===e?r:{...r,sessionId:e})};return window.addEventListener("popstate",e),()=>window.removeEventListener("popstate",e)},[]),(0,$.useEffect)(()=>{if(new URLSearchParams(window.location.search).has("project")){let e=Mf({projectId:N,tab:E,branch:D,threadId:R});window.history.replaceState(null,"",e)}},[]);let[ei,ea]=(0,$.useState)(!1),[eo,el]=(0,$.useState)(!1),[ec,ed]=(0,$.useState)(!1),[eu,eh]=(0,$.useState)(null),[ef,ep]=(0,$.useState)(E),[em,eg]=(0,$.useState)(R),[ex,ev]=(0,$.useState)(0),[ey,eb]=(0,$.useState)(0),[ew,e_]=(0,$.useState)(!1),[eS,ej]=(0,$.useState)(!1),ek=(0,$.useRef)(null),[eC,eN]=(0,$.useState)(void 0),[eE,eD]=(0,$.useTransition)(),{projects:eR,currentProject:eT,loading:eA,addProject:eI,createProject:eF,updateProject:eP,deleteProject:eL,selectProject:ez,routeProjectPending:eO,routeProjectNotFound:eB}=function(e){let[r,s]=(0,$.useState)([]),[n,i]=(0,$.useState)(null),[a,o]=(0,$.useState)(!0),[l,c]=(0,$.useState)(e),d=(0,$.useRef)(n),u=(0,$.useRef)(e);d.current=n,u.current=e;let h=l!==e,f=a||h,p=!f&&!!e&&!r.some(r=>r.id===e),m=(0,$.useCallback)(async()=>{o(!0);try{let e=await rD.api.getProjects();if(s(e),e.length>0&&!d.current){let r=u.current?e.find(e=>e.id===u.current):e[0];i(r??null)}}finally{o(!1)}},[]);(0,$.useEffect)(()=>{m()},[m]),(0,$.useEffect)(()=>{h&&!a&&(c(e),i(e?r.find(r=>r.id===e)??null:r[0]??null))},[e,a,r,h]);let g=async e=>{let r=await rD.api.createProject(e);return s(e=>[r,...e]),i(r),r},x=(0,$.useCallback)((e,r)=>{let n=e=>"function"==typeof r?r(e):r;s(r=>r.map(r=>r.id===e?n(r):r)),i(r=>r?.id===e?n(r):r)},[]),v=(0,$.useRef)(new Map),y=async(e,s)=>{let n,i={};if(void 0!==s.agentMode&&(i.agent_mode=s.agentMode),void 0!==s.executorMode&&(i.executor_mode=s.executorMode),Object.keys(i).length>0){let s=r.find(r=>r.id===e)??d.current;(n=v.current.get(e))||!s||s.id!==e||(n={seq:0,baseline:s},v.current.set(e,n)),n&&(n.seq+=1),x(e,e=>({...e,...i}))}let a=n?.seq,o=()=>!n||n.seq===a;try{let r=await rD.api.updateProject(e,s);return o()&&(n&&v.current.delete(e),x(e,r)),r}catch(r){throw n&&o()&&(v.current.delete(e),x(e,n.baseline)),r}},b=async e=>{await rD.api.deleteProject(e),s(r=>r.filter(r=>r.id!==e)),n?.id===e&&i(r.find(r=>r.id!==e)??null)};return{projects:r,currentProject:h?null:n,routeProjectPending:f,routeProjectNotFound:p,loading:a,addProject:e=>{s(r=>[e,...r]),i(e)},createProject:g,updateProject:y,deleteProject:b,selectProject:e=>{i(e)},refresh:m}}(N),e$=(0,$.useRef)(void 0);if(eT?.id!==eC){if(void 0!==eC){let s=(e=e$.current,r=eT?.id,e&&!e.checkPlacement&&void 0!==r&&e.projectId===r?{branch:e.branch,sessionId:e.sessionId}:{branch:null,sessionId:null});M(s),s.sessionId&&ev(e=>e+1)}eN(eT?.id)}let{worktrees:eW,loading:eH,stale:eU,listWarning:eq,refetch:eK}=function(e,r,s){let n=e?`${e}::${s??"local"}`:null,[i,a]=(0,$.useState)([]),[o,l]=(0,$.useState)(dA),[c,d]=(0,$.useState)(!0),[u,h]=(0,$.useState)(null),[f,p]=(0,$.useState)(null),m=(0,$.useRef)(null),g=e=>{m.current=e,h(e)},[x,v]=(0,$.useState)(null);if(n!==x){v(n),p(null);let e=n?dT.get(n):void 0;e&&(a(e),g(n),d(!0))}let y=(0,$.useRef)(0),b=(0,$.useRef)(null),w=(0,$.useRef)(0),_=(0,$.useRef)(null),S=(0,$.useRef)(r);S.current=r;let j=(0,$.useCallback)(async(r=!1)=>{if(r&&b.current)return;b.current?.abort();let s=new AbortController;b.current=s,w.current=0;let i=y.current;if(!e||!n){b.current=null,a([]),l(dA),g(null),p(null),d(!1);return}r||d(!0);let o=!1;try{let c=await rD.api.getProjectWorktreeList(e,void 0,s.signal);if(i!==y.current)return;let d=c.worktrees;dT.set(n,d),p(n),l(e=>{let r={staleRemote:c.stale??null,activeRemoteInvalid:!0===c.activeRemoteInvalid};return e.staleRemote?.serverId===r.staleRemote?.serverId&&e.activeRemoteInvalid===r.activeRemoteInvalid?e:r}),o=!0,a(e=>{let s=r?function(e,r,s){if(void 0===s||r.some(e=>e.branch===s))return r;let n=e.findIndex(e=>e.branch===s);if(n<0)return r;let i=[...r];return i.splice(Math.min(n,i.length),0,e[n]),i}(e,d,S.current):d;return e.length===s.length&&e.every((e,r)=>e.branch===s[r].branch&&e.currentBranch===s[r].currentBranch&&e.expectedBranch===s[r].expectedBranch&&dR(e)===dR(s[r]))?e:s})}catch(e){if(i!==y.current||e instanceof Error&&"AbortError"===e.name)return;console.error("Failed to fetch worktrees:",e),r||m.current===n||a([{branch:null}])}finally{if(i!==y.current||b.current!==s)return;o&&(w.current=Date.now()),g(n),r||d(!1),b.current=null}},[e,n]),k=(0,$.useCallback)(()=>{Date.now()-w.current<5e3||j(!0)},[j]);return(0,$.useEffect)(()=>(j(),()=>{b.current?.abort(),b.current=null,y.current+=1}),[j]),(0,$.useEffect)(()=>{let e=_.current;_.current={projectId:n,branch:r},e&&e.projectId===n&&e.branch!==r&&j(!0)},[n,r,j]),(0,a8.useGlobalEventStream)(r=>{if(!e||r.projectId!==e)return;let s="session:status"===r.type&&("stopped"===r.status||"error"===r.status);("session:taskCompleted"===r.type||"executor:stopped"===r.type||s)&&j(!0)}),(0,$.useEffect)(()=>{let e=null,r=()=>{null!==e&&(window.clearInterval(e),e=null)},s=()=>{r(),e=window.setInterval(()=>void j(!0),3e5)},n=()=>k(),i=()=>{"visible"===document.visibilityState?(k(),s()):r()};return window.addEventListener("focus",n),document.addEventListener("visibilitychange",i),"visible"===document.visibilityState&&s(),()=>{r(),window.removeEventListener("focus",n),document.removeEventListener("visibilitychange",i)}},[j,k]),{worktrees:i,loading:c||f!==n,stale:u!==n,listWarning:o,refetch:(0,$.useCallback)(()=>j(!1),[j])}}(eT?.id??null,I,eT?.agent_mode??null),{statuses:eV,rootDirty:eX,defaultTarget:eY,repositoryLabel:eG,repositoryServerId:eJ,setTarget:eZ,refetch:eQ}=function(e,r){let[s,n]=(0,$.useState)(new Map),[i,a]=(0,$.useState)(!1),[o,l]=(0,$.useState)(null),[c,d]=(0,$.useState)(null),[u,h]=(0,$.useState)(null),[f,p]=(0,$.useState)(0),[m,g]=(0,$.useState)(e);e!==m&&(g(e),n(new Map),a(!1),l(null),d(null));let x=(0,$.useCallback)(()=>p(e=>e+1),[]);return(0,$.useEffect)(()=>{let s,i=r.map(e=>e.branch).filter(e=>null!==e),o=new Set(i),c=(s=r.find(e=>null===e.branch))?(void 0===s.currentBranch?s.expectedBranch:s.currentBranch)??null:null,u=i.map(e=>({branch:e}));null===c||o.has(c)||u.push({branch:c});let f=!1;return(async()=>{if(!e||0===u.length){f||(n(new Map),a(!1),l(null),d(null));return}if(dI(e).length>0&&(await function(e){let r=dF.get(e);if(r)return r;let s=(async()=>{let r=new Map;for(;;){let s=dI(e).filter(({key:e,target:s})=>r.get(e)!==s);if(0===s.length)break;for(let{key:n,branch:i,target:a}of s){r.set(n,a);let s=!1;try{s=await rD.api.setMergeTarget(e,i,a,{ifAbsent:!0})}catch{}if(s)try{localStorage.getItem(n)===a&&localStorage.removeItem(n)}catch{}}}})();return dF.set(e,s),s.finally(()=>{dF.get(e)===s&&dF.delete(e)}),s}(e),f))return;let r=await rD.api.getMergeStatus(e,u);f||r.ok&&(n(function(e){let r=new Map;for(let s of e){if("target-not-found"===s.error&&s.requestedTarget){r.set(s.branch,{branch:s.branch,error:s.error,requestedTarget:s.requestedTarget,targetSource:s.targetSource});continue}!s.error&&s.target&&s.status&&r.set(s.branch,{branch:s.branch,status:s.status,unmergedCount:s.unmergedCount??0,dirty:s.dirty??!1,target:s.target})}return r}(r.entries.filter(e=>o.has(e.branch)).map(e=>e.branch===c?{...e,dirty:!1}:e))),a(null!==c&&(r.entries.find(e=>e.branch===c)?.dirty??!1)),l(function(e){for(let r of e)if("default"===r.targetSource&&r.target)return r.target;return null}(r.entries)),d(r.repository.label),h("local"===r.repository.kind?"local":r.repository.remoteServerId))})(),()=>{f=!0}},[e,r,f,x]),{statuses:s,rootDirty:i,defaultTarget:o,repositoryLabel:c,repositoryServerId:u,setTarget:(0,$.useCallback)((r,s)=>{e&&rD.api.setMergeTarget(e,r,s).then(e=>{e&&x()})},[e,x]),refetch:x}}(eT?.id??null,eW),e0=function(e,r){let[s,n]=(0,$.useState)(()=>Iu(e));s.projectId!==e&&n(Iu(e));let i=(0,$.useRef)(e);(0,$.useEffect)(()=>{i.current=e},[e]);let a=(0,$.useRef)(new Map),o=(0,$.useRef)(new Map),[l,c]=(0,$.useState)(0),d=(0,$.useRef)(new Set),u=(0,$.useCallback)(e=>{n(r=>{let s=Date.now();return Ip(e(r,s),d.current,s)})},[]),h=(0,$.useCallback)((e,r)=>{let s=i.current;if(!s)return;let n=`${s}\0${e??""}`,l=(a.current.get(n)??0)+1;a.current.set(n,l);let{request:c,issuedAt:d}=Aq(s,e,{force:r});c.then(r=>{i.current!==s||(o.current.get(n)??0)>=l||(o.current.set(n,l),u((s,n)=>(function(e,r,s,n,i=n){let a=e;for(let e of s)a=If(a,e,n);let o=new Set(s.map(e=>e.id)),l=[];for(let e of a.entries.values())(e.branch??null)===(r??null)&&(o.has(e.runId)||e.insertedAt>i||l.push(e.runId));return l.length>0?Ih(a,l,n):a})(s,e,r,n,d)))}).catch(()=>{})},[u]);(0,$.useEffect)(()=>{e&&h(r,!1)},[e,r,h]);let{state:f}=(0,a8.useConnectionStatus)(),p=(0,$.useRef)(null),m=(0,$.useRef)(!1);(0,$.useEffect)(()=>{let s=p.current;p.current=f;let n=Ii(s,f,m.current);"live"===f&&(m.current=!0),n&&e&&h(r,!0)},[f,e,r,h]),(0,a8.useGlobalEventStream)(r=>{if("workflow:run-updated"!==r.type||!e||r.projectId!==e)return;let s=r.run;s&&"string"==typeof s.id&&u((e,r)=>If(e,s,r))});let g=(0,$.useCallback)((e,r)=>{u((s,n)=>If(s,e,n,r))},[u]),x=(0,$.useCallback)(e=>{d.current=e,n(r=>Ip(r,e,Date.now()))},[]),v=(0,$.useMemo)(()=>[...s.entries.values()],[s]),y=JSON.stringify([...new Set(v.filter(e=>null===e.appearedAt).map(e=>e.branch??""))].sort());(0,$.useEffect)(()=>{let e=JSON.parse(y);if(0===e.length)return;let r=setInterval(()=>{for(let r of(n(e=>(function(e,r){let s=[];for(let n of e.entries.values())n.insertedAt+72e4<=r&&s.push(n.runId);let n=s.length>0?Ih(e,s,r):e,i=!1;for(let e of n.tombstones.values())if(e<=r){i=!0;break}if(i){let e=new Map;for(let[s,i]of n.tombstones)i>r&&e.set(s,i);n={...n,tombstones:e}}return n})(e,Date.now())),e))h(""===r?null:r,!0);c(e=>e+1)},5e3);return()=>clearInterval(r)},[y,h]);let b=(0,$.useMemo)(()=>v.filter(e=>null===e.appearedAt&&"preparing"!==e.run.status&&!Ic(e.run.status)).map(e=>e.reviewerSessionId),[v]);return(0,$.useMemo)(()=>({entries:v,addRun:g,awaitedSessionIds:b,pollTick:l,markAppeared:x}),[v,g,b,l,x])}(eT?.id??null,I),e1=function(e,r,s,n){let i=JSON.stringify((r??[]).map(e=>e.branch)),a=(0,$.useMemo)(()=>JSON.parse(i),[i]),[o,l]=(0,$.useState)([]),[c,d]=(0,$.useState)(null);e!==c&&(d(e),l(e?Ia.get(e)??[]:[]));let u=(0,$.useRef)(e);u.current=e;let h=(0,$.useRef)(new Map),f=(0,$.useRef)(0),p=(0,$.useRef)(0),m=(0,$.useRef)(0),g=(0,$.useCallback)(e=>!(e<m.current)&&(m.current=e,!0),[]);(0,$.useEffect)(()=>{e&&Ia.set(e,o)},[e,o]);let[x,v]=(0,$.useState)(null),y=(0,$.useCallback)((e,r,s,n=1/0)=>{if(null===r||u.current!==e)return;let i=r.filter(e=>{let r=h.current.get(e.id);return void 0===r||r<=n});l(e=>{let r,n=(r=new Map(e.map(e=>[e.id,e])),i.map(e=>{let s=r.get(e.id);return s&&"New Session"===e.title&&"New Session"!==s.title?{...e,title:s.title}:e}));if(!s||n.some(e=>e.id===s))return n;let a=e.find(e=>e.id===s);return a?[a,...n]:n})},[]),b=(0,$.useCallback)(async r=>{if(!e)return void l([]);let s=f.current,n=++p.current,i=await Is(e);if(u.current===e&&g(n)){if("incomplete"===i)return void v(r=>({projectId:e,gen:(r?.gen??0)+1}));v(r=>r?.projectId===e?null:r),y(e,i,r?.keepSessionId,s)}},[e,y,g]);(0,$.useEffect)(()=>{let e=!1;return b().catch(r=>{e||console.warn("[ResidentSessions] refresh failed:",r)}),()=>{e=!0}},[b]),(0,$.useEffect)(()=>{if(!e||x?.projectId!==e)return;let r=!1,s=f.current,n=++p.current;return In(e,a).then(i=>{!r&&g(n)&&y(e,i,void 0,s)}).catch(e=>{r||console.warn("[ResidentSessions] fallback refresh failed:",e)}),()=>{r=!0}},[e,x,a,y,g]);let{state:w}=(0,a8.useConnectionStatus)(),_=(0,$.useRef)(null),S=(0,$.useRef)(!1);(0,$.useEffect)(()=>{let e=_.current;_.current=w;let r=Ii(e,w,S.current);"live"===w&&(S.current=!0),r&&b().catch(e=>console.warn("[ResidentSessions] reconnect refresh failed:",e))},[w,b]);let j=n&&n.sessionIds.length>0?`${n.tick}#${n.sessionIds.join("\0")}`:"",k=(0,$.useRef)(o);return(0,$.useEffect)(()=>{k.current=o},[o]),(0,$.useEffect)(()=>{!j||j.slice(j.indexOf("#")+1).split("\0").every(e=>k.current.some(r=>r.id===e))||b().catch(e=>console.warn("[ResidentSessions] awaited refresh failed:",e))},[j,b]),(0,$.useEffect)(()=>{if(!s||!s.processAlive||!e||s.projectId!==e||h.current.has(s.id))return;let r=!k.current.some(e=>e.id===s.id);l(e=>(function(e,r){let s=e.findIndex(e=>e.id===r.id);if(-1===s)return[r,...e];let n=e[s],i="New Session"===r.title&&"New Session"!==n.title?n.title:r.title,a=[...e];return a[s]={...r,title:i,status:n.status},a})(e,s)),r&&b({keepSessionId:s.id}).catch(e=>console.warn("[ResidentSessions] seed refresh failed:",e))},[e,s,b]),(0,a8.useGlobalEventStream)(r=>{if(e&&r.projectId===e){if("session:process"===r.type){let e="string"==typeof r.sessionId?r.sessionId:null,s="boolean"==typeof r.alive?r.alive:null,n="string"==typeof r.branch?r.branch:null;if(!e||null===s)return;if(!s){h.current.set(e,++f.current),l(r=>r.filter(r=>r.id!==e));return}h.current.delete(e),b().catch(e=>console.warn("[ResidentSessions] process refresh failed:",e)),null!==n&&l(r=>r.map(r=>r.id===e?{...r,branch:n}:r))}if("session:status"===r.type){let e="string"==typeof r.sessionId?r.sessionId:null,s="string"==typeof r.status?r.status:null;if(!e||!s)return;l(r=>r.map(r=>r.id===e?{...r,status:s}:r))}if("session:title"===r.type){let e="string"==typeof r.sessionId?r.sessionId:null;if(!e)return;l(s=>{var n,i;return i=("string"==typeof(n=r.title)?n.trim():"")||"New Session",s.map(r=>r.id===e?{...r,title:i}:r)})}}}),(0,$.useMemo)(()=>{let e=new Map;for(let r of o){let s=r.branch??"",n=e.get(s)??[];n.push(r),e.set(s,n)}for(let r of e.values())r.sort((e,r)=>(r.updated_at??"").localeCompare(e.updated_at??""));return e},[o])}(eT?.id??null,eW,z,{sessionIds:e0.awaitedSessionIds,tick:e0.pollTick}),e2=(0,$.useMemo)(()=>{let e=new Set;for(let r of e1.values())for(let s of r)e.add(s.id);return e},[e1]),e5=(0,$.useCallback)(e=>{for(let r of e1.values()){let s=r.find(r=>r.id===e);if(s)return s.title}return null},[e1]),e3=(0,$.useMemo)(()=>(function(e,r,s){if(0===r.length)return e;let n=new Map(e),i=new Set;for(let r of e.values())for(let e of r)i.add(e.id);for(let e of r){var a;if(null!==e.appearedAt||i.has(e.reviewerSessionId))continue;let r=e.branch??"",o=n.get(r)??[];n.set(r,[(a=s(e.sourceSessionId),{id:e.reviewerSessionId,projectId:e.projectId,branch:e.branch,title:Im(e,a),status:"preparing",processAlive:!1,updated_at:e.run.created_at,kind:Io,runId:e.runId}),...o])}return n})(e1,e0.entries,e5),[e1,e0.entries,e5]),e4=null!==es&&es.projectId===eT?.id,e6=e4?e0.entries.find(e=>e.runId===es.runId):void 0,{tasks:e7,loading:e8,createTask:e9,updateTask:te,deleteTask:tt,archive:tr,unarchive:ts,refetch:tn}=function(e){let[r,s]=(0,$.useState)([]),[n,i]=(0,$.useState)(!0),a=(0,$.useCallback)(async()=>{if(!e){s([]),i(!1);return}try{let r=await rD.api.getTasks(e,{includeArchived:!0});s(r)}catch(e){console.error("Failed to fetch tasks:",e)}finally{i(!1)}},[e]);(0,$.useEffect)(()=>{a()},[a]);let o=(0,$.useCallback)(async r=>{if(!e)return null;try{let n=await rD.api.createTask(e,r);return s(e=>[...e,n]),n}catch(e){return console.error("Failed to create task:",e),null}},[e]),l=(0,$.useCallback)(async(e,n)=>{s(r=>r.map(r=>r.id===e?{...r,...n,updated_at:new Date().toISOString()}:r));try{let r=await rD.api.updateTask(e,n);return s(s=>s.map(s=>s.id===e?r:s)),r}catch(e){return console.error("Failed to update task:",e),s(r),null}},[r]),c=(0,$.useCallback)(async e=>{s(r=>r.filter(r=>r.id!==e));try{await rD.api.deleteTask(e)}catch(e){console.error("Failed to delete task:",e),s(r)}},[r]),d=(0,$.useCallback)(async e=>{s(r=>r.map(r=>r.id===e?{...r,archived_at:Date.now()}:r));try{let r=await rD.api.archiveTask(e);s(s=>s.map(s=>s.id===e?r:s))}catch(e){console.error("Failed to archive task:",e),s(r)}},[r]),u=(0,$.useCallback)(async e=>{s(r=>r.map(r=>r.id===e?{...r,archived_at:null}:r));try{let r=await rD.api.unarchiveTask(e);s(s=>s.map(s=>s.id===e?r:s))}catch(e){console.error("Failed to unarchive task:",e),s(r)}},[r]),h=(0,$.useCallback)(async n=>{if(e){s(n.map(e=>r.find(r=>r.id===e)).filter(e=>void 0!==e));try{await rD.api.reorderTasks(e,n)}catch(e){console.error("Failed to reorder tasks:",e),s(r)}}},[e,r]);return{tasks:r,loading:n,createTask:o,updateTask:l,deleteTask:c,archive:d,unarchive:u,reorderTasks:h,refetch:a}}(eT?.id??null),{schedules:ti,loading:ta,createSchedule:to,updateSchedule:tl,deleteSchedule:tc,runNow:td}=function(e){let[r,s]=(0,$.useState)([]),[n,i]=(0,$.useState)(!1),[a,o]=(0,$.useState)(null);e!==a&&(o(e),s(e?dL.get(e)??[]:[])),(0,$.useEffect)(()=>{e&&dL.set(e,r)},[e,r]);let l=(0,$.useRef)(e),c=(0,$.useRef)(0),d=(0,$.useCallback)(async(e,r,n)=>{if(!e){c.current===r&&(s([]),i(!1));return}n&&i(!0);try{let n=await rD.api.getSchedules(e);c.current===r&&s(n)}catch(e){console.error("Failed to fetch schedules:",e)}finally{n&&c.current===r&&i(!1)}},[]);(0,$.useEffect)(()=>{l.current=e,c.current+=1,d(e,c.current,!0)},[e,d]);let u=(0,$.useCallback)(async()=>{let e=l.current;e&&await d(e,c.current,!1)},[d]),h=(0,$.useRef)(u);(0,$.useEffect)(()=>{h.current=u},[u]),(0,a8.useGlobalEventStream)(e=>{!e.type?.startsWith("schedule:")||l.current&&e.projectId===l.current&&h.current()});let f=(0,$.useCallback)(async r=>{if(!e)throw Error("No project selected");let s=await rD.api.createSchedule(e,r);return await u(),s},[e,u]),p=(0,$.useCallback)(async(e,r)=>{let s=await rD.api.updateSchedule(e,r);return await u(),s},[u]),m=(0,$.useCallback)(async e=>{await rD.api.deleteSchedule(e),await u()},[u]),g=(0,$.useCallback)(async(e,r)=>{let s=r;if(!s){let e=crypto.randomUUID();s={requestId:e,runId:e}}let n=await rD.api.runScheduleNow(e,s);return await u(),n},[u]);return{schedules:r,loading:n,refetch:u,createSchedule:f,updateSchedule:p,deleteSchedule:m,runNow:g}}(eT?.id??null),[tu,th]=(0,$.useState)(null),[tf,tp]=(0,$.useState)(null),[tm,tg]=(0,$.useState)(null),[tx,tv]=(0,$.useState)(null),[ty,tb]=(0,$.useState)(!1),[tw,t_]=(0,$.useState)(null),tS=(0,$.useCallback)(e=>{tp({kind:"task",taskId:e.id,status:e.status}),ep("tasks")},[ep]),{activity:tj,since:tk,refetch:tC,setOptimisticActivity:tN}=function(e){let[r,s]=(0,$.useState)(new Map),[n,i]=(0,$.useState)(new Map),a=(0,$.useRef)(new Map),o=(0,$.useRef)(new Map),l=(0,$.useRef)(null),c=(0,$.useCallback)(async()=>{if(!e){s(new Map),i(new Map),o.current=new Map,l.current=null,a.current=new Map;return}try{let r=await (0,rD.authFetch)(`${"localhost"===window.location.hostname&&"3000"===window.location.port?"http://localhost:5173":""}/api/projects/${e}/branches/activity`);if(!r.ok)return;let n=await r.json(),c=l.current!==e,{nextActivity:d,nextSince:u}=function(e,r,s,n){let i=new Map,a=new Map,o=[];for(let l of e){let e=l.branch??"",c=s.get(e)??0;if(!n&&l.since<c){let s=r.get(e);if(void 0!==s){i.set(e,s),a.set(e,c);continue}}i.set(e,l.activity),a.set(e,l.since),n||r.get(e)===l.activity||o.push(l.branch)}return{nextActivity:i,nextSince:a,transitions:o}}(n.branches,o.current,a.current,c);s(d),i(u),o.current=d,l.current=e,a.current=u}catch{}},[e]);return(0,$.useEffect)(()=>{c()},[c]),(0,a8.useGlobalEventStream)(r=>{var n,l,c;let d,u;if("branch:activity"!==r.type||!e||r.projectId!==e)return;let h=(n=r,l=o.current,c=a.current,d=n.branch??"",u=c.get(d)??0,n.since<u?{kind:"stale"}:l.get(d)===n.activity?{kind:"redundant",key:d}:{kind:"transition",key:d});"stale"===h.kind||(a.current.set(h.key,r.since),i(new Map(a.current)),"redundant"!==h.kind&&s(e=>{let s=new Map(e);return s.set(h.key,r.activity),o.current=s,s}))}),{activity:r,since:n,refetch:c,setOptimisticActivity:(0,$.useCallback)((e,r)=>{s(s=>{let n=function(e,r,s){let n=r??"";if(e.get(n)===s)return e;let i=new Map(e);return i.set(n,s),i}(s,e,r);return o.current=n,n})},[])}}(eT?.id??null),{rules:tE,createRule:tD,updateRule:tR,deleteRule:tT}=function(e,r){let[s,n]=(0,$.useState)([]),[i,a]=(0,$.useState)(!0),o=(0,$.useCallback)(async()=>{if(!e){n([]),a(!1);return}try{let s=await rD.api.getRules(e,r);n(s)}catch(e){console.error("Failed to fetch rules:",e)}finally{a(!1)}},[e,r]);(0,$.useEffect)(()=>{o()},[o]);let l=(0,$.useCallback)(async s=>{if(!e)return null;try{let i=await rD.api.createRule(e,{...s,branch:r});return n(e=>[...e,i]),i}catch(e){return console.error("Failed to create rule:",e),null}},[e,r]),c=(0,$.useCallback)(async(e,r)=>{n(s=>s.map(s=>s.id===e?{...s,...r,enabled:void 0!==r.enabled?+!!r.enabled:s.enabled,updated_at:new Date().toISOString()}:s));try{let s=await rD.api.updateRule(e,r);return n(r=>r.map(r=>r.id===e?s:r)),s}catch(e){return console.error("Failed to update rule:",e),n(s),null}},[s]),d=(0,$.useCallback)(async e=>{n(r=>r.filter(r=>r.id!==e));try{await rD.api.deleteRule(e)}catch(e){console.error("Failed to delete rule:",e),n(s)}},[s]);return{rules:s,loading:i,createRule:l,updateRule:c,deleteRule:d,refetch:o}}(eT?.id??null,I),{commands:tA,createCommand:tM,updateCommand:tI,deleteCommand:tF}=function(e,r){let[s,n]=(0,$.useState)([]),[i,a]=(0,$.useState)(!0),o=(0,$.useCallback)(async()=>{if(!e){n([]),a(!1);return}try{let s=await rD.api.getCommands(e,r);n(s)}catch(e){console.error("Failed to fetch commands:",e)}finally{a(!1)}},[e,r]);(0,$.useEffect)(()=>{o()},[o]);let l=(0,$.useCallback)(async s=>{if(!e)return null;try{let i=await rD.api.createCommand(e,{...s,branch:r});return n(e=>[...e,i]),i}catch(e){return console.error("Failed to create command:",e),null}},[e,r]),c=(0,$.useCallback)(async(e,r)=>{n(s=>s.map(s=>s.id===e?{...s,...r,updated_at:new Date().toISOString()}:s));try{let s=await rD.api.updateCommand(e,r);return n(r=>r.map(r=>r.id===e?s:r)),s}catch(e){return console.error("Failed to update command:",e),n(s),null}},[s]),d=(0,$.useCallback)(async e=>{n(r=>r.filter(r=>r.id!==e));try{await rD.api.deleteCommand(e)}catch(e){console.error("Failed to delete command:",e),n(s)}},[s]);return{commands:s,loading:i,createCommand:l,updateCommand:c,deleteCommand:d,refetch:o}}(eT?.id??null,I),tP=(0,$.useRef)(null),tL=(0,$.useRef)(null),[tz,tO]=(0,$.useState)(!1),tB=(0,$.useCallback)(()=>{let e=tL.current;e&&(e.isCollapsed()?e.expand():e.collapse())},[]),t$=(0,$.useSyncExternalStore)(F7,U,()=>!1),tW=`${tz?"Show":"Hide"} Main Chat`,tH=(0,$.useSyncExternalStore)(EO,EB,E$),tU=eT?.id??null,tq=eT?.agent_mode??null,tK=(0,$.useCallback)(e=>!!tU&&tH.has(EW(tU,e,tq)),[tH,tU,tq]),tV=(0,$.useCallback)(e=>{if(tU)return tH.get(EW(tU,e,tq))},[tH,tU,tq]),tX=(0,$.useCallback)(e=>tk.get(F4(e)),[tk]),tY=(0,$.useMemo)(()=>(function(e,r,s,n){let i=new Map;if(!e)return i;for(let a of e){let e=F4(a.branch),o=r.get(e);if(!s?.(a.branch)){i.set(e,o??"idle");continue}if("main-running"===o||"main-waiting"===o)i.set(e,o);else if("main-completed"===o){let r=n?.backendSince?.(a.branch)??0,s=n?.placeholderSince?.(a.branch)??0;i.set(e,s>r?"idle":"main-completed")}else i.set(e,"idle")}return i})(eW,tj,tK,{backendSince:tX,placeholderSince:tV}),[eW,tj,tK,tX,tV]);o=eQ,l=tY,c=eT?.id??null,d=(0,$.useRef)(new Set),h=(u=function(e){let r=new Set;if(!e)return r;for(let[s,n]of e)dP.has(n)&&r.add(s);return r}(l)).size>0,f=JSON.stringify(Array.from(u).sort()),(0,$.useEffect)(()=>{let e=new Set(JSON.parse(f)),r=d.current;d.current=e,function(e,r){for(let s of e)if(!r.has(s))return!0;return!1}(r,e)&&o()},[f,o]),(0,$.useEffect)(()=>{let e=()=>o();return window.addEventListener("focus",e),()=>window.removeEventListener("focus",e)},[o]),(0,a8.useGlobalEventStream)(e=>{"executor:stopped"===e.type&&e.projectId===c&&o(),"merge-target:updated"===e.type&&null!==c&&e.projectId===c&&o(),"files:changed"===e.type&&null!==c&&e.projectId===c&&o()}),(0,$.useEffect)(()=>{let e=null,r=()=>{null!==e&&(clearInterval(e),e=null)},s=()=>{r(),e=setInterval(o,h?3e4:6e4)},n=()=>{"visible"===document.visibilityState?s():r()};return"visible"===document.visibilityState&&s(),document.addEventListener("visibilitychange",n),()=>{r(),document.removeEventListener("visibilitychange",n)}},[o,h]);let[tG,tJ]=(0,$.useState)(null),[tZ,tQ]=(0,$.useState)(null),[t0,t1]=(0,$.useState)(null),[t2,t5]=(0,$.useState)(!1),t3="workspace"===ef&&t2&&null!==tZ,{notifications:t4,unreadCount:t6,markRead:t7,markAllRead:t8,remove:t9,clear:re,markReviewRunRead:rt}=function(e,r=null,s=null){let[n,i]=(0,$.useState)([]),a=(0,$.useRef)(new Set),o=(0,$.useRef)(new Set),l=(0,$.useRef)(n);(0,$.useEffect)(()=>{l.current=n},[n]);let c=(0,$.useRef)(new Set);(0,$.useEffect)(()=>{for(let e of new Set(Object.values(FL)))FH.has(e)||FU.has(e)||(FU.add(e),(async()=>{try{let r=await fetch(e),s=await r.blob(),n=new Audio(URL.createObjectURL(s));n.preload="auto",n.load(),FH.set(e,n)}catch{}finally{FU.delete(e)}})())},[]);let d=(0,$.useRef)(e),u=(0,$.useRef)({resultAt:r,turnEndAt:s});(0,$.useEffect)(()=>{d.current=e,u.current={resultAt:r,turnEndAt:s}},[e,r,s]);let h=(0,$.useRef)(new Map);(0,$.useEffect)(()=>{if(!e||null===r)return;let n=()=>{if("visible"!==document.visibilityState)return;let n=h.current.get(e),i=(e,r)=>null==e?r:null===r?e:Math.max(e,r);h.current.set(e,{resultAt:i(n?.resultAt,r),turnEndAt:i(n?.turnEndAt,s)})};return n(),document.addEventListener("visibilitychange",n),()=>document.removeEventListener("visibilitychange",n)},[e,r,s]);let f=(0,$.useCallback)(e=>{if(null===e.session_id)return!1;let r=h.current.get(e.session_id);return void 0!==r&&FK(e,r)},[]),p=(0,$.useCallback)(e=>{if(o.current.has(e))return;o.current.add(e);let r=Date.now();i(s=>s.map(s=>s.id===e&&null===s.read_at?{...s,read_at:r}:s)),(0,rD.markNotificationRead)(e).catch(()=>{i(s=>s.map(s=>s.id===e&&s.read_at===r?{...s,read_at:null}:s))}).finally(()=>{o.current.delete(e)})},[]),m=(0,$.useCallback)(e=>null===e.read_at&&null!==e.workflow_run_id&&c.current.has(e.workflow_run_id)?((0,rD.markNotificationRead)(e.id).catch(()=>{}),{...e,read_at:Date.now()}):e,[]);(0,$.useEffect)(()=>{let e=!1;return(0,rD.getNotifications)({limit:100}).then(r=>{if(e)return;for(let e of r)a.current.add(e.id);let s=r.map(m);i(e=>{let r=[];for(let e of s)r=FO(r,e);for(let n of e)s.some(e=>e.id===n.id)||(r=FO(r,n));return r});try{window.localStorage.removeItem("vibedeckx:completion-notifications")}catch{}}).catch(e=>{console.warn("[notifications] hydration failed:",e)}),()=>{e=!0}},[m]);let g=(0,$.useCallback)((e,r=!1)=>{let s=!a.current.has(e.id);a.current.add(e.id);let n=d.current,o=null!==e.session_id&&e.session_id===n&&FK(e,u.current),l=null!==e.workflow_run_id&&c.current.has(e.workflow_run_id),h=o||l||r;return i(r=>FO(r,h?{...e,read_at:e.read_at??Date.now()}:e)),h&&null===e.read_at&&(0,rD.markNotificationRead)(e.id).catch(()=>{}),s&&!l&&!r},[]),x=(0,$.useRef)(null),v=(0,$.useRef)(!1);(0,$.useEffect)(()=>(v.current=!1,()=>{v.current=!0,x.current&&clearTimeout(x.current)}),[]);let y=(0,$.useCallback)(()=>{x.current&&(clearTimeout(x.current),x.current=null);let e=r=>{(0,rD.getNotifications)({limit:100}).then(e=>{let r=Date.now(),s=null;for(let n of e){if(a.current.has(n.id))continue;let e=g(n,f(n)),i=null===n.read_at&&r-n.created_at<=12e4;e&&i&&(!s||n.created_at>s.created_at)&&(s=n)}s&&FV(FL[s.kind])}).catch(s=>{let n=Fz[r];console.warn(`[notifications] reconnect catch-up failed${void 0===n?", giving up":`, retrying in ${n}ms`}:`,s),void 0===n||v.current||(x.current=setTimeout(()=>{x.current=null,e(r+1)},n))})};e(0)},[g,f]);(0,a8.useGlobalEventStream)(e=>{if(e.type===a8.STREAM_RECONNECTED_EVENT)return void y();if("notification:created"!==e.type)return;let r=e.notification;r?.id&&g(r)&&FV(FL[r.kind])}),(0,$.useEffect)(()=>{if(e&&null!==r)for(let a of n){if(a.session_id!==e||null!==a.read_at||!FK(a,{resultAt:r,turnEndAt:s})||o.current.has(a.id))continue;let{id:n}=a;o.current.add(n),(0,rD.markNotificationRead)(n).then(()=>{i(e=>e.map(e=>e.id===n&&null===e.read_at?{...e,read_at:Date.now()}:e))}).catch(()=>{}).finally(()=>{o.current.delete(n)})}},[e,r,s,n]);let b=(0,$.useCallback)(e=>p(e),[p]),w=(0,$.useCallback)((e,r)=>{for(let s of(r?.runEnded&&c.current.add(e),l.current))s.workflow_run_id===e&&null===s.read_at&&p(s.id)},[p]),_=(0,$.useCallback)(()=>{let e=Date.now();i(r=>r.some(e=>null===e.read_at)?r.map(r=>null===r.read_at?{...r,read_at:e}:r):r),(0,rD.markAllNotificationsRead)().catch(()=>i(n))},[n]),S=(0,$.useCallback)(e=>{p(e),i(r=>r.filter(r=>r.id!==e))},[p]),j=(0,$.useCallback)(()=>{(0,rD.markAllNotificationsRead)().catch(e=>console.warn("[notifications] read-all failed:",e)),i(e=>e.length?[]:e)},[]),k=FW(n).reduce((e,r)=>e+ +!!r.unread,0);return{notifications:n,unreadCount:k,markRead:b,markAllRead:_,remove:S,clear:j,markReviewRunRead:w}}(t3?tG:null,t3?tZ:null,t3?t0:null),rr=(0,$.useMemo)(()=>({markReviewRunRead:rt}),[rt]),rs=(0,$.useMemo)(()=>t4.filter(e=>e.project_id===eT?.id&&null===e.read_at).length,[t4,eT?.id]),rn=(0,$.useCallback)(()=>{tN(I,"working")},[I,tN]),ri=(0,$.useCallback)(()=>{tn()},[tn]),ra=(0,$.useCallback)((e,r)=>{M({branch:e,sessionId:r}),en(null),ev(e=>e+1),e_(!1),(0,FI.touchRecentSessionOpen)(r)},[]),ro=(0,$.useRef)(0),rl=(0,$.useCallback)((e,r,s)=>{ep("workspace"),P(e),K({branch:e,path:r,line:s,nonce:++ro.current})},[P]),rc=(0,$.useCallback)((e,r,s)=>{en({projectId:e,runId:r}),M({branch:s,sessionId:null}),ev(e=>e+1),e_(!1),ep("workspace")},[]),rd=(0,$.useCallback)(e=>{"preparing-review"===e.kind&&e.runId?rc(e.projectId,e.runId,e.branch):(ra(e.branch,e.id),ep("workspace"))},[ra,rc]),ru=(0,$.useCallback)(e=>{let r=e0.entries.find(r=>r.runId===e);r&&rc(r.projectId,r.runId,r.branch)},[e0.entries,rc]),rh=e0.markAppeared;(0,$.useEffect)(()=>{rh(e2)},[e2,rh]),(0,$.useEffect)(()=>{if(!es)return;if(es.projectId!==eT?.id)return void en(null);let e=e6?null!==e6.appearedAt?{kind:"switch",branch:e6.branch,sessionId:e6.reviewerSessionId}:"preparing"===e6.run.status?{kind:"wait"}:Ic(e6.run.status)?{kind:"gone"}:e2.has(e6.reviewerSessionId)?{kind:"switch",branch:e6.branch,sessionId:e6.reviewerSessionId}:{kind:"wait"}:{kind:"gone"};"switch"===e.kind&&ra(e.branch,e.sessionId)},[es,e6,e2,eT?.id,ra]);let rf=(0,$.useCallback)(e=>{tC();let r=eR.find(r=>r.id===e.projectId);(0,FI.touchSessionStarted)({sessionId:e.id,projectId:e.projectId,projectName:r?.name??"",targetId:r?.agent_mode??"local",branch:e.branch});let s=function(e,r=new Date){return!0!==e.processAlive?null:{id:e.id,projectId:e.projectId,branch:e.branch,title:"New Session",status:e.status,processAlive:!0,updated_at:r.toISOString()}}(e);s&&O(s)},[tC,eR]),rp=(0,$.useCallback)((e,r)=>{r.trim()&&(0,FI.updateCachedSessionTitle)(e,r.trim())},[]),rm=(0,$.useCallback)(()=>{tN(I,"idle")},[I,tN]),rg=(0,$.useCallback)(()=>{tn()},[tn]);s=eT?.id??null,n={onTaskChanged:rg},p=(0,$.useRef)(n.onTaskChanged),(0,$.useEffect)(()=>{p.current=n.onTaskChanged}),(0,a8.useGlobalEventStream)(e=>{s&&e.projectId===s&&("task:created"===e.type||"task:updated"===e.type||"task:deleted"===e.type)&&p.current?.()});let rx=(0,$.useMemo)(()=>{let e=F4(I);return e7.find(r=>r.assigned_branch===e)??null},[e7,I]);(0,$.useCallback)(e=>{eD(async()=>{await ek.current?.submitMessage(e.description??e.title)})},[]);let[rv,ry]=(0,$.useState)(null),rb=(0,$.useCallback)((e,r)=>{eT&&(EU(EW(eT.id,r,eT.agent_mode)),ry({projectId:eT.id,branch:r,tasks:[{...e,subtasks:T9(e7,e.id)}],nonce:Date.now()}),ep("workspace"),P(r),ev(e=>e+1))},[eT,e7,P]);(0,$.useCallback)(e=>{te(e,{assigned_branch:null})},[te]),(0,$.useEffect)(()=>{let e=e$.current;if(void 0!==e&&e.projectId!==eT?.id&&(e$.current=void 0,e_(!1),ej(!1)),!eU&&0!==eW.length){if(void 0!==e&&e.projectId===eT?.id){let r=eW.find(r=>r.branch===e.branch);if(r&&e.checkPlacement){e$.current=void 0,e_(!1),ej(!1);let s=F6(r,eT?.agent_mode??"local");return"absent"===s.kind?void er(s.missing):("creating"===s.kind&&xN.toast.info(`'${e.branch}' is still being created on ${s.machineName}`),void P(e.branch))}if(r){e$.current=void 0,I!==e.branch||F!==e.sessionId?e.sessionId?ra(e.branch,e.sessionId):P(e.branch):e.sessionId&&(0,FI.touchRecentSessionOpen)(e.sessionId),ej(!1),e_(!1);return}return void(eH||(e$.current=void 0,e_(!1),ej(!1),xN.toast.warning(`Workspace "${e.branch??"main"}" no longer exists`),P(eW[0].branch)))}!eH&&(eW.some(e=>e.branch===I)||(F&&xN.toast.warning(`Workspace "${I??"main"}" no longer exists`),P(eW[0].branch)))}},[eW,eH,eU,I,F,eT?.id,eT?.agent_mode,ra,P]),(0,$.useEffect)(()=>{(ew||eS)&&(null===I&&(eH||0!==eW.length)||(e_(!1),ej(!1)))},[ew,eS,I,eH,eW]);let rw=(0,$.useCallback)((e,r,s=null)=>{if(ep("workspace"),e===eT?.id)return void(s?ra(r,s):P(r));let n=eR.find(r=>r.id===e);n&&(s?e_(!0):ej(!0),e$.current={projectId:e,branch:r,sessionId:s},ez(n))},[eT?.id,eR,ez,ra,P]),[r_,rS]=(0,$.useState)(!1),rj=!!eT;(0,$.useEffect)(()=>{let e=e=>{if("k"===e.key&&(e.metaKey||e.ctrlKey)){e.preventDefault(),rS(e=>!e);return}if(G(e,V)){if("workspace"!==ef||!rj)return;e.preventDefault(),e.repeat||tB();return}"o"===e.key.toLowerCase()&&e.shiftKey&&(e.metaKey||e.ctrlKey)&&"workspace"===ef&&(e.preventDefault(),ev(e=>e+1),ek.current?.startNewConversation())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[ef,rj,tB]);let rk=(0,$.useRef)(!1),rC=(0,$.useCallback)(async(e,r)=>{let s=eR.find(r=>r.id===e);if(!s)return null;let n="local"===r?"local":r;return(s.agent_mode??"local")!==n?eP(s.id,{agentMode:n}):s},[eR,eP]),rN=(i={projectId:eT?.id??null,resolveProjectForTarget:rC,getScheduleRun:rD.api.getScheduleRun,getSchedules:rD.api.getSchedules,runScheduleNow:td,selectAgentSession:(e,r)=>{ep("workspace"),ra(e,r)},openScheduleRun:(e,r)=>{th(e),tv(r),ep("schedules")},onRerunResult:e=>{e.replay&&e.status&&"starting"!==e.status&&"running"!==e.status?"completed"===e.status?xN.toast.success("Schedule run already completed"):xN.toast.error(`Schedule run already ${e.status}`):xN.toast.success("Schedule run started")},onError:(e,r)=>{console.error(`Project activity ${e} failed:`,r),"session-navigation"===e?xN.toast.error("Failed to open agent session"):"schedule-navigation"===e?xN.toast.error("Failed to open schedule run"):xN.toast.error(r instanceof Error?r.message:"Failed to start schedule run")}},(m=(0,$.useRef)(i)).current=i,(g=(0,$.useRef)({projectId:i.projectId,generation:0})).current.projectId!==i.projectId&&(g.current={projectId:i.projectId,generation:g.current.generation+1}),x=(0,$.useRef)(new Map),v=(0,$.useRef)(new Map),y=(0,$.useCallback)(e=>g.current.projectId===e.projectId&&g.current.generation===e.generation,[]),b=(0,$.useCallback)(async(e,r)=>{if(!e.projectId)return null;let s=m.current,n=await s.getScheduleRun(r);if(!y(e))return null;if(n.project_id!==e.projectId)throw Error("Schedule run does not belong to the active project");let i=await s.getSchedules(e.projectId);if(!y(e))return null;let a=i.find(e=>e.id===n.schedule_id);if(!a||a.project_id!==e.projectId)throw Error("Schedule does not belong to the active project");return{run:n,schedule:a}},[y]),w=(0,$.useCallback)(async(e,r,s)=>{let n={...g.current};if(n.projectId)try{let i=await m.current.resolveProjectForTarget(n.projectId,r);if(!y(n)||!i||i.id!==n.projectId)return;m.current.selectAgentSession(s,e,i.id)}catch(e){y(n)&&m.current.onError("session-navigation",e)}},[y]),_=(0,$.useCallback)(async(e,r)=>{let s={...g.current};try{let n=await b(s,e);if(!n||!y(s))return;if(r&&r!==n.schedule.id)throw Error("Schedule run target changed while opening");m.current.openScheduleRun(n.schedule.id,e)}catch(e){y(s)&&m.current.onError("schedule-navigation",e)}},[y,b]),S=(0,$.useCallback)(e=>{let r={...g.current};if(!r.projectId)return Promise.resolve();let s=`${r.projectId}:${e}`,n=v.current.get(s);if(n)return n;let i=(async()=>{try{let n,i=dz(r.projectId,e),a=x.current.get(i)??function(e,r,s){try{let n=window.sessionStorage.getItem(e);if(!n)return;let i=JSON.parse(n);return"string"==typeof i.requestId&&"string"==typeof i.runId&&i.projectId===r&&"string"==typeof i.scheduleId&&i.scheduleId.length>0&&i.sourceRunId===s?i:void 0}catch{return}}(i,r.projectId,e);if(a){let e=await m.current.getSchedules(r.projectId);if(!y(r))return;let s=a.scheduleId,o=e.find(e=>e.id===s);if(!o||o.project_id!==r.projectId)throw Error("Schedule does not belong to the active project");n=o,x.current.set(i,a)}else{let o=await b(r,e);if(!o||!y(r))return;n=o.schedule;let l=crypto.randomUUID();a={projectId:r.projectId,scheduleId:n.id,requestId:l,runId:l,sourceRunId:e},x.current.set(i,a);var s=a;try{window.sessionStorage.setItem(i,JSON.stringify(s))}catch{}}let o={requestId:a.requestId,runId:a.runId,sourceRunId:a.sourceRunId},l=await m.current.runScheduleNow(n.id,o);if(x.current.delete(i),dO(i),!y(r))return;m.current.onRerunResult(l)}catch(s){if(r.projectId&&("object"==typeof s&&null!==s&&"status"in s&&409===s.status||"object"==typeof s&&null!==s&&"durable"in s&&!0===s.durable)){let s=dz(r.projectId,e);x.current.delete(s),dO(s)}throw y(r)&&m.current.onError("schedule-rerun",s),s}})().finally(()=>{v.current.get(s)===i&&v.current.delete(s)});return v.current.set(s,i),i},[y,b]),{openAgentSession:w,openScheduleRun:_,runScheduleAgain:S}),rR=(a={projectId:eT?.id??null,schedules:ti,getTask:rD.api.getTask,resolveProjectForTarget:rC,openTask:t_,selectAgentSession:(e,r)=>{ep("workspace"),ra(e,r)},selectWorkspace:e=>{P(e),ep("workspace")},selectSchedule:e=>{th(e),ep("schedules")},openScheduleRun:rN.openScheduleRun,onError:e=>{xN.toast.error(e instanceof Error?e.message:"Unable to open Context item")}},(j=(0,$.useRef)(a)).current=a,(k=(0,$.useRef)({projectId:a.projectId,generation:0})).current.projectId!==a.projectId&&(k.current={projectId:a.projectId,generation:k.current.generation+1}),C=(0,$.useCallback)(e=>e.projectId===k.current.projectId&&e.generation===k.current.generation,[]),{open:(0,$.useCallback)(async e=>{let r={...k.current},s=e.navigation;if(!r.projectId||e.deleted||!s){C(r)&&j.current.onError(Error("This Context item is no longer available"));return}try{if("task"===s.kind){let e=await j.current.getTask(r.projectId,s.taskId);if(!C(r))return;if(e.id!==s.taskId||e.project_id!==r.projectId)throw Error("Task is no longer available in this project");j.current.openTask(e);return}if("agent_session"===s.kind||"workspace"===s.kind){let e=await j.current.resolveProjectForTarget(r.projectId,s.target);if(!C(r))return;if(!e||e.id!==r.projectId)throw Error("Workspace target is no longer available");"agent_session"===s.kind?j.current.selectAgentSession(s.branch,s.sessionId,e.id):j.current.selectWorkspace(s.branch,e.id);return}if("schedule"===s.kind){let e=j.current.schedules.find(e=>e.id===s.scheduleId&&e.project_id===r.projectId);if(!e)throw Error("Schedule is no longer available in this project");j.current.selectSchedule(e.id);return}await j.current.openScheduleRun(s.runId,s.scheduleId)}catch(e){C(r)&&j.current.onError(e)}},[C])}),rT=(0,$.useCallback)(e=>{eg(e),P(null),ep("project-chat")},[P]),rA=(0,$.useCallback)(()=>{eg(null),ep("project-info")},[]);(0,$.useEffect)(()=>{ep(E),eg("project-chat"===E?R:null),"project-chat"===E&&P(null)},[E,R,P]);let rM=(0,$.useCallback)(e=>{tv(r=>r===e?null:r)},[]),rI=(0,$.useCallback)(e=>{if(rk.current)return;let r=eR.find(r=>r.id===e);r&&(rS(!1),ez(r),ep("project-info"))},[eR,ez]),rF=(0,$.useCallback)(async e=>{if(!rk.current){rk.current=!0,rS(!1);try{let r=await rC(e.projectId,e.targetId);if(!r)return;(0,FI.touchRecentSessionOpen)(e.sessionId,e),ep("workspace"),r.id===eT?.id?ra(e.branch,e.sessionId):(e_(!0),e$.current={projectId:r.id,branch:e.branch,sessionId:e.sessionId},ez(r))}catch(e){console.error("Quick switcher navigation failed:",e),xN.toast.error("Failed to open session")}finally{rk.current=!1}}},[eT?.id,rC,ez,ra]);(0,$.useEffect)(()=>{if(eA||eO||eB)return;let e=Mf({projectId:eT?.id,tab:ef,branch:I,threadId:em}),r=e;if(F){let s=new URL(e,window.location.origin);s.searchParams.set("session",F),r=s.pathname+s.search}window.history.replaceState(null,"",r),(0,F3.saveLastLocation)(r)},[eT?.id,ef,I,em,eA,eO,eB,F]),(0,$.useEffect)(()=>{eO||(0,F3.settleRestoredLocation)(!eB)&&(P(null),window.history.replaceState(null,"","/"),window.dispatchEvent(new PopStateEvent("popstate")))},[eO,eB,P]);let rP=(0,$.useCallback)(e=>{eK(),P(e)},[eK,P]),rL=(0,$.useCallback)((e,r)=>{e.branch&&(Y(e),ee(r),el(!0))},[]),rz=(0,$.useCallback)(e=>{let r=F6(null===e?void 0:eW.find(r=>r.branch===e),eT?.agent_mode??"local");"absent"===r.kind?er(r.missing):("creating"===r.kind&&xN.toast.info(`'${e}' is still being created on ${r.machineName}`),P(e))},[eW,eT?.agent_mode,P]),rO=(0,$.useCallback)(e=>{if(rS(!1),ep("workspace"),e.projectId===eT?.id)return void rz(e.branch);let r=eR.find(r=>r.id===e.projectId);r&&(ej(!0),e$.current={projectId:e.projectId,branch:e.branch,sessionId:null,checkPlacement:!0},ez(r))},[eT?.id,eR,rz,ez]),rB=(0,$.useRef)({content:"",at:0}),r$=(0,$.useCallback)(e=>{let r=Date.now(),s=rB.current;s.content===e&&r-s.at<600||(rB.current={content:e,at:r},tP.current?.sendMessage(e))},[]),rW=(0,$.useCallback)(()=>{let e=`Please perform the following git operations for this worktree:
|
|
54
43
|
|
|
55
44
|
1. Commit all current uncommitted changes with an appropriate commit message
|
|
56
45
|
2. Fetch the latest changes from the remote main branch
|
|
57
46
|
3. Rebase the current branch onto main (resolve any conflicts if needed)
|
|
58
47
|
4. Merge the current branch into main
|
|
59
48
|
|
|
60
|
-
Please proceed step by step and let me know if there are any issues or conflicts that need manual resolution.`;ek.current?.submitMessage(e)},[]),rH=(0,$.useCallback)(async e=>{if(eT)try{await eP(eT.id,{agentMode:e})}catch(e){console.error("Failed to update agent mode:",e)}},[eT,eP]),rU=(0,$.useCallback)(async e=>{if(eT)try{await eP(eT.id,{executorMode:e})}catch(e){console.error("Failed to update executor mode:",e)}},[eT,eP]),rq=!eT;return(0,B.jsx)(ul,{children:(0,B.jsx)(ue,{children:(0,B.jsx)(I0,{value:rr,children:(0,B.jsx)("div",{className:"h-screen flex flex-col w-full",children:(0,B.jsxs)(xj,{projectId:eT?.id??void 0,children:[(0,B.jsxs)("div",{"data-focus-region":"default",className:"border-b border-border bg-card px-3 h-[44px] flex items-center justify-between sticky top-0 z-10",children:[(0,B.jsxs)("div",{className:"flex items-center gap-[9px]",children:[(0,B.jsx)(xL.Logo,{size:22}),(0,B.jsxs)("h1",{className:"text-[13px] font-semibold tracking-tight text-foreground",children:["VibeDeck",(0,B.jsx)("span",{className:"text-primary font-bold",children:"X"})]})]}),(0,B.jsxs)("div",{className:"flex items-center gap-2.5",children:["workspace"===ef&&!rq&&(0,B.jsx)(Z.Button,{variant:"ghost",size:"icon-sm","aria-label":tW,"aria-pressed":tz,title:`${tW} (${J(t$,V)})`,onClick:tB,children:tz?(0,B.jsx)(mD,{className:"h-4 w-4"}):(0,B.jsx)(mE,{className:"h-4 w-4"})}),(0,B.jsx)(Z.Button,{variant:"ghost",size:"icon-sm","aria-label":"Search projects, workspaces, and sessions",title:"Search (⌘K / Ctrl+K)",onClick:()=>rS(!0),children:(0,B.jsx)(oo,{className:"h-4 w-4"})}),(0,B.jsx)(F4,{}),(0,B.jsx)(mA.DocsButton,{}),(0,B.jsx)(mT,{inviteUrl:T?.discordInviteUrl}),(0,B.jsx)(F7,{}),(0,B.jsx)(F1,{notifications:t4,unreadCount:t6,projects:eR,onNavigate:rw,markRead:t7,markAllRead:t8,remove:t9,clear:re}),(0,B.jsx)(xP,{})]})]}),(0,B.jsxs)("div",{className:"flex-1 flex overflow-hidden",children:[(0,B.jsx)(um,{activeView:ef,onViewChange:e=>{"project-chat"!==e&&eg(null),ep(e)},worktrees:eW,worktreesStale:eU,staleRemoteName:eq.staleRemote?.name??null,activeRemoteInvalid:eq.activeRemoteInvalid,selectedBranch:I,onBranchChange:rz,currentProject:eT,onCreateWorktreeOpen:()=>el(!0),onDeleteWorktree:e=>{eh(e),ed(!0)},onManageWorkspaceRemotes:e=>rL(e),onAnchorRootWorkspace:async e=>{if(eT){try{await rD.api.anchorRootWorkspace(eT.id,e),xN.toast.success(`Main workspace anchored to ${e}`)}catch(e){xN.toast.error(e instanceof Error?e.message:"Failed to anchor workspace")}eK()}},onSetRootWorkspaceBranch:async e=>{if(eT){try{await rD.api.setRootWorkspaceBranch(eT.id,e),xN.toast.success(`Main workspace anchored to ${e}`)}catch(e){xN.toast.error(e instanceof Error?e.message:"Failed to change workspace branch")}eK()}},mergeStatuses:eV,mergeRootDirty:eX,mergeDefaultTarget:eY,mergeRepositoryLabel:eG,mergeRepositoryServerId:eJ,onMergeTargetChange:eZ,onMergeBadgeClick:e=>{P(e),ep("workspace"),eb(e=>e+1)},workspaceStatuses:tY,residentSessions:e3,selectedSessionId:e6?e6.reviewerSessionId:F,onResidentSessionSelect:rd,hasProject:!rq,projects:eR,onSelectProject:ez,onCreateProjectOpen:()=>ea(!0),schedules:ti,selectedScheduleId:tu,onScheduleSelect:e=>{th(e),ep("schedules")},onCreateScheduleOpen:()=>{ep("schedules"),tb(!0)},tasks:e7,selectedTaskId:tm,onTasksOpen:()=>ep("tasks"),onTaskSelect:tS,onCreateTaskOpen:()=>{tp({kind:"draft"}),ep("tasks")}}),(0,B.jsx)("div",{className:rq&&("workspace"===ef||"tasks"===ef||"project-info"===ef||"project-chat"===ef)?"flex-1 overflow-hidden":"hidden",children:(0,B.jsx)("div",{className:"h-full flex items-center justify-center bg-background",children:(0,B.jsxs)("div",{className:"text-center space-y-6",children:[(0,B.jsx)("div",{className:"mx-auto w-16 h-16 rounded-2xl bg-primary/10 flex items-center justify-center",children:eB?(0,B.jsx)(oI,{className:"h-8 w-8 text-destructive"}):(0,B.jsx)(eM,{className:"h-8 w-8 text-primary"})}),(0,B.jsx)("h1",{className:"text-3xl font-bold tracking-tight text-foreground",children:eB?"Project not found":"Welcome to VibeDeckX"}),(0,B.jsx)("p",{className:"text-muted-foreground max-w-sm mx-auto leading-relaxed",role:eB?"alert":void 0,children:eB?"This project does not exist or you do not have access to it.":"Create your first project to get started with AI-powered development."}),eB?(0,B.jsx)(Z.Button,{variant:"outline",size:"lg",onClick:()=>{let e=eR[0];e&&ez(e),window.history.replaceState(null,"",e?Mf({projectId:e.id,tab:"project-info"}):"/"),window.dispatchEvent(new PopStateEvent("popstate")),ep("project-info"),eg(null)},children:"Back to projects"}):(0,B.jsxs)(Z.Button,{variant:"accent",size:"lg",onClick:()=>ea(!0),className:"shadow-md",children:[(0,B.jsx)(eM,{className:"h-5 w-5 mr-2"}),"Create Project"]})]})})}),(0,B.jsx)("div",{className:"workspace"!==ef||rq?"hidden":"flex-1 overflow-hidden flex",children:(0,B.jsxs)(hD,{direction:"horizontal",autoSaveId:"workspace-panels",children:[(0,B.jsx)(uT,{ref:tL,defaultSize:33,minSize:25,collapsible:!0,collapsedSize:0,onCollapse:()=>tO(!0),onExpand:()=>tO(!1),children:(0,B.jsxs)("div",{"data-focus-region":"default",className:"h-full flex flex-col overflow-hidden",children:[eT&&(0,B.jsx)("div",{className:"px-4 py-3 border-b border-border/60 flex-shrink-0",children:(0,B.jsx)(rE,{assignedTask:rx,rules:tE,commands:tA,onCreateRule:tD,onUpdateRule:tR,onDeleteRule:tT,onCreateCommand:tM,onUpdateCommand:tI,onDeleteCommand:tF,onExecuteCommand:r$,onUpdateTaskTitle:(e,r)=>te(e,{title:r}),onCompleteTask:e=>{te(e,{status:"done",assigned_branch:null})}})}),(0,B.jsx)("div",{className:"flex-1 overflow-hidden",children:(0,B.jsx)(Fu,{ref:tP,projectId:eT?.id??null,branch:I},`${eT?.id??""}:${I??""}`)})]})}),(0,B.jsx)(hR,{}),(0,B.jsx)(uT,{defaultSize:67,minSize:25,children:(0,B.jsx)("div",{className:"h-full flex flex-col overflow-hidden",children:(0,B.jsx)(NG,{active:"workspace"===ef,agentSessionId:tG,onAgentTabActiveChange:t5,projectId:eT?.id??null,selectedBranch:I,activateAgentTabNonce:ex,diffCompareNonce:ey,terminalRequest:W,fileOpenRequest:q,forceAgentTab:ew,mergeTarget:I?dM(eV.get(I))??eY:null,onMergeRequest:rW,project:eT,onExecutorModeChange:rU,agentSlot:(0,B.jsxs)(B.Fragment,{children:[e4&&es&&(0,B.jsx)(It,{runId:es.runId,entry:e6,title:e6?Im(e6,e5(e6.sourceSessionId)):"Review",onOpenSource:(e,r)=>ra(r,e)}),(0,B.jsx)("div",{className:e4?"hidden":"contents",children:(0,B.jsx)(Ie,{ref:ek,projectId:eT?.id??null,branch:I,sessionId:F,navPending:ew||eS||e4,preparingReviews:e0.entries,onReviewStarted:e0.addRun,onViewPreparingReview:ru,setSessionUrlParam:L,onActiveSessionChange:tJ,onActiveSessionResultAtChange:tQ,onActiveSessionTurnEndAtChange:t1,project:eT,onAgentModeChange:rH,onTaskCompleted:ri,onSessionStarted:rf,onSessionTitleUpdated:rp,onSessionSelected:Fz.touchRecentSessionOpen,onStatusChange:rn,onNewConversation:rm,onOpenSchedule:e=>{th(e),ep("schedules")},onOpenTask:t_,taskSessionRequest:rv,onTaskSessionRequestHandled:()=>ry(null)})})]})})})})]})}),(0,B.jsx)("div",{className:"tasks"!==ef||rq?"hidden":"flex-1 overflow-hidden",children:(0,B.jsx)(FL,{active:"tasks"===ef&&!rq,projectId:eT?.id??null,tasks:e7,loading:e8,worktrees:eW,onCreateTask:e9,onUpdateTask:te,onDeleteTask:tt,onArchiveTask:tr,onUnarchiveTask:ts,onOpenSourceSession:e=>{e.source_session_id&&(e.source_tool_use_id&&(Tt={toolUseId:e.source_tool_use_id,at:Date.now()}),ep("workspace"),ra(e.source_session?.branch??null,e.source_session_id))},onStartSession:rb,onOpenFile:rl,openRequest:tf,onSelectedTaskChange:tg})}),"project-info"===ef&&!rq&&eT&&(0,B.jsx)("div",{className:"flex-1 overflow-hidden",children:(0,B.jsx)(lT,{project:eT,waitingCount:rs,onOpenProjectChatThread:rT,onOpenAgentSession:(e,r,s)=>{rN.openAgentSession(e,r,s)},onOpenScheduleRun:(e,r)=>{rN.openScheduleRun(e,r)},onRunScheduleAgain:rN.runScheduleAgain,onViewAllTasks:()=>ep("tasks"),onOpenTaskInTasks:tS,onProjectUpdated:eP})}),"project-chat"===ef&&!rq&&eT&&em&&(0,B.jsx)("div",{className:"flex-1 overflow-hidden",children:(0,B.jsx)(dD,{projectId:eT.id,threadId:em,projectName:eT.name,onBack:rA,onSelectThread:rT,onOpenContext:e=>{rR.open(e)},onOpenAgentSession:(e,r,s)=>rN.openAgentSession(e,r,s),onOpenScheduleRun:(e,r)=>rN.openScheduleRun(e,r),onRunScheduleAgain:rN.runScheduleAgain})}),"schedules"===ef&&!rq&&eT&&(0,B.jsx)("div",{className:"flex-1 overflow-hidden",children:(0,B.jsx)(mN,{projectId:eT?.id??"",hasLocal:!!eT?.path,schedules:ti,loading:ta,selectedId:tu,onSelect:th,worktrees:eW,onCreate:to,onUpdate:tl,onDelete:async e=>{await tc(e),tu===e&&th(null)},onOpenSourceSession:(e,r)=>{ep("workspace"),ra(e,r)},onRunNow:td,createOpen:ty,onCreateOpenChange:tb,openRunId:tx,onOpenRunHandled:rM})}),"remote-servers"===ef&&(0,B.jsx)("div",{className:"flex-1 overflow-hidden",children:(0,B.jsxs)("div",{className:"h-full flex flex-col overflow-auto",children:[(0,B.jsx)(ug,{title:"Remote Servers"}),(0,B.jsx)("div",{className:"flex-1 px-6 py-5 flex justify-center",children:(0,B.jsx)("div",{className:"w-full max-w-2xl",children:(0,B.jsx)(xy,{})})})]})}),(0,B.jsx)("div",{className:"settings"!==ef?"hidden":"flex-1 overflow-hidden",children:(0,B.jsx)(xi,{})})]}),eT&&(0,B.jsx)(xA,{projectId:eT.id,project:eT,open:eo,onOpenChange:e=>{el(e),e||(Y(void 0),ee(void 0))},onWorktreeCreated:rP,initialBranchName:X?.branch??void 0,initialMachines:X?.machines,initialTargets:X?.targets,initialSelectedTargets:Q}),(0,B.jsx)(xM,{missing:et,onOpenChange:e=>{e||er(null)},onCreateHere:()=>{if(er(null),!et)return;let e=eW.find(e=>e.branch===et.branch);e&&rL(e,[et.current.serverId])},onOpenAnyway:()=>{er(null),et&&P(et.branch)}}),(0,B.jsx)(aZ,{task:tw,open:null!==tw,onOpenChange:e=>{e||t_(null)},onOpenInTasks:tS}),(0,B.jsx)(mM,{open:ei,onOpenChange:ea,onProjectCreated:e=>{eI(e),ep("project-info")}}),eT&&(0,B.jsx)(xI,{projectId:eT.id,worktree:eu,open:ec,onOpenChange:ed,onWorktreeDeleted:eK,onOpenTerminal:(e,r)=>{P(e),ep("workspace"),H(e=>({targetId:r,nonce:(e?.nonce??0)+1}))}}),(0,B.jsx)(FB,{open:r_,onOpenChange:rS,onNavigateProject:rI,onNavigateWorkspace:rO,onNavigateSession:rF})]})})})})})}e.s(["default",()=>Pr],837031)}]);
|
|
49
|
+
Please proceed step by step and let me know if there are any issues or conflicts that need manual resolution.`;ek.current?.submitMessage(e)},[]),rH=(0,$.useCallback)(async e=>{if(eT)try{await eP(eT.id,{agentMode:e})}catch(e){console.error("Failed to update agent mode:",e)}},[eT,eP]),rU=(0,$.useCallback)(async e=>{if(eT)try{await eP(eT.id,{executorMode:e})}catch(e){console.error("Failed to update executor mode:",e)}},[eT,eP]),rq=!eT;return(0,B.jsx)(ul,{children:(0,B.jsx)(ue,{children:(0,B.jsx)(IG,{value:rr,children:(0,B.jsx)("div",{className:"h-screen flex flex-col w-full",children:(0,B.jsxs)(xj,{projectId:eT?.id??void 0,children:[(0,B.jsxs)("div",{"data-focus-region":"default",className:"border-b border-border bg-card px-3 h-[44px] flex items-center justify-between sticky top-0 z-10",children:[(0,B.jsxs)("div",{className:"flex items-center gap-[9px]",children:[(0,B.jsx)(xL.Logo,{size:22}),(0,B.jsxs)("h1",{className:"text-[13px] font-semibold tracking-tight text-foreground",children:["VibeDeck",(0,B.jsx)("span",{className:"text-primary font-bold",children:"X"})]})]}),(0,B.jsxs)("div",{className:"flex items-center gap-2.5",children:["workspace"===ef&&!rq&&(0,B.jsx)(Z.Button,{variant:"ghost",size:"icon-sm","aria-label":tW,"aria-pressed":tz,title:`${tW} (${J(t$,V)})`,onClick:tB,children:tz?(0,B.jsx)(mD,{className:"h-4 w-4"}):(0,B.jsx)(mE,{className:"h-4 w-4"})}),(0,B.jsx)(Z.Button,{variant:"ghost",size:"icon-sm","aria-label":"Search projects, workspaces, and sessions",title:"Search (⌘K / Ctrl+K)",onClick:()=>rS(!0),children:(0,B.jsx)(oo,{className:"h-4 w-4"})}),(0,B.jsx)(F1,{}),(0,B.jsx)(mA.DocsButton,{}),(0,B.jsx)(mT,{inviteUrl:T?.discordInviteUrl}),(0,B.jsx)(F5,{}),(0,B.jsx)(FJ,{notifications:t4,unreadCount:t6,projects:eR,onNavigate:rw,markRead:t7,markAllRead:t8,remove:t9,clear:re}),(0,B.jsx)(xP,{})]})]}),(0,B.jsxs)("div",{className:"flex-1 flex overflow-hidden",children:[(0,B.jsx)(um,{activeView:ef,onViewChange:e=>{"project-chat"!==e&&eg(null),ep(e)},worktrees:eW,worktreesStale:eU,staleRemoteName:eq.staleRemote?.name??null,activeRemoteInvalid:eq.activeRemoteInvalid,selectedBranch:I,onBranchChange:rz,currentProject:eT,onCreateWorktreeOpen:()=>el(!0),onDeleteWorktree:e=>{eh(e),ed(!0)},onManageWorkspaceRemotes:e=>rL(e),onAnchorRootWorkspace:async e=>{if(eT){try{await rD.api.anchorRootWorkspace(eT.id,e),xN.toast.success(`Main workspace anchored to ${e}`)}catch(e){xN.toast.error(e instanceof Error?e.message:"Failed to anchor workspace")}eK()}},onSetRootWorkspaceBranch:async e=>{if(eT){try{await rD.api.setRootWorkspaceBranch(eT.id,e),xN.toast.success(`Main workspace anchored to ${e}`)}catch(e){xN.toast.error(e instanceof Error?e.message:"Failed to change workspace branch")}eK()}},mergeStatuses:eV,mergeRootDirty:eX,mergeDefaultTarget:eY,mergeRepositoryLabel:eG,mergeRepositoryServerId:eJ,onMergeTargetChange:eZ,onMergeBadgeClick:e=>{P(e),ep("workspace"),eb(e=>e+1)},workspaceStatuses:tY,residentSessions:e3,selectedSessionId:e6?e6.reviewerSessionId:F,onResidentSessionSelect:rd,hasProject:!rq,projects:eR,onSelectProject:ez,onCreateProjectOpen:()=>ea(!0),schedules:ti,selectedScheduleId:tu,onScheduleSelect:e=>{th(e),ep("schedules")},onCreateScheduleOpen:()=>{ep("schedules"),tb(!0)},tasks:e7,selectedTaskId:tm,onTasksOpen:()=>ep("tasks"),onTaskSelect:tS,onCreateTaskOpen:()=>{tp({kind:"draft"}),ep("tasks")}}),(0,B.jsx)("div",{className:rq&&("workspace"===ef||"tasks"===ef||"project-info"===ef||"project-chat"===ef)?"flex-1 overflow-hidden":"hidden",children:(0,B.jsx)("div",{className:"h-full flex items-center justify-center bg-background",children:(0,B.jsxs)("div",{className:"text-center space-y-6",children:[(0,B.jsx)("div",{className:"mx-auto w-16 h-16 rounded-2xl bg-primary/10 flex items-center justify-center",children:eB?(0,B.jsx)(oI,{className:"h-8 w-8 text-destructive"}):(0,B.jsx)(eM,{className:"h-8 w-8 text-primary"})}),(0,B.jsx)("h1",{className:"text-3xl font-bold tracking-tight text-foreground",children:eB?"Project not found":"Welcome to VibeDeckX"}),(0,B.jsx)("p",{className:"text-muted-foreground max-w-sm mx-auto leading-relaxed",role:eB?"alert":void 0,children:eB?"This project does not exist or you do not have access to it.":"Create your first project to get started with AI-powered development."}),eB?(0,B.jsx)(Z.Button,{variant:"outline",size:"lg",onClick:()=>{let e=eR[0];e&&ez(e),window.history.replaceState(null,"",e?Mf({projectId:e.id,tab:"project-info"}):"/"),window.dispatchEvent(new PopStateEvent("popstate")),ep("project-info"),eg(null)},children:"Back to projects"}):(0,B.jsxs)(Z.Button,{variant:"accent",size:"lg",onClick:()=>ea(!0),className:"shadow-md",children:[(0,B.jsx)(eM,{className:"h-5 w-5 mr-2"}),"Create Project"]})]})})}),(0,B.jsx)("div",{className:"workspace"!==ef||rq?"hidden":"flex-1 overflow-hidden flex",children:(0,B.jsxs)(hD,{direction:"horizontal",autoSaveId:"workspace-panels",children:[(0,B.jsx)(uT,{ref:tL,defaultSize:33,minSize:25,collapsible:!0,collapsedSize:0,onCollapse:()=>tO(!0),onExpand:()=>tO(!1),children:(0,B.jsxs)("div",{"data-focus-region":"default",className:"h-full flex flex-col overflow-hidden",children:[eT&&(0,B.jsx)("div",{className:"px-4 py-3 border-b border-border/60 flex-shrink-0",children:(0,B.jsx)(rE,{assignedTask:rx,rules:tE,commands:tA,onCreateRule:tD,onUpdateRule:tR,onDeleteRule:tT,onCreateCommand:tM,onUpdateCommand:tI,onDeleteCommand:tF,onExecuteCommand:r$,onUpdateTaskTitle:(e,r)=>te(e,{title:r}),onCompleteTask:e=>{te(e,{status:"done",assigned_branch:null})}})}),(0,B.jsx)("div",{className:"flex-1 overflow-hidden",children:(0,B.jsx)(Fo,{ref:tP,projectId:eT?.id??null,branch:I},`${eT?.id??""}:${I??""}`)})]})}),(0,B.jsx)(hR,{}),(0,B.jsx)(uT,{defaultSize:67,minSize:25,children:(0,B.jsx)("div",{className:"h-full flex flex-col overflow-hidden",children:(0,B.jsx)(NG,{active:"workspace"===ef,agentSessionId:tG,onAgentTabActiveChange:t5,projectId:eT?.id??null,selectedBranch:I,activateAgentTabNonce:ex,diffCompareNonce:ey,terminalRequest:W,fileOpenRequest:q,forceAgentTab:ew,mergeTarget:I?dM(eV.get(I))??eY:null,onMergeRequest:rW,project:eT,onExecutorModeChange:rU,agentSlot:(0,B.jsxs)(B.Fragment,{children:[e4&&es&&(0,B.jsx)(It,{runId:es.runId,entry:e6,title:e6?Im(e6,e5(e6.sourceSessionId)):"Review",onOpenSource:(e,r)=>ra(r,e)}),(0,B.jsx)("div",{className:e4?"hidden":"contents",children:(0,B.jsx)(Ie,{ref:ek,projectId:eT?.id??null,branch:I,sessionId:F,navPending:ew||eS||e4,preparingReviews:e0.entries,onReviewStarted:e0.addRun,onViewPreparingReview:ru,setSessionUrlParam:L,onActiveSessionChange:tJ,onActiveSessionResultAtChange:tQ,onActiveSessionTurnEndAtChange:t1,project:eT,onAgentModeChange:rH,onTaskCompleted:ri,onSessionStarted:rf,onSessionTitleUpdated:rp,onSessionSelected:FI.touchRecentSessionOpen,onStatusChange:rn,onNewConversation:rm,onOpenSchedule:e=>{th(e),ep("schedules")},onOpenTask:t_,taskSessionRequest:rv,onTaskSessionRequestHandled:()=>ry(null)})})]})})})})]})}),(0,B.jsx)("div",{className:"tasks"!==ef||rq?"hidden":"flex-1 overflow-hidden",children:(0,B.jsx)(FM,{active:"tasks"===ef&&!rq,projectId:eT?.id??null,tasks:e7,loading:e8,worktrees:eW,onCreateTask:e9,onUpdateTask:te,onDeleteTask:tt,onArchiveTask:tr,onUnarchiveTask:ts,onOpenSourceSession:e=>{e.source_session_id&&(e.source_tool_use_id&&(Tt={toolUseId:e.source_tool_use_id,at:Date.now()}),ep("workspace"),ra(e.source_session?.branch??null,e.source_session_id))},onStartSession:rb,onOpenFile:rl,openRequest:tf,onSelectedTaskChange:tg})}),"project-info"===ef&&!rq&&eT&&(0,B.jsx)("div",{className:"flex-1 overflow-hidden",children:(0,B.jsx)(lT,{project:eT,waitingCount:rs,onOpenProjectChatThread:rT,onOpenAgentSession:(e,r,s)=>{rN.openAgentSession(e,r,s)},onOpenScheduleRun:(e,r)=>{rN.openScheduleRun(e,r)},onRunScheduleAgain:rN.runScheduleAgain,onViewAllTasks:()=>ep("tasks"),onOpenTaskInTasks:tS,onProjectUpdated:eP})}),"project-chat"===ef&&!rq&&eT&&em&&(0,B.jsx)("div",{className:"flex-1 overflow-hidden",children:(0,B.jsx)(dD,{projectId:eT.id,threadId:em,projectName:eT.name,onBack:rA,onSelectThread:rT,onOpenContext:e=>{rR.open(e)},onOpenAgentSession:(e,r,s)=>rN.openAgentSession(e,r,s),onOpenScheduleRun:(e,r)=>rN.openScheduleRun(e,r),onRunScheduleAgain:rN.runScheduleAgain})}),"schedules"===ef&&!rq&&eT&&(0,B.jsx)("div",{className:"flex-1 overflow-hidden",children:(0,B.jsx)(mN,{projectId:eT?.id??"",hasLocal:!!eT?.path,schedules:ti,loading:ta,selectedId:tu,onSelect:th,worktrees:eW,onCreate:to,onUpdate:tl,onDelete:async e=>{await tc(e),tu===e&&th(null)},onOpenSourceSession:(e,r)=>{ep("workspace"),ra(e,r)},onRunNow:td,createOpen:ty,onCreateOpenChange:tb,openRunId:tx,onOpenRunHandled:rM})}),"remote-servers"===ef&&(0,B.jsx)("div",{className:"flex-1 overflow-hidden",children:(0,B.jsxs)("div",{className:"h-full flex flex-col overflow-auto",children:[(0,B.jsx)(ug,{title:"Remote Servers"}),(0,B.jsx)("div",{className:"flex-1 px-6 py-5 flex justify-center",children:(0,B.jsx)("div",{className:"w-full max-w-2xl",children:(0,B.jsx)(xy,{})})})]})}),(0,B.jsx)("div",{className:"settings"!==ef?"hidden":"flex-1 overflow-hidden",children:(0,B.jsx)(xi,{})})]}),eT&&(0,B.jsx)(xA,{projectId:eT.id,project:eT,open:eo,onOpenChange:e=>{el(e),e||(Y(void 0),ee(void 0))},onWorktreeCreated:rP,initialBranchName:X?.branch??void 0,initialMachines:X?.machines,initialTargets:X?.targets,initialSelectedTargets:Q}),(0,B.jsx)(xM,{missing:et,onOpenChange:e=>{e||er(null)},onCreateHere:()=>{if(er(null),!et)return;let e=eW.find(e=>e.branch===et.branch);e&&rL(e,[et.current.serverId])},onOpenAnyway:()=>{er(null),et&&P(et.branch)}}),(0,B.jsx)(aZ,{task:tw,open:null!==tw,onOpenChange:e=>{e||t_(null)},onOpenInTasks:tS}),(0,B.jsx)(mM,{open:ei,onOpenChange:ea,onProjectCreated:e=>{eI(e),ep("project-info")}}),eT&&(0,B.jsx)(xI,{projectId:eT.id,worktree:eu,open:ec,onOpenChange:ed,onWorktreeDeleted:eK,onOpenTerminal:(e,r)=>{P(e),ep("workspace"),H(e=>({targetId:r,nonce:(e?.nonce??0)+1}))}}),(0,B.jsx)(FP,{open:r_,onOpenChange:rS,onNavigateProject:rI,onNavigateWorkspace:rO,onNavigateSession:rF})]})})})})})}e.s(["default",()=>F8],837031)}]);
|