@grackle-ai/web 0.107.0 → 0.107.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/KnowledgePage-DgnY2L9q.js","assets/dagview-tHPW3Rz3.js","assets/grpc-DIjMtMRF.js","assets/markdown-Yr3vTPLR.js","assets/KnowledgePage-BmY14aDt.css"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/KnowledgePage-DC4SWTgI.js","assets/dagview-tHPW3Rz3.js","assets/grpc-DIjMtMRF.js","assets/markdown-Yr3vTPLR.js","assets/KnowledgePage-BmY14aDt.css"])))=>i.map(i=>d[i]);
2
2
  import{r as w2,a as N2,b as y,j as a,d as fy,H as py,P as my,i as C2,B as E2,c as A2,C as D2,M as R2,e as M2}from"./dagview-tHPW3Rz3.js";import{c as I2,a as Ed,G as O2,b as B2,d as L2,e as z2,f as $2,M as P2,A as E_,D as A_,W as U2,O as H2,g as V2,C as Di,h as D_,i as R_,w as q2,t as G2,p as $c,j as F2,R as $r,S as hy}from"./grpc-DIjMtMRF.js";import{v as Z2,r as K2,t as Pc,i as Y2,f as J2,M as Ad,a as Dd}from"./markdown-Yr3vTPLR.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const c of document.querySelectorAll('link[rel="modulepreload"]'))r(c);new MutationObserver(c=>{for(const d of c)if(d.type==="childList")for(const u of d.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&r(u)}).observe(document,{childList:!0,subtree:!0});function o(c){const d={};return c.integrity&&(d.integrity=c.integrity),c.referrerPolicy&&(d.referrerPolicy=c.referrerPolicy),c.crossOrigin==="use-credentials"?d.credentials="include":c.crossOrigin==="anonymous"?d.credentials="omit":d.credentials="same-origin",d}function r(c){if(c.ep)return;c.ep=!0;const d=o(c);fetch(c.href,d)}})();var tp={exports:{}},Pr={},np={exports:{}},sp={};/**
3
3
  * @license React
4
4
  * scheduler.production.js
@@ -300,7 +300,7 @@ ${r.content}`);break}}}return s.join(`
300
300
 
301
301
  ${r}
302
302
 
303
- --- End forwarded ---`}function aI(t){return t.replace(/[\r\n]+/g," ").trim().replace(/---/g,"—")}function iI({events:t,formatForClipboard:s}){const[o,r]=y.useState(!1),[c,d]=y.useState(new Set),u=y.useRef(void 0),p=y.useMemo(()=>c.size,[c]),m=y.useCallback(S=>{r(!0),S!==void 0?(d(new Set([S])),u.current=S):(d(new Set),u.current=void 0)},[]),g=y.useCallback(()=>{r(!1),d(new Set),u.current=void 0},[]),v=y.useCallback((S,j)=>{if(j&&u.current!==void 0){const w=Math.min(u.current,S),T=Math.max(u.current,S);d(C=>{const D=new Set(C);for(let O=w;O<=T;O++)O<t.length&&gl(t[O])&&D.add(O);return D})}else d(w=>{const T=new Set(w);return T.has(S)?T.delete(S):T.add(S),T.size===0?(r(!1),u.current=void 0):u.current=S,T})},[t]),_=y.useCallback(()=>{const S=new Set;for(let j=0;j<t.length;j++)gl(t[j])&&S.add(j);d(S)},[t]),b=y.useCallback(()=>{d(new Set)},[]),x=y.useCallback(async()=>{const j=[...c].sort((T,C)=>T-C).filter(T=>T<t.length).map(T=>t[T]);if(j.length===0)return!1;const w=s(j);try{return await navigator.clipboard.writeText(w),!0}catch{return!1}},[c,t,s]);return{isSelecting:o,selectedIndices:c,selectedCount:p,enterSelectionMode:m,cancelSelection:g,toggleEvent:v,selectAll:_,deselectAll:b,copySelected:x}}const oI="_wrapper_1cdza_1",rI="_scrollContainer_1cdza_9",lI="_selectingPadding_1cdza_16",cI="_toolbar_1cdza_20",dI="_directionToggle_1cdza_27",uI="_scrollToAnchor_1cdza_65",fI="_scrollToAnchorBottom_1cdza_89",pI="_scrollToAnchorTop_1cdza_93",mI="_eventOverflowWarning_1cdza_97",ia={wrapper:oI,scrollContainer:rI,selectingPadding:lI,toolbar:cI,directionToggle:dI,scrollToAnchor:uI,scrollToAnchorBottom:fI,scrollToAnchorTop:pI,eventOverflowWarning:mI},hI=10*1024,gI=new Set(["running","idle"]);function vI(t){const s=new Date(t.timestamp).toLocaleTimeString();switch(t.eventType){case"text":case"output":return`Select message from assistant at ${s}`;case"user_input":return`Select message from user at ${s}`;case"tool_result":case"tool_use":return`Select tool event at ${s}`;case"error":return`Select error at ${s}`;default:return`Select event at ${s}`}}const P1="grackle-stream-direction";function yI(){try{return localStorage.getItem(P1)==="reversed"}catch{return!1}}function bI({eventsDropped:t}){return t<=0?a.jsx(a.Fragment,{}):a.jsxs("div",{className:ia.eventOverflowWarning,role:"alert",children:[a.jsx(wm,{size:Qt,"aria-hidden":"true"})," ",t.toLocaleString()," older event",t===1?"":"s"," were dropped — only the most recent 5,000 are shown. Full history is available in the session log."]})}function al({events:t,eventsDropped:s,emptyState:o,onShowToast:r,sessions:c,currentSessionId:d,environments:u,personas:p,onForward:m}){const g=y.useRef(null),[v,_]=y.useState(yI),b=D3(),[x,S]=y.useState(!1),[j,w]=y.useState(!1),[T,C]=y.useState(void 0),D=iI({events:t,formatForClipboard:$1}),O=y.useMemo(()=>t.filter(gl).length,[t]),A=y.useMemo(()=>c?c.filter(q=>gI.has(q.status)&&q.id!==d):[],[c,d]),I=y.useMemo(()=>v?[...t].reverse():t,[t,v]),{isAtAnchor:$,scrollToAnchor:B}=eI({scrollRef:g,contentLength:t.length,isReversed:v,paused:D.isSelecting}),P=()=>{const q=!v;_(q);try{localStorage.setItem(P1,q?"reversed":"default")}catch{}};y.useEffect(()=>{if(!D.isSelecting)return;const q=de=>{de.key==="Escape"&&!x&&!j&&D.cancelSelection()};return window.addEventListener("keydown",q),()=>{window.removeEventListener("keydown",q)}},[D.isSelecting,D.cancelSelection,x,j]);const X=y.useCallback(async()=>{await D.copySelected()&&(r==null||r(`Copied ${D.selectedCount} message${D.selectedCount===1?"":"s"} to clipboard`,"success"))},[D,r]),H=y.useCallback(()=>[...D.selectedIndices].sort((de,re)=>de-re).filter(de=>de<t.length).map(de=>t[de]),[D.selectedIndices,t]),Q=y.useCallback(q=>{if(!q)return"this session";const de=c==null?void 0:c.find(xe=>xe.id===q);if(!de)return q.slice(0,8);const re=u==null?void 0:u.find(xe=>xe.id===de.environmentId);return(re==null?void 0:re.displayName)??de.environmentId.slice(0,8)},[c,u]),he=y.useCallback(async(q,de)=>{if(!m)return;const re=Q(q);try{await m(q,de);const xe=D.selectedCount;r==null||r(`Forwarded ${xe} message${xe===1?"":"s"} to ${re}`,"success"),D.cancelSelection()}catch{r==null||r("Failed to forward messages","error")}},[m,Q,r,D]),W=y.useCallback(q=>{S(!1);const de=H(),re=Q(d),xe=sI(re,de);if(new TextEncoder().encode(xe).length>hI){C({sessionId:q,text:xe}),w(!0);return}he(q,xe).catch(()=>{})},[H,Q,d,he]),ie=y.useCallback(()=>{w(!1),T&&(he(T.sessionId,T.text).catch(()=>{}),C(void 0))},[T,he]),L=y.useCallback(()=>{w(!1),C(void 0)},[]),E=b?0:.2,J=v?-8:8,me=T?Math.round(new TextEncoder().encode(T.text).length/1024):0;return a.jsxs("div",{className:ia.wrapper,children:[a.jsx("div",{className:ia.toolbar,children:a.jsx(Oi,{text:v?"Showing newest first":"Showing oldest first",children:a.jsx("button",{className:ia.directionToggle,onClick:P,"aria-label":v?"Switch to newest at bottom":"Switch to newest at top","data-testid":"direction-toggle",children:v?a.jsx(Sy,{size:Qt,"aria-hidden":"true"}):a.jsx(jy,{size:Qt,"aria-hidden":"true"})})})}),a.jsxs("div",{ref:g,className:`${ia.scrollContainer} ${D.isSelecting?ia.selectingPadding:""}`,"data-testid":"event-stream-scroll",children:[t.length===0&&o,a.jsx(bI,{eventsDropped:s}),a.jsx(ls,{initial:!1,children:I.map((q,de)=>{const re=v?t.length-1-de:de;return a.jsx(Nt.div,{initial:{opacity:0,y:J},animate:{opacity:1,y:0},transition:{duration:E,ease:"easeOut"},children:a.jsx(_6,{copyText:nI(q),isContentBearing:gl(q),isSelecting:D.isSelecting,isSelected:D.selectedIndices.has(re),checkboxLabel:vI(q),onSelect:()=>{D.enterSelectionMode(re)},onToggle:xe=>{D.toggleEvent(re,xe)},onCopied:()=>{r==null||r("Copied to clipboard","success")},children:a.jsx(iD,{event:q,toolUseCtx:q.toolUseCtx,settled:q.settled})})},`${q.sessionId}-${q.timestamp}-${re}`)})})]}),a.jsx(ls,{children:D.isSelecting&&a.jsx(E6,{selectedCount:D.selectedCount,totalSelectable:O,onSelectAll:D.selectAll,onDeselectAll:D.deselectAll,onCopy:()=>{X().catch(()=>{})},onForward:m!==void 0?()=>{S(!0)}:void 0,forwardDisabled:A.length===0,onCancel:D.cancelSelection})}),a.jsx(W6,{isOpen:x,sessions:A,environments:u??[],personas:p,onSelect:W,onCancel:()=>{S(!1)}}),a.jsx(Ls,{isOpen:j,title:"Send large message?",description:`This will forward a large message (${me} KB). Continue?`,confirmLabel:"Send",onConfirm:ie,onCancel:L}),a.jsx(ls,{children:!$&&a.jsxs(Nt.button,{className:`${ia.scrollToAnchor} ${v?ia.scrollToAnchorTop:ia.scrollToAnchorBottom}`,onClick:B,initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.9},transition:{duration:.15},"aria-label":"Scroll to latest","data-testid":"scroll-to-anchor",children:[v?a.jsx(jy,{size:Qt,"aria-hidden":"true"}):a.jsx(Sy,{size:Qt,"aria-hidden":"true"})," New events"]})})]})}function gh(t){const{value:s,onSave:o,validate:r,fieldId:c,activeFieldId:d,onActivate:u,enterToSave:p=!0,trimOnSave:m=!0}=t,[g,v]=y.useState(""),[_,b]=y.useState(""),x=y.useRef(!1),S=d===c,j=y.useCallback($=>{v($),b("")},[]),w=y.useCallback(()=>{b("")},[]),T=y.useCallback(()=>{x.current=!1,u==null||u(null),v(""),b("")},[u]),C=y.useCallback(()=>{const $=m?g.trim():g;if(r){const P=r(g);if(P){b(P);return}}const B=m?s.trim():s;if($===B){T();return}o($),T()},[g,s,m,r,o,T]),D=y.useCallback(()=>{x.current=!0,u==null||u(c),v(s),b("")},[c,s,u]),O=y.useCallback($=>{if(x.current){x.current=!1;return}$.relatedTarget instanceof HTMLElement&&$.relatedTarget.dataset.editAction===c||C()},[c,C]),A=y.useCallback($=>{$.key==="Escape"?T():$.key==="Enter"&&p&&C()},[T,p,C]),I=(()=>{if(!S)return!1;const $=m?s.trim():s;return(m?g.trim():g)!==$})();return y.useEffect(()=>{!S&&(g!==""||_!=="")&&(v(""),b(""))},[S,g,_]),{isEditing:S,draft:g,error:_,isDirty:I,startEdit:D,cancelEdit:T,save:C,setDraft:j,clearError:w,handleBlur:O,handleKeyDown:A,ignoreInitialBlurRef:x}}const _I="_editFieldWrapper_yuzty_1",xI="_editInput_yuzty_10",kI="_editTextarea_yuzty_42",SI="_editSelect_yuzty_78",jI="_editError_yuzty_111",TI="_editInputInvalid_yuzty_118",wI="_editHint_yuzty_123",NI="_unsavedDot_yuzty_132",CI="_metaValueClickable_yuzty_140",EI="_editButton_yuzty_159",AI="_metaPlaceholder_yuzty_175",DI="_worktreeToggle_yuzty_180",st={editFieldWrapper:_I,editInput:xI,editTextarea:kI,editSelect:SI,editError:jI,editInputInvalid:TI,editHint:wI,unsavedDot:NI,metaValueClickable:CI,editButton:EI,metaPlaceholder:AI,worktreeToggle:DI};function Zt(t){const{value:s,onSave:o,validate:r,mode:c="edit",fieldId:d="text",activeFieldId:u,onActivate:p,onChange:m,renderDisplay:g,placeholder:v,maxLength:_,ariaLabel:b,"data-testid":x}=t,S=y.useRef(null),j=gh({value:s,onSave:o,validate:r,fieldId:d,activeFieldId:u,onActivate:p,enterToSave:!0,trimOnSave:!0});if(y.useEffect(()=>{if(j.isEditing){const T=window.setTimeout(()=>{var C;(C=S.current)==null||C.focus()},0);return()=>window.clearTimeout(T)}},[j.isEditing]),c==="create"){const T=D=>{m==null||m(D.target.value)},C=r==null?void 0:r(s);return a.jsxs("div",{className:st.editFieldWrapper,children:[a.jsx("input",{className:`${st.editInput} ${C?st.editInputInvalid:""}`,value:s,onChange:T,maxLength:_,placeholder:v,"aria-label":b,"data-testid":x?`${x}-input`:void 0}),C&&a.jsx("span",{className:st.editError,"data-testid":"edit-error",children:C})]})}if(j.isEditing)return a.jsxs("div",{className:st.editFieldWrapper,children:[a.jsx("input",{ref:S,className:`${st.editInput} ${j.error?st.editInputInvalid:""}`,value:j.draft,onChange:T=>j.setDraft(T.target.value),onBlur:j.handleBlur,onKeyDown:j.handleKeyDown,maxLength:_,placeholder:v,"aria-label":b,"data-testid":x?`${x}-input`:void 0}),j.isDirty&&a.jsx("span",{className:st.unsavedDot,title:"Unsaved changes"}),j.error&&a.jsx("span",{className:st.editError,"data-testid":"edit-error",children:j.error}),a.jsx("span",{className:st.editHint,children:"Enter to save · Esc to cancel"})]});const w=g==null?void 0:g(s);return a.jsxs("span",{role:"button",tabIndex:0,className:st.metaValueClickable,onClick:()=>j.startEdit(),onKeyDown:T=>{(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),j.startEdit())},title:"Click to edit","aria-label":b,"data-testid":x?`${x}-button`:void 0,children:[w!==void 0?w:s?a.jsx("span",{children:s}):a.jsx("span",{className:st.metaPlaceholder,children:v||"None"}),a.jsx("span",{className:st.editButton,"aria-hidden":"true",children:"✏️"})]})}function ym(t){const{value:s,onSave:o,validate:r,mode:c="edit",fieldId:d="textarea",activeFieldId:u,onActivate:p,onChange:m,renderDisplay:g,placeholder:v,ariaLabel:_,"data-testid":b}=t,x=y.useRef(null),S=gh({value:s,onSave:o,validate:r,fieldId:d,activeFieldId:u,onActivate:p,enterToSave:!1,trimOnSave:!1});if(y.useEffect(()=>{if(S.isEditing){const w=window.setTimeout(()=>{var T;(T=x.current)==null||T.focus()},0);return()=>window.clearTimeout(w)}},[S.isEditing]),c==="create"){const w=C=>{m==null||m(C.target.value)},T=r==null?void 0:r(s);return a.jsxs("div",{className:st.editFieldWrapper,children:[a.jsx("textarea",{className:`${st.editTextarea} ${T?st.editInputInvalid:""}`,value:s,onChange:w,placeholder:v,"aria-label":_,"data-testid":b?`${b}-input`:void 0}),T&&a.jsx("span",{className:st.editError,"data-testid":"edit-error",children:T})]})}if(S.isEditing)return a.jsxs("div",{className:st.editFieldWrapper,children:[a.jsx("textarea",{ref:x,className:`${st.editTextarea} ${S.error?st.editInputInvalid:""}`,value:S.draft,onChange:w=>S.setDraft(w.target.value),onBlur:S.handleBlur,onKeyDown:S.handleKeyDown,title:_,"aria-label":_,"data-testid":b?`${b}-input`:void 0}),S.isDirty&&a.jsx("span",{className:st.unsavedDot,title:"Unsaved changes"}),S.error&&a.jsx("span",{className:st.editError,"data-testid":"edit-error",children:S.error}),a.jsx("span",{className:st.editHint,children:"Tab to save · Esc to cancel"})]});const j=g==null?void 0:g(s);return a.jsxs("span",{role:"button",tabIndex:0,className:st.metaValueClickable,onClick:()=>S.startEdit(),onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),S.startEdit())},title:"Click to edit","aria-label":_,"data-testid":b?`${b}-button`:void 0,children:[j!==void 0?j:s?a.jsx("span",{children:s}):a.jsx("span",{className:st.metaPlaceholder,children:v||"None"}),a.jsx("span",{className:st.editButton,"aria-hidden":"true",children:"✏️"})]})}function Td(t){var D;const{value:s,onSave:o,mode:r="edit",options:c,fieldId:d="select",activeFieldId:u,onActivate:p,onChange:m,renderDisplay:g,placeholder:v,ariaLabel:_,"data-testid":b}=t,x=y.useRef(null),S=gh({value:s,onSave:o,fieldId:d,activeFieldId:u,onActivate:p,enterToSave:!1,trimOnSave:!1});y.useEffect(()=>{if(S.isEditing){const O=window.setTimeout(()=>{var A;(A=x.current)==null||A.focus()},0);return()=>window.clearTimeout(O)}},[S.isEditing]);const j=y.useCallback(O=>{const A=O.target.value;S.ignoreInitialBlurRef.current=!1,A!==s&&o(A),S.cancelEdit()},[s,o,S]),w=y.useCallback(O=>{if(S.ignoreInitialBlurRef.current){S.ignoreInitialBlurRef.current=!1;return}O.relatedTarget instanceof HTMLElement&&O.relatedTarget.dataset.editAction===d||S.cancelEdit()},[d,S]);if(r==="create")return a.jsx("select",{className:st.editSelect,value:s,onChange:O=>m==null?void 0:m(O.target.value),"aria-label":_,"data-testid":b?`${b}-select`:void 0,children:c.map(O=>a.jsx("option",{value:O.value,children:O.label},O.value))});if(S.isEditing)return a.jsx("select",{ref:x,className:st.editSelect,value:S.draft,onChange:j,onBlur:w,title:_,"aria-label":_,"data-testid":b?`${b}-select`:void 0,children:c.map(O=>a.jsx("option",{value:O.value,children:O.label},O.value))});const T=g==null?void 0:g(s),C=(D=c.find(O=>O.value===s))==null?void 0:D.label;return a.jsxs("button",{type:"button",className:st.metaValueClickable,onClick:()=>S.startEdit(),title:"Click to change","aria-label":_,"data-testid":b?`${b}-button`:void 0,children:[T!==void 0?T:C?a.jsx("span",{children:C}):a.jsx("span",{className:st.metaPlaceholder,children:v||"None"}),a.jsx("span",{className:st.editButton,"aria-hidden":"true",children:"✏️"})]})}function RI(t){const{checked:s,onChange:o,label:r,ariaLabel:c,"data-testid":d}=t;return a.jsxs("label",{className:st.worktreeToggle,"data-testid":d,children:[a.jsx("input",{type:"checkbox",checked:s,onChange:u=>o(u.target.checked),"aria-label":c}),a.jsx("span",{children:r})]})}const MI="_nav_1snmp_1",II="_searchForm_1snmp_8",OI="_searchInput_1snmp_15",BI="_searchButton_1snmp_33",LI="_clearButton_1snmp_68",zI="_workspaceSelect_1snmp_85",$I="_listHeader_1snmp_99",PI="_nodeList_1snmp_108",UI="_nodeItem_1snmp_116",HI="_indicator_1snmp_129",VI="_label_1snmp_136",qI="_badge_1snmp_145",ns={nav:MI,searchForm:II,searchInput:OI,searchButton:BI,clearButton:LI,workspaceSelect:zI,listHeader:$I,nodeList:PI,nodeItem:UI,indicator:HI,label:VI,badge:qI};function GI({nodes:t,workspaces:s,loading:o,searchQuery:r,onSearch:c,onClearSearch:d,onSelectNode:u,onWorkspaceChange:p}){const[m,g]=y.useState(""),v=y.useCallback(S=>{S.preventDefault(),m.trim()&&c(m.trim())},[m,c]),_=y.useCallback(()=>{g(""),d()},[d]),b=y.useCallback(S=>{u(S)},[u]),x=y.useCallback(S=>{g(""),p(S)},[p]);return a.jsxs("div",{className:ns.nav,"data-testid":"knowledge-nav",children:[a.jsxs("form",{className:ns.searchForm,onSubmit:v,children:[a.jsx("input",{className:ns.searchInput,type:"text",placeholder:"Search...",value:m,onChange:S=>{g(S.target.value)},"data-testid":"knowledge-search-input","aria-label":"Search knowledge nodes"}),a.jsx("button",{type:"submit",className:ns.searchButton,disabled:o,children:"Go"})]}),r&&a.jsx("button",{type:"button",className:ns.clearButton,onClick:_,children:"Clear search"}),a.jsxs("select",{className:ns.workspaceSelect,onChange:S=>{x(S.target.value)},"data-testid":"knowledge-workspace-filter","aria-label":"Filter by workspace",children:[a.jsx("option",{value:"",children:"All workspaces"}),s.map(S=>a.jsx("option",{value:S.id,children:S.name},S.id))]}),a.jsxs("div",{className:ns.listHeader,children:["Nodes (",t.length,")"]}),a.jsx("ul",{className:ns.nodeList,children:t.map(S=>a.jsxs("li",{className:ns.nodeItem,onClick:()=>{b(S.id)},onKeyDown:j=>{(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),b(S.id))},role:"button",tabIndex:0,children:[a.jsx("span",{className:ns.indicator,style:{backgroundColor:S.kind==="reference"?"#4A9EFF":S.category==="decision"?"#22C55E":S.category==="concept"?"#A855F7":S.category==="snippet"?"#6B7280":"#EAB308"}}),a.jsx("span",{className:ns.label,children:S.label}),a.jsx("span",{className:ns.badge,children:S.kind==="reference"?S.sourceType:S.category})]},S.id))})]})}const FI="_container_bwu10_1",ZI="_hamburger_bwu10_33",KI="_brand_bwu10_49",YI="_brandLogo_bwu10_68",JI="_info_bwu10_75",WI="_connectionLabel_bwu10_90",XI="_connectionDot_bwu10_103",QI="_connected_bwu10_106",e5="_disconnected_bwu10_110",t5="_connecting_bwu10_113",Rs={container:FI,hamburger:ZI,brand:KI,brandLogo:YI,info:JI,connectionLabel:WI,connectionDot:XI,connected:QI,disconnected:e5,connecting:t5},n5={connected:"Connected",connecting:"Connecting...",disconnected:"Disconnected"},s5={connected:Rs.connected,connecting:Rs.connecting,disconnected:Rs.disconnected};function a5({connectionStatus:t,environments:s,sessions:o,onToggleSidebar:r,sidebarOpen:c}){const d=ct(),u=s.length,p=s.filter(v=>v.status==="connected").length,m=o.filter(v=>["running","idle"].includes(v.status)).length,g=n5[t];return a.jsxs("div",{className:Rs.container,children:[r&&a.jsx("button",{type:"button",className:Rs.hamburger,onClick:r,"aria-label":"Toggle sidebar","aria-expanded":c,children:a.jsx(dT,{size:At,"aria-hidden":"true"})}),a.jsx(Oi,{text:"Home",placement:"bottom",children:a.jsxs("button",{type:"button",className:Rs.brand,onClick:()=>d(Ii),"data-testid":"statusbar-brand",children:[a.jsx("img",{src:"/icon-192x192.png",alt:"",className:Rs.brandLogo,"aria-hidden":"true","data-testid":"statusbar-logo"}),"Grackle"]})}),a.jsxs("div",{className:Rs.info,children:[a.jsxs("span",{"aria-label":g,children:[a.jsx("span",{className:`${Rs.connectionDot} ${s5[t]}`,"aria-hidden":"true",children:a.jsx(Ya,{size:Nm,fill:"currentColor"})})," ",a.jsx("span",{className:Rs.connectionLabel,"aria-hidden":"true",children:g})]}),a.jsxs("span",{children:[p,"/",u," env",u!==1?"s":""]}),a.jsxs("span",{children:[m," active"]})]})]})}const i5="_nav_13gkc_1",o5="_tab_13gkc_35",r5="_tabIcon_13gkc_68",l5="_tabLabel_13gkc_79",c5="_tabActive_13gkc_84",Gr={nav:i5,tab:o5,tabIcon:r5,tabLabel:l5,tabActive:c5},cd=[{view:"dashboard",label:"Dashboard",icon:a.jsx(Wj,{size:At}),route:Ii,testId:"sidebar-tab-dashboard"},{view:"chat",label:"Chat",icon:a.jsx(B_,{size:At}),route:dl,testId:"sidebar-tab-chat"},{view:"tasks",label:"Tasks",icon:a.jsx(Bj,{size:At}),route:UN,testId:"sidebar-tab-tasks"},{view:"environments",label:"Environments",icon:a.jsx(pT,{size:At}),route:Lo,testId:"sidebar-tab-environments"},{view:"knowledge",label:"Knowledge",icon:a.jsx(Cj,{size:At}),route:ix,testId:"sidebar-tab-knowledge"},{view:"findings",label:"Findings",icon:a.jsx(pd,{size:At}),route:zd,testId:"sidebar-tab-findings"},{view:"settings",label:"Settings",icon:a.jsx(CT,{size:At}),route:ON,testId:"sidebar-tab-settings"}];function d5(t){return t===Ii||t==="/"?"dashboard":t.startsWith("/chat")||t.startsWith("/sessions")?"chat":t.startsWith("/workspaces")||t.startsWith("/environments")?"environments":t.startsWith(ix)?"knowledge":t.startsWith(zd)?"findings":t.startsWith(Ei)?"settings":"tasks"}function u5({tabs:t=cd}){const s=Yt(),o=ct(),r=y.useRef(null),c=d5(s.pathname),d=y.useCallback(p=>{o(p.route)},[o]),u=y.useCallback(p=>{var b,x;const m=(b=r.current)==null?void 0:b.querySelectorAll('[role="tab"]');if(!m)return;const g=Array.from(m).findIndex(S=>S===document.activeElement),v=g>=0?g:t.findIndex(S=>S.view===c);let _=v;if(p.key==="ArrowRight"||p.key==="j"||p.key==="J")p.preventDefault(),_=(v+1)%t.length;else if(p.key==="ArrowLeft"||p.key==="k"||p.key==="K")p.preventDefault(),_=(v-1+t.length)%t.length;else if(p.key==="Home")p.preventDefault(),_=0;else if(p.key==="End")p.preventDefault(),_=t.length-1;else return;o(t[_].route),(x=m[_])==null||x.focus()},[c,o,t]);return a.jsx("nav",{className:Gr.nav,ref:r,role:"tablist","aria-orientation":"horizontal","aria-label":"App navigation",onKeyDown:u,"data-testid":"sidebar-nav",children:t.map(p=>{const m=p.view===c;return a.jsx(Oi,{text:p.label,placement:"bottom",children:a.jsxs("button",{role:"tab",type:"button","aria-selected":m,tabIndex:m?0:-1,className:`${Gr.tab} ${m?Gr.tabActive:""}`,onClick:()=>d(p),"data-testid":p.testId,"aria-label":p.label,children:[a.jsx("span",{className:Gr.tabIcon,"aria-hidden":"true",children:p.icon}),a.jsx("span",{className:Gr.tabLabel,children:p.label})]})},p.view)})})}const f5="_container_pi6ii_1",p5="_content_pi6ii_66",s_={container:f5,content:p5},m5=320,U1=220,H1=600,V1="grackle-sidebar-width";function h5(){try{const t=localStorage.getItem(V1);if(t!==null){const s=Number(t);if(Number.isFinite(s)&&s>=U1&&s<=H1)return s}}catch{}return m5}function g5(t){try{localStorage.setItem(V1,String(t))}catch{}}function v5({content:t}){const[s]=y.useState(h5),o=y.useRef(null);if(y.useEffect(()=>{const r=o.current;if(!r)return;const c=new ResizeObserver(d=>{for(const u of d){const p=u.borderBoxSize[0];if(p){const m=Math.round(p.inlineSize);m>=U1&&m<=H1&&g5(m)}}});return c.observe(r),()=>{c.disconnect()}},[]),t!==void 0)return a.jsx("div",{className:s_.container,ref:o,"data-testid":"sidebar",style:{width:s},children:a.jsx("div",{className:s_.content,children:t})})}const y5="_bar_tnfsh_1",b5="_btnPrimary_tnfsh_32",_5="_statusText_tnfsh_85",x5="_statusCompleted_tnfsh_90",k5="_statusFailed_tnfsh_94",S5="_statusBlocked_tnfsh_98",j5="_hintText_tnfsh_103",wt={bar:y5,btnPrimary:b5,statusText:_5,statusCompleted:x5,statusFailed:k5,statusBlocked:S5,hintText:j5};function T5({sessions:t,tasks:s,environments:o}){const r=ct(),c=Yt(),d=Et("/sessions/:sessionId"),u=Et("/tasks/:taskId"),p=Et("/tasks/:taskId/stream"),m=Et("/tasks/:taskId/findings"),g=Et("/tasks/:taskId/edit"),v=Et("/environments/:environmentId/workspaces/:workspaceId/tasks/:taskId"),_=Et("/environments/:environmentId/workspaces/:workspaceId/tasks/:taskId/stream"),b=Et("/environments/:environmentId/workspaces/:workspaceId/tasks/:taskId/findings"),x=Et("/environments/:environmentId/workspaces/:workspaceId/tasks/:taskId/edit"),S=Et("/sessions/new"),j=Et("/environments/:environmentId/workspaces/:workspaceId"),w=Et("/tasks/new"),T=Et("/chat"),C=Et("/"),D=Et("/settings/*"),O=d==null?void 0:d.params.sessionId,A=(u==null?void 0:u.params.taskId)??(p==null?void 0:p.params.taskId)??(m==null?void 0:m.params.taskId)??(v==null?void 0:v.params.taskId)??(_==null?void 0:_.params.taskId)??(b==null?void 0:b.params.taskId)??(x==null?void 0:x.params.taskId),I=v??_??b??x,$=(I==null?void 0:I.params.environmentId)??(j==null?void 0:j.params.environmentId),B=c.pathname.startsWith("/environments")&&!j&&!I,P=!!T,X=!!S,H=!!j&&!v&&!_&&!b&&!x,Q=!!w;if(!!C&&!X&&!H&&!Q||!!D||(!!g||!!x)||Q||B||X)return a.jsx(a.Fragment,{});if(P)return o.find(E=>E.adapterType==="local"&&E.status==="connected")?a.jsx(a.Fragment,{}):a.jsx("div",{className:wt.bar,children:a.jsx("span",{className:wt.hintText,children:"Add a local environment to start chatting"})});if(H)return a.jsx("div",{className:wt.bar,children:a.jsx("span",{className:wt.hintText,children:"Select a task or click + to create one"})});if(A){const L=s.find(me=>me.id===A);if(!L)return a.jsx("div",{className:wt.bar,children:a.jsx("span",{className:wt.hintText,children:"Loading..."})});const E=new Map(s.map(me=>[me.id,me])),J=L.dependsOn.some(me=>{const q=E.get(me);return q!==void 0&&q.status!=="complete"});if(L.status==="not_started"){const me=J?L.dependsOn.map(q=>E.get(q)).filter(q=>q&&q.status!=="complete").map(q=>q.title):[];return a.jsx("div",{className:wt.bar,children:J?a.jsxs("span",{className:wt.statusBlocked,children:["Blocked by: ",me.join(", ")]}):a.jsx("span",{className:wt.hintText,children:"Use the buttons above to start or manage this task"})})}if(L.status==="working"||L.status==="paused"){const me=L.latestSessionId||void 0,q=me?t.find(re=>re.id===me):void 0;return q&&q.status!=="stopped"?a.jsx(a.Fragment,{}):a.jsx("div",{className:wt.bar,children:a.jsx("span",{className:wt.hintText,children:"Waiting for agent..."})})}if(L.status==="complete")return a.jsxs("div",{className:wt.bar,children:[a.jsx("span",{className:`${wt.statusText} ${wt.statusCompleted}`,children:"Task completed"}),a.jsx("button",{onClick:()=>r(zi(L.workspaceId,void 0,$)),className:wt.btnPrimary,children:"+ New Task"})]});if(L.status==="failed")return a.jsx("div",{className:wt.bar,children:a.jsx("span",{className:`${wt.statusText} ${wt.statusFailed}`,children:"Task failed"})})}if(O){const L=t.find(me=>me.id===O),E=(L==null?void 0:L.status)==="stopped";if(L!==void 0&&!E)return a.jsx(a.Fragment,{});if(E)return a.jsxs("div",{className:wt.bar,children:[a.jsxs("span",{className:`${wt.statusText} ${wt.hintText}`,children:["Session ",L.endReason||L.status]}),a.jsx("button",{onClick:()=>r(tx(L.environmentId)),className:wt.btnPrimary,children:"+ New Chat"})]})}return a.jsx("div",{className:wt.bar,children:a.jsx("span",{className:wt.hintText,children:"Loading..."})})}const w5="_nav_14i94_1",N5="_tab_14i94_24",C5="_tabActive_14i94_62",E5="_tabLabel_14i94_75",A5="_statusDot_14i94_81",D5="_pulse_14i94_87",R5="_addButton_14i94_99",M5="_empty_14i94_132",Va={nav:w5,tab:N5,tabActive:C5,tabLabel:E5,statusDot:A5,pulse:D5,addButton:R5,empty:M5},I5={connected:"var(--accent-green)",sleeping:"var(--accent-yellow)",error:"var(--accent-red)",disconnected:"var(--text-tertiary)",connecting:"var(--accent-blue)"};function O5({environments:t}){const s=ct(),o=y.useRef(null),r=Et("/environments/:environmentId"),c=Et("/environments/:environmentId/edit"),d=Et("/environments/:environmentId/workspaces/:workspaceId"),u=Et("/environments/:environmentId/workspaces/:workspaceId/*"),p=(r==null?void 0:r.params.environmentId)??(c==null?void 0:c.params.environmentId)??(d==null?void 0:d.params.environmentId)??(u==null?void 0:u.params.environmentId),m=p==="new"?void 0:p,g=y.useCallback(b=>{s(Mi(b))},[s]),v=y.useCallback(b=>{var T;const x=(T=o.current)==null?void 0:T.querySelectorAll('[role="tab"]');if(!x||x.length===0)return;const S=Array.from(x).findIndex(C=>C===document.activeElement),j=S>=0?S:t.findIndex(C=>C.id===m);let w=j;if(b.key==="ArrowDown"||b.key==="j"||b.key==="J")b.preventDefault(),w=(j+1)%x.length;else if(b.key==="ArrowUp"||b.key==="k"||b.key==="K")b.preventDefault(),w=(j-1+x.length)%x.length;else if(b.key==="Home")b.preventDefault(),w=0;else if(b.key==="End")b.preventDefault(),w=x.length-1;else return;w<t.length&&s(Mi(t[w].id)),x[w].focus()},[m,t,s]),_=m??(t.length>0?t[0].id:void 0);return a.jsxs("div",{className:Va.nav,"data-testid":"environment-nav",children:[a.jsx("nav",{ref:o,role:"tablist","aria-orientation":"vertical","aria-label":"Environments",onKeyDown:v,children:t.map(b=>{const x=b.id===m,S=b.id===_,j=I5[b.status]||"var(--text-tertiary)",w=b.status==="connected";return a.jsxs("button",{role:"tab",type:"button","aria-selected":x,tabIndex:S?0:-1,className:`${Va.tab} ${x?Va.tabActive:""}`,onClick:()=>g(b.id),"data-testid":"env-nav-item",children:[a.jsx("span",{className:`${Va.statusDot} ${w?Va.pulse:""}`,style:{color:j},"aria-hidden":"true",children:a.jsx(Ya,{size:Nm,fill:"currentColor"})}),a.jsx("span",{className:Va.tabLabel,title:b.displayName||b.id,children:b.displayName||b.id})]},b.id)})}),a.jsx("button",{type:"button",className:Va.addButton,onClick:()=>s(MN),title:"Add environment","data-testid":"env-nav-add",children:"+ Add Environment"}),t.length===0&&a.jsx("div",{className:Va.empty,children:"No environments yet."})]})}function Ho(t){const s=new Date(t),o=new Date,r=o.getTime()-s.getTime(),c=Math.floor(r/1e3),d=Math.floor(c/60),u=Math.floor(d/60),p=Math.floor(u/24);if(c<60)return"just now";if(d<60)return`${d}m ago`;if(u<24)return`${u}h ago`;if(p===1)return"yesterday";if(p<7)return`${p} days ago`;const m=s.getFullYear()===o.getFullYear(),g=s.toLocaleString("en-US",{month:"short"}),v=s.getDate();return m?`${g} ${v}`:`${g} ${v} ${s.getFullYear()}`}function q1(t){const s=new Date(t);if(Number.isNaN(s.getTime()))return"—";const o=new Date,r=s.getTime()-o.getTime();if(r<=0)return"overdue";const c=Math.floor(r/1e3),d=Math.floor(c/60),u=Math.floor(d/60),p=Math.floor(u/24);if(c<60)return`in ${c}s`;if(d<60)return`in ${d}m`;if(u<24)return`in ${u}h`;if(p<7)return`in ${p} day${p===1?"":"s"}`;const m=s.getFullYear()===o.getFullYear(),g=s.toLocaleString("en-US",{month:"short"}),v=s.getDate();return m?`${g} ${v}`:`${g} ${v} ${s.getFullYear()}`}const a_={architecture:{text:"var(--accent-blue)",bg:"var(--accent-blue-dim)"},api:{text:"var(--accent-green)",bg:"var(--accent-green-dim)"},bug:{text:"var(--accent-red)",bg:"var(--accent-red-dim)"},decision:{text:"var(--accent-yellow)",bg:"var(--accent-yellow-dim)"},dependency:{text:"var(--accent-purple)",bg:"var(--accent-purple-dim)"},pattern:{text:"var(--accent-cyan)",bg:"var(--accent-cyan-dim)"},general:{text:"var(--text-secondary)",bg:"var(--bg-elevated)"}};function wd(t){return a_[t]||a_.general}const B5="_nav_dlm8m_1",L5="_categoryPills_dlm8m_24",z5="_categoryPill_dlm8m_24",$5="_tab_dlm8m_42",P5="_tabActive_dlm8m_80",U5="_tabContent_dlm8m_93",H5="_tabLabel_dlm8m_100",V5="_tabMeta_dlm8m_106",q5="_categoryDot_dlm8m_111",G5="_empty_dlm8m_118",As={nav:B5,categoryPills:L5,categoryPill:z5,tab:$5,tabActive:P5,tabContent:U5,tabLabel:H5,tabMeta:V5,categoryDot:q5,empty:G5};function F5({findings:t,workspaceId:s,environmentId:o}){const r=ct(),c=y.useRef(null),d=Et("/findings/:findingId"),u=Et("/environments/:environmentId/workspaces/:workspaceId/findings/:findingId"),p=(d==null?void 0:d.params.findingId)??(u==null?void 0:u.params.findingId),m=y.useMemo(()=>{const b=new Set(t.map(x=>x.category).filter(Boolean));return Array.from(b).sort()},[t]),g=y.useCallback(b=>{r(Qp(b,s,o))},[r,s,o]),v=y.useCallback(b=>{var T;const x=(T=c.current)==null?void 0:T.querySelectorAll('[role="tab"]');if(!x||x.length===0)return;const S=Array.from(x).findIndex(C=>C===document.activeElement),j=S>=0?S:t.findIndex(C=>C.id===p);let w=j;if(b.key==="ArrowDown"||b.key==="j"||b.key==="J")b.preventDefault(),w=(j+1)%x.length;else if(b.key==="ArrowUp"||b.key==="k"||b.key==="K")b.preventDefault(),w=(j-1+x.length)%x.length;else if(b.key==="Home")b.preventDefault(),w=0;else if(b.key==="End")b.preventDefault(),w=x.length-1;else return;w<t.length&&r(Qp(t[w].id,s,o)),x[w].focus()},[p,t,r,s,o]),_=p??(t.length>0?t[0].id:void 0);return a.jsxs("div",{className:As.nav,"data-testid":"findings-nav",children:[m.length>1&&a.jsx("div",{className:As.categoryPills,"data-testid":"findings-nav-categories",children:m.map(b=>a.jsx("span",{className:As.categoryPill,style:{color:wd(b).text},children:b},b))}),a.jsx("nav",{ref:c,role:"tablist","aria-orientation":"vertical","aria-label":"Findings",onKeyDown:v,children:t.map(b=>{const x=b.id===p,S=b.id===_;return a.jsxs("button",{role:"tab",type:"button","aria-selected":x,tabIndex:S?0:-1,className:`${As.tab} ${x?As.tabActive:""}`,onClick:()=>g(b.id),"data-testid":"finding-nav-item",children:[a.jsx("span",{className:As.categoryDot,style:{color:wd(b.category).text},"aria-hidden":"true",children:a.jsx(Ya,{size:Nm,fill:"currentColor"})}),a.jsxs("span",{className:As.tabContent,children:[a.jsx("span",{className:As.tabLabel,title:b.title,children:b.title}),a.jsx("span",{className:As.tabMeta,title:b.createdAt,children:Ho(b.createdAt)})]})]},b.id)})}),t.length===0&&a.jsx("div",{className:As.empty,children:"No findings yet. Agents will post discoveries here."})]})}function Z5(t){if(t.length===0)return[];const s=[...t].sort((r,c)=>r[0]-c[0]),o=[[s[0][0],s[0][1]]];for(let r=1;r<s.length;r++){const c=o[o.length-1],[d,u]=s[r];d<=c[1]+1?c[1]=Math.max(c[1],u):o.push([d,u])}return o}function G1({text:t,indices:s,highlightClass:o}){if(!s||s.length===0)return a.jsx(a.Fragment,{children:t});const r=Z5(s),c=[];let d=0;for(const[u,p]of r)u>d&&c.push(a.jsx("span",{children:t.slice(d,u)},`p${d}`)),c.push(a.jsx("mark",{className:o,children:t.slice(u,p+1)},`m${u}`)),d=p+1;return d<t.length&&c.push(a.jsx("span",{children:t.slice(d)},`p${d}`)),a.jsx(a.Fragment,{children:c})}function K5(t){const s=new Map(t.map(r=>[r.id,{...r,children:[]}])),o=[];for(const r of s.values())r.parentTaskId&&s.has(r.parentTaskId)?s.get(r.parentTaskId).children.push(r):o.push(r);for(const r of s.values())r.children.sort((c,d)=>c.sortOrder-d.sortOrder);return o.sort((r,c)=>r.sortOrder-c.sortOrder)}function Y5(t,s){const o=new Map;for(const d of t){const p=d.dependsOn.length>0&&d.dependsOn.some(g=>s.get(g)!=="complete")?"blocked":d.status,m=o.get(p);m?m.push(d):o.set(p,[d])}const r=[],c=new Set;for(const d of LT){c.add(d);const u=o.get(d);if(u&&u.length>0){u.sort((m,g)=>m.sortOrder-g.sortOrder);const p=Ja(d);r.push({status:d,label:p.label,style:p,tasks:u})}}for(const[d,u]of o)if(!c.has(d)&&u.length>0){u.sort((m,g)=>m.sortOrder-g.sortOrder);const p=Ja(d);r.push({status:d,label:p.label,style:p,tasks:u})}return r}const J5="_container_z4i38_1",W5="_header_z4i38_5",X5="_headerActions_z4i38_17",Q5="_searchInput_z4i38_23",eO="_searchHighlight_z4i38_56",tO="_groupToggle_z4i38_62",nO="_groupToggleActive_z4i38_89",sO="_addButton_z4i38_93",aO="_taskRow_z4i38_120",iO="_selected_z4i38_140",oO="_expandArrow_z4i38_150",rO="_expanded_z4i38_157",lO="_leafSpacer_z4i38_161",cO="_taskStatusIcon_z4i38_166",dO="_taskTitle_z4i38_170",uO="_workspaceBadge_z4i38_177",fO="_childCountBadge_z4i38_195",pO="_dependencyBadge_z4i38_208",mO="_blockedBadge_z4i38_220",hO="_addChildButton_z4i38_225",gO="_emptyState_z4i38_268",vO="_statusGroupHeader_z4i38_275",yO="_statusGroupIcon_z4i38_294",bO="_statusGroupLabel_z4i38_298",_O="_statusGroupCount_z4i38_303",Ke={container:J5,header:W5,headerActions:X5,searchInput:Q5,searchHighlight:eO,groupToggle:tO,groupToggleActive:nO,addButton:sO,taskRow:aO,selected:iO,expandArrow:oO,expanded:rO,leafSpacer:lO,taskStatusIcon:cO,taskTitle:dO,workspaceBadge:uO,childCountBadge:fO,dependencyBadge:pO,blockedBadge:mO,addChildButton:hO,emptyState:gO,statusGroupHeader:vO,statusGroupIcon:yO,statusGroupLabel:bO,statusGroupCount:_O},xO=[{name:"title",weight:2},{name:"description",weight:1}],F1=16,kO=16,Z1="grackle-task-group-by-status";function i_(){try{return localStorage.getItem(Z1)==="true"}catch{return!1}}function SO(t){try{localStorage.setItem(Z1,String(t))}catch{}}function jO({group:t,isExpanded:s,onToggle:o,selectedTaskId:r,navigate:c,titleHighlights:d,workspaceNames:u}){return a.jsxs("div",{"data-testid":`status-group-${t.status}`,children:[a.jsxs("div",{className:Ke.statusGroupHeader,role:"button",tabIndex:0,"aria-expanded":s,onClick:o,onKeyDown:p=>{(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),o())},children:[a.jsx("span",{className:`${Ke.expandArrow} ${s?Ke.expanded:""}`,"aria-hidden":"true",children:a.jsx(fa,{size:at})}),a.jsx("span",{className:Ke.statusGroupIcon,style:{color:t.style.color},"aria-hidden":"true",children:t.style.icon}),a.jsx("span",{className:Ke.statusGroupLabel,children:t.label}),a.jsx("span",{className:Ke.statusGroupCount,children:t.tasks.length})]}),a.jsx(ls,{children:s&&a.jsx(Nt.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2},style:{overflow:"hidden"},children:t.tasks.map(p=>{const m=Ja(p.status),g=r===p.id,v=p.parentTaskId||!p.workspaceId?void 0:u.get(p.workspaceId);return a.jsxs("div",{onClick:()=>c($n(p.id)),role:"button",tabIndex:0,"aria-label":p.title,onKeyDown:_=>{_.currentTarget===_.target&&(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),c($n(p.id)))},className:`${Ke.taskRow} ${g?Ke.selected:""}`,style:{"--task-indent":`${F1}px`},"data-task-id":p.id,children:[a.jsx("span",{className:Ke.leafSpacer}),a.jsx("span",{className:Ke.taskStatusIcon,style:{color:m.color},"aria-hidden":"true","data-testid":`task-status-${vl(p.status)}`,children:m.icon}),a.jsx("span",{className:Ke.taskTitle,title:p.title,children:a.jsx(G1,{text:p.title,indices:d.get(p.id),highlightClass:Ke.searchHighlight})}),v&&a.jsx("span",{className:Ke.workspaceBadge,title:v,children:v})]},p.id)})})})]})}function K1({node:t,depth:s,expandedTasks:o,toggleTask:r,selectedTaskId:c,navigate:d,taskStatusById:u,titleHighlights:p,workspaceNames:m}){const g=Ja(t.status),v=t.dependsOn.length>0&&t.dependsOn.some(T=>u.get(T)!=="complete"),_=o.has(t.id),b=t.children.length>0,x=c===t.id,S=F1+s*kO,w=s===0&&!t.parentTaskId&&t.workspaceId?m.get(t.workspaceId):void 0;return a.jsxs(a.Fragment,{children:[a.jsxs("div",{onClick:()=>d($n(t.id)),role:"button",tabIndex:0,"aria-label":t.title,onKeyDown:T=>{T.currentTarget===T.target&&(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),d($n(t.id)))},className:`${Ke.taskRow} ${x?Ke.selected:""}`,style:{"--task-indent":`${S}px`},"data-task-id":t.id,children:[b&&a.jsx("span",{className:`${Ke.expandArrow} ${_?Ke.expanded:""}`,role:"button",tabIndex:0,"aria-label":_?"Collapse task":"Expand task",onClick:T=>{T.stopPropagation(),r(t.id)},onKeyDown:T=>{(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),T.stopPropagation(),r(t.id))},children:a.jsx(fa,{size:at,"aria-hidden":"true"})}),!b&&a.jsx("span",{className:Ke.leafSpacer}),a.jsx("span",{className:Ke.taskStatusIcon,style:{color:g.color},"aria-hidden":"true","data-testid":`task-status-${vl(t.status)}`,children:g.icon}),a.jsx("span",{className:Ke.taskTitle,title:t.title,children:a.jsx(G1,{text:t.title,indices:p.get(t.id),highlightClass:Ke.searchHighlight})}),w&&a.jsx("span",{className:Ke.workspaceBadge,title:w,children:w}),b&&a.jsxs("span",{className:Ke.childCountBadge,children:[t.children.filter(T=>T.status==="complete").length,"/",t.children.length]}),t.dependsOn.length>0&&a.jsx("span",{className:`${Ke.dependencyBadge} ${v?Ke.blockedBadge:""}`,title:`Depends on: ${t.dependsOn.join(", ")}`,children:v?"blocked":"dep"}),s<P2&&a.jsx(Oi,{text:"Add child task",children:a.jsx("button",{onClick:T=>{T.stopPropagation(),d(zi(t.workspaceId,t.id))},"aria-label":"Add child task",className:Ke.addChildButton,children:"+"})})]}),a.jsx(ls,{children:b&&_&&a.jsx(Nt.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.15},style:{overflow:"hidden"},children:t.children.map(T=>a.jsx(K1,{node:T,depth:s+1,expandedTasks:o,toggleTask:r,selectedTaskId:c,navigate:d,taskStatusById:u,titleHighlights:p,workspaceNames:m},T.id))})})]})}function TO({workspaces:t,tasks:s}){const o=ct(),[r,c]=y.useState(new Set),[d,u]=y.useState(new Set),[p,m]=y.useState(i_),[g,v]=y.useState(i_),[_,b]=y.useState(new Map),x=Et("/tasks/:taskId/*"),S=(x==null?void 0:x.params.taskId)!=="new"?x==null?void 0:x.params.taskId:void 0,j=y.useMemo(()=>new Map(s.map(W=>[W.id,W.status])),[s]),w=y.useMemo(()=>new Map(t.map(W=>[W.id,W.name])),[t]),T=()=>{const W=!p;SO(W),m(W),W&&(v(!0),b(new Map))},C=W=>{b(ie=>{const L=new Map(ie),E=L.has(W)?L.get(W):g;return L.set(W,!E),L})},D=W=>_.has(W)?_.get(W):g,O=W=>{c(ie=>{const L=new Set(ie);return L.has(W)?(L.delete(W),u(E=>new Set(E).add(W))):(L.add(W),u(E=>{const J=new Set(E);return J.delete(W),J})),L})};y.useEffect(()=>{const W=new Set(s.filter(ie=>ie.parentTaskId).map(ie=>ie.parentTaskId));W.size>0&&c(ie=>{const L=new Set(ie);for(const E of W)d.has(E)||L.add(E);return L})},[s,d]);const[A,I]=y.useState(""),{directMatchTaskIds:$,treeMatchTaskIds:B,titleHighlights:P}=y.useMemo(()=>{if(!A.trim())return{directMatchTaskIds:null,treeMatchTaskIds:null,titleHighlights:new Map};const W=$2(s,A,xO),ie=new Set(W.map(me=>me.item.id)),L=new Map;for(const me of W){const q=me.matches.find(de=>de.key==="title");q&&L.set(me.item.id,q.indices)}const E=new Set(ie),J=new Map(s.map(me=>[me.id,me]));for(const me of[...ie]){let q=J.get(me);for(;q!=null&&q.parentTaskId;)E.add(q.parentTaskId),q=J.get(q.parentTaskId)}return{directMatchTaskIds:ie,treeMatchTaskIds:E,titleHighlights:L}},[A,s]),X=$!==null,H=X?p?$:B:null,Q=H?s.filter(W=>H.has(W.id)):s,he=p?[]:K5(Q);return a.jsxs("div",{className:Ke.container,children:[a.jsxs("div",{className:Ke.header,children:[a.jsx("span",{children:"Tasks"}),a.jsxs("div",{className:Ke.headerActions,children:[a.jsx(Oi,{text:p?"Switch to tree view":"Group tasks by status",children:a.jsx("button",{className:`${Ke.groupToggle} ${p?Ke.groupToggleActive:""}`,onClick:T,"aria-label":p?"Switch to tree view":"Group tasks by status","aria-pressed":p,"data-testid":"task-group-by-status-toggle",children:a.jsx(oT,{size:Qt})})}),a.jsx(Oi,{text:"New task",children:a.jsx("button",{className:Ke.addButton,onClick:()=>o(zi()),"aria-label":"New task","data-testid":"new-task-button",children:"+"})})]})]}),s.length>0&&a.jsx("input",{type:"text",value:A,onChange:W=>I(W.target.value),placeholder:"Filter...","aria-label":"Filter tasks",className:Ke.searchInput,"data-testid":"sidebar-search"}),p?Y5(Q,j).map(W=>a.jsx(jO,{group:W,isExpanded:D(W.status),onToggle:()=>C(W.status),selectedTaskId:S,navigate:o,titleHighlights:P,workspaceNames:w},W.status)):he.map(W=>a.jsx(K1,{node:W,depth:0,expandedTasks:r,toggleTask:O,selectedTaskId:S,navigate:o,taskStatusById:j,titleHighlights:P,workspaceNames:w},W.id)),Q.length===0&&!X&&a.jsx("div",{className:Ke.emptyState,children:"No tasks yet. Click + to create one."}),Q.length===0&&X&&a.jsx("div",{className:Ke.emptyState,children:"No matching tasks"})]})}const wO="_toast_ed2dk_1",NO="_success_ed2dk_18",CO="_icon_ed2dk_22",EO="_error_ed2dk_25",AO="_warning_ed2dk_32",DO="_info_ed2dk_38",RO="_message_ed2dk_53",MO="_close_ed2dk_60",Fr={toast:wO,success:NO,icon:CO,error:EO,warning:AO,info:DO,message:RO,close:MO},IO={success:a.jsx(Bi,{size:At}),error:a.jsx(pa,{size:At}),warning:a.jsx(wm,{size:At}),info:a.jsx(Tm,{size:At})};function OO({toast:t,onDismiss:s}){return y.useEffect(()=>{const o=setTimeout(()=>s(t.id),t.duration);return()=>clearTimeout(o)},[t.id,t.duration,s]),a.jsxs(Nt.div,{className:`${Fr.toast} ${Fr[t.variant]}`,role:"status",initial:{opacity:0,y:-16,scale:.94},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-8,scale:.94},transition:{duration:.2,ease:"easeOut"},layout:!0,children:[a.jsx("span",{className:Fr.icon,"aria-hidden":"true",children:IO[t.variant]}),a.jsx("span",{className:Fr.message,children:t.message}),a.jsx("button",{type:"button",className:Fr.close,onClick:()=>s(t.id),"aria-label":"Dismiss notification",children:a.jsx(pa,{size:Qt,"aria-hidden":"true"})})]})}const BO="_container_qqse2_1",LO={container:BO};function zO({toasts:t,onDismiss:s}){return a.jsx("div",{className:LO.container,"data-testid":"toast-container",children:a.jsx(ls,{children:t.map(o=>a.jsx(OO,{toast:o,onDismiss:s},o.id))})})}const $O="_callout_e5awm_1",PO="_success_e5awm_11",UO="_icon_e5awm_15",HO="_error_e5awm_18",VO="_warning_e5awm_25",qO="_info_e5awm_32",GO="_content_e5awm_48",FO="_close_e5awm_53",Zr={callout:$O,success:PO,icon:UO,error:HO,warning:VO,info:qO,content:GO,close:FO},ZO={success:a.jsx(Bi,{size:At}),error:a.jsx(pa,{size:At}),warning:a.jsx(wm,{size:At}),info:a.jsx(Tm,{size:At})};function KO({variant:t="info",children:s,dismissible:o=!1,className:r}){const[c,d]=y.useState(!1);return a.jsx(a.Fragment,{children:!c&&a.jsxs("div",{className:[Zr.callout,Zr[t],r].filter(Boolean).join(" "),role:t==="error"||t==="warning"?"alert":"status",children:[a.jsx("span",{className:Zr.icon,"aria-hidden":"true",children:ZO[t]}),a.jsx("span",{className:Zr.content,children:s}),o&&a.jsx("button",{type:"button",className:Zr.close,onClick:()=>d(!0),"aria-label":"Dismiss",children:a.jsx(pa,{size:Qt,"aria-hidden":"true"})})]})})}function YO({currentVersion:t,latestVersion:s,updateAvailable:o,isDocker:r}){if(!o)return a.jsx(a.Fragment,{});const c=r?"docker pull ghcr.io/nick-pape/grackle:latest && docker restart grackle":`npm install -g @grackle-ai/cli@${s}`;return a.jsx("div",{"data-testid":"update-banner",children:a.jsxs(KO,{variant:"info",dismissible:!0,children:[a.jsxs("strong",{children:["Grackle v",s]})," is available (you have v",t,")."," ","Run: ",a.jsx("code",{children:c})]})})}const JO="_container_de44x_1",WO="_emptyState_de44x_8",XO="_card_de44x_14",QO="_cardClickable_de44x_34",eB="_cardHeader_de44x_42",tB="_categoryBadge_de44x_54",nB="_findingTitle_de44x_62",sB="_findingDate_de44x_68",aB="_findingContent_de44x_80",iB="_tags_de44x_86",oB="_tag_de44x_86",ys={container:JO,emptyState:WO,card:XO,cardClickable:QO,cardHeader:eB,categoryBadge:tB,findingTitle:nB,findingDate:sB,findingContent:aB,tags:iB,tag:oB};function Y1({findings:t,onFindingClick:s}){return t.length===0?a.jsx("div",{className:ys.emptyState,children:"No findings yet. Agents will post discoveries here."}):a.jsx("div",{className:ys.container,children:t.map((o,r)=>{const c=wd(o.category),d=s?Nt.button:Nt.div;return a.jsxs(d,{type:s?"button":void 0,className:`${ys.card} ${s?ys.cardClickable:""}`,initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{delay:r*.05,duration:.2},onClick:s?()=>{s(o.id)}:void 0,children:[a.jsxs("div",{className:ys.cardHeader,children:[a.jsx("span",{className:ys.categoryBadge,style:{background:c.bg,color:c.text},children:o.category}),a.jsx("span",{className:ys.findingTitle,children:o.title}),a.jsx("span",{className:ys.findingDate,title:o.createdAt,children:Ho(o.createdAt)})]}),a.jsx("div",{className:ys.findingContent,children:o.content.length>300?o.content.slice(0,300)+"...":o.content}),o.tags.length>0&&a.jsx("div",{className:ys.tags,children:o.tags.map(u=>a.jsx("span",{className:ys.tag,style:{color:c.text,textShadow:`0 0 8px ${c.text}`},children:u},u))})]},o.id)})})}const rB="_container_m1fsr_1",lB="_heading_m1fsr_7",cB="_section_m1fsr_14",dB="_sectionTitle_m1fsr_26",uB="_sectionDescription_m1fsr_35",fB="_emptyState_m1fsr_41",pB="_tokenList_m1fsr_48",mB="_tokenRow_m1fsr_55",hB="_tokenBadge_m1fsr_68",gB="_tokenName_m1fsr_83",vB="_tokenTarget_m1fsr_90",yB="_deleteButton_m1fsr_99",bB="_addForm_m1fsr_113",_B="_formRow_m1fsr_119",xB="_input_m1fsr_125",kB="_select_m1fsr_155",SB="_addButton_m1fsr_187",jB="_emptyStateInfo_m1fsr_221",TB="_themeOptions_m1fsr_229",wB="_themeOption_m1fsr_229",NB="_themeOptionSelected_m1fsr_254",CB="_themeOptionHeader_m1fsr_259",EB="_themeOptionLabel_m1fsr_266",AB="_themeOptionDesc_m1fsr_273",DB="_variantToggle_m1fsr_279",RB="_variantButton_m1fsr_286",MB="_variantActive_m1fsr_305",IB="_themeSwatches_m1fsr_311",OB="_themeSwatch_m1fsr_311",BB="_systemToggle_m1fsr_325",LB="_systemToggleHint_m1fsr_341",zB="_themeActive_m1fsr_348",$B="_aboutGrid_m1fsr_354",PB="_aboutItem_m1fsr_360",UB="_aboutLabel_m1fsr_373",HB="_aboutValue_m1fsr_379",VB="_aboutDot_m1fsr_387",qB="_aboutDotConnected_m1fsr_394",GB="_aboutDotDisconnected_m1fsr_398",FB="_aboutDotConnecting_m1fsr_402",ge={container:rB,heading:lB,section:cB,sectionTitle:dB,sectionDescription:uB,emptyState:fB,tokenList:pB,tokenRow:mB,tokenBadge:hB,tokenName:gB,tokenTarget:vB,deleteButton:yB,addForm:bB,formRow:_B,input:xB,select:kB,addButton:SB,emptyStateInfo:jB,themeOptions:TB,themeOption:wB,themeOptionSelected:NB,themeOptionHeader:CB,themeOptionLabel:EB,themeOptionDesc:AB,variantToggle:DB,variantButton:RB,variantActive:MB,themeSwatches:IB,themeSwatch:OB,systemToggle:BB,systemToggleHint:LB,themeActive:zB,aboutGrid:$B,aboutItem:PB,aboutLabel:UB,aboutValue:HB,aboutDot:VB,aboutDotConnected:qB,aboutDotDisconnected:GB,aboutDotConnecting:FB},ZB=[{value:"env_var",label:"Environment Variable"},{value:"file",label:"File"}];function KB({tokens:t,onSetToken:s,onDeleteToken:o,onShowToast:r}){const[c,d]=y.useState(""),[u,p]=y.useState(""),[m,g]=y.useState("env_var"),[v,_]=y.useState(""),[b,x]=y.useState(null),S=T=>{if(T.preventDefault(),!c||!u)return;const C=m==="env_var"?v||c.toUpperCase()+"_TOKEN":"";s(c,u,m,C,m==="file"?v:""),r==null||r("Token saved successfully","success"),d(""),p(""),_("")},j=T=>{x(T)},w=()=>{b&&(o(b),r==null||r("Token deleted","info")),x(null)};return a.jsxs(a.Fragment,{children:[a.jsx(Ls,{isOpen:b!==null,title:"Delete Token?",description:b?`"${b}" will be permanently removed.`:void 0,onConfirm:w,onCancel:()=>x(null)}),a.jsxs("section",{className:ge.section,children:[a.jsx("h3",{className:ge.sectionTitle,children:"Tokens"}),a.jsx("p",{className:ge.sectionDescription,children:"API tokens are auto-pushed to environments when set or updated. Values are write-only."}),t.length===0?a.jsx("div",{className:ge.emptyStateInfo,children:"Add your first API token to enable service integrations."}):a.jsx("div",{className:ge.tokenList,children:t.map(T=>a.jsxs("div",{className:ge.tokenRow,children:[a.jsx("span",{className:ge.tokenBadge,children:T.tokenType}),a.jsx("span",{className:ge.tokenName,children:T.name}),a.jsx("span",{className:ge.tokenTarget,children:T.tokenType==="env_var"?T.envVar:T.filePath}),a.jsx("button",{className:ge.deleteButton,onClick:()=>j(T.name),title:`Delete ${T.name}`,"aria-label":`Delete ${T.name}`,children:a.jsx(pa,{size:Qt,"aria-hidden":"true"})})]},T.name))}),a.jsxs("form",{className:ge.addForm,onSubmit:S,children:[a.jsxs("div",{className:ge.formRow,children:[a.jsx("input",{className:ge.input,type:"text",placeholder:"Token name",value:c,onChange:T=>d(T.target.value)}),a.jsx("input",{className:ge.input,type:"password",placeholder:"Value",value:u,onChange:T=>p(T.target.value)})]}),a.jsxs("div",{className:ge.formRow,children:[a.jsx("select",{className:ge.select,value:m,onChange:T=>g(T.target.value),children:ZB.map(T=>a.jsx("option",{value:T.value,children:T.label},T.value))}),a.jsx("input",{className:ge.input,type:"text",placeholder:m==="env_var"?"Env var name (e.g. API_TOKEN)":"File path (e.g. /home/user/.token)",value:v,onChange:T=>_(T.target.value)}),a.jsx("button",{className:ge.addButton,type:"submit",children:"Add Token"})]})]})]})]})}const Gd=[{id:"grackle",label:"Grackle",description:"The default Grackle theme — iridescent purple on clean dark.",swatches:["#0e1218","#8b5cf6","#60a5fa","#e5e7eb","#34d399"],variantLightId:"grackle-light",variantDarkId:"grackle-dark"},{id:"grackle-light",label:"Grackle Light",description:"Light Grackle variant.",hidden:!0},{id:"grackle-dark",label:"Grackle Dark",description:"Dark Grackle variant.",hidden:!0},{id:"glass",label:"Glassmorphism",description:"Dark frosted-glass aesthetic with backdrop blur effects.",swatches:["#0a0c14","#4ecca3","#70a1ff","#e2e8f0","#a855f7"]},{id:"matrix",label:"Matrix",description:"Phosphor-green CRT terminal with scanlines and glow.",swatches:["#050505","#00ff41","#00bfff","#33ff77","#ffb000"]},{id:"brutalist",label:"Neubrutalism",description:"Thick borders, raw colors, bold type — ugly on purpose.",swatches:["#f5f0e8","#ff5757","#5ce1e6","#1a1a1a","#ffde59"],variantLightId:"brutalist-light",variantDarkId:"brutalist-dark"},{id:"brutalist-light",label:"Neubrutalism Light",description:"Light neubrutalism variant.",hidden:!0},{id:"brutalist-dark",label:"Neubrutalism Dark",description:"Dark neubrutalism variant.",hidden:!0},{id:"monokai",label:"Monokai",description:"Classic warm editor palette — pink, green, and purple.",swatches:["#272822","#f92672","#a6e22e","#f8f8f2","#ae81ff"],variantLightId:"monokai-light",variantDarkId:"monokai-dark"},{id:"monokai-dark",label:"Monokai Dark",description:"Dark Monokai variant.",hidden:!0},{id:"monokai-light",label:"Monokai Light",description:"Light Monokai variant.",hidden:!0},{id:"ubuntu",label:"Ubuntu",description:"Aubergine terminal with the GNOME Tango palette.",swatches:["#300a24","#8ae234","#ef2929","#eeeeec","#fce94f"]},{id:"sandstone",label:"Sandstone",description:"Warm terracotta accent on dark brown, in the style of Claude Code.",swatches:["#1a1815","#C15F3C","#6b8afd","#e8e6e3","#a78bfa"]},{id:"verdigris",label:"Verdigris",description:"Teal accent on charcoal, in the style of ChatGPT.",swatches:["#141414","#00a67e","#3b82f6","#ececec","#ab68ff"]},{id:"primer",label:"Primer",description:"Blue accent on ink-dark grey, in the style of GitHub.",swatches:["#0d1117","#58a6ff","#3fb950","#c9d1d9","#bc8cff"]}],J1=new Set(Gd.map(t=>t.id)),o_="grackle";function bm(t){return Gd.find(s=>s.id===t)}function YB({themeId:t,resolvedThemeId:s,onSetTheme:o,preferSystem:r,onSetPreferSystem:c}){return a.jsxs("section",{className:ge.section,children:[a.jsx("h3",{className:ge.sectionTitle,children:"Appearance"}),a.jsx("p",{className:ge.sectionDescription,children:"Choose how Grackle looks across the app."}),a.jsx("div",{className:ge.themeOptions,children:Gd.filter(d=>!d.hidden).map(d=>{const u=!!(d.variantLightId&&d.variantDarkId),p=u?t===d.id||t===d.variantLightId||t===d.variantDarkId:t===d.id,m=u&&s===d.variantLightId;return a.jsxs("button",{type:"button",className:`${ge.themeOption} ${p?ge.themeOptionSelected:""}`,"aria-pressed":p,onClick:()=>o(d.id),children:[a.jsxs("span",{className:ge.themeOptionHeader,children:[a.jsxs("span",{children:[a.jsx("span",{className:ge.themeOptionLabel,children:d.label}),a.jsx("span",{className:ge.themeOptionDesc,children:d.description})]}),u&&a.jsxs("span",{className:ge.variantToggle,children:[a.jsx("span",{role:"button",tabIndex:0,className:`${ge.variantButton} ${p&&m?ge.variantActive:""}`,onClick:g=>{g.stopPropagation(),c(!1),o(d.variantLightId)},onKeyDown:g=>{(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),g.stopPropagation(),c(!1),o(d.variantLightId))},"aria-label":"Light variant","aria-pressed":p&&m,children:"☼"}),a.jsx("span",{role:"button",tabIndex:0,className:`${ge.variantButton} ${p&&!m?ge.variantActive:""}`,onClick:g=>{g.stopPropagation(),c(!1),o(d.variantDarkId)},onKeyDown:g=>{(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),g.stopPropagation(),c(!1),o(d.variantDarkId))},"aria-label":"Dark variant","aria-pressed":p&&!m,children:"☾"})]})]}),d.swatches&&a.jsx("span",{className:ge.themeSwatches,children:d.swatches.map((g,v)=>a.jsx("span",{className:ge.themeSwatch,style:{background:g}},v))})]},d.id)})}),a.jsxs("label",{className:ge.systemToggle,children:[a.jsx("input",{type:"checkbox",checked:r,onChange:d=>c(d.target.checked)}),a.jsx("span",{children:"Match system light/dark preference"})]}),a.jsx("p",{className:ge.systemToggleHint,children:"Automatically switches between light and dark variants when available."}),a.jsxs("p",{className:ge.themeActive,children:["Active theme: ",a.jsx("strong",{children:s})]})]})}const JB={connected:"Connected",connecting:"Connecting...",disconnected:"Disconnected"},WB={connected:ge.aboutDotConnected,connecting:ge.aboutDotConnecting,disconnected:ge.aboutDotDisconnected};function XB({connectionStatus:t,environments:s,sessions:o}){const r=s.filter(u=>u.status==="connected").length,c=s.length,d=o.filter(u=>["running","idle"].includes(u.status)).length;return a.jsxs("section",{className:ge.section,"data-testid":"about-panel",children:[a.jsx("h3",{className:ge.sectionTitle,children:"About"}),a.jsx("p",{className:ge.sectionDescription,children:"Connection status and application information."}),a.jsxs("div",{className:ge.aboutGrid,children:[a.jsxs("div",{className:ge.aboutItem,children:[a.jsx("span",{className:ge.aboutLabel,children:"Connection"}),a.jsxs("span",{className:ge.aboutValue,children:[a.jsx("span",{className:`${ge.aboutDot} ${WB[t]}`}),JB[t]]})]}),a.jsxs("div",{className:ge.aboutItem,children:[a.jsx("span",{className:ge.aboutLabel,children:"Environments"}),a.jsxs("span",{className:ge.aboutValue,children:[r,"/",c," connected"]})]}),a.jsxs("div",{className:ge.aboutItem,children:[a.jsx("span",{className:ge.aboutLabel,children:"Active Sessions"}),a.jsx("span",{className:ge.aboutValue,children:d})]}),a.jsxs("div",{className:ge.aboutItem,children:[a.jsx("span",{className:ge.aboutLabel,children:"Version"}),a.jsx("span",{className:ge.aboutValue,children:"0.106.3"})]})]})]})}const QB="_container_cddyd_1",eL="_header_cddyd_8",tL="_headerTitle_cddyd_35",nL="_badge_cddyd_44",sL="_headerActions_cddyd_54",aL="_body_cddyd_61",iL="_formContent_cddyd_73",oL="_section_cddyd_85",rL="_label_cddyd_91",lL="_titleInput_cddyd_98",cL="_descriptionTextarea_cddyd_131",dL="_parentContext_cddyd_167",uL="_parentLabel_cddyd_175",fL="_parentName_cddyd_182",pL="_personaSelect_cddyd_186",mL="_depList_cddyd_220",hL="_depItem_cddyd_226",gL="_depItemSelected_cddyd_248",vL="_noDeps_cddyd_252",yL="_btnPrimary_cddyd_258",bL="_btnGhost_cddyd_289",nt={container:QB,header:eL,headerTitle:tL,badge:nL,headerActions:sL,body:aL,formContent:iL,section:oL,label:rL,titleInput:lL,descriptionTextarea:cL,parentContext:dL,parentLabel:uL,parentName:fL,personaSelect:pL,depList:mL,depItem:hL,depItemSelected:gL,noDeps:vL,btnPrimary:yL,btnGhost:bL};function W1({mode:t,taskId:s,workspaceId:o,parentTaskId:r,environmentId:c,tasks:d,workspaces:u,personas:p,onCreateTask:m,onUpdateTask:g,onEditDone:v,onShowToast:_}){const b=ct(),x=t==="edit",S=x&&s?d.find(ke=>ke.id===s):void 0,j=x?(S==null?void 0:S.workspaceId)??"":o??"",[w,T]=y.useState(j),C=j||w,D=u.find(ke=>ke.id===C),O=c??(D==null?void 0:D.linkedEnvironmentIds[0]),A=!x&&!o,I=x?(S==null?void 0:S.parentTaskId)??"":r??"",$=I?d.find(ke=>ke.id===I):void 0,[B,P]=y.useState((S==null?void 0:S.title)??""),[X,H]=y.useState((S==null?void 0:S.description)??""),[Q,he]=y.useState((S==null?void 0:S.dependsOn)??[]),[W,ie]=y.useState((S==null?void 0:S.defaultPersonaId)??""),[L,E]=y.useState((S==null?void 0:S.canDecompose)??!1),[J,me]=y.useState(!1),q=y.useRef(!1);y.useEffect(()=>{x&&S&&!q.current&&(q.current=!0,P(S.title),H(S.description),he(S.dependsOn),ie(S.defaultPersonaId),E(S.canDecompose))},[x,S]);const de=d.filter(ke=>ke.workspaceId===C&&(!x||ke.id!==s)&&ke.id!==I),re=B.trim().length>0&&(!x||S!==void 0)&&C.length>0,xe=ke=>{he(Le=>Le.includes(ke)?Le.filter(Ot=>Ot!==ke):[...Le,ke])},be=()=>{!re||J||x&&S===void 0||(x&&s?(g(s,B.trim(),X,Q,W),_==null||_("Task updated","success"),v?v():b($n(s,void 0,C,O),{replace:!0})):(me(!0),m(C,B.trim(),X,Q.length>0?Q:void 0,I||void 0,W,L,()=>{_==null||_("Task created","success"),b(o?Ri(o,O):"/tasks",{replace:!0})},ke=>{_==null||_(ke,"error"),me(!1)})))},fe=()=>{if(v){v();return}b(x&&s?$n(s,void 0,C,O):o?Ri(o,O):"/tasks")},_e=x?"edit task":I?"child task":"new task";return a.jsxs("div",{className:nt.container,children:[a.jsxs("div",{className:nt.header,children:[a.jsxs("div",{className:nt.headerTitle,children:[a.jsx("span",{className:nt.badge,children:_e}),$&&a.jsxs("span",{className:nt.parentContext,children:[a.jsx("span",{className:nt.parentLabel,children:"Child of"}),a.jsx("span",{className:nt.parentName,children:$.title})]})]}),a.jsxs("div",{className:nt.headerActions,children:[a.jsx("button",{onClick:be,disabled:!re||J,className:nt.btnPrimary,"data-testid":"task-edit-save",children:J?"Creating…":x?"Save Changes":"Create"}),a.jsx("button",{onClick:fe,className:nt.btnGhost,children:"Cancel"})]})]}),a.jsx("div",{className:nt.body,children:a.jsxs("div",{className:nt.formContent,children:[A&&a.jsxs("div",{className:nt.section,children:[a.jsx("label",{className:nt.label,htmlFor:"task-edit-workspace",children:"Workspace"}),a.jsxs("select",{id:"task-edit-workspace",value:w,onChange:ke=>T(ke.target.value),className:nt.personaSelect,"data-testid":"task-edit-workspace",children:[a.jsx("option",{value:"",children:"Select a workspace..."}),u.map(ke=>a.jsx("option",{value:ke.id,children:ke.name},ke.id))]})]}),a.jsxs("div",{className:nt.section,children:[a.jsx("label",{className:nt.label,htmlFor:"task-edit-title",children:"Title"}),a.jsx("input",{id:"task-edit-title",type:"text",value:B,onChange:ke=>P(ke.target.value),placeholder:"Task title...",autoFocus:!0,className:nt.titleInput,"data-testid":"task-edit-title",onKeyDown:ke=>{ke.key==="Enter"&&re&&be()}})]}),a.jsxs("div",{className:nt.section,children:[a.jsx("label",{className:nt.label,htmlFor:"task-edit-description",children:"Description"}),a.jsx("textarea",{id:"task-edit-description",value:X,onChange:ke=>H(ke.target.value),placeholder:"Describe the task... (markdown supported)",className:nt.descriptionTextarea,"data-testid":"task-edit-description",rows:8})]}),a.jsxs("div",{className:nt.section,children:[a.jsx("label",{className:nt.label,htmlFor:"task-edit-persona",children:"Default Persona"}),a.jsxs("select",{id:"task-edit-persona",value:W,onChange:ke=>ie(ke.target.value),className:nt.personaSelect,"data-testid":"task-edit-persona",children:[a.jsx("option",{value:"",children:"(Inherit)"}),p.map(ke=>a.jsx("option",{value:ke.id,children:ke.name},ke.id))]})]}),!x&&a.jsx("div",{className:nt.section,children:a.jsxs("label",{className:nt.depItem,"data-testid":"task-edit-can-decompose",children:[a.jsx("input",{type:"checkbox",checked:L,onChange:ke=>E(ke.target.checked)}),"Can spawn subtasks"]})}),a.jsxs("div",{className:nt.section,children:[a.jsx("div",{className:nt.label,children:"Dependencies"}),de.length===0?a.jsx("div",{className:nt.noDeps,children:"No other tasks in this workspace"}):a.jsx("div",{className:nt.depList,children:de.map(ke=>{const Le=Q.includes(ke.id);return a.jsxs("label",{className:`${nt.depItem} ${Le?nt.depItemSelected:""}`,"data-testid":`dep-option-${ke.id}`,children:[a.jsx("input",{type:"checkbox",checked:Le,onChange:()=>xe(ke.id)}),ke.title,a.jsxs("span",{style:{opacity:.5,fontSize:"11px",marginLeft:"4px"},children:["(",ke.status,")"]})]},ke.id)})})]})]})})]})}const _L="_actionButtons_1rjka_1",xL="_btnPrimary_1rjka_8",kL="_btnDanger_1rjka_39",SL="_btnGhost_1rjka_78",Xt={actionButtons:_L,btnPrimary:xL,btnDanger:kL,btnGhost:SL};function jL({task:t,sessionId:s,isBlocked:o,onStart:r,onResume:c,onStop:d,onPause:u,onDelete:p,onEdit:m}){if(t.status==="not_started")return o?a.jsxs("div",{className:Xt.actionButtons,"data-testid":"task-action-buttons",children:[a.jsx("button",{onClick:m,className:Xt.btnGhost,"data-testid":"task-action-edit",children:"Edit"}),a.jsx("button",{onClick:p,className:Xt.btnDanger,"data-testid":"task-action-delete",children:"Delete"})]}):a.jsxs("div",{className:Xt.actionButtons,"data-testid":"task-action-buttons",children:[a.jsx("button",{"data-testid":"task-header-start",onClick:r,className:Xt.btnPrimary,children:"Start"}),a.jsx("button",{onClick:m,className:Xt.btnGhost,"data-testid":"task-action-edit",children:"Edit"}),a.jsx("button",{onClick:p,className:Xt.btnDanger,"data-testid":"task-action-delete",children:"Delete"})]});if(t.status==="working")return a.jsxs("div",{className:Xt.actionButtons,"data-testid":"task-action-buttons",children:[a.jsx("button",{onClick:d,className:Xt.btnDanger,"data-testid":"task-action-stop",children:"Stop"}),a.jsx("button",{onClick:u,disabled:!s,className:Xt.btnGhost,"data-testid":"task-action-pause",children:"Pause"})]});if(t.status==="paused")return a.jsxs("div",{className:Xt.actionButtons,"data-testid":"task-action-buttons",children:[a.jsx("button",{onClick:d,className:Xt.btnPrimary,"data-testid":"task-action-stop",children:"Stop"}),a.jsx("button",{onClick:c,className:Xt.btnGhost,"data-testid":"task-action-resume",children:"Resume"}),a.jsx("button",{onClick:p,className:Xt.btnDanger,"data-testid":"task-action-delete",children:"Delete"})]});if(t.status==="complete")return a.jsx("div",{className:Xt.actionButtons,"data-testid":"task-action-buttons",children:a.jsx("button",{onClick:p,className:Xt.btnDanger,"data-testid":"task-action-delete",children:"Delete"})});if(t.status==="failed")return a.jsxs("div",{className:Xt.actionButtons,"data-testid":"task-action-buttons",children:[a.jsx("button",{onClick:r,className:Xt.btnPrimary,"data-testid":"task-header-start",children:"Retry"}),a.jsx("button",{onClick:p,className:Xt.btnDanger,"data-testid":"task-action-delete",children:"Delete"})]})}const TL="_workpadSection_y8nj9_1",wL="_workpadLabel_y8nj9_9",NL="_workpadStatus_y8nj9_17",CL="_workpadSummary_y8nj9_23",EL="_workpadExtra_y8nj9_29",qa={workpadSection:TL,workpadLabel:wL,workpadStatus:NL,workpadSummary:CL,workpadExtra:EL};function AL({workpad:t}){if(!t)return;let s;try{const o=JSON.parse(t);if(o==null||typeof o!="object"||Array.isArray(o))return;s=o}catch{return a.jsxs("div",{className:qa.workpadSection,"data-testid":"workpad-panel",children:[a.jsx("div",{className:qa.workpadLabel,children:"Workpad"}),a.jsx("div",{className:qa.workpadExtra,children:t})]})}if(!(!s.status&&!s.summary&&!s.extra))return a.jsxs("div",{className:qa.workpadSection,"data-testid":"workpad-panel",children:[a.jsx("div",{className:qa.workpadLabel,children:"Workpad"}),s.status&&a.jsx("div",{className:qa.workpadStatus,"data-testid":"workpad-status",children:s.status}),s.summary&&a.jsx("div",{className:qa.workpadSummary,"data-testid":"workpad-summary",children:s.summary}),s.extra&&Object.keys(s.extra).length>0&&a.jsx("div",{className:qa.workpadExtra,"data-testid":"workpad-extra",children:JSON.stringify(s.extra,null,2)})]})}const DL="_overviewDashboard_r05qm_1",RL="_overviewHero_r05qm_7",ML="_statusBadge_r05qm_14",IL="_statusPending_r05qm_26",OL="_statusAssigned_r05qm_31",BL="_statusInProgress_r05qm_36",LL="_statusReview_r05qm_41",zL="_statusDone_r05qm_46",$L="_statusFailed_r05qm_51",PL="_statusWaitingInput_r05qm_56",UL="_overviewBranchPill_r05qm_61",HL="_branchLink_r05qm_76",VL="_overviewSection_r05qm_87",qL="_overviewLabel_r05qm_93",GL="_overviewValue_r05qm_100",FL="_overviewMuted_r05qm_105",ZL="_overviewMarkdown_r05qm_111",KL="_envRow_r05qm_180",YL="_envDot_r05qm_186",JL="_envDotGreen_r05qm_193",WL="_envDotYellow_r05qm_197",XL="_envDotRed_r05qm_201",QL="_envDotGray_r05qm_205",e8="_depList_r05qm_209",t8="_depItem_r05qm_215",n8="_depBlocked_r05qm_222",s8="_depDone_r05qm_226",a8="_timeline_r05qm_230",i8="_timelineRow_r05qm_236",o8="_timelineKey_r05qm_243",r8="_timelineValue_r05qm_249",l8="_timelineDelta_r05qm_253",c8="_reviewNotes_r05qm_264",ye={overviewDashboard:DL,overviewHero:RL,statusBadge:ML,statusPending:IL,statusAssigned:OL,statusInProgress:BL,statusReview:LL,statusDone:zL,statusFailed:$L,statusWaitingInput:PL,overviewBranchPill:UL,branchLink:HL,overviewSection:VL,overviewLabel:qL,overviewValue:GL,overviewMuted:FL,overviewMarkdown:ZL,envRow:KL,envDot:YL,envDotGreen:JL,envDotYellow:WL,envDotRed:XL,envDotGray:QL,depList:e8,depItem:t8,depBlocked:n8,depDone:s8,timeline:a8,timelineRow:i8,timelineKey:o8,timelineValue:r8,timelineDelta:l8,reviewNotes:c8};function Jc(t){if(!t)return"—";const s=new Date(t);return isNaN(s.getTime())?"—":s.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"})}function Bp(t,s){if(!t||!s)return;const o=new Date(s).getTime()-new Date(t).getTime();if(isNaN(o)||o<0)return;const r=Math.floor(o/6e4),c=Math.floor(o%6e4/1e3);if(r===0)return`${c}s`;const d=Math.floor(r/60),u=r%60;return d===0?`${r}m ${c}s`:`${d}h ${u}m`}function r_(t){const s=t.toLowerCase();return s==="ready"||s==="running"||s==="available"||s==="connected"?ye.envDotGreen:s==="provisioning"||s==="starting"||s==="pending"||s==="connecting"?ye.envDotYellow:s==="error"||s==="failed"||s==="disconnected"?ye.envDotRed:ye.envDotGray}function d8({status:t}){const s=Ja(t),o=BT(t);return a.jsx("span",{className:`${ye.statusBadge} ${ye[o]??ye.statusPending}`,"data-testid":"task-overview-status-badge",children:s.label})}function u8({task:t,tasksById:s,environments:o,workspaces:r,taskSessions:c,selectedEnvId:d,taskUsage:u,treeUsage:p}){const m=c.length>0?c[c.length-1]:void 0,g=(m==null?void 0:m.environmentId)??"",v=g?o.find(S=>S.id===g):void 0,_=r.find(S=>S.id===t.workspaceId),b=o.find(S=>S.id===d),x=t.branch&&(_!=null&&_.repoUrl)?`${_.repoUrl.replace(/\/$/,"")}/tree/${encodeURIComponent(t.branch)}`:void 0;return a.jsxs("div",{className:ye.overviewDashboard,"data-testid":"task-overview-panel",children:[a.jsxs("div",{className:ye.overviewHero,children:[a.jsx(d8,{status:t.status}),t.branch&&a.jsx("span",{className:ye.overviewBranchPill,"data-testid":"task-overview-branch",children:x?a.jsxs("a",{href:x,target:"_blank",rel:"noreferrer noopener",className:ye.branchLink,children:["🔗"," ",t.branch]}):a.jsxs("span",{children:["🔗"," ",t.branch]})})]}),typeof t.description=="string"&&t.description&&a.jsxs("div",{className:ye.overviewSection,"data-testid":"task-overview-description",children:[a.jsx("div",{className:ye.overviewLabel,children:"Description"}),a.jsx("div",{className:ye.overviewMarkdown,children:a.jsx(Ad,{remarkPlugins:[Dd],children:t.description})})]}),t.workpad&&a.jsx(AL,{workpad:t.workpad}),a.jsxs("div",{className:ye.overviewSection,children:[a.jsx("div",{className:ye.overviewLabel,children:"Environment"}),g&&v?a.jsxs("div",{className:ye.envRow,"data-testid":"task-overview-environment",children:[a.jsx("span",{className:`${ye.envDot} ${r_(v.status)}`,title:v.status,"aria-label":`Status: ${v.status}`,role:"img"}),a.jsx("span",{className:ye.overviewValue,children:v.displayName})]}):b?a.jsxs("div",{className:ye.envRow,"data-testid":"task-overview-environment",children:[a.jsx("span",{className:`${ye.envDot} ${r_(b.status)}`,title:b.status,"aria-label":`Status: ${b.status}`,role:"img"}),a.jsx("span",{className:ye.overviewValue,children:b.displayName}),a.jsx("span",{className:ye.overviewMuted,children:"(workspace default)"})]}):a.jsx("div",{className:ye.overviewMuted,children:"Set in workspace settings"})]}),a.jsxs("div",{className:ye.overviewSection,"data-testid":"task-overview-dependencies",children:[a.jsx("div",{className:ye.overviewLabel,children:"Dependencies"}),t.dependsOn.length===0?a.jsx("div",{className:ye.overviewMuted,children:"None"}):a.jsx("div",{className:ye.depList,children:t.dependsOn.map(S=>{const j=s.get(S),w=(j==null?void 0:j.status)==="complete";return a.jsxs("div",{className:`${ye.depItem} ${w?ye.depDone:ye.depBlocked}`,children:[a.jsx("span",{children:w?"✓":"○"}),a.jsx("span",{children:(j==null?void 0:j.title)??S})]},S)})})]}),a.jsxs("div",{className:ye.overviewSection,"data-testid":"task-overview-timeline",children:[a.jsx("div",{className:ye.overviewLabel,children:"Timeline"}),a.jsxs("div",{className:ye.timeline,children:[t.createdAt&&a.jsxs("div",{className:ye.timelineRow,children:[a.jsx("span",{className:ye.timelineKey,children:"Created"}),a.jsx("span",{className:ye.timelineValue,children:Jc(t.createdAt)})]}),t.assignedAt&&(()=>{const S=Bp(t.createdAt,t.assignedAt);return a.jsxs("div",{className:ye.timelineRow,children:[a.jsx("span",{className:ye.timelineKey,children:"Assigned"}),a.jsx("span",{className:ye.timelineValue,children:Jc(t.assignedAt)}),S!==void 0&&a.jsx("span",{className:ye.timelineDelta,children:S})]})})(),t.startedAt&&(()=>{const S=Bp(t.assignedAt??t.createdAt,t.startedAt);return a.jsxs("div",{className:ye.timelineRow,children:[a.jsx("span",{className:ye.timelineKey,children:"Started"}),a.jsx("span",{className:ye.timelineValue,children:Jc(t.startedAt)}),S!==void 0&&a.jsx("span",{className:ye.timelineDelta,children:S})]})})(),t.completedAt&&(()=>{const S=Bp(t.startedAt,t.completedAt);return a.jsxs("div",{className:ye.timelineRow,children:[a.jsx("span",{className:ye.timelineKey,children:"Completed"}),a.jsx("span",{className:ye.timelineValue,children:Jc(t.completedAt)}),S!==void 0&&a.jsx("span",{className:ye.timelineDelta,children:S})]})})(),!t.createdAt&&!t.assignedAt&&!t.startedAt&&!t.completedAt&&a.jsx("div",{className:ye.overviewMuted,children:"No timing data"})]})]}),u&&u.costMillicents>0&&a.jsxs("div",{className:ye.overviewSection,"data-testid":"task-overview-usage",children:[a.jsx("div",{className:ye.overviewLabel,children:"Usage"}),a.jsxs("div",{className:ye.timeline,children:[a.jsxs("div",{className:ye.timelineRow,children:[a.jsx("span",{className:ye.timelineKey,children:"Cost"}),a.jsx("span",{className:ye.timelineValue,children:Ms(u.costMillicents)}),a.jsxs("span",{className:ye.timelineDelta,children:[u.sessionCount," session",u.sessionCount!==1?"s":""]})]}),p&&p.costMillicents>u.costMillicents&&a.jsxs("div",{className:ye.timelineRow,children:[a.jsx("span",{className:ye.timelineKey,children:"Total (incl. subtasks)"}),a.jsx("span",{className:ye.timelineValue,children:Ms(p.costMillicents)}),a.jsxs("span",{className:ye.timelineDelta,children:[p.sessionCount," session",p.sessionCount!==1?"s":""]})]})]})]}),(t.tokenBudget>0||t.costBudgetMillicents>0)&&a.jsxs("div",{className:ye.overviewSection,"data-testid":"task-overview-budget",children:[a.jsx("div",{className:ye.overviewLabel,children:"Budget"}),a.jsxs("div",{className:ye.timeline,children:[t.tokenBudget>0&&a.jsxs("div",{className:ye.timelineRow,children:[a.jsx("span",{className:ye.timelineKey,children:"Tokens"}),a.jsxs("span",{className:ye.timelineValue,children:[zo(((u==null?void 0:u.inputTokens)??0)+((u==null?void 0:u.outputTokens)??0))," / ",zo(t.tokenBudget)]})]}),t.costBudgetMillicents>0&&a.jsxs("div",{className:ye.timelineRow,children:[a.jsx("span",{className:ye.timelineKey,children:"Cost"}),a.jsxs("span",{className:ye.timelineValue,children:[Ms((u==null?void 0:u.costMillicents)??0)," / ",Ms(t.costBudgetMillicents)]})]})]})]}),t.reviewNotes&&a.jsxs("div",{className:ye.overviewSection,"data-testid":"task-overview-review-notes",children:[a.jsx("div",{className:ye.overviewLabel,children:"Review Notes"}),a.jsx("div",{className:ye.reviewNotes,children:t.reviewNotes})]})]})}function f8({plugins:t,loading:s,onSetPluginEnabled:o}){return a.jsxs("div",{className:ge.container,"data-testid":"plugins-panel",children:[a.jsx("h2",{className:ge.heading,children:"Plugins"}),a.jsxs("div",{className:ge.section,children:[a.jsx("p",{className:ge.sectionDescription,children:"Enable or disable optional Grackle plugins. A server restart is required for changes to take effect."}),s&&a.jsx("p",{className:ge.emptyState,children:"Loading plugins..."}),!s&&t.length===0&&a.jsx("p",{className:ge.emptyState,children:"No plugins found."}),!s&&t.map(r=>{const c=r.enabled!==r.loaded;return a.jsxs("div",{className:ge.tokenRow,"data-testid":`plugin-row-${r.name}`,children:[a.jsxs("div",{style:{flex:1},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[a.jsx("span",{className:ge.tokenName,children:r.name}),r.required&&a.jsx("span",{className:ge.tokenBadge,title:"Required — cannot be disabled",children:"required"})]}),a.jsx("div",{className:ge.tokenTarget,children:r.description}),c&&a.jsx("div",{style:{fontSize:"var(--font-size-xs)",color:"var(--accent-yellow)",marginTop:"2px"},"data-testid":`plugin-restart-notice-${r.name}`,children:"Restart Grackle to apply changes"})]}),a.jsx("label",{style:{display:"flex",alignItems:"center",gap:"6px",cursor:r.required?"not-allowed":"pointer"},title:r.required?"Core is required and cannot be disabled":void 0,children:a.jsx("input",{type:"checkbox",checked:r.enabled,disabled:r.required,onChange:d=>o(r.name,d.target.checked),"data-testid":`plugin-toggle-${r.name}`,"aria-label":`Enable or disable ${r.name} plugin`,style:{accentColor:"var(--accent-green)",width:"16px",height:"16px"}})})]},r.name)})]})]})}const p8="_container_legrg_1",m8="_header_legrg_8",h8="_headerTitle_legrg_35",g8="_badge_legrg_44",v8="_headerActions_legrg_54",y8="_body_legrg_61",b8="_formContent_legrg_73",_8="_section_legrg_85",x8="_label_legrg_91",k8="_nameInput_legrg_98",S8="_fieldInput_legrg_131",j8="_adapterSelect_legrg_164",T8="_readOnlyValue_legrg_198",w8="_codespaceSection_legrg_204",N8="_codespaceActions_legrg_210",C8="_creatingHint_legrg_216",E8="_errorHint_legrg_222",A8="_btnPrimary_legrg_235",D8="_btnGhost_legrg_266",ce={container:p8,header:m8,headerTitle:h8,badge:g8,headerActions:v8,body:y8,formContent:b8,section:_8,label:x8,nameInput:k8,fieldInput:S8,adapterSelect:j8,readOnlyValue:T8,codespaceSection:w8,codespaceActions:N8,creatingHint:C8,errorHint:E8,btnPrimary:A8,btnGhost:D8},dd=1,ud=65535;function Lp(t){if(!t.trim())return!0;const s=Number(t);return Number.isInteger(s)&&s>=dd&&s<=ud}function zp(t){try{const s=JSON.parse(t);if(typeof s=="object"&&s!==null&&!Array.isArray(s))return s}catch{}return{}}function R8({codespaceName:t,onCodespaceNameChange:s,envName:o,onEnvNameChange:r,codespaces:c,codespaceError:d,codespaceListError:u,codespaceCreating:p,onCreateCodespace:m}){const[g,v]=y.useState("pick"),[_,b]=y.useState(""),[x,S]=y.useState("");return g==="create"?a.jsxs("div",{className:ce.codespaceSection,children:[a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,children:"Repository"}),a.jsx("input",{type:"text",value:_,onChange:j=>b(j.target.value),placeholder:"owner/repo",className:ce.fieldInput,"data-testid":"env-codespace-repo"})]}),a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,children:"Machine Type"}),a.jsx("input",{type:"text",value:x,onChange:j=>S(j.target.value),placeholder:"Machine type (optional)...",className:ce.fieldInput,"data-testid":"env-codespace-machine"})]}),a.jsxs("div",{className:ce.codespaceActions,children:[a.jsx("button",{onClick:()=>{_.trim()&&(m(_.trim(),x.trim()||void 0),v("pick"),b(""),S(""))},disabled:!_.trim(),className:ce.btnPrimary,children:"Create"}),a.jsx("button",{onClick:()=>{v("pick"),b(""),S("")},className:ce.btnGhost,children:"Cancel"})]})]}):a.jsx("div",{className:ce.codespaceSection,children:a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,children:"Codespace"}),!u&&a.jsxs("select",{value:t,onChange:j=>{j.target.value==="__create__"?(v("create"),s("")):(s(j.target.value),j.target.value&&!o.trim()&&r(j.target.value))},disabled:p,className:ce.adapterSelect,"data-testid":"env-codespace-select",children:[a.jsx("option",{value:"",children:"Select a codespace..."}),c.map(j=>a.jsxs("option",{value:j.name,children:[j.name," (",j.repository,") — ",j.state]},j.name)),a.jsx("option",{value:"__create__",children:"Create new from repo..."})]}),p&&a.jsx("span",{className:ce.creatingHint,children:"Creating codespace..."}),u&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:ce.errorHint,children:u}),a.jsx("input",{type:"text",value:t,onChange:j=>s(j.target.value),placeholder:"Or enter codespace name manually...",className:ce.fieldInput,"data-testid":"env-codespace-manual"})]}),d&&!u&&a.jsx("span",{className:ce.errorHint,children:d})]})})}function X1({mode:t,environmentId:s,environments:o,onAddEnvironment:r,onUpdateEnvironment:c,onListCodespaces:d,codespaces:u,codespaceError:p,codespaceListError:m,codespaceCreating:g,onCreateCodespace:v,onShowToast:_}){const b=ct(),x=t==="edit",S=x&&s?o.find(fe=>fe.id===s):void 0,[j,w]=y.useState(""),[T,C]=y.useState("local"),[D,O]=y.useState(""),[A,I]=y.useState(""),[$,B]=y.useState(""),[P,X]=y.useState(""),[H,Q]=y.useState(""),[he,W]=y.useState(""),[ie,L]=y.useState(""),[E,J]=y.useState(null),me=y.useCallback(()=>{const fe={};if(T==="local"){if(D.trim()&&(fe.host=D.trim()),A.trim()){const _e=Number(A);Number.isInteger(_e)&&(fe.port=_e)}}else if(T==="ssh"){if(fe.host=D.trim(),$.trim()&&(fe.user=$.trim()),A.trim()){const _e=Number(A);Number.isInteger(_e)&&(fe.sshPort=_e)}P.trim()&&(fe.identityFile=P.trim())}else T==="docker"?(H.trim()&&(fe.image=H.trim()),he.trim()&&(fe.repo=he.trim())):T==="codespace"&&(fe.codespaceName=ie.trim());return fe},[T,D,A,$,P,H,he,ie]),q=()=>!(!j.trim()||T==="ssh"&&!D.trim()||T==="codespace"&&!ie.trim()||(T==="local"||T==="ssh")&&!Lp(A)),de=()=>{q()&&(r(j.trim(),T,me()),_==null||_("Environment added successfully","success"),b(Lo,{replace:!0}))},re=()=>{b(s?Mi(s):Lo)},xe=y.useCallback((fe,_e)=>{if(!S||!s)return;const ke=zp(S.adapterConfig),Le=_e.trim();Le?ke[fe]=Le:delete ke[fe],c(s,{adapterConfig:ke})},[S,s,c]),be=y.useCallback((fe,_e)=>{if(!S||!s)return;const ke=zp(S.adapterConfig);if(_e.trim()){const Le=Number(_e);Number.isInteger(Le)&&Le>=dd&&Le<=ud&&(ke[fe]=Le)}else delete ke[fe];c(s,{adapterConfig:ke})},[S,s,c]);if(x){if(!S)return a.jsxs("div",{className:ce.container,children:[a.jsxs("div",{className:ce.header,children:[a.jsx("div",{className:ce.headerTitle,children:a.jsx("span",{className:ce.badge,children:"edit environment"})}),a.jsx("div",{className:ce.headerActions,children:a.jsx("button",{onClick:re,className:ce.btnGhost,children:"Back"})})]}),a.jsx("div",{className:ce.body,children:a.jsx("div",{className:ce.formContent,children:a.jsx("span",{className:ce.readOnlyValue,children:"Environment not found"})})})]});const fe=zp(S.adapterConfig);return a.jsxs("div",{className:ce.container,"data-testid":"env-edit-panel",children:[a.jsxs("div",{className:ce.header,children:[a.jsx("div",{className:ce.headerTitle,children:a.jsx("span",{className:ce.badge,children:"edit environment"})}),a.jsx("div",{className:ce.headerActions,children:a.jsx("button",{onClick:re,className:ce.btnGhost,"data-testid":"env-edit-back",children:"Back"})})]}),a.jsx("div",{className:ce.body,children:a.jsxs("div",{className:ce.formContent,children:[a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,children:"Name"}),a.jsx(Zt,{value:S.displayName,onSave:_e=>{s&&c(s,{displayName:_e})},validate:_e=>_e.trim()===""?"Name cannot be empty":void 0,mode:"edit",fieldId:"name",activeFieldId:E,onActivate:J,placeholder:"Environment name",ariaLabel:"Environment name","data-testid":"env-edit-name"})]}),a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,children:"Adapter Type"}),a.jsx("span",{className:ce.readOnlyValue,"data-testid":"env-edit-adapter-type",children:S.adapterType})]}),S.adapterType==="local"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,children:"Host"}),a.jsx(Zt,{value:String(fe.host??""),onSave:_e=>xe("host",_e),mode:"edit",fieldId:"host",activeFieldId:E,onActivate:J,placeholder:"(default)",ariaLabel:"Host","data-testid":"env-edit-host"})]}),a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,children:"Port"}),a.jsx(Zt,{value:String(fe.port??""),onSave:_e=>be("port",_e),validate:_e=>Lp(_e)?void 0:"Port must be 1-65535",mode:"edit",fieldId:"port",activeFieldId:E,onActivate:J,placeholder:"(default)",ariaLabel:"Port","data-testid":"env-edit-port"})]})]}),S.adapterType==="ssh"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,children:"Host"}),a.jsx(Zt,{value:String(fe.host??""),onSave:_e=>xe("host",_e),validate:_e=>_e.trim()===""?"Host is required":void 0,mode:"edit",fieldId:"host",activeFieldId:E,onActivate:J,placeholder:"hostname or IP",ariaLabel:"Host","data-testid":"env-edit-host"})]}),a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,children:"User"}),a.jsx(Zt,{value:String(fe.user??""),onSave:_e=>xe("user",_e),mode:"edit",fieldId:"user",activeFieldId:E,onActivate:J,placeholder:"(default)",ariaLabel:"User","data-testid":"env-edit-user"})]}),a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,children:"SSH Port"}),a.jsx(Zt,{value:String(fe.sshPort??""),onSave:_e=>be("sshPort",_e),validate:_e=>Lp(_e)?void 0:"Port must be 1-65535",mode:"edit",fieldId:"sshPort",activeFieldId:E,onActivate:J,placeholder:"22",ariaLabel:"SSH Port","data-testid":"env-edit-ssh-port"})]}),a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,children:"Identity File"}),a.jsx(Zt,{value:String(fe.identityFile??""),onSave:_e=>xe("identityFile",_e),mode:"edit",fieldId:"identityFile",activeFieldId:E,onActivate:J,placeholder:"~/.ssh/id_rsa",ariaLabel:"Identity File","data-testid":"env-edit-identity-file"})]})]}),S.adapterType==="docker"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,children:"Image"}),a.jsx(Zt,{value:String(fe.image??""),onSave:_e=>xe("image",_e),mode:"edit",fieldId:"image",activeFieldId:E,onActivate:J,placeholder:"(default)",ariaLabel:"Image","data-testid":"env-edit-image"})]}),a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,children:"Repo"}),a.jsx(Zt,{value:String(fe.repo??""),onSave:_e=>xe("repo",_e),mode:"edit",fieldId:"repo",activeFieldId:E,onActivate:J,placeholder:"(none)",ariaLabel:"Repo","data-testid":"env-edit-repo"})]})]}),S.adapterType==="codespace"&&a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,children:"Codespace Name"}),a.jsx(Zt,{value:String(fe.codespaceName??""),onSave:_e=>xe("codespaceName",_e),validate:_e=>_e.trim()===""?"Codespace name is required":void 0,mode:"edit",fieldId:"codespaceName",activeFieldId:E,onActivate:J,placeholder:"codespace-name",ariaLabel:"Codespace Name","data-testid":"env-edit-codespace-name"})]})]})})]})}return a.jsxs("div",{className:ce.container,"data-testid":"env-create-panel",children:[a.jsxs("div",{className:ce.header,children:[a.jsx("div",{className:ce.headerTitle,children:a.jsx("span",{className:ce.badge,children:"new environment"})}),a.jsxs("div",{className:ce.headerActions,children:[a.jsx("button",{onClick:de,disabled:!q(),className:ce.btnPrimary,"data-testid":"env-create-submit",children:"Create"}),a.jsx("button",{onClick:re,className:ce.btnGhost,children:"Cancel"})]})]}),a.jsx("div",{className:ce.body,children:a.jsxs("div",{className:ce.formContent,children:[a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,htmlFor:"env-create-name",children:"Name"}),a.jsx("input",{id:"env-create-name",type:"text",value:j,onChange:fe=>w(fe.target.value),placeholder:"Environment name...",autoFocus:!0,className:ce.nameInput,"data-testid":"env-create-name",onKeyDown:fe=>{fe.key==="Enter"&&q()&&de()}})]}),a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,htmlFor:"env-create-adapter",children:"Adapter Type"}),a.jsxs("select",{id:"env-create-adapter",value:T,onChange:fe=>{C(fe.target.value),fe.target.value==="codespace"&&d()},className:ce.adapterSelect,"data-testid":"env-create-adapter",children:[a.jsx("option",{value:"local",children:"local"}),a.jsx("option",{value:"ssh",children:"ssh"}),a.jsx("option",{value:"docker",children:"docker"}),a.jsx("option",{value:"codespace",children:"codespace"})]})]}),T==="local"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,htmlFor:"env-create-host",children:"Host"}),a.jsx("input",{id:"env-create-host",type:"text",value:D,onChange:fe=>O(fe.target.value),placeholder:"Host (optional)...",className:ce.fieldInput,"data-testid":"env-create-host"})]}),a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,htmlFor:"env-create-port",children:"Port"}),a.jsx("input",{id:"env-create-port",type:"number",min:dd,max:ud,value:A,onChange:fe=>I(fe.target.value),placeholder:"Port (optional)...",className:ce.fieldInput,"data-testid":"env-create-port"})]})]}),T==="ssh"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,htmlFor:"env-create-host",children:"Host"}),a.jsx("input",{id:"env-create-host",type:"text",value:D,onChange:fe=>O(fe.target.value),placeholder:"Host (required)...",className:ce.fieldInput,"data-testid":"env-create-host"})]}),a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,htmlFor:"env-create-user",children:"User"}),a.jsx("input",{id:"env-create-user",type:"text",value:$,onChange:fe=>B(fe.target.value),placeholder:"User (optional)...",className:ce.fieldInput,"data-testid":"env-create-user"})]}),a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,htmlFor:"env-create-port",children:"SSH Port"}),a.jsx("input",{id:"env-create-port",type:"number",min:dd,max:ud,value:A,onChange:fe=>I(fe.target.value),placeholder:"SSH port (optional)...",className:ce.fieldInput,"data-testid":"env-create-port"})]}),a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,htmlFor:"env-create-identity",children:"Identity File"}),a.jsx("input",{id:"env-create-identity",type:"text",value:P,onChange:fe=>X(fe.target.value),placeholder:"Identity file (optional)...",className:ce.fieldInput,"data-testid":"env-create-identity"})]})]}),T==="docker"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,htmlFor:"env-create-image",children:"Image"}),a.jsx("input",{id:"env-create-image",type:"text",value:H,onChange:fe=>Q(fe.target.value),placeholder:"Image (optional)...",className:ce.fieldInput,"data-testid":"env-create-image"})]}),a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,htmlFor:"env-create-repo",children:"Repo"}),a.jsx("input",{id:"env-create-repo",type:"text",value:he,onChange:fe=>W(fe.target.value),placeholder:"Repo (optional)...",className:ce.fieldInput,"data-testid":"env-create-repo"})]})]}),T==="codespace"&&a.jsx(R8,{codespaceName:ie,onCodespaceNameChange:L,envName:j,onEnvNameChange:w,codespaces:u,codespaceError:p,codespaceListError:m,codespaceCreating:g,onCreateCodespace:v})]})})]})}const M8="_group_1iprv_1",I8="_groupTitle_1iprv_8",O8="_shortcutList_1iprv_17",B8="_shortcutRow_1iprv_23",L8="_keys_1iprv_36",z8="_kbd_1iprv_43",$8="_description_1iprv_60",Ti={group:M8,groupTitle:I8,shortcutList:O8,shortcutRow:B8,keys:L8,kbd:z8,description:$8},P8=[{title:"Global",shortcuts:[{keys:["?"],description:"Open keyboard shortcuts reference"},{keys:["N"],description:"Create a new task"},{keys:["Escape"],description:"Close dialog or cancel editing"}]},{title:"Task Page",shortcuts:[{keys:["1"],description:"Switch to Overview tab"},{keys:["2"],description:"Switch to Stream tab"},{keys:["3"],description:"Switch to Findings tab"}]},{title:"Workspace Page",shortcuts:[{keys:["1"],description:"Switch to Graph view"},{keys:["2"],description:"Switch to Board view"},{keys:["3"],description:"Switch to Tasks view"}]},{title:"Navigation Lists",shortcuts:[{keys:["←"],description:"Previous tab (horizontal nav)"},{keys:["→"],description:"Next tab (horizontal nav)"},{keys:["↑"],description:"Previous item (vertical nav)"},{keys:["↓"],description:"Next item (vertical nav)"},{keys:["J"],description:"Next item (alias for arrow down/right)"},{keys:["K"],description:"Previous item (alias for arrow up/left)"},{keys:["Home"],description:"Jump to first item"},{keys:["End"],description:"Jump to last item"}]},{title:"Editing",shortcuts:[{keys:["Enter"],description:"Activate / save inline edit"},{keys:["Space"],description:"Activate button or start editing"},{keys:["Escape"],description:"Cancel edit and discard changes"}]},{title:"Chat",shortcuts:[{keys:["Enter"],description:"Send message (when input is focused)"}]}];function U8(){return a.jsxs("section",{className:ge.section,"data-testid":"keyboard-shortcuts-panel",children:[a.jsx("h3",{className:ge.sectionTitle,children:"Keyboard Shortcuts"}),a.jsx("p",{className:ge.sectionDescription,children:"Keyboard shortcuts for navigating and interacting with Grackle. Global shortcuts are suppressed while typing in text fields."}),P8.map(t=>a.jsxs("div",{className:Ti.group,children:[a.jsx("h4",{className:Ti.groupTitle,children:t.title}),a.jsx("div",{className:Ti.shortcutList,children:t.shortcuts.map(s=>a.jsxs("div",{className:Ti.shortcutRow,children:[a.jsx("span",{className:Ti.keys,children:s.keys.map(o=>a.jsx("kbd",{className:Ti.kbd,children:o},o))}),a.jsx("span",{className:Ti.description,children:s.description})]},s.description))})]},t.title))]})}const H8=[{key:"claude",label:"Claude",description:"Forward Claude credentials for AI agent access.",options:[{value:"off",label:"Off"},{value:"subscription",label:"Subscription"},{value:"api_key",label:"API Key"}]},{key:"github",label:"GitHub",description:"Forward GITHUB_TOKEN and GH_TOKEN for git operations.",options:[{value:"off",label:"Off"},{value:"on",label:"On"}]},{key:"copilot",label:"Copilot",description:"Forward Copilot tokens (COPILOT_GITHUB_TOKEN, CLI config).",options:[{value:"off",label:"Off"},{value:"on",label:"On"}]},{key:"codex",label:"Codex",description:"Forward OPENAI_API_KEY for Codex/OpenAI access.",options:[{value:"off",label:"Off"},{value:"on",label:"On"}]},{key:"goose",label:"Goose",description:"Forward Goose config and API keys for Goose agent access.",options:[{value:"off",label:"Off"},{value:"on",label:"On"}]}];function V8({credentialProviders:t,onUpdateCredentialProviders:s}){const o=(r,c)=>{const d={...t};r==="claude"?d.claude=c:d[r]=c,s(d)};return a.jsxs("section",{className:ge.section,children:[a.jsx("h3",{className:ge.sectionTitle,children:"Credential Providers"}),a.jsx("p",{className:ge.sectionDescription,children:"Enable providers to automatically forward credentials to environments at task start. Credentials are read fresh from the host each time."}),a.jsx("div",{className:ge.tokenList,children:H8.map(r=>a.jsxs("div",{className:ge.tokenRow,children:[a.jsx("span",{className:ge.tokenName,children:r.label}),a.jsx("span",{className:ge.tokenTarget,children:r.description}),a.jsx("select",{className:ge.select,value:t[r.key],onChange:c=>o(r.key,c.target.value),children:r.options.map(c=>a.jsx("option",{value:c.value,children:c.label},c.value))})]},r.key))})]})}const q8="_container_10efq_1",G8="_header_10efq_7",F8="_list_10efq_105",Z8="_card_10efq_111",K8="_cardHeader_10efq_125",Y8="_cardTitle_10efq_135",J8="_defaultBadge_10efq_141",W8="_cardActions_10efq_155",X8="_description_10efq_160",Q8="_meta_10efq_166",e7="_empty_10efq_212",t7="_typeBadge_10efq_362",ss={container:q8,header:G8,list:F8,card:Z8,cardHeader:K8,cardTitle:Y8,defaultBadge:J8,cardActions:W8,description:X8,meta:Q8,empty:e7,typeBadge:t7};function n7({personas:t,appDefaultPersonaId:s,onDeletePersona:o,onSetAppDefaultPersonaId:r,onNavigateToNew:c,onNavigateToPersona:d}){const[u,p]=y.useState(null),m=u?t.find(v=>v.id===u):void 0,g=async v=>{await o(v),p(null)};return a.jsxs("div",{className:ss.container,children:[a.jsxs("div",{className:ss.header,children:[a.jsx("h2",{children:"Personas"}),a.jsx(on,{variant:"primary",size:"md",onClick:c,"data-testid":"persona-new-button",children:"+ New Persona"})]}),t.length===0?a.jsx("p",{className:ss.empty,children:"No personas yet. Create one to get started."}):a.jsx("div",{className:ss.list,children:t.map(v=>{const _=s===v.id,b=v.type==="script";return a.jsxs("div",{className:ss.card,"data-testid":`persona-card-${v.id}`,onClick:()=>d(v.id),role:"button",tabIndex:0,onKeyDown:x=>{x.currentTarget===x.target&&(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),d(v.id))},children:[a.jsxs("div",{className:ss.cardHeader,children:[a.jsxs("span",{className:ss.cardTitle,children:[a.jsx("strong",{children:v.name}),a.jsx("span",{className:ss.typeBadge,"data-testid":`persona-type-badge-${v.id}`,children:b?"Script":"Agent"}),_&&a.jsx("span",{className:ss.defaultBadge,"data-testid":`persona-default-badge-${v.id}`,children:"App Default"})]}),a.jsxs("div",{className:ss.cardActions,onClick:x=>x.stopPropagation(),children:[!_&&a.jsx(on,{variant:"ghost",size:"sm",onClick:()=>{r(v.id).catch(()=>{})},"data-testid":`persona-set-default-${v.id}`,title:"Set as app default persona",children:"Set Default"}),a.jsx(on,{variant:"ghost",size:"sm",onClick:()=>d(v.id),children:"Edit"}),a.jsx(on,{variant:"ghost",size:"sm",onClick:()=>p(v.id),"data-testid":`persona-delete-${v.id}`,children:"Delete"})]})]}),v.description&&a.jsx("p",{className:ss.description,children:v.description}),a.jsxs("div",{className:ss.meta,children:[v.runtime&&a.jsxs("span",{children:["Runtime: ",v.runtime]}),v.model&&a.jsxs("span",{children:["Model: ",v.model]}),v.maxTurns>0&&a.jsxs("span",{children:["Max turns: ",v.maxTurns]})]})]},v.id)})}),a.jsx(Ls,{isOpen:u!==null,title:"Delete Persona?",description:`"${(m==null?void 0:m.name)??""}" will be permanently removed.`,confirmLabel:"Delete",onConfirm:()=>{u&&g(u).catch(()=>{})},onCancel:()=>p(null)})]})}const s7="_container_uy08i_1",a7="_header_uy08i_7",i7="_count_uy08i_13",o7="_presets_uy08i_18",r7="_presetButton_uy08i_24",l7="_filterInput_uy08i_41",c7="_groups_uy08i_53",d7="_group_uy08i_53",u7="_groupHeader_uy08i_68",f7="_groupName_uy08i_77",p7="_groupCount_uy08i_81",m7="_toolList_uy08i_87",h7="_toolItem_uy08i_95",g7="_toolName_uy08i_103",bn={container:s7,header:a7,count:i7,presets:o7,presetButton:r7,filterInput:l7,groups:c7,group:d7,groupHeader:u7,groupName:f7,groupCount:p7,toolList:m7,toolItem:h7,toolName:g7},v7=(()=>{const t=new Map;for(const s of E_){const o=s==="get_version_status"?"version":s.split("_")[0];t.has(o)||t.set(o,[]),t.get(o).push(s)}return[...t.entries()].sort(([s],[o])=>s.localeCompare(o)).map(([s,o])=>({group:s,tools:o.sort()}))})(),y7=[{name:"default",label:"Default",tools:A_},{name:"worker",label:"Worker",tools:U2},{name:"orchestrator",label:"Orchestrator",tools:H2},{name:"admin",label:"Admin",tools:V2}];function l_({selectedTools:t,onChange:s,disabled:o}){const[r,c]=y.useState(""),d=y.useMemo(()=>new Set(t),[t]),u=y.useCallback(v=>{if(o)return;const _=new Set(d);_.has(v)?_.delete(v):_.add(v),s([..._].sort())},[d,s,o]),p=y.useCallback((v,_)=>{if(o)return;const b=new Set(d);for(const x of v)_?b.delete(x):b.add(x);s([...b].sort())},[d,s,o]),m=y.useCallback(v=>{o||s([...v].sort())},[s,o]),g=r.toLowerCase();return a.jsxs("div",{className:bn.container,"data-testid":"mcp-tool-selector",children:[a.jsx("div",{className:bn.header,children:a.jsx("span",{className:bn.count,children:t.length===0?`Using default (${A_.length} tools)`:`${t.length} of ${E_.size} tools selected`})}),a.jsxs("div",{className:bn.presets,"data-testid":"mcp-tool-presets",children:[y7.map(v=>a.jsx("button",{type:"button",className:bn.presetButton,disabled:o,onClick:()=>m(v.tools),"data-testid":`preset-${v.name}`,children:v.label},v.name)),a.jsx("button",{type:"button",className:bn.presetButton,disabled:o,onClick:()=>s([]),"data-testid":"preset-clear",children:"Clear"})]}),a.jsx("input",{type:"text",className:bn.filterInput,placeholder:"Filter tools...",value:r,onChange:v=>c(v.target.value),disabled:o,"data-testid":"mcp-tool-filter"}),a.jsx("div",{className:bn.groups,children:v7.map(({group:v,tools:_})=>{const b=g?_.filter(S=>S.toLowerCase().includes(g)):_;if(b.length===0)return null;const x=b.every(S=>d.has(S));return a.jsxs("div",{className:bn.group,"data-testid":`tool-group-${v}`,children:[a.jsxs("label",{className:bn.groupHeader,children:[a.jsx("input",{type:"checkbox",checked:x,onChange:()=>p(b,x),disabled:o,"data-testid":`group-toggle-${v}`}),a.jsx("span",{className:bn.groupName,children:v}),a.jsxs("span",{className:bn.groupCount,children:["(",b.filter(S=>d.has(S)).length,"/",b.length,")"]})]}),a.jsx("div",{className:bn.toolList,children:b.map(S=>a.jsxs("label",{className:bn.toolItem,children:[a.jsx("input",{type:"checkbox",checked:d.has(S),onChange:()=>u(S),disabled:o,"data-testid":`tool-${S}`}),a.jsx("span",{className:bn.toolName,children:S})]},S))})]},v)})})]})}const b7="_container_1gfuq_1",_7="_header_1gfuq_7",x7="_list_1gfuq_19",k7="_card_1gfuq_25",S7="_cardHeader_1gfuq_40",j7="_cardTitle_1gfuq_46",T7="_statusBadge_1gfuq_56",w7="_enabled_1gfuq_68",N7="_disabled_1gfuq_71",C7="_cardActions_1gfuq_75",E7="_cardMeta_1gfuq_80",A7="_empty_1gfuq_98",as={container:b7,header:_7,list:x7,card:k7,cardHeader:S7,cardTitle:j7,statusBadge:T7,enabled:w7,disabled:N7,cardActions:C7,cardMeta:E7,empty:A7};function D7({schedules:t,personas:s,onDeleteSchedule:o,onToggleEnabled:r,onNavigateToNew:c,onNavigateToSchedule:d}){const[u,p]=y.useState(null),m=u?t.find(b=>b.id===u):void 0,g=async b=>{await o(b),p(null)},v=y.useMemo(()=>{const b=new Map;for(const x of s)b.set(x.id,x.name);return b},[s]),_=b=>v.get(b)??b;return a.jsxs("div",{className:as.container,children:[a.jsxs("div",{className:as.header,children:[a.jsx("h2",{children:"Schedules"}),a.jsx(on,{variant:"primary",size:"md",onClick:c,"data-testid":"schedule-new-button",children:"+ New Schedule"})]}),t.length===0?a.jsx("p",{className:as.empty,"data-testid":"schedule-empty-state",children:"No schedules yet. Create one to run tasks on a recurring cadence."}):a.jsx("div",{className:as.list,children:t.map(b=>a.jsxs("div",{className:as.card,"data-testid":`schedule-card-${b.id}`,onClick:()=>d(b.id),role:"button",tabIndex:0,onKeyDown:x=>{x.currentTarget===x.target&&(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),d(b.id))},children:[a.jsxs("div",{className:as.cardHeader,children:[a.jsxs("span",{className:as.cardTitle,children:[a.jsx("strong",{children:b.title}),a.jsx("span",{className:`${as.statusBadge} ${b.enabled?as.enabled:as.disabled}`,"data-testid":`schedule-status-badge-${b.id}`,children:b.enabled?"Enabled":"Disabled"})]}),a.jsxs("div",{className:as.cardActions,onClick:x=>x.stopPropagation(),children:[a.jsx(on,{variant:"ghost",size:"sm",onClick:()=>{(async()=>{await r(b.id,{enabled:!b.enabled})})().catch(()=>{})},"data-testid":`schedule-toggle-${b.id}`,title:b.enabled?"Disable schedule":"Enable schedule",children:b.enabled?"Disable":"Enable"}),a.jsx(on,{variant:"ghost",size:"sm",onClick:()=>d(b.id),"data-testid":`schedule-edit-${b.id}`,children:"Edit"}),a.jsx(on,{variant:"ghost",size:"sm",onClick:()=>p(b.id),"data-testid":`schedule-delete-${b.id}`,children:"Delete"})]})]}),a.jsxs("div",{className:as.cardMeta,children:[a.jsx("span",{"data-testid":`schedule-expression-${b.id}`,children:b.scheduleExpression}),b.personaId&&a.jsxs("span",{"data-testid":`schedule-persona-${b.id}`,children:["Persona: ",_(b.personaId)]}),a.jsxs("span",{"data-testid":`schedule-last-run-${b.id}`,children:["Last run: ",b.lastRunAt?Ho(b.lastRunAt):"Never"]}),b.enabled&&b.nextRunAt?a.jsxs("span",{"data-testid":`schedule-next-run-${b.id}`,children:["Next run: ",q1(b.nextRunAt)]}):null,b.runCount>0&&a.jsxs("span",{"data-testid":`schedule-run-count-${b.id}`,children:["Runs: ",b.runCount]})]})]},b.id))}),a.jsx(Ls,{isOpen:u!==null,title:"Delete Schedule?",description:`"${(m==null?void 0:m.title)??""}" will be permanently removed. Tasks already created by this schedule will not be affected.`,confirmLabel:"Delete",onConfirm:()=>{u&&g(u).catch(()=>{})},onCancel:()=>p(null)})]})}const R7="_nav_1bhou_1",M7="_tab_1bhou_24",I7="_tabIcon_1bhou_62",O7="_tabActive_1bhou_68",Wc={nav:R7,tab:M7,tabIcon:I7,tabActive:O7},aa=[{path:"credentials",label:"Credentials",icon:a.jsx(eT,{size:At})},{path:"personas",label:"Personas",icon:a.jsx(MT,{size:At})},{path:"schedules",label:"Schedules",icon:a.jsx(Aj,{size:At})},{path:"appearance",label:"Appearance",icon:a.jsx(hT,{size:At})},{path:"shortcuts",label:"Shortcuts",icon:a.jsx(nT,{size:At})},{path:"plugins",label:"Plugins",icon:a.jsx(xT,{size:At})},{path:"about",label:"About",icon:a.jsx(Tm,{size:At})}];function B7(){var u;const t=Yt(),s=ct(),o=y.useRef(null),r=((u=aa.find(p=>{const m=`${Ei}/${p.path}`;return t.pathname===m||t.pathname.startsWith(`${m}/`)}))==null?void 0:u.path)??aa[0].path,c=y.useCallback(p=>{s(`${Ei}/${p}`)},[s]),d=y.useCallback(p=>{var x,S;const m=(x=o.current)==null?void 0:x.querySelectorAll('[role="tab"]');if(!m)return;const g=Array.from(m).findIndex(j=>j===document.activeElement),v=g>=0?g:aa.findIndex(j=>j.path===r);let _=v;if(p.key==="ArrowDown"||p.key==="j"||p.key==="J")p.preventDefault(),_=(v+1)%aa.length;else if(p.key==="ArrowUp"||p.key==="k"||p.key==="K")p.preventDefault(),_=(v-1+aa.length)%aa.length;else if(p.key==="Home")p.preventDefault(),_=0;else if(p.key==="End")p.preventDefault(),_=aa.length-1;else return;const b=aa[_].path;s(`${Ei}/${b}`),(S=m[_])==null||S.focus()},[r,s]);return a.jsx("nav",{className:Wc.nav,ref:o,role:"tablist","aria-orientation":"vertical","aria-label":"Settings",onKeyDown:d,children:aa.map(p=>{const m=p.path===r;return a.jsxs("button",{role:"tab",type:"button","aria-selected":m,tabIndex:m?0:-1,className:`${Wc.tab} ${m?Wc.tabActive:""}`,onClick:()=>c(p.path),children:[a.jsx("span",{className:Wc.tabIcon,"aria-hidden":"true",children:p.icon}),p.label]},p.path)})})}const L7="_container_1dqrb_1",z7="_header_1dqrb_5",$7="_refreshButton_1dqrb_17",P7="_streamRow_1dqrb_32",U7="_selected_1dqrb_49",H7="_systemRow_1dqrb_53 _streamRow_1dqrb_32",V7="_streamIcon_1dqrb_60",q7="_streamName_1dqrb_65",G7="_subscriberBadge_1dqrb_74",F7="_emptyState_1dqrb_88",Z7="_loading_1dqrb_95",_n={container:L7,header:z7,refreshButton:$7,streamRow:P7,selected:U7,systemRow:H7,streamIcon:V7,streamName:q7,subscriberBadge:G7,emptyState:F7,loading:Z7},c_=14;function K7({streams:t,loading:s,streamsLoadError:o=!1,streamsLoadedOnce:r=!0,onRefresh:c}){const d=ct(),u=Yt(),p=Et("/chat/:streamId"),m=p==null?void 0:p.params.streamId,g=!m&&u.pathname===dl,v=[...t].sort((x,S)=>x.name.localeCompare(S.name)),_=y.useCallback(()=>{d(dl)},[d]),b=y.useCallback(x=>{d(PN(x))},[d]);return a.jsxs("div",{className:_n.container,"data-testid":"stream-list",children:[a.jsxs("div",{className:_n.header,children:[a.jsx("span",{children:"Streams"}),c&&a.jsx("button",{className:_n.refreshButton,onClick:c,"aria-label":"Refresh streams","data-testid":"stream-list-refresh",children:a.jsx(TT,{size:12})})]}),a.jsxs("button",{type:"button",className:`${_n.systemRow}${g?` ${_n.selected}`:""}`,onClick:_,"data-testid":"stream-list-system-row","aria-current":g?"page":void 0,children:[a.jsx(B_,{size:c_,className:_n.streamIcon}),a.jsx("span",{className:_n.streamName,children:"System"})]}),s&&v.length===0&&a.jsx("div",{className:_n.loading,children:"Loading..."}),!s&&o&&a.jsx("div",{className:_n.emptyState,"data-testid":"stream-list-error",children:"Unable to load streams"}),!s&&!o&&r&&v.length===0&&a.jsx("div",{className:_n.emptyState,children:"No streams"}),v.map(x=>{const S=m===x.id;return a.jsxs("button",{type:"button",className:`${_n.streamRow}${S?` ${_n.selected}`:""}`,onClick:()=>b(x.id),"data-testid":`stream-list-row-${x.id}`,"aria-current":S?"page":void 0,children:[a.jsx(ST,{size:c_,className:_n.streamIcon}),a.jsx("span",{className:_n.streamName,children:x.name}),x.subscriberCount>0&&a.jsx("span",{className:_n.subscriberBadge,children:x.subscriberCount})]},x.id)})]})}const Y7="_panel_1au81_1",J7="_header_1au81_24",W7="_title_1au81_33",X7="_closeButton_1au81_43",Q7="_body_1au81_57",ez="_section_1au81_63",tz="_sectionLabel_1au81_67",nz="_metaRow_1au81_76",sz="_metaKey_1au81_84",az="_metaValue_1au81_90",iz="_subscriberCard_1au81_99",oz="_subscriberHeader_1au81_107",rz="_sessionLink_1au81_114",lz="_badges_1au81_132",cz="_badgeRw_1au81_150 _badge_1au81_132",dz="_badgeR_1au81_150 _badge_1au81_132",uz="_badgeW_1au81_162 _badge_1au81_132",fz="_badgeAsync_1au81_168 _badge_1au81_132",pz="_badgeSync_1au81_174 _badge_1au81_132",mz="_badgeDetach_1au81_178 _badge_1au81_132",hz="_spawnTag_1au81_184 _badge_1au81_132",gz="_fdNumber_1au81_189",vz="_emptySubscribers_1au81_195",ot={panel:Y7,header:J7,title:W7,closeButton:X7,body:Q7,section:ez,sectionLabel:tz,metaRow:nz,metaKey:sz,metaValue:az,subscriberCard:iz,subscriberHeader:oz,sessionLink:rz,badges:lz,badgeRw:cz,badgeR:dz,badgeW:uz,badgeAsync:fz,badgeSync:pz,badgeDetach:mz,spawnTag:hz,fdNumber:gz,emptySubscribers:vz};function yz({permission:t}){const s=t==="rw"?ot.badgeRw:t==="r"?ot.badgeR:ot.badgeW;return a.jsx("span",{className:s,children:t})}function bz({mode:t}){const s=t==="async"?ot.badgeAsync:t==="detach"?ot.badgeDetach:ot.badgeSync;return a.jsx("span",{className:s,children:t})}function _z({stream:t,onClose:s}){const o=ct();return y.useEffect(()=>{const r=c=>{c.key==="Escape"&&s()};return document.addEventListener("keydown",r),()=>{document.removeEventListener("keydown",r)}},[s]),a.jsxs("div",{className:ot.panel,"data-testid":"stream-detail-panel",children:[a.jsxs("div",{className:ot.header,children:[a.jsx("h3",{className:ot.title,children:t.name}),a.jsx("button",{className:ot.closeButton,onClick:s,"aria-label":"Close stream details",children:"×"})]}),a.jsxs("div",{className:ot.body,children:[a.jsxs("div",{className:ot.section,children:[a.jsx("div",{className:ot.sectionLabel,children:"Overview"}),a.jsxs("div",{className:ot.metaRow,children:[a.jsx("span",{className:ot.metaKey,children:"Stream ID"}),a.jsx("span",{className:ot.metaValue,children:t.id})]}),a.jsxs("div",{className:ot.metaRow,children:[a.jsx("span",{className:ot.metaKey,children:"Subscribers"}),a.jsx("span",{className:ot.metaValue,children:t.subscriberCount})]}),a.jsxs("div",{className:ot.metaRow,children:[a.jsx("span",{className:ot.metaKey,children:"Buffered"}),a.jsxs("span",{className:ot.metaValue,children:[t.messageBufferDepth," msgs"]})]})]}),a.jsxs("div",{className:ot.section,children:[a.jsx("div",{className:ot.sectionLabel,children:"Subscribers"}),t.subscribers.length===0?a.jsx("div",{className:ot.emptySubscribers,children:"No active subscribers"}):t.subscribers.map(r=>a.jsxs("div",{className:ot.subscriberCard,"data-testid":`subscriber-card-${r.subscriptionId}`,children:[a.jsxs("div",{className:ot.subscriberHeader,children:[a.jsxs("span",{className:ot.fdNumber,children:["fd ",r.fd]}),a.jsxs("button",{className:ot.sessionLink,onClick:()=>{o(Ld(r.sessionId))},title:r.sessionId,children:[r.sessionId.slice(0,12),"…"]})]}),a.jsxs("div",{className:ot.badges,children:[a.jsx(yz,{permission:r.permission}),a.jsx(bz,{mode:r.deliveryMode}),r.createdBySpawn&&a.jsx("span",{className:ot.spawnTag,children:"spawn"})]})]},r.subscriptionId))]})]})]})}function xz({tasks:t,taskStatusById:s,sessionStatusByTaskId:o}){const r=new Map;for(const d of t)if(d.parentTaskId){const u=r.get(d.parentTaskId);u?u.push(d):r.set(d.parentTaskId,[d])}const c=new Map(Ty.map(d=>[d,[]]));for(const d of t){const u=vl(d.status),p=d.dependsOn.length>0&&d.dependsOn.some(S=>s.get(S)!=="complete"),m=r.get(d.id)??[],g=m.length,v=m.filter(S=>S.status==="complete").length;let _;if(u==="paused"&&o){const S=o.get(d.id);S==="idle"?_="Needs input":S==="completed"&&(_="Ready to complete")}const b={task:d,isBlocked:p,childCount:g,doneChildCount:v,pausedSubBadge:_},x=c.get(u);x?x.push(b):c.get("not_started").push(b)}for(const d of c.values())d.sort((u,p)=>u.task.sortOrder-p.task.sortOrder);return Ty.map(d=>{const u=Ja(d);return{status:d,label:u.label,style:u,tasks:c.get(d)??[]}})}const kz="_boardContainer_1c4y1_1",Sz="_column_1c4y1_17",jz="_columnHeader_1c4y1_34",Tz="_columnIcon_1c4y1_47",wz="_columnLabel_1c4y1_52",Nz="_columnCount_1c4y1_57",Cz="_cardList_1c4y1_67",Ez="_emptyPlaceholder_1c4y1_76",Az="_card_1c4y1_67",Dz="_cardHeader_1c4y1_107",Rz="_cardStatusIcon_1c4y1_113",Mz="_cardTitle_1c4y1_119",Iz="_cardBadges_1c4y1_127",Oz="_badge_1c4y1_134",Bz="_blockedBadge_1c4y1_146",Lz="_childBadge_1c4y1_151",zz="_depBadge_1c4y1_155",$z="_parentBadge_1c4y1_159",Pz="_pausedSubBadge_1c4y1_166",Uz="_personaBadge_1c4y1_170",Hz="_envBadge_1c4y1_174",Vz="_emptyCta_1c4y1_178",qz="_ctaButton_1c4y1_188",Gz="_ctaDescription_1c4y1_204",lt={boardContainer:kz,column:Sz,columnHeader:jz,columnIcon:Tz,columnLabel:wz,columnCount:Nz,cardList:Cz,emptyPlaceholder:Ez,card:Az,cardHeader:Dz,cardStatusIcon:Rz,cardTitle:Mz,cardBadges:Iz,badge:Oz,blockedBadge:Bz,childBadge:Lz,depBadge:zz,parentBadge:$z,pausedSubBadge:Pz,personaBadge:Uz,envBadge:Hz,emptyCta:Vz,ctaButton:qz,ctaDescription:Gz};function Fz({workspaceId:t,environmentId:s,tasks:o,sessions:r,personas:c,environments:d}){const u=ct(),p=y.useMemo(()=>o.filter(b=>b.workspaceId===t),[o,t]),m=y.useMemo(()=>new Map(o.map(b=>[b.id,b.status])),[o]),g=y.useMemo(()=>new Map(p.map(b=>[b.id,b])),[p]),v=y.useMemo(()=>{const b=new Map(r.map(C=>[C.id,C])),x=new Map(c.map(C=>[C.id,C])),S=new Map(d.map(C=>[C.id,C])),j=new Map,w=new Map,T=new Map;for(const C of p)if(C.latestSessionId){const D=b.get(C.latestSessionId);if(D){if(j.set(C.id,D.endReason||D.status),D.personaId){const O=x.get(D.personaId);O&&w.set(C.id,O.name)}if(D.environmentId){const O=S.get(D.environmentId);O&&T.set(C.id,O.displayName)}}}return{sessionStatusByTaskId:j,personaNameByTaskId:w,environmentNameByTaskId:T}},[p,r,c,d]),_=y.useMemo(()=>xz({tasks:p,taskStatusById:m,sessionStatusByTaskId:v.sessionStatusByTaskId}),[p,m,v]);return p.length===0?a.jsxs("div",{className:lt.emptyCta,"data-testid":"board-empty-cta",children:[a.jsx("button",{className:lt.ctaButton,onClick:()=>u(zi(t,void 0,s)),children:"Create Task"}),a.jsx("div",{className:lt.ctaDescription,children:"Break your work into tasks and let agents tackle them"})]}):a.jsx("div",{className:lt.boardContainer,"data-testid":"board-container",children:_.map(b=>a.jsxs("section",{className:lt.column,"data-testid":`board-column-${b.status}`,"aria-label":`${b.label}, ${b.tasks.length} ${b.tasks.length===1?"task":"tasks"}`,children:[a.jsxs("div",{className:lt.columnHeader,children:[a.jsx("span",{className:lt.columnIcon,style:{color:b.style.color},children:b.style.icon}),a.jsx("span",{className:lt.columnLabel,children:b.label}),a.jsx("span",{className:lt.columnCount,"data-testid":`board-count-${b.status}`,children:b.tasks.length})]}),a.jsx("div",{className:lt.cardList,children:b.tasks.length===0?a.jsx("div",{className:lt.emptyPlaceholder,children:"No tasks"}):a.jsx(ls,{mode:"popLayout",children:b.tasks.map(x=>a.jsx(Nt.div,{layout:!0,initial:{opacity:0,y:4},animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.15},children:a.jsx(Zz,{boardTask:x,tasksById:g,personaName:v.personaNameByTaskId.get(x.task.id),envName:v.environmentNameByTaskId.get(x.task.id),onClick:()=>u($n(x.task.id,void 0,t,s))})},x.task.id))})})]},b.status))})}function Zz({boardTask:t,tasksById:s,personaName:o,envName:r,onClick:c}){const{task:d,isBlocked:u,childCount:p,doneChildCount:m,pausedSubBadge:g}=t,v=Ja(d.status),_=d.parentTaskId?s.get(d.parentTaskId):void 0;return a.jsxs("div",{className:lt.card,tabIndex:0,role:"button","data-testid":`board-card-${d.id}`,onClick:c,onKeyDown:b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),c())},children:[a.jsxs("div",{className:lt.cardHeader,children:[a.jsx("span",{className:lt.cardStatusIcon,style:{color:v.color},children:v.icon}),a.jsx("span",{className:lt.cardTitle,children:d.title})]}),a.jsxs("div",{className:lt.cardBadges,children:[_&&a.jsx("span",{className:`${lt.badge} ${lt.parentBadge}`,title:_.title,children:_.title}),p>0&&a.jsxs("span",{className:`${lt.badge} ${lt.childBadge}`,children:[m,"/",p]}),u&&a.jsx("span",{className:`${lt.badge} ${lt.blockedBadge}`,children:"blocked"}),d.dependsOn.length>0&&!u&&a.jsx("span",{className:`${lt.badge} ${lt.depBadge}`,children:"dep"}),g&&a.jsx("span",{className:`${lt.badge} ${lt.pausedSubBadge}`,children:g}),o&&a.jsx("span",{className:`${lt.badge} ${lt.personaBadge}`,children:o}),r&&a.jsx("span",{className:`${lt.badge} ${lt.envBadge}`,children:r})]})]})}const Kz="_formContent_ymnez_1",Yz="_section_ymnez_13",Jz="_label_ymnez_19",Wz="_titleInput_ymnez_26",Xz="_descriptionTextarea_ymnez_58",Qz="_selectField_ymnez_94",e$="_checkboxRow_ymnez_128",t$="_checkboxLabel_ymnez_141",n$="_fieldError_ymnez_146",xt={formContent:Kz,section:Yz,label:Jz,titleInput:Wz,descriptionTextarea:Xz,selectField:Qz,checkboxRow:e$,checkboxLabel:t$,fieldError:n$};function s$(t,s){return{name:(t==null?void 0:t.name)??"",description:(t==null?void 0:t.description)??"",repoUrl:(t==null?void 0:t.repoUrl)??"",environmentId:(t==null?void 0:t.linkedEnvironmentIds[0])??s??"",defaultPersonaId:(t==null?void 0:t.defaultPersonaId)??"",useWorktrees:(t==null?void 0:t.useWorktrees)??!0,workingDirectory:(t==null?void 0:t.workingDirectory)??""}}const a$=100;function i$({values:t,onChange:s,environments:o,personas:r,errors:c,disabled:d,autoFocusName:u}){const p=(m,g)=>{s({...t,[m]:g})};return a.jsxs("div",{className:xt.formContent,children:[a.jsxs("div",{className:xt.section,children:[a.jsx("label",{className:xt.label,htmlFor:"ws-name",children:"Name"}),a.jsx("input",{id:"ws-name",className:xt.titleInput,type:"text",value:t.name,onChange:m=>p("name",m.target.value),placeholder:"Workspace name",maxLength:a$,autoFocus:u,disabled:d,"data-testid":"workspace-form-name"}),(c==null?void 0:c.name)&&a.jsx("span",{className:xt.fieldError,"data-testid":"workspace-form-error-name",children:c.name})]}),a.jsxs("div",{className:xt.section,children:[a.jsx("label",{className:xt.label,htmlFor:"ws-description",children:"Description"}),a.jsx("textarea",{id:"ws-description",className:xt.descriptionTextarea,value:t.description,onChange:m=>p("description",m.target.value),placeholder:"Optional description (Markdown supported)",disabled:d,"data-testid":"workspace-form-description"})]}),a.jsxs("div",{className:xt.section,children:[a.jsx("label",{className:xt.label,htmlFor:"ws-repo",children:"Repository URL"}),a.jsx("input",{id:"ws-repo",className:xt.titleInput,type:"text",value:t.repoUrl,onChange:m=>p("repoUrl",m.target.value),placeholder:"https://github.com/org/repo",disabled:d,"data-testid":"workspace-form-repo"}),(c==null?void 0:c.repoUrl)&&a.jsx("span",{className:xt.fieldError,"data-testid":"workspace-form-error-repoUrl",children:c.repoUrl})]}),a.jsxs("div",{className:xt.section,children:[a.jsx("label",{className:xt.label,htmlFor:"ws-environment",children:"Environment"}),a.jsxs("select",{id:"ws-environment",className:xt.selectField,value:t.environmentId,onChange:m=>p("environmentId",m.target.value),disabled:d,"data-testid":"workspace-form-environment",children:[a.jsx("option",{value:"",children:"Select environment…"}),o.map(m=>a.jsx("option",{value:m.id,children:m.displayName||m.id},m.id))]}),(c==null?void 0:c.environmentId)&&a.jsx("span",{className:xt.fieldError,"data-testid":"workspace-form-error-environmentId",children:c.environmentId})]}),a.jsxs("div",{className:xt.section,children:[a.jsx("label",{className:xt.label,htmlFor:"ws-persona",children:"Default Persona"}),a.jsxs("select",{id:"ws-persona",className:xt.selectField,value:t.defaultPersonaId,onChange:m=>p("defaultPersonaId",m.target.value),disabled:d,"data-testid":"workspace-form-persona",children:[a.jsx("option",{value:"",children:"(Inherit)"}),r.map(m=>a.jsx("option",{value:m.id,children:m.name},m.id))]})]}),a.jsx("div",{className:xt.section,children:a.jsxs("label",{className:xt.checkboxRow,children:[a.jsx("input",{type:"checkbox",checked:t.useWorktrees,onChange:m=>p("useWorktrees",m.target.checked),disabled:d,"data-testid":"workspace-form-worktrees"}),a.jsx("span",{className:xt.checkboxLabel,children:"Enable worktree isolation"})]})}),a.jsxs("div",{className:xt.section,children:[a.jsx("label",{className:xt.label,htmlFor:"ws-workdir",children:"Working Directory"}),a.jsx("input",{id:"ws-workdir",className:xt.titleInput,type:"text",value:t.workingDirectory,onChange:m=>p("workingDirectory",m.target.value),placeholder:"Default (server default)",disabled:d,"data-testid":"workspace-form-workdir"})]})]})}const Q1=y.createContext(void 0),o$=4e3;function r$({children:t}){const[s,o]=y.useState([]),r=y.useRef(0),c=y.useCallback(u=>{o(p=>p.filter(m=>m.id!==u))},[]),d=y.useCallback((u,p="info",m=o$)=>{const g=`toast-${++r.current}`;o(v=>[...v,{id:g,message:u,variant:p,duration:m}])},[]);return a.jsx(Q1.Provider,{value:{toasts:s,showToast:d,dismissToast:c},children:t})}function gn(){const t=y.useContext(Q1);if(!t)throw new Error("useToast must be used within ToastProvider");return t}const _m="grackle-theme",ek="grackle-prefer-system",tk="(prefers-color-scheme: dark)";let Xr=[],fd;function $p(){fd=void 0;for(const t of Xr)t()}function xm(){return typeof window>"u"?!1:window.matchMedia(tk).matches}function il(){if(typeof localStorage>"u")return o_;try{const t=localStorage.getItem(_m);if(t!==null&&J1.has(t))return t}catch{}return o_}function Nd(){if(typeof localStorage>"u")return!1;try{return localStorage.getItem(ek)==="true"}catch{return!1}}function km(t){return Gd.find(s=>s.variantLightId===t||s.variantDarkId===t)}function nk(t,s){const o=bm(t);if(o!=null&&o.variantDarkId)return s&&o.variantLightId?xm()?o.variantDarkId:o.variantLightId:o.variantDarkId;if(o!=null&&o.hidden&&s){const r=km(t);if(r!=null&&r.variantLightId&&r.variantDarkId)return xm()?r.variantDarkId:r.variantLightId}return t}function Do(t,s,o=!1){o&&document.documentElement.classList.add("no-transitions"),document.documentElement.dataset.theme=nk(t,s),o&&(document.documentElement.offsetHeight,requestAnimationFrame(()=>{document.documentElement.classList.remove("no-transitions")}))}typeof document<"u"&&Do(il(),Nd());function l$(){return fd===void 0&&(fd={themeId:il(),systemDark:xm(),preferSystem:Nd()}),fd}function c$(t){return Xr=[...Xr,t],()=>{Xr=Xr.filter(s=>s!==t)}}function d$(){const t=y.useSyncExternalStore(c$,l$),{themeId:s,preferSystem:o}=t,r=nk(s,o),c=y.useCallback(u=>{if(J1.has(u)){try{localStorage.setItem(_m,u)}catch{}Do(u,Nd(),!0),$p()}},[]),d=y.useCallback(u=>{try{localStorage.setItem(ek,u?"true":"false")}catch{}if(u){const p=il(),m=bm(p);if(m!=null&&m.hidden){const g=km(p);if(g)try{localStorage.setItem(_m,g.id)}catch{}}}Do(il(),u,!0),$p()},[]);return y.useEffect(()=>{Do(s,o)},[s,o]),y.useEffect(()=>{if(typeof window>"u")return;const u=window.matchMedia(tk),p=()=>{const m=il(),g=Nd();if(g){const v=bm(m);if(v!=null&&v.variantDarkId&&v.variantLightId&&Do(m,g),v!=null&&v.hidden){const _=km(m);_!=null&&_.variantDarkId&&_.variantLightId&&Do(m,g)}}$p()};return u.addEventListener("change",p),()=>{u.removeEventListener("change",p)}},[]),{themeId:s,setTheme:c,resolvedThemeId:r,preferSystem:o,setPreferSystem:d}}const sk=y.createContext(void 0);function u$({children:t}){const s=d$();return a.jsx(sk.Provider,{value:s,children:t})}function ak(){const t=y.useContext(sk);if(!t)throw new Error("useThemeContext must be used within ThemeProvider");return t}const ik=y.createContext(void 0),ok=y.createContext(void 0);function f$({children:t}){const[s,o]=y.useState(void 0),r=y.useCallback(c=>{o(c)},[]);return a.jsx(ok.Provider,{value:r,children:a.jsx(ik.Provider,{value:s,children:t})})}function p$(){return y.useContext(ik)}function m$(){const t=y.useContext(ok);if(t===void 0)throw new Error("useSidebarSetter must be used within a SidebarProvider");return t}const vh=y.createContext(void 0);function rt(){const t=y.useContext(vh);if(!t)throw new Error("useGrackle must be used within GrackleProvider");return t}function rk(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function lk(t,s){return console.warn(`[ws] Malformed "${t}" message: ${s}`),!1}function h$(t){return rk(t)&&typeof t.sessionId=="string"&&typeof t.eventType=="string"&&typeof t.timestamp=="string"&&typeof t.content=="string"&&(t.raw===void 0||typeof t.raw=="string")}const g$=new Set(["off","subscription","api_key"]),Xc=new Set(["off","on"]);function v$(t){return rk(t)&&g$.has(t.claude)&&Xc.has(t.github)&&Xc.has(t.copilot)&&Xc.has(t.codex)&&Xc.has(t.goose)}function ck(t){switch(t){case"waiting_input":return"idle";case"completed":return"stopped";case"killed":return"stopped";case"failed":return"stopped";case"interrupted":return"stopped";case"terminated":return"stopped";default:return t}}function dk(t){switch(t){case"completed":return"completed";case"killed":return"killed";case"failed":return"interrupted";case"interrupted":return"interrupted";case"terminated":return"terminated";default:return}}const Ao=5e3;function y$(t,s){const o=[];let r=t;const c=new Set;for(;r&&s.has(r)&&!c.has(r);){c.add(r);const d=s.get(r);o.unshift(d),r=d.parentTaskId||void 0}return o}const ua={label:"Home",url:Ii};function b$(t){return t?[ua,{label:"Settings",url:Ei},{label:t,url:void 0}]:[ua,{label:"Settings",url:void 0}]}const yh={label:"Environments",url:Lo};function _$(){return[ua,{label:"Environments",url:void 0}]}function x$(){return[ua,{label:"New Chat",url:void 0}]}function k$(t){return[ua,{label:`Session ${t.slice(0,8)}`,url:void 0}]}function S$(t,s,o,r){const c=o.find(u=>u.id===t),d=r.find(u=>u.id===s);return[ua,yh,{label:(d==null?void 0:d.displayName)??"Environment",url:Mi(s)},{label:(c==null?void 0:c.name)??"Workspace",url:void 0}]}function j$(t,s,o,r,c){const d=y$(t,c),u=c.get(t),p=u==null?void 0:u.workspaceId,m=p?o.find(x=>x.id===p):void 0,g=s??(m==null?void 0:m.linkedEnvironmentIds[0]),v=g?r.find(x=>x.id===g):void 0,_=[ua];v&&g&&(_.push(yh),_.push({label:v.displayName,url:Mi(g)})),m&&g&&_.push({label:m.name,url:Ri(m.id,g)});for(let x=0;x<d.length-1;x++)_.push({label:d[x].title,url:$n(d[x].id,void 0,p,g)});const b=d[d.length-1];return _.push({label:(b==null?void 0:b.title)??t,url:void 0}),_}const T$={label:"Findings",url:zd};function w$(){return[ua,{label:"Findings",url:void 0}]}function uk(t,s,o,r,c){const d=[ua];if(s&&o){const u=r.find(m=>m.id===s),p=c.find(m=>m.id===o);d.push(yh),p&&d.push({label:p.displayName,url:Mi(o)}),u&&d.push({label:u.name,url:Ri(s,o)}),d.push({label:"Findings",url:HN(s,o)})}else d.push(T$);return d.push({label:t,url:void 0}),d}function bh(t){const s=[];for(const o of t){const r=s[s.length-1];o.eventType==="text"&&(r==null?void 0:r.eventType)==="text"?s[s.length-1]={...r,content:r.content+o.content}:s.push(o)}return s}function Qc(t){if(typeof t.id=="string")return t.id;const s=t.data;if(s&&typeof s.toolCallId=="string")return s.toolCallId;const o=t.item;if(o&&typeof o.id=="string")return o.id}function N$(t){if(typeof t.tool_use_id=="string")return t.tool_use_id;const s=t.data;if(s&&typeof s.toolCallId=="string")return s.toolCallId;const o=t.item;if(o&&typeof o.id=="string")return o.id}function _h(t){const s=new Map;for(const v of t)if(v.raw)try{s.set(v,JSON.parse(v.raw))}catch{}const o=new Map;for(const v of t){if(v.eventType!=="tool_use")continue;const _=s.get(v),b=_?Qc(_):void 0;if(b)try{const x=JSON.parse(v.content);o.set(b,{tool:x.tool,args:x.args})}catch{}}const r=new Set,c=new Set,d=t.map((v,_)=>{if(v.eventType!=="tool_result")return v;const b=s.get(v),x=b?N$(b):void 0;if(!x)return v;const S=o.get(x);if(!S)return v;r.add(x),c.add(_);let j;const w=v.content.trim();if(w.startsWith("{"))try{const T=JSON.parse(w);typeof T.detailedContent=="string"&&(j=T.detailedContent)}catch{}return{...v,toolUseCtx:{...S,detailedResult:j}}}),u=[];for(let v=0;v<d.length;v++){if(d[v].eventType!=="tool_use")continue;const _=s.get(d[v]),b=_?Qc(_):void 0;b&&r.has(b)||u.push(v)}const p=[];for(let v=0;v<d.length;v++)d[v].eventType!=="tool_result"||c.has(v)||p.push(v);let m=0;for(const v of u){for(;m<p.length&&p[m]<v;)m++;if(m>=p.length)break;const _=p[m];if(_!==v+1)continue;const b=d[v],x=d[_];let S;try{const j=JSON.parse(b.content);S={tool:j.tool,args:j.args}}catch{}if(S){let j;const w=x.content.trim();if(w.startsWith("{"))try{const D=JSON.parse(w);typeof D.detailedContent=="string"&&(j=D.detailedContent)}catch{}d[_]={...x,toolUseCtx:{...S,detailedResult:j}},c.add(_);const T=s.get(b),C=T?Qc(T):void 0;C?r.add(C):(r.add(`__seq_${v}`),s.set(b,{...T??{},__seqId:`__seq_${v}`})),m++}}const g=d.filter(v=>{if(v.eventType!=="tool_use")return!0;const _=s.get(v);if(!_)return!0;const b=Qc(_);if(b&&r.has(b))return!1;const x=_.__seqId;return!(x&&r.has(x))});for(let v=0;v<g.length;v++){if(g[v].eventType!=="tool_use")continue;let _=!1;for(let b=v+1;b<g.length;b++)if(g[b].eventType!=="tool_use"){_=!0;break}_&&(g[v]={...g[v],settled:!0})}return g}function C$(t,s,o){const r=t.filter(m=>m.status==="running"||m.status==="idle"||m.status==="waiting").length,c=fk(s),d=s.filter(m=>Sm(m,c)).length,u=s.filter(m=>m.status==="paused"||m.status==="failed"||Sm(m,c)).length,p=o.filter(m=>m.status==="disconnected"||m.status==="error").length;return{activeSessions:r,blockedTasks:d,attentionTasks:u,unhealthyEnvironments:p}}function fk(t){const s=new Map;for(const o of t)s.set(o.id,o.status);return s}function Sm(t,s){return t.dependsOn.some(o=>s.get(o)!=="complete")}function E$(t,s){var u;const o=new Map;for(const p of s)o.set(p.id,p);const r=fk(t),c=[];for(const p of t){const m=p.workspaceId?((u=o.get(p.workspaceId))==null?void 0:u.name)??"Unknown":"Unknown";p.status==="failed"?c.push({task:p,reason:"failed",workspaceName:m}):Sm(p,r)?c.push({task:p,reason:"blocked",workspaceName:m}):p.status==="paused"&&c.push({task:p,reason:"paused",workspaceName:m})}const d={failed:0,blocked:1,paused:2};return c.sort((p,m)=>(d[p.reason]??3)-(d[m.reason]??3)),c}function A$(t,s){const o=new Map;for(const r of s)o.set(r.id,r);return t.filter(r=>r.status==="running"||r.status==="idle"||r.status==="waiting").map(r=>{var c;return{session:r,environmentName:((c=o.get(r.environmentId))==null?void 0:c.displayName)??"Unknown"}})}function D$(t,s,o){const r=new Map;for(const c of s){if(!c.workspaceId)continue;let d=r.get(c.workspaceId);d||(d={totalTasks:0,completedTasks:0,workingTasks:0,failedTasks:0},r.set(c.workspaceId,d)),d.totalTasks+=1,c.status==="complete"?d.completedTasks+=1:c.status==="working"?d.workingTasks+=1:c.status==="failed"&&(d.failedTasks+=1)}return t.map(c=>{const d=r.get(c.id)??{totalTasks:0,completedTasks:0,workingTasks:0,failedTasks:0};return{workspace:c,totalTasks:d.totalTasks,completedTasks:d.completedTasks,workingTasks:d.workingTasks,failedTasks:d.failedTasks}})}const Ds=[{id:"kn-auth-flow",label:"Authentication Flow",kind:"knowledge",category:"concept",content:"The application uses JWT Bearer tokens for stateless authentication. Access tokens expire after 24h. Refresh tokens are stored in the database and rotated on use. The auth middleware verifies tokens and attaches the decoded payload to req.user.",tags:["auth","jwt","security"],workspaceId:"proj-alpha",createdAt:"2026-02-25T10:30:00Z",updatedAt:"2026-02-27T08:15:00Z",val:5},{id:"kn-db-schema",label:"Database Schema",kind:"knowledge",category:"concept",content:"PostgreSQL database with tables: users, sessions, refresh_tokens, audit_log. Uses UUID primary keys, TIMESTAMPTZ for all timestamps, and JSONB for flexible metadata columns. Connection pooling via pg-pool with per-tenant isolation.",tags:["database","postgres","schema"],workspaceId:"proj-alpha",createdAt:"2026-02-23T11:00:00Z",updatedAt:"2026-02-26T22:45:00Z",val:4},{id:"kn-error-handling",label:"Error Response Pattern",kind:"knowledge",category:"concept",content:"All API errors follow the shape { error: string, code: string, details?: unknown }. HTTP status codes map to: 400 (validation), 401 (unauthenticated), 403 (forbidden), 404 (not found), 409 (conflict), 429 (rate limited), 500 (internal).",tags:["api","errors","patterns"],workspaceId:"proj-alpha",createdAt:"2026-02-27T08:17:00Z",updatedAt:"2026-02-27T08:17:00Z",val:3},{id:"kn-rate-limiting",label:"Rate Limiting Strategy",kind:"knowledge",category:"concept",content:"Token-bucket algorithm with in-memory state per client IP. Default rate: 100 requests/minute, burst: 20. Returns 429 with Retry-After header. Redis adapter available for multi-instance deployments.",tags:["api","rate-limiting","infrastructure"],workspaceId:"proj-alpha",createdAt:"2026-02-27T09:00:00Z",updatedAt:"2026-02-27T09:00:00Z",val:2},{id:"kn-etl-pipeline",label:"ETL Pipeline Architecture",kind:"knowledge",category:"concept",content:"Data pipelines follow an Extract-Transform-Load pattern with pluggable stages. Each stage reads from a source (Postgres, S3, API), transforms via configurable mappers, and loads into a target (Parquet, BigQuery, S3). Incremental loads use high-watermark tracking.",tags:["etl","pipeline","architecture"],workspaceId:"proj-beta",createdAt:"2026-02-26T08:00:00Z",updatedAt:"2026-02-27T09:05:00Z",val:4},{id:"kn-parquet-format",label:"Parquet Output Format",kind:"knowledge",category:"concept",content:"Parquet files are written with row-group buffering (configurable batch size, default 10000 rows). Supports Snappy, ZSTD, and GZIP compression. Schema is derived from the internal column type system using Arrow type mapping.",tags:["parquet","data-format","compression"],workspaceId:"proj-beta",createdAt:"2026-02-26T08:05:00Z",updatedAt:"2026-02-26T08:15:00Z",val:3},{id:"kn-jwt-over-session",label:"JWT over Session Auth",kind:"knowledge",category:"decision",content:"Chose JWT tokens over server-side sessions for stateless auth. Rationale: (1) no session store needed, (2) works across microservices without shared state, (3) supports mobile clients natively. Trade-off: tokens can't be revoked instantly (mitigated by short expiry + refresh rotation).",tags:["auth","decision","jwt"],workspaceId:"proj-alpha",createdAt:"2026-02-25T10:00:00Z",updatedAt:"2026-02-25T10:00:00Z",val:3},{id:"kn-pg-pool-decision",label:"pg-pool over Knex",kind:"knowledge",category:"decision",content:"Chose pg-pool over Knex for connection pooling. pg-pool gives direct control over idle timeout, max connections, and health check queries. Knex wraps pg-pool and adds query-building overhead we don't need since we write raw SQL with parameterized queries.",tags:["database","decision","postgres"],workspaceId:"proj-alpha",createdAt:"2026-02-23T11:30:00Z",updatedAt:"2026-02-23T11:30:00Z",val:2},{id:"kn-watermark-decision",label:"Local Watermark Storage",kind:"knowledge",category:"decision",content:"Currently using local SQLite for watermark storage. This works for single-worker pipelines but needs to move to a shared store (Redis or Postgres) for production multi-worker scenarios. Tracked as a follow-up task.",tags:["pipeline","decision","watermarks"],workspaceId:"proj-beta",createdAt:"2026-02-27T09:05:00Z",updatedAt:"2026-02-27T09:05:00Z",val:2},{id:"kn-jwt-middleware",label:"JWT Verify Middleware",kind:"knowledge",category:"snippet",content:`\`\`\`typescript
303
+ --- End forwarded ---`}function aI(t){return t.replace(/[\r\n]+/g," ").trim().replace(/---/g,"—")}function iI({events:t,formatForClipboard:s}){const[o,r]=y.useState(!1),[c,d]=y.useState(new Set),u=y.useRef(void 0),p=y.useMemo(()=>c.size,[c]),m=y.useCallback(S=>{r(!0),S!==void 0?(d(new Set([S])),u.current=S):(d(new Set),u.current=void 0)},[]),g=y.useCallback(()=>{r(!1),d(new Set),u.current=void 0},[]),v=y.useCallback((S,j)=>{if(j&&u.current!==void 0){const w=Math.min(u.current,S),T=Math.max(u.current,S);d(C=>{const D=new Set(C);for(let O=w;O<=T;O++)O<t.length&&gl(t[O])&&D.add(O);return D})}else d(w=>{const T=new Set(w);return T.has(S)?T.delete(S):T.add(S),T.size===0?(r(!1),u.current=void 0):u.current=S,T})},[t]),_=y.useCallback(()=>{const S=new Set;for(let j=0;j<t.length;j++)gl(t[j])&&S.add(j);d(S)},[t]),b=y.useCallback(()=>{d(new Set)},[]),x=y.useCallback(async()=>{const j=[...c].sort((T,C)=>T-C).filter(T=>T<t.length).map(T=>t[T]);if(j.length===0)return!1;const w=s(j);try{return await navigator.clipboard.writeText(w),!0}catch{return!1}},[c,t,s]);return{isSelecting:o,selectedIndices:c,selectedCount:p,enterSelectionMode:m,cancelSelection:g,toggleEvent:v,selectAll:_,deselectAll:b,copySelected:x}}const oI="_wrapper_1cdza_1",rI="_scrollContainer_1cdza_9",lI="_selectingPadding_1cdza_16",cI="_toolbar_1cdza_20",dI="_directionToggle_1cdza_27",uI="_scrollToAnchor_1cdza_65",fI="_scrollToAnchorBottom_1cdza_89",pI="_scrollToAnchorTop_1cdza_93",mI="_eventOverflowWarning_1cdza_97",ia={wrapper:oI,scrollContainer:rI,selectingPadding:lI,toolbar:cI,directionToggle:dI,scrollToAnchor:uI,scrollToAnchorBottom:fI,scrollToAnchorTop:pI,eventOverflowWarning:mI},hI=10*1024,gI=new Set(["running","idle"]);function vI(t){const s=new Date(t.timestamp).toLocaleTimeString();switch(t.eventType){case"text":case"output":return`Select message from assistant at ${s}`;case"user_input":return`Select message from user at ${s}`;case"tool_result":case"tool_use":return`Select tool event at ${s}`;case"error":return`Select error at ${s}`;default:return`Select event at ${s}`}}const P1="grackle-stream-direction";function yI(){try{return localStorage.getItem(P1)==="reversed"}catch{return!1}}function bI({eventsDropped:t}){return t<=0?a.jsx(a.Fragment,{}):a.jsxs("div",{className:ia.eventOverflowWarning,role:"alert",children:[a.jsx(wm,{size:Qt,"aria-hidden":"true"})," ",t.toLocaleString()," older event",t===1?"":"s"," were dropped — only the most recent 5,000 are shown. Full history is available in the session log."]})}function al({events:t,eventsDropped:s,emptyState:o,onShowToast:r,sessions:c,currentSessionId:d,environments:u,personas:p,onForward:m}){const g=y.useRef(null),[v,_]=y.useState(yI),b=D3(),[x,S]=y.useState(!1),[j,w]=y.useState(!1),[T,C]=y.useState(void 0),D=iI({events:t,formatForClipboard:$1}),O=y.useMemo(()=>t.filter(gl).length,[t]),A=y.useMemo(()=>c?c.filter(q=>gI.has(q.status)&&q.id!==d):[],[c,d]),I=y.useMemo(()=>v?[...t].reverse():t,[t,v]),{isAtAnchor:$,scrollToAnchor:B}=eI({scrollRef:g,contentLength:t.length,isReversed:v,paused:D.isSelecting}),P=()=>{const q=!v;_(q);try{localStorage.setItem(P1,q?"reversed":"default")}catch{}};y.useEffect(()=>{if(!D.isSelecting)return;const q=de=>{de.key==="Escape"&&!x&&!j&&D.cancelSelection()};return window.addEventListener("keydown",q),()=>{window.removeEventListener("keydown",q)}},[D.isSelecting,D.cancelSelection,x,j]);const X=y.useCallback(async()=>{await D.copySelected()&&(r==null||r(`Copied ${D.selectedCount} message${D.selectedCount===1?"":"s"} to clipboard`,"success"))},[D,r]),H=y.useCallback(()=>[...D.selectedIndices].sort((de,re)=>de-re).filter(de=>de<t.length).map(de=>t[de]),[D.selectedIndices,t]),Q=y.useCallback(q=>{if(!q)return"this session";const de=c==null?void 0:c.find(xe=>xe.id===q);if(!de)return q.slice(0,8);const re=u==null?void 0:u.find(xe=>xe.id===de.environmentId);return(re==null?void 0:re.displayName)??de.environmentId.slice(0,8)},[c,u]),he=y.useCallback(async(q,de)=>{if(!m)return;const re=Q(q);try{await m(q,de);const xe=D.selectedCount;r==null||r(`Forwarded ${xe} message${xe===1?"":"s"} to ${re}`,"success"),D.cancelSelection()}catch{r==null||r("Failed to forward messages","error")}},[m,Q,r,D]),W=y.useCallback(q=>{S(!1);const de=H(),re=Q(d),xe=sI(re,de);if(new TextEncoder().encode(xe).length>hI){C({sessionId:q,text:xe}),w(!0);return}he(q,xe).catch(()=>{})},[H,Q,d,he]),ie=y.useCallback(()=>{w(!1),T&&(he(T.sessionId,T.text).catch(()=>{}),C(void 0))},[T,he]),L=y.useCallback(()=>{w(!1),C(void 0)},[]),E=b?0:.2,J=v?-8:8,me=T?Math.round(new TextEncoder().encode(T.text).length/1024):0;return a.jsxs("div",{className:ia.wrapper,children:[a.jsx("div",{className:ia.toolbar,children:a.jsx(Oi,{text:v?"Showing newest first":"Showing oldest first",children:a.jsx("button",{className:ia.directionToggle,onClick:P,"aria-label":v?"Switch to newest at bottom":"Switch to newest at top","data-testid":"direction-toggle",children:v?a.jsx(Sy,{size:Qt,"aria-hidden":"true"}):a.jsx(jy,{size:Qt,"aria-hidden":"true"})})})}),a.jsxs("div",{ref:g,className:`${ia.scrollContainer} ${D.isSelecting?ia.selectingPadding:""}`,"data-testid":"event-stream-scroll",children:[t.length===0&&o,a.jsx(bI,{eventsDropped:s}),a.jsx(ls,{initial:!1,children:I.map((q,de)=>{const re=v?t.length-1-de:de;return a.jsx(Nt.div,{initial:{opacity:0,y:J},animate:{opacity:1,y:0},transition:{duration:E,ease:"easeOut"},children:a.jsx(_6,{copyText:nI(q),isContentBearing:gl(q),isSelecting:D.isSelecting,isSelected:D.selectedIndices.has(re),checkboxLabel:vI(q),onSelect:()=>{D.enterSelectionMode(re)},onToggle:xe=>{D.toggleEvent(re,xe)},onCopied:()=>{r==null||r("Copied to clipboard","success")},children:a.jsx(iD,{event:q,toolUseCtx:q.toolUseCtx,settled:q.settled})})},`${q.sessionId}-${q.timestamp}-${re}`)})})]}),a.jsx(ls,{children:D.isSelecting&&a.jsx(E6,{selectedCount:D.selectedCount,totalSelectable:O,onSelectAll:D.selectAll,onDeselectAll:D.deselectAll,onCopy:()=>{X().catch(()=>{})},onForward:m!==void 0?()=>{S(!0)}:void 0,forwardDisabled:A.length===0,onCancel:D.cancelSelection})}),a.jsx(W6,{isOpen:x,sessions:A,environments:u??[],personas:p,onSelect:W,onCancel:()=>{S(!1)}}),a.jsx(Ls,{isOpen:j,title:"Send large message?",description:`This will forward a large message (${me} KB). Continue?`,confirmLabel:"Send",onConfirm:ie,onCancel:L}),a.jsx(ls,{children:!$&&a.jsxs(Nt.button,{className:`${ia.scrollToAnchor} ${v?ia.scrollToAnchorTop:ia.scrollToAnchorBottom}`,onClick:B,initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.9},transition:{duration:.15},"aria-label":"Scroll to latest","data-testid":"scroll-to-anchor",children:[v?a.jsx(jy,{size:Qt,"aria-hidden":"true"}):a.jsx(Sy,{size:Qt,"aria-hidden":"true"})," New events"]})})]})}function gh(t){const{value:s,onSave:o,validate:r,fieldId:c,activeFieldId:d,onActivate:u,enterToSave:p=!0,trimOnSave:m=!0}=t,[g,v]=y.useState(""),[_,b]=y.useState(""),x=y.useRef(!1),S=d===c,j=y.useCallback($=>{v($),b("")},[]),w=y.useCallback(()=>{b("")},[]),T=y.useCallback(()=>{x.current=!1,u==null||u(null),v(""),b("")},[u]),C=y.useCallback(()=>{const $=m?g.trim():g;if(r){const P=r(g);if(P){b(P);return}}const B=m?s.trim():s;if($===B){T();return}o($),T()},[g,s,m,r,o,T]),D=y.useCallback(()=>{x.current=!0,u==null||u(c),v(s),b("")},[c,s,u]),O=y.useCallback($=>{if(x.current){x.current=!1;return}$.relatedTarget instanceof HTMLElement&&$.relatedTarget.dataset.editAction===c||C()},[c,C]),A=y.useCallback($=>{$.key==="Escape"?T():$.key==="Enter"&&p&&C()},[T,p,C]),I=(()=>{if(!S)return!1;const $=m?s.trim():s;return(m?g.trim():g)!==$})();return y.useEffect(()=>{!S&&(g!==""||_!=="")&&(v(""),b(""))},[S,g,_]),{isEditing:S,draft:g,error:_,isDirty:I,startEdit:D,cancelEdit:T,save:C,setDraft:j,clearError:w,handleBlur:O,handleKeyDown:A,ignoreInitialBlurRef:x}}const _I="_editFieldWrapper_yuzty_1",xI="_editInput_yuzty_10",kI="_editTextarea_yuzty_42",SI="_editSelect_yuzty_78",jI="_editError_yuzty_111",TI="_editInputInvalid_yuzty_118",wI="_editHint_yuzty_123",NI="_unsavedDot_yuzty_132",CI="_metaValueClickable_yuzty_140",EI="_editButton_yuzty_159",AI="_metaPlaceholder_yuzty_175",DI="_worktreeToggle_yuzty_180",st={editFieldWrapper:_I,editInput:xI,editTextarea:kI,editSelect:SI,editError:jI,editInputInvalid:TI,editHint:wI,unsavedDot:NI,metaValueClickable:CI,editButton:EI,metaPlaceholder:AI,worktreeToggle:DI};function Zt(t){const{value:s,onSave:o,validate:r,mode:c="edit",fieldId:d="text",activeFieldId:u,onActivate:p,onChange:m,renderDisplay:g,placeholder:v,maxLength:_,ariaLabel:b,"data-testid":x}=t,S=y.useRef(null),j=gh({value:s,onSave:o,validate:r,fieldId:d,activeFieldId:u,onActivate:p,enterToSave:!0,trimOnSave:!0});if(y.useEffect(()=>{if(j.isEditing){const T=window.setTimeout(()=>{var C;(C=S.current)==null||C.focus()},0);return()=>window.clearTimeout(T)}},[j.isEditing]),c==="create"){const T=D=>{m==null||m(D.target.value)},C=r==null?void 0:r(s);return a.jsxs("div",{className:st.editFieldWrapper,children:[a.jsx("input",{className:`${st.editInput} ${C?st.editInputInvalid:""}`,value:s,onChange:T,maxLength:_,placeholder:v,"aria-label":b,"data-testid":x?`${x}-input`:void 0}),C&&a.jsx("span",{className:st.editError,"data-testid":"edit-error",children:C})]})}if(j.isEditing)return a.jsxs("div",{className:st.editFieldWrapper,children:[a.jsx("input",{ref:S,className:`${st.editInput} ${j.error?st.editInputInvalid:""}`,value:j.draft,onChange:T=>j.setDraft(T.target.value),onBlur:j.handleBlur,onKeyDown:j.handleKeyDown,maxLength:_,placeholder:v,"aria-label":b,"data-testid":x?`${x}-input`:void 0}),j.isDirty&&a.jsx("span",{className:st.unsavedDot,title:"Unsaved changes"}),j.error&&a.jsx("span",{className:st.editError,"data-testid":"edit-error",children:j.error}),a.jsx("span",{className:st.editHint,children:"Enter to save · Esc to cancel"})]});const w=g==null?void 0:g(s);return a.jsxs("span",{role:"button",tabIndex:0,className:st.metaValueClickable,onClick:()=>j.startEdit(),onKeyDown:T=>{(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),j.startEdit())},title:"Click to edit","aria-label":b,"data-testid":x?`${x}-button`:void 0,children:[w!==void 0?w:s?a.jsx("span",{children:s}):a.jsx("span",{className:st.metaPlaceholder,children:v||"None"}),a.jsx("span",{className:st.editButton,"aria-hidden":"true",children:"✏️"})]})}function ym(t){const{value:s,onSave:o,validate:r,mode:c="edit",fieldId:d="textarea",activeFieldId:u,onActivate:p,onChange:m,renderDisplay:g,placeholder:v,ariaLabel:_,"data-testid":b}=t,x=y.useRef(null),S=gh({value:s,onSave:o,validate:r,fieldId:d,activeFieldId:u,onActivate:p,enterToSave:!1,trimOnSave:!1});if(y.useEffect(()=>{if(S.isEditing){const w=window.setTimeout(()=>{var T;(T=x.current)==null||T.focus()},0);return()=>window.clearTimeout(w)}},[S.isEditing]),c==="create"){const w=C=>{m==null||m(C.target.value)},T=r==null?void 0:r(s);return a.jsxs("div",{className:st.editFieldWrapper,children:[a.jsx("textarea",{className:`${st.editTextarea} ${T?st.editInputInvalid:""}`,value:s,onChange:w,placeholder:v,"aria-label":_,"data-testid":b?`${b}-input`:void 0}),T&&a.jsx("span",{className:st.editError,"data-testid":"edit-error",children:T})]})}if(S.isEditing)return a.jsxs("div",{className:st.editFieldWrapper,children:[a.jsx("textarea",{ref:x,className:`${st.editTextarea} ${S.error?st.editInputInvalid:""}`,value:S.draft,onChange:w=>S.setDraft(w.target.value),onBlur:S.handleBlur,onKeyDown:S.handleKeyDown,title:_,"aria-label":_,"data-testid":b?`${b}-input`:void 0}),S.isDirty&&a.jsx("span",{className:st.unsavedDot,title:"Unsaved changes"}),S.error&&a.jsx("span",{className:st.editError,"data-testid":"edit-error",children:S.error}),a.jsx("span",{className:st.editHint,children:"Tab to save · Esc to cancel"})]});const j=g==null?void 0:g(s);return a.jsxs("span",{role:"button",tabIndex:0,className:st.metaValueClickable,onClick:()=>S.startEdit(),onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),S.startEdit())},title:"Click to edit","aria-label":_,"data-testid":b?`${b}-button`:void 0,children:[j!==void 0?j:s?a.jsx("span",{children:s}):a.jsx("span",{className:st.metaPlaceholder,children:v||"None"}),a.jsx("span",{className:st.editButton,"aria-hidden":"true",children:"✏️"})]})}function Td(t){var D;const{value:s,onSave:o,mode:r="edit",options:c,fieldId:d="select",activeFieldId:u,onActivate:p,onChange:m,renderDisplay:g,placeholder:v,ariaLabel:_,"data-testid":b}=t,x=y.useRef(null),S=gh({value:s,onSave:o,fieldId:d,activeFieldId:u,onActivate:p,enterToSave:!1,trimOnSave:!1});y.useEffect(()=>{if(S.isEditing){const O=window.setTimeout(()=>{var A;(A=x.current)==null||A.focus()},0);return()=>window.clearTimeout(O)}},[S.isEditing]);const j=y.useCallback(O=>{const A=O.target.value;S.ignoreInitialBlurRef.current=!1,A!==s&&o(A),S.cancelEdit()},[s,o,S]),w=y.useCallback(O=>{if(S.ignoreInitialBlurRef.current){S.ignoreInitialBlurRef.current=!1;return}O.relatedTarget instanceof HTMLElement&&O.relatedTarget.dataset.editAction===d||S.cancelEdit()},[d,S]);if(r==="create")return a.jsx("select",{className:st.editSelect,value:s,onChange:O=>m==null?void 0:m(O.target.value),"aria-label":_,"data-testid":b?`${b}-select`:void 0,children:c.map(O=>a.jsx("option",{value:O.value,children:O.label},O.value))});if(S.isEditing)return a.jsx("select",{ref:x,className:st.editSelect,value:S.draft,onChange:j,onBlur:w,title:_,"aria-label":_,"data-testid":b?`${b}-select`:void 0,children:c.map(O=>a.jsx("option",{value:O.value,children:O.label},O.value))});const T=g==null?void 0:g(s),C=(D=c.find(O=>O.value===s))==null?void 0:D.label;return a.jsxs("button",{type:"button",className:st.metaValueClickable,onClick:()=>S.startEdit(),title:"Click to change","aria-label":_,"data-testid":b?`${b}-button`:void 0,children:[T!==void 0?T:C?a.jsx("span",{children:C}):a.jsx("span",{className:st.metaPlaceholder,children:v||"None"}),a.jsx("span",{className:st.editButton,"aria-hidden":"true",children:"✏️"})]})}function RI(t){const{checked:s,onChange:o,label:r,ariaLabel:c,"data-testid":d}=t;return a.jsxs("label",{className:st.worktreeToggle,"data-testid":d,children:[a.jsx("input",{type:"checkbox",checked:s,onChange:u=>o(u.target.checked),"aria-label":c}),a.jsx("span",{children:r})]})}const MI="_nav_1snmp_1",II="_searchForm_1snmp_8",OI="_searchInput_1snmp_15",BI="_searchButton_1snmp_33",LI="_clearButton_1snmp_68",zI="_workspaceSelect_1snmp_85",$I="_listHeader_1snmp_99",PI="_nodeList_1snmp_108",UI="_nodeItem_1snmp_116",HI="_indicator_1snmp_129",VI="_label_1snmp_136",qI="_badge_1snmp_145",ns={nav:MI,searchForm:II,searchInput:OI,searchButton:BI,clearButton:LI,workspaceSelect:zI,listHeader:$I,nodeList:PI,nodeItem:UI,indicator:HI,label:VI,badge:qI};function GI({nodes:t,workspaces:s,loading:o,searchQuery:r,onSearch:c,onClearSearch:d,onSelectNode:u,onWorkspaceChange:p}){const[m,g]=y.useState(""),v=y.useCallback(S=>{S.preventDefault(),m.trim()&&c(m.trim())},[m,c]),_=y.useCallback(()=>{g(""),d()},[d]),b=y.useCallback(S=>{u(S)},[u]),x=y.useCallback(S=>{g(""),p(S)},[p]);return a.jsxs("div",{className:ns.nav,"data-testid":"knowledge-nav",children:[a.jsxs("form",{className:ns.searchForm,onSubmit:v,children:[a.jsx("input",{className:ns.searchInput,type:"text",placeholder:"Search...",value:m,onChange:S=>{g(S.target.value)},"data-testid":"knowledge-search-input","aria-label":"Search knowledge nodes"}),a.jsx("button",{type:"submit",className:ns.searchButton,disabled:o,children:"Go"})]}),r&&a.jsx("button",{type:"button",className:ns.clearButton,onClick:_,children:"Clear search"}),a.jsxs("select",{className:ns.workspaceSelect,onChange:S=>{x(S.target.value)},"data-testid":"knowledge-workspace-filter","aria-label":"Filter by workspace",children:[a.jsx("option",{value:"",children:"All workspaces"}),s.map(S=>a.jsx("option",{value:S.id,children:S.name},S.id))]}),a.jsxs("div",{className:ns.listHeader,children:["Nodes (",t.length,")"]}),a.jsx("ul",{className:ns.nodeList,children:t.map(S=>a.jsxs("li",{className:ns.nodeItem,onClick:()=>{b(S.id)},onKeyDown:j=>{(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),b(S.id))},role:"button",tabIndex:0,children:[a.jsx("span",{className:ns.indicator,style:{backgroundColor:S.kind==="reference"?"#4A9EFF":S.category==="decision"?"#22C55E":S.category==="concept"?"#A855F7":S.category==="snippet"?"#6B7280":"#EAB308"}}),a.jsx("span",{className:ns.label,children:S.label}),a.jsx("span",{className:ns.badge,children:S.kind==="reference"?S.sourceType:S.category})]},S.id))})]})}const FI="_container_bwu10_1",ZI="_hamburger_bwu10_33",KI="_brand_bwu10_49",YI="_brandLogo_bwu10_68",JI="_info_bwu10_75",WI="_connectionLabel_bwu10_90",XI="_connectionDot_bwu10_103",QI="_connected_bwu10_106",e5="_disconnected_bwu10_110",t5="_connecting_bwu10_113",Rs={container:FI,hamburger:ZI,brand:KI,brandLogo:YI,info:JI,connectionLabel:WI,connectionDot:XI,connected:QI,disconnected:e5,connecting:t5},n5={connected:"Connected",connecting:"Connecting...",disconnected:"Disconnected"},s5={connected:Rs.connected,connecting:Rs.connecting,disconnected:Rs.disconnected};function a5({connectionStatus:t,environments:s,sessions:o,onToggleSidebar:r,sidebarOpen:c}){const d=ct(),u=s.length,p=s.filter(v=>v.status==="connected").length,m=o.filter(v=>["running","idle"].includes(v.status)).length,g=n5[t];return a.jsxs("div",{className:Rs.container,children:[r&&a.jsx("button",{type:"button",className:Rs.hamburger,onClick:r,"aria-label":"Toggle sidebar","aria-expanded":c,children:a.jsx(dT,{size:At,"aria-hidden":"true"})}),a.jsx(Oi,{text:"Home",placement:"bottom",children:a.jsxs("button",{type:"button",className:Rs.brand,onClick:()=>d(Ii),"data-testid":"statusbar-brand",children:[a.jsx("img",{src:"/icon-192x192.png",alt:"",className:Rs.brandLogo,"aria-hidden":"true","data-testid":"statusbar-logo"}),"Grackle"]})}),a.jsxs("div",{className:Rs.info,children:[a.jsxs("span",{"aria-label":g,children:[a.jsx("span",{className:`${Rs.connectionDot} ${s5[t]}`,"aria-hidden":"true",children:a.jsx(Ya,{size:Nm,fill:"currentColor"})})," ",a.jsx("span",{className:Rs.connectionLabel,"aria-hidden":"true",children:g})]}),a.jsxs("span",{children:[p,"/",u," env",u!==1?"s":""]}),a.jsxs("span",{children:[m," active"]})]})]})}const i5="_nav_13gkc_1",o5="_tab_13gkc_35",r5="_tabIcon_13gkc_68",l5="_tabLabel_13gkc_79",c5="_tabActive_13gkc_84",Gr={nav:i5,tab:o5,tabIcon:r5,tabLabel:l5,tabActive:c5},cd=[{view:"dashboard",label:"Dashboard",icon:a.jsx(Wj,{size:At}),route:Ii,testId:"sidebar-tab-dashboard"},{view:"chat",label:"Chat",icon:a.jsx(B_,{size:At}),route:dl,testId:"sidebar-tab-chat"},{view:"tasks",label:"Tasks",icon:a.jsx(Bj,{size:At}),route:UN,testId:"sidebar-tab-tasks"},{view:"environments",label:"Environments",icon:a.jsx(pT,{size:At}),route:Lo,testId:"sidebar-tab-environments"},{view:"knowledge",label:"Knowledge",icon:a.jsx(Cj,{size:At}),route:ix,testId:"sidebar-tab-knowledge"},{view:"findings",label:"Findings",icon:a.jsx(pd,{size:At}),route:zd,testId:"sidebar-tab-findings"},{view:"settings",label:"Settings",icon:a.jsx(CT,{size:At}),route:ON,testId:"sidebar-tab-settings"}];function d5(t){return t===Ii||t==="/"?"dashboard":t.startsWith("/chat")||t.startsWith("/sessions")?"chat":t.startsWith("/workspaces")||t.startsWith("/environments")?"environments":t.startsWith(ix)?"knowledge":t.startsWith(zd)?"findings":t.startsWith(Ei)?"settings":"tasks"}function u5({tabs:t=cd}){const s=Yt(),o=ct(),r=y.useRef(null),c=d5(s.pathname),d=y.useCallback(p=>{o(p.route)},[o]),u=y.useCallback(p=>{var b,x;const m=(b=r.current)==null?void 0:b.querySelectorAll('[role="tab"]');if(!m)return;const g=Array.from(m).findIndex(S=>S===document.activeElement),v=g>=0?g:t.findIndex(S=>S.view===c);let _=v;if(p.key==="ArrowRight"||p.key==="j"||p.key==="J")p.preventDefault(),_=(v+1)%t.length;else if(p.key==="ArrowLeft"||p.key==="k"||p.key==="K")p.preventDefault(),_=(v-1+t.length)%t.length;else if(p.key==="Home")p.preventDefault(),_=0;else if(p.key==="End")p.preventDefault(),_=t.length-1;else return;o(t[_].route),(x=m[_])==null||x.focus()},[c,o,t]);return a.jsx("nav",{className:Gr.nav,ref:r,role:"tablist","aria-orientation":"horizontal","aria-label":"App navigation",onKeyDown:u,"data-testid":"sidebar-nav",children:t.map(p=>{const m=p.view===c;return a.jsx(Oi,{text:p.label,placement:"bottom",children:a.jsxs("button",{role:"tab",type:"button","aria-selected":m,tabIndex:m?0:-1,className:`${Gr.tab} ${m?Gr.tabActive:""}`,onClick:()=>d(p),"data-testid":p.testId,"aria-label":p.label,children:[a.jsx("span",{className:Gr.tabIcon,"aria-hidden":"true",children:p.icon}),a.jsx("span",{className:Gr.tabLabel,children:p.label})]})},p.view)})})}const f5="_container_pi6ii_1",p5="_content_pi6ii_66",s_={container:f5,content:p5},m5=320,U1=220,H1=600,V1="grackle-sidebar-width";function h5(){try{const t=localStorage.getItem(V1);if(t!==null){const s=Number(t);if(Number.isFinite(s)&&s>=U1&&s<=H1)return s}}catch{}return m5}function g5(t){try{localStorage.setItem(V1,String(t))}catch{}}function v5({content:t}){const[s]=y.useState(h5),o=y.useRef(null);if(y.useEffect(()=>{const r=o.current;if(!r)return;const c=new ResizeObserver(d=>{for(const u of d){const p=u.borderBoxSize[0];if(p){const m=Math.round(p.inlineSize);m>=U1&&m<=H1&&g5(m)}}});return c.observe(r),()=>{c.disconnect()}},[]),t!==void 0)return a.jsx("div",{className:s_.container,ref:o,"data-testid":"sidebar",style:{width:s},children:a.jsx("div",{className:s_.content,children:t})})}const y5="_bar_tnfsh_1",b5="_btnPrimary_tnfsh_32",_5="_statusText_tnfsh_85",x5="_statusCompleted_tnfsh_90",k5="_statusFailed_tnfsh_94",S5="_statusBlocked_tnfsh_98",j5="_hintText_tnfsh_103",wt={bar:y5,btnPrimary:b5,statusText:_5,statusCompleted:x5,statusFailed:k5,statusBlocked:S5,hintText:j5};function T5({sessions:t,tasks:s,environments:o}){const r=ct(),c=Yt(),d=Et("/sessions/:sessionId"),u=Et("/tasks/:taskId"),p=Et("/tasks/:taskId/stream"),m=Et("/tasks/:taskId/findings"),g=Et("/tasks/:taskId/edit"),v=Et("/environments/:environmentId/workspaces/:workspaceId/tasks/:taskId"),_=Et("/environments/:environmentId/workspaces/:workspaceId/tasks/:taskId/stream"),b=Et("/environments/:environmentId/workspaces/:workspaceId/tasks/:taskId/findings"),x=Et("/environments/:environmentId/workspaces/:workspaceId/tasks/:taskId/edit"),S=Et("/sessions/new"),j=Et("/environments/:environmentId/workspaces/:workspaceId"),w=Et("/tasks/new"),T=Et("/chat"),C=Et("/"),D=Et("/settings/*"),O=d==null?void 0:d.params.sessionId,A=(u==null?void 0:u.params.taskId)??(p==null?void 0:p.params.taskId)??(m==null?void 0:m.params.taskId)??(v==null?void 0:v.params.taskId)??(_==null?void 0:_.params.taskId)??(b==null?void 0:b.params.taskId)??(x==null?void 0:x.params.taskId),I=v??_??b??x,$=(I==null?void 0:I.params.environmentId)??(j==null?void 0:j.params.environmentId),B=c.pathname.startsWith("/environments")&&!j&&!I,P=!!T,X=!!S,H=!!j&&!v&&!_&&!b&&!x,Q=!!w;if(!!C&&!X&&!H&&!Q||!!D||(!!g||!!x)||Q||B||X)return a.jsx(a.Fragment,{});if(P)return o.find(E=>E.adapterType==="local"&&E.status==="connected")?a.jsx(a.Fragment,{}):a.jsx("div",{className:wt.bar,children:a.jsx("span",{className:wt.hintText,children:"Add a local environment to start chatting"})});if(H)return a.jsx("div",{className:wt.bar,children:a.jsx("span",{className:wt.hintText,children:"Select a task or click + to create one"})});if(A){const L=s.find(me=>me.id===A);if(!L)return a.jsx("div",{className:wt.bar,children:a.jsx("span",{className:wt.hintText,children:"Loading..."})});const E=new Map(s.map(me=>[me.id,me])),J=L.dependsOn.some(me=>{const q=E.get(me);return q!==void 0&&q.status!=="complete"});if(L.status==="not_started"){const me=J?L.dependsOn.map(q=>E.get(q)).filter(q=>q&&q.status!=="complete").map(q=>q.title):[];return a.jsx("div",{className:wt.bar,children:J?a.jsxs("span",{className:wt.statusBlocked,children:["Blocked by: ",me.join(", ")]}):a.jsx("span",{className:wt.hintText,children:"Use the buttons above to start or manage this task"})})}if(L.status==="working"||L.status==="paused"){const me=L.latestSessionId||void 0,q=me?t.find(re=>re.id===me):void 0;return q&&q.status!=="stopped"?a.jsx(a.Fragment,{}):a.jsx("div",{className:wt.bar,children:a.jsx("span",{className:wt.hintText,children:"Waiting for agent..."})})}if(L.status==="complete")return a.jsxs("div",{className:wt.bar,children:[a.jsx("span",{className:`${wt.statusText} ${wt.statusCompleted}`,children:"Task completed"}),a.jsx("button",{onClick:()=>r(zi(L.workspaceId,void 0,$)),className:wt.btnPrimary,children:"+ New Task"})]});if(L.status==="failed")return a.jsx("div",{className:wt.bar,children:a.jsx("span",{className:`${wt.statusText} ${wt.statusFailed}`,children:"Task failed"})})}if(O){const L=t.find(me=>me.id===O),E=(L==null?void 0:L.status)==="stopped";if(L!==void 0&&!E)return a.jsx(a.Fragment,{});if(E)return a.jsxs("div",{className:wt.bar,children:[a.jsxs("span",{className:`${wt.statusText} ${wt.hintText}`,children:["Session ",L.endReason||L.status]}),a.jsx("button",{onClick:()=>r(tx(L.environmentId)),className:wt.btnPrimary,children:"+ New Chat"})]})}return a.jsx("div",{className:wt.bar,children:a.jsx("span",{className:wt.hintText,children:"Loading..."})})}const w5="_nav_14i94_1",N5="_tab_14i94_24",C5="_tabActive_14i94_62",E5="_tabLabel_14i94_75",A5="_statusDot_14i94_81",D5="_pulse_14i94_87",R5="_addButton_14i94_99",M5="_empty_14i94_132",Va={nav:w5,tab:N5,tabActive:C5,tabLabel:E5,statusDot:A5,pulse:D5,addButton:R5,empty:M5},I5={connected:"var(--accent-green)",sleeping:"var(--accent-yellow)",error:"var(--accent-red)",disconnected:"var(--text-tertiary)",connecting:"var(--accent-blue)"};function O5({environments:t}){const s=ct(),o=y.useRef(null),r=Et("/environments/:environmentId"),c=Et("/environments/:environmentId/edit"),d=Et("/environments/:environmentId/workspaces/:workspaceId"),u=Et("/environments/:environmentId/workspaces/:workspaceId/*"),p=(r==null?void 0:r.params.environmentId)??(c==null?void 0:c.params.environmentId)??(d==null?void 0:d.params.environmentId)??(u==null?void 0:u.params.environmentId),m=p==="new"?void 0:p,g=y.useCallback(b=>{s(Mi(b))},[s]),v=y.useCallback(b=>{var T;const x=(T=o.current)==null?void 0:T.querySelectorAll('[role="tab"]');if(!x||x.length===0)return;const S=Array.from(x).findIndex(C=>C===document.activeElement),j=S>=0?S:t.findIndex(C=>C.id===m);let w=j;if(b.key==="ArrowDown"||b.key==="j"||b.key==="J")b.preventDefault(),w=(j+1)%x.length;else if(b.key==="ArrowUp"||b.key==="k"||b.key==="K")b.preventDefault(),w=(j-1+x.length)%x.length;else if(b.key==="Home")b.preventDefault(),w=0;else if(b.key==="End")b.preventDefault(),w=x.length-1;else return;w<t.length&&s(Mi(t[w].id)),x[w].focus()},[m,t,s]),_=m??(t.length>0?t[0].id:void 0);return a.jsxs("div",{className:Va.nav,"data-testid":"environment-nav",children:[a.jsx("nav",{ref:o,role:"tablist","aria-orientation":"vertical","aria-label":"Environments",onKeyDown:v,children:t.map(b=>{const x=b.id===m,S=b.id===_,j=I5[b.status]||"var(--text-tertiary)",w=b.status==="connected";return a.jsxs("button",{role:"tab",type:"button","aria-selected":x,tabIndex:S?0:-1,className:`${Va.tab} ${x?Va.tabActive:""}`,onClick:()=>g(b.id),"data-testid":"env-nav-item",children:[a.jsx("span",{className:`${Va.statusDot} ${w?Va.pulse:""}`,style:{color:j},"aria-hidden":"true",children:a.jsx(Ya,{size:Nm,fill:"currentColor"})}),a.jsx("span",{className:Va.tabLabel,title:b.displayName||b.id,children:b.displayName||b.id})]},b.id)})}),a.jsx("button",{type:"button",className:Va.addButton,onClick:()=>s(MN),title:"Add environment","data-testid":"env-nav-add",children:"+ Add Environment"}),t.length===0&&a.jsx("div",{className:Va.empty,children:"No environments yet."})]})}function Ho(t){const s=new Date(t),o=new Date,r=o.getTime()-s.getTime(),c=Math.floor(r/1e3),d=Math.floor(c/60),u=Math.floor(d/60),p=Math.floor(u/24);if(c<60)return"just now";if(d<60)return`${d}m ago`;if(u<24)return`${u}h ago`;if(p===1)return"yesterday";if(p<7)return`${p} days ago`;const m=s.getFullYear()===o.getFullYear(),g=s.toLocaleString("en-US",{month:"short"}),v=s.getDate();return m?`${g} ${v}`:`${g} ${v} ${s.getFullYear()}`}function q1(t){const s=new Date(t);if(Number.isNaN(s.getTime()))return"—";const o=new Date,r=s.getTime()-o.getTime();if(r<=0)return"overdue";const c=Math.floor(r/1e3),d=Math.floor(c/60),u=Math.floor(d/60),p=Math.floor(u/24);if(c<60)return`in ${c}s`;if(d<60)return`in ${d}m`;if(u<24)return`in ${u}h`;if(p<7)return`in ${p} day${p===1?"":"s"}`;const m=s.getFullYear()===o.getFullYear(),g=s.toLocaleString("en-US",{month:"short"}),v=s.getDate();return m?`${g} ${v}`:`${g} ${v} ${s.getFullYear()}`}const a_={architecture:{text:"var(--accent-blue)",bg:"var(--accent-blue-dim)"},api:{text:"var(--accent-green)",bg:"var(--accent-green-dim)"},bug:{text:"var(--accent-red)",bg:"var(--accent-red-dim)"},decision:{text:"var(--accent-yellow)",bg:"var(--accent-yellow-dim)"},dependency:{text:"var(--accent-purple)",bg:"var(--accent-purple-dim)"},pattern:{text:"var(--accent-cyan)",bg:"var(--accent-cyan-dim)"},general:{text:"var(--text-secondary)",bg:"var(--bg-elevated)"}};function wd(t){return a_[t]||a_.general}const B5="_nav_dlm8m_1",L5="_categoryPills_dlm8m_24",z5="_categoryPill_dlm8m_24",$5="_tab_dlm8m_42",P5="_tabActive_dlm8m_80",U5="_tabContent_dlm8m_93",H5="_tabLabel_dlm8m_100",V5="_tabMeta_dlm8m_106",q5="_categoryDot_dlm8m_111",G5="_empty_dlm8m_118",As={nav:B5,categoryPills:L5,categoryPill:z5,tab:$5,tabActive:P5,tabContent:U5,tabLabel:H5,tabMeta:V5,categoryDot:q5,empty:G5};function F5({findings:t,workspaceId:s,environmentId:o}){const r=ct(),c=y.useRef(null),d=Et("/findings/:findingId"),u=Et("/environments/:environmentId/workspaces/:workspaceId/findings/:findingId"),p=(d==null?void 0:d.params.findingId)??(u==null?void 0:u.params.findingId),m=y.useMemo(()=>{const b=new Set(t.map(x=>x.category).filter(Boolean));return Array.from(b).sort()},[t]),g=y.useCallback(b=>{r(Qp(b,s,o))},[r,s,o]),v=y.useCallback(b=>{var T;const x=(T=c.current)==null?void 0:T.querySelectorAll('[role="tab"]');if(!x||x.length===0)return;const S=Array.from(x).findIndex(C=>C===document.activeElement),j=S>=0?S:t.findIndex(C=>C.id===p);let w=j;if(b.key==="ArrowDown"||b.key==="j"||b.key==="J")b.preventDefault(),w=(j+1)%x.length;else if(b.key==="ArrowUp"||b.key==="k"||b.key==="K")b.preventDefault(),w=(j-1+x.length)%x.length;else if(b.key==="Home")b.preventDefault(),w=0;else if(b.key==="End")b.preventDefault(),w=x.length-1;else return;w<t.length&&r(Qp(t[w].id,s,o)),x[w].focus()},[p,t,r,s,o]),_=p??(t.length>0?t[0].id:void 0);return a.jsxs("div",{className:As.nav,"data-testid":"findings-nav",children:[m.length>1&&a.jsx("div",{className:As.categoryPills,"data-testid":"findings-nav-categories",children:m.map(b=>a.jsx("span",{className:As.categoryPill,style:{color:wd(b).text},children:b},b))}),a.jsx("nav",{ref:c,role:"tablist","aria-orientation":"vertical","aria-label":"Findings",onKeyDown:v,children:t.map(b=>{const x=b.id===p,S=b.id===_;return a.jsxs("button",{role:"tab",type:"button","aria-selected":x,tabIndex:S?0:-1,className:`${As.tab} ${x?As.tabActive:""}`,onClick:()=>g(b.id),"data-testid":"finding-nav-item",children:[a.jsx("span",{className:As.categoryDot,style:{color:wd(b.category).text},"aria-hidden":"true",children:a.jsx(Ya,{size:Nm,fill:"currentColor"})}),a.jsxs("span",{className:As.tabContent,children:[a.jsx("span",{className:As.tabLabel,title:b.title,children:b.title}),a.jsx("span",{className:As.tabMeta,title:b.createdAt,children:Ho(b.createdAt)})]})]},b.id)})}),t.length===0&&a.jsx("div",{className:As.empty,children:"No findings yet. Agents will post discoveries here."})]})}function Z5(t){if(t.length===0)return[];const s=[...t].sort((r,c)=>r[0]-c[0]),o=[[s[0][0],s[0][1]]];for(let r=1;r<s.length;r++){const c=o[o.length-1],[d,u]=s[r];d<=c[1]+1?c[1]=Math.max(c[1],u):o.push([d,u])}return o}function G1({text:t,indices:s,highlightClass:o}){if(!s||s.length===0)return a.jsx(a.Fragment,{children:t});const r=Z5(s),c=[];let d=0;for(const[u,p]of r)u>d&&c.push(a.jsx("span",{children:t.slice(d,u)},`p${d}`)),c.push(a.jsx("mark",{className:o,children:t.slice(u,p+1)},`m${u}`)),d=p+1;return d<t.length&&c.push(a.jsx("span",{children:t.slice(d)},`p${d}`)),a.jsx(a.Fragment,{children:c})}function K5(t){const s=new Map(t.map(r=>[r.id,{...r,children:[]}])),o=[];for(const r of s.values())r.parentTaskId&&s.has(r.parentTaskId)?s.get(r.parentTaskId).children.push(r):o.push(r);for(const r of s.values())r.children.sort((c,d)=>c.sortOrder-d.sortOrder);return o.sort((r,c)=>r.sortOrder-c.sortOrder)}function Y5(t,s){const o=new Map;for(const d of t){const p=d.dependsOn.length>0&&d.dependsOn.some(g=>s.get(g)!=="complete")?"blocked":d.status,m=o.get(p);m?m.push(d):o.set(p,[d])}const r=[],c=new Set;for(const d of LT){c.add(d);const u=o.get(d);if(u&&u.length>0){u.sort((m,g)=>m.sortOrder-g.sortOrder);const p=Ja(d);r.push({status:d,label:p.label,style:p,tasks:u})}}for(const[d,u]of o)if(!c.has(d)&&u.length>0){u.sort((m,g)=>m.sortOrder-g.sortOrder);const p=Ja(d);r.push({status:d,label:p.label,style:p,tasks:u})}return r}const J5="_container_z4i38_1",W5="_header_z4i38_5",X5="_headerActions_z4i38_17",Q5="_searchInput_z4i38_23",eO="_searchHighlight_z4i38_56",tO="_groupToggle_z4i38_62",nO="_groupToggleActive_z4i38_89",sO="_addButton_z4i38_93",aO="_taskRow_z4i38_120",iO="_selected_z4i38_140",oO="_expandArrow_z4i38_150",rO="_expanded_z4i38_157",lO="_leafSpacer_z4i38_161",cO="_taskStatusIcon_z4i38_166",dO="_taskTitle_z4i38_170",uO="_workspaceBadge_z4i38_177",fO="_childCountBadge_z4i38_195",pO="_dependencyBadge_z4i38_208",mO="_blockedBadge_z4i38_220",hO="_addChildButton_z4i38_225",gO="_emptyState_z4i38_268",vO="_statusGroupHeader_z4i38_275",yO="_statusGroupIcon_z4i38_294",bO="_statusGroupLabel_z4i38_298",_O="_statusGroupCount_z4i38_303",Ke={container:J5,header:W5,headerActions:X5,searchInput:Q5,searchHighlight:eO,groupToggle:tO,groupToggleActive:nO,addButton:sO,taskRow:aO,selected:iO,expandArrow:oO,expanded:rO,leafSpacer:lO,taskStatusIcon:cO,taskTitle:dO,workspaceBadge:uO,childCountBadge:fO,dependencyBadge:pO,blockedBadge:mO,addChildButton:hO,emptyState:gO,statusGroupHeader:vO,statusGroupIcon:yO,statusGroupLabel:bO,statusGroupCount:_O},xO=[{name:"title",weight:2},{name:"description",weight:1}],F1=16,kO=16,Z1="grackle-task-group-by-status";function i_(){try{return localStorage.getItem(Z1)==="true"}catch{return!1}}function SO(t){try{localStorage.setItem(Z1,String(t))}catch{}}function jO({group:t,isExpanded:s,onToggle:o,selectedTaskId:r,navigate:c,titleHighlights:d,workspaceNames:u}){return a.jsxs("div",{"data-testid":`status-group-${t.status}`,children:[a.jsxs("div",{className:Ke.statusGroupHeader,role:"button",tabIndex:0,"aria-expanded":s,onClick:o,onKeyDown:p=>{(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),o())},children:[a.jsx("span",{className:`${Ke.expandArrow} ${s?Ke.expanded:""}`,"aria-hidden":"true",children:a.jsx(fa,{size:at})}),a.jsx("span",{className:Ke.statusGroupIcon,style:{color:t.style.color},"aria-hidden":"true",children:t.style.icon}),a.jsx("span",{className:Ke.statusGroupLabel,children:t.label}),a.jsx("span",{className:Ke.statusGroupCount,children:t.tasks.length})]}),a.jsx(ls,{children:s&&a.jsx(Nt.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2},style:{overflow:"hidden"},children:t.tasks.map(p=>{const m=Ja(p.status),g=r===p.id,v=p.parentTaskId||!p.workspaceId?void 0:u.get(p.workspaceId);return a.jsxs("div",{onClick:()=>c($n(p.id)),role:"button",tabIndex:0,"aria-label":p.title,onKeyDown:_=>{_.currentTarget===_.target&&(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),c($n(p.id)))},className:`${Ke.taskRow} ${g?Ke.selected:""}`,style:{"--task-indent":`${F1}px`},"data-task-id":p.id,children:[a.jsx("span",{className:Ke.leafSpacer}),a.jsx("span",{className:Ke.taskStatusIcon,style:{color:m.color},"aria-hidden":"true","data-testid":`task-status-${vl(p.status)}`,children:m.icon}),a.jsx("span",{className:Ke.taskTitle,title:p.title,children:a.jsx(G1,{text:p.title,indices:d.get(p.id),highlightClass:Ke.searchHighlight})}),v&&a.jsx("span",{className:Ke.workspaceBadge,title:v,children:v})]},p.id)})})})]})}function K1({node:t,depth:s,expandedTasks:o,toggleTask:r,selectedTaskId:c,navigate:d,taskStatusById:u,titleHighlights:p,workspaceNames:m}){const g=Ja(t.status),v=t.dependsOn.length>0&&t.dependsOn.some(T=>u.get(T)!=="complete"),_=o.has(t.id),b=t.children.length>0,x=c===t.id,S=F1+s*kO,w=s===0&&!t.parentTaskId&&t.workspaceId?m.get(t.workspaceId):void 0;return a.jsxs(a.Fragment,{children:[a.jsxs("div",{onClick:()=>d($n(t.id)),role:"button",tabIndex:0,"aria-label":t.title,onKeyDown:T=>{T.currentTarget===T.target&&(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),d($n(t.id)))},className:`${Ke.taskRow} ${x?Ke.selected:""}`,style:{"--task-indent":`${S}px`},"data-task-id":t.id,children:[b&&a.jsx("span",{className:`${Ke.expandArrow} ${_?Ke.expanded:""}`,role:"button",tabIndex:0,"aria-label":_?"Collapse task":"Expand task",onClick:T=>{T.stopPropagation(),r(t.id)},onKeyDown:T=>{(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),T.stopPropagation(),r(t.id))},children:a.jsx(fa,{size:at,"aria-hidden":"true"})}),!b&&a.jsx("span",{className:Ke.leafSpacer}),a.jsx("span",{className:Ke.taskStatusIcon,style:{color:g.color},"aria-hidden":"true","data-testid":`task-status-${vl(t.status)}`,children:g.icon}),a.jsx("span",{className:Ke.taskTitle,title:t.title,children:a.jsx(G1,{text:t.title,indices:p.get(t.id),highlightClass:Ke.searchHighlight})}),w&&a.jsx("span",{className:Ke.workspaceBadge,title:w,children:w}),b&&a.jsxs("span",{className:Ke.childCountBadge,children:[t.children.filter(T=>T.status==="complete").length,"/",t.children.length]}),t.dependsOn.length>0&&a.jsx("span",{className:`${Ke.dependencyBadge} ${v?Ke.blockedBadge:""}`,title:`Depends on: ${t.dependsOn.join(", ")}`,children:v?"blocked":"dep"}),s<P2&&a.jsx(Oi,{text:"Add child task",children:a.jsx("button",{onClick:T=>{T.stopPropagation(),d(zi(t.workspaceId,t.id))},"aria-label":"Add child task",className:Ke.addChildButton,children:"+"})})]}),a.jsx(ls,{children:b&&_&&a.jsx(Nt.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.15},style:{overflow:"hidden"},children:t.children.map(T=>a.jsx(K1,{node:T,depth:s+1,expandedTasks:o,toggleTask:r,selectedTaskId:c,navigate:d,taskStatusById:u,titleHighlights:p,workspaceNames:m},T.id))})})]})}function TO({workspaces:t,tasks:s}){const o=ct(),[r,c]=y.useState(new Set),[d,u]=y.useState(new Set),[p,m]=y.useState(i_),[g,v]=y.useState(i_),[_,b]=y.useState(new Map),x=Et("/tasks/:taskId/*"),S=(x==null?void 0:x.params.taskId)!=="new"?x==null?void 0:x.params.taskId:void 0,j=y.useMemo(()=>new Map(s.map(W=>[W.id,W.status])),[s]),w=y.useMemo(()=>new Map(t.map(W=>[W.id,W.name])),[t]),T=()=>{const W=!p;SO(W),m(W),W&&(v(!0),b(new Map))},C=W=>{b(ie=>{const L=new Map(ie),E=L.has(W)?L.get(W):g;return L.set(W,!E),L})},D=W=>_.has(W)?_.get(W):g,O=W=>{c(ie=>{const L=new Set(ie);return L.has(W)?(L.delete(W),u(E=>new Set(E).add(W))):(L.add(W),u(E=>{const J=new Set(E);return J.delete(W),J})),L})};y.useEffect(()=>{const W=new Set(s.filter(ie=>ie.parentTaskId).map(ie=>ie.parentTaskId));W.size>0&&c(ie=>{const L=new Set(ie);for(const E of W)d.has(E)||L.add(E);return L})},[s,d]);const[A,I]=y.useState(""),{directMatchTaskIds:$,treeMatchTaskIds:B,titleHighlights:P}=y.useMemo(()=>{if(!A.trim())return{directMatchTaskIds:null,treeMatchTaskIds:null,titleHighlights:new Map};const W=$2(s,A,xO),ie=new Set(W.map(me=>me.item.id)),L=new Map;for(const me of W){const q=me.matches.find(de=>de.key==="title");q&&L.set(me.item.id,q.indices)}const E=new Set(ie),J=new Map(s.map(me=>[me.id,me]));for(const me of[...ie]){let q=J.get(me);for(;q!=null&&q.parentTaskId;)E.add(q.parentTaskId),q=J.get(q.parentTaskId)}return{directMatchTaskIds:ie,treeMatchTaskIds:E,titleHighlights:L}},[A,s]),X=$!==null,H=X?p?$:B:null,Q=H?s.filter(W=>H.has(W.id)):s,he=p?[]:K5(Q);return a.jsxs("div",{className:Ke.container,children:[a.jsxs("div",{className:Ke.header,children:[a.jsx("span",{children:"Tasks"}),a.jsxs("div",{className:Ke.headerActions,children:[a.jsx(Oi,{text:p?"Switch to tree view":"Group tasks by status",children:a.jsx("button",{className:`${Ke.groupToggle} ${p?Ke.groupToggleActive:""}`,onClick:T,"aria-label":p?"Switch to tree view":"Group tasks by status","aria-pressed":p,"data-testid":"task-group-by-status-toggle",children:a.jsx(oT,{size:Qt})})}),a.jsx(Oi,{text:"New task",children:a.jsx("button",{className:Ke.addButton,onClick:()=>o(zi()),"aria-label":"New task","data-testid":"new-task-button",children:"+"})})]})]}),s.length>0&&a.jsx("input",{type:"text",value:A,onChange:W=>I(W.target.value),placeholder:"Filter...","aria-label":"Filter tasks",className:Ke.searchInput,"data-testid":"sidebar-search"}),p?Y5(Q,j).map(W=>a.jsx(jO,{group:W,isExpanded:D(W.status),onToggle:()=>C(W.status),selectedTaskId:S,navigate:o,titleHighlights:P,workspaceNames:w},W.status)):he.map(W=>a.jsx(K1,{node:W,depth:0,expandedTasks:r,toggleTask:O,selectedTaskId:S,navigate:o,taskStatusById:j,titleHighlights:P,workspaceNames:w},W.id)),Q.length===0&&!X&&a.jsx("div",{className:Ke.emptyState,children:"No tasks yet. Click + to create one."}),Q.length===0&&X&&a.jsx("div",{className:Ke.emptyState,children:"No matching tasks"})]})}const wO="_toast_ed2dk_1",NO="_success_ed2dk_18",CO="_icon_ed2dk_22",EO="_error_ed2dk_25",AO="_warning_ed2dk_32",DO="_info_ed2dk_38",RO="_message_ed2dk_53",MO="_close_ed2dk_60",Fr={toast:wO,success:NO,icon:CO,error:EO,warning:AO,info:DO,message:RO,close:MO},IO={success:a.jsx(Bi,{size:At}),error:a.jsx(pa,{size:At}),warning:a.jsx(wm,{size:At}),info:a.jsx(Tm,{size:At})};function OO({toast:t,onDismiss:s}){return y.useEffect(()=>{const o=setTimeout(()=>s(t.id),t.duration);return()=>clearTimeout(o)},[t.id,t.duration,s]),a.jsxs(Nt.div,{className:`${Fr.toast} ${Fr[t.variant]}`,role:"status",initial:{opacity:0,y:-16,scale:.94},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-8,scale:.94},transition:{duration:.2,ease:"easeOut"},layout:!0,children:[a.jsx("span",{className:Fr.icon,"aria-hidden":"true",children:IO[t.variant]}),a.jsx("span",{className:Fr.message,children:t.message}),a.jsx("button",{type:"button",className:Fr.close,onClick:()=>s(t.id),"aria-label":"Dismiss notification",children:a.jsx(pa,{size:Qt,"aria-hidden":"true"})})]})}const BO="_container_qqse2_1",LO={container:BO};function zO({toasts:t,onDismiss:s}){return a.jsx("div",{className:LO.container,"data-testid":"toast-container",children:a.jsx(ls,{children:t.map(o=>a.jsx(OO,{toast:o,onDismiss:s},o.id))})})}const $O="_callout_e5awm_1",PO="_success_e5awm_11",UO="_icon_e5awm_15",HO="_error_e5awm_18",VO="_warning_e5awm_25",qO="_info_e5awm_32",GO="_content_e5awm_48",FO="_close_e5awm_53",Zr={callout:$O,success:PO,icon:UO,error:HO,warning:VO,info:qO,content:GO,close:FO},ZO={success:a.jsx(Bi,{size:At}),error:a.jsx(pa,{size:At}),warning:a.jsx(wm,{size:At}),info:a.jsx(Tm,{size:At})};function KO({variant:t="info",children:s,dismissible:o=!1,className:r}){const[c,d]=y.useState(!1);return a.jsx(a.Fragment,{children:!c&&a.jsxs("div",{className:[Zr.callout,Zr[t],r].filter(Boolean).join(" "),role:t==="error"||t==="warning"?"alert":"status",children:[a.jsx("span",{className:Zr.icon,"aria-hidden":"true",children:ZO[t]}),a.jsx("span",{className:Zr.content,children:s}),o&&a.jsx("button",{type:"button",className:Zr.close,onClick:()=>d(!0),"aria-label":"Dismiss",children:a.jsx(pa,{size:Qt,"aria-hidden":"true"})})]})})}function YO({currentVersion:t,latestVersion:s,updateAvailable:o,isDocker:r}){if(!o)return a.jsx(a.Fragment,{});const c=r?"docker pull ghcr.io/nick-pape/grackle:latest && docker restart grackle":`npm install -g @grackle-ai/cli@${s}`;return a.jsx("div",{"data-testid":"update-banner",children:a.jsxs(KO,{variant:"info",dismissible:!0,children:[a.jsxs("strong",{children:["Grackle v",s]})," is available (you have v",t,")."," ","Run: ",a.jsx("code",{children:c})]})})}const JO="_container_de44x_1",WO="_emptyState_de44x_8",XO="_card_de44x_14",QO="_cardClickable_de44x_34",eB="_cardHeader_de44x_42",tB="_categoryBadge_de44x_54",nB="_findingTitle_de44x_62",sB="_findingDate_de44x_68",aB="_findingContent_de44x_80",iB="_tags_de44x_86",oB="_tag_de44x_86",ys={container:JO,emptyState:WO,card:XO,cardClickable:QO,cardHeader:eB,categoryBadge:tB,findingTitle:nB,findingDate:sB,findingContent:aB,tags:iB,tag:oB};function Y1({findings:t,onFindingClick:s}){return t.length===0?a.jsx("div",{className:ys.emptyState,children:"No findings yet. Agents will post discoveries here."}):a.jsx("div",{className:ys.container,children:t.map((o,r)=>{const c=wd(o.category),d=s?Nt.button:Nt.div;return a.jsxs(d,{type:s?"button":void 0,className:`${ys.card} ${s?ys.cardClickable:""}`,initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{delay:r*.05,duration:.2},onClick:s?()=>{s(o.id)}:void 0,children:[a.jsxs("div",{className:ys.cardHeader,children:[a.jsx("span",{className:ys.categoryBadge,style:{background:c.bg,color:c.text},children:o.category}),a.jsx("span",{className:ys.findingTitle,children:o.title}),a.jsx("span",{className:ys.findingDate,title:o.createdAt,children:Ho(o.createdAt)})]}),a.jsx("div",{className:ys.findingContent,children:o.content.length>300?o.content.slice(0,300)+"...":o.content}),o.tags.length>0&&a.jsx("div",{className:ys.tags,children:o.tags.map(u=>a.jsx("span",{className:ys.tag,style:{color:c.text,textShadow:`0 0 8px ${c.text}`},children:u},u))})]},o.id)})})}const rB="_container_m1fsr_1",lB="_heading_m1fsr_7",cB="_section_m1fsr_14",dB="_sectionTitle_m1fsr_26",uB="_sectionDescription_m1fsr_35",fB="_emptyState_m1fsr_41",pB="_tokenList_m1fsr_48",mB="_tokenRow_m1fsr_55",hB="_tokenBadge_m1fsr_68",gB="_tokenName_m1fsr_83",vB="_tokenTarget_m1fsr_90",yB="_deleteButton_m1fsr_99",bB="_addForm_m1fsr_113",_B="_formRow_m1fsr_119",xB="_input_m1fsr_125",kB="_select_m1fsr_155",SB="_addButton_m1fsr_187",jB="_emptyStateInfo_m1fsr_221",TB="_themeOptions_m1fsr_229",wB="_themeOption_m1fsr_229",NB="_themeOptionSelected_m1fsr_254",CB="_themeOptionHeader_m1fsr_259",EB="_themeOptionLabel_m1fsr_266",AB="_themeOptionDesc_m1fsr_273",DB="_variantToggle_m1fsr_279",RB="_variantButton_m1fsr_286",MB="_variantActive_m1fsr_305",IB="_themeSwatches_m1fsr_311",OB="_themeSwatch_m1fsr_311",BB="_systemToggle_m1fsr_325",LB="_systemToggleHint_m1fsr_341",zB="_themeActive_m1fsr_348",$B="_aboutGrid_m1fsr_354",PB="_aboutItem_m1fsr_360",UB="_aboutLabel_m1fsr_373",HB="_aboutValue_m1fsr_379",VB="_aboutDot_m1fsr_387",qB="_aboutDotConnected_m1fsr_394",GB="_aboutDotDisconnected_m1fsr_398",FB="_aboutDotConnecting_m1fsr_402",ge={container:rB,heading:lB,section:cB,sectionTitle:dB,sectionDescription:uB,emptyState:fB,tokenList:pB,tokenRow:mB,tokenBadge:hB,tokenName:gB,tokenTarget:vB,deleteButton:yB,addForm:bB,formRow:_B,input:xB,select:kB,addButton:SB,emptyStateInfo:jB,themeOptions:TB,themeOption:wB,themeOptionSelected:NB,themeOptionHeader:CB,themeOptionLabel:EB,themeOptionDesc:AB,variantToggle:DB,variantButton:RB,variantActive:MB,themeSwatches:IB,themeSwatch:OB,systemToggle:BB,systemToggleHint:LB,themeActive:zB,aboutGrid:$B,aboutItem:PB,aboutLabel:UB,aboutValue:HB,aboutDot:VB,aboutDotConnected:qB,aboutDotDisconnected:GB,aboutDotConnecting:FB},ZB=[{value:"env_var",label:"Environment Variable"},{value:"file",label:"File"}];function KB({tokens:t,onSetToken:s,onDeleteToken:o,onShowToast:r}){const[c,d]=y.useState(""),[u,p]=y.useState(""),[m,g]=y.useState("env_var"),[v,_]=y.useState(""),[b,x]=y.useState(null),S=T=>{if(T.preventDefault(),!c||!u)return;const C=m==="env_var"?v||c.toUpperCase()+"_TOKEN":"";s(c,u,m,C,m==="file"?v:""),r==null||r("Token saved successfully","success"),d(""),p(""),_("")},j=T=>{x(T)},w=()=>{b&&(o(b),r==null||r("Token deleted","info")),x(null)};return a.jsxs(a.Fragment,{children:[a.jsx(Ls,{isOpen:b!==null,title:"Delete Token?",description:b?`"${b}" will be permanently removed.`:void 0,onConfirm:w,onCancel:()=>x(null)}),a.jsxs("section",{className:ge.section,children:[a.jsx("h3",{className:ge.sectionTitle,children:"Tokens"}),a.jsx("p",{className:ge.sectionDescription,children:"API tokens are auto-pushed to environments when set or updated. Values are write-only."}),t.length===0?a.jsx("div",{className:ge.emptyStateInfo,children:"Add your first API token to enable service integrations."}):a.jsx("div",{className:ge.tokenList,children:t.map(T=>a.jsxs("div",{className:ge.tokenRow,children:[a.jsx("span",{className:ge.tokenBadge,children:T.tokenType}),a.jsx("span",{className:ge.tokenName,children:T.name}),a.jsx("span",{className:ge.tokenTarget,children:T.tokenType==="env_var"?T.envVar:T.filePath}),a.jsx("button",{className:ge.deleteButton,onClick:()=>j(T.name),title:`Delete ${T.name}`,"aria-label":`Delete ${T.name}`,children:a.jsx(pa,{size:Qt,"aria-hidden":"true"})})]},T.name))}),a.jsxs("form",{className:ge.addForm,onSubmit:S,children:[a.jsxs("div",{className:ge.formRow,children:[a.jsx("input",{className:ge.input,type:"text",placeholder:"Token name",value:c,onChange:T=>d(T.target.value)}),a.jsx("input",{className:ge.input,type:"password",placeholder:"Value",value:u,onChange:T=>p(T.target.value)})]}),a.jsxs("div",{className:ge.formRow,children:[a.jsx("select",{className:ge.select,value:m,onChange:T=>g(T.target.value),children:ZB.map(T=>a.jsx("option",{value:T.value,children:T.label},T.value))}),a.jsx("input",{className:ge.input,type:"text",placeholder:m==="env_var"?"Env var name (e.g. API_TOKEN)":"File path (e.g. /home/user/.token)",value:v,onChange:T=>_(T.target.value)}),a.jsx("button",{className:ge.addButton,type:"submit",children:"Add Token"})]})]})]})]})}const Gd=[{id:"grackle",label:"Grackle",description:"The default Grackle theme — iridescent purple on clean dark.",swatches:["#0e1218","#8b5cf6","#60a5fa","#e5e7eb","#34d399"],variantLightId:"grackle-light",variantDarkId:"grackle-dark"},{id:"grackle-light",label:"Grackle Light",description:"Light Grackle variant.",hidden:!0},{id:"grackle-dark",label:"Grackle Dark",description:"Dark Grackle variant.",hidden:!0},{id:"glass",label:"Glassmorphism",description:"Dark frosted-glass aesthetic with backdrop blur effects.",swatches:["#0a0c14","#4ecca3","#70a1ff","#e2e8f0","#a855f7"]},{id:"matrix",label:"Matrix",description:"Phosphor-green CRT terminal with scanlines and glow.",swatches:["#050505","#00ff41","#00bfff","#33ff77","#ffb000"]},{id:"brutalist",label:"Neubrutalism",description:"Thick borders, raw colors, bold type — ugly on purpose.",swatches:["#f5f0e8","#ff5757","#5ce1e6","#1a1a1a","#ffde59"],variantLightId:"brutalist-light",variantDarkId:"brutalist-dark"},{id:"brutalist-light",label:"Neubrutalism Light",description:"Light neubrutalism variant.",hidden:!0},{id:"brutalist-dark",label:"Neubrutalism Dark",description:"Dark neubrutalism variant.",hidden:!0},{id:"monokai",label:"Monokai",description:"Classic warm editor palette — pink, green, and purple.",swatches:["#272822","#f92672","#a6e22e","#f8f8f2","#ae81ff"],variantLightId:"monokai-light",variantDarkId:"monokai-dark"},{id:"monokai-dark",label:"Monokai Dark",description:"Dark Monokai variant.",hidden:!0},{id:"monokai-light",label:"Monokai Light",description:"Light Monokai variant.",hidden:!0},{id:"ubuntu",label:"Ubuntu",description:"Aubergine terminal with the GNOME Tango palette.",swatches:["#300a24","#8ae234","#ef2929","#eeeeec","#fce94f"]},{id:"sandstone",label:"Sandstone",description:"Warm terracotta accent on dark brown, in the style of Claude Code.",swatches:["#1a1815","#C15F3C","#6b8afd","#e8e6e3","#a78bfa"]},{id:"verdigris",label:"Verdigris",description:"Teal accent on charcoal, in the style of ChatGPT.",swatches:["#141414","#00a67e","#3b82f6","#ececec","#ab68ff"]},{id:"primer",label:"Primer",description:"Blue accent on ink-dark grey, in the style of GitHub.",swatches:["#0d1117","#58a6ff","#3fb950","#c9d1d9","#bc8cff"]}],J1=new Set(Gd.map(t=>t.id)),o_="grackle";function bm(t){return Gd.find(s=>s.id===t)}function YB({themeId:t,resolvedThemeId:s,onSetTheme:o,preferSystem:r,onSetPreferSystem:c}){return a.jsxs("section",{className:ge.section,children:[a.jsx("h3",{className:ge.sectionTitle,children:"Appearance"}),a.jsx("p",{className:ge.sectionDescription,children:"Choose how Grackle looks across the app."}),a.jsx("div",{className:ge.themeOptions,children:Gd.filter(d=>!d.hidden).map(d=>{const u=!!(d.variantLightId&&d.variantDarkId),p=u?t===d.id||t===d.variantLightId||t===d.variantDarkId:t===d.id,m=u&&s===d.variantLightId;return a.jsxs("button",{type:"button",className:`${ge.themeOption} ${p?ge.themeOptionSelected:""}`,"aria-pressed":p,onClick:()=>o(d.id),children:[a.jsxs("span",{className:ge.themeOptionHeader,children:[a.jsxs("span",{children:[a.jsx("span",{className:ge.themeOptionLabel,children:d.label}),a.jsx("span",{className:ge.themeOptionDesc,children:d.description})]}),u&&a.jsxs("span",{className:ge.variantToggle,children:[a.jsx("span",{role:"button",tabIndex:0,className:`${ge.variantButton} ${p&&m?ge.variantActive:""}`,onClick:g=>{g.stopPropagation(),c(!1),o(d.variantLightId)},onKeyDown:g=>{(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),g.stopPropagation(),c(!1),o(d.variantLightId))},"aria-label":"Light variant","aria-pressed":p&&m,children:"☼"}),a.jsx("span",{role:"button",tabIndex:0,className:`${ge.variantButton} ${p&&!m?ge.variantActive:""}`,onClick:g=>{g.stopPropagation(),c(!1),o(d.variantDarkId)},onKeyDown:g=>{(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),g.stopPropagation(),c(!1),o(d.variantDarkId))},"aria-label":"Dark variant","aria-pressed":p&&!m,children:"☾"})]})]}),d.swatches&&a.jsx("span",{className:ge.themeSwatches,children:d.swatches.map((g,v)=>a.jsx("span",{className:ge.themeSwatch,style:{background:g}},v))})]},d.id)})}),a.jsxs("label",{className:ge.systemToggle,children:[a.jsx("input",{type:"checkbox",checked:r,onChange:d=>c(d.target.checked)}),a.jsx("span",{children:"Match system light/dark preference"})]}),a.jsx("p",{className:ge.systemToggleHint,children:"Automatically switches between light and dark variants when available."}),a.jsxs("p",{className:ge.themeActive,children:["Active theme: ",a.jsx("strong",{children:s})]})]})}const JB={connected:"Connected",connecting:"Connecting...",disconnected:"Disconnected"},WB={connected:ge.aboutDotConnected,connecting:ge.aboutDotConnecting,disconnected:ge.aboutDotDisconnected};function XB({connectionStatus:t,environments:s,sessions:o}){const r=s.filter(u=>u.status==="connected").length,c=s.length,d=o.filter(u=>["running","idle"].includes(u.status)).length;return a.jsxs("section",{className:ge.section,"data-testid":"about-panel",children:[a.jsx("h3",{className:ge.sectionTitle,children:"About"}),a.jsx("p",{className:ge.sectionDescription,children:"Connection status and application information."}),a.jsxs("div",{className:ge.aboutGrid,children:[a.jsxs("div",{className:ge.aboutItem,children:[a.jsx("span",{className:ge.aboutLabel,children:"Connection"}),a.jsxs("span",{className:ge.aboutValue,children:[a.jsx("span",{className:`${ge.aboutDot} ${WB[t]}`}),JB[t]]})]}),a.jsxs("div",{className:ge.aboutItem,children:[a.jsx("span",{className:ge.aboutLabel,children:"Environments"}),a.jsxs("span",{className:ge.aboutValue,children:[r,"/",c," connected"]})]}),a.jsxs("div",{className:ge.aboutItem,children:[a.jsx("span",{className:ge.aboutLabel,children:"Active Sessions"}),a.jsx("span",{className:ge.aboutValue,children:d})]}),a.jsxs("div",{className:ge.aboutItem,children:[a.jsx("span",{className:ge.aboutLabel,children:"Version"}),a.jsx("span",{className:ge.aboutValue,children:"0.107.1"})]})]})]})}const QB="_container_cddyd_1",eL="_header_cddyd_8",tL="_headerTitle_cddyd_35",nL="_badge_cddyd_44",sL="_headerActions_cddyd_54",aL="_body_cddyd_61",iL="_formContent_cddyd_73",oL="_section_cddyd_85",rL="_label_cddyd_91",lL="_titleInput_cddyd_98",cL="_descriptionTextarea_cddyd_131",dL="_parentContext_cddyd_167",uL="_parentLabel_cddyd_175",fL="_parentName_cddyd_182",pL="_personaSelect_cddyd_186",mL="_depList_cddyd_220",hL="_depItem_cddyd_226",gL="_depItemSelected_cddyd_248",vL="_noDeps_cddyd_252",yL="_btnPrimary_cddyd_258",bL="_btnGhost_cddyd_289",nt={container:QB,header:eL,headerTitle:tL,badge:nL,headerActions:sL,body:aL,formContent:iL,section:oL,label:rL,titleInput:lL,descriptionTextarea:cL,parentContext:dL,parentLabel:uL,parentName:fL,personaSelect:pL,depList:mL,depItem:hL,depItemSelected:gL,noDeps:vL,btnPrimary:yL,btnGhost:bL};function W1({mode:t,taskId:s,workspaceId:o,parentTaskId:r,environmentId:c,tasks:d,workspaces:u,personas:p,onCreateTask:m,onUpdateTask:g,onEditDone:v,onShowToast:_}){const b=ct(),x=t==="edit",S=x&&s?d.find(ke=>ke.id===s):void 0,j=x?(S==null?void 0:S.workspaceId)??"":o??"",[w,T]=y.useState(j),C=j||w,D=u.find(ke=>ke.id===C),O=c??(D==null?void 0:D.linkedEnvironmentIds[0]),A=!x&&!o,I=x?(S==null?void 0:S.parentTaskId)??"":r??"",$=I?d.find(ke=>ke.id===I):void 0,[B,P]=y.useState((S==null?void 0:S.title)??""),[X,H]=y.useState((S==null?void 0:S.description)??""),[Q,he]=y.useState((S==null?void 0:S.dependsOn)??[]),[W,ie]=y.useState((S==null?void 0:S.defaultPersonaId)??""),[L,E]=y.useState((S==null?void 0:S.canDecompose)??!1),[J,me]=y.useState(!1),q=y.useRef(!1);y.useEffect(()=>{x&&S&&!q.current&&(q.current=!0,P(S.title),H(S.description),he(S.dependsOn),ie(S.defaultPersonaId),E(S.canDecompose))},[x,S]);const de=d.filter(ke=>ke.workspaceId===C&&(!x||ke.id!==s)&&ke.id!==I),re=B.trim().length>0&&(!x||S!==void 0)&&C.length>0,xe=ke=>{he(Le=>Le.includes(ke)?Le.filter(Ot=>Ot!==ke):[...Le,ke])},be=()=>{!re||J||x&&S===void 0||(x&&s?(g(s,B.trim(),X,Q,W),_==null||_("Task updated","success"),v?v():b($n(s,void 0,C,O),{replace:!0})):(me(!0),m(C,B.trim(),X,Q.length>0?Q:void 0,I||void 0,W,L,()=>{_==null||_("Task created","success"),b(o?Ri(o,O):"/tasks",{replace:!0})},ke=>{_==null||_(ke,"error"),me(!1)})))},fe=()=>{if(v){v();return}b(x&&s?$n(s,void 0,C,O):o?Ri(o,O):"/tasks")},_e=x?"edit task":I?"child task":"new task";return a.jsxs("div",{className:nt.container,children:[a.jsxs("div",{className:nt.header,children:[a.jsxs("div",{className:nt.headerTitle,children:[a.jsx("span",{className:nt.badge,children:_e}),$&&a.jsxs("span",{className:nt.parentContext,children:[a.jsx("span",{className:nt.parentLabel,children:"Child of"}),a.jsx("span",{className:nt.parentName,children:$.title})]})]}),a.jsxs("div",{className:nt.headerActions,children:[a.jsx("button",{onClick:be,disabled:!re||J,className:nt.btnPrimary,"data-testid":"task-edit-save",children:J?"Creating…":x?"Save Changes":"Create"}),a.jsx("button",{onClick:fe,className:nt.btnGhost,children:"Cancel"})]})]}),a.jsx("div",{className:nt.body,children:a.jsxs("div",{className:nt.formContent,children:[A&&a.jsxs("div",{className:nt.section,children:[a.jsx("label",{className:nt.label,htmlFor:"task-edit-workspace",children:"Workspace"}),a.jsxs("select",{id:"task-edit-workspace",value:w,onChange:ke=>T(ke.target.value),className:nt.personaSelect,"data-testid":"task-edit-workspace",children:[a.jsx("option",{value:"",children:"Select a workspace..."}),u.map(ke=>a.jsx("option",{value:ke.id,children:ke.name},ke.id))]})]}),a.jsxs("div",{className:nt.section,children:[a.jsx("label",{className:nt.label,htmlFor:"task-edit-title",children:"Title"}),a.jsx("input",{id:"task-edit-title",type:"text",value:B,onChange:ke=>P(ke.target.value),placeholder:"Task title...",autoFocus:!0,className:nt.titleInput,"data-testid":"task-edit-title",onKeyDown:ke=>{ke.key==="Enter"&&re&&be()}})]}),a.jsxs("div",{className:nt.section,children:[a.jsx("label",{className:nt.label,htmlFor:"task-edit-description",children:"Description"}),a.jsx("textarea",{id:"task-edit-description",value:X,onChange:ke=>H(ke.target.value),placeholder:"Describe the task... (markdown supported)",className:nt.descriptionTextarea,"data-testid":"task-edit-description",rows:8})]}),a.jsxs("div",{className:nt.section,children:[a.jsx("label",{className:nt.label,htmlFor:"task-edit-persona",children:"Default Persona"}),a.jsxs("select",{id:"task-edit-persona",value:W,onChange:ke=>ie(ke.target.value),className:nt.personaSelect,"data-testid":"task-edit-persona",children:[a.jsx("option",{value:"",children:"(Inherit)"}),p.map(ke=>a.jsx("option",{value:ke.id,children:ke.name},ke.id))]})]}),!x&&a.jsx("div",{className:nt.section,children:a.jsxs("label",{className:nt.depItem,"data-testid":"task-edit-can-decompose",children:[a.jsx("input",{type:"checkbox",checked:L,onChange:ke=>E(ke.target.checked)}),"Can spawn subtasks"]})}),a.jsxs("div",{className:nt.section,children:[a.jsx("div",{className:nt.label,children:"Dependencies"}),de.length===0?a.jsx("div",{className:nt.noDeps,children:"No other tasks in this workspace"}):a.jsx("div",{className:nt.depList,children:de.map(ke=>{const Le=Q.includes(ke.id);return a.jsxs("label",{className:`${nt.depItem} ${Le?nt.depItemSelected:""}`,"data-testid":`dep-option-${ke.id}`,children:[a.jsx("input",{type:"checkbox",checked:Le,onChange:()=>xe(ke.id)}),ke.title,a.jsxs("span",{style:{opacity:.5,fontSize:"11px",marginLeft:"4px"},children:["(",ke.status,")"]})]},ke.id)})})]})]})})]})}const _L="_actionButtons_1rjka_1",xL="_btnPrimary_1rjka_8",kL="_btnDanger_1rjka_39",SL="_btnGhost_1rjka_78",Xt={actionButtons:_L,btnPrimary:xL,btnDanger:kL,btnGhost:SL};function jL({task:t,sessionId:s,isBlocked:o,onStart:r,onResume:c,onStop:d,onPause:u,onDelete:p,onEdit:m}){if(t.status==="not_started")return o?a.jsxs("div",{className:Xt.actionButtons,"data-testid":"task-action-buttons",children:[a.jsx("button",{onClick:m,className:Xt.btnGhost,"data-testid":"task-action-edit",children:"Edit"}),a.jsx("button",{onClick:p,className:Xt.btnDanger,"data-testid":"task-action-delete",children:"Delete"})]}):a.jsxs("div",{className:Xt.actionButtons,"data-testid":"task-action-buttons",children:[a.jsx("button",{"data-testid":"task-header-start",onClick:r,className:Xt.btnPrimary,children:"Start"}),a.jsx("button",{onClick:m,className:Xt.btnGhost,"data-testid":"task-action-edit",children:"Edit"}),a.jsx("button",{onClick:p,className:Xt.btnDanger,"data-testid":"task-action-delete",children:"Delete"})]});if(t.status==="working")return a.jsxs("div",{className:Xt.actionButtons,"data-testid":"task-action-buttons",children:[a.jsx("button",{onClick:d,className:Xt.btnDanger,"data-testid":"task-action-stop",children:"Stop"}),a.jsx("button",{onClick:u,disabled:!s,className:Xt.btnGhost,"data-testid":"task-action-pause",children:"Pause"})]});if(t.status==="paused")return a.jsxs("div",{className:Xt.actionButtons,"data-testid":"task-action-buttons",children:[a.jsx("button",{onClick:d,className:Xt.btnPrimary,"data-testid":"task-action-stop",children:"Stop"}),a.jsx("button",{onClick:c,className:Xt.btnGhost,"data-testid":"task-action-resume",children:"Resume"}),a.jsx("button",{onClick:p,className:Xt.btnDanger,"data-testid":"task-action-delete",children:"Delete"})]});if(t.status==="complete")return a.jsx("div",{className:Xt.actionButtons,"data-testid":"task-action-buttons",children:a.jsx("button",{onClick:p,className:Xt.btnDanger,"data-testid":"task-action-delete",children:"Delete"})});if(t.status==="failed")return a.jsxs("div",{className:Xt.actionButtons,"data-testid":"task-action-buttons",children:[a.jsx("button",{onClick:r,className:Xt.btnPrimary,"data-testid":"task-header-start",children:"Retry"}),a.jsx("button",{onClick:p,className:Xt.btnDanger,"data-testid":"task-action-delete",children:"Delete"})]})}const TL="_workpadSection_y8nj9_1",wL="_workpadLabel_y8nj9_9",NL="_workpadStatus_y8nj9_17",CL="_workpadSummary_y8nj9_23",EL="_workpadExtra_y8nj9_29",qa={workpadSection:TL,workpadLabel:wL,workpadStatus:NL,workpadSummary:CL,workpadExtra:EL};function AL({workpad:t}){if(!t)return;let s;try{const o=JSON.parse(t);if(o==null||typeof o!="object"||Array.isArray(o))return;s=o}catch{return a.jsxs("div",{className:qa.workpadSection,"data-testid":"workpad-panel",children:[a.jsx("div",{className:qa.workpadLabel,children:"Workpad"}),a.jsx("div",{className:qa.workpadExtra,children:t})]})}if(!(!s.status&&!s.summary&&!s.extra))return a.jsxs("div",{className:qa.workpadSection,"data-testid":"workpad-panel",children:[a.jsx("div",{className:qa.workpadLabel,children:"Workpad"}),s.status&&a.jsx("div",{className:qa.workpadStatus,"data-testid":"workpad-status",children:s.status}),s.summary&&a.jsx("div",{className:qa.workpadSummary,"data-testid":"workpad-summary",children:s.summary}),s.extra&&Object.keys(s.extra).length>0&&a.jsx("div",{className:qa.workpadExtra,"data-testid":"workpad-extra",children:JSON.stringify(s.extra,null,2)})]})}const DL="_overviewDashboard_r05qm_1",RL="_overviewHero_r05qm_7",ML="_statusBadge_r05qm_14",IL="_statusPending_r05qm_26",OL="_statusAssigned_r05qm_31",BL="_statusInProgress_r05qm_36",LL="_statusReview_r05qm_41",zL="_statusDone_r05qm_46",$L="_statusFailed_r05qm_51",PL="_statusWaitingInput_r05qm_56",UL="_overviewBranchPill_r05qm_61",HL="_branchLink_r05qm_76",VL="_overviewSection_r05qm_87",qL="_overviewLabel_r05qm_93",GL="_overviewValue_r05qm_100",FL="_overviewMuted_r05qm_105",ZL="_overviewMarkdown_r05qm_111",KL="_envRow_r05qm_180",YL="_envDot_r05qm_186",JL="_envDotGreen_r05qm_193",WL="_envDotYellow_r05qm_197",XL="_envDotRed_r05qm_201",QL="_envDotGray_r05qm_205",e8="_depList_r05qm_209",t8="_depItem_r05qm_215",n8="_depBlocked_r05qm_222",s8="_depDone_r05qm_226",a8="_timeline_r05qm_230",i8="_timelineRow_r05qm_236",o8="_timelineKey_r05qm_243",r8="_timelineValue_r05qm_249",l8="_timelineDelta_r05qm_253",c8="_reviewNotes_r05qm_264",ye={overviewDashboard:DL,overviewHero:RL,statusBadge:ML,statusPending:IL,statusAssigned:OL,statusInProgress:BL,statusReview:LL,statusDone:zL,statusFailed:$L,statusWaitingInput:PL,overviewBranchPill:UL,branchLink:HL,overviewSection:VL,overviewLabel:qL,overviewValue:GL,overviewMuted:FL,overviewMarkdown:ZL,envRow:KL,envDot:YL,envDotGreen:JL,envDotYellow:WL,envDotRed:XL,envDotGray:QL,depList:e8,depItem:t8,depBlocked:n8,depDone:s8,timeline:a8,timelineRow:i8,timelineKey:o8,timelineValue:r8,timelineDelta:l8,reviewNotes:c8};function Jc(t){if(!t)return"—";const s=new Date(t);return isNaN(s.getTime())?"—":s.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"})}function Bp(t,s){if(!t||!s)return;const o=new Date(s).getTime()-new Date(t).getTime();if(isNaN(o)||o<0)return;const r=Math.floor(o/6e4),c=Math.floor(o%6e4/1e3);if(r===0)return`${c}s`;const d=Math.floor(r/60),u=r%60;return d===0?`${r}m ${c}s`:`${d}h ${u}m`}function r_(t){const s=t.toLowerCase();return s==="ready"||s==="running"||s==="available"||s==="connected"?ye.envDotGreen:s==="provisioning"||s==="starting"||s==="pending"||s==="connecting"?ye.envDotYellow:s==="error"||s==="failed"||s==="disconnected"?ye.envDotRed:ye.envDotGray}function d8({status:t}){const s=Ja(t),o=BT(t);return a.jsx("span",{className:`${ye.statusBadge} ${ye[o]??ye.statusPending}`,"data-testid":"task-overview-status-badge",children:s.label})}function u8({task:t,tasksById:s,environments:o,workspaces:r,taskSessions:c,selectedEnvId:d,taskUsage:u,treeUsage:p}){const m=c.length>0?c[c.length-1]:void 0,g=(m==null?void 0:m.environmentId)??"",v=g?o.find(S=>S.id===g):void 0,_=r.find(S=>S.id===t.workspaceId),b=o.find(S=>S.id===d),x=t.branch&&(_!=null&&_.repoUrl)?`${_.repoUrl.replace(/\/$/,"")}/tree/${encodeURIComponent(t.branch)}`:void 0;return a.jsxs("div",{className:ye.overviewDashboard,"data-testid":"task-overview-panel",children:[a.jsxs("div",{className:ye.overviewHero,children:[a.jsx(d8,{status:t.status}),t.branch&&a.jsx("span",{className:ye.overviewBranchPill,"data-testid":"task-overview-branch",children:x?a.jsxs("a",{href:x,target:"_blank",rel:"noreferrer noopener",className:ye.branchLink,children:["🔗"," ",t.branch]}):a.jsxs("span",{children:["🔗"," ",t.branch]})})]}),typeof t.description=="string"&&t.description&&a.jsxs("div",{className:ye.overviewSection,"data-testid":"task-overview-description",children:[a.jsx("div",{className:ye.overviewLabel,children:"Description"}),a.jsx("div",{className:ye.overviewMarkdown,children:a.jsx(Ad,{remarkPlugins:[Dd],children:t.description})})]}),t.workpad&&a.jsx(AL,{workpad:t.workpad}),a.jsxs("div",{className:ye.overviewSection,children:[a.jsx("div",{className:ye.overviewLabel,children:"Environment"}),g&&v?a.jsxs("div",{className:ye.envRow,"data-testid":"task-overview-environment",children:[a.jsx("span",{className:`${ye.envDot} ${r_(v.status)}`,title:v.status,"aria-label":`Status: ${v.status}`,role:"img"}),a.jsx("span",{className:ye.overviewValue,children:v.displayName})]}):b?a.jsxs("div",{className:ye.envRow,"data-testid":"task-overview-environment",children:[a.jsx("span",{className:`${ye.envDot} ${r_(b.status)}`,title:b.status,"aria-label":`Status: ${b.status}`,role:"img"}),a.jsx("span",{className:ye.overviewValue,children:b.displayName}),a.jsx("span",{className:ye.overviewMuted,children:"(workspace default)"})]}):a.jsx("div",{className:ye.overviewMuted,children:"Set in workspace settings"})]}),a.jsxs("div",{className:ye.overviewSection,"data-testid":"task-overview-dependencies",children:[a.jsx("div",{className:ye.overviewLabel,children:"Dependencies"}),t.dependsOn.length===0?a.jsx("div",{className:ye.overviewMuted,children:"None"}):a.jsx("div",{className:ye.depList,children:t.dependsOn.map(S=>{const j=s.get(S),w=(j==null?void 0:j.status)==="complete";return a.jsxs("div",{className:`${ye.depItem} ${w?ye.depDone:ye.depBlocked}`,children:[a.jsx("span",{children:w?"✓":"○"}),a.jsx("span",{children:(j==null?void 0:j.title)??S})]},S)})})]}),a.jsxs("div",{className:ye.overviewSection,"data-testid":"task-overview-timeline",children:[a.jsx("div",{className:ye.overviewLabel,children:"Timeline"}),a.jsxs("div",{className:ye.timeline,children:[t.createdAt&&a.jsxs("div",{className:ye.timelineRow,children:[a.jsx("span",{className:ye.timelineKey,children:"Created"}),a.jsx("span",{className:ye.timelineValue,children:Jc(t.createdAt)})]}),t.assignedAt&&(()=>{const S=Bp(t.createdAt,t.assignedAt);return a.jsxs("div",{className:ye.timelineRow,children:[a.jsx("span",{className:ye.timelineKey,children:"Assigned"}),a.jsx("span",{className:ye.timelineValue,children:Jc(t.assignedAt)}),S!==void 0&&a.jsx("span",{className:ye.timelineDelta,children:S})]})})(),t.startedAt&&(()=>{const S=Bp(t.assignedAt??t.createdAt,t.startedAt);return a.jsxs("div",{className:ye.timelineRow,children:[a.jsx("span",{className:ye.timelineKey,children:"Started"}),a.jsx("span",{className:ye.timelineValue,children:Jc(t.startedAt)}),S!==void 0&&a.jsx("span",{className:ye.timelineDelta,children:S})]})})(),t.completedAt&&(()=>{const S=Bp(t.startedAt,t.completedAt);return a.jsxs("div",{className:ye.timelineRow,children:[a.jsx("span",{className:ye.timelineKey,children:"Completed"}),a.jsx("span",{className:ye.timelineValue,children:Jc(t.completedAt)}),S!==void 0&&a.jsx("span",{className:ye.timelineDelta,children:S})]})})(),!t.createdAt&&!t.assignedAt&&!t.startedAt&&!t.completedAt&&a.jsx("div",{className:ye.overviewMuted,children:"No timing data"})]})]}),u&&u.costMillicents>0&&a.jsxs("div",{className:ye.overviewSection,"data-testid":"task-overview-usage",children:[a.jsx("div",{className:ye.overviewLabel,children:"Usage"}),a.jsxs("div",{className:ye.timeline,children:[a.jsxs("div",{className:ye.timelineRow,children:[a.jsx("span",{className:ye.timelineKey,children:"Cost"}),a.jsx("span",{className:ye.timelineValue,children:Ms(u.costMillicents)}),a.jsxs("span",{className:ye.timelineDelta,children:[u.sessionCount," session",u.sessionCount!==1?"s":""]})]}),p&&p.costMillicents>u.costMillicents&&a.jsxs("div",{className:ye.timelineRow,children:[a.jsx("span",{className:ye.timelineKey,children:"Total (incl. subtasks)"}),a.jsx("span",{className:ye.timelineValue,children:Ms(p.costMillicents)}),a.jsxs("span",{className:ye.timelineDelta,children:[p.sessionCount," session",p.sessionCount!==1?"s":""]})]})]})]}),(t.tokenBudget>0||t.costBudgetMillicents>0)&&a.jsxs("div",{className:ye.overviewSection,"data-testid":"task-overview-budget",children:[a.jsx("div",{className:ye.overviewLabel,children:"Budget"}),a.jsxs("div",{className:ye.timeline,children:[t.tokenBudget>0&&a.jsxs("div",{className:ye.timelineRow,children:[a.jsx("span",{className:ye.timelineKey,children:"Tokens"}),a.jsxs("span",{className:ye.timelineValue,children:[zo(((u==null?void 0:u.inputTokens)??0)+((u==null?void 0:u.outputTokens)??0))," / ",zo(t.tokenBudget)]})]}),t.costBudgetMillicents>0&&a.jsxs("div",{className:ye.timelineRow,children:[a.jsx("span",{className:ye.timelineKey,children:"Cost"}),a.jsxs("span",{className:ye.timelineValue,children:[Ms((u==null?void 0:u.costMillicents)??0)," / ",Ms(t.costBudgetMillicents)]})]})]})]}),t.reviewNotes&&a.jsxs("div",{className:ye.overviewSection,"data-testid":"task-overview-review-notes",children:[a.jsx("div",{className:ye.overviewLabel,children:"Review Notes"}),a.jsx("div",{className:ye.reviewNotes,children:t.reviewNotes})]})]})}function f8({plugins:t,loading:s,onSetPluginEnabled:o}){return a.jsxs("div",{className:ge.container,"data-testid":"plugins-panel",children:[a.jsx("h2",{className:ge.heading,children:"Plugins"}),a.jsxs("div",{className:ge.section,children:[a.jsx("p",{className:ge.sectionDescription,children:"Enable or disable optional Grackle plugins. A server restart is required for changes to take effect."}),s&&a.jsx("p",{className:ge.emptyState,children:"Loading plugins..."}),!s&&t.length===0&&a.jsx("p",{className:ge.emptyState,children:"No plugins found."}),!s&&t.map(r=>{const c=r.enabled!==r.loaded;return a.jsxs("div",{className:ge.tokenRow,"data-testid":`plugin-row-${r.name}`,children:[a.jsxs("div",{style:{flex:1},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[a.jsx("span",{className:ge.tokenName,children:r.name}),r.required&&a.jsx("span",{className:ge.tokenBadge,title:"Required — cannot be disabled",children:"required"})]}),a.jsx("div",{className:ge.tokenTarget,children:r.description}),c&&a.jsx("div",{style:{fontSize:"var(--font-size-xs)",color:"var(--accent-yellow)",marginTop:"2px"},"data-testid":`plugin-restart-notice-${r.name}`,children:"Restart Grackle to apply changes"})]}),a.jsx("label",{style:{display:"flex",alignItems:"center",gap:"6px",cursor:r.required?"not-allowed":"pointer"},title:r.required?"Core is required and cannot be disabled":void 0,children:a.jsx("input",{type:"checkbox",checked:r.enabled,disabled:r.required,onChange:d=>o(r.name,d.target.checked),"data-testid":`plugin-toggle-${r.name}`,"aria-label":`Enable or disable ${r.name} plugin`,style:{accentColor:"var(--accent-green)",width:"16px",height:"16px"}})})]},r.name)})]})]})}const p8="_container_legrg_1",m8="_header_legrg_8",h8="_headerTitle_legrg_35",g8="_badge_legrg_44",v8="_headerActions_legrg_54",y8="_body_legrg_61",b8="_formContent_legrg_73",_8="_section_legrg_85",x8="_label_legrg_91",k8="_nameInput_legrg_98",S8="_fieldInput_legrg_131",j8="_adapterSelect_legrg_164",T8="_readOnlyValue_legrg_198",w8="_codespaceSection_legrg_204",N8="_codespaceActions_legrg_210",C8="_creatingHint_legrg_216",E8="_errorHint_legrg_222",A8="_btnPrimary_legrg_235",D8="_btnGhost_legrg_266",ce={container:p8,header:m8,headerTitle:h8,badge:g8,headerActions:v8,body:y8,formContent:b8,section:_8,label:x8,nameInput:k8,fieldInput:S8,adapterSelect:j8,readOnlyValue:T8,codespaceSection:w8,codespaceActions:N8,creatingHint:C8,errorHint:E8,btnPrimary:A8,btnGhost:D8},dd=1,ud=65535;function Lp(t){if(!t.trim())return!0;const s=Number(t);return Number.isInteger(s)&&s>=dd&&s<=ud}function zp(t){try{const s=JSON.parse(t);if(typeof s=="object"&&s!==null&&!Array.isArray(s))return s}catch{}return{}}function R8({codespaceName:t,onCodespaceNameChange:s,envName:o,onEnvNameChange:r,codespaces:c,codespaceError:d,codespaceListError:u,codespaceCreating:p,onCreateCodespace:m}){const[g,v]=y.useState("pick"),[_,b]=y.useState(""),[x,S]=y.useState("");return g==="create"?a.jsxs("div",{className:ce.codespaceSection,children:[a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,children:"Repository"}),a.jsx("input",{type:"text",value:_,onChange:j=>b(j.target.value),placeholder:"owner/repo",className:ce.fieldInput,"data-testid":"env-codespace-repo"})]}),a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,children:"Machine Type"}),a.jsx("input",{type:"text",value:x,onChange:j=>S(j.target.value),placeholder:"Machine type (optional)...",className:ce.fieldInput,"data-testid":"env-codespace-machine"})]}),a.jsxs("div",{className:ce.codespaceActions,children:[a.jsx("button",{onClick:()=>{_.trim()&&(m(_.trim(),x.trim()||void 0),v("pick"),b(""),S(""))},disabled:!_.trim(),className:ce.btnPrimary,children:"Create"}),a.jsx("button",{onClick:()=>{v("pick"),b(""),S("")},className:ce.btnGhost,children:"Cancel"})]})]}):a.jsx("div",{className:ce.codespaceSection,children:a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,children:"Codespace"}),!u&&a.jsxs("select",{value:t,onChange:j=>{j.target.value==="__create__"?(v("create"),s("")):(s(j.target.value),j.target.value&&!o.trim()&&r(j.target.value))},disabled:p,className:ce.adapterSelect,"data-testid":"env-codespace-select",children:[a.jsx("option",{value:"",children:"Select a codespace..."}),c.map(j=>a.jsxs("option",{value:j.name,children:[j.name," (",j.repository,") — ",j.state]},j.name)),a.jsx("option",{value:"__create__",children:"Create new from repo..."})]}),p&&a.jsx("span",{className:ce.creatingHint,children:"Creating codespace..."}),u&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:ce.errorHint,children:u}),a.jsx("input",{type:"text",value:t,onChange:j=>s(j.target.value),placeholder:"Or enter codespace name manually...",className:ce.fieldInput,"data-testid":"env-codespace-manual"})]}),d&&!u&&a.jsx("span",{className:ce.errorHint,children:d})]})})}function X1({mode:t,environmentId:s,environments:o,onAddEnvironment:r,onUpdateEnvironment:c,onListCodespaces:d,codespaces:u,codespaceError:p,codespaceListError:m,codespaceCreating:g,onCreateCodespace:v,onShowToast:_}){const b=ct(),x=t==="edit",S=x&&s?o.find(fe=>fe.id===s):void 0,[j,w]=y.useState(""),[T,C]=y.useState("local"),[D,O]=y.useState(""),[A,I]=y.useState(""),[$,B]=y.useState(""),[P,X]=y.useState(""),[H,Q]=y.useState(""),[he,W]=y.useState(""),[ie,L]=y.useState(""),[E,J]=y.useState(null),me=y.useCallback(()=>{const fe={};if(T==="local"){if(D.trim()&&(fe.host=D.trim()),A.trim()){const _e=Number(A);Number.isInteger(_e)&&(fe.port=_e)}}else if(T==="ssh"){if(fe.host=D.trim(),$.trim()&&(fe.user=$.trim()),A.trim()){const _e=Number(A);Number.isInteger(_e)&&(fe.sshPort=_e)}P.trim()&&(fe.identityFile=P.trim())}else T==="docker"?(H.trim()&&(fe.image=H.trim()),he.trim()&&(fe.repo=he.trim())):T==="codespace"&&(fe.codespaceName=ie.trim());return fe},[T,D,A,$,P,H,he,ie]),q=()=>!(!j.trim()||T==="ssh"&&!D.trim()||T==="codespace"&&!ie.trim()||(T==="local"||T==="ssh")&&!Lp(A)),de=()=>{q()&&(r(j.trim(),T,me()),_==null||_("Environment added successfully","success"),b(Lo,{replace:!0}))},re=()=>{b(s?Mi(s):Lo)},xe=y.useCallback((fe,_e)=>{if(!S||!s)return;const ke=zp(S.adapterConfig),Le=_e.trim();Le?ke[fe]=Le:delete ke[fe],c(s,{adapterConfig:ke})},[S,s,c]),be=y.useCallback((fe,_e)=>{if(!S||!s)return;const ke=zp(S.adapterConfig);if(_e.trim()){const Le=Number(_e);Number.isInteger(Le)&&Le>=dd&&Le<=ud&&(ke[fe]=Le)}else delete ke[fe];c(s,{adapterConfig:ke})},[S,s,c]);if(x){if(!S)return a.jsxs("div",{className:ce.container,children:[a.jsxs("div",{className:ce.header,children:[a.jsx("div",{className:ce.headerTitle,children:a.jsx("span",{className:ce.badge,children:"edit environment"})}),a.jsx("div",{className:ce.headerActions,children:a.jsx("button",{onClick:re,className:ce.btnGhost,children:"Back"})})]}),a.jsx("div",{className:ce.body,children:a.jsx("div",{className:ce.formContent,children:a.jsx("span",{className:ce.readOnlyValue,children:"Environment not found"})})})]});const fe=zp(S.adapterConfig);return a.jsxs("div",{className:ce.container,"data-testid":"env-edit-panel",children:[a.jsxs("div",{className:ce.header,children:[a.jsx("div",{className:ce.headerTitle,children:a.jsx("span",{className:ce.badge,children:"edit environment"})}),a.jsx("div",{className:ce.headerActions,children:a.jsx("button",{onClick:re,className:ce.btnGhost,"data-testid":"env-edit-back",children:"Back"})})]}),a.jsx("div",{className:ce.body,children:a.jsxs("div",{className:ce.formContent,children:[a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,children:"Name"}),a.jsx(Zt,{value:S.displayName,onSave:_e=>{s&&c(s,{displayName:_e})},validate:_e=>_e.trim()===""?"Name cannot be empty":void 0,mode:"edit",fieldId:"name",activeFieldId:E,onActivate:J,placeholder:"Environment name",ariaLabel:"Environment name","data-testid":"env-edit-name"})]}),a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,children:"Adapter Type"}),a.jsx("span",{className:ce.readOnlyValue,"data-testid":"env-edit-adapter-type",children:S.adapterType})]}),S.adapterType==="local"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,children:"Host"}),a.jsx(Zt,{value:String(fe.host??""),onSave:_e=>xe("host",_e),mode:"edit",fieldId:"host",activeFieldId:E,onActivate:J,placeholder:"(default)",ariaLabel:"Host","data-testid":"env-edit-host"})]}),a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,children:"Port"}),a.jsx(Zt,{value:String(fe.port??""),onSave:_e=>be("port",_e),validate:_e=>Lp(_e)?void 0:"Port must be 1-65535",mode:"edit",fieldId:"port",activeFieldId:E,onActivate:J,placeholder:"(default)",ariaLabel:"Port","data-testid":"env-edit-port"})]})]}),S.adapterType==="ssh"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,children:"Host"}),a.jsx(Zt,{value:String(fe.host??""),onSave:_e=>xe("host",_e),validate:_e=>_e.trim()===""?"Host is required":void 0,mode:"edit",fieldId:"host",activeFieldId:E,onActivate:J,placeholder:"hostname or IP",ariaLabel:"Host","data-testid":"env-edit-host"})]}),a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,children:"User"}),a.jsx(Zt,{value:String(fe.user??""),onSave:_e=>xe("user",_e),mode:"edit",fieldId:"user",activeFieldId:E,onActivate:J,placeholder:"(default)",ariaLabel:"User","data-testid":"env-edit-user"})]}),a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,children:"SSH Port"}),a.jsx(Zt,{value:String(fe.sshPort??""),onSave:_e=>be("sshPort",_e),validate:_e=>Lp(_e)?void 0:"Port must be 1-65535",mode:"edit",fieldId:"sshPort",activeFieldId:E,onActivate:J,placeholder:"22",ariaLabel:"SSH Port","data-testid":"env-edit-ssh-port"})]}),a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,children:"Identity File"}),a.jsx(Zt,{value:String(fe.identityFile??""),onSave:_e=>xe("identityFile",_e),mode:"edit",fieldId:"identityFile",activeFieldId:E,onActivate:J,placeholder:"~/.ssh/id_rsa",ariaLabel:"Identity File","data-testid":"env-edit-identity-file"})]})]}),S.adapterType==="docker"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,children:"Image"}),a.jsx(Zt,{value:String(fe.image??""),onSave:_e=>xe("image",_e),mode:"edit",fieldId:"image",activeFieldId:E,onActivate:J,placeholder:"(default)",ariaLabel:"Image","data-testid":"env-edit-image"})]}),a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,children:"Repo"}),a.jsx(Zt,{value:String(fe.repo??""),onSave:_e=>xe("repo",_e),mode:"edit",fieldId:"repo",activeFieldId:E,onActivate:J,placeholder:"(none)",ariaLabel:"Repo","data-testid":"env-edit-repo"})]})]}),S.adapterType==="codespace"&&a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,children:"Codespace Name"}),a.jsx(Zt,{value:String(fe.codespaceName??""),onSave:_e=>xe("codespaceName",_e),validate:_e=>_e.trim()===""?"Codespace name is required":void 0,mode:"edit",fieldId:"codespaceName",activeFieldId:E,onActivate:J,placeholder:"codespace-name",ariaLabel:"Codespace Name","data-testid":"env-edit-codespace-name"})]})]})})]})}return a.jsxs("div",{className:ce.container,"data-testid":"env-create-panel",children:[a.jsxs("div",{className:ce.header,children:[a.jsx("div",{className:ce.headerTitle,children:a.jsx("span",{className:ce.badge,children:"new environment"})}),a.jsxs("div",{className:ce.headerActions,children:[a.jsx("button",{onClick:de,disabled:!q(),className:ce.btnPrimary,"data-testid":"env-create-submit",children:"Create"}),a.jsx("button",{onClick:re,className:ce.btnGhost,children:"Cancel"})]})]}),a.jsx("div",{className:ce.body,children:a.jsxs("div",{className:ce.formContent,children:[a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,htmlFor:"env-create-name",children:"Name"}),a.jsx("input",{id:"env-create-name",type:"text",value:j,onChange:fe=>w(fe.target.value),placeholder:"Environment name...",autoFocus:!0,className:ce.nameInput,"data-testid":"env-create-name",onKeyDown:fe=>{fe.key==="Enter"&&q()&&de()}})]}),a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,htmlFor:"env-create-adapter",children:"Adapter Type"}),a.jsxs("select",{id:"env-create-adapter",value:T,onChange:fe=>{C(fe.target.value),fe.target.value==="codespace"&&d()},className:ce.adapterSelect,"data-testid":"env-create-adapter",children:[a.jsx("option",{value:"local",children:"local"}),a.jsx("option",{value:"ssh",children:"ssh"}),a.jsx("option",{value:"docker",children:"docker"}),a.jsx("option",{value:"codespace",children:"codespace"})]})]}),T==="local"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,htmlFor:"env-create-host",children:"Host"}),a.jsx("input",{id:"env-create-host",type:"text",value:D,onChange:fe=>O(fe.target.value),placeholder:"Host (optional)...",className:ce.fieldInput,"data-testid":"env-create-host"})]}),a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,htmlFor:"env-create-port",children:"Port"}),a.jsx("input",{id:"env-create-port",type:"number",min:dd,max:ud,value:A,onChange:fe=>I(fe.target.value),placeholder:"Port (optional)...",className:ce.fieldInput,"data-testid":"env-create-port"})]})]}),T==="ssh"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,htmlFor:"env-create-host",children:"Host"}),a.jsx("input",{id:"env-create-host",type:"text",value:D,onChange:fe=>O(fe.target.value),placeholder:"Host (required)...",className:ce.fieldInput,"data-testid":"env-create-host"})]}),a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,htmlFor:"env-create-user",children:"User"}),a.jsx("input",{id:"env-create-user",type:"text",value:$,onChange:fe=>B(fe.target.value),placeholder:"User (optional)...",className:ce.fieldInput,"data-testid":"env-create-user"})]}),a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,htmlFor:"env-create-port",children:"SSH Port"}),a.jsx("input",{id:"env-create-port",type:"number",min:dd,max:ud,value:A,onChange:fe=>I(fe.target.value),placeholder:"SSH port (optional)...",className:ce.fieldInput,"data-testid":"env-create-port"})]}),a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,htmlFor:"env-create-identity",children:"Identity File"}),a.jsx("input",{id:"env-create-identity",type:"text",value:P,onChange:fe=>X(fe.target.value),placeholder:"Identity file (optional)...",className:ce.fieldInput,"data-testid":"env-create-identity"})]})]}),T==="docker"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,htmlFor:"env-create-image",children:"Image"}),a.jsx("input",{id:"env-create-image",type:"text",value:H,onChange:fe=>Q(fe.target.value),placeholder:"Image (optional)...",className:ce.fieldInput,"data-testid":"env-create-image"})]}),a.jsxs("div",{className:ce.section,children:[a.jsx("label",{className:ce.label,htmlFor:"env-create-repo",children:"Repo"}),a.jsx("input",{id:"env-create-repo",type:"text",value:he,onChange:fe=>W(fe.target.value),placeholder:"Repo (optional)...",className:ce.fieldInput,"data-testid":"env-create-repo"})]})]}),T==="codespace"&&a.jsx(R8,{codespaceName:ie,onCodespaceNameChange:L,envName:j,onEnvNameChange:w,codespaces:u,codespaceError:p,codespaceListError:m,codespaceCreating:g,onCreateCodespace:v})]})})]})}const M8="_group_1iprv_1",I8="_groupTitle_1iprv_8",O8="_shortcutList_1iprv_17",B8="_shortcutRow_1iprv_23",L8="_keys_1iprv_36",z8="_kbd_1iprv_43",$8="_description_1iprv_60",Ti={group:M8,groupTitle:I8,shortcutList:O8,shortcutRow:B8,keys:L8,kbd:z8,description:$8},P8=[{title:"Global",shortcuts:[{keys:["?"],description:"Open keyboard shortcuts reference"},{keys:["N"],description:"Create a new task"},{keys:["Escape"],description:"Close dialog or cancel editing"}]},{title:"Task Page",shortcuts:[{keys:["1"],description:"Switch to Overview tab"},{keys:["2"],description:"Switch to Stream tab"},{keys:["3"],description:"Switch to Findings tab"}]},{title:"Workspace Page",shortcuts:[{keys:["1"],description:"Switch to Graph view"},{keys:["2"],description:"Switch to Board view"},{keys:["3"],description:"Switch to Tasks view"}]},{title:"Navigation Lists",shortcuts:[{keys:["←"],description:"Previous tab (horizontal nav)"},{keys:["→"],description:"Next tab (horizontal nav)"},{keys:["↑"],description:"Previous item (vertical nav)"},{keys:["↓"],description:"Next item (vertical nav)"},{keys:["J"],description:"Next item (alias for arrow down/right)"},{keys:["K"],description:"Previous item (alias for arrow up/left)"},{keys:["Home"],description:"Jump to first item"},{keys:["End"],description:"Jump to last item"}]},{title:"Editing",shortcuts:[{keys:["Enter"],description:"Activate / save inline edit"},{keys:["Space"],description:"Activate button or start editing"},{keys:["Escape"],description:"Cancel edit and discard changes"}]},{title:"Chat",shortcuts:[{keys:["Enter"],description:"Send message (when input is focused)"}]}];function U8(){return a.jsxs("section",{className:ge.section,"data-testid":"keyboard-shortcuts-panel",children:[a.jsx("h3",{className:ge.sectionTitle,children:"Keyboard Shortcuts"}),a.jsx("p",{className:ge.sectionDescription,children:"Keyboard shortcuts for navigating and interacting with Grackle. Global shortcuts are suppressed while typing in text fields."}),P8.map(t=>a.jsxs("div",{className:Ti.group,children:[a.jsx("h4",{className:Ti.groupTitle,children:t.title}),a.jsx("div",{className:Ti.shortcutList,children:t.shortcuts.map(s=>a.jsxs("div",{className:Ti.shortcutRow,children:[a.jsx("span",{className:Ti.keys,children:s.keys.map(o=>a.jsx("kbd",{className:Ti.kbd,children:o},o))}),a.jsx("span",{className:Ti.description,children:s.description})]},s.description))})]},t.title))]})}const H8=[{key:"claude",label:"Claude",description:"Forward Claude credentials for AI agent access.",options:[{value:"off",label:"Off"},{value:"subscription",label:"Subscription"},{value:"api_key",label:"API Key"}]},{key:"github",label:"GitHub",description:"Forward GITHUB_TOKEN and GH_TOKEN for git operations.",options:[{value:"off",label:"Off"},{value:"on",label:"On"}]},{key:"copilot",label:"Copilot",description:"Forward Copilot tokens (COPILOT_GITHUB_TOKEN, CLI config).",options:[{value:"off",label:"Off"},{value:"on",label:"On"}]},{key:"codex",label:"Codex",description:"Forward OPENAI_API_KEY for Codex/OpenAI access.",options:[{value:"off",label:"Off"},{value:"on",label:"On"}]},{key:"goose",label:"Goose",description:"Forward Goose config and API keys for Goose agent access.",options:[{value:"off",label:"Off"},{value:"on",label:"On"}]}];function V8({credentialProviders:t,onUpdateCredentialProviders:s}){const o=(r,c)=>{const d={...t};r==="claude"?d.claude=c:d[r]=c,s(d)};return a.jsxs("section",{className:ge.section,children:[a.jsx("h3",{className:ge.sectionTitle,children:"Credential Providers"}),a.jsx("p",{className:ge.sectionDescription,children:"Enable providers to automatically forward credentials to environments at task start. Credentials are read fresh from the host each time."}),a.jsx("div",{className:ge.tokenList,children:H8.map(r=>a.jsxs("div",{className:ge.tokenRow,children:[a.jsx("span",{className:ge.tokenName,children:r.label}),a.jsx("span",{className:ge.tokenTarget,children:r.description}),a.jsx("select",{className:ge.select,value:t[r.key],onChange:c=>o(r.key,c.target.value),children:r.options.map(c=>a.jsx("option",{value:c.value,children:c.label},c.value))})]},r.key))})]})}const q8="_container_10efq_1",G8="_header_10efq_7",F8="_list_10efq_105",Z8="_card_10efq_111",K8="_cardHeader_10efq_125",Y8="_cardTitle_10efq_135",J8="_defaultBadge_10efq_141",W8="_cardActions_10efq_155",X8="_description_10efq_160",Q8="_meta_10efq_166",e7="_empty_10efq_212",t7="_typeBadge_10efq_362",ss={container:q8,header:G8,list:F8,card:Z8,cardHeader:K8,cardTitle:Y8,defaultBadge:J8,cardActions:W8,description:X8,meta:Q8,empty:e7,typeBadge:t7};function n7({personas:t,appDefaultPersonaId:s,onDeletePersona:o,onSetAppDefaultPersonaId:r,onNavigateToNew:c,onNavigateToPersona:d}){const[u,p]=y.useState(null),m=u?t.find(v=>v.id===u):void 0,g=async v=>{await o(v),p(null)};return a.jsxs("div",{className:ss.container,children:[a.jsxs("div",{className:ss.header,children:[a.jsx("h2",{children:"Personas"}),a.jsx(on,{variant:"primary",size:"md",onClick:c,"data-testid":"persona-new-button",children:"+ New Persona"})]}),t.length===0?a.jsx("p",{className:ss.empty,children:"No personas yet. Create one to get started."}):a.jsx("div",{className:ss.list,children:t.map(v=>{const _=s===v.id,b=v.type==="script";return a.jsxs("div",{className:ss.card,"data-testid":`persona-card-${v.id}`,onClick:()=>d(v.id),role:"button",tabIndex:0,onKeyDown:x=>{x.currentTarget===x.target&&(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),d(v.id))},children:[a.jsxs("div",{className:ss.cardHeader,children:[a.jsxs("span",{className:ss.cardTitle,children:[a.jsx("strong",{children:v.name}),a.jsx("span",{className:ss.typeBadge,"data-testid":`persona-type-badge-${v.id}`,children:b?"Script":"Agent"}),_&&a.jsx("span",{className:ss.defaultBadge,"data-testid":`persona-default-badge-${v.id}`,children:"App Default"})]}),a.jsxs("div",{className:ss.cardActions,onClick:x=>x.stopPropagation(),children:[!_&&a.jsx(on,{variant:"ghost",size:"sm",onClick:()=>{r(v.id).catch(()=>{})},"data-testid":`persona-set-default-${v.id}`,title:"Set as app default persona",children:"Set Default"}),a.jsx(on,{variant:"ghost",size:"sm",onClick:()=>d(v.id),children:"Edit"}),a.jsx(on,{variant:"ghost",size:"sm",onClick:()=>p(v.id),"data-testid":`persona-delete-${v.id}`,children:"Delete"})]})]}),v.description&&a.jsx("p",{className:ss.description,children:v.description}),a.jsxs("div",{className:ss.meta,children:[v.runtime&&a.jsxs("span",{children:["Runtime: ",v.runtime]}),v.model&&a.jsxs("span",{children:["Model: ",v.model]}),v.maxTurns>0&&a.jsxs("span",{children:["Max turns: ",v.maxTurns]})]})]},v.id)})}),a.jsx(Ls,{isOpen:u!==null,title:"Delete Persona?",description:`"${(m==null?void 0:m.name)??""}" will be permanently removed.`,confirmLabel:"Delete",onConfirm:()=>{u&&g(u).catch(()=>{})},onCancel:()=>p(null)})]})}const s7="_container_uy08i_1",a7="_header_uy08i_7",i7="_count_uy08i_13",o7="_presets_uy08i_18",r7="_presetButton_uy08i_24",l7="_filterInput_uy08i_41",c7="_groups_uy08i_53",d7="_group_uy08i_53",u7="_groupHeader_uy08i_68",f7="_groupName_uy08i_77",p7="_groupCount_uy08i_81",m7="_toolList_uy08i_87",h7="_toolItem_uy08i_95",g7="_toolName_uy08i_103",bn={container:s7,header:a7,count:i7,presets:o7,presetButton:r7,filterInput:l7,groups:c7,group:d7,groupHeader:u7,groupName:f7,groupCount:p7,toolList:m7,toolItem:h7,toolName:g7},v7=(()=>{const t=new Map;for(const s of E_){const o=s==="get_version_status"?"version":s.split("_")[0];t.has(o)||t.set(o,[]),t.get(o).push(s)}return[...t.entries()].sort(([s],[o])=>s.localeCompare(o)).map(([s,o])=>({group:s,tools:o.sort()}))})(),y7=[{name:"default",label:"Default",tools:A_},{name:"worker",label:"Worker",tools:U2},{name:"orchestrator",label:"Orchestrator",tools:H2},{name:"admin",label:"Admin",tools:V2}];function l_({selectedTools:t,onChange:s,disabled:o}){const[r,c]=y.useState(""),d=y.useMemo(()=>new Set(t),[t]),u=y.useCallback(v=>{if(o)return;const _=new Set(d);_.has(v)?_.delete(v):_.add(v),s([..._].sort())},[d,s,o]),p=y.useCallback((v,_)=>{if(o)return;const b=new Set(d);for(const x of v)_?b.delete(x):b.add(x);s([...b].sort())},[d,s,o]),m=y.useCallback(v=>{o||s([...v].sort())},[s,o]),g=r.toLowerCase();return a.jsxs("div",{className:bn.container,"data-testid":"mcp-tool-selector",children:[a.jsx("div",{className:bn.header,children:a.jsx("span",{className:bn.count,children:t.length===0?`Using default (${A_.length} tools)`:`${t.length} of ${E_.size} tools selected`})}),a.jsxs("div",{className:bn.presets,"data-testid":"mcp-tool-presets",children:[y7.map(v=>a.jsx("button",{type:"button",className:bn.presetButton,disabled:o,onClick:()=>m(v.tools),"data-testid":`preset-${v.name}`,children:v.label},v.name)),a.jsx("button",{type:"button",className:bn.presetButton,disabled:o,onClick:()=>s([]),"data-testid":"preset-clear",children:"Clear"})]}),a.jsx("input",{type:"text",className:bn.filterInput,placeholder:"Filter tools...",value:r,onChange:v=>c(v.target.value),disabled:o,"data-testid":"mcp-tool-filter"}),a.jsx("div",{className:bn.groups,children:v7.map(({group:v,tools:_})=>{const b=g?_.filter(S=>S.toLowerCase().includes(g)):_;if(b.length===0)return null;const x=b.every(S=>d.has(S));return a.jsxs("div",{className:bn.group,"data-testid":`tool-group-${v}`,children:[a.jsxs("label",{className:bn.groupHeader,children:[a.jsx("input",{type:"checkbox",checked:x,onChange:()=>p(b,x),disabled:o,"data-testid":`group-toggle-${v}`}),a.jsx("span",{className:bn.groupName,children:v}),a.jsxs("span",{className:bn.groupCount,children:["(",b.filter(S=>d.has(S)).length,"/",b.length,")"]})]}),a.jsx("div",{className:bn.toolList,children:b.map(S=>a.jsxs("label",{className:bn.toolItem,children:[a.jsx("input",{type:"checkbox",checked:d.has(S),onChange:()=>u(S),disabled:o,"data-testid":`tool-${S}`}),a.jsx("span",{className:bn.toolName,children:S})]},S))})]},v)})})]})}const b7="_container_1gfuq_1",_7="_header_1gfuq_7",x7="_list_1gfuq_19",k7="_card_1gfuq_25",S7="_cardHeader_1gfuq_40",j7="_cardTitle_1gfuq_46",T7="_statusBadge_1gfuq_56",w7="_enabled_1gfuq_68",N7="_disabled_1gfuq_71",C7="_cardActions_1gfuq_75",E7="_cardMeta_1gfuq_80",A7="_empty_1gfuq_98",as={container:b7,header:_7,list:x7,card:k7,cardHeader:S7,cardTitle:j7,statusBadge:T7,enabled:w7,disabled:N7,cardActions:C7,cardMeta:E7,empty:A7};function D7({schedules:t,personas:s,onDeleteSchedule:o,onToggleEnabled:r,onNavigateToNew:c,onNavigateToSchedule:d}){const[u,p]=y.useState(null),m=u?t.find(b=>b.id===u):void 0,g=async b=>{await o(b),p(null)},v=y.useMemo(()=>{const b=new Map;for(const x of s)b.set(x.id,x.name);return b},[s]),_=b=>v.get(b)??b;return a.jsxs("div",{className:as.container,children:[a.jsxs("div",{className:as.header,children:[a.jsx("h2",{children:"Schedules"}),a.jsx(on,{variant:"primary",size:"md",onClick:c,"data-testid":"schedule-new-button",children:"+ New Schedule"})]}),t.length===0?a.jsx("p",{className:as.empty,"data-testid":"schedule-empty-state",children:"No schedules yet. Create one to run tasks on a recurring cadence."}):a.jsx("div",{className:as.list,children:t.map(b=>a.jsxs("div",{className:as.card,"data-testid":`schedule-card-${b.id}`,onClick:()=>d(b.id),role:"button",tabIndex:0,onKeyDown:x=>{x.currentTarget===x.target&&(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),d(b.id))},children:[a.jsxs("div",{className:as.cardHeader,children:[a.jsxs("span",{className:as.cardTitle,children:[a.jsx("strong",{children:b.title}),a.jsx("span",{className:`${as.statusBadge} ${b.enabled?as.enabled:as.disabled}`,"data-testid":`schedule-status-badge-${b.id}`,children:b.enabled?"Enabled":"Disabled"})]}),a.jsxs("div",{className:as.cardActions,onClick:x=>x.stopPropagation(),children:[a.jsx(on,{variant:"ghost",size:"sm",onClick:()=>{(async()=>{await r(b.id,{enabled:!b.enabled})})().catch(()=>{})},"data-testid":`schedule-toggle-${b.id}`,title:b.enabled?"Disable schedule":"Enable schedule",children:b.enabled?"Disable":"Enable"}),a.jsx(on,{variant:"ghost",size:"sm",onClick:()=>d(b.id),"data-testid":`schedule-edit-${b.id}`,children:"Edit"}),a.jsx(on,{variant:"ghost",size:"sm",onClick:()=>p(b.id),"data-testid":`schedule-delete-${b.id}`,children:"Delete"})]})]}),a.jsxs("div",{className:as.cardMeta,children:[a.jsx("span",{"data-testid":`schedule-expression-${b.id}`,children:b.scheduleExpression}),b.personaId&&a.jsxs("span",{"data-testid":`schedule-persona-${b.id}`,children:["Persona: ",_(b.personaId)]}),a.jsxs("span",{"data-testid":`schedule-last-run-${b.id}`,children:["Last run: ",b.lastRunAt?Ho(b.lastRunAt):"Never"]}),b.enabled&&b.nextRunAt?a.jsxs("span",{"data-testid":`schedule-next-run-${b.id}`,children:["Next run: ",q1(b.nextRunAt)]}):null,b.runCount>0&&a.jsxs("span",{"data-testid":`schedule-run-count-${b.id}`,children:["Runs: ",b.runCount]})]})]},b.id))}),a.jsx(Ls,{isOpen:u!==null,title:"Delete Schedule?",description:`"${(m==null?void 0:m.title)??""}" will be permanently removed. Tasks already created by this schedule will not be affected.`,confirmLabel:"Delete",onConfirm:()=>{u&&g(u).catch(()=>{})},onCancel:()=>p(null)})]})}const R7="_nav_1bhou_1",M7="_tab_1bhou_24",I7="_tabIcon_1bhou_62",O7="_tabActive_1bhou_68",Wc={nav:R7,tab:M7,tabIcon:I7,tabActive:O7},aa=[{path:"credentials",label:"Credentials",icon:a.jsx(eT,{size:At})},{path:"personas",label:"Personas",icon:a.jsx(MT,{size:At})},{path:"schedules",label:"Schedules",icon:a.jsx(Aj,{size:At})},{path:"appearance",label:"Appearance",icon:a.jsx(hT,{size:At})},{path:"shortcuts",label:"Shortcuts",icon:a.jsx(nT,{size:At})},{path:"plugins",label:"Plugins",icon:a.jsx(xT,{size:At})},{path:"about",label:"About",icon:a.jsx(Tm,{size:At})}];function B7(){var u;const t=Yt(),s=ct(),o=y.useRef(null),r=((u=aa.find(p=>{const m=`${Ei}/${p.path}`;return t.pathname===m||t.pathname.startsWith(`${m}/`)}))==null?void 0:u.path)??aa[0].path,c=y.useCallback(p=>{s(`${Ei}/${p}`)},[s]),d=y.useCallback(p=>{var x,S;const m=(x=o.current)==null?void 0:x.querySelectorAll('[role="tab"]');if(!m)return;const g=Array.from(m).findIndex(j=>j===document.activeElement),v=g>=0?g:aa.findIndex(j=>j.path===r);let _=v;if(p.key==="ArrowDown"||p.key==="j"||p.key==="J")p.preventDefault(),_=(v+1)%aa.length;else if(p.key==="ArrowUp"||p.key==="k"||p.key==="K")p.preventDefault(),_=(v-1+aa.length)%aa.length;else if(p.key==="Home")p.preventDefault(),_=0;else if(p.key==="End")p.preventDefault(),_=aa.length-1;else return;const b=aa[_].path;s(`${Ei}/${b}`),(S=m[_])==null||S.focus()},[r,s]);return a.jsx("nav",{className:Wc.nav,ref:o,role:"tablist","aria-orientation":"vertical","aria-label":"Settings",onKeyDown:d,children:aa.map(p=>{const m=p.path===r;return a.jsxs("button",{role:"tab",type:"button","aria-selected":m,tabIndex:m?0:-1,className:`${Wc.tab} ${m?Wc.tabActive:""}`,onClick:()=>c(p.path),children:[a.jsx("span",{className:Wc.tabIcon,"aria-hidden":"true",children:p.icon}),p.label]},p.path)})})}const L7="_container_1dqrb_1",z7="_header_1dqrb_5",$7="_refreshButton_1dqrb_17",P7="_streamRow_1dqrb_32",U7="_selected_1dqrb_49",H7="_systemRow_1dqrb_53 _streamRow_1dqrb_32",V7="_streamIcon_1dqrb_60",q7="_streamName_1dqrb_65",G7="_subscriberBadge_1dqrb_74",F7="_emptyState_1dqrb_88",Z7="_loading_1dqrb_95",_n={container:L7,header:z7,refreshButton:$7,streamRow:P7,selected:U7,systemRow:H7,streamIcon:V7,streamName:q7,subscriberBadge:G7,emptyState:F7,loading:Z7},c_=14;function K7({streams:t,loading:s,streamsLoadError:o=!1,streamsLoadedOnce:r=!0,onRefresh:c}){const d=ct(),u=Yt(),p=Et("/chat/:streamId"),m=p==null?void 0:p.params.streamId,g=!m&&u.pathname===dl,v=[...t].sort((x,S)=>x.name.localeCompare(S.name)),_=y.useCallback(()=>{d(dl)},[d]),b=y.useCallback(x=>{d(PN(x))},[d]);return a.jsxs("div",{className:_n.container,"data-testid":"stream-list",children:[a.jsxs("div",{className:_n.header,children:[a.jsx("span",{children:"Streams"}),c&&a.jsx("button",{className:_n.refreshButton,onClick:c,"aria-label":"Refresh streams","data-testid":"stream-list-refresh",children:a.jsx(TT,{size:12})})]}),a.jsxs("button",{type:"button",className:`${_n.systemRow}${g?` ${_n.selected}`:""}`,onClick:_,"data-testid":"stream-list-system-row","aria-current":g?"page":void 0,children:[a.jsx(B_,{size:c_,className:_n.streamIcon}),a.jsx("span",{className:_n.streamName,children:"System"})]}),s&&v.length===0&&a.jsx("div",{className:_n.loading,children:"Loading..."}),!s&&o&&a.jsx("div",{className:_n.emptyState,"data-testid":"stream-list-error",children:"Unable to load streams"}),!s&&!o&&r&&v.length===0&&a.jsx("div",{className:_n.emptyState,children:"No streams"}),v.map(x=>{const S=m===x.id;return a.jsxs("button",{type:"button",className:`${_n.streamRow}${S?` ${_n.selected}`:""}`,onClick:()=>b(x.id),"data-testid":`stream-list-row-${x.id}`,"aria-current":S?"page":void 0,children:[a.jsx(ST,{size:c_,className:_n.streamIcon}),a.jsx("span",{className:_n.streamName,children:x.name}),x.subscriberCount>0&&a.jsx("span",{className:_n.subscriberBadge,children:x.subscriberCount})]},x.id)})]})}const Y7="_panel_1au81_1",J7="_header_1au81_24",W7="_title_1au81_33",X7="_closeButton_1au81_43",Q7="_body_1au81_57",ez="_section_1au81_63",tz="_sectionLabel_1au81_67",nz="_metaRow_1au81_76",sz="_metaKey_1au81_84",az="_metaValue_1au81_90",iz="_subscriberCard_1au81_99",oz="_subscriberHeader_1au81_107",rz="_sessionLink_1au81_114",lz="_badges_1au81_132",cz="_badgeRw_1au81_150 _badge_1au81_132",dz="_badgeR_1au81_150 _badge_1au81_132",uz="_badgeW_1au81_162 _badge_1au81_132",fz="_badgeAsync_1au81_168 _badge_1au81_132",pz="_badgeSync_1au81_174 _badge_1au81_132",mz="_badgeDetach_1au81_178 _badge_1au81_132",hz="_spawnTag_1au81_184 _badge_1au81_132",gz="_fdNumber_1au81_189",vz="_emptySubscribers_1au81_195",ot={panel:Y7,header:J7,title:W7,closeButton:X7,body:Q7,section:ez,sectionLabel:tz,metaRow:nz,metaKey:sz,metaValue:az,subscriberCard:iz,subscriberHeader:oz,sessionLink:rz,badges:lz,badgeRw:cz,badgeR:dz,badgeW:uz,badgeAsync:fz,badgeSync:pz,badgeDetach:mz,spawnTag:hz,fdNumber:gz,emptySubscribers:vz};function yz({permission:t}){const s=t==="rw"?ot.badgeRw:t==="r"?ot.badgeR:ot.badgeW;return a.jsx("span",{className:s,children:t})}function bz({mode:t}){const s=t==="async"?ot.badgeAsync:t==="detach"?ot.badgeDetach:ot.badgeSync;return a.jsx("span",{className:s,children:t})}function _z({stream:t,onClose:s}){const o=ct();return y.useEffect(()=>{const r=c=>{c.key==="Escape"&&s()};return document.addEventListener("keydown",r),()=>{document.removeEventListener("keydown",r)}},[s]),a.jsxs("div",{className:ot.panel,"data-testid":"stream-detail-panel",children:[a.jsxs("div",{className:ot.header,children:[a.jsx("h3",{className:ot.title,children:t.name}),a.jsx("button",{className:ot.closeButton,onClick:s,"aria-label":"Close stream details",children:"×"})]}),a.jsxs("div",{className:ot.body,children:[a.jsxs("div",{className:ot.section,children:[a.jsx("div",{className:ot.sectionLabel,children:"Overview"}),a.jsxs("div",{className:ot.metaRow,children:[a.jsx("span",{className:ot.metaKey,children:"Stream ID"}),a.jsx("span",{className:ot.metaValue,children:t.id})]}),a.jsxs("div",{className:ot.metaRow,children:[a.jsx("span",{className:ot.metaKey,children:"Subscribers"}),a.jsx("span",{className:ot.metaValue,children:t.subscriberCount})]}),a.jsxs("div",{className:ot.metaRow,children:[a.jsx("span",{className:ot.metaKey,children:"Buffered"}),a.jsxs("span",{className:ot.metaValue,children:[t.messageBufferDepth," msgs"]})]})]}),a.jsxs("div",{className:ot.section,children:[a.jsx("div",{className:ot.sectionLabel,children:"Subscribers"}),t.subscribers.length===0?a.jsx("div",{className:ot.emptySubscribers,children:"No active subscribers"}):t.subscribers.map(r=>a.jsxs("div",{className:ot.subscriberCard,"data-testid":`subscriber-card-${r.subscriptionId}`,children:[a.jsxs("div",{className:ot.subscriberHeader,children:[a.jsxs("span",{className:ot.fdNumber,children:["fd ",r.fd]}),a.jsxs("button",{className:ot.sessionLink,onClick:()=>{o(Ld(r.sessionId))},title:r.sessionId,children:[r.sessionId.slice(0,12),"…"]})]}),a.jsxs("div",{className:ot.badges,children:[a.jsx(yz,{permission:r.permission}),a.jsx(bz,{mode:r.deliveryMode}),r.createdBySpawn&&a.jsx("span",{className:ot.spawnTag,children:"spawn"})]})]},r.subscriptionId))]})]})]})}function xz({tasks:t,taskStatusById:s,sessionStatusByTaskId:o}){const r=new Map;for(const d of t)if(d.parentTaskId){const u=r.get(d.parentTaskId);u?u.push(d):r.set(d.parentTaskId,[d])}const c=new Map(Ty.map(d=>[d,[]]));for(const d of t){const u=vl(d.status),p=d.dependsOn.length>0&&d.dependsOn.some(S=>s.get(S)!=="complete"),m=r.get(d.id)??[],g=m.length,v=m.filter(S=>S.status==="complete").length;let _;if(u==="paused"&&o){const S=o.get(d.id);S==="idle"?_="Needs input":S==="completed"&&(_="Ready to complete")}const b={task:d,isBlocked:p,childCount:g,doneChildCount:v,pausedSubBadge:_},x=c.get(u);x?x.push(b):c.get("not_started").push(b)}for(const d of c.values())d.sort((u,p)=>u.task.sortOrder-p.task.sortOrder);return Ty.map(d=>{const u=Ja(d);return{status:d,label:u.label,style:u,tasks:c.get(d)??[]}})}const kz="_boardContainer_1c4y1_1",Sz="_column_1c4y1_17",jz="_columnHeader_1c4y1_34",Tz="_columnIcon_1c4y1_47",wz="_columnLabel_1c4y1_52",Nz="_columnCount_1c4y1_57",Cz="_cardList_1c4y1_67",Ez="_emptyPlaceholder_1c4y1_76",Az="_card_1c4y1_67",Dz="_cardHeader_1c4y1_107",Rz="_cardStatusIcon_1c4y1_113",Mz="_cardTitle_1c4y1_119",Iz="_cardBadges_1c4y1_127",Oz="_badge_1c4y1_134",Bz="_blockedBadge_1c4y1_146",Lz="_childBadge_1c4y1_151",zz="_depBadge_1c4y1_155",$z="_parentBadge_1c4y1_159",Pz="_pausedSubBadge_1c4y1_166",Uz="_personaBadge_1c4y1_170",Hz="_envBadge_1c4y1_174",Vz="_emptyCta_1c4y1_178",qz="_ctaButton_1c4y1_188",Gz="_ctaDescription_1c4y1_204",lt={boardContainer:kz,column:Sz,columnHeader:jz,columnIcon:Tz,columnLabel:wz,columnCount:Nz,cardList:Cz,emptyPlaceholder:Ez,card:Az,cardHeader:Dz,cardStatusIcon:Rz,cardTitle:Mz,cardBadges:Iz,badge:Oz,blockedBadge:Bz,childBadge:Lz,depBadge:zz,parentBadge:$z,pausedSubBadge:Pz,personaBadge:Uz,envBadge:Hz,emptyCta:Vz,ctaButton:qz,ctaDescription:Gz};function Fz({workspaceId:t,environmentId:s,tasks:o,sessions:r,personas:c,environments:d}){const u=ct(),p=y.useMemo(()=>o.filter(b=>b.workspaceId===t),[o,t]),m=y.useMemo(()=>new Map(o.map(b=>[b.id,b.status])),[o]),g=y.useMemo(()=>new Map(p.map(b=>[b.id,b])),[p]),v=y.useMemo(()=>{const b=new Map(r.map(C=>[C.id,C])),x=new Map(c.map(C=>[C.id,C])),S=new Map(d.map(C=>[C.id,C])),j=new Map,w=new Map,T=new Map;for(const C of p)if(C.latestSessionId){const D=b.get(C.latestSessionId);if(D){if(j.set(C.id,D.endReason||D.status),D.personaId){const O=x.get(D.personaId);O&&w.set(C.id,O.name)}if(D.environmentId){const O=S.get(D.environmentId);O&&T.set(C.id,O.displayName)}}}return{sessionStatusByTaskId:j,personaNameByTaskId:w,environmentNameByTaskId:T}},[p,r,c,d]),_=y.useMemo(()=>xz({tasks:p,taskStatusById:m,sessionStatusByTaskId:v.sessionStatusByTaskId}),[p,m,v]);return p.length===0?a.jsxs("div",{className:lt.emptyCta,"data-testid":"board-empty-cta",children:[a.jsx("button",{className:lt.ctaButton,onClick:()=>u(zi(t,void 0,s)),children:"Create Task"}),a.jsx("div",{className:lt.ctaDescription,children:"Break your work into tasks and let agents tackle them"})]}):a.jsx("div",{className:lt.boardContainer,"data-testid":"board-container",children:_.map(b=>a.jsxs("section",{className:lt.column,"data-testid":`board-column-${b.status}`,"aria-label":`${b.label}, ${b.tasks.length} ${b.tasks.length===1?"task":"tasks"}`,children:[a.jsxs("div",{className:lt.columnHeader,children:[a.jsx("span",{className:lt.columnIcon,style:{color:b.style.color},children:b.style.icon}),a.jsx("span",{className:lt.columnLabel,children:b.label}),a.jsx("span",{className:lt.columnCount,"data-testid":`board-count-${b.status}`,children:b.tasks.length})]}),a.jsx("div",{className:lt.cardList,children:b.tasks.length===0?a.jsx("div",{className:lt.emptyPlaceholder,children:"No tasks"}):a.jsx(ls,{mode:"popLayout",children:b.tasks.map(x=>a.jsx(Nt.div,{layout:!0,initial:{opacity:0,y:4},animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.15},children:a.jsx(Zz,{boardTask:x,tasksById:g,personaName:v.personaNameByTaskId.get(x.task.id),envName:v.environmentNameByTaskId.get(x.task.id),onClick:()=>u($n(x.task.id,void 0,t,s))})},x.task.id))})})]},b.status))})}function Zz({boardTask:t,tasksById:s,personaName:o,envName:r,onClick:c}){const{task:d,isBlocked:u,childCount:p,doneChildCount:m,pausedSubBadge:g}=t,v=Ja(d.status),_=d.parentTaskId?s.get(d.parentTaskId):void 0;return a.jsxs("div",{className:lt.card,tabIndex:0,role:"button","data-testid":`board-card-${d.id}`,onClick:c,onKeyDown:b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),c())},children:[a.jsxs("div",{className:lt.cardHeader,children:[a.jsx("span",{className:lt.cardStatusIcon,style:{color:v.color},children:v.icon}),a.jsx("span",{className:lt.cardTitle,children:d.title})]}),a.jsxs("div",{className:lt.cardBadges,children:[_&&a.jsx("span",{className:`${lt.badge} ${lt.parentBadge}`,title:_.title,children:_.title}),p>0&&a.jsxs("span",{className:`${lt.badge} ${lt.childBadge}`,children:[m,"/",p]}),u&&a.jsx("span",{className:`${lt.badge} ${lt.blockedBadge}`,children:"blocked"}),d.dependsOn.length>0&&!u&&a.jsx("span",{className:`${lt.badge} ${lt.depBadge}`,children:"dep"}),g&&a.jsx("span",{className:`${lt.badge} ${lt.pausedSubBadge}`,children:g}),o&&a.jsx("span",{className:`${lt.badge} ${lt.personaBadge}`,children:o}),r&&a.jsx("span",{className:`${lt.badge} ${lt.envBadge}`,children:r})]})]})}const Kz="_formContent_ymnez_1",Yz="_section_ymnez_13",Jz="_label_ymnez_19",Wz="_titleInput_ymnez_26",Xz="_descriptionTextarea_ymnez_58",Qz="_selectField_ymnez_94",e$="_checkboxRow_ymnez_128",t$="_checkboxLabel_ymnez_141",n$="_fieldError_ymnez_146",xt={formContent:Kz,section:Yz,label:Jz,titleInput:Wz,descriptionTextarea:Xz,selectField:Qz,checkboxRow:e$,checkboxLabel:t$,fieldError:n$};function s$(t,s){return{name:(t==null?void 0:t.name)??"",description:(t==null?void 0:t.description)??"",repoUrl:(t==null?void 0:t.repoUrl)??"",environmentId:(t==null?void 0:t.linkedEnvironmentIds[0])??s??"",defaultPersonaId:(t==null?void 0:t.defaultPersonaId)??"",useWorktrees:(t==null?void 0:t.useWorktrees)??!0,workingDirectory:(t==null?void 0:t.workingDirectory)??""}}const a$=100;function i$({values:t,onChange:s,environments:o,personas:r,errors:c,disabled:d,autoFocusName:u}){const p=(m,g)=>{s({...t,[m]:g})};return a.jsxs("div",{className:xt.formContent,children:[a.jsxs("div",{className:xt.section,children:[a.jsx("label",{className:xt.label,htmlFor:"ws-name",children:"Name"}),a.jsx("input",{id:"ws-name",className:xt.titleInput,type:"text",value:t.name,onChange:m=>p("name",m.target.value),placeholder:"Workspace name",maxLength:a$,autoFocus:u,disabled:d,"data-testid":"workspace-form-name"}),(c==null?void 0:c.name)&&a.jsx("span",{className:xt.fieldError,"data-testid":"workspace-form-error-name",children:c.name})]}),a.jsxs("div",{className:xt.section,children:[a.jsx("label",{className:xt.label,htmlFor:"ws-description",children:"Description"}),a.jsx("textarea",{id:"ws-description",className:xt.descriptionTextarea,value:t.description,onChange:m=>p("description",m.target.value),placeholder:"Optional description (Markdown supported)",disabled:d,"data-testid":"workspace-form-description"})]}),a.jsxs("div",{className:xt.section,children:[a.jsx("label",{className:xt.label,htmlFor:"ws-repo",children:"Repository URL"}),a.jsx("input",{id:"ws-repo",className:xt.titleInput,type:"text",value:t.repoUrl,onChange:m=>p("repoUrl",m.target.value),placeholder:"https://github.com/org/repo",disabled:d,"data-testid":"workspace-form-repo"}),(c==null?void 0:c.repoUrl)&&a.jsx("span",{className:xt.fieldError,"data-testid":"workspace-form-error-repoUrl",children:c.repoUrl})]}),a.jsxs("div",{className:xt.section,children:[a.jsx("label",{className:xt.label,htmlFor:"ws-environment",children:"Environment"}),a.jsxs("select",{id:"ws-environment",className:xt.selectField,value:t.environmentId,onChange:m=>p("environmentId",m.target.value),disabled:d,"data-testid":"workspace-form-environment",children:[a.jsx("option",{value:"",children:"Select environment…"}),o.map(m=>a.jsx("option",{value:m.id,children:m.displayName||m.id},m.id))]}),(c==null?void 0:c.environmentId)&&a.jsx("span",{className:xt.fieldError,"data-testid":"workspace-form-error-environmentId",children:c.environmentId})]}),a.jsxs("div",{className:xt.section,children:[a.jsx("label",{className:xt.label,htmlFor:"ws-persona",children:"Default Persona"}),a.jsxs("select",{id:"ws-persona",className:xt.selectField,value:t.defaultPersonaId,onChange:m=>p("defaultPersonaId",m.target.value),disabled:d,"data-testid":"workspace-form-persona",children:[a.jsx("option",{value:"",children:"(Inherit)"}),r.map(m=>a.jsx("option",{value:m.id,children:m.name},m.id))]})]}),a.jsx("div",{className:xt.section,children:a.jsxs("label",{className:xt.checkboxRow,children:[a.jsx("input",{type:"checkbox",checked:t.useWorktrees,onChange:m=>p("useWorktrees",m.target.checked),disabled:d,"data-testid":"workspace-form-worktrees"}),a.jsx("span",{className:xt.checkboxLabel,children:"Enable worktree isolation"})]})}),a.jsxs("div",{className:xt.section,children:[a.jsx("label",{className:xt.label,htmlFor:"ws-workdir",children:"Working Directory"}),a.jsx("input",{id:"ws-workdir",className:xt.titleInput,type:"text",value:t.workingDirectory,onChange:m=>p("workingDirectory",m.target.value),placeholder:"Default (server default)",disabled:d,"data-testid":"workspace-form-workdir"})]})]})}const Q1=y.createContext(void 0),o$=4e3;function r$({children:t}){const[s,o]=y.useState([]),r=y.useRef(0),c=y.useCallback(u=>{o(p=>p.filter(m=>m.id!==u))},[]),d=y.useCallback((u,p="info",m=o$)=>{const g=`toast-${++r.current}`;o(v=>[...v,{id:g,message:u,variant:p,duration:m}])},[]);return a.jsx(Q1.Provider,{value:{toasts:s,showToast:d,dismissToast:c},children:t})}function gn(){const t=y.useContext(Q1);if(!t)throw new Error("useToast must be used within ToastProvider");return t}const _m="grackle-theme",ek="grackle-prefer-system",tk="(prefers-color-scheme: dark)";let Xr=[],fd;function $p(){fd=void 0;for(const t of Xr)t()}function xm(){return typeof window>"u"?!1:window.matchMedia(tk).matches}function il(){if(typeof localStorage>"u")return o_;try{const t=localStorage.getItem(_m);if(t!==null&&J1.has(t))return t}catch{}return o_}function Nd(){if(typeof localStorage>"u")return!1;try{return localStorage.getItem(ek)==="true"}catch{return!1}}function km(t){return Gd.find(s=>s.variantLightId===t||s.variantDarkId===t)}function nk(t,s){const o=bm(t);if(o!=null&&o.variantDarkId)return s&&o.variantLightId?xm()?o.variantDarkId:o.variantLightId:o.variantDarkId;if(o!=null&&o.hidden&&s){const r=km(t);if(r!=null&&r.variantLightId&&r.variantDarkId)return xm()?r.variantDarkId:r.variantLightId}return t}function Do(t,s,o=!1){o&&document.documentElement.classList.add("no-transitions"),document.documentElement.dataset.theme=nk(t,s),o&&(document.documentElement.offsetHeight,requestAnimationFrame(()=>{document.documentElement.classList.remove("no-transitions")}))}typeof document<"u"&&Do(il(),Nd());function l$(){return fd===void 0&&(fd={themeId:il(),systemDark:xm(),preferSystem:Nd()}),fd}function c$(t){return Xr=[...Xr,t],()=>{Xr=Xr.filter(s=>s!==t)}}function d$(){const t=y.useSyncExternalStore(c$,l$),{themeId:s,preferSystem:o}=t,r=nk(s,o),c=y.useCallback(u=>{if(J1.has(u)){try{localStorage.setItem(_m,u)}catch{}Do(u,Nd(),!0),$p()}},[]),d=y.useCallback(u=>{try{localStorage.setItem(ek,u?"true":"false")}catch{}if(u){const p=il(),m=bm(p);if(m!=null&&m.hidden){const g=km(p);if(g)try{localStorage.setItem(_m,g.id)}catch{}}}Do(il(),u,!0),$p()},[]);return y.useEffect(()=>{Do(s,o)},[s,o]),y.useEffect(()=>{if(typeof window>"u")return;const u=window.matchMedia(tk),p=()=>{const m=il(),g=Nd();if(g){const v=bm(m);if(v!=null&&v.variantDarkId&&v.variantLightId&&Do(m,g),v!=null&&v.hidden){const _=km(m);_!=null&&_.variantDarkId&&_.variantLightId&&Do(m,g)}}$p()};return u.addEventListener("change",p),()=>{u.removeEventListener("change",p)}},[]),{themeId:s,setTheme:c,resolvedThemeId:r,preferSystem:o,setPreferSystem:d}}const sk=y.createContext(void 0);function u$({children:t}){const s=d$();return a.jsx(sk.Provider,{value:s,children:t})}function ak(){const t=y.useContext(sk);if(!t)throw new Error("useThemeContext must be used within ThemeProvider");return t}const ik=y.createContext(void 0),ok=y.createContext(void 0);function f$({children:t}){const[s,o]=y.useState(void 0),r=y.useCallback(c=>{o(c)},[]);return a.jsx(ok.Provider,{value:r,children:a.jsx(ik.Provider,{value:s,children:t})})}function p$(){return y.useContext(ik)}function m$(){const t=y.useContext(ok);if(t===void 0)throw new Error("useSidebarSetter must be used within a SidebarProvider");return t}const vh=y.createContext(void 0);function rt(){const t=y.useContext(vh);if(!t)throw new Error("useGrackle must be used within GrackleProvider");return t}function rk(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function lk(t,s){return console.warn(`[ws] Malformed "${t}" message: ${s}`),!1}function h$(t){return rk(t)&&typeof t.sessionId=="string"&&typeof t.eventType=="string"&&typeof t.timestamp=="string"&&typeof t.content=="string"&&(t.raw===void 0||typeof t.raw=="string")}const g$=new Set(["off","subscription","api_key"]),Xc=new Set(["off","on"]);function v$(t){return rk(t)&&g$.has(t.claude)&&Xc.has(t.github)&&Xc.has(t.copilot)&&Xc.has(t.codex)&&Xc.has(t.goose)}function ck(t){switch(t){case"waiting_input":return"idle";case"completed":return"stopped";case"killed":return"stopped";case"failed":return"stopped";case"interrupted":return"stopped";case"terminated":return"stopped";default:return t}}function dk(t){switch(t){case"completed":return"completed";case"killed":return"killed";case"failed":return"interrupted";case"interrupted":return"interrupted";case"terminated":return"terminated";default:return}}const Ao=5e3;function y$(t,s){const o=[];let r=t;const c=new Set;for(;r&&s.has(r)&&!c.has(r);){c.add(r);const d=s.get(r);o.unshift(d),r=d.parentTaskId||void 0}return o}const ua={label:"Home",url:Ii};function b$(t){return t?[ua,{label:"Settings",url:Ei},{label:t,url:void 0}]:[ua,{label:"Settings",url:void 0}]}const yh={label:"Environments",url:Lo};function _$(){return[ua,{label:"Environments",url:void 0}]}function x$(){return[ua,{label:"New Chat",url:void 0}]}function k$(t){return[ua,{label:`Session ${t.slice(0,8)}`,url:void 0}]}function S$(t,s,o,r){const c=o.find(u=>u.id===t),d=r.find(u=>u.id===s);return[ua,yh,{label:(d==null?void 0:d.displayName)??"Environment",url:Mi(s)},{label:(c==null?void 0:c.name)??"Workspace",url:void 0}]}function j$(t,s,o,r,c){const d=y$(t,c),u=c.get(t),p=u==null?void 0:u.workspaceId,m=p?o.find(x=>x.id===p):void 0,g=s??(m==null?void 0:m.linkedEnvironmentIds[0]),v=g?r.find(x=>x.id===g):void 0,_=[ua];v&&g&&(_.push(yh),_.push({label:v.displayName,url:Mi(g)})),m&&g&&_.push({label:m.name,url:Ri(m.id,g)});for(let x=0;x<d.length-1;x++)_.push({label:d[x].title,url:$n(d[x].id,void 0,p,g)});const b=d[d.length-1];return _.push({label:(b==null?void 0:b.title)??t,url:void 0}),_}const T$={label:"Findings",url:zd};function w$(){return[ua,{label:"Findings",url:void 0}]}function uk(t,s,o,r,c){const d=[ua];if(s&&o){const u=r.find(m=>m.id===s),p=c.find(m=>m.id===o);d.push(yh),p&&d.push({label:p.displayName,url:Mi(o)}),u&&d.push({label:u.name,url:Ri(s,o)}),d.push({label:"Findings",url:HN(s,o)})}else d.push(T$);return d.push({label:t,url:void 0}),d}function bh(t){const s=[];for(const o of t){const r=s[s.length-1];o.eventType==="text"&&(r==null?void 0:r.eventType)==="text"?s[s.length-1]={...r,content:r.content+o.content}:s.push(o)}return s}function Qc(t){if(typeof t.id=="string")return t.id;const s=t.data;if(s&&typeof s.toolCallId=="string")return s.toolCallId;const o=t.item;if(o&&typeof o.id=="string")return o.id}function N$(t){if(typeof t.tool_use_id=="string")return t.tool_use_id;const s=t.data;if(s&&typeof s.toolCallId=="string")return s.toolCallId;const o=t.item;if(o&&typeof o.id=="string")return o.id}function _h(t){const s=new Map;for(const v of t)if(v.raw)try{s.set(v,JSON.parse(v.raw))}catch{}const o=new Map;for(const v of t){if(v.eventType!=="tool_use")continue;const _=s.get(v),b=_?Qc(_):void 0;if(b)try{const x=JSON.parse(v.content);o.set(b,{tool:x.tool,args:x.args})}catch{}}const r=new Set,c=new Set,d=t.map((v,_)=>{if(v.eventType!=="tool_result")return v;const b=s.get(v),x=b?N$(b):void 0;if(!x)return v;const S=o.get(x);if(!S)return v;r.add(x),c.add(_);let j;const w=v.content.trim();if(w.startsWith("{"))try{const T=JSON.parse(w);typeof T.detailedContent=="string"&&(j=T.detailedContent)}catch{}return{...v,toolUseCtx:{...S,detailedResult:j}}}),u=[];for(let v=0;v<d.length;v++){if(d[v].eventType!=="tool_use")continue;const _=s.get(d[v]),b=_?Qc(_):void 0;b&&r.has(b)||u.push(v)}const p=[];for(let v=0;v<d.length;v++)d[v].eventType!=="tool_result"||c.has(v)||p.push(v);let m=0;for(const v of u){for(;m<p.length&&p[m]<v;)m++;if(m>=p.length)break;const _=p[m];if(_!==v+1)continue;const b=d[v],x=d[_];let S;try{const j=JSON.parse(b.content);S={tool:j.tool,args:j.args}}catch{}if(S){let j;const w=x.content.trim();if(w.startsWith("{"))try{const D=JSON.parse(w);typeof D.detailedContent=="string"&&(j=D.detailedContent)}catch{}d[_]={...x,toolUseCtx:{...S,detailedResult:j}},c.add(_);const T=s.get(b),C=T?Qc(T):void 0;C?r.add(C):(r.add(`__seq_${v}`),s.set(b,{...T??{},__seqId:`__seq_${v}`})),m++}}const g=d.filter(v=>{if(v.eventType!=="tool_use")return!0;const _=s.get(v);if(!_)return!0;const b=Qc(_);if(b&&r.has(b))return!1;const x=_.__seqId;return!(x&&r.has(x))});for(let v=0;v<g.length;v++){if(g[v].eventType!=="tool_use")continue;let _=!1;for(let b=v+1;b<g.length;b++)if(g[b].eventType!=="tool_use"){_=!0;break}_&&(g[v]={...g[v],settled:!0})}return g}function C$(t,s,o){const r=t.filter(m=>m.status==="running"||m.status==="idle"||m.status==="waiting").length,c=fk(s),d=s.filter(m=>Sm(m,c)).length,u=s.filter(m=>m.status==="paused"||m.status==="failed"||Sm(m,c)).length,p=o.filter(m=>m.status==="disconnected"||m.status==="error").length;return{activeSessions:r,blockedTasks:d,attentionTasks:u,unhealthyEnvironments:p}}function fk(t){const s=new Map;for(const o of t)s.set(o.id,o.status);return s}function Sm(t,s){return t.dependsOn.some(o=>s.get(o)!=="complete")}function E$(t,s){var u;const o=new Map;for(const p of s)o.set(p.id,p);const r=fk(t),c=[];for(const p of t){const m=p.workspaceId?((u=o.get(p.workspaceId))==null?void 0:u.name)??"Unknown":"Unknown";p.status==="failed"?c.push({task:p,reason:"failed",workspaceName:m}):Sm(p,r)?c.push({task:p,reason:"blocked",workspaceName:m}):p.status==="paused"&&c.push({task:p,reason:"paused",workspaceName:m})}const d={failed:0,blocked:1,paused:2};return c.sort((p,m)=>(d[p.reason]??3)-(d[m.reason]??3)),c}function A$(t,s){const o=new Map;for(const r of s)o.set(r.id,r);return t.filter(r=>r.status==="running"||r.status==="idle"||r.status==="waiting").map(r=>{var c;return{session:r,environmentName:((c=o.get(r.environmentId))==null?void 0:c.displayName)??"Unknown"}})}function D$(t,s,o){const r=new Map;for(const c of s){if(!c.workspaceId)continue;let d=r.get(c.workspaceId);d||(d={totalTasks:0,completedTasks:0,workingTasks:0,failedTasks:0},r.set(c.workspaceId,d)),d.totalTasks+=1,c.status==="complete"?d.completedTasks+=1:c.status==="working"?d.workingTasks+=1:c.status==="failed"&&(d.failedTasks+=1)}return t.map(c=>{const d=r.get(c.id)??{totalTasks:0,completedTasks:0,workingTasks:0,failedTasks:0};return{workspace:c,totalTasks:d.totalTasks,completedTasks:d.completedTasks,workingTasks:d.workingTasks,failedTasks:d.failedTasks}})}const Ds=[{id:"kn-auth-flow",label:"Authentication Flow",kind:"knowledge",category:"concept",content:"The application uses JWT Bearer tokens for stateless authentication. Access tokens expire after 24h. Refresh tokens are stored in the database and rotated on use. The auth middleware verifies tokens and attaches the decoded payload to req.user.",tags:["auth","jwt","security"],workspaceId:"proj-alpha",createdAt:"2026-02-25T10:30:00Z",updatedAt:"2026-02-27T08:15:00Z",val:5},{id:"kn-db-schema",label:"Database Schema",kind:"knowledge",category:"concept",content:"PostgreSQL database with tables: users, sessions, refresh_tokens, audit_log. Uses UUID primary keys, TIMESTAMPTZ for all timestamps, and JSONB for flexible metadata columns. Connection pooling via pg-pool with per-tenant isolation.",tags:["database","postgres","schema"],workspaceId:"proj-alpha",createdAt:"2026-02-23T11:00:00Z",updatedAt:"2026-02-26T22:45:00Z",val:4},{id:"kn-error-handling",label:"Error Response Pattern",kind:"knowledge",category:"concept",content:"All API errors follow the shape { error: string, code: string, details?: unknown }. HTTP status codes map to: 400 (validation), 401 (unauthenticated), 403 (forbidden), 404 (not found), 409 (conflict), 429 (rate limited), 500 (internal).",tags:["api","errors","patterns"],workspaceId:"proj-alpha",createdAt:"2026-02-27T08:17:00Z",updatedAt:"2026-02-27T08:17:00Z",val:3},{id:"kn-rate-limiting",label:"Rate Limiting Strategy",kind:"knowledge",category:"concept",content:"Token-bucket algorithm with in-memory state per client IP. Default rate: 100 requests/minute, burst: 20. Returns 429 with Retry-After header. Redis adapter available for multi-instance deployments.",tags:["api","rate-limiting","infrastructure"],workspaceId:"proj-alpha",createdAt:"2026-02-27T09:00:00Z",updatedAt:"2026-02-27T09:00:00Z",val:2},{id:"kn-etl-pipeline",label:"ETL Pipeline Architecture",kind:"knowledge",category:"concept",content:"Data pipelines follow an Extract-Transform-Load pattern with pluggable stages. Each stage reads from a source (Postgres, S3, API), transforms via configurable mappers, and loads into a target (Parquet, BigQuery, S3). Incremental loads use high-watermark tracking.",tags:["etl","pipeline","architecture"],workspaceId:"proj-beta",createdAt:"2026-02-26T08:00:00Z",updatedAt:"2026-02-27T09:05:00Z",val:4},{id:"kn-parquet-format",label:"Parquet Output Format",kind:"knowledge",category:"concept",content:"Parquet files are written with row-group buffering (configurable batch size, default 10000 rows). Supports Snappy, ZSTD, and GZIP compression. Schema is derived from the internal column type system using Arrow type mapping.",tags:["parquet","data-format","compression"],workspaceId:"proj-beta",createdAt:"2026-02-26T08:05:00Z",updatedAt:"2026-02-26T08:15:00Z",val:3},{id:"kn-jwt-over-session",label:"JWT over Session Auth",kind:"knowledge",category:"decision",content:"Chose JWT tokens over server-side sessions for stateless auth. Rationale: (1) no session store needed, (2) works across microservices without shared state, (3) supports mobile clients natively. Trade-off: tokens can't be revoked instantly (mitigated by short expiry + refresh rotation).",tags:["auth","decision","jwt"],workspaceId:"proj-alpha",createdAt:"2026-02-25T10:00:00Z",updatedAt:"2026-02-25T10:00:00Z",val:3},{id:"kn-pg-pool-decision",label:"pg-pool over Knex",kind:"knowledge",category:"decision",content:"Chose pg-pool over Knex for connection pooling. pg-pool gives direct control over idle timeout, max connections, and health check queries. Knex wraps pg-pool and adds query-building overhead we don't need since we write raw SQL with parameterized queries.",tags:["database","decision","postgres"],workspaceId:"proj-alpha",createdAt:"2026-02-23T11:30:00Z",updatedAt:"2026-02-23T11:30:00Z",val:2},{id:"kn-watermark-decision",label:"Local Watermark Storage",kind:"knowledge",category:"decision",content:"Currently using local SQLite for watermark storage. This works for single-worker pipelines but needs to move to a shared store (Redis or Postgres) for production multi-worker scenarios. Tracked as a follow-up task.",tags:["pipeline","decision","watermarks"],workspaceId:"proj-beta",createdAt:"2026-02-27T09:05:00Z",updatedAt:"2026-02-27T09:05:00Z",val:2},{id:"kn-jwt-middleware",label:"JWT Verify Middleware",kind:"knowledge",category:"snippet",content:`\`\`\`typescript
304
304
  export function verifyToken(req: Request, res: Response, next: NextFunction): void {
305
305
  const header = req.headers.authorization;
306
306
  if (!header?.startsWith("Bearer ")) {
@@ -727,7 +727,7 @@ export function verifyToken(req: Request, res: Response, next: NextFunction): vo
727
727
 
728
728
  Tests: 3 passed, 3 total
729
729
  Time: 1.234s`,raw:JSON.stringify({tool_use_id:"tool-mock-003",is_error:!1})}},{delayMs:6400,event:{eventType:"tool_use",timestamp:Ie(6400),content:JSON.stringify({tool:"Grep",args:{pattern:"decoded\\.exp",path:"src/"}}),raw:JSON.stringify({id:"tool-mock-004"})}},{delayMs:7e3,event:{eventType:"tool_result",timestamp:Ie(7e3),content:`src/middleware/auth.ts:14: if (decoded.exp < Date.now() / 1000) {
730
- src/utils/token-refresh.ts:28: const remaining = decoded.exp - Date.now() / 1000;`,raw:JSON.stringify({tool_use_id:"tool-mock-004",is_error:!1})}},{delayMs:7800,event:{eventType:"text",timestamp:Ie(7800),content:"Fixed. The token expiry comparison was inverted — `decoded.exp > Date.now()` should have been `<` (a token is expired when its `exp` is in the past). The other occurrence in `token-refresh.ts` uses subtraction (not comparison), so it was already correct. All 3 auth tests pass."}},{delayMs:8400,event:{eventType:"usage",timestamp:Ie(8400),content:JSON.stringify({input_tokens:42600,output_tokens:1850,cost_millicents:12e3})}},{delayMs:8800,event:{eventType:"status",timestamp:Ie(8800),content:"completed"}}]}],is={onConnect:async()=>{},onDisconnect:()=>{},handleEvent:()=>!1},f_=400;function U$({children:t}){const[s,o]=y.useState(M$),[r,c]=y.useState(I$),[d,u]=y.useState(O$),[p,m]=y.useState(void 0),[g,v]=y.useState(B$),[_,b]=y.useState(""),[x,S]=y.useState(L$),[j,w]=y.useState(ed),[T,C]=y.useState(void 0),D=!1,[O,A]=y.useState(z$),[I,$]=y.useState({claude:"off",github:"off",copilot:"off",codex:"off",goose:"off"}),[B,P]=y.useState($$),[X,H]=y.useState([]),[Q]=y.useState(P$),[he,W]=y.useState(""),[ie,L]=y.useState(Ds),[E,J]=y.useState(Ga),[me,q]=y.useState(void 0),[de,re]=y.useState(void 0),[xe,be]=y.useState(""),fe=y.useRef(void 0),_e=y.useRef(0),ke=y.useRef(0),Le=y.useRef(new Set),Ot=y.useRef(new Map),Vn=y.useRef(x);Vn.current=x;const oe=y.useRef(new Map),Je=y.useRef(new Map),Ht=y.useCallback(V=>(_e.current+=1,`mock-${V}-${String(_e.current).padStart(3,"0")}`),[]),ne=y.useCallback(()=>{const V=u_[ke.current%u_.length];return ke.current+=1,V},[]),Ct=y.useCallback((V,te,le)=>{const ue=setTimeout(()=>{var ve;Le.current.delete(ue),le&&((ve=Ot.current.get(le))==null||ve.delete(ue)),V()},te);Le.current.add(ue),le&&(Ot.current.has(le)||Ot.current.set(le,new Set),Ot.current.get(le).add(ue))},[]),Bt=y.useCallback(V=>{const te=Ot.current.get(V);te&&(te.forEach(le=>{clearTimeout(le),Le.current.delete(le)}),Ot.current.delete(V))},[]),Lt=y.useCallback((V,te,le)=>{c(ue=>ue.map(ve=>ve.id===V?{...ve,status:te,...le!==void 0?{endReason:le}:{}}:ve))},[]),Pe=y.useCallback(V=>{u(te=>[...te,V])},[]),rn=y.useCallback((V,te,le)=>{te.forEach((ue,ve)=>{Ct(()=>{const Ve={sessionId:V,...ue.event,timestamp:new Date().toISOString()};if(Pe(Ve),ue.event.eventType==="status"){const Te=ck(ue.event.content),Me=dk(ue.event.content);Lt(V,Te,Me)}ve===te.length-1&&le&&le()},ue.delayMs,V)})},[Ct,Pe,Lt]),ha=y.useCallback(async(V,te,le,ue)=>{console.log("[MockGrackle] spawn",{environmentId:V,prompt:te,runtime:ue});const ve=Ht("sess"),Ve={id:ve,environmentId:V,runtime:ue||"claude-code",status:"running",prompt:te,startedAt:new Date().toISOString()};c(Me=>[...Me,Ve]),m(ve);const Te=ne();if(console.log(`[MockGrackle] Playing scenario: ${Te.label}`),Te.pauseForInput){const Me=Te.pauseAfterStep??Te.steps.length-1,Xe=Te.steps.slice(0,Me+1),gt=Xe.length>0?Xe[Xe.length-1].delayMs:0;rn(ve,Xe),Ct(()=>{Lt(ve,"idle"),Pe({sessionId:ve,eventType:"status",timestamp:new Date().toISOString(),content:"idle"})},gt+f_,ve),Te.resumeSteps&&oe.current.set(ve,Te.resumeSteps)}else rn(ve,Te.steps)},[Ht,ne,rn,Ct,Lt,Pe]),us=y.useCallback(async V=>{console.log("[MockGrackle] kill",V),Bt(V),oe.current.delete(V),Lt(V,"stopped","killed"),Pe({sessionId:V,eventType:"status",timestamp:new Date().toISOString(),content:"killed"}),S(te=>te.map(le=>le.latestSessionId===V&&le.status==="working"?{...le,status:"not_started"}:le))},[Bt,Lt,Pe]),ei=y.useCallback(async V=>{console.log("[MockGrackle] stopGraceful",V),Bt(V),oe.current.delete(V),Lt(V,"stopped","terminated"),Pe({sessionId:V,eventType:"status",timestamp:new Date().toISOString(),content:"terminated"}),S(te=>te.map(le=>le.latestSessionId===V&&le.status==="working"?{...le,status:"not_started"}:le))},[Bt,Lt,Pe]),ga=y.useCallback(()=>{console.log("[MockGrackle] refresh")},[]),en=y.useCallback(async V=>{console.log("[MockGrackle] loadSessionEvents",V)},[]),Pi=y.useCallback(()=>{console.log("[MockGrackle] clearEvents"),u([])},[]),va=y.useCallback(async(V,te,le,ue,ve,Ve,Te,Me,Xe)=>{console.log("[MockGrackle] createWorkspace",{name:V,description:te});const gt={id:Ht("proj"),name:V,description:te||"",repoUrl:le||"",linkedEnvironmentIds:ue?[ue]:[],status:"active",workingDirectory:Te||"",useWorktrees:Ve??!0,defaultPersonaId:ve||"",tokenBudget:0,costBudgetMillicents:0,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};v($e=>[...$e,gt]),Me&&Me()},[Ht]),ti=y.useCallback(async V=>{console.log("[MockGrackle] archiveWorkspace",V),v(te=>te.map(le=>le.id===V?{...le,status:"archived"}:le))},[]),Ss=y.useCallback(async V=>{console.log("[MockGrackle] loadTasks",V)},[]),Ui=y.useCallback(async(V,te,le,ue,ve,Ve,Te,Me,Xe)=>{console.log("[MockGrackle] createTask",{workspaceId:V,title:te,parentTaskId:ve}),S(gt=>{const Qe=gt.filter(zs=>zs.workspaceId===V).reduce((zs,Yo)=>Math.max(zs,Yo.sortOrder),0),dt=ve?gt.find(zs=>zs.id===ve):void 0;if(ve&&!dt)return console.warn("[MockGrackle] Parent task not found:",ve),gt;if(dt&&!dt.canDecompose)return console.warn("[MockGrackle] Parent task does not have decomposition rights:",ve),gt;const yt=dt?dt.depth+1:0,Ts={id:Ht("task"),workspaceId:V,title:te,description:le||"",status:"not_started",branch:"",latestSessionId:"",dependsOn:ue||[],reviewNotes:void 0,sortOrder:Qe+1,createdAt:new Date().toISOString(),parentTaskId:ve||"",depth:yt,childTaskIds:[],canDecompose:Te??!ve,defaultPersonaId:Ve||"",workpad:"",tokenBudget:0,costBudgetMillicents:0};return[...gt,Ts]}),Me&&Me()},[Ht]),qn=y.useCallback(async(V,te,le,ue)=>{var gt;console.log("[MockGrackle] startTask",{taskId:V});const ve=Vn.current.find($e=>$e.id===V),Ve=(ve==null?void 0:ve.title)??"",Te=Ht("sess"),Me={id:Te,environmentId:"env-local-01",runtime:"claude-code",status:"running",prompt:Ve||V,startedAt:new Date().toISOString()};c($e=>[...$e,Me]),S($e=>$e.map(Qe=>Qe.id===V?{...Qe,status:"working",latestSessionId:Te,branch:`mock/${V.slice(0,8)}`}:Qe));const Xe=ne();if(console.log(`[MockGrackle] Playing task scenario: ${Xe.label}`),Xe.pauseForInput){const $e=Xe.pauseAfterStep??Xe.steps.length-1,Qe=Xe.steps.slice(0,$e+1),dt=Qe.length>0?Qe[Qe.length-1].delayMs:0;if(rn(Te,Qe),Ct(()=>{Lt(Te,"idle"),Pe({sessionId:Te,eventType:"status",timestamp:new Date().toISOString(),content:"idle"})},dt+f_,Te),Xe.resumeSteps){const yt=[...Xe.resumeSteps];oe.current.set(Te,yt);const Ts=yt.reduce((zs,Yo)=>Math.max(zs,Yo.delayMs),0);Je.current.set(Te,{taskId:V,delayAfterResume:Ts+200})}}else{const $e=Xe.steps.length>0?Xe.steps[Xe.steps.length-1].delayMs:0;rn(Te,Xe.steps);const Qe=(gt=Xe.steps[Xe.steps.length-1])==null?void 0:gt.event.content;Ct(()=>{Qe==="completed"?S(dt=>dt.map(yt=>yt.id===V&&yt.status==="working"?{...yt,status:"paused"}:yt)):Qe==="failed"&&S(dt=>dt.map(yt=>yt.id===V&&yt.status==="working"?{...yt,status:"failed"}:yt))},$e+100,Te)}},[Ht,ne,rn,Ct,Lt,Pe]),De=y.useCallback(async(V,te)=>{console.log("[MockGrackle] sendInput",{sessionId:V,text:te}),Pe({sessionId:V,eventType:"output",timestamp:new Date().toISOString(),content:`User input: ${te}`}),Lt(V,"running"),Pe({sessionId:V,eventType:"status",timestamp:new Date().toISOString(),content:"running"});const le=oe.current.get(V);if(le)oe.current.delete(V),rn(V,le);else{const ve=[{delayMs:500,event:{eventType:"output",timestamp:new Date().toISOString(),content:"I received your input, continuing..."}},{delayMs:1500,event:{eventType:"status",timestamp:new Date().toISOString(),content:"completed"}}];rn(V,ve)}const ue=Je.current.get(V);ue&&(Je.current.delete(V),Ct(()=>{S(ve=>ve.map(Ve=>Ve.id===ue.taskId&&Ve.status==="working"?{...Ve,status:"paused"}:Ve))},ue.delayAfterResume,V))},[Pe,Lt,rn,Ct]),We=y.useCallback(async V=>{console.log("[MockGrackle] completeTask",V),S(te=>te.map(le=>le.id===V?{...le,status:"complete"}:le))},[]),tn=y.useCallback(async V=>{console.log("[MockGrackle] resumeTask",V)},[]),jt=y.useCallback(async(V,te,le,ue,ve)=>{console.log("[MockGrackle] updateTask",{taskId:V,title:te}),S(Ve=>Ve.map(Te=>Te.id===V?{...Te,title:te.trim()||Te.title,description:le,dependsOn:ue,...ve!==void 0?{defaultPersonaId:ve}:{}}:Te))},[]),vn=y.useCallback(async V=>{console.log("[MockGrackle] deleteTask",V),S(te=>te.filter(le=>le.id!==V))},[]),nn=y.useCallback(async V=>{console.log("[MockGrackle] loadFindings",V),w(ed.filter(te=>te.workspaceId===V))},[]),Hi=y.useCallback(async()=>{console.log("[MockGrackle] loadAllFindings"),w([...ed])},[]),Vi=y.useCallback(async V=>{console.log("[MockGrackle] loadFinding",V);const te=ed.find(le=>le.id===V);C(te)},[]),qi=y.useCallback(async(V,te,le,ue,ve)=>{console.log("[MockGrackle] postFinding",{workspaceId:V,title:te});const Ve={id:Ht("find"),workspaceId:V,taskId:"",sessionId:"",category:ue||"general",title:te,content:le,tags:ve||[],createdAt:new Date().toISOString()};w(Te=>[...Te,Ve])},[Ht]),ni=y.useCallback(async()=>{console.log("[MockGrackle] loadEnvironments")},[]),si=y.useCallback(async(V,te,le)=>{console.log("[MockGrackle] addEnvironment",{displayName:V,adapterType:te,adapterConfig:le})},[]),ai=y.useCallback(async(V,te)=>{console.log("[MockGrackle] updateEnvironment",{environmentId:V,...te}),o(le=>le.map(ue=>ue.id!==V?ue:{...ue,...te.displayName!==void 0?{displayName:te.displayName}:{},...te.adapterConfig!==void 0?{adapterConfig:JSON.stringify(te.adapterConfig)}:{}}))},[]),js=y.useCallback(async()=>{console.log("[MockGrackle] loadTokens")},[]),ii=y.useCallback(async(V,te,le,ue,ve)=>{console.log("[MockGrackle] setToken",{name:V,tokenType:le}),A(Ve=>[...Ve.filter(Me=>Me.name!==V),{name:V,tokenType:le,envVar:ue,filePath:ve,expiresAt:""}])},[]),ya=y.useCallback(async V=>{console.log("[MockGrackle] deleteToken",V),A(te=>te.filter(le=>le.name!==V))},[]),Tl=y.useCallback(async V=>{console.log("[MockGrackle] updateCredentialProviders",V),$(V)},[]);y.useEffect(()=>()=>{Le.current.forEach(clearTimeout),Le.current.clear()},[]);const wl=y.useMemo(()=>({connectionStatus:"connected",environments:{environments:s,environmentsLoading:!1,provisionStatus:{},operationError:"",clearOperationError:()=>{},loadEnvironments:ni,addEnvironment:si,updateEnvironment:ai,provisionEnvironment:async(V,te)=>{},stopEnvironment:async()=>{},removeEnvironment:async()=>{},domainHook:is},sessions:{sessions:r,sessionsLoading:!1,events:d,eventsDropped:0,lastSpawnedId:p,taskSessions:Q,spawn:ha,sendInput:De,kill:us,stopGraceful:ei,loadSessionEvents:en,clearEvents:Pi,loadTaskSessions:async V=>{console.log("[MockGrackle] loadTaskSessions",V)},domainHook:is},workspaces:{workspaces:g,workspacesLoading:!1,workspaceCreating:!1,loadWorkspaces:async()=>{console.log("[MockGrackle] loadWorkspaces")},createWorkspace:va,archiveWorkspace:ti,updateWorkspace:async(V,te)=>{console.log("[MockGrackle] updateWorkspace",{workspaceId:V,...te}),v(le=>le.map(ue=>ue.id!==V?ue:{...ue,...te.name!==void 0?{name:te.name}:{},...te.description!==void 0?{description:te.description}:{},...te.repoUrl!==void 0?{repoUrl:te.repoUrl}:{},...te.environmentId!==void 0?{environmentId:te.environmentId}:{},...te.workingDirectory!==void 0?{workingDirectory:te.workingDirectory}:{},...te.useWorktrees!==void 0?{useWorktrees:te.useWorktrees}:{},...te.defaultPersonaId!==void 0?{defaultPersonaId:te.defaultPersonaId}:{},updatedAt:new Date().toISOString()}))},linkEnvironment:async(V,te)=>{if(console.log("[MockGrackle] linkEnvironment",{workspaceId:V,environmentId:te}),te==="error-env"){b("Failed to link environment");return}b(""),v(le=>le.map(ue=>ue.id!==V||ue.linkedEnvironmentIds.includes(te)?ue:{...ue,linkedEnvironmentIds:[...ue.linkedEnvironmentIds,te]}))},unlinkEnvironment:async(V,te)=>{if(console.log("[MockGrackle] unlinkEnvironment",{workspaceId:V,environmentId:te}),te==="error-env"){b("Failed to unlink environment");return}b(""),v(le=>le.map(ue=>ue.id!==V?ue:{...ue,linkedEnvironmentIds:ue.linkedEnvironmentIds.filter(ve=>ve!==te)}))},linkOperationError:_,clearLinkOperationError:()=>{b("")},domainHook:is},tasks:{tasks:x,tasksLoading:!1,taskStartingId:void 0,loadTasks:Ss,loadAllTasks:async()=>{console.log("[MockGrackle] loadAllTasks")},createTask:Ui,startTask:qn,stopTask:async V=>{console.log("[MockGrackle] stopTask",{taskId:V}),await We(V)},completeTask:We,resumeTask:tn,updateTask:jt,deleteTask:vn,domainHook:is},findings:{findings:j,selectedFinding:T,findingLoading:D,findingsLoading:!1,loadFindings:nn,loadAllFindings:Hi,loadFinding:Vi,postFinding:qi,domainHook:is},tokens:{tokens:O,tokensLoading:!1,loadTokens:js,setToken:ii,deleteToken:ya,domainHook:is},credentials:{credentialProviders:I,credentialsLoading:!1,updateCredentialProviders:Tl,domainHook:is},codespaces:{codespaces:[],codespaceError:"",codespaceListError:"",codespaceCreating:!1,listCodespaces:async()=>{},createCodespace:async()=>{},domainHook:is},personas:{personas:B,personasLoading:!1,createPersona:async(V,te,le,ue,ve,Ve,Te,Me,Xe)=>{console.log("[MockGrackle] createPersona",{name:V});const gt={id:`mock-persona-${Date.now()}`,name:V,description:te,systemPrompt:le,toolConfig:"{}",runtime:ue??"claude-code",model:ve||"",maxTurns:Ve||0,mcpServers:"[]",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),type:Te||"agent",script:Me||"",allowedMcpTools:Xe||[]};return P($e=>[...$e,gt]),gt},updatePersona:async(V,te,le,ue,ve,Ve,Te,Me,Xe,gt)=>{console.log("[MockGrackle] updatePersona",{personaId:V,name:te});const $e=B.find(yt=>yt.id===V);if(!$e)throw new Error(`Persona not found: ${V}`);const Qe=new Date().toISOString(),dt={...$e,...te!==void 0?{name:te}:{},...le!==void 0?{description:le}:{},...ue!==void 0?{systemPrompt:ue}:{},...ve!==void 0?{runtime:ve}:{},...Ve!==void 0?{model:Ve}:{},...Te!==void 0?{maxTurns:Te}:{},...Me!==void 0?{type:Me}:{},...Xe!==void 0?{script:Xe}:{},...gt!==void 0?{allowedMcpTools:gt}:{},updatedAt:Qe};return P(yt=>yt.map(Ts=>Ts.id===V?dt:Ts)),dt},deletePersona:async V=>{console.log("[MockGrackle] deletePersona",V),P(te=>te.filter(le=>le.id!==V))},domainHook:is},schedules:{schedules:X,schedulesLoading:!1,createSchedule:async(V,te,le,ue,ve)=>{console.log("[MockGrackle] createSchedule",{title:V});const Ve={id:`mock-schedule-${Date.now()}`,title:V,description:te,scheduleExpression:le,personaId:ue,workspaceId:ve??"",parentTaskId:"",enabled:!0,lastRunAt:"",nextRunAt:new Date(Date.now()+6e4).toISOString(),runCount:0,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return H(Te=>[...Te,Ve]),Ve},updateSchedule:async(V,te)=>{console.log("[MockGrackle] updateSchedule",{scheduleId:V,fields:te});let le;if(H(ue=>ue.map(ve=>ve.id!==V?ve:(le={...ve,...te,updatedAt:new Date().toISOString()},le))),!le)throw new Error(`Schedule not found: ${V}`);return le},deleteSchedule:async V=>{console.log("[MockGrackle] deleteSchedule",V),H(te=>te.filter(le=>le.id!==V))},domainHook:is},streams:{streams:[],streamsLoading:!1,streamsLoadedOnce:!0,streamsLoadError:!1,loadStreams:async()=>{},domainHook:is},knowledge:{graphData:{nodes:ie,links:E},selectedNode:me,loading:!1,selectedId:de,searchQuery:xe,search:async V=>{if(console.log("[MockGrackle] knowledge.search",V),!V.trim()){be(V);return}be(V);const te=fe.current,le=te?Ds.filter(Te=>!Te.workspaceId||Te.workspaceId===te):Ds,ue=V.toLowerCase(),ve=le.filter(Te=>{var Me,Xe,gt;return Te.label.toLowerCase().includes(ue)||((Me=Te.content)==null?void 0:Me.toLowerCase().includes(ue))||((Xe=Te.tags)==null?void 0:Xe.some($e=>$e.toLowerCase().includes(ue)))||((gt=Te.category)==null?void 0:gt.toLowerCase().includes(ue))});L(ve);const Ve=new Set(ve.map(Te=>Te.id));J(Ga.filter(Te=>Ve.has(Te.source)&&Ve.has(Te.target))),re(void 0),q(void 0)},clearSearch:()=>{console.log("[MockGrackle] knowledge.clearSearch"),be("");const V=fe.current,te=V?Ds.filter(ue=>!ue.workspaceId||ue.workspaceId===V):Ds;L(te);const le=new Set(te.map(ue=>ue.id));J(Ga.filter(ue=>le.has(ue.source)&&le.has(ue.target)))},selectNode:async V=>{console.log("[MockGrackle] knowledge.selectNode",V),re(V);const te=V in d_?d_[V]:void 0;if(te)q(te);else{const le=Ds.find(ue=>ue.id===V);if(le){const ue=Ga.filter(ve=>ve.source===V||ve.target===V).map(ve=>({fromId:ve.source,toId:ve.target,type:ve.type}));q({node:le,edges:ue})}}},clearSelection:()=>{console.log("[MockGrackle] knowledge.clearSelection"),re(void 0),q(void 0)},expandNode:async V=>{console.log("[MockGrackle] knowledge.expandNode",V),L(te=>{const le=new Set(te.map(Me=>Me.id)),ue=Ga.filter(Me=>Me.source===V||Me.target===V),ve=new Set;for(const Me of ue)le.has(Me.source)||ve.add(Me.source),le.has(Me.target)||ve.add(Me.target);if(ve.size===0)return te;const Ve=Ds.filter(Me=>ve.has(Me.id)),Te=new Set([...le,...ve]);return J(Me=>{const Xe=new Set(Me.map($e=>`${$e.source}|${$e.target}|${$e.type}`)),gt=Ga.filter($e=>Te.has($e.source)&&Te.has($e.target)&&!Xe.has(`${$e.source}|${$e.target}|${$e.type}`));return gt.length>0?[...Me,...gt]:Me}),[...te,...Ve]})},loadRecent:async V=>{if(console.log("[MockGrackle] knowledge.loadRecent",V),fe.current=V,V){const te=Ds.filter(ue=>!ue.workspaceId||ue.workspaceId===V);L(te);const le=new Set(te.map(ue=>ue.id));J(Ga.filter(ue=>le.has(ue.source)&&le.has(ue.target)))}else L(Ds),J(Ga);be("")},handleEvent:()=>!1,domainHook:is},plugins:{plugins:[{name:"core",description:"Core infrastructure",enabled:!0,required:!0,loaded:!0},{name:"orchestration",description:"Task orchestration",enabled:!0,required:!1,loaded:!0},{name:"scheduling",description:"Scheduled triggers",enabled:!0,required:!1,loaded:!0},{name:"knowledge",description:"Knowledge graph",enabled:!1,required:!1,loaded:!1}],pluginsLoading:!1,loadPlugins:async()=>{console.log("[MockGrackle] loadPlugins")},setPluginEnabled:async(V,te)=>{console.log("[MockGrackle] setPluginEnabled",V,te)}},appDefaultPersonaId:he,setAppDefaultPersonaId:async V=>{console.log("[MockGrackle] setAppDefaultPersonaId",V),W(V)},onboardingCompleted:!0,completeOnboarding:async()=>{console.log("[MockGrackle] completeOnboarding")},usageCache:{"workspace:proj-alpha":{inputTokens:214500,outputTokens:44850,costMillicents:112e3,sessionCount:4},"workspace:proj-beta":{inputTokens:86700,outputTokens:23800,costMillicents:48e3,sessionCount:3},"task:task-001":{inputTokens:126800,outputTokens:20850,costMillicents:63e3,sessionCount:2},"task:task-006":{inputTokens:18900,outputTokens:4500,costMillicents:1e4,sessionCount:1},"task_tree:task-001":{inputTokens:126800,outputTokens:20850,costMillicents:63e3,sessionCount:2},"task_tree:task-006":{inputTokens:18900,outputTokens:4500,costMillicents:1e4,sessionCount:1}},loadUsage:async(V,te)=>{console.log(`[MockGrackle] loadUsage(${V}, ${te})`)},refresh:ga}),[s,r,d,p,Q,g,_,x,j,T,O,I,B,X,he,ie,E,me,de,xe,ha,De,us,ei,en,Pi,va,ti,Ss,Ui,qn,We,tn,jt,vn,nn,Hi,Vi,qi,ni,si,ai,js,ii,ya,Tl,ga]);return a.jsx(vh.Provider,{value:wl,children:t})}const pk=3e3,H$=pk;function V$(t){const[s,o]=y.useState("connecting"),r=y.useRef(t.onSessionEvent);r.current=t.onSessionEvent;const c=y.useRef(t.onDomainEvent);c.current=t.onDomainEvent;const d=y.useRef(t.onConnect);d.current=t.onConnect;const u=y.useRef(t.onDisconnect);return u.current=t.onDisconnect,y.useEffect(()=>{let p=!1,m,g;async function v(){var x,S;if(p)return;Promise.resolve((x=d.current)==null?void 0:x.call(d)).catch(()=>{});let _=!1;const b=()=>{!_&&!p&&(_=!0,o("connected"))};g=setTimeout(b,H$);try{const j=Fe.streamEvents({});for await(const w of j){if(b(),p)break;const T=w.event;if(T.case==="sessionEvent"){const C=T.value;r.current({sessionId:C.sessionId,type:C.type,timestamp:C.timestamp,content:C.content,raw:C.raw})}else if(T.case==="domainEvent"){const C=T.value;c.current({id:C.id,type:C.type,timestamp:C.timestamp,payloadJson:C.payloadJson})}}}catch(j){if(clearTimeout(g),j instanceof Di&&j.code===D_.Unauthenticated){window.location.href=$N;return}}clearTimeout(g),p||(o("connecting"),(S=u.current)==null||S.call(u),m=setTimeout(()=>{v().catch(()=>{})},pk))}return v().catch(()=>{}),()=>{p=!0,clearTimeout(m),clearTimeout(g)}},[]),{connectionStatus:s}}const jm=["core","orchestration","scheduling"],mk=y.createContext({pluginNames:[...jm],loading:!1,error:void 0});function q$({children:t}){const[s,o]=y.useState([...jm]),[r,c]=y.useState(!0),[d,u]=y.useState(void 0);return y.useEffect(()=>{let p=!1;return fetch("/api/manifest").then(async m=>{if(!m.ok)throw new Error(`Manifest fetch returned ${m.status}`);return m.json()}).then(m=>{p||(o(m.plugins.map(g=>g.name)),c(!1))}).catch(m=>{p||(o([...jm]),u(m instanceof Error?m:new Error(String(m))),c(!1))}),()=>{p=!0}},[]),a.jsx(mk.Provider,{value:{pluginNames:s,loading:r,error:d},children:t})}function xh(){return y.useContext(mk)}const G$=new Set(["dashboard","chat","environments","settings"]),F$=new Set(["tasks","findings"]),Z$=new Set(["knowledge"]),hk={core:{navItems:cd.filter(t=>G$.has(t.view)),domainHookKeys:["environments","sessions","workspaces","tokens","credentials","codespaces","streams","plugins"]},orchestration:{navItems:cd.filter(t=>F$.has(t.view)),domainHookKeys:["tasks","findings","personas","notifications"]},scheduling:{navItems:[],domainHookKeys:["schedules"]},knowledge:{navItems:cd.filter(t=>Z$.has(t.view)),domainHookKeys:["knowledge"]}};function K$(t){return t.flatMap(s=>{var o;return((o=hk[s])==null?void 0:o.navItems)??[]})}function Y$(t){return new Set(t.flatMap(s=>{var o;return((o=hk[s])==null?void 0:o.domainHookKeys)??[]}))}function J$(t){return{id:t.id,displayName:t.displayName,adapterType:t.adapterType,adapterConfig:t.adapterConfig||"{}",status:t.status,bootstrapped:t.bootstrapped}}function p_(t){return{id:t.id,environmentId:t.environmentId,runtime:t.runtime,status:t.status,prompt:t.prompt,startedAt:t.startedAt,endedAt:t.endedAt||void 0,error:t.error||void 0,endReason:t.endReason||void 0,personaId:t.personaId||void 0,inputTokens:t.inputTokens,outputTokens:t.outputTokens,costMillicents:t.costMillicents}}function W$(t){return{sessionId:t.sessionId,eventType:R_(t.type),timestamp:t.timestamp,content:t.content,raw:t.raw||void 0}}function X$(t){return{id:t.id,name:t.name,description:t.description,repoUrl:t.repoUrl,linkedEnvironmentIds:[...t.linkedEnvironmentIds],status:q2(t.status),workingDirectory:t.workingDirectory,useWorktrees:t.useWorktrees,defaultPersonaId:t.defaultPersonaId,tokenBudget:t.tokenBudget,costBudgetMillicents:t.costBudgetMillicents,createdAt:t.createdAt,updatedAt:t.updatedAt}}function m_(t){return{id:t.id,workspaceId:t.workspaceId??void 0,title:t.title,description:t.description,status:G2(t.status),branch:t.branch,latestSessionId:t.latestSessionId,dependsOn:[...t.dependsOn],sortOrder:t.sortOrder,createdAt:t.createdAt,startedAt:t.startedAt||void 0,completedAt:t.completedAt||void 0,parentTaskId:t.parentTaskId,depth:t.depth,childTaskIds:[...t.childTaskIds],canDecompose:t.canDecompose,defaultPersonaId:t.defaultPersonaId,workpad:t.workpad,tokenBudget:t.tokenBudget,costBudgetMillicents:t.costBudgetMillicents}}function Up(t){return{id:t.id,workspaceId:t.workspaceId,taskId:t.taskId,sessionId:t.sessionId,category:t.category,title:t.title,content:t.content,tags:[...t.tags],createdAt:t.createdAt}}function Q$(t){return{name:t.name,tokenType:t.type,envVar:t.envVar,filePath:t.filePath,expiresAt:t.expiresAt}}function eP(t){return{claude:F2(t.claude),github:$c(t.github),copilot:$c(t.copilot),codex:$c(t.codex),goose:$c(t.goose)}}function tP(t){return{name:t.name,repository:t.repository,state:t.state,gitStatus:t.gitStatus}}function Hp(t){return{id:t.id,name:t.name,description:t.description,systemPrompt:t.systemPrompt,toolConfig:t.toolConfig?JSON.stringify({allowedTools:[...t.toolConfig.allowedTools],disallowedTools:[...t.toolConfig.disallowedTools]}):"{}",runtime:t.runtime,model:t.model,maxTurns:t.maxTurns,mcpServers:JSON.stringify(t.mcpServers.map(s=>({name:s.name,command:s.command,args:[...s.args],tools:[...s.tools]}))),createdAt:t.createdAt,updatedAt:t.updatedAt,type:t.type||"agent",script:t.script,allowedMcpTools:[...t.allowedMcpTools]}}function nP(t){return{inputTokens:t.inputTokens,outputTokens:t.outputTokens,costMillicents:t.costMillicents,sessionCount:t.sessionCount}}function Vp(t){return{id:t.id,title:t.title,description:t.description,scheduleExpression:t.scheduleExpression,personaId:t.personaId,workspaceId:t.workspaceId,parentTaskId:t.parentTaskId,enabled:t.enabled,lastRunAt:t.lastRunAt,nextRunAt:t.nextRunAt,runCount:t.runCount,createdAt:t.createdAt,updatedAt:t.updatedAt}}function td(t,s=0){return{id:t.id,label:t.title||t.label||t.id,kind:t.kind,category:t.category||void 0,sourceType:t.sourceType||void 0,sourceId:t.sourceId||void 0,content:t.content||void 0,tags:t.tags.length>0?[...t.tags]:void 0,workspaceId:t.workspaceId||void 0,createdAt:t.createdAt||void 0,updatedAt:t.updatedAt||void 0,val:s}}function qp(t){return{source:t.fromId,target:t.toId,type:t.type}}function sP(t){return{subscriptionId:t.subscriptionId,sessionId:t.sessionId,fd:t.fd,permission:t.permission,deliveryMode:t.deliveryMode,createdBySpawn:t.createdBySpawn}}function aP(t){return{id:t.id,name:t.name,subscriberCount:t.subscriberCount,messageBufferDepth:t.messageBufferDepth,subscribers:t.subscribers.map(sP)}}function ks(){const[t,s]=y.useState(!1),o=y.useRef(0),r=y.useCallback(c=>(o.current++,o.current===1&&s(!0),c.finally(()=>{o.current--,o.current===0&&s(!1)})),[]);return{loading:t,track:r}}const h_=5e3;function Kr(t){return t instanceof Di?t.message:"Operation failed"}function iP(){const[t,s]=y.useState([]),{loading:o,track:r}=ks(),[c,d]=y.useState({}),[u,p]=y.useState(""),m=y.useCallback(()=>{p("")},[]),g=y.useCallback(async()=>{try{const C=await r(Fe.listEnvironments({}));s(C.environments.map(J$))}catch{}},[r]),v=y.useCallback(C=>{switch(C.type){case"environment.added":return!0;case"environment.removed":{const D=C.payload.environmentId;return D&&(s(O=>O.filter(A=>A.id!==D)),d(O=>{const A={...O};return delete A[D],A})),!0}case"environment.changed":return g().catch(()=>{}),!0;case"environment.provision_progress":{const D=C.payload;if(typeof D.environmentId!="string"||typeof D.stage!="string"||typeof D.message!="string"||typeof D.progress!="number")return lk("environment.provision_progress","invalid payload"),!0;if(d(O=>({...O,[D.environmentId]:{stage:D.stage,message:D.message,progress:D.progress}})),D.stage==="ready"){const O=D.environmentId;setTimeout(()=>{d(A=>{const I={...A};return delete I[O],I})},h_)}return!0}default:return!1}},[g]),_=y.useCallback(C=>{var D;if(C.type==="environments"){const O=Array.isArray((D=C.payload)==null?void 0:D.environments)?C.payload.environments:[];return s(O),!0}return!1},[]),b=y.useCallback(async(C,D,O)=>{p("");try{await Fe.addEnvironment({displayName:C,adapterType:D,adapterConfig:JSON.stringify(O??{})})}catch(A){p(Kr(A))}},[]),x=y.useCallback(async(C,D)=>{p("");try{await Fe.updateEnvironment({id:C,displayName:D.displayName,adapterConfig:D.adapterConfig?JSON.stringify(D.adapterConfig):void 0})}catch(O){p(Kr(O))}},[]),S=y.useCallback(async(C,D)=>{p("");try{const O=Fe.provisionEnvironment({id:C,force:D??!1});for await(const A of O)d(I=>({...I,[C]:{stage:A.stage,message:A.message,progress:A.progress}})),A.stage==="ready"&&setTimeout(()=>{d(I=>{const $={...I};return delete $[C],$})},h_)}catch(O){d(A=>{const I={...A};return delete I[C],I}),p(Kr(O))}},[]),j=y.useCallback(async C=>{p("");try{await Fe.stopEnvironment({id:C})}catch(D){p(Kr(D))}},[]),w=y.useCallback(async C=>{p("");try{await Fe.removeEnvironment({id:C})}catch(D){p(Kr(D))}},[]);return{environments:t,environmentsLoading:o,provisionStatus:c,operationError:u,clearOperationError:m,loadEnvironments:g,addEnvironment:b,updateEnvironment:x,provisionEnvironment:S,stopEnvironment:j,removeEnvironment:w,handleEvent:v,handleLegacyMessage:_,domainHook:{onConnect:()=>g(),onDisconnect:()=>{},handleEvent:v}}}const Gp=new Set(["pending","running","idle"]),oP=new Set(["completed","failed","interrupted","hibernating","suspended"]),g_=["pending","running","idle"];function rP(){const[t,s]=y.useState([]),{loading:o,track:r}=ks(),[c,d]=y.useState([]),[u,p]=y.useState(0),[m,g]=y.useState(void 0),[v,_]=y.useState({}),b=y.useCallback(async()=>{try{const P=(await r(Fe.listSessions({}))).sessions.map(p_);s(X=>{const H=new Map(X.map(Q=>[Q.id,Q]));return P.map(Q=>{const he=H.get(Q.id),W=he==null?void 0:he.status;return!W||W===Q.status?Q:oP.has(W)&&Gp.has(Q.status)?{...Q,status:W,...he.endReason!==void 0?{endReason:he.endReason}:{}}:Gp.has(W)&&Gp.has(Q.status)&&g_.indexOf(W)>g_.indexOf(Q.status)?{...Q,status:W}:Q})})}catch{}},[r]),x=y.useCallback(B=>{if(B.type!=="session_event")return!1;if(!h$(B.payload))return lk("session_event","payload is not a valid SessionEvent"),!0;const P=B.payload;let X=0;if(d(H=>{const Q=[...H,P];return Q.length>Ao?(X=Q.length-Ao,Q.slice(-Ao)):Q}),X>0&&p(H=>H+X),P.eventType==="usage")try{const H=JSON.parse(P.content),Q=Number(H.input_tokens)||0,he=Number(H.output_tokens)||0,W=Number(H.cost_millicents)||0;(Q>0||he>0||W>0)&&s(ie=>ie.map(L=>L.id===P.sessionId?{...L,inputTokens:(L.inputTokens??0)+Q,outputTokens:(L.outputTokens??0)+he,costMillicents:(L.costMillicents??0)+W}:L))}catch{}if(P.eventType==="status"){const H=ck(P.content),Q=dk(P.content);s(he=>he.some(ie=>ie.id===P.sessionId)?he.map(ie=>ie.id===P.sessionId?{...ie,status:H,...Q!==void 0?{endReason:Q}:{}}:ie):[...he,{id:P.sessionId,environmentId:"",runtime:"",status:H,prompt:"",startedAt:P.timestamp,...Q!==void 0?{endReason:Q}:{}}])}return!0},[]),S=y.useCallback(B=>{x({type:"session_event",payload:B})},[x]),j=y.useCallback(B=>{var P,X,H,Q,he;switch(B.type){case"sessions":{const W=Array.isArray((P=B.payload)==null?void 0:P.sessions)?B.payload.sessions:[];return s(W),!0}case"spawned":{const W=(X=B.payload)==null?void 0:X.sessionId;return typeof W=="string"&&W&&g(W),b().catch(()=>{}),!0}case"session_events":{const W=Array.isArray((H=B.payload)==null?void 0:H.events)?B.payload.events:[];return W.length>0&&d(W),!0}case"task_sessions":{const W=(Q=B.payload)==null?void 0:Q.taskId;if(typeof W=="string"&&W){const ie=Array.isArray((he=B.payload)==null?void 0:he.sessions)?B.payload.sessions:[];_(L=>({...L,[W]:ie}))}return!0}default:return!1}},[b]),w=y.useCallback(async(B,P,X,H)=>{try{const Q=await Fe.spawnAgent({environmentId:B,prompt:P,personaId:X||"",workingDirectory:H||""});g(Q.id),await b()}catch{}},[b]),T=y.useCallback(async(B,P)=>{await Fe.sendInput({sessionId:B,text:P})},[]),C=y.useCallback(async B=>{try{await Fe.killAgent({id:B,graceful:!1})}catch{}},[]),D=y.useCallback(async B=>{try{await Fe.killAgent({id:B,graceful:!0})}catch{}},[]),O=y.useCallback(async B=>{try{const X=(await Fe.getSessionEvents({id:B})).events.map(W$);if(X.length>0){let H=0;d(Q=>{const he=new Set;for(const L of Q)L.sessionId===B&&he.add(`${L.timestamp}|${L.eventType}`);const W=X.filter(L=>!he.has(`${L.timestamp}|${L.eventType}`)),ie=[...Q,...W].sort((L,E)=>L.sessionId!==E.sessionId?0:L.timestamp.localeCompare(E.timestamp));return ie.length>Ao?(H=ie.length-Ao,ie.slice(-Ao)):ie}),H>0&&p(Q=>Q+H)}}catch{}},[]),A=y.useCallback(()=>{d([]),p(0)},[]),I=y.useCallback(async B=>{try{const X=(await Fe.getTaskSessions({id:B})).sessions.map(p_);_(H=>({...H,[B]:X}))}catch{}},[]);return{sessions:t,sessionsLoading:o,events:c,eventsDropped:u,lastSpawnedId:m,taskSessions:v,loadSessions:b,spawn:w,sendInput:T,kill:C,stopGraceful:D,loadSessionEvents:O,clearEvents:A,loadTaskSessions:I,handleMessage:x,handleSessionEvent:S,handleLegacyMessage:j,domainHook:{onConnect:()=>b(),onDisconnect:()=>{A()},handleEvent:()=>!1}}}function v_(t){return t instanceof Di?t.message:"Operation failed"}function lP(){const[t,s]=y.useState([]),{loading:o,track:r}=ks(),[c,d]=y.useState(!1),[u,p]=y.useState(""),m=y.useCallback(async()=>{try{const C=await r(Fe.listWorkspaces({}));s(C.workspaces.map(X$))}catch{}},[r]),g=y.useCallback(C=>{switch(C.type){case"workspace.created":return d(!1),m().catch(()=>{}),!0;case"workspace.archived":case"workspace.updated":return m().catch(()=>{}),!0;default:return!1}},[m]),v=y.useCallback(()=>{d(!1)},[]),_=y.useCallback(async(C,D,O,A,I,$,B,P,X)=>{d(!0);try{await Fe.createWorkspace({name:C,description:D||"",repoUrl:O||"",environmentId:A||"",defaultPersonaId:I||void 0,useWorktrees:$??!0,workingDirectory:B||void 0}),d(!1),P==null||P()}catch(H){d(!1);const Q=H instanceof Di?H.message:"Failed to create workspace";X==null||X(Q)}},[]),b=y.useCallback(async C=>{try{await Fe.archiveWorkspace({id:C})}catch{}},[]),x=y.useCallback(async(C,D)=>{try{await Fe.updateWorkspace({id:C,...D})}catch{}},[]),S=y.useCallback(()=>{p("")},[]),j=y.useCallback(async(C,D)=>{try{p(""),await Fe.linkEnvironment({workspaceId:C,environmentId:D}),await m().catch(()=>{})}catch(O){p(v_(O))}},[m]),w=y.useCallback(async(C,D)=>{try{p(""),await Fe.unlinkEnvironment({workspaceId:C,environmentId:D}),await m().catch(()=>{})}catch(O){p(v_(O))}},[m]);return{workspaces:t,workspacesLoading:o,workspaceCreating:c,loadWorkspaces:m,createWorkspace:_,archiveWorkspace:b,updateWorkspace:x,linkEnvironment:j,unlinkEnvironment:w,linkOperationError:u,clearLinkOperationError:S,handleEvent:g,onDisconnect:v,domainHook:{onConnect:()=>m(),onDisconnect:v,handleEvent:g}}}function cP(){const[t,s]=y.useState([]),{loading:o,track:r}=ks(),[c,d]=y.useState(void 0),u=y.useRef({}),p=y.useCallback(async A=>{try{const $=(await pn.listTasks({workspaceId:A})).tasks.map(m_);s(B=>[...B.filter(P=>P.workspaceId!==A),...$])}catch{}},[]),m=y.useCallback(async()=>{try{const I=(await r(pn.listTasks({}))).tasks.map(m_);s($=>{const B=new Set(I.map(P=>P.id));return[...$.filter(P=>!B.has(P.id)),...I]})}catch{}},[r]),g=y.useCallback((A,I)=>{const $=B=>{clearTimeout(u.current[B]),u.current[B]=setTimeout(()=>{delete u.current[B],p(B).catch(()=>{})},200)};A?$(A):I&&s(B=>{const P=B.find(X=>X.id===I);return P!=null&&P.workspaceId?$(P.workspaceId):m().catch(()=>{}),B})},[p,m]),v=y.useCallback(A=>{const I=A.payload;switch(A.type){case"task.created":{const $=typeof I.workspaceId=="string"?I.workspaceId:"";return $&&p($).catch(()=>{}),!0}case"task.started":{const $=typeof I.taskId=="string"?I.taskId:"",B=typeof I.sessionId=="string"?I.sessionId:"",P=typeof I.workspaceId=="string"?I.workspaceId:"";return d(X=>$&&X===$?void 0:X),B&&$&&s(X=>X.map(H=>H.id===$?{...H,latestSessionId:B}:H)),g(P,$),!0}case"task.completed":case"task.deleted":case"task.reparented":case"task.updated":{const $=typeof I.workspaceId=="string"?I.workspaceId:"",B=typeof I.taskId=="string"?I.taskId:"";return d(P=>B&&P===B?void 0:P),g($,B),!0}default:return!1}},[p,g]),_=y.useCallback(()=>{d(void 0)},[]),b=y.useCallback(A=>{var I,$;if(A.type==="tasks"){const B=Array.isArray((I=A.payload)==null?void 0:I.tasks)?A.payload.tasks:[],P=typeof(($=A.payload)==null?void 0:$.workspaceId)=="string"&&A.payload.workspaceId?A.payload.workspaceId:"";return s(P?X=>[...X.filter(H=>H.workspaceId!==P),...B]:X=>{const H=new Set(B.map(Q=>Q.id));return[...X.filter(Q=>!H.has(Q.id)),...B]}),!0}return!1},[]),x=y.useCallback(async(A,I,$,B,P,X,H,Q,he)=>{try{await pn.createTask({workspaceId:A,title:I,description:$||"",dependsOn:B||[],parentTaskId:P||"",defaultPersonaId:X||void 0,canDecompose:H??void 0}),Q==null||Q()}catch(W){const ie=W instanceof Di?W.message:"Failed to create task";he==null||he(ie)}},[]),S=y.useCallback(async(A,I,$,B)=>{d(A);try{await pn.startTask({taskId:A,personaId:I||"",environmentId:$||"",notes:B||""})}catch(P){if(P instanceof Di&&P.code===D_.ResourceExhausted)return;d(void 0)}},[]),j=y.useCallback(async A=>{try{await pn.stopTask({id:A})}catch{}},[]),w=y.useCallback(async A=>{try{await pn.completeTask({id:A})}catch{}},[]),T=y.useCallback(async A=>{try{await pn.resumeTask({id:A})}catch{}},[]),C=y.useCallback(async(A,I,$,B,P)=>{try{await pn.updateTask({id:A,title:I,description:$,dependsOn:B,...P!==void 0?{defaultPersonaId:P}:{}})}catch{}},[]),D=y.useCallback(async A=>{try{await pn.deleteTask({id:A})}catch{}},[]);return{tasks:t,tasksLoading:o,taskStartingId:c,loadTasks:p,loadAllTasks:m,createTask:x,startTask:S,stopTask:j,completeTask:w,resumeTask:T,updateTask:C,deleteTask:D,handleEvent:v,onDisconnect:_,handleLegacyMessage:b,domainHook:{onConnect:()=>m(),onDisconnect:_,handleEvent:v}}}function dP(){const[t,s]=y.useState([]),[o,r]=y.useState(void 0),[c,d]=y.useState(!1),{loading:u,track:p}=ks(),m=y.useCallback(async S=>{try{const j=await p(pn.queryFindings({workspaceId:S}));s(j.findings.map(Up))}catch{}},[p]),g=y.useCallback(async()=>{try{const S=await p(pn.queryFindings({workspaceId:""}));s(S.findings.map(Up))}catch{}},[p]),v=y.useCallback(async S=>{r(void 0),d(!0);try{const j=await pn.getFinding({id:S});r(Up(j))}catch{r(void 0)}finally{d(!1)}},[]),_=y.useCallback(S=>{if(S.type==="finding.posted"){const j=typeof S.payload.workspaceId=="string"?S.payload.workspaceId:"";return j&&m(j).catch(()=>{}),!0}return!1},[m]),b=y.useCallback(async(S,j,w,T,C)=>{try{await pn.postFinding({workspaceId:S,title:j,content:w,category:T??"general",tags:C??[]})}catch{}},[]);return{findings:t,selectedFinding:o,findingLoading:c,findingsLoading:u,loadFindings:m,loadAllFindings:g,loadFinding:v,postFinding:b,handleEvent:_,domainHook:{onConnect:()=>g(),onDisconnect:()=>{},handleEvent:_}}}function uP(){const[t,s]=y.useState([]),{loading:o,track:r}=ks(),c=y.useCallback(async()=>{try{const g=await r(Fe.listTokens({}));s(g.tokens.map(Q$))}catch{}},[r]),d=y.useCallback(g=>g.type==="token.changed"?(c().catch(()=>{}),!0):!1,[c]),u=y.useCallback(async(g,v,_,b,x)=>{try{await Fe.setToken({name:g,value:v,type:_,envVar:b,filePath:x})}catch{}},[]),p=y.useCallback(async g=>{try{await Fe.deleteToken({name:g})}catch{}},[]);return{tokens:t,tokensLoading:o,loadTokens:c,setToken:u,deleteToken:p,handleEvent:d,domainHook:{onConnect:()=>c(),onDisconnect:()=>{},handleEvent:d}}}function fP(){const[t,s]=y.useState({claude:"off",github:"off",copilot:"off",codex:"off",goose:"off"}),{loading:o,track:r}=ks(),c=y.useCallback(async()=>{try{const m=await r(Fe.getCredentialProviders({}));s(eP(m))}catch{}},[r]),d=y.useCallback(m=>m.type==="credential.providers_changed"?(v$(m.payload)&&s(m.payload),!0):!1,[]),u=y.useCallback(async m=>{const g=[{provider:"claude",value:m.claude},{provider:"github",value:m.github},{provider:"copilot",value:m.copilot},{provider:"codex",value:m.codex},{provider:"goose",value:m.goose}];await Promise.allSettled(g.map(({provider:v,value:_})=>Fe.setCredentialProvider({provider:v,value:_})))},[]);return{credentialProviders:t,credentialsLoading:o,loadCredentials:c,updateCredentialProviders:u,handleEvent:d,domainHook:{onConnect:()=>c(),onDisconnect:()=>{},handleEvent:d}}}function pP(){const[t,s]=y.useState([]),[o,r]=y.useState(""),[c,d]=y.useState(""),[u,p]=y.useState(!1),m=y.useCallback(async()=>{try{const _=await Fe.listCodespaces({});s(_.codespaces.map(tP)),d(_.error)}catch{}},[]),g=y.useCallback(async(_,b)=>{p(!0),r("");try{await Fe.createCodespace({repo:_,machine:b??""}),p(!1),await m()}catch(x){p(!1);const S=x instanceof Di?x.message:"Failed to create codespace";r(S)}},[m]);return{codespaces:t,codespaceError:o,codespaceListError:c,codespaceCreating:u,listCodespaces:m,createCodespace:g,domainHook:{onConnect:()=>m(),onDisconnect:()=>{},handleEvent:()=>!1}}}function mP(){const[t,s]=y.useState([]),{loading:o,track:r}=ks(),c=y.useCallback(async()=>{try{const v=await r(pn.listPersonas({}));s(v.personas.map(Hp))}catch{}},[r]),d=y.useCallback(v=>{switch(v.type){case"persona.created":case"persona.updated":case"persona.deleted":return c().catch(()=>{}),!0;default:return!1}},[c]),u=y.useCallback(async(v,_,b,x,S,j,w,T,C)=>{const D=await pn.createPersona({name:v,description:_,systemPrompt:b,runtime:x||"",model:S||"",maxTurns:j||0,type:w||"agent",script:T||"",allowedMcpTools:C||[]}),O=Hp(D);return s(A=>[...A.filter(I=>I.id!==O.id),O]),O},[]),p=y.useCallback(async(v,_,b,x,S,j,w,T,C,D)=>{const O={id:v};_!==void 0&&(O.name=_),b!==void 0&&(O.description=b),x!==void 0&&(O.systemPrompt=x),S!==void 0&&(O.runtime=S),j!==void 0&&(O.model=j),w!==void 0&&(O.maxTurns=w),T!==void 0&&(O.type=T),C!==void 0&&(O.script=C),D!==void 0&&(O.allowedMcpTools={tools:D});const A=await pn.updatePersona(O),I=Hp(A);return s($=>$.map(B=>B.id===I.id?I:B)),I},[]),m=y.useCallback(async v=>{await pn.deletePersona({id:v}),s(_=>_.filter(b=>b.id!==v))},[]);return{personas:t,personasLoading:o,loadPersonas:c,createPersona:u,updatePersona:p,deletePersona:m,handleEvent:d,domainHook:{onConnect:()=>c(),onDisconnect:()=>{},handleEvent:d}}}function hP(){const[t,s]=y.useState([]),{loading:o,track:r}=ks(),c=y.useRef(void 0),d=y.useCallback(async()=>{try{const _=await r(Uc.listSchedules({}));s(_.schedules.map(Vp))}catch{}},[r]),u=y.useCallback(_=>{switch(_.type){case"schedule.created":case"schedule.updated":case"schedule.deleted":return d().catch(()=>{}),!0;case"schedule.fired":return clearTimeout(c.current),c.current=setTimeout(()=>{d().catch(()=>{})},500),!0;default:return!1}},[d]),p=y.useCallback(async(_,b,x,S,j,w)=>{const T=await Uc.createSchedule({title:_,description:b,scheduleExpression:x,personaId:S,workspaceId:j||"",parentTaskId:w||""}),C=Vp(T);return s(D=>[...D.filter(O=>O.id!==C.id),C]),C},[]),m=y.useCallback(async(_,b)=>{const x={id:_};b.title!==void 0&&(x.title=b.title),b.description!==void 0&&(x.description=b.description),b.scheduleExpression!==void 0&&(x.scheduleExpression=b.scheduleExpression),b.personaId!==void 0&&(x.personaId=b.personaId),b.enabled!==void 0&&(x.enabled=b.enabled);const S=await Uc.updateSchedule(x),j=Vp(S);return s(w=>w.map(T=>T.id===j.id?j:T)),j},[]),g=y.useCallback(async _=>{await Uc.deleteSchedule({id:_}),s(b=>b.filter(x=>x.id!==_))},[]);return{schedules:t,schedulesLoading:o,loadSchedules:d,createSchedule:p,updateSchedule:m,deleteSchedule:g,handleEvent:u,domainHook:{onConnect:()=>d(),onDisconnect:()=>{clearTimeout(c.current)},handleEvent:u}}}function gP(t){if(t)try{return JSON.parse(t)}catch{return}}function vP(){const[t,s]=y.useState(new Map),[o,r]=y.useState([]),[c,d]=y.useState(void 0),[u,p]=y.useState(void 0),[m,g]=y.useState(!1),[v,_]=y.useState(""),b=y.useRef(""),x=y.useCallback(async A=>{const I=A??"";b.current=I,_(""),g(!0);try{const $=await Hc.listRecentKnowledgeNodes({limit:30,workspaceId:I}),B=new Map,P=[];for(const X of $.nodes)B.set(X.id,td(X));for(const X of $.edges)P.push(qp(X));for(const X of P){const H=B.get(X.source);H&&(H.val+=1);const Q=B.get(X.target);Q&&(Q.val+=1)}s(B),r(P)}catch{}finally{g(!1)}},[]),S=y.useCallback(async A=>{if(A.trim()){_(A),p(void 0),d(void 0),g(!0);try{const I=await Hc.searchKnowledge({query:A,limit:20,workspaceId:b.current}),$=new Map,B=[];for(const P of I.results){P.node&&$.set(P.node.id,td(P.node,P.edges.length));for(const X of P.edges)B.push(qp(X))}s($),r(B)}catch{}finally{g(!1)}}},[]),j=y.useCallback(()=>{x(b.current).catch(()=>{})},[x]),w=y.useCallback(async A=>{p(A);try{const I=await Hc.getKnowledgeNode({id:A});if(!I.node){d(void 0);return}d({node:td(I.node,I.edges.length),edges:I.edges.map($=>({fromId:$.fromId,toId:$.toId,type:$.type,metadata:gP($.metadataJson)}))})}catch{d(void 0)}},[]),T=y.useCallback(()=>{p(void 0),d(void 0)},[]),C=y.useCallback(async A=>{try{const I=await Hc.expandKnowledgeNode({id:A,depth:1});s($=>{const B=new Map($);for(const P of I.nodes)B.has(P.id)||B.set(P.id,td(P));return B}),r($=>{const B=new Set($.map(X=>`${X.source}:${X.target}:${X.type}`)),P=[];for(const X of I.edges){const H=qp(X),Q=`${H.source}:${H.target}:${H.type}`;B.has(Q)||P.push(H)}return[...$,...P]})}catch{}},[]),D=y.useCallback(A=>!1,[]),O={onConnect:async()=>{},onDisconnect:()=>{},handleEvent:D};return{graphData:{nodes:[...t.values()],links:o},selectedNode:c,selectedId:u,loading:m,searchQuery:v,search:S,clearSearch:j,selectNode:w,clearSelection:T,expandNode:C,loadRecent:x,handleEvent:D,domainHook:O}}function yP(){const t=y.useRef("default");y.useEffect(()=>{typeof Notification>"u"||(t.current=Notification.permission)},[]);function s(r){if(r.type!=="notification.escalated")return!1;if(typeof Notification>"u")return!0;if(t.current==="default")return Notification.requestPermission().then(u=>{t.current=u}).catch(()=>{}),!0;if(t.current!=="granted")return!0;const c=r.payload,d=new Notification(c.title||"Agent needs input",{body:c.message||"An agent is waiting for your input.",tag:c.escalationId,icon:"/icon-192x192.png"});return d.onclick=()=>{window.focus(),c.taskUrl&&(window.location.href=c.taskUrl),d.close()},!0}return{handleEvent:s,domainHook:{onConnect:async()=>{},onDisconnect:()=>{},handleEvent:s}}}function bP(){const[t,s]=y.useState([]),[o,r]=y.useState(!1),[c,d]=y.useState(!1),{loading:u,track:p}=ks(),m=y.useRef(0),g=y.useCallback(async()=>{const b=m.current;try{const x=await p(Fe.listStreams({}));m.current===b&&(s(x.streams.map(aP)),d(!1))}catch{m.current===b&&d(!0)}finally{m.current===b&&r(!0)}},[p]),v=y.useCallback(b=>!1,[]);return{streams:t,streamsLoading:u,streamsLoadedOnce:o,streamsLoadError:c,loadStreams:g,handleEvent:v,domainHook:{onConnect:g,onDisconnect:()=>{m.current+=1,s([]),r(!1),d(!1)},handleEvent:v}}}function _P(){const[t,s]=y.useState([]),{loading:o,track:r}=ks(),c=y.useCallback(async()=>{try{const m=await r(Fe.listPlugins({}));s(m.plugins.map(g=>({name:g.name,description:g.description,enabled:g.enabled,required:g.required,loaded:g.loaded})))}catch{}},[r]),d=y.useCallback(m=>m.type==="plugin.changed"?(c().catch(()=>{}),!0):!1,[c]),u=y.useCallback(async(m,g)=>{try{const v=await Fe.setPluginEnabled({name:m,enabled:g});s(_=>_.map(b=>b.name===v.name?{...b,enabled:v.enabled}:b))}catch{}},[]);return{plugins:t,pluginsLoading:o,loadPlugins:c,setPluginEnabled:u,domainHook:{onConnect:()=>c(),onDisconnect:()=>{},handleEvent:d}}}function xP(){const[t,s]=y.useState(""),[o,r]=y.useState(void 0),[c,d]=y.useState({}),{pluginNames:u}=xh(),p=Y$(u),m=iP(),g=rP(),v=lP(),_=cP(),b=dP(),x=uP(),S=fP(),j=pP(),w=mP(),T=hP(),C=vP(),D=yP(),O=bP(),A=_P(),I=[...p.has("environments")?[m.domainHook]:[],...p.has("sessions")?[g.domainHook]:[],...p.has("workspaces")?[v.domainHook]:[],...p.has("tasks")?[_.domainHook]:[],...p.has("findings")?[b.domainHook]:[],...p.has("tokens")?[x.domainHook]:[],...p.has("credentials")?[S.domainHook]:[],...p.has("codespaces")?[j.domainHook]:[],...p.has("personas")?[w.domainHook]:[],...p.has("schedules")?[T.domainHook]:[],...p.has("knowledge")?[C.domainHook]:[],...p.has("notifications")?[D.domainHook]:[],...p.has("streams")?[O.domainHook]:[],...p.has("plugins")?[A.domainHook]:[]],{connectionStatus:$}=V$({onSessionEvent:E=>{g.handleSessionEvent({sessionId:E.sessionId,eventType:R_(E.type),timestamp:E.timestamp,content:E.content,raw:E.raw||void 0})},onDomainEvent:E=>{try{const J=JSON.parse(E.payloadJson);he({id:E.id,type:E.type,timestamp:E.timestamp,payload:J})}catch{console.warn("[grackle] Failed to parse domain event payloadJson:",E.payloadJson)}},onConnect:W,onDisconnect:ie}),B="default_persona_id",P="onboarding_completed",X=y.useCallback(async E=>{const J=await Fe.setSetting({key:B,value:E});s(J.value)},[]),H=y.useCallback(async()=>{r(!0);try{await Fe.setSetting({key:P,value:"true"})}catch{}},[]),Q=y.useCallback(async(E,J)=>{try{const me=await Fe.getUsage({scope:E,id:J}),q=`${E}:${J}`;d(de=>({...de,[q]:nP(me)}))}catch{}},[]);function he(E){const J=E.payload.key,me=E.payload.value;if(E.type==="setting.changed"){J===B&&s(me??""),J===P&&r(me==="true");return}for(const q of I)if(q.handleEvent(E))break;(E.type==="environment.removed"||E.type==="environment.changed"||E.type==="task.started")&&g.loadSessions().catch(()=>{}),(E.type==="session.started"||E.type==="session.stopped")&&O.loadStreams().catch(()=>{})}async function W(){for(const E of I)E.onConnect().catch(()=>{});try{const E=await Fe.getSetting({key:B});s(E.value)}catch{}try{const E=await Fe.getSetting({key:P});r(E.value==="true")}catch{}}function ie(){I.forEach(E=>E.onDisconnect())}const L=y.useCallback(()=>{m.loadEnvironments().catch(()=>{}),g.loadSessions().catch(()=>{}),v.loadWorkspaces().catch(()=>{}),x.loadTokens().catch(()=>{})},[m.loadEnvironments,g.loadSessions,v.loadWorkspaces,x.loadTokens]);return{connectionStatus:$,environments:{environments:m.environments,environmentsLoading:m.environmentsLoading,provisionStatus:m.provisionStatus,operationError:m.operationError,clearOperationError:m.clearOperationError,loadEnvironments:m.loadEnvironments,addEnvironment:m.addEnvironment,updateEnvironment:m.updateEnvironment,provisionEnvironment:m.provisionEnvironment,stopEnvironment:m.stopEnvironment,removeEnvironment:m.removeEnvironment,domainHook:m.domainHook},sessions:{sessions:g.sessions,sessionsLoading:g.sessionsLoading,events:g.events,eventsDropped:g.eventsDropped,lastSpawnedId:g.lastSpawnedId,taskSessions:g.taskSessions,spawn:g.spawn,sendInput:g.sendInput,kill:g.kill,stopGraceful:g.stopGraceful,loadSessionEvents:g.loadSessionEvents,clearEvents:g.clearEvents,loadTaskSessions:g.loadTaskSessions,domainHook:g.domainHook},workspaces:{workspaces:v.workspaces,workspacesLoading:v.workspacesLoading,workspaceCreating:v.workspaceCreating,loadWorkspaces:v.loadWorkspaces,createWorkspace:v.createWorkspace,archiveWorkspace:v.archiveWorkspace,updateWorkspace:v.updateWorkspace,linkEnvironment:v.linkEnvironment,unlinkEnvironment:v.unlinkEnvironment,linkOperationError:v.linkOperationError,clearLinkOperationError:v.clearLinkOperationError,domainHook:v.domainHook},tasks:{tasks:_.tasks,tasksLoading:_.tasksLoading,taskStartingId:_.taskStartingId,loadTasks:_.loadTasks,loadAllTasks:_.loadAllTasks,createTask:_.createTask,startTask:_.startTask,stopTask:_.stopTask,completeTask:_.completeTask,resumeTask:_.resumeTask,updateTask:_.updateTask,deleteTask:_.deleteTask,domainHook:_.domainHook},findings:{findings:b.findings,selectedFinding:b.selectedFinding,findingLoading:b.findingLoading,findingsLoading:b.findingsLoading,loadFindings:b.loadFindings,loadAllFindings:b.loadAllFindings,loadFinding:b.loadFinding,postFinding:b.postFinding,domainHook:b.domainHook},tokens:{tokens:x.tokens,tokensLoading:x.tokensLoading,loadTokens:x.loadTokens,setToken:x.setToken,deleteToken:x.deleteToken,domainHook:x.domainHook},credentials:{credentialProviders:S.credentialProviders,credentialsLoading:S.credentialsLoading,updateCredentialProviders:S.updateCredentialProviders,domainHook:S.domainHook},codespaces:{codespaces:j.codespaces,codespaceError:j.codespaceError,codespaceListError:j.codespaceListError,codespaceCreating:j.codespaceCreating,listCodespaces:j.listCodespaces,createCodespace:j.createCodespace,domainHook:j.domainHook},personas:{personas:w.personas,personasLoading:w.personasLoading,createPersona:w.createPersona,updatePersona:w.updatePersona,deletePersona:w.deletePersona,domainHook:w.domainHook},schedules:{schedules:T.schedules,schedulesLoading:T.schedulesLoading,createSchedule:T.createSchedule,updateSchedule:T.updateSchedule,deleteSchedule:T.deleteSchedule,domainHook:T.domainHook},streams:{streams:O.streams,streamsLoading:O.streamsLoading,streamsLoadedOnce:O.streamsLoadedOnce,streamsLoadError:O.streamsLoadError,loadStreams:O.loadStreams,domainHook:O.domainHook},knowledge:C,plugins:{plugins:A.plugins,pluginsLoading:A.pluginsLoading,loadPlugins:A.loadPlugins,setPluginEnabled:A.setPluginEnabled},appDefaultPersonaId:t,setAppDefaultPersonaId:X,onboardingCompleted:o,completeOnboarding:H,usageCache:c,loadUsage:Q,refresh:L}}function kP({children:t}){const s=xP();return a.jsx(vh.Provider,{value:s,children:t})}function SP(t,s){const o=y.useRef(null);y.useEffect(()=>{const r=o.current;if(o.current=t,r===null)return;const c=new Map;for(const u of r)c.set(u.id,u);const d=new Set;for(const u of t){d.add(u.id);const p=c.get(u.id);if(p&&p.status!==u.status&&u.status!=="sleeping"){if(u.status==="connecting"){s("Provisioning environment…","info");continue}u.status==="connected"?s("Environment connected","success"):u.status==="error"?s("Environment provision failed","error"):u.status==="disconnected"&&(p.status==="connected"?s("Environment disconnected","warning"):s("Environment stopped","info"))}}for(const u of r)d.has(u.id)||s("Environment removed","info")},[t,s])}function jP(t,s,o){const r=y.useRef(t);y.useEffect(()=>{t&&t!==r.current&&(o(t,"error"),s()),r.current=t},[t,s,o])}const TP={working:{message:"Task is now running",variant:"info"},paused:{message:"Task paused",variant:"warning"},complete:{message:"Task complete",variant:"success"},failed:{message:"Task failed to complete",variant:"error"}};function wP(t){return TP[t]}function NP(t,s){if(t===void 0)return[];const o=[],r=new Map;for(const d of t)r.set(d.id,d);const c=new Set;for(const d of s){c.add(d.id);const u=r.get(d.id);if(!u||u.status===d.status)continue;const p=wP(d.status);p&&o.push(p)}for(const d of t)c.has(d.id)||o.push({message:"Task deleted",variant:"info"});return o}function CP(t,s){const o=y.useRef(void 0);y.useEffect(()=>{const r=o.current;o.current=t;const c=NP(r,t);for(const d of c)s(d.message,d.variant)},[t,s])}const EP="_dashboard_16pzm_1",AP="_kpiStrip_16pzm_11",DP="_kpiCard_16pzm_23",RP="_kpiValue_16pzm_68",MP="_kpiLabel_16pzm_76",IP="_bodyGrid_16pzm_84",OP="_section_16pzm_96",BP="_sectionHeader_16pzm_109",LP="_sectionIcon_16pzm_118",zP="_sectionTitle_16pzm_123",$P="_sectionCount_16pzm_131",PP="_sectionBody_16pzm_138",UP="_emptyHint_16pzm_143",HP="_sessionRow_16pzm_150",VP="_sessionPrompt_16pzm_177",qP="_sessionEnv_16pzm_186",GP="_sessionRuntime_16pzm_192",FP="_sessionStatus_16pzm_198",ZP="_statusDot_16pzm_207",KP="_attentionRow_16pzm_233",YP="_attentionTitle_16pzm_259",JP="_attentionMeta_16pzm_267",WP="_reasonBadge_16pzm_274",XP="_bottomGrid_16pzm_301",QP="_envRow_16pzm_312",e9="_envName_16pzm_323",t9="_envStatusBadge_16pzm_333",n9="_workspaceRow_16pzm_369",s9="_workspaceTop_16pzm_395",a9="_workspaceName_16pzm_401",i9="_workspaceCounts_16pzm_407",o9="_progressBar_16pzm_415",r9="_progressFill_16pzm_422",pe={dashboard:EP,kpiStrip:AP,kpiCard:DP,kpiValue:RP,kpiLabel:MP,bodyGrid:IP,section:OP,sectionHeader:BP,sectionIcon:LP,sectionTitle:zP,sectionCount:$P,sectionBody:PP,emptyHint:UP,sessionRow:HP,sessionPrompt:VP,sessionEnv:qP,sessionRuntime:GP,sessionStatus:FP,statusDot:ZP,attentionRow:KP,attentionTitle:YP,attentionMeta:JP,reasonBadge:WP,bottomGrid:XP,envRow:QP,envName:e9,envStatusBadge:t9,workspaceRow:n9,workspaceTop:s9,workspaceName:a9,workspaceCounts:i9,progressBar:o9,progressFill:r9};function l9(){return a.jsxs("div",{className:pe.dashboard,"aria-hidden":"true",children:[a.jsx("div",{className:pe.kpiStrip,children:Array.from({length:4},(t,s)=>a.jsxs("div",{className:pe.kpiCard,children:[a.jsx(Ne,{width:"3rem",height:"2rem"}),a.jsx(Ne,{width:"80%",height:"0.75rem"})]},s))}),a.jsxs("div",{className:pe.bodyGrid,children:[a.jsxs("div",{className:pe.section,children:[a.jsxs("div",{className:pe.sectionHeader,children:[a.jsx(Ne,{width:"1rem",height:"1rem",variant:"circular"}),a.jsx(Ne,{width:"8rem",height:"0.75rem"}),a.jsx("span",{className:pe.sectionCount,children:a.jsx(Ne,{width:"1rem",height:"0.75rem"})})]}),a.jsx("div",{className:pe.sectionBody,children:Array.from({length:3},(t,s)=>a.jsxs("div",{className:pe.sessionRow,style:{cursor:"default"},children:[a.jsx(Ne,{width:"60%",height:"0.875rem"}),a.jsx(Ne,{width:"4rem",height:"0.75rem"}),a.jsx(Ne,{width:"3rem",height:"0.75rem"}),a.jsx(Ne,{width:"3rem",height:"0.75rem"})]},s))})]}),a.jsxs("div",{className:pe.section,children:[a.jsxs("div",{className:pe.sectionHeader,children:[a.jsx(Ne,{width:"1rem",height:"1rem",variant:"circular"}),a.jsx(Ne,{width:"8rem",height:"0.75rem"}),a.jsx("span",{className:pe.sectionCount,children:a.jsx(Ne,{width:"1rem",height:"0.75rem"})})]}),a.jsx("div",{className:pe.sectionBody,children:Array.from({length:2},(t,s)=>a.jsxs("div",{className:pe.attentionRow,style:{cursor:"default"},children:[a.jsxs("div",{className:pe.attentionTitle,children:[a.jsx(Ne,{width:"3rem",height:"0.875rem",borderRadius:"var(--radius-sm)"}),a.jsx(Ne,{width:"70%",height:"0.875rem"})]}),a.jsx("div",{className:pe.attentionMeta,children:a.jsx(Ne,{width:"5rem",height:"0.625rem"})})]},s))})]})]}),a.jsxs("div",{className:pe.bottomGrid,children:[a.jsxs("div",{className:pe.section,children:[a.jsxs("div",{className:pe.sectionHeader,children:[a.jsx(Ne,{width:"1rem",height:"1rem",variant:"circular"}),a.jsx(Ne,{width:"9rem",height:"0.75rem"}),a.jsx("span",{className:pe.sectionCount,children:a.jsx(Ne,{width:"1rem",height:"0.75rem"})})]}),a.jsx("div",{className:pe.sectionBody,children:Array.from({length:2},(t,s)=>a.jsxs("div",{className:pe.envRow,children:[a.jsx(Ne,{width:"60%",height:"0.875rem"}),a.jsx(Ne,{width:"4rem",height:"0.875rem",borderRadius:"var(--radius-sm)"})]},s))})]}),a.jsxs("div",{className:pe.section,children:[a.jsxs("div",{className:pe.sectionHeader,children:[a.jsx(Ne,{width:"1rem",height:"1rem",variant:"circular"}),a.jsx(Ne,{width:"6rem",height:"0.75rem"}),a.jsx("span",{className:pe.sectionCount,children:a.jsx(Ne,{width:"1rem",height:"0.75rem"})})]}),a.jsx("div",{className:pe.sectionBody,children:Array.from({length:2},(t,s)=>a.jsxs("div",{className:pe.workspaceRow,style:{cursor:"default"},children:[a.jsxs("div",{className:pe.workspaceTop,children:[a.jsx(Ne,{width:"50%",height:"0.875rem"}),a.jsx(Ne,{width:"2rem",height:"0.75rem"})]}),a.jsx("div",{className:pe.progressBar,children:a.jsx("div",{className:pe.progressFill,style:{width:"0%"}})})]},s))})]})]})]})}const c9={hidden:{opacity:0,y:12},visible:t=>({opacity:1,y:0,transition:{delay:t*.06,duration:.3,ease:"easeOut"}})},nd={hidden:{opacity:0,y:16},visible:t=>({opacity:1,y:0,transition:{delay:.15+t*.08,duration:.35,ease:"easeOut"}})};function d9(t,s,o,r){const c=[`${t} of ${s} tasks completed`];return o>0&&c.push(`${o} in progress`),r>0&&c.push(`${r} failed`),c.join(", ")}function sd({value:t,label:s,accent:o,index:r,testId:c}){return a.jsxs(Nt.div,{className:pe.kpiCard,"data-accent":o,"data-testid":c,variants:c9,initial:"hidden",animate:"visible",custom:r,children:[a.jsx("span",{className:pe.kpiValue,children:t}),a.jsx("span",{className:pe.kpiLabel,children:s})]})}function u9(){const{workspaces:{workspaces:t,workspacesLoading:s},tasks:{tasks:o,tasksLoading:r,loadTasks:c},sessions:{sessions:d,sessionsLoading:u},environments:{environments:p,environmentsLoading:m}}=rt(),g=ct(),v=y.useRef(new Set);y.useEffect(()=>{for(const w of t)v.current.has(w.id)||(v.current.add(w.id),c(w.id).catch(()=>{}))},[t,c]);const _=y.useMemo(()=>C$(d,o,p),[d,o,p]),b=y.useMemo(()=>A$(d,p),[d,p]),x=y.useMemo(()=>E$(o,t),[o,t]),S=y.useMemo(()=>D$(t,o),[t,o,p]);return d.length===0&&o.length===0&&p.length===0&&t.length===0&&(u||r||m||s)?a.jsx(l9,{}):a.jsxs("div",{className:pe.dashboard,"data-testid":"dashboard",children:[a.jsxs("div",{className:pe.kpiStrip,"data-testid":"dashboard-kpi-strip",children:[a.jsx(sd,{value:_.activeSessions,label:"Active Sessions",accent:"green",index:0,testId:"kpi-active-sessions"}),a.jsx(sd,{value:_.blockedTasks,label:"Blocked Tasks",accent:"yellow",index:1,testId:"kpi-blocked-tasks"}),a.jsx(sd,{value:_.attentionTasks,label:"Needs Attention",accent:"red",index:2,testId:"kpi-attention-tasks"}),a.jsx(sd,{value:_.unhealthyEnvironments,label:"Unhealthy Envs",accent:"blue",index:3,testId:"kpi-unhealthy-envs"})]}),a.jsxs("div",{className:pe.bodyGrid,children:[a.jsxs(Nt.div,{className:pe.section,variants:nd,initial:"hidden",animate:"visible",custom:0,"data-testid":"dashboard-active-sessions",children:[a.jsxs("div",{className:pe.sectionHeader,children:[a.jsx("span",{className:pe.sectionIcon,"aria-hidden":"true",children:"●"}),a.jsx("span",{className:pe.sectionTitle,children:"Active Sessions"}),a.jsx("span",{className:pe.sectionCount,children:b.length})]}),a.jsx("div",{className:pe.sectionBody,children:b.length===0?a.jsx("div",{className:pe.emptyHint,children:"No active sessions"}):b.map(({session:w,environmentName:T})=>a.jsxs("button",{type:"button",className:pe.sessionRow,onClick:()=>g(Ld(w.id)),"data-testid":"session-row",children:[a.jsx("span",{className:pe.sessionPrompt,title:w.prompt,children:w.prompt||"—"}),a.jsx("span",{className:pe.sessionEnv,children:T}),a.jsx("span",{className:pe.sessionRuntime,children:w.runtime}),a.jsxs("span",{className:pe.sessionStatus,children:[a.jsx("span",{className:pe.statusDot,"data-status":w.status}),w.status]})]},w.id))})]}),a.jsxs(Nt.div,{className:pe.section,variants:nd,initial:"hidden",animate:"visible",custom:1,"data-testid":"dashboard-needs-attention",children:[a.jsxs("div",{className:pe.sectionHeader,children:[a.jsx("span",{className:pe.sectionIcon,"aria-hidden":"true",children:"⚑"}),a.jsx("span",{className:pe.sectionTitle,children:"Needs Attention"}),a.jsx("span",{className:pe.sectionCount,children:x.length})]}),a.jsx("div",{className:pe.sectionBody,children:x.length===0?a.jsx("div",{className:pe.emptyHint,children:"All clear"}):x.map(({task:w,reason:T,workspaceName:C})=>a.jsxs("button",{type:"button",className:pe.attentionRow,onClick:()=>g($n(w.id)),"data-testid":"attention-row",children:[a.jsxs("div",{className:pe.attentionTitle,children:[a.jsx("span",{className:pe.reasonBadge,"data-reason":T,children:T}),w.title]}),a.jsx("div",{className:pe.attentionMeta,children:a.jsx("span",{children:C})})]},w.id))})]})]}),a.jsxs("div",{className:pe.bottomGrid,children:[a.jsxs(Nt.div,{className:pe.section,variants:nd,initial:"hidden",animate:"visible",custom:2,"data-testid":"dashboard-env-health",children:[a.jsxs("div",{className:pe.sectionHeader,children:[a.jsx("span",{className:pe.sectionIcon,"aria-hidden":"true",children:"◈"}),a.jsx("span",{className:pe.sectionTitle,children:"Environment Health"}),a.jsx("span",{className:pe.sectionCount,children:p.length})]}),a.jsx("div",{className:pe.sectionBody,children:p.length===0?a.jsx("div",{className:pe.emptyHint,children:"No environments configured"}):p.map(w=>a.jsxs("div",{className:pe.envRow,"data-testid":"dashboard-env-row",children:[a.jsx("span",{className:pe.envName,children:w.displayName}),a.jsx("span",{className:pe.envStatusBadge,"data-status":w.status,children:w.status})]},w.id))})]}),a.jsxs(Nt.div,{className:pe.section,variants:nd,initial:"hidden",animate:"visible",custom:3,"data-testid":"dashboard-workspace-snapshot",children:[a.jsxs("div",{className:pe.sectionHeader,children:[a.jsx("span",{className:pe.sectionIcon,"aria-hidden":"true",children:"▦"}),a.jsx("span",{className:pe.sectionTitle,children:"Workspaces"}),a.jsx("span",{className:pe.sectionCount,children:t.length})]}),a.jsx("div",{className:pe.sectionBody,children:S.length===0?a.jsx("div",{className:pe.emptyHint,children:"No workspaces yet"}):S.map(({workspace:w,totalTasks:T,completedTasks:C,workingTasks:D,failedTasks:O})=>{const A=T>0?Math.round(C/T*100):0;return a.jsxs("button",{type:"button",className:pe.workspaceRow,onClick:()=>g(Ri(w.id,w.linkedEnvironmentIds[0])),"data-testid":"workspace-row",children:[a.jsxs("div",{className:pe.workspaceTop,children:[a.jsx("span",{className:pe.workspaceName,children:w.name}),a.jsxs("span",{className:pe.workspaceCounts,"aria-label":d9(C,T,D,O),children:[C,"/",T,D>0&&a.jsxs("span",{style:{color:"var(--accent-green)"},"aria-hidden":"true",children:["▸",D]}),O>0&&a.jsxs("span",{style:{color:"var(--accent-red)"},"aria-hidden":"true",children:["✗",O]})]})]}),T>0&&a.jsx("div",{className:pe.progressBar,children:a.jsx("div",{className:pe.progressFill,style:{width:`${A}%`}})})]},w.id)})})]})]})]})}const f9="_panelContainer_1udy7_1",p9="_emptyState_1udy7_8",m9="_workspaceSummary_1udy7_17",h9="_workspaceSummaryTitle_1udy7_28",g9="_workspaceSummarySubtitle_1udy7_32",v9="_header_1udy7_36",y9="_headerInfo_1udy7_71",b9="_headerTitle_1udy7_106",_9="_taskStatusBadge_1udy7_128",x9="_taskBranch_1udy7_137",k9="_taskBlockedBadge_1udy7_143",S9="_tabBar_1udy7_277",j9="_tab_1udy7_277",T9="_active_1udy7_303",w9="_eventScroll_1udy7_308",N9="_tabContent_1udy7_314",C9="_noContext_1udy7_319",E9="_overviewContent_1udy7_325",A9="_overviewDashboard_1udy7_334",D9="_overviewHero_1udy7_340",R9="_overviewSection_1udy7_347",M9="_overviewLabel_1udy7_353",I9="_envRow_1udy7_360",O9="_timeline_1udy7_366",B9="_timelineRow_1udy7_372",L9="_waitingMessage_1udy7_379",z9="_errorMessage_1udy7_383",$9="_emptyCta_1udy7_387",P9="_ctaTitle_1udy7_399",U9="_ctaDescription_1udy7_405",H9="_ctaButton_1udy7_412",V9="_workspaceHeader_1udy7_533",q9="_workspaceName_1udy7_558",G9="_workspaceMeta_1udy7_571",F9="_metaRow_1udy7_579",Z9="_metaLabel_1udy7_592",K9="_metaValue_1udy7_607",Y9="_archiveButton_1udy7_617",J9="_repoLink_1udy7_647",W9="_metaToggle_1udy7_657",X9="_metaToggleArrow_1udy7_678",Q9="_metaToggleArrowOpen_1udy7_683",eU="_progressBarContainer_1udy7_687",tU="_progressBar_1udy7_687",nU="_progressFill_1udy7_703",sU="_progressLabel_1udy7_710",aU="_metaTimestamps_1udy7_717",iU="_metaTimestamp_1udy7_717",oU="_metaPlaceholder_1udy7_739",rU="_linkedEnvList_1udy7_744",lU="_linkedEnvChip_1udy7_750",cU="_chipDismiss_1udy7_762",dU="_linkError_1udy7_777",uU="_linkEnvSelect_1udy7_782",Y={panelContainer:f9,emptyState:p9,workspaceSummary:m9,workspaceSummaryTitle:h9,workspaceSummarySubtitle:g9,header:v9,headerInfo:y9,headerTitle:b9,taskStatusBadge:_9,taskBranch:x9,taskBlockedBadge:k9,tabBar:S9,tab:j9,active:T9,eventScroll:w9,tabContent:N9,noContext:C9,overviewContent:E9,overviewDashboard:A9,overviewHero:D9,overviewSection:R9,overviewLabel:M9,envRow:I9,timeline:O9,timelineRow:B9,waitingMessage:L9,errorMessage:z9,emptyCta:$9,ctaTitle:P9,ctaDescription:U9,ctaButton:H9,workspaceHeader:V9,workspaceName:q9,workspaceMeta:G9,metaRow:F9,metaLabel:Z9,metaValue:K9,archiveButton:Y9,repoLink:J9,metaToggle:W9,metaToggleArrow:X9,metaToggleArrowOpen:Q9,progressBarContainer:eU,progressBar:tU,progressFill:nU,progressLabel:sU,metaTimestamps:aU,metaTimestamp:iU,metaPlaceholder:oU,linkedEnvList:rU,linkedEnvChip:lU,chipDismiss:cU,linkError:dU,linkEnvSelect:uU};function fU(){return a.jsx("div",{className:Y.emptyState,children:"Select a task or click + to create one"})}function pU(){return a.jsx("div",{className:Y.emptyState,children:"Select an environment to manage its workspaces, or add a new one."})}function mU(){const{workspaces:{workspaces:t},environments:{environments:s}}=rt(),o=ct(),r=s.length>0;return t.length>0?a.jsx(u9,{}):a.jsxs("div",{className:Y.emptyCta,"data-testid":"welcome-cta",children:[a.jsx("div",{className:Y.ctaTitle,children:"Welcome to Grackle"}),a.jsx("div",{className:Y.ctaDescription,children:"Organize your work into workspaces and let agents tackle the tasks."}),a.jsx("button",{className:Y.ctaButton,onClick:()=>o(ax),disabled:!r,"data-testid":"welcome-create-button",children:"Create Your First Workspace"}),!r&&a.jsx("div",{className:Y.ctaDescription,children:"Add an environment first before creating a workspace."})]})}const hU="_panelContainer_1rih4_1",gU="_chatHeader_1rih4_9",vU="_chatHeaderInfo_1rih4_38",yU="_chatHeaderActions_1rih4_44",bU="_detailButton_1rih4_50",_U="_emptyState_1rih4_64",xU="_emptyTitle_1rih4_76",kU="_emptyDescription_1rih4_82",SU="_emptyHint_1rih4_88",Kt={panelContainer:hU,chatHeader:gU,chatHeaderInfo:vU,chatHeaderActions:yU,detailButton:bU,emptyState:_U,emptyTitle:xU,emptyDescription:kU,emptyHint:SU};function Fp(){return a.jsx("div",{className:Kt.panelContainer,"aria-hidden":"true",children:a.jsxs("div",{style:{flex:1,overflow:"hidden",padding:"var(--space-md)",display:"flex",flexDirection:"column",gap:"var(--space-md)"},children:[a.jsx(Ne,{width:"65%",height:"2.5rem",borderRadius:"var(--radius-sm)"}),a.jsx(Ne,{width:"85%",height:"4rem",borderRadius:"var(--radius-sm)"}),a.jsx(Ne,{width:"45%",height:"2rem",borderRadius:"var(--radius-sm)"}),a.jsx(Ne,{width:"75%",height:"3rem",borderRadius:"var(--radius-sm)"}),a.jsx(Ne,{width:"55%",height:"2.5rem",borderRadius:"var(--radius-sm)"})]})})}function jU({hasLocalEnvironment:t}){return a.jsxs("div",{className:Kt.emptyState,"data-testid":"chat-empty-state",children:[a.jsx("div",{className:Kt.emptyTitle,children:"Welcome to Grackle"}),a.jsx("div",{className:Kt.emptyDescription,children:t?"Type a message below to start chatting with the System agent. It can help you plan work, create tasks, and coordinate agents.":"Add a local environment in Settings to start chatting."}),!t&&a.jsx("div",{className:Kt.emptyHint,children:"Go to Settings → Environments to add one."})]})}function TU({streamName:t}){return a.jsxs("div",{className:Kt.emptyState,"data-testid":"stream-no-session-state",children:[a.jsx("div",{className:Kt.emptyTitle,children:t}),a.jsx("div",{className:Kt.emptyDescription,children:"No active sessions on this stream."})]})}function wU(){return a.jsxs("div",{className:Kt.emptyState,"data-testid":"stream-not-found-state",children:[a.jsx("div",{className:Kt.emptyTitle,children:"Stream not found"}),a.jsxs("div",{className:Kt.emptyDescription,children:["This stream no longer exists or hasn't been created yet."," ",a.jsx(_l,{to:dl,children:"Back to System"})]})]})}function NU(){return a.jsxs("div",{className:Kt.emptyState,"data-testid":"stream-unavailable-state",children:[a.jsx("div",{className:Kt.emptyTitle,children:"Stream unavailable"}),a.jsxs("div",{className:Kt.emptyDescription,children:["The stream could not be loaded. It may have been deleted, or there may be a temporary network problem."," ",a.jsx(_l,{to:dl,children:"Back to System"})]})]})}function y_(){const{streamId:t}=Hn(),{tasks:{tasks:s,tasksLoading:o,startTask:r},sessions:{sessions:c,sessionsLoading:d,events:u,eventsDropped:p,taskSessions:m,loadTaskSessions:g,loadSessionEvents:v,kill:_,stopGraceful:b,sendInput:x,spawn:S},environments:{environments:j,provisionEnvironment:w},personas:{personas:T},streams:{streams:C,streamsLoading:D,streamsLoadedOnce:O,streamsLoadError:A}}=rt(),{showToast:I}=gn(),[$,B]=y.useState(!1),P=y.useRef(void 0),[X,H]=y.useState(),Q=s.find(be=>be.id===$r),he=t===void 0&&Q!=null&&Q.latestSessionId?c.find(be=>be.id===Q.latestSessionId)??(m[$r]??[]).find(be=>be.id===Q.latestSessionId):void 0;y.useEffect(()=>{t===void 0&&g($r).catch(()=>{})},[t,g]),y.useEffect(()=>{t===void 0&&(Q!=null&&Q.latestSessionId)&&g($r).catch(()=>{})},[t,Q==null?void 0:Q.latestSessionId,g]);const W=t!==void 0?C.find(be=>be.id===t):void 0,ie=y.useMemo(()=>!W||W.subscribers.length===0?void 0:(W.subscribers.find(_e=>_e.permission==="rw")??W.subscribers[0]).sessionId,[W]),L=ie!==void 0?c.find(be=>be.id===ie):void 0,E=t===void 0?he:L;y.useEffect(()=>{E&&E.id!==P.current&&(P.current=E.id,v(E.id).catch(()=>{}))},[E==null?void 0:E.id,v]),y.useEffect(()=>{P.current=void 0,B(!1)},[t]);const J=y.useMemo(()=>{if(!E)return[];const be=u.filter(fe=>fe.sessionId===E.id);return _h(bh(be))},[u,E==null?void 0:E.id]),me=j.find(be=>be.adapterType==="local"&&be.status==="connected"),q=E!==void 0&&E.status!=="stopped"&&E.status!=="suspended",de=(E==null?void 0:E.status)==="idle";y.useEffect(()=>{X&&E&&de&&(x(E.id,X).catch(()=>{}),H(void 0))},[X,de,E==null?void 0:E.id,x]);const re=y.useCallback((be,fe,_e,ke)=>{ke&&H(ke),r(be,fe,_e).catch(()=>{})},[r]);if(t===void 0&&!Q&&(d||o))return a.jsx(Fp,{});if(t!==void 0&&!W&&(D||!O))return a.jsx(Fp,{});if(t!==void 0&&W&&d&&!E)return a.jsx(Fp,{});if(t!==void 0&&!W)return a.jsx("div",{className:Kt.panelContainer,"data-testid":"chat-page",children:a.jsx(al,{events:[],eventsDropped:0,emptyState:A?a.jsx(NU,{}):a.jsx(wU,{}),onShowToast:I})});const xe=t!==void 0&&W?W.name:void 0;return a.jsxs("div",{className:Kt.panelContainer,"data-testid":"chat-page",children:[q&&a.jsxs("div",{className:Kt.chatHeader,children:[a.jsxs("span",{className:Kt.chatHeaderInfo,children:[xe&&a.jsxs("strong",{children:[xe," — "]}),"Session: ",E.id.slice(0,8)," | ",E.runtime," | ",E.status]}),a.jsxs("div",{className:Kt.chatHeaderActions,children:[W&&a.jsx("button",{className:Kt.detailButton,onClick:()=>B(be=>!be),"aria-label":"Stream details","aria-expanded":$,"data-testid":"stream-detail-toggle",children:"Info"}),a.jsx(ox,{label:"Stop",onClick:()=>{b(E.id).catch(()=>{})},variant:"danger",size:"sm","data-testid":"stop-split-button",options:[{label:"Stop",description:"Graceful shutdown",onClick:()=>{b(E.id).catch(()=>{})}},{label:"Kill",description:"Force kill",onClick:()=>{_(E.id).catch(()=>{})}}]})]})]}),t!==void 0&&W&&!E&&!d&&a.jsx(al,{events:[],eventsDropped:0,emptyState:a.jsx(TU,{streamName:W.name}),onShowToast:I}),(t===void 0||E)&&a.jsx(al,{events:J,eventsDropped:p,emptyState:t===void 0?a.jsx(jU,{hasLocalEnvironment:!!me}):void 0,onShowToast:I}),t===void 0&&me&&q&&a.jsx(rl,{mode:"send",sessionId:E.id,environmentId:E.environmentId,personas:T,environments:j,onSendInput:(be,fe)=>{x(be,fe).catch(()=>{})},onSpawn:(be,fe,_e)=>{S(be,fe,_e).catch(()=>{})},onStartTask:(be,fe,_e)=>{r(be,fe,_e).catch(()=>{})},onProvisionEnvironment:be=>{w(be).catch(()=>{})},onShowToast:I}),t===void 0&&me&&!q&&a.jsx(rl,{mode:"start",taskId:$r,environmentId:me.id,personas:T,environments:j,onSendInput:(be,fe)=>{x(be,fe).catch(()=>{})},onSpawn:(be,fe,_e)=>{S(be,fe,_e).catch(()=>{})},onStartTask:re,onProvisionEnvironment:be=>{w(be).catch(()=>{})},onShowToast:I}),$&&W&&a.jsx(_z,{stream:W,onClose:()=>B(!1)})]})}function CU(){const t=x$(),[s]=Im(),o=s.get("env")??"",{sessions:{sendInput:r,spawn:c},tasks:{startTask:d},personas:{personas:u},environments:{environments:p,provisionEnvironment:m}}=rt(),{showToast:g}=gn();return a.jsxs("div",{className:Y.panelContainer,children:[a.jsx(xs,{segments:t}),a.jsx("div",{className:Y.emptyState,children:"Enter a prompt below to start a new session"}),a.jsx(rl,{mode:"spawn",environmentId:o,showPersonaSelect:!0,personas:u,environments:p,onSendInput:(v,_)=>{r(v,_).catch(()=>{})},onSpawn:(v,_,b)=>{c(v,_,b).catch(()=>{})},onStartTask:(v,_,b)=>{d(v,_,b).catch(()=>{})},onProvisionEnvironment:v=>{m(v).catch(()=>{})},onShowToast:g})]})}function EU(){return a.jsxs("div",{className:Y.panelContainer,"aria-hidden":"true",children:[a.jsxs("div",{className:Y.header,children:[a.jsx("span",{children:a.jsx(Ne,{width:"10rem",height:"0.875rem"})}),a.jsx("span",{className:Y.headerInfo,children:a.jsx(Ne,{width:"16rem",height:"0.875rem"})})]}),a.jsx("div",{className:Y.eventScroll,children:a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"var(--space-md)"},children:[a.jsx(Ne,{width:"70%",height:"2.5rem",borderRadius:"var(--radius-sm)"}),a.jsx(Ne,{width:"90%",height:"4rem",borderRadius:"var(--radius-sm)"}),a.jsx(Ne,{width:"50%",height:"2rem",borderRadius:"var(--radius-sm)"}),a.jsx(Ne,{width:"80%",height:"3.5rem",borderRadius:"var(--radius-sm)"}),a.jsx(Ne,{width:"60%",height:"2.5rem",borderRadius:"var(--radius-sm)"})]})})]})}function AU({sessionId:t,session:s,isActive:o,onStop:r,onKill:c}){return a.jsxs("div",{className:Y.header,children:[a.jsxs("span",{children:["Session: ",t.slice(0,8),s&&` | ${s.runtime} | ${s.endReason||s.status}`,s!=null&&s.inputTokens||s!=null&&s.outputTokens||s!=null&&s.costMillicents?` | ${zo((s.inputTokens??0)+(s.outputTokens??0))} tokens · ${Ms(s.costMillicents??0)}`:""]}),a.jsxs("span",{className:Y.headerInfo,children:[s&&a.jsx("span",{children:s.prompt.length>60?s.prompt.slice(0,60)+"...":s.prompt}),o&&a.jsx(ox,{label:"Stop",onClick:r,variant:"danger",size:"sm","data-testid":"stop-split-button",options:[{label:"Stop",description:"Graceful shutdown",onClick:r},{label:"Kill",description:"Force kill",onClick:c}]})]})]})}function DU({session:t}){const s=t&&(t.status==="stopped"||t.status==="suspended"),o=s?`Session ${t.endReason||t.status} with no events recorded.`:"Waiting for events...";return a.jsx("div",{className:s?Y.errorMessage:Y.waitingMessage,children:o})}function RU(){const{sessionId:t}=Hn(),{sessions:{events:s,eventsDropped:o,sessions:r,sessionsLoading:c,kill:d,stopGraceful:u,loadSessionEvents:p,sendInput:m,spawn:g},tasks:{startTask:v},personas:{personas:_},environments:{environments:b,provisionEnvironment:x}}=rt(),{showToast:S}=gn(),j=y.useRef(void 0),w=k$(t),T=r.find(O=>O.id===t)??void 0,C=y.useMemo(()=>{const O=t?s.filter(A=>A.sessionId===t):[];return _h(bh(O))},[s,t]);if(y.useEffect(()=>{t&&t!==j.current&&(j.current=t,p(t).catch(()=>{}))},[t,p]),!T&&c)return a.jsx(EU,{});if(!t)return a.jsx("div",{className:Y.emptyState,children:"No session selected"});const D=(T==null?void 0:T.status)==="running"||(T==null?void 0:T.status)==="idle";return a.jsxs("div",{className:Y.panelContainer,children:[a.jsx(xs,{segments:w}),a.jsx(AU,{sessionId:t,session:T,isActive:D,onStop:()=>{u(t).catch(()=>{})},onKill:()=>{d(t).catch(()=>{})}}),a.jsx(al,{events:C,eventsDropped:o,emptyState:a.jsx(DU,{session:T}),onShowToast:S,sessions:r,currentSessionId:t,environments:b,personas:_,onForward:(O,A)=>m(O,A)}),D&&a.jsx(rl,{mode:"send",sessionId:t,environmentId:T.environmentId,personas:_,environments:b,onSendInput:(O,A)=>{m(O,A).catch(()=>{})},onSpawn:(O,A,I)=>{g(O,A,I).catch(()=>{})},onStartTask:(O,A,I)=>{v(O,A,I).catch(()=>{})},onProvisionEnvironment:O=>{x(O).catch(()=>{})},onShowToast:S})]})}function MU(t){if(!t)return!1;const s=t.tagName;return!!(s==="INPUT"||s==="TEXTAREA"||s==="SELECT"||t.isContentEditable)}function la(t,s){const o=y.useRef(s);o.current=s;const{key:r,ctrl:c=!1,shift:d=!1,suppressInInputs:u=!0,enabled:p=!0}=t;y.useEffect(()=>{if(!p)return;const m=g=>{if(u&&MU(document.activeElement??void 0))return;const v=g.ctrlKey||g.metaKey;c===v&&(d&&!g.shiftKey||g.key===r&&o.current())};return document.addEventListener("keydown",m),()=>{document.removeEventListener("keydown",m)}},[r,c,d,u,p])}function IU(){return a.jsxs("div",{className:Y.panelContainer,"aria-hidden":"true",children:[a.jsx("div",{className:Y.workspaceHeader,children:a.jsx("span",{className:Y.workspaceName,children:a.jsx(Ne,{width:"12rem",height:"1.25rem"})})}),a.jsx("div",{className:Y.metaToggle,style:{cursor:"default"},children:a.jsx(Ne,{width:"4rem",height:"0.625rem"})}),a.jsxs("div",{className:Y.progressBarContainer,children:[a.jsx("div",{className:Y.progressBar,children:a.jsx("div",{className:Y.progressFill,style:{width:"0%"}})}),a.jsx(Ne,{width:"2rem",height:"0.625rem"})]}),a.jsxs("div",{className:Y.tabBar,role:"tablist","aria-label":"Workspace view",children:[a.jsx("span",{className:`${Y.tab} ${Y.active}`,children:"Graph"}),a.jsx("span",{className:Y.tab,children:"Board"}),a.jsx("span",{className:Y.tab,children:"Tasks"})]}),a.jsx("div",{className:Y.overviewContent,children:Array.from({length:3},(t,s)=>a.jsx(jd,{lines:2},s))})]})}function b_(t){if(!t)return"";const s=new Date(t);if(isNaN(s.getTime()))return"";const r=Date.now()-s.getTime();if(r<0)return"just now";const c=Math.floor(r/6e4);if(c<1)return"just now";if(c<60)return`${c}m ago`;const d=Math.floor(c/60);if(d<24)return`${d}h ago`;const u=Math.floor(d/24);return u<30?`${u}d ago`:s.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}const Zp=100;function OU(t){try{const s=new URL(t);return s.protocol!=="http:"&&s.protocol!=="https:"?void 0:s.toString()}catch{return}}function BU(){const{workspaceId:t,environmentId:s}=Hn(),o=ct(),{tasks:{tasks:r},environments:{environments:c},workspaces:{workspaces:d,workspacesLoading:u,archiveWorkspace:p,updateWorkspace:m,linkEnvironment:g,unlinkEnvironment:v,linkOperationError:_,clearLinkOperationError:b},personas:{personas:x},sessions:{sessions:S},usageCache:j,loadUsage:w}=rt(),{resolvedThemeId:T}=ak(),[C,D]=y.useState("tasks"),[O,A]=y.useState(!1),[I,$]=y.useState(null),[B,P]=y.useState(!1),X=y.useRef(void 0),H=d.find(q=>q.id===t),Q=s??(H==null?void 0:H.linkedEnvironmentIds[0])??"",he=S$(t,Q,d,c);la({key:"1"},()=>D("graph")),la({key:"2"},()=>D("board")),la({key:"3"},()=>D("tasks")),y.useEffect(()=>{const q=X.current;X.current=t,!(q===void 0||q===t)&&I!==null&&$(null)},[t,I]);const W=S.reduce((q,de)=>q+(de.costMillicents??0),0);y.useEffect(()=>{t&&w("workspace",t).catch(()=>{})},[t,w,W]);const ie=t?j[`workspace:${t}`]:void 0,L=r.filter(q=>q.workspaceId===t),E=L.filter(q=>q.status==="complete").length,J=L.length,me=J>0?Math.round(E/J*100):0;return!H&&u?a.jsx(IU,{}):a.jsxs("div",{className:Y.panelContainer,children:[a.jsx(xs,{segments:he}),a.jsxs("div",{className:Y.workspaceHeader,children:[a.jsx("span",{className:Y.workspaceName,"data-testid":"workspace-name",children:a.jsx(Zt,{value:(H==null?void 0:H.name)||"",onSave:q=>{H&&m(H.id,{name:q}).catch(()=>{})},validate:q=>{const de=q.trim();if(!de)return"Name is required";if(de.length>Zp)return`Max ${Zp} characters`},maxLength:Zp,fieldId:"name",activeFieldId:I,onActivate:$,ariaLabel:"Workspace name",renderDisplay:q=>q||t||void 0,"data-testid":"edit-name"})}),a.jsx("button",{className:Y.archiveButton,onClick:()=>A(!0),title:"Archive workspace","data-testid":"archive-workspace-button",children:"Archive"})]}),a.jsxs("button",{className:Y.metaToggle,onClick:()=>P(!B),"aria-expanded":!B,"aria-controls":"workspace-meta-panel","data-testid":"meta-toggle",children:[a.jsx("span",{className:`${Y.metaToggleArrow} ${B?"":Y.metaToggleArrowOpen}`,children:"▶"}),"Details"]}),!B&&a.jsxs("div",{className:Y.workspaceMeta,"data-testid":"workspace-meta",id:"workspace-meta-panel",children:[a.jsxs("div",{className:Y.metaRow,children:[a.jsx("span",{className:Y.metaLabel,children:"Description"}),a.jsx("div",{className:Y.metaValue,children:a.jsx(ym,{value:(H==null?void 0:H.description)||"",onSave:q=>{H&&m(H.id,{description:q}).catch(()=>{})},fieldId:"description",activeFieldId:I,onActivate:$,renderDisplay:q=>q?a.jsx("span",{className:Y.overviewMarkdown,children:a.jsx(Ad,{remarkPlugins:[Dd],children:q})}):void 0,placeholder:"No description",ariaLabel:"Workspace description","data-testid":"edit-description"})})]}),a.jsxs("div",{className:Y.metaRow,children:[a.jsx("span",{className:Y.metaLabel,children:"Repository"}),a.jsx("div",{className:Y.metaValue,children:a.jsx(Zt,{value:(H==null?void 0:H.repoUrl)||"",onSave:q=>{H&&m(H.id,{repoUrl:q}).catch(()=>{})},validate:q=>{const de=q.trim();if(de&&!/^https?:\/\/.+/.test(de))return"Must be a valid http(s) URL"},fieldId:"repoUrl",activeFieldId:I,onActivate:$,renderDisplay:q=>{const de=OU(q);return de?a.jsx("a",{className:Y.repoLink,href:de,target:"_blank",rel:"noopener noreferrer",onClick:re=>re.stopPropagation(),children:q}):q?a.jsx("span",{children:q}):void 0},placeholder:"No repository",ariaLabel:"Workspace repository URL","data-testid":"edit-repo"})})]}),a.jsxs("div",{className:Y.metaRow,children:[a.jsx("span",{className:Y.metaLabel,children:"Environments"}),a.jsx("div",{className:Y.metaValue,"data-testid":"linked-environments",children:H?a.jsxs("span",{className:Y.linkedEnvList,children:[(()=>{const q=[...new Set(H.linkedEnvironmentIds)];return q.length===0?a.jsx("span",{className:Y.metaPlaceholder,children:"None"}):q.map(de=>{const re=c.find(xe=>xe.id===de);return a.jsxs("span",{className:Y.linkedEnvChip,"data-testid":`linked-env-${de}`,children:[(re==null?void 0:re.displayName)||de,a.jsx("button",{className:Y.chipDismiss,onClick:()=>{v(H.id,de).catch(()=>{})},title:`Unlink ${(re==null?void 0:re.displayName)||de}`,"aria-label":`Unlink ${(re==null?void 0:re.displayName)||de}`,"data-testid":`unlink-env-${de}`,disabled:q.length<=1,children:"x"})]},de)})})(),(()=>{const q=new Set(H.linkedEnvironmentIds),de=c.filter(re=>!q.has(re.id));return de.length===0?null:a.jsxs("select",{className:Y.linkEnvSelect,value:"",onChange:re=>{re.target.value&&g(H.id,re.target.value).catch(()=>{})},"aria-label":"Link environment","data-testid":"link-env-select",children:[a.jsx("option",{value:"",children:"+ Link"}),de.map(re=>a.jsx("option",{value:re.id,children:re.displayName||re.id},re.id))]})})(),_&&a.jsxs("span",{className:Y.linkError,"data-testid":"link-operation-error",role:"alert",children:[_,a.jsx("button",{className:Y.chipDismiss,onClick:b,"aria-label":"Dismiss error","data-testid":"dismiss-link-error",children:"x"})]})]}):a.jsx("span",{className:Y.metaPlaceholder,children:"None"})})]}),a.jsxs("div",{className:Y.metaRow,children:[a.jsx("span",{className:Y.metaLabel,children:"Persona"}),a.jsx("div",{className:Y.metaValue,children:a.jsx(Td,{value:(H==null?void 0:H.defaultPersonaId)||"",onSave:q=>{H&&m(H.id,{defaultPersonaId:q}).catch(()=>{})},options:[{value:"",label:"(Inherit)"},...x.map(q=>({value:q.id,label:q.name}))],fieldId:"defaultPersonaId",activeFieldId:I,onActivate:$,renderDisplay:q=>{const de=x.find(re=>re.id===q);if(de)return a.jsx("span",{children:de.name})},placeholder:(H==null?void 0:H.defaultPersonaId)||"(Inherit)",ariaLabel:"Workspace default persona","data-testid":"edit-persona"})})]}),a.jsxs("div",{className:Y.metaRow,children:[a.jsx("span",{className:Y.metaLabel,children:"Worktrees"}),a.jsx("div",{className:Y.metaValue,children:a.jsx(RI,{checked:(H==null?void 0:H.useWorktrees)??!0,onChange:q=>{H&&m(H.id,{useWorktrees:q}).catch(()=>{})},label:"Enable worktree isolation","data-testid":"worktree-toggle"})})]}),a.jsxs("div",{className:Y.metaRow,children:[a.jsx("span",{className:Y.metaLabel,children:"Working Dir"}),a.jsx("div",{className:Y.metaValue,children:a.jsx(Zt,{value:(H==null?void 0:H.workingDirectory)||"",onSave:q=>{H&&m(H.id,{workingDirectory:q}).catch(()=>{})},fieldId:"workingDirectory",activeFieldId:I,onActivate:$,placeholder:"Default (server default)",ariaLabel:"Working directory","data-testid":"edit-working-directory"})})]}),H&&a.jsxs("div",{className:Y.metaTimestamps,children:[a.jsxs("span",{className:Y.metaTimestamp,children:["Created ",b_(H.createdAt)]}),H.updatedAt&&H.updatedAt!==H.createdAt&&a.jsxs("span",{className:Y.metaTimestamp,children:["· Updated ",b_(H.updatedAt)]})]})]}),J>0&&a.jsxs("div",{className:Y.progressBarContainer,"data-testid":"progress-bar",children:[a.jsx("div",{className:Y.progressBar,children:a.jsx("div",{className:Y.progressFill,style:{width:`${me}%`}})}),a.jsxs("span",{className:Y.progressLabel,children:[E,"/",J]})]}),ie&&ie.costMillicents>0&&a.jsx("div",{className:Y.progressBarContainer,children:a.jsxs("span",{className:Y.progressLabel,children:["Usage: ",Ms(ie.costMillicents)," (",ie.sessionCount," session",ie.sessionCount!==1?"s":"",")"]})}),H&&(H.tokenBudget>0||H.costBudgetMillicents>0)&&a.jsx("div",{className:Y.progressBarContainer,children:a.jsxs("span",{className:Y.progressLabel,children:["Budget:"," ",H.tokenBudget>0&&a.jsxs(a.Fragment,{children:["Tokens: ",zo(((ie==null?void 0:ie.inputTokens)??0)+((ie==null?void 0:ie.outputTokens)??0))," / ",zo(H.tokenBudget)]}),H.tokenBudget>0&&H.costBudgetMillicents>0&&" | ",H.costBudgetMillicents>0&&a.jsxs(a.Fragment,{children:["Cost: ",Ms((ie==null?void 0:ie.costMillicents)??0)," / ",Ms(H.costBudgetMillicents)]})]})}),a.jsxs("div",{className:Y.tabBar,role:"tablist","aria-label":"Workspace view",children:[a.jsx("button",{role:"tab","aria-selected":C==="graph",className:`${Y.tab} ${C==="graph"?Y.active:""}`,onClick:()=>D("graph"),children:"Graph"}),a.jsx("button",{role:"tab","aria-selected":C==="board",className:`${Y.tab} ${C==="board"?Y.active:""}`,onClick:()=>D("board"),"data-testid":"board-tab",children:"Board"}),a.jsx("button",{role:"tab","aria-selected":C==="tasks",className:`${Y.tab} ${C==="tasks"?Y.active:""}`,onClick:()=>D("tasks"),children:"Tasks"})]}),C==="tasks"&&J>0&&a.jsxs("div",{className:Y.workspaceSummary,children:[a.jsx("span",{className:Y.workspaceSummaryTitle,children:`${E}/${J} tasks complete`}),a.jsx("span",{className:Y.workspaceSummarySubtitle,children:"Select a task or click + to create one"})]}),C==="tasks"&&J===0&&a.jsxs("div",{className:Y.emptyCta,children:[a.jsx("button",{className:Y.ctaButton,onClick:()=>o(zi(t,void 0,Q)),children:"Create Task"}),a.jsx("div",{className:Y.ctaDescription,children:"Break your work into tasks and let agents tackle them"})]}),C==="board"&&a.jsx(Fz,{workspaceId:t,environmentId:Q,tasks:r,sessions:S,personas:x,environments:c}),C==="graph"&&a.jsx(GN,{workspaceId:t,environmentId:Q,tasks:r,resolvedThemeId:T}),a.jsx(Ls,{isOpen:O,title:"Archive Workspace?",description:"This will hide the workspace from the sidebar. Tasks will not be deleted.",confirmLabel:"Archive",onConfirm:()=>{H&&(p(H.id).catch(()=>{}),o("/",{replace:!0})),A(!1)},onCancel:()=>A(!1)})]})}const LU="_container_3pgew_1",zU="_header_3pgew_8",$U="_headerTitle_3pgew_35",PU="_headerActions_3pgew_44",UU="_body_3pgew_51",HU="_btnPrimary_3pgew_63",VU="_btnGhost_3pgew_94",qU="_error_3pgew_116",Fa={container:LU,header:zU,headerTitle:$U,headerActions:PU,body:UU,btnPrimary:HU,btnGhost:VU,error:qU};function GU(t){const s={};return t.name.trim()||(s.name="Name is required"),t.repoUrl.trim()&&!/^https?:\/\/.+/i.test(t.repoUrl.trim())&&(s.repoUrl="Must be a valid http(s) URL"),t.environmentId||(s.environmentId="Environment is required"),Object.keys(s).length>0?s:void 0}const FU=[{label:"Home",url:Ii},{label:"New Workspace",url:void 0}];function ZU(){const[t]=Im(),s=t.get("environment")??void 0,{environments:{environments:o},personas:{personas:r},workspaces:{createWorkspace:c,workspaceCreating:d}}=rt(),{showToast:u}=gn(),p=ct(),[m,g]=y.useState(()=>{var w;return s$(void 0,s||((w=o[0])==null?void 0:w.id))}),[v,_]=y.useState(),[b,x]=y.useState();y.useEffect(()=>{s||m.environmentId||o.length===0||g(w=>{var T;return w.environmentId?w:{...w,environmentId:((T=o[0])==null?void 0:T.id)??""}})},[o,s,m.environmentId]);const S=()=>{const w=GU(m);if(w){_(w),x(void 0);return}_(void 0),x(void 0),c(m.name.trim(),m.description,m.repoUrl.trim(),m.environmentId,m.defaultPersonaId,m.useWorktrees,m.workingDirectory,()=>{u("Workspace created","success"),p(Ii,{replace:!0})},T=>{x(T)}).catch(()=>{})},j=()=>{p(s?Mi(s):Ii,{replace:!0})};return a.jsxs("div",{className:Fa.container,children:[a.jsxs("div",{className:Fa.header,children:[a.jsx("div",{className:Fa.headerTitle,children:a.jsx(xs,{segments:FU})}),a.jsxs("div",{className:Fa.headerActions,children:[a.jsx("button",{className:Fa.btnGhost,onClick:j,disabled:d,"data-testid":"workspace-create-cancel",children:"Cancel"}),a.jsx("button",{className:Fa.btnPrimary,onClick:S,disabled:d||!m.name.trim()||!m.environmentId,"data-testid":"workspace-create-save",children:d?a.jsx(B1,{size:"sm",label:"Creating"}):"Create Workspace"})]})]}),a.jsxs("div",{className:Fa.body,children:[a.jsx(i$,{values:m,onChange:w=>{g(w),_(void 0),x(void 0)},environments:o,personas:r,errors:v,disabled:d,autoFocusName:!0}),b&&a.jsx("div",{className:Fa.error,"data-testid":"workspace-create-submit-error",children:b})]})]})}function __(){const{workspaceId:t,environmentId:s}=Hn(),[o]=Im(),r=t??o.get("workspace")??"",c=o.get("parent")??void 0,{tasks:{tasks:d,createTask:u,updateTask:p},workspaces:{workspaces:m},personas:{personas:g}}=rt(),{showToast:v}=gn();return a.jsx(W1,{mode:"new",workspaceId:r,parentTaskId:c,environmentId:s,tasks:d,workspaces:m,personas:g,onCreateTask:(_,b,x,S,j,w,T,C,D)=>{u(_,b,x,S,j,w,T,C,D).catch(()=>{})},onUpdateTask:(_,b,x,S,j)=>{p(_,b,x,S,j).catch(()=>{})},onShowToast:v})}function KU(){return a.jsxs("div",{className:Y.panelContainer,"aria-hidden":"true",children:[a.jsx("div",{className:Y.header,children:a.jsxs("span",{className:Y.headerTitle,children:[a.jsx(Ne,{width:"12rem",height:"1rem"}),a.jsx(Ne,{width:"4rem",height:"1rem",borderRadius:"var(--radius-full)"})]})}),a.jsxs("div",{className:Y.tabBar,role:"tablist","aria-label":"Task view",children:[a.jsx("span",{className:`${Y.tab} ${Y.active}`,children:"Overview"}),a.jsx("span",{className:Y.tab,children:"Stream"}),a.jsx("span",{className:Y.tab,children:"Findings"})]}),a.jsx("div",{className:Y.overviewContent,children:a.jsxs("div",{className:Y.overviewDashboard,children:[a.jsx("div",{className:Y.overviewHero,children:a.jsx(Ne,{width:"5rem",height:"1.5rem",borderRadius:"var(--radius-full)"})}),a.jsxs("div",{className:Y.overviewSection,children:[a.jsx("div",{className:Y.overviewLabel,children:"Description"}),a.jsx(vm,{lines:2})]}),a.jsxs("div",{className:Y.overviewSection,children:[a.jsx("div",{className:Y.overviewLabel,children:"Environment"}),a.jsxs("div",{className:Y.envRow,children:[a.jsx(Ne,{width:"0.5rem",height:"0.5rem",variant:"circular"}),a.jsx(Ne,{width:"8rem",height:"0.875rem"})]})]}),a.jsxs("div",{className:Y.overviewSection,children:[a.jsx("div",{className:Y.overviewLabel,children:"Dependencies"}),a.jsx(vm,{lines:2})]}),a.jsxs("div",{className:Y.overviewSection,children:[a.jsx("div",{className:Y.overviewLabel,children:"Timeline"}),a.jsx("div",{className:Y.timeline,children:Array.from({length:4},(t,s)=>a.jsxs("div",{className:Y.timelineRow,children:[a.jsx(Ne,{width:"4rem",height:"0.75rem"}),a.jsx(Ne,{width:"10rem",height:"0.75rem"})]},s))})]})]})})]})}function Za(){const{taskId:t,workspaceId:s,environmentId:o}=Hn(),r=Yt(),c=ct(),{showToast:d}=gn(),{sessions:{events:u,eventsDropped:p,sessions:m,loadSessionEvents:g,taskSessions:v,loadTaskSessions:_,sendInput:b,spawn:x,kill:S},tasks:{tasks:j,tasksLoading:w,startTask:T,stopTask:C,resumeTask:D,deleteTask:O,createTask:A,updateTask:I},environments:{environments:$,provisionEnvironment:B},findings:{findings:P,loadFindings:X},workspaces:{workspaces:H},personas:{personas:Q},usageCache:he,loadUsage:W}=rt(),ie=y.useRef(void 0),L=y.useRef(void 0),E=y.useRef(void 0),J=y.useRef(void 0),me=y.useRef(void 0),q=r.pathname.endsWith("/stream")?"stream":r.pathname.endsWith("/findings")?"findings":"overview",de=r.pathname.endsWith("/edit"),[re,xe]=y.useState(q),[be,fe]=y.useState(!1),[_e,ke]=y.useState(void 0),[Le,Ot]=y.useState(""),[Vn,oe]=y.useState(de),Je=y.useRef(q),Ht=y.useRef(de),ne=j.find(De=>De.id===t),Ct=(ne==null?void 0:ne.workspaceId)||void 0,Bt=H.find(De=>De.id===Ct);y.useEffect(()=>{q!==Je.current&&(Je.current=q,q!==re&&xe(q))},[q,re]),y.useEffect(()=>{de!==Ht.current&&(Ht.current=de,de!==Vn&&oe(de))},[de,Vn]),y.useEffect(()=>{if(Le===""){if(Bt!=null&&Bt.linkedEnvironmentIds[0])Ot(Bt.linkedEnvironmentIds[0]);else if($.length>0){const De=$.find(We=>We.status==="connected");Ot((De==null?void 0:De.id)??$[0].id)}}},[Le,Bt==null?void 0:Bt.linkedEnvironmentIds[0],$]);const Lt=ne?v[ne.id]??[]:[];let Pe;_e&&Lt.some(De=>De.id===_e)?Pe=_e:Pe=(ne==null?void 0:ne.latestSessionId)||void 0;const rn=()=>{fe(!0)},ha=()=>{if(!ne)return;O(ne.id).catch(()=>{}),fe(!1);const De=o??(Bt==null?void 0:Bt.linkedEnvironmentIds[0]);c(ne.workspaceId&&De?Ri(ne.workspaceId,De):"/",{replace:!0})};y.useEffect(()=>{(ne==null?void 0:ne.id)!==L.current&&(L.current=ne==null?void 0:ne.id,ke(void 0),Ot(""),oe(de))},[ne==null?void 0:ne.id,de]),y.useEffect(()=>{if(!(ne!=null&&ne.id))return;const De=ne.id!==J.current,We=ne.latestSessionId!==me.current;(De||We)&&(J.current=ne.id,me.current=ne.latestSessionId,_(ne.id).catch(()=>{}))},[ne==null?void 0:ne.id,ne==null?void 0:ne.latestSessionId,_]),y.useEffect(()=>{if((ne==null?void 0:ne.status)!==E.current){const De=E.current===void 0;E.current=ne==null?void 0:ne.status;const We=(ne==null?void 0:ne.status)==="not_started"?"overview":(ne==null?void 0:ne.status)==="working"||(ne==null?void 0:ne.status)==="paused"?"stream":(ne==null?void 0:ne.status)==="complete"?"findings":void 0;We&&We!==re&&!(De&&q!=="overview")&&xe(We)}},[ne==null?void 0:ne.status,re,q]);const us=y.useMemo(()=>new Map(j.map(De=>[De.id,De])),[j]),ei=y.useMemo(()=>{const De=Pe?u.filter(We=>We.sessionId===Pe):[];return _h(bh(De))},[u,Pe]),ga=ne?ne.dependsOn.some(De=>{const We=us.get(De);return We!==void 0&&We.status!=="complete"}):!1,en=y.useMemo(()=>j$(t,o,H,$,us),[t,o,H,$,us]);y.useEffect(()=>{Pe&&Pe!==ie.current&&(ie.current=Pe,g(Pe).catch(()=>{}))},[Pe,g]),y.useEffect(()=>{re==="findings"&&Ct&&X(Ct).catch(()=>{})},[re,Ct,X]);const Pi=Lt.reduce((De,We)=>De+(We.costMillicents??0),0);y.useEffect(()=>{ne&&(W("task",ne.id).catch(()=>{}),ne.childTaskIds.length>0&&W("task_tree",ne.id).catch(()=>{}))},[ne==null?void 0:ne.id,ne==null?void 0:ne.childTaskIds.length,W,Pi]);const va=ne?`task:${ne.id}`:"",ti=va in he?he[va]:void 0,Ss=ne?`task_tree:${ne.id}`:"",Ui=ne&&ne.childTaskIds.length>0&&Ss in he?he[Ss]:void 0,qn=De=>{xe(De),c($n(t,De==="overview"?void 0:De,s,o))};return la({key:"1"},()=>qn("overview")),la({key:"2"},()=>qn("stream")),la({key:"3"},()=>qn("findings")),!ne&&w?a.jsx(KU,{}):a.jsxs("div",{className:Y.panelContainer,children:[a.jsx(xs,{segments:en}),a.jsxs("div",{className:Y.header,children:[a.jsxs("span",{className:Y.headerTitle,children:[a.jsx("span",{"data-testid":"task-title",children:(ne==null?void 0:ne.title)||t}),ne&&a.jsx("span",{className:Y.taskStatusBadge,"data-testid":"task-status",children:ne.status}),(ne==null?void 0:ne.branch)&&a.jsx("span",{className:Y.taskBranch,children:ne.branch}),ga&&a.jsx("span",{className:Y.taskBlockedBadge,children:"blocked"})]}),ne&&a.jsx(jL,{task:ne,sessionId:Pe,isBlocked:ga,onStart:()=>{T(ne.id,void 0,Le).catch(()=>{})},onResume:()=>{D(ne.id).catch(()=>{})},onStop:()=>{C(ne.id).catch(()=>{})},onPause:()=>{Pe&&S(Pe).catch(()=>{})},onDelete:rn,onEdit:()=>oe(!0)})]}),a.jsxs("div",{className:Y.tabBar,role:"tablist","aria-label":"Task view",children:[a.jsx("button",{role:"tab","aria-selected":re==="overview",className:`${Y.tab} ${re==="overview"?Y.active:""}`,onClick:()=>qn("overview"),children:"Overview"}),a.jsx("button",{role:"tab","aria-selected":re==="stream",className:`${Y.tab} ${re==="stream"?Y.active:""}`,onClick:()=>qn("stream"),children:"Stream"}),a.jsx("button",{role:"tab","aria-selected":re==="findings",className:`${Y.tab} ${re==="findings"?Y.active:""}`,onClick:()=>qn("findings"),children:"Findings"})]}),a.jsxs(ls,{mode:"wait",children:[re==="overview"&&a.jsx(Nt.div,{initial:{opacity:0,y:4},animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.15},className:Y.overviewContent,"data-testid":"task-overview",children:Vn&&ne?a.jsx(W1,{mode:"edit",taskId:ne.id,workspaceId:Ct,environmentId:o,tasks:j,workspaces:H,personas:Q,onCreateTask:(De,We,tn,jt,vn,nn,Hi,Vi,qi)=>{A(De,We,tn,jt,vn,nn,Hi,Vi,qi).catch(()=>{})},onUpdateTask:(De,We,tn,jt,vn)=>{I(De,We,tn,jt,vn).catch(()=>{})},onEditDone:()=>{de?c($n(ne.id,void 0,s,o),{replace:!0}):oe(!1)},onShowToast:d}):ne?a.jsx(u8,{task:ne,tasksById:us,environments:$,workspaces:H,taskSessions:Lt,selectedEnvId:Le,taskUsage:ti,treeUsage:Ui}):a.jsx("div",{className:Y.waitingMessage,children:"No additional details"})},"overview"),re==="stream"&&a.jsxs(Nt.div,{initial:{opacity:0,y:4},animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.15},style:{display:"flex",flexDirection:"column",flex:1,overflow:"hidden"},children:[a.jsx(u6,{taskSessions:Lt,selectedSessionId:Pe,onSelect:De=>ke(De)}),a.jsx(al,{events:ei,eventsDropped:p,emptyState:!Pe&&ne?ga?a.jsx("div",{className:Y.emptyCta,"data-testid":"stream-blocked-message",children:a.jsx("div",{className:Y.ctaDescription,children:"This task is blocked by incomplete dependencies"})}):a.jsxs("div",{className:Y.emptyCta,children:[a.jsx("button",{"data-testid":"stream-start-cta",className:Y.ctaButton,onClick:()=>{T(ne.id,void 0,Le).catch(()=>{})},children:"Start Task"}),a.jsx("div",{className:Y.ctaDescription,children:"Click to begin agent execution"})]}):Pe&&ei.length===0?a.jsx("div",{className:Y.waitingMessage,children:"Waiting for events..."}):void 0,onShowToast:d})]},"stream"),re==="findings"&&a.jsx(Nt.div,{initial:{opacity:0,y:4},animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.15},className:Y.tabContent,children:Ct?a.jsx(Y1,{findings:P.filter(De=>De.workspaceId===Ct)}):a.jsx("div",{className:Y.noContext,children:"Navigate to a task within a workspace to view findings"})},"findings")]}),(()=>{if(!ne||ne.status!=="working"&&ne.status!=="paused")return;const De=Pe?m.find(We=>We.id===Pe):void 0;if(!(!De||De.status==="stopped"))return a.jsx(rl,{mode:"send",sessionId:De.id,environmentId:De.environmentId,personas:Q,environments:$,onSendInput:(We,tn)=>{b(We,tn).catch(()=>{})},onSpawn:(We,tn,jt)=>{x(We,tn,jt).catch(()=>{})},onStartTask:(We,tn,jt)=>{T(We,tn,jt).catch(()=>{})},onProvisionEnvironment:We=>{B(We).catch(()=>{})},onShowToast:d})})(),ne&&a.jsx(Ls,{isOpen:be,title:"Delete Task?",description:`"${ne.title}" will be permanently removed.`,onConfirm:ha,onCancel:()=>fe(!1)})]})}function YU(){const{environments:{environments:t,addEnvironment:s,updateEnvironment:o},codespaces:{codespaces:r,codespaceError:c,codespaceListError:d,codespaceCreating:u,listCodespaces:p,createCodespace:m}}=rt(),{showToast:g}=gn();return a.jsx(X1,{mode:"new",environments:t,onAddEnvironment:(v,_,b)=>{s(v,_,b).catch(()=>{})},onUpdateEnvironment:(v,_)=>{o(v,_).catch(()=>{})},onListCodespaces:()=>{p().catch(()=>{})},codespaces:r,codespaceError:c,codespaceListError:d,codespaceCreating:u,onCreateCodespace:(v,_)=>{m(v,_).catch(()=>{})},onShowToast:g})}function JU(){const{environmentId:t}=Hn(),{environments:{environments:s,addEnvironment:o,updateEnvironment:r},codespaces:{codespaces:c,codespaceError:d,codespaceListError:u,codespaceCreating:p,listCodespaces:m,createCodespace:g}}=rt(),{showToast:v}=gn();return a.jsx(X1,{mode:"edit",environmentId:t,environments:s,onAddEnvironment:(_,b,x)=>{o(_,b,x).catch(()=>{})},onUpdateEnvironment:(_,b)=>{r(_,b).catch(()=>{})},onListCodespaces:()=>{m().catch(()=>{})},codespaces:c,codespaceError:d,codespaceListError:u,codespaceCreating:p,onCreateCodespace:(_,b)=>{g(_,b).catch(()=>{})},onShowToast:v})}const WU="_layout_11u79_1",XU="_content_11u79_8",QU="_tabPanel_11u79_14",ol={layout:WU,content:XU,tabPanel:QU};function eH(){const t=_$();return a.jsxs("div",{className:ol.layout,children:[a.jsx(xs,{segments:t}),a.jsx("div",{className:ol.content,children:a.jsx(ma,{})})]})}const tH="_container_144a4_1",nH="_envHeader_144a4_6",sH="_envTitleRow_144a4_10",aH="_statusDot_144a4_16",iH="_envName_144a4_21",oH="_statusBadge_144a4_27",rH="_envMeta_144a4_33",lH="_metaTag_144a4_39",cH="_actions_144a4_51",dH="_provisionMessage_144a4_59",uH="_errorMessage_144a4_64",fH="_section_144a4_69",pH="_sectionHeader_144a4_73",mH="_cardList_144a4_121",hH="_card_144a4_121",gH="_cardHeader_144a4_138",vH="_cardName_144a4_144",yH="_cardActions_144a4_149",bH="_cardDescription_144a4_154",_H="_cardMeta_144a4_160",xH="_repoLink_144a4_166",kH="_empty_144a4_174",SH="_errorHint_144a4_180",jH="_btnPrimary_144a4_186",TH="_btnOutline_144a4_220",wH="_btnSmall_144a4_247",NH="_btnDanger_144a4_273",Re={container:tH,envHeader:nH,envTitleRow:sH,statusDot:aH,envName:iH,statusBadge:oH,envMeta:rH,metaTag:lH,actions:cH,provisionMessage:dH,errorMessage:uH,section:fH,sectionHeader:pH,cardList:mH,card:hH,cardHeader:gH,cardName:vH,cardActions:yH,cardDescription:bH,cardMeta:_H,repoLink:xH,empty:kH,errorHint:SH,btnPrimary:jH,btnOutline:TH,btnSmall:wH,btnDanger:NH};function CH(){return a.jsxs("div",{className:Re.container,"aria-hidden":"true",children:[a.jsxs("div",{className:Re.envHeader,children:[a.jsxs("div",{className:Re.envTitleRow,children:[a.jsx(Ne,{width:"0.875rem",height:"0.875rem",variant:"circular"}),a.jsx(Ne,{width:"12rem",height:"1.5rem"}),a.jsx(Ne,{width:"4rem",height:"0.875rem"})]}),a.jsxs("div",{className:Re.envMeta,children:[a.jsx(Ne,{width:"6rem",height:"1.25rem",borderRadius:"var(--radius-sm)"}),a.jsx(Ne,{width:"5rem",height:"1.25rem",borderRadius:"var(--radius-sm)"}),a.jsx(Ne,{width:"4.5rem",height:"1.25rem",borderRadius:"var(--radius-sm)"})]})]}),a.jsxs("div",{className:Re.actions,children:[a.jsx(Ne,{width:"5rem",height:"2rem",borderRadius:"var(--radius-sm)"}),a.jsx(Ne,{width:"4rem",height:"2rem",borderRadius:"var(--radius-sm)"})]}),a.jsxs("div",{className:Re.section,children:[a.jsx("div",{className:Re.sectionHeader,children:a.jsx("h3",{style:{margin:0},children:"Workspaces"})}),a.jsxs("div",{className:Re.cardList,children:[a.jsx(jd,{lines:2}),a.jsx(jd,{lines:2})]})]})]})}const EH={connected:"var(--accent-green)",sleeping:"var(--accent-yellow)",error:"var(--accent-red)",disconnected:"var(--text-tertiary)",connecting:"var(--accent-blue)"};function AH(){const{environmentId:t}=Hn(),s=ct(),{environments:{environments:o,environmentsLoading:r,provisionStatus:c,provisionEnvironment:d,stopEnvironment:u,removeEnvironment:p},workspaces:{workspaces:m,archiveWorkspace:g,linkEnvironment:v,unlinkEnvironment:_,linkOperationError:b,clearLinkOperationError:x},sessions:{sessions:S}}=rt(),[j,w]=y.useState(!1),[T,C]=y.useState(!1),[D,O]=y.useState(void 0),A=o.find(E=>E.id===t);if(!A&&r)return a.jsx(CH,{});if(!t||!A)return a.jsx(rs,{to:Lo,replace:!0});const I=m.filter(E=>E.linkedEnvironmentIds.includes(A.id)),$=S.filter(E=>E.environmentId===A.id),B=$.reduce((E,J)=>E+(J.costMillicents??0),0),P=EH[A.status]||"var(--text-tertiary)",X=A.status==="connected",H=A.status==="connecting",Q=A.status==="disconnected"||A.status==="error"||A.status==="sleeping",he=A.id in c?c[A.id]:void 0,W=()=>{p(A.id).catch(()=>{}),w(!1),s(Lo,{replace:!0})},ie=()=>{C(!1),d(A.id,!0).catch(()=>{})},L=E=>{g(E).catch(()=>{}),O(void 0)};return a.jsxs("div",{className:Re.container,children:[a.jsx(Ls,{isOpen:j,title:"Delete Environment?",description:`"${A.displayName||A.id}" will be permanently removed along with all its data.`,onConfirm:W,onCancel:()=>w(!1)}),a.jsx(Ls,{isOpen:T,title:"Reprovision Environment?",description:"This will kill any active session and force a fresh provision cycle. The environment will be temporarily disconnected.",confirmLabel:"Reprovision",onConfirm:ie,onCancel:()=>C(!1)}),a.jsxs("div",{className:Re.envHeader,children:[a.jsxs("div",{className:Re.envTitleRow,children:[a.jsx("span",{className:Re.statusDot,style:{color:P},children:"●"}),a.jsx("h2",{className:Re.envName,children:A.displayName||A.id}),a.jsx("span",{className:Re.statusBadge,style:{color:P},children:A.status})]}),a.jsxs("div",{className:Re.envMeta,children:[a.jsxs("span",{className:Re.metaTag,children:["Adapter: ",A.adapterType]}),$.length>0&&a.jsxs("span",{className:Re.metaTag,children:[$.length," session",$.length!==1?"s":""]}),B>0&&a.jsxs("span",{className:Re.metaTag,children:["Cost: ",Ms(B)]})]})]}),a.jsxs("div",{className:Re.actions,children:[X&&a.jsxs(a.Fragment,{children:[a.jsx("button",{className:Re.btnPrimary,onClick:()=>s(tx(A.id)),children:"New Chat"}),a.jsx("button",{className:Re.btnOutline,onClick:()=>{u(A.id).catch(()=>{})},children:"Stop"}),a.jsx("button",{className:Re.btnOutline,onClick:()=>C(!0),disabled:he!==void 0,"data-testid":"env-reprovision-btn",children:"Reprovision"})]}),Q&&a.jsx("button",{className:Re.btnPrimary,onClick:()=>{d(A.id).catch(()=>{})},children:A.status==="error"?"Retry":A.status==="sleeping"?"Wake":"Connect"}),H&&he!==void 0&&a.jsx("span",{className:Re.provisionMessage,children:he.message}),A.status==="error"&&(he==null?void 0:he.stage)==="error"&&a.jsx("span",{className:Re.errorMessage,children:he.message}),a.jsx("button",{className:Re.btnOutline,onClick:()=>s(IN(A.id)),"data-testid":"env-edit-btn",children:"Edit Config"}),a.jsx("button",{className:Re.btnDanger,onClick:()=>w(!0),children:"Delete"})]}),a.jsxs("div",{className:Re.section,children:[a.jsxs("div",{className:Re.sectionHeader,children:[a.jsx("h3",{children:"Workspaces"}),a.jsx("button",{className:Re.btnPrimary,onClick:()=>s(`${ax}?environment=${encodeURIComponent(A.id)}`),"data-testid":"workspace-create-button",children:"+ New Workspace"}),(()=>{const E=m.filter(J=>!J.linkedEnvironmentIds.includes(A.id)&&J.status==="active");return E.length===0?null:a.jsxs("select",{className:Re.btnPrimary,value:"",onChange:J=>{J.target.value&&v(J.target.value,A.id).catch(()=>{})},"aria-label":"Link a workspace","data-testid":"link-workspace-select",children:[a.jsx("option",{value:"",children:"+ Link Workspace"}),E.map(J=>a.jsx("option",{value:J.id,children:J.name},J.id))]})})()]}),b&&a.jsxs("p",{className:Re.errorHint,"data-testid":"link-operation-error",role:"alert",children:[b,a.jsx("button",{className:Re.btnSmall,onClick:x,"aria-label":"Dismiss error","data-testid":"dismiss-link-error",children:"Dismiss"})]}),I.length===0&&a.jsx("p",{className:Re.empty,"data-testid":"linked-workspaces-empty",children:"No workspaces yet. Create one to get started."}),a.jsx("div",{className:Re.cardList,"data-testid":"linked-workspaces-list",children:I.map(E=>a.jsx(DH,{workspace:E,confirmArchiveId:D,onOpen:()=>s(Ri(E.id,A.id)),onArchive:()=>O(E.id),onConfirmArchive:()=>L(E.id),onCancelArchive:()=>O(void 0),onUnlink:()=>{_(E.id,A.id).catch(()=>{})}},E.id))})]})]})}function DH({workspace:t,confirmArchiveId:s,onOpen:o,onArchive:r,onConfirmArchive:c,onCancelArchive:d,onUnlink:u}){const p=s===t.id,m=t.repoUrl&&/^https?:\/\//.test(t.repoUrl);return a.jsxs("div",{className:Re.card,"data-testid":"workspace-card","data-workspace-id":t.id,children:[a.jsxs("div",{className:Re.cardHeader,children:[a.jsx("strong",{className:Re.cardName,children:t.name}),a.jsxs("div",{className:Re.cardActions,children:[a.jsx("button",{className:Re.btnSmall,onClick:o,children:"Open"}),a.jsx("button",{className:Re.btnSmall,onClick:u,disabled:t.linkedEnvironmentIds.length<=1,"data-testid":`unlink-workspace-${t.id}`,children:"Unlink"}),p?a.jsxs(a.Fragment,{children:[a.jsx("button",{className:Re.btnDanger,onClick:c,children:"Confirm"}),a.jsx("button",{className:Re.btnSmall,onClick:d,children:"Cancel"})]}):a.jsx("button",{className:Re.btnSmall,onClick:r,children:"Archive"})]})]}),t.description&&a.jsx("p",{className:Re.cardDescription,children:t.description}),t.repoUrl&&a.jsx("div",{className:Re.cardMeta,children:m?a.jsx("a",{href:t.repoUrl,target:"_blank",rel:"noopener noreferrer",className:Re.repoLink,children:t.repoUrl}):a.jsx("span",{children:t.repoUrl})})]})}const RH={credentials:"Credentials",personas:"Personas",schedules:"Schedules",appearance:"Appearance",about:"About",shortcuts:"Shortcuts",plugins:"Plugins"};function MH(){const s=Yt().pathname.replace(/^\/settings\/?/,"").split("/")[0],o=RH[s],r=b$(o);return a.jsxs("div",{className:ol.layout,children:[a.jsx(xs,{segments:r}),a.jsx("div",{className:ol.content,children:a.jsx("div",{className:ol.tabPanel,children:a.jsx(ma,{})},s)})]})}function IH(){const{tokens:{tokens:t,setToken:s,deleteToken:o},credentials:{credentialProviders:r,updateCredentialProviders:c}}=rt(),{showToast:d}=gn();return a.jsxs(a.Fragment,{children:[a.jsx(V8,{credentialProviders:r,onUpdateCredentialProviders:u=>{c(u).catch(()=>{})}}),a.jsx(KB,{tokens:t,onSetToken:(u,p,m,g,v)=>{s(u,p,m,g,v).catch(()=>{})},onDeleteToken:u=>{o(u).catch(()=>{})},onShowToast:d})]})}function OH(){const{personas:{personas:t,deletePersona:s},appDefaultPersonaId:o,setAppDefaultPersonaId:r}=rt(),{showToast:c}=gn(),d=ct();return a.jsx(n7,{personas:t,appDefaultPersonaId:o,onDeletePersona:async u=>{try{await s(u)}catch(p){throw console.error("Failed to delete persona",{personaId:u,error:p}),c("Failed to delete persona","error"),p}},onSetAppDefaultPersonaId:async u=>{try{await r(u)}catch(p){console.error("Failed to set app default persona ID",{personaId:u,error:p}),c("Failed to set app default persona","error")}},onNavigateToNew:()=>d(BN),onNavigateToPersona:u=>d(nx(u))})}const BH="_container_1ooin_1",LH="_form_1ooin_7",zH="_formActions_1ooin_75",$H="_editableSection_1ooin_82",PH="_defaultBadge_1ooin_93",UH="_typeToggle_1ooin_107",HH="_scriptEditor_1ooin_121",VH="_optional_1ooin_128",bs={container:BH,form:LH,formActions:zH,editableSection:$H,defaultBadge:PH,typeToggle:UH,scriptEditor:HH,optional:VH},x_=[{value:"claude-code",label:"claude-code"},{value:"codex",label:"codex"},{value:"copilot",label:"copilot"},{value:"goose",label:"goose"},{value:"stub",label:"stub"},{value:"claude-code-acp",label:"claude-code-acp (experimental)"},{value:"codex-acp",label:"codex-acp (experimental)"},{value:"copilot-acp",label:"copilot-acp (experimental)"}],k_=[{value:"genaiscript",label:"genaiscript"}],qH="0";function S_(){const{personaId:t}=Hn(),s=ct(),{showToast:o}=gn(),{personas:{personas:r,createPersona:c,updatePersona:d,deletePersona:u},appDefaultPersonaId:p,setAppDefaultPersonaId:m}=rt(),g=t===void 0,v=g?void 0:r.find(b=>b.id===t);if(!g&&r.length>0&&!v)return a.jsx(rs,{to:rp,replace:!0});const _=[{label:"Settings",url:Ei},{label:"Personas",url:rp},{label:g?"New Persona":(v==null?void 0:v.name)??"Persona",url:void 0}];return a.jsxs("div",{className:bs.container,children:[a.jsx(xs,{segments:_}),a.jsx(GH,{existing:v,isNew:g,appDefaultPersonaId:p,onCreatePersona:c,onUpdatePersona:d,onDeletePersona:u,onSetAppDefaultPersonaId:m,onDone:()=>{s(rp)},showToast:o})]})}function GH({existing:t,isNew:s,appDefaultPersonaId:o,onCreatePersona:r,onUpdatePersona:c,onDeletePersona:d,onSetAppDefaultPersonaId:u,onDone:p,showToast:m}){const g=ct(),[v,_]=y.useState((t==null?void 0:t.name)??""),[b,x]=y.useState((t==null?void 0:t.description)??""),[S,j]=y.useState((t==null?void 0:t.systemPrompt)??""),[w,T]=y.useState((t==null?void 0:t.runtime)??"claude-code"),[C,D]=y.useState((t==null?void 0:t.model)??"sonnet"),[O,A]=y.useState((t==null?void 0:t.maxTurns)??0),[I,$]=y.useState((t==null?void 0:t.type)==="script"?"script":"agent"),[B,P]=y.useState((t==null?void 0:t.script)??""),[X,H]=y.useState((t==null?void 0:t.allowedMcpTools)??[]),[Q,he]=y.useState(!1),[W,ie]=y.useState(null),[L,E]=y.useState(!!s);y.useEffect(()=>{if(!s&&t&&!L){E(!0),_(t.name),x(t.description),j(t.systemPrompt);const oe=t.type==="script"?"script":"agent";T(oe==="script"?t.runtime||"genaiscript":t.runtime),D(t.model),A(t.maxTurns),$(oe),P(t.script||""),H(t.allowedMcpTools)}},[s,t,L]);const J=oe=>{$(oe),oe==="script"?T("genaiscript"):w==="genaiscript"&&T("claude-code")},me=!s&&t===void 0,q=v.trim().length>0&&!me&&S.trim().length>0&&(I==="script"?B.trim().length>0:!!w&&!!C),de=s&&q,re=!s&&o===(t==null?void 0:t.id),xe=!s&&t&&!re&&I==="agent"&&!!w&&!!C,be=(oe,Je)=>{if(!oe.trim())return`${Je} is required`},fe=oe=>{if(oe.preventDefault(),!(me||!q)){if(t){c(t.id,v,b,S,w,C,O,I,B).then(()=>{m("Persona updated","success"),p()},()=>{m("Failed to save persona","error")});return}r(v,b,S,w,C,O,I,B,X).then(Je=>{m("Persona created","success"),g(nx(Je.id),{replace:!0})},()=>{m("Failed to save persona","error")})}},_e=()=>{t&&d(t.id).then(()=>{m("Persona deleted","success"),p()},()=>{m("Failed to delete persona","error")})},ke=async(oe,Je,Ht,ne)=>oe().then(()=>{Je(),m(Ht,"success")},()=>{m(ne,"error")}),Le=(oe,Je)=>{if(!t)return;const Ht=oe==="type"?String(Je):I,ne=oe==="runtime"?String(Je):oe==="type"?String(Je)==="script"?"genaiscript":w==="genaiscript"?"claude-code":w:w,Ct=oe==="model"?String(Je):C,Bt=oe==="maxTurns"?Number(Je):O,Lt=oe==="systemPrompt"?String(Je):S,Pe=oe==="script"?String(Je):B;ke(()=>c(t.id,oe==="name"?String(Je):v,oe==="description"?String(Je):b,Lt,ne,Ct,Bt,Ht,Pe),()=>{if(oe==="type"){const rn=String(Je)==="script"?"script":"agent";$(rn),T(ne)}oe==="runtime"&&T(String(Je)),oe==="name"&&_(String(Je)),oe==="description"&&x(String(Je)),oe==="systemPrompt"&&j(String(Je)),oe==="model"&&D(String(Je)),oe==="maxTurns"&&A(Number(Je)),oe==="script"&&P(String(Je))},"Persona updated","Failed to update persona").catch(()=>{})},Ot=oe=>{fe(oe)},Vn=()=>{t&&u(t.id).then(()=>{m("Set as app default","success")},()=>{m("Failed to set app default","error")})};return a.jsxs(a.Fragment,{children:[me?a.jsxs("div",{className:bs.form,children:[a.jsx("h3",{children:"Edit Persona"}),a.jsx("p",{children:"Loading persona..."})]}):s?a.jsxs("form",{onSubmit:Ot,className:bs.form,children:[a.jsx("h3",{children:"Create Persona"}),a.jsxs("div",{className:bs.typeToggle,"data-testid":"persona-type-toggle",children:[a.jsxs("label",{children:[a.jsx("input",{type:"radio",name:"personaType",value:"agent",checked:I==="agent",onChange:()=>J("agent")}),"Agent"]}),a.jsxs("label",{children:[a.jsx("input",{type:"radio",name:"personaType",value:"script",checked:I==="script",onChange:()=>J("script")}),"Script"]})]}),a.jsxs("label",{children:["Name",a.jsx("input",{type:"text",value:v,onChange:oe=>_(oe.target.value),placeholder:I==="script"?"e.g. Nightly Report":"e.g. Frontend Engineer",required:!0,"data-testid":"persona-detail-name"})]}),a.jsxs("label",{children:["Description",a.jsx("input",{type:"text",value:b,onChange:oe=>x(oe.target.value),placeholder:"Brief description...","data-testid":"persona-detail-description"})]}),a.jsxs("label",{children:["Runtime",a.jsx("select",{value:w,onChange:oe=>T(oe.target.value),"data-testid":"persona-runtime-select",children:(I==="script"?k_:x_).map(oe=>a.jsx("option",{value:oe.value,children:oe.label},oe.value))})]}),I==="agent"&&a.jsxs(a.Fragment,{children:[a.jsxs("label",{children:["Model",a.jsx("input",{type:"text",value:C,onChange:oe=>D(oe.target.value),placeholder:"e.g. sonnet","data-testid":"persona-detail-model"})]}),a.jsxs("label",{children:["Max Turns",a.jsx("input",{type:"number",value:O,onChange:oe=>A(parseInt(oe.target.value,10)||0),min:0,"data-testid":"persona-detail-max-turns"})]}),a.jsxs("label",{children:["System Prompt",a.jsx("textarea",{value:S,onChange:oe=>j(oe.target.value),placeholder:"You are a senior frontend engineer...",rows:10,required:!0,"data-testid":"persona-detail-prompt"})]})]}),I==="script"&&a.jsxs(a.Fragment,{children:[a.jsxs("label",{children:["Model ",a.jsx("span",{className:bs.optional,children:"(optional)"}),a.jsx("input",{type:"text",value:C,onChange:oe=>D(oe.target.value),placeholder:"e.g. sonnet (leave empty for script-only)","data-testid":"persona-detail-model"})]}),a.jsxs("label",{children:["System Prompt",a.jsx("textarea",{value:S,onChange:oe=>j(oe.target.value),placeholder:"Context for the script...",rows:4,required:!0,"data-testid":"persona-detail-prompt"})]}),a.jsxs("label",{children:["Script",a.jsx("textarea",{value:B,onChange:oe=>P(oe.target.value),placeholder:`script({ model: "openai:gpt-4o" });
730
+ src/utils/token-refresh.ts:28: const remaining = decoded.exp - Date.now() / 1000;`,raw:JSON.stringify({tool_use_id:"tool-mock-004",is_error:!1})}},{delayMs:7800,event:{eventType:"text",timestamp:Ie(7800),content:"Fixed. The token expiry comparison was inverted — `decoded.exp > Date.now()` should have been `<` (a token is expired when its `exp` is in the past). The other occurrence in `token-refresh.ts` uses subtraction (not comparison), so it was already correct. All 3 auth tests pass."}},{delayMs:8400,event:{eventType:"usage",timestamp:Ie(8400),content:JSON.stringify({input_tokens:42600,output_tokens:1850,cost_millicents:12e3})}},{delayMs:8800,event:{eventType:"status",timestamp:Ie(8800),content:"completed"}}]}],is={onConnect:async()=>{},onDisconnect:()=>{},handleEvent:()=>!1},f_=400;function U$({children:t}){const[s,o]=y.useState(M$),[r,c]=y.useState(I$),[d,u]=y.useState(O$),[p,m]=y.useState(void 0),[g,v]=y.useState(B$),[_,b]=y.useState(""),[x,S]=y.useState(L$),[j,w]=y.useState(ed),[T,C]=y.useState(void 0),D=!1,[O,A]=y.useState(z$),[I,$]=y.useState({claude:"off",github:"off",copilot:"off",codex:"off",goose:"off"}),[B,P]=y.useState($$),[X,H]=y.useState([]),[Q]=y.useState(P$),[he,W]=y.useState(""),[ie,L]=y.useState(Ds),[E,J]=y.useState(Ga),[me,q]=y.useState(void 0),[de,re]=y.useState(void 0),[xe,be]=y.useState(""),fe=y.useRef(void 0),_e=y.useRef(0),ke=y.useRef(0),Le=y.useRef(new Set),Ot=y.useRef(new Map),Vn=y.useRef(x);Vn.current=x;const oe=y.useRef(new Map),Je=y.useRef(new Map),Ht=y.useCallback(V=>(_e.current+=1,`mock-${V}-${String(_e.current).padStart(3,"0")}`),[]),ne=y.useCallback(()=>{const V=u_[ke.current%u_.length];return ke.current+=1,V},[]),Ct=y.useCallback((V,te,le)=>{const ue=setTimeout(()=>{var ve;Le.current.delete(ue),le&&((ve=Ot.current.get(le))==null||ve.delete(ue)),V()},te);Le.current.add(ue),le&&(Ot.current.has(le)||Ot.current.set(le,new Set),Ot.current.get(le).add(ue))},[]),Bt=y.useCallback(V=>{const te=Ot.current.get(V);te&&(te.forEach(le=>{clearTimeout(le),Le.current.delete(le)}),Ot.current.delete(V))},[]),Lt=y.useCallback((V,te,le)=>{c(ue=>ue.map(ve=>ve.id===V?{...ve,status:te,...le!==void 0?{endReason:le}:{}}:ve))},[]),Pe=y.useCallback(V=>{u(te=>[...te,V])},[]),rn=y.useCallback((V,te,le)=>{te.forEach((ue,ve)=>{Ct(()=>{const Ve={sessionId:V,...ue.event,timestamp:new Date().toISOString()};if(Pe(Ve),ue.event.eventType==="status"){const Te=ck(ue.event.content),Me=dk(ue.event.content);Lt(V,Te,Me)}ve===te.length-1&&le&&le()},ue.delayMs,V)})},[Ct,Pe,Lt]),ha=y.useCallback(async(V,te,le,ue)=>{console.log("[MockGrackle] spawn",{environmentId:V,prompt:te,runtime:ue});const ve=Ht("sess"),Ve={id:ve,environmentId:V,runtime:ue||"claude-code",status:"running",prompt:te,startedAt:new Date().toISOString()};c(Me=>[...Me,Ve]),m(ve);const Te=ne();if(console.log(`[MockGrackle] Playing scenario: ${Te.label}`),Te.pauseForInput){const Me=Te.pauseAfterStep??Te.steps.length-1,Xe=Te.steps.slice(0,Me+1),gt=Xe.length>0?Xe[Xe.length-1].delayMs:0;rn(ve,Xe),Ct(()=>{Lt(ve,"idle"),Pe({sessionId:ve,eventType:"status",timestamp:new Date().toISOString(),content:"idle"})},gt+f_,ve),Te.resumeSteps&&oe.current.set(ve,Te.resumeSteps)}else rn(ve,Te.steps)},[Ht,ne,rn,Ct,Lt,Pe]),us=y.useCallback(async V=>{console.log("[MockGrackle] kill",V),Bt(V),oe.current.delete(V),Lt(V,"stopped","killed"),Pe({sessionId:V,eventType:"status",timestamp:new Date().toISOString(),content:"killed"}),S(te=>te.map(le=>le.latestSessionId===V&&le.status==="working"?{...le,status:"not_started"}:le))},[Bt,Lt,Pe]),ei=y.useCallback(async V=>{console.log("[MockGrackle] stopGraceful",V),Bt(V),oe.current.delete(V),Lt(V,"stopped","terminated"),Pe({sessionId:V,eventType:"status",timestamp:new Date().toISOString(),content:"terminated"}),S(te=>te.map(le=>le.latestSessionId===V&&le.status==="working"?{...le,status:"not_started"}:le))},[Bt,Lt,Pe]),ga=y.useCallback(()=>{console.log("[MockGrackle] refresh")},[]),en=y.useCallback(async V=>{console.log("[MockGrackle] loadSessionEvents",V)},[]),Pi=y.useCallback(()=>{console.log("[MockGrackle] clearEvents"),u([])},[]),va=y.useCallback(async(V,te,le,ue,ve,Ve,Te,Me,Xe)=>{console.log("[MockGrackle] createWorkspace",{name:V,description:te});const gt={id:Ht("proj"),name:V,description:te||"",repoUrl:le||"",linkedEnvironmentIds:ue?[ue]:[],status:"active",workingDirectory:Te||"",useWorktrees:Ve??!0,defaultPersonaId:ve||"",tokenBudget:0,costBudgetMillicents:0,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};v($e=>[...$e,gt]),Me&&Me()},[Ht]),ti=y.useCallback(async V=>{console.log("[MockGrackle] archiveWorkspace",V),v(te=>te.map(le=>le.id===V?{...le,status:"archived"}:le))},[]),Ss=y.useCallback(async V=>{console.log("[MockGrackle] loadTasks",V)},[]),Ui=y.useCallback(async(V,te,le,ue,ve,Ve,Te,Me,Xe)=>{console.log("[MockGrackle] createTask",{workspaceId:V,title:te,parentTaskId:ve}),S(gt=>{const Qe=gt.filter(zs=>zs.workspaceId===V).reduce((zs,Yo)=>Math.max(zs,Yo.sortOrder),0),dt=ve?gt.find(zs=>zs.id===ve):void 0;if(ve&&!dt)return console.warn("[MockGrackle] Parent task not found:",ve),gt;if(dt&&!dt.canDecompose)return console.warn("[MockGrackle] Parent task does not have decomposition rights:",ve),gt;const yt=dt?dt.depth+1:0,Ts={id:Ht("task"),workspaceId:V,title:te,description:le||"",status:"not_started",branch:"",latestSessionId:"",dependsOn:ue||[],reviewNotes:void 0,sortOrder:Qe+1,createdAt:new Date().toISOString(),parentTaskId:ve||"",depth:yt,childTaskIds:[],canDecompose:Te??!ve,defaultPersonaId:Ve||"",workpad:"",tokenBudget:0,costBudgetMillicents:0};return[...gt,Ts]}),Me&&Me()},[Ht]),qn=y.useCallback(async(V,te,le,ue)=>{var gt;console.log("[MockGrackle] startTask",{taskId:V});const ve=Vn.current.find($e=>$e.id===V),Ve=(ve==null?void 0:ve.title)??"",Te=Ht("sess"),Me={id:Te,environmentId:"env-local-01",runtime:"claude-code",status:"running",prompt:Ve||V,startedAt:new Date().toISOString()};c($e=>[...$e,Me]),S($e=>$e.map(Qe=>Qe.id===V?{...Qe,status:"working",latestSessionId:Te,branch:`mock/${V.slice(0,8)}`}:Qe));const Xe=ne();if(console.log(`[MockGrackle] Playing task scenario: ${Xe.label}`),Xe.pauseForInput){const $e=Xe.pauseAfterStep??Xe.steps.length-1,Qe=Xe.steps.slice(0,$e+1),dt=Qe.length>0?Qe[Qe.length-1].delayMs:0;if(rn(Te,Qe),Ct(()=>{Lt(Te,"idle"),Pe({sessionId:Te,eventType:"status",timestamp:new Date().toISOString(),content:"idle"})},dt+f_,Te),Xe.resumeSteps){const yt=[...Xe.resumeSteps];oe.current.set(Te,yt);const Ts=yt.reduce((zs,Yo)=>Math.max(zs,Yo.delayMs),0);Je.current.set(Te,{taskId:V,delayAfterResume:Ts+200})}}else{const $e=Xe.steps.length>0?Xe.steps[Xe.steps.length-1].delayMs:0;rn(Te,Xe.steps);const Qe=(gt=Xe.steps[Xe.steps.length-1])==null?void 0:gt.event.content;Ct(()=>{Qe==="completed"?S(dt=>dt.map(yt=>yt.id===V&&yt.status==="working"?{...yt,status:"paused"}:yt)):Qe==="failed"&&S(dt=>dt.map(yt=>yt.id===V&&yt.status==="working"?{...yt,status:"failed"}:yt))},$e+100,Te)}},[Ht,ne,rn,Ct,Lt,Pe]),De=y.useCallback(async(V,te)=>{console.log("[MockGrackle] sendInput",{sessionId:V,text:te}),Pe({sessionId:V,eventType:"output",timestamp:new Date().toISOString(),content:`User input: ${te}`}),Lt(V,"running"),Pe({sessionId:V,eventType:"status",timestamp:new Date().toISOString(),content:"running"});const le=oe.current.get(V);if(le)oe.current.delete(V),rn(V,le);else{const ve=[{delayMs:500,event:{eventType:"output",timestamp:new Date().toISOString(),content:"I received your input, continuing..."}},{delayMs:1500,event:{eventType:"status",timestamp:new Date().toISOString(),content:"completed"}}];rn(V,ve)}const ue=Je.current.get(V);ue&&(Je.current.delete(V),Ct(()=>{S(ve=>ve.map(Ve=>Ve.id===ue.taskId&&Ve.status==="working"?{...Ve,status:"paused"}:Ve))},ue.delayAfterResume,V))},[Pe,Lt,rn,Ct]),We=y.useCallback(async V=>{console.log("[MockGrackle] completeTask",V),S(te=>te.map(le=>le.id===V?{...le,status:"complete"}:le))},[]),tn=y.useCallback(async V=>{console.log("[MockGrackle] resumeTask",V)},[]),jt=y.useCallback(async(V,te,le,ue,ve)=>{console.log("[MockGrackle] updateTask",{taskId:V,title:te}),S(Ve=>Ve.map(Te=>Te.id===V?{...Te,title:te.trim()||Te.title,description:le,dependsOn:ue,...ve!==void 0?{defaultPersonaId:ve}:{}}:Te))},[]),vn=y.useCallback(async V=>{console.log("[MockGrackle] deleteTask",V),S(te=>te.filter(le=>le.id!==V))},[]),nn=y.useCallback(async V=>{console.log("[MockGrackle] loadFindings",V),w(ed.filter(te=>te.workspaceId===V))},[]),Hi=y.useCallback(async()=>{console.log("[MockGrackle] loadAllFindings"),w([...ed])},[]),Vi=y.useCallback(async V=>{console.log("[MockGrackle] loadFinding",V);const te=ed.find(le=>le.id===V);C(te)},[]),qi=y.useCallback(async(V,te,le,ue,ve)=>{console.log("[MockGrackle] postFinding",{workspaceId:V,title:te});const Ve={id:Ht("find"),workspaceId:V,taskId:"",sessionId:"",category:ue||"general",title:te,content:le,tags:ve||[],createdAt:new Date().toISOString()};w(Te=>[...Te,Ve])},[Ht]),ni=y.useCallback(async()=>{console.log("[MockGrackle] loadEnvironments")},[]),si=y.useCallback(async(V,te,le)=>{console.log("[MockGrackle] addEnvironment",{displayName:V,adapterType:te,adapterConfig:le})},[]),ai=y.useCallback(async(V,te)=>{console.log("[MockGrackle] updateEnvironment",{environmentId:V,...te}),o(le=>le.map(ue=>ue.id!==V?ue:{...ue,...te.displayName!==void 0?{displayName:te.displayName}:{},...te.adapterConfig!==void 0?{adapterConfig:JSON.stringify(te.adapterConfig)}:{}}))},[]),js=y.useCallback(async()=>{console.log("[MockGrackle] loadTokens")},[]),ii=y.useCallback(async(V,te,le,ue,ve)=>{console.log("[MockGrackle] setToken",{name:V,tokenType:le}),A(Ve=>[...Ve.filter(Me=>Me.name!==V),{name:V,tokenType:le,envVar:ue,filePath:ve,expiresAt:""}])},[]),ya=y.useCallback(async V=>{console.log("[MockGrackle] deleteToken",V),A(te=>te.filter(le=>le.name!==V))},[]),Tl=y.useCallback(async V=>{console.log("[MockGrackle] updateCredentialProviders",V),$(V)},[]);y.useEffect(()=>()=>{Le.current.forEach(clearTimeout),Le.current.clear()},[]);const wl=y.useMemo(()=>({connectionStatus:"connected",environments:{environments:s,environmentsLoading:!1,provisionStatus:{},operationError:"",clearOperationError:()=>{},loadEnvironments:ni,addEnvironment:si,updateEnvironment:ai,provisionEnvironment:async(V,te)=>{},stopEnvironment:async()=>{},removeEnvironment:async()=>{},domainHook:is},sessions:{sessions:r,sessionsLoading:!1,events:d,eventsDropped:0,lastSpawnedId:p,taskSessions:Q,spawn:ha,sendInput:De,kill:us,stopGraceful:ei,loadSessionEvents:en,clearEvents:Pi,loadTaskSessions:async V=>{console.log("[MockGrackle] loadTaskSessions",V)},domainHook:is},workspaces:{workspaces:g,workspacesLoading:!1,workspaceCreating:!1,loadWorkspaces:async()=>{console.log("[MockGrackle] loadWorkspaces")},createWorkspace:va,archiveWorkspace:ti,updateWorkspace:async(V,te)=>{console.log("[MockGrackle] updateWorkspace",{workspaceId:V,...te}),v(le=>le.map(ue=>ue.id!==V?ue:{...ue,...te.name!==void 0?{name:te.name}:{},...te.description!==void 0?{description:te.description}:{},...te.repoUrl!==void 0?{repoUrl:te.repoUrl}:{},...te.environmentId!==void 0?{environmentId:te.environmentId}:{},...te.workingDirectory!==void 0?{workingDirectory:te.workingDirectory}:{},...te.useWorktrees!==void 0?{useWorktrees:te.useWorktrees}:{},...te.defaultPersonaId!==void 0?{defaultPersonaId:te.defaultPersonaId}:{},updatedAt:new Date().toISOString()}))},linkEnvironment:async(V,te)=>{if(console.log("[MockGrackle] linkEnvironment",{workspaceId:V,environmentId:te}),te==="error-env"){b("Failed to link environment");return}b(""),v(le=>le.map(ue=>ue.id!==V||ue.linkedEnvironmentIds.includes(te)?ue:{...ue,linkedEnvironmentIds:[...ue.linkedEnvironmentIds,te]}))},unlinkEnvironment:async(V,te)=>{if(console.log("[MockGrackle] unlinkEnvironment",{workspaceId:V,environmentId:te}),te==="error-env"){b("Failed to unlink environment");return}b(""),v(le=>le.map(ue=>ue.id!==V?ue:{...ue,linkedEnvironmentIds:ue.linkedEnvironmentIds.filter(ve=>ve!==te)}))},linkOperationError:_,clearLinkOperationError:()=>{b("")},domainHook:is},tasks:{tasks:x,tasksLoading:!1,taskStartingId:void 0,loadTasks:Ss,loadAllTasks:async()=>{console.log("[MockGrackle] loadAllTasks")},createTask:Ui,startTask:qn,stopTask:async V=>{console.log("[MockGrackle] stopTask",{taskId:V}),await We(V)},completeTask:We,resumeTask:tn,updateTask:jt,deleteTask:vn,domainHook:is},findings:{findings:j,selectedFinding:T,findingLoading:D,findingsLoading:!1,loadFindings:nn,loadAllFindings:Hi,loadFinding:Vi,postFinding:qi,domainHook:is},tokens:{tokens:O,tokensLoading:!1,loadTokens:js,setToken:ii,deleteToken:ya,domainHook:is},credentials:{credentialProviders:I,credentialsLoading:!1,updateCredentialProviders:Tl,domainHook:is},codespaces:{codespaces:[],codespaceError:"",codespaceListError:"",codespaceCreating:!1,listCodespaces:async()=>{},createCodespace:async()=>{},domainHook:is},personas:{personas:B,personasLoading:!1,createPersona:async(V,te,le,ue,ve,Ve,Te,Me,Xe)=>{console.log("[MockGrackle] createPersona",{name:V});const gt={id:`mock-persona-${Date.now()}`,name:V,description:te,systemPrompt:le,toolConfig:"{}",runtime:ue??"claude-code",model:ve||"",maxTurns:Ve||0,mcpServers:"[]",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),type:Te||"agent",script:Me||"",allowedMcpTools:Xe||[]};return P($e=>[...$e,gt]),gt},updatePersona:async(V,te,le,ue,ve,Ve,Te,Me,Xe,gt)=>{console.log("[MockGrackle] updatePersona",{personaId:V,name:te});const $e=B.find(yt=>yt.id===V);if(!$e)throw new Error(`Persona not found: ${V}`);const Qe=new Date().toISOString(),dt={...$e,...te!==void 0?{name:te}:{},...le!==void 0?{description:le}:{},...ue!==void 0?{systemPrompt:ue}:{},...ve!==void 0?{runtime:ve}:{},...Ve!==void 0?{model:Ve}:{},...Te!==void 0?{maxTurns:Te}:{},...Me!==void 0?{type:Me}:{},...Xe!==void 0?{script:Xe}:{},...gt!==void 0?{allowedMcpTools:gt}:{},updatedAt:Qe};return P(yt=>yt.map(Ts=>Ts.id===V?dt:Ts)),dt},deletePersona:async V=>{console.log("[MockGrackle] deletePersona",V),P(te=>te.filter(le=>le.id!==V))},domainHook:is},schedules:{schedules:X,schedulesLoading:!1,createSchedule:async(V,te,le,ue,ve)=>{console.log("[MockGrackle] createSchedule",{title:V});const Ve={id:`mock-schedule-${Date.now()}`,title:V,description:te,scheduleExpression:le,personaId:ue,workspaceId:ve??"",parentTaskId:"",enabled:!0,lastRunAt:"",nextRunAt:new Date(Date.now()+6e4).toISOString(),runCount:0,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return H(Te=>[...Te,Ve]),Ve},updateSchedule:async(V,te)=>{console.log("[MockGrackle] updateSchedule",{scheduleId:V,fields:te});let le;if(H(ue=>ue.map(ve=>ve.id!==V?ve:(le={...ve,...te,updatedAt:new Date().toISOString()},le))),!le)throw new Error(`Schedule not found: ${V}`);return le},deleteSchedule:async V=>{console.log("[MockGrackle] deleteSchedule",V),H(te=>te.filter(le=>le.id!==V))},domainHook:is},streams:{streams:[],streamsLoading:!1,streamsLoadedOnce:!0,streamsLoadError:!1,loadStreams:async()=>{},domainHook:is},knowledge:{graphData:{nodes:ie,links:E},selectedNode:me,loading:!1,selectedId:de,searchQuery:xe,search:async V=>{if(console.log("[MockGrackle] knowledge.search",V),!V.trim()){be(V);return}be(V);const te=fe.current,le=te?Ds.filter(Te=>!Te.workspaceId||Te.workspaceId===te):Ds,ue=V.toLowerCase(),ve=le.filter(Te=>{var Me,Xe,gt;return Te.label.toLowerCase().includes(ue)||((Me=Te.content)==null?void 0:Me.toLowerCase().includes(ue))||((Xe=Te.tags)==null?void 0:Xe.some($e=>$e.toLowerCase().includes(ue)))||((gt=Te.category)==null?void 0:gt.toLowerCase().includes(ue))});L(ve);const Ve=new Set(ve.map(Te=>Te.id));J(Ga.filter(Te=>Ve.has(Te.source)&&Ve.has(Te.target))),re(void 0),q(void 0)},clearSearch:()=>{console.log("[MockGrackle] knowledge.clearSearch"),be("");const V=fe.current,te=V?Ds.filter(ue=>!ue.workspaceId||ue.workspaceId===V):Ds;L(te);const le=new Set(te.map(ue=>ue.id));J(Ga.filter(ue=>le.has(ue.source)&&le.has(ue.target)))},selectNode:async V=>{console.log("[MockGrackle] knowledge.selectNode",V),re(V);const te=V in d_?d_[V]:void 0;if(te)q(te);else{const le=Ds.find(ue=>ue.id===V);if(le){const ue=Ga.filter(ve=>ve.source===V||ve.target===V).map(ve=>({fromId:ve.source,toId:ve.target,type:ve.type}));q({node:le,edges:ue})}}},clearSelection:()=>{console.log("[MockGrackle] knowledge.clearSelection"),re(void 0),q(void 0)},expandNode:async V=>{console.log("[MockGrackle] knowledge.expandNode",V),L(te=>{const le=new Set(te.map(Me=>Me.id)),ue=Ga.filter(Me=>Me.source===V||Me.target===V),ve=new Set;for(const Me of ue)le.has(Me.source)||ve.add(Me.source),le.has(Me.target)||ve.add(Me.target);if(ve.size===0)return te;const Ve=Ds.filter(Me=>ve.has(Me.id)),Te=new Set([...le,...ve]);return J(Me=>{const Xe=new Set(Me.map($e=>`${$e.source}|${$e.target}|${$e.type}`)),gt=Ga.filter($e=>Te.has($e.source)&&Te.has($e.target)&&!Xe.has(`${$e.source}|${$e.target}|${$e.type}`));return gt.length>0?[...Me,...gt]:Me}),[...te,...Ve]})},loadRecent:async V=>{if(console.log("[MockGrackle] knowledge.loadRecent",V),fe.current=V,V){const te=Ds.filter(ue=>!ue.workspaceId||ue.workspaceId===V);L(te);const le=new Set(te.map(ue=>ue.id));J(Ga.filter(ue=>le.has(ue.source)&&le.has(ue.target)))}else L(Ds),J(Ga);be("")},handleEvent:()=>!1,domainHook:is},plugins:{plugins:[{name:"core",description:"Core infrastructure",enabled:!0,required:!0,loaded:!0},{name:"orchestration",description:"Task orchestration",enabled:!0,required:!1,loaded:!0},{name:"scheduling",description:"Scheduled triggers",enabled:!0,required:!1,loaded:!0},{name:"knowledge",description:"Knowledge graph",enabled:!1,required:!1,loaded:!1}],pluginsLoading:!1,loadPlugins:async()=>{console.log("[MockGrackle] loadPlugins")},setPluginEnabled:async(V,te)=>{console.log("[MockGrackle] setPluginEnabled",V,te)}},appDefaultPersonaId:he,setAppDefaultPersonaId:async V=>{console.log("[MockGrackle] setAppDefaultPersonaId",V),W(V)},onboardingCompleted:!0,completeOnboarding:async()=>{console.log("[MockGrackle] completeOnboarding")},usageCache:{"workspace:proj-alpha":{inputTokens:214500,outputTokens:44850,costMillicents:112e3,sessionCount:4},"workspace:proj-beta":{inputTokens:86700,outputTokens:23800,costMillicents:48e3,sessionCount:3},"task:task-001":{inputTokens:126800,outputTokens:20850,costMillicents:63e3,sessionCount:2},"task:task-006":{inputTokens:18900,outputTokens:4500,costMillicents:1e4,sessionCount:1},"task_tree:task-001":{inputTokens:126800,outputTokens:20850,costMillicents:63e3,sessionCount:2},"task_tree:task-006":{inputTokens:18900,outputTokens:4500,costMillicents:1e4,sessionCount:1}},loadUsage:async(V,te)=>{console.log(`[MockGrackle] loadUsage(${V}, ${te})`)},refresh:ga}),[s,r,d,p,Q,g,_,x,j,T,O,I,B,X,he,ie,E,me,de,xe,ha,De,us,ei,en,Pi,va,ti,Ss,Ui,qn,We,tn,jt,vn,nn,Hi,Vi,qi,ni,si,ai,js,ii,ya,Tl,ga]);return a.jsx(vh.Provider,{value:wl,children:t})}const pk=3e3,H$=pk;function V$(t){const[s,o]=y.useState("connecting"),r=y.useRef(t.onSessionEvent);r.current=t.onSessionEvent;const c=y.useRef(t.onDomainEvent);c.current=t.onDomainEvent;const d=y.useRef(t.onConnect);d.current=t.onConnect;const u=y.useRef(t.onDisconnect);return u.current=t.onDisconnect,y.useEffect(()=>{let p=!1,m,g;async function v(){var x,S;if(p)return;Promise.resolve((x=d.current)==null?void 0:x.call(d)).catch(()=>{});let _=!1;const b=()=>{!_&&!p&&(_=!0,o("connected"))};g=setTimeout(b,H$);try{const j=Fe.streamEvents({});for await(const w of j){if(b(),p)break;const T=w.event;if(T.case==="sessionEvent"){const C=T.value;r.current({sessionId:C.sessionId,type:C.type,timestamp:C.timestamp,content:C.content,raw:C.raw})}else if(T.case==="domainEvent"){const C=T.value;c.current({id:C.id,type:C.type,timestamp:C.timestamp,payloadJson:C.payloadJson})}}}catch(j){if(clearTimeout(g),j instanceof Di&&j.code===D_.Unauthenticated){window.location.href=$N;return}}clearTimeout(g),p||(o("connecting"),(S=u.current)==null||S.call(u),m=setTimeout(()=>{v().catch(()=>{})},pk))}return v().catch(()=>{}),()=>{p=!0,clearTimeout(m),clearTimeout(g)}},[]),{connectionStatus:s}}const jm=["core","orchestration","scheduling"],mk=y.createContext({pluginNames:[...jm],loading:!1,error:void 0});function q$({children:t}){const[s,o]=y.useState([...jm]),[r,c]=y.useState(!0),[d,u]=y.useState(void 0);return y.useEffect(()=>{let p=!1;return fetch("/api/manifest").then(async m=>{if(!m.ok)throw new Error(`Manifest fetch returned ${m.status}`);return m.json()}).then(m=>{p||(o(m.plugins.map(g=>g.name)),c(!1))}).catch(m=>{p||(o([...jm]),u(m instanceof Error?m:new Error(String(m))),c(!1))}),()=>{p=!0}},[]),a.jsx(mk.Provider,{value:{pluginNames:s,loading:r,error:d},children:t})}function xh(){return y.useContext(mk)}const G$=new Set(["dashboard","chat","environments","settings"]),F$=new Set(["tasks","findings"]),Z$=new Set(["knowledge"]),hk={core:{navItems:cd.filter(t=>G$.has(t.view)),domainHookKeys:["environments","sessions","workspaces","tokens","credentials","codespaces","streams","plugins"]},orchestration:{navItems:cd.filter(t=>F$.has(t.view)),domainHookKeys:["tasks","findings","personas","notifications"]},scheduling:{navItems:[],domainHookKeys:["schedules"]},knowledge:{navItems:cd.filter(t=>Z$.has(t.view)),domainHookKeys:["knowledge"]}};function K$(t){return t.flatMap(s=>{var o;return((o=hk[s])==null?void 0:o.navItems)??[]})}function Y$(t){return new Set(t.flatMap(s=>{var o;return((o=hk[s])==null?void 0:o.domainHookKeys)??[]}))}function J$(t){return{id:t.id,displayName:t.displayName,adapterType:t.adapterType,adapterConfig:t.adapterConfig||"{}",status:t.status,bootstrapped:t.bootstrapped}}function p_(t){return{id:t.id,environmentId:t.environmentId,runtime:t.runtime,status:t.status,prompt:t.prompt,startedAt:t.startedAt,endedAt:t.endedAt||void 0,error:t.error||void 0,endReason:t.endReason||void 0,personaId:t.personaId||void 0,inputTokens:t.inputTokens,outputTokens:t.outputTokens,costMillicents:t.costMillicents}}function W$(t){return{sessionId:t.sessionId,eventType:R_(t.type),timestamp:t.timestamp,content:t.content,raw:t.raw||void 0}}function X$(t){return{id:t.id,name:t.name,description:t.description,repoUrl:t.repoUrl,linkedEnvironmentIds:[...t.linkedEnvironmentIds],status:q2(t.status),workingDirectory:t.workingDirectory,useWorktrees:t.useWorktrees,defaultPersonaId:t.defaultPersonaId,tokenBudget:t.tokenBudget,costBudgetMillicents:t.costBudgetMillicents,createdAt:t.createdAt,updatedAt:t.updatedAt}}function m_(t){return{id:t.id,workspaceId:t.workspaceId??void 0,title:t.title,description:t.description,status:G2(t.status),branch:t.branch,latestSessionId:t.latestSessionId,dependsOn:[...t.dependsOn],sortOrder:t.sortOrder,createdAt:t.createdAt,startedAt:t.startedAt||void 0,completedAt:t.completedAt||void 0,parentTaskId:t.parentTaskId,depth:t.depth,childTaskIds:[...t.childTaskIds],canDecompose:t.canDecompose,defaultPersonaId:t.defaultPersonaId,workpad:t.workpad,tokenBudget:t.tokenBudget,costBudgetMillicents:t.costBudgetMillicents}}function Up(t){return{id:t.id,workspaceId:t.workspaceId,taskId:t.taskId,sessionId:t.sessionId,category:t.category,title:t.title,content:t.content,tags:[...t.tags],createdAt:t.createdAt}}function Q$(t){return{name:t.name,tokenType:t.type,envVar:t.envVar,filePath:t.filePath,expiresAt:t.expiresAt}}function eP(t){return{claude:F2(t.claude),github:$c(t.github),copilot:$c(t.copilot),codex:$c(t.codex),goose:$c(t.goose)}}function tP(t){return{name:t.name,repository:t.repository,state:t.state,gitStatus:t.gitStatus}}function Hp(t){return{id:t.id,name:t.name,description:t.description,systemPrompt:t.systemPrompt,toolConfig:t.toolConfig?JSON.stringify({allowedTools:[...t.toolConfig.allowedTools],disallowedTools:[...t.toolConfig.disallowedTools]}):"{}",runtime:t.runtime,model:t.model,maxTurns:t.maxTurns,mcpServers:JSON.stringify(t.mcpServers.map(s=>({name:s.name,command:s.command,args:[...s.args],tools:[...s.tools]}))),createdAt:t.createdAt,updatedAt:t.updatedAt,type:t.type||"agent",script:t.script,allowedMcpTools:[...t.allowedMcpTools]}}function nP(t){return{inputTokens:t.inputTokens,outputTokens:t.outputTokens,costMillicents:t.costMillicents,sessionCount:t.sessionCount}}function Vp(t){return{id:t.id,title:t.title,description:t.description,scheduleExpression:t.scheduleExpression,personaId:t.personaId,workspaceId:t.workspaceId,parentTaskId:t.parentTaskId,enabled:t.enabled,lastRunAt:t.lastRunAt,nextRunAt:t.nextRunAt,runCount:t.runCount,createdAt:t.createdAt,updatedAt:t.updatedAt}}function td(t,s=0){return{id:t.id,label:t.title||t.label||t.id,kind:t.kind,category:t.category||void 0,sourceType:t.sourceType||void 0,sourceId:t.sourceId||void 0,content:t.content||void 0,tags:t.tags.length>0?[...t.tags]:void 0,workspaceId:t.workspaceId||void 0,createdAt:t.createdAt||void 0,updatedAt:t.updatedAt||void 0,val:s}}function qp(t){return{source:t.fromId,target:t.toId,type:t.type}}function sP(t){return{subscriptionId:t.subscriptionId,sessionId:t.sessionId,fd:t.fd,permission:t.permission,deliveryMode:t.deliveryMode,createdBySpawn:t.createdBySpawn}}function aP(t){return{id:t.id,name:t.name,subscriberCount:t.subscriberCount,messageBufferDepth:t.messageBufferDepth,subscribers:t.subscribers.map(sP)}}function ks(){const[t,s]=y.useState(!1),o=y.useRef(0),r=y.useCallback(c=>(o.current++,o.current===1&&s(!0),c.finally(()=>{o.current--,o.current===0&&s(!1)})),[]);return{loading:t,track:r}}const h_=5e3;function Kr(t){return t instanceof Di?t.message:"Operation failed"}function iP(){const[t,s]=y.useState([]),{loading:o,track:r}=ks(),[c,d]=y.useState({}),[u,p]=y.useState(""),m=y.useCallback(()=>{p("")},[]),g=y.useCallback(async()=>{try{const C=await r(Fe.listEnvironments({}));s(C.environments.map(J$))}catch{}},[r]),v=y.useCallback(C=>{switch(C.type){case"environment.added":return!0;case"environment.removed":{const D=C.payload.environmentId;return D&&(s(O=>O.filter(A=>A.id!==D)),d(O=>{const A={...O};return delete A[D],A})),!0}case"environment.changed":return g().catch(()=>{}),!0;case"environment.provision_progress":{const D=C.payload;if(typeof D.environmentId!="string"||typeof D.stage!="string"||typeof D.message!="string"||typeof D.progress!="number")return lk("environment.provision_progress","invalid payload"),!0;if(d(O=>({...O,[D.environmentId]:{stage:D.stage,message:D.message,progress:D.progress}})),D.stage==="ready"){const O=D.environmentId;setTimeout(()=>{d(A=>{const I={...A};return delete I[O],I})},h_)}return!0}default:return!1}},[g]),_=y.useCallback(C=>{var D;if(C.type==="environments"){const O=Array.isArray((D=C.payload)==null?void 0:D.environments)?C.payload.environments:[];return s(O),!0}return!1},[]),b=y.useCallback(async(C,D,O)=>{p("");try{await Fe.addEnvironment({displayName:C,adapterType:D,adapterConfig:JSON.stringify(O??{})})}catch(A){p(Kr(A))}},[]),x=y.useCallback(async(C,D)=>{p("");try{await Fe.updateEnvironment({id:C,displayName:D.displayName,adapterConfig:D.adapterConfig?JSON.stringify(D.adapterConfig):void 0})}catch(O){p(Kr(O))}},[]),S=y.useCallback(async(C,D)=>{p("");try{const O=Fe.provisionEnvironment({id:C,force:D??!1});for await(const A of O)d(I=>({...I,[C]:{stage:A.stage,message:A.message,progress:A.progress}})),A.stage==="ready"&&setTimeout(()=>{d(I=>{const $={...I};return delete $[C],$})},h_)}catch(O){d(A=>{const I={...A};return delete I[C],I}),p(Kr(O))}},[]),j=y.useCallback(async C=>{p("");try{await Fe.stopEnvironment({id:C})}catch(D){p(Kr(D))}},[]),w=y.useCallback(async C=>{p("");try{await Fe.removeEnvironment({id:C})}catch(D){p(Kr(D))}},[]);return{environments:t,environmentsLoading:o,provisionStatus:c,operationError:u,clearOperationError:m,loadEnvironments:g,addEnvironment:b,updateEnvironment:x,provisionEnvironment:S,stopEnvironment:j,removeEnvironment:w,handleEvent:v,handleLegacyMessage:_,domainHook:{onConnect:()=>g(),onDisconnect:()=>{},handleEvent:v}}}const Gp=new Set(["pending","running","idle"]),oP=new Set(["completed","failed","interrupted","hibernating","suspended"]),g_=["pending","running","idle"];function rP(){const[t,s]=y.useState([]),{loading:o,track:r}=ks(),[c,d]=y.useState([]),[u,p]=y.useState(0),[m,g]=y.useState(void 0),[v,_]=y.useState({}),b=y.useCallback(async()=>{try{const P=(await r(Fe.listSessions({}))).sessions.map(p_);s(X=>{const H=new Map(X.map(Q=>[Q.id,Q]));return P.map(Q=>{const he=H.get(Q.id),W=he==null?void 0:he.status;return!W||W===Q.status?Q:oP.has(W)&&Gp.has(Q.status)?{...Q,status:W,...he.endReason!==void 0?{endReason:he.endReason}:{}}:Gp.has(W)&&Gp.has(Q.status)&&g_.indexOf(W)>g_.indexOf(Q.status)?{...Q,status:W}:Q})})}catch{}},[r]),x=y.useCallback(B=>{if(B.type!=="session_event")return!1;if(!h$(B.payload))return lk("session_event","payload is not a valid SessionEvent"),!0;const P=B.payload;let X=0;if(d(H=>{const Q=[...H,P];return Q.length>Ao?(X=Q.length-Ao,Q.slice(-Ao)):Q}),X>0&&p(H=>H+X),P.eventType==="usage")try{const H=JSON.parse(P.content),Q=Number(H.input_tokens)||0,he=Number(H.output_tokens)||0,W=Number(H.cost_millicents)||0;(Q>0||he>0||W>0)&&s(ie=>ie.map(L=>L.id===P.sessionId?{...L,inputTokens:(L.inputTokens??0)+Q,outputTokens:(L.outputTokens??0)+he,costMillicents:(L.costMillicents??0)+W}:L))}catch{}if(P.eventType==="status"){const H=ck(P.content),Q=dk(P.content);s(he=>he.some(ie=>ie.id===P.sessionId)?he.map(ie=>ie.id===P.sessionId?{...ie,status:H,...Q!==void 0?{endReason:Q}:{}}:ie):[...he,{id:P.sessionId,environmentId:"",runtime:"",status:H,prompt:"",startedAt:P.timestamp,...Q!==void 0?{endReason:Q}:{}}])}return!0},[]),S=y.useCallback(B=>{x({type:"session_event",payload:B})},[x]),j=y.useCallback(B=>{var P,X,H,Q,he;switch(B.type){case"sessions":{const W=Array.isArray((P=B.payload)==null?void 0:P.sessions)?B.payload.sessions:[];return s(W),!0}case"spawned":{const W=(X=B.payload)==null?void 0:X.sessionId;return typeof W=="string"&&W&&g(W),b().catch(()=>{}),!0}case"session_events":{const W=Array.isArray((H=B.payload)==null?void 0:H.events)?B.payload.events:[];return W.length>0&&d(W),!0}case"task_sessions":{const W=(Q=B.payload)==null?void 0:Q.taskId;if(typeof W=="string"&&W){const ie=Array.isArray((he=B.payload)==null?void 0:he.sessions)?B.payload.sessions:[];_(L=>({...L,[W]:ie}))}return!0}default:return!1}},[b]),w=y.useCallback(async(B,P,X,H)=>{try{const Q=await Fe.spawnAgent({environmentId:B,prompt:P,personaId:X||"",workingDirectory:H||""});g(Q.id),await b()}catch{}},[b]),T=y.useCallback(async(B,P)=>{await Fe.sendInput({sessionId:B,text:P})},[]),C=y.useCallback(async B=>{try{await Fe.killAgent({id:B,graceful:!1})}catch{}},[]),D=y.useCallback(async B=>{try{await Fe.killAgent({id:B,graceful:!0})}catch{}},[]),O=y.useCallback(async B=>{try{const X=(await Fe.getSessionEvents({id:B})).events.map(W$);if(X.length>0){let H=0;d(Q=>{const he=new Set;for(const L of Q)L.sessionId===B&&he.add(`${L.timestamp}|${L.eventType}`);const W=X.filter(L=>!he.has(`${L.timestamp}|${L.eventType}`)),ie=[...Q,...W].sort((L,E)=>L.sessionId!==E.sessionId?0:L.timestamp.localeCompare(E.timestamp));return ie.length>Ao?(H=ie.length-Ao,ie.slice(-Ao)):ie}),H>0&&p(Q=>Q+H)}}catch{}},[]),A=y.useCallback(()=>{d([]),p(0)},[]),I=y.useCallback(async B=>{try{const X=(await Fe.getTaskSessions({id:B})).sessions.map(p_);_(H=>({...H,[B]:X}))}catch{}},[]);return{sessions:t,sessionsLoading:o,events:c,eventsDropped:u,lastSpawnedId:m,taskSessions:v,loadSessions:b,spawn:w,sendInput:T,kill:C,stopGraceful:D,loadSessionEvents:O,clearEvents:A,loadTaskSessions:I,handleMessage:x,handleSessionEvent:S,handleLegacyMessage:j,domainHook:{onConnect:()=>b(),onDisconnect:()=>{A()},handleEvent:()=>!1}}}function v_(t){return t instanceof Di?t.message:"Operation failed"}function lP(){const[t,s]=y.useState([]),{loading:o,track:r}=ks(),[c,d]=y.useState(!1),[u,p]=y.useState(""),m=y.useCallback(async()=>{try{const C=await r(Fe.listWorkspaces({}));s(C.workspaces.map(X$))}catch{}},[r]),g=y.useCallback(C=>{switch(C.type){case"workspace.created":return d(!1),m().catch(()=>{}),!0;case"workspace.archived":case"workspace.updated":return m().catch(()=>{}),!0;default:return!1}},[m]),v=y.useCallback(()=>{d(!1)},[]),_=y.useCallback(async(C,D,O,A,I,$,B,P,X)=>{d(!0);try{await Fe.createWorkspace({name:C,description:D||"",repoUrl:O||"",environmentId:A||"",defaultPersonaId:I||void 0,useWorktrees:$??!0,workingDirectory:B||void 0}),d(!1),P==null||P()}catch(H){d(!1);const Q=H instanceof Di?H.message:"Failed to create workspace";X==null||X(Q)}},[]),b=y.useCallback(async C=>{try{await Fe.archiveWorkspace({id:C})}catch{}},[]),x=y.useCallback(async(C,D)=>{try{await Fe.updateWorkspace({id:C,...D})}catch{}},[]),S=y.useCallback(()=>{p("")},[]),j=y.useCallback(async(C,D)=>{try{p(""),await Fe.linkEnvironment({workspaceId:C,environmentId:D}),await m().catch(()=>{})}catch(O){p(v_(O))}},[m]),w=y.useCallback(async(C,D)=>{try{p(""),await Fe.unlinkEnvironment({workspaceId:C,environmentId:D}),await m().catch(()=>{})}catch(O){p(v_(O))}},[m]);return{workspaces:t,workspacesLoading:o,workspaceCreating:c,loadWorkspaces:m,createWorkspace:_,archiveWorkspace:b,updateWorkspace:x,linkEnvironment:j,unlinkEnvironment:w,linkOperationError:u,clearLinkOperationError:S,handleEvent:g,onDisconnect:v,domainHook:{onConnect:()=>m(),onDisconnect:v,handleEvent:g}}}function cP(){const[t,s]=y.useState([]),{loading:o,track:r}=ks(),[c,d]=y.useState(void 0),u=y.useRef({}),p=y.useCallback(async A=>{try{const $=(await pn.listTasks({workspaceId:A})).tasks.map(m_);s(B=>[...B.filter(P=>P.workspaceId!==A),...$])}catch{}},[]),m=y.useCallback(async()=>{try{const I=(await r(pn.listTasks({}))).tasks.map(m_);s($=>{const B=new Set(I.map(P=>P.id));return[...$.filter(P=>!B.has(P.id)),...I]})}catch{}},[r]),g=y.useCallback((A,I)=>{const $=B=>{clearTimeout(u.current[B]),u.current[B]=setTimeout(()=>{delete u.current[B],p(B).catch(()=>{})},200)};A?$(A):I&&s(B=>{const P=B.find(X=>X.id===I);return P!=null&&P.workspaceId?$(P.workspaceId):m().catch(()=>{}),B})},[p,m]),v=y.useCallback(A=>{const I=A.payload;switch(A.type){case"task.created":{const $=typeof I.workspaceId=="string"?I.workspaceId:"";return $&&p($).catch(()=>{}),!0}case"task.started":{const $=typeof I.taskId=="string"?I.taskId:"",B=typeof I.sessionId=="string"?I.sessionId:"",P=typeof I.workspaceId=="string"?I.workspaceId:"";return d(X=>$&&X===$?void 0:X),B&&$&&s(X=>X.map(H=>H.id===$?{...H,latestSessionId:B}:H)),g(P,$),!0}case"task.completed":case"task.deleted":case"task.reparented":case"task.updated":{const $=typeof I.workspaceId=="string"?I.workspaceId:"",B=typeof I.taskId=="string"?I.taskId:"";return d(P=>B&&P===B?void 0:P),g($,B),!0}default:return!1}},[p,g]),_=y.useCallback(()=>{d(void 0)},[]),b=y.useCallback(A=>{var I,$;if(A.type==="tasks"){const B=Array.isArray((I=A.payload)==null?void 0:I.tasks)?A.payload.tasks:[],P=typeof(($=A.payload)==null?void 0:$.workspaceId)=="string"&&A.payload.workspaceId?A.payload.workspaceId:"";return s(P?X=>[...X.filter(H=>H.workspaceId!==P),...B]:X=>{const H=new Set(B.map(Q=>Q.id));return[...X.filter(Q=>!H.has(Q.id)),...B]}),!0}return!1},[]),x=y.useCallback(async(A,I,$,B,P,X,H,Q,he)=>{try{await pn.createTask({workspaceId:A,title:I,description:$||"",dependsOn:B||[],parentTaskId:P||"",defaultPersonaId:X||void 0,canDecompose:H??void 0}),Q==null||Q()}catch(W){const ie=W instanceof Di?W.message:"Failed to create task";he==null||he(ie)}},[]),S=y.useCallback(async(A,I,$,B)=>{d(A);try{await pn.startTask({taskId:A,personaId:I||"",environmentId:$||"",notes:B||""})}catch(P){if(P instanceof Di&&P.code===D_.ResourceExhausted)return;d(void 0)}},[]),j=y.useCallback(async A=>{try{await pn.stopTask({id:A})}catch{}},[]),w=y.useCallback(async A=>{try{await pn.completeTask({id:A})}catch{}},[]),T=y.useCallback(async A=>{try{await pn.resumeTask({id:A})}catch{}},[]),C=y.useCallback(async(A,I,$,B,P)=>{try{await pn.updateTask({id:A,title:I,description:$,dependsOn:B,...P!==void 0?{defaultPersonaId:P}:{}})}catch{}},[]),D=y.useCallback(async A=>{try{await pn.deleteTask({id:A})}catch{}},[]);return{tasks:t,tasksLoading:o,taskStartingId:c,loadTasks:p,loadAllTasks:m,createTask:x,startTask:S,stopTask:j,completeTask:w,resumeTask:T,updateTask:C,deleteTask:D,handleEvent:v,onDisconnect:_,handleLegacyMessage:b,domainHook:{onConnect:()=>m(),onDisconnect:_,handleEvent:v}}}function dP(){const[t,s]=y.useState([]),[o,r]=y.useState(void 0),[c,d]=y.useState(!1),{loading:u,track:p}=ks(),m=y.useCallback(async S=>{try{const j=await p(pn.queryFindings({workspaceId:S}));s(j.findings.map(Up))}catch{}},[p]),g=y.useCallback(async()=>{try{const S=await p(pn.queryFindings({workspaceId:""}));s(S.findings.map(Up))}catch{}},[p]),v=y.useCallback(async S=>{r(void 0),d(!0);try{const j=await pn.getFinding({id:S});r(Up(j))}catch{r(void 0)}finally{d(!1)}},[]),_=y.useCallback(S=>{if(S.type==="finding.posted"){const j=typeof S.payload.workspaceId=="string"?S.payload.workspaceId:"";return j&&m(j).catch(()=>{}),!0}return!1},[m]),b=y.useCallback(async(S,j,w,T,C)=>{try{await pn.postFinding({workspaceId:S,title:j,content:w,category:T??"general",tags:C??[]})}catch{}},[]);return{findings:t,selectedFinding:o,findingLoading:c,findingsLoading:u,loadFindings:m,loadAllFindings:g,loadFinding:v,postFinding:b,handleEvent:_,domainHook:{onConnect:()=>g(),onDisconnect:()=>{},handleEvent:_}}}function uP(){const[t,s]=y.useState([]),{loading:o,track:r}=ks(),c=y.useCallback(async()=>{try{const g=await r(Fe.listTokens({}));s(g.tokens.map(Q$))}catch{}},[r]),d=y.useCallback(g=>g.type==="token.changed"?(c().catch(()=>{}),!0):!1,[c]),u=y.useCallback(async(g,v,_,b,x)=>{try{await Fe.setToken({name:g,value:v,type:_,envVar:b,filePath:x})}catch{}},[]),p=y.useCallback(async g=>{try{await Fe.deleteToken({name:g})}catch{}},[]);return{tokens:t,tokensLoading:o,loadTokens:c,setToken:u,deleteToken:p,handleEvent:d,domainHook:{onConnect:()=>c(),onDisconnect:()=>{},handleEvent:d}}}function fP(){const[t,s]=y.useState({claude:"off",github:"off",copilot:"off",codex:"off",goose:"off"}),{loading:o,track:r}=ks(),c=y.useCallback(async()=>{try{const m=await r(Fe.getCredentialProviders({}));s(eP(m))}catch{}},[r]),d=y.useCallback(m=>m.type==="credential.providers_changed"?(v$(m.payload)&&s(m.payload),!0):!1,[]),u=y.useCallback(async m=>{const g=[{provider:"claude",value:m.claude},{provider:"github",value:m.github},{provider:"copilot",value:m.copilot},{provider:"codex",value:m.codex},{provider:"goose",value:m.goose}];await Promise.allSettled(g.map(({provider:v,value:_})=>Fe.setCredentialProvider({provider:v,value:_})))},[]);return{credentialProviders:t,credentialsLoading:o,loadCredentials:c,updateCredentialProviders:u,handleEvent:d,domainHook:{onConnect:()=>c(),onDisconnect:()=>{},handleEvent:d}}}function pP(){const[t,s]=y.useState([]),[o,r]=y.useState(""),[c,d]=y.useState(""),[u,p]=y.useState(!1),m=y.useCallback(async()=>{try{const _=await Fe.listCodespaces({});s(_.codespaces.map(tP)),d(_.error)}catch{}},[]),g=y.useCallback(async(_,b)=>{p(!0),r("");try{await Fe.createCodespace({repo:_,machine:b??""}),p(!1),await m()}catch(x){p(!1);const S=x instanceof Di?x.message:"Failed to create codespace";r(S)}},[m]);return{codespaces:t,codespaceError:o,codespaceListError:c,codespaceCreating:u,listCodespaces:m,createCodespace:g,domainHook:{onConnect:()=>m(),onDisconnect:()=>{},handleEvent:()=>!1}}}function mP(){const[t,s]=y.useState([]),{loading:o,track:r}=ks(),c=y.useCallback(async()=>{try{const v=await r(pn.listPersonas({}));s(v.personas.map(Hp))}catch{}},[r]),d=y.useCallback(v=>{switch(v.type){case"persona.created":case"persona.updated":case"persona.deleted":return c().catch(()=>{}),!0;default:return!1}},[c]),u=y.useCallback(async(v,_,b,x,S,j,w,T,C)=>{const D=await pn.createPersona({name:v,description:_,systemPrompt:b,runtime:x||"",model:S||"",maxTurns:j||0,type:w||"agent",script:T||"",allowedMcpTools:C||[]}),O=Hp(D);return s(A=>[...A.filter(I=>I.id!==O.id),O]),O},[]),p=y.useCallback(async(v,_,b,x,S,j,w,T,C,D)=>{const O={id:v};_!==void 0&&(O.name=_),b!==void 0&&(O.description=b),x!==void 0&&(O.systemPrompt=x),S!==void 0&&(O.runtime=S),j!==void 0&&(O.model=j),w!==void 0&&(O.maxTurns=w),T!==void 0&&(O.type=T),C!==void 0&&(O.script=C),D!==void 0&&(O.allowedMcpTools={tools:D});const A=await pn.updatePersona(O),I=Hp(A);return s($=>$.map(B=>B.id===I.id?I:B)),I},[]),m=y.useCallback(async v=>{await pn.deletePersona({id:v}),s(_=>_.filter(b=>b.id!==v))},[]);return{personas:t,personasLoading:o,loadPersonas:c,createPersona:u,updatePersona:p,deletePersona:m,handleEvent:d,domainHook:{onConnect:()=>c(),onDisconnect:()=>{},handleEvent:d}}}function hP(){const[t,s]=y.useState([]),{loading:o,track:r}=ks(),c=y.useRef(void 0),d=y.useCallback(async()=>{try{const _=await r(Uc.listSchedules({}));s(_.schedules.map(Vp))}catch{}},[r]),u=y.useCallback(_=>{switch(_.type){case"schedule.created":case"schedule.updated":case"schedule.deleted":return d().catch(()=>{}),!0;case"schedule.fired":return clearTimeout(c.current),c.current=setTimeout(()=>{d().catch(()=>{})},500),!0;default:return!1}},[d]),p=y.useCallback(async(_,b,x,S,j,w)=>{const T=await Uc.createSchedule({title:_,description:b,scheduleExpression:x,personaId:S,workspaceId:j||"",parentTaskId:w||""}),C=Vp(T);return s(D=>[...D.filter(O=>O.id!==C.id),C]),C},[]),m=y.useCallback(async(_,b)=>{const x={id:_};b.title!==void 0&&(x.title=b.title),b.description!==void 0&&(x.description=b.description),b.scheduleExpression!==void 0&&(x.scheduleExpression=b.scheduleExpression),b.personaId!==void 0&&(x.personaId=b.personaId),b.enabled!==void 0&&(x.enabled=b.enabled);const S=await Uc.updateSchedule(x),j=Vp(S);return s(w=>w.map(T=>T.id===j.id?j:T)),j},[]),g=y.useCallback(async _=>{await Uc.deleteSchedule({id:_}),s(b=>b.filter(x=>x.id!==_))},[]);return{schedules:t,schedulesLoading:o,loadSchedules:d,createSchedule:p,updateSchedule:m,deleteSchedule:g,handleEvent:u,domainHook:{onConnect:()=>d(),onDisconnect:()=>{clearTimeout(c.current)},handleEvent:u}}}function gP(t){if(t)try{return JSON.parse(t)}catch{return}}function vP(){const[t,s]=y.useState(new Map),[o,r]=y.useState([]),[c,d]=y.useState(void 0),[u,p]=y.useState(void 0),[m,g]=y.useState(!1),[v,_]=y.useState(""),b=y.useRef(""),x=y.useCallback(async A=>{const I=A??"";b.current=I,_(""),g(!0);try{const $=await Hc.listRecentKnowledgeNodes({limit:30,workspaceId:I}),B=new Map,P=[];for(const X of $.nodes)B.set(X.id,td(X));for(const X of $.edges)P.push(qp(X));for(const X of P){const H=B.get(X.source);H&&(H.val+=1);const Q=B.get(X.target);Q&&(Q.val+=1)}s(B),r(P)}catch{}finally{g(!1)}},[]),S=y.useCallback(async A=>{if(A.trim()){_(A),p(void 0),d(void 0),g(!0);try{const I=await Hc.searchKnowledge({query:A,limit:20,workspaceId:b.current}),$=new Map,B=[];for(const P of I.results){P.node&&$.set(P.node.id,td(P.node,P.edges.length));for(const X of P.edges)B.push(qp(X))}s($),r(B)}catch{}finally{g(!1)}}},[]),j=y.useCallback(()=>{x(b.current).catch(()=>{})},[x]),w=y.useCallback(async A=>{p(A);try{const I=await Hc.getKnowledgeNode({id:A});if(!I.node){d(void 0);return}d({node:td(I.node,I.edges.length),edges:I.edges.map($=>({fromId:$.fromId,toId:$.toId,type:$.type,metadata:gP($.metadataJson)}))})}catch{d(void 0)}},[]),T=y.useCallback(()=>{p(void 0),d(void 0)},[]),C=y.useCallback(async A=>{try{const I=await Hc.expandKnowledgeNode({id:A,depth:1});s($=>{const B=new Map($);for(const P of I.nodes)B.has(P.id)||B.set(P.id,td(P));return B}),r($=>{const B=new Set($.map(X=>`${X.source}:${X.target}:${X.type}`)),P=[];for(const X of I.edges){const H=qp(X),Q=`${H.source}:${H.target}:${H.type}`;B.has(Q)||P.push(H)}return[...$,...P]})}catch{}},[]),D=y.useCallback(A=>!1,[]),O={onConnect:async()=>{},onDisconnect:()=>{},handleEvent:D};return{graphData:{nodes:[...t.values()],links:o},selectedNode:c,selectedId:u,loading:m,searchQuery:v,search:S,clearSearch:j,selectNode:w,clearSelection:T,expandNode:C,loadRecent:x,handleEvent:D,domainHook:O}}function yP(){const t=y.useRef("default");y.useEffect(()=>{typeof Notification>"u"||(t.current=Notification.permission)},[]);function s(r){if(r.type!=="notification.escalated")return!1;if(typeof Notification>"u")return!0;if(t.current==="default")return Notification.requestPermission().then(u=>{t.current=u}).catch(()=>{}),!0;if(t.current!=="granted")return!0;const c=r.payload,d=new Notification(c.title||"Agent needs input",{body:c.message||"An agent is waiting for your input.",tag:c.escalationId,icon:"/icon-192x192.png"});return d.onclick=()=>{window.focus(),c.taskUrl&&(window.location.href=c.taskUrl),d.close()},!0}return{handleEvent:s,domainHook:{onConnect:async()=>{},onDisconnect:()=>{},handleEvent:s}}}function bP(){const[t,s]=y.useState([]),[o,r]=y.useState(!1),[c,d]=y.useState(!1),{loading:u,track:p}=ks(),m=y.useRef(0),g=y.useCallback(async()=>{const b=m.current;try{const x=await p(Fe.listStreams({}));m.current===b&&(s(x.streams.map(aP)),d(!1))}catch{m.current===b&&d(!0)}finally{m.current===b&&r(!0)}},[p]),v=y.useCallback(b=>!1,[]);return{streams:t,streamsLoading:u,streamsLoadedOnce:o,streamsLoadError:c,loadStreams:g,handleEvent:v,domainHook:{onConnect:g,onDisconnect:()=>{m.current+=1,s([]),r(!1),d(!1)},handleEvent:v}}}function _P(){const[t,s]=y.useState([]),{loading:o,track:r}=ks(),c=y.useCallback(async()=>{try{const m=await r(Fe.listPlugins({}));s(m.plugins.map(g=>({name:g.name,description:g.description,enabled:g.enabled,required:g.required,loaded:g.loaded})))}catch{}},[r]),d=y.useCallback(m=>m.type==="plugin.changed"?(c().catch(()=>{}),!0):!1,[c]),u=y.useCallback(async(m,g)=>{try{const v=await Fe.setPluginEnabled({name:m,enabled:g});s(_=>_.map(b=>b.name===v.name?{...b,enabled:v.enabled}:b))}catch{}},[]);return{plugins:t,pluginsLoading:o,loadPlugins:c,setPluginEnabled:u,domainHook:{onConnect:()=>c(),onDisconnect:()=>{},handleEvent:d}}}function xP(){const[t,s]=y.useState(""),[o,r]=y.useState(void 0),[c,d]=y.useState({}),{pluginNames:u}=xh(),p=Y$(u),m=iP(),g=rP(),v=lP(),_=cP(),b=dP(),x=uP(),S=fP(),j=pP(),w=mP(),T=hP(),C=vP(),D=yP(),O=bP(),A=_P(),I=[...p.has("environments")?[m.domainHook]:[],...p.has("sessions")?[g.domainHook]:[],...p.has("workspaces")?[v.domainHook]:[],...p.has("tasks")?[_.domainHook]:[],...p.has("findings")?[b.domainHook]:[],...p.has("tokens")?[x.domainHook]:[],...p.has("credentials")?[S.domainHook]:[],...p.has("codespaces")?[j.domainHook]:[],...p.has("personas")?[w.domainHook]:[],...p.has("schedules")?[T.domainHook]:[],...p.has("knowledge")?[C.domainHook]:[],...p.has("notifications")?[D.domainHook]:[],...p.has("streams")?[O.domainHook]:[],...p.has("plugins")?[A.domainHook]:[]],{connectionStatus:$}=V$({onSessionEvent:E=>{g.handleSessionEvent({sessionId:E.sessionId,eventType:R_(E.type),timestamp:E.timestamp,content:E.content,raw:E.raw||void 0})},onDomainEvent:E=>{try{const J=JSON.parse(E.payloadJson);he({id:E.id,type:E.type,timestamp:E.timestamp,payload:J})}catch{console.warn("[grackle] Failed to parse domain event payloadJson:",E.payloadJson)}},onConnect:W,onDisconnect:ie}),B="default_persona_id",P="onboarding_completed",X=y.useCallback(async E=>{const J=await Fe.setSetting({key:B,value:E});s(J.value)},[]),H=y.useCallback(async()=>{r(!0);try{await Fe.setSetting({key:P,value:"true"})}catch{}},[]),Q=y.useCallback(async(E,J)=>{try{const me=await Fe.getUsage({scope:E,id:J}),q=`${E}:${J}`;d(de=>({...de,[q]:nP(me)}))}catch{}},[]);function he(E){const J=E.payload.key,me=E.payload.value;if(E.type==="setting.changed"){J===B&&s(me??""),J===P&&r(me==="true");return}for(const q of I)if(q.handleEvent(E))break;(E.type==="environment.removed"||E.type==="environment.changed"||E.type==="task.started")&&g.loadSessions().catch(()=>{}),(E.type==="session.started"||E.type==="session.stopped")&&O.loadStreams().catch(()=>{})}async function W(){for(const E of I)E.onConnect().catch(()=>{});try{const E=await Fe.getSetting({key:B});s(E.value)}catch{}try{const E=await Fe.getSetting({key:P});r(E.value==="true")}catch{}}function ie(){I.forEach(E=>E.onDisconnect())}const L=y.useCallback(()=>{m.loadEnvironments().catch(()=>{}),g.loadSessions().catch(()=>{}),v.loadWorkspaces().catch(()=>{}),x.loadTokens().catch(()=>{})},[m.loadEnvironments,g.loadSessions,v.loadWorkspaces,x.loadTokens]);return{connectionStatus:$,environments:{environments:m.environments,environmentsLoading:m.environmentsLoading,provisionStatus:m.provisionStatus,operationError:m.operationError,clearOperationError:m.clearOperationError,loadEnvironments:m.loadEnvironments,addEnvironment:m.addEnvironment,updateEnvironment:m.updateEnvironment,provisionEnvironment:m.provisionEnvironment,stopEnvironment:m.stopEnvironment,removeEnvironment:m.removeEnvironment,domainHook:m.domainHook},sessions:{sessions:g.sessions,sessionsLoading:g.sessionsLoading,events:g.events,eventsDropped:g.eventsDropped,lastSpawnedId:g.lastSpawnedId,taskSessions:g.taskSessions,spawn:g.spawn,sendInput:g.sendInput,kill:g.kill,stopGraceful:g.stopGraceful,loadSessionEvents:g.loadSessionEvents,clearEvents:g.clearEvents,loadTaskSessions:g.loadTaskSessions,domainHook:g.domainHook},workspaces:{workspaces:v.workspaces,workspacesLoading:v.workspacesLoading,workspaceCreating:v.workspaceCreating,loadWorkspaces:v.loadWorkspaces,createWorkspace:v.createWorkspace,archiveWorkspace:v.archiveWorkspace,updateWorkspace:v.updateWorkspace,linkEnvironment:v.linkEnvironment,unlinkEnvironment:v.unlinkEnvironment,linkOperationError:v.linkOperationError,clearLinkOperationError:v.clearLinkOperationError,domainHook:v.domainHook},tasks:{tasks:_.tasks,tasksLoading:_.tasksLoading,taskStartingId:_.taskStartingId,loadTasks:_.loadTasks,loadAllTasks:_.loadAllTasks,createTask:_.createTask,startTask:_.startTask,stopTask:_.stopTask,completeTask:_.completeTask,resumeTask:_.resumeTask,updateTask:_.updateTask,deleteTask:_.deleteTask,domainHook:_.domainHook},findings:{findings:b.findings,selectedFinding:b.selectedFinding,findingLoading:b.findingLoading,findingsLoading:b.findingsLoading,loadFindings:b.loadFindings,loadAllFindings:b.loadAllFindings,loadFinding:b.loadFinding,postFinding:b.postFinding,domainHook:b.domainHook},tokens:{tokens:x.tokens,tokensLoading:x.tokensLoading,loadTokens:x.loadTokens,setToken:x.setToken,deleteToken:x.deleteToken,domainHook:x.domainHook},credentials:{credentialProviders:S.credentialProviders,credentialsLoading:S.credentialsLoading,updateCredentialProviders:S.updateCredentialProviders,domainHook:S.domainHook},codespaces:{codespaces:j.codespaces,codespaceError:j.codespaceError,codespaceListError:j.codespaceListError,codespaceCreating:j.codespaceCreating,listCodespaces:j.listCodespaces,createCodespace:j.createCodespace,domainHook:j.domainHook},personas:{personas:w.personas,personasLoading:w.personasLoading,createPersona:w.createPersona,updatePersona:w.updatePersona,deletePersona:w.deletePersona,domainHook:w.domainHook},schedules:{schedules:T.schedules,schedulesLoading:T.schedulesLoading,createSchedule:T.createSchedule,updateSchedule:T.updateSchedule,deleteSchedule:T.deleteSchedule,domainHook:T.domainHook},streams:{streams:O.streams,streamsLoading:O.streamsLoading,streamsLoadedOnce:O.streamsLoadedOnce,streamsLoadError:O.streamsLoadError,loadStreams:O.loadStreams,domainHook:O.domainHook},knowledge:C,plugins:{plugins:A.plugins,pluginsLoading:A.pluginsLoading,loadPlugins:A.loadPlugins,setPluginEnabled:A.setPluginEnabled},appDefaultPersonaId:t,setAppDefaultPersonaId:X,onboardingCompleted:o,completeOnboarding:H,usageCache:c,loadUsage:Q,refresh:L}}function kP({children:t}){const s=xP();return a.jsx(vh.Provider,{value:s,children:t})}function SP(t,s){const o=y.useRef(null);y.useEffect(()=>{const r=o.current;if(o.current=t,r===null)return;const c=new Map;for(const u of r)c.set(u.id,u);const d=new Set;for(const u of t){d.add(u.id);const p=c.get(u.id);if(p&&p.status!==u.status&&u.status!=="sleeping"){if(u.status==="connecting"){s("Provisioning environment…","info");continue}u.status==="connected"?s("Environment connected","success"):u.status==="error"?s("Environment provision failed","error"):u.status==="disconnected"&&(p.status==="connected"?s("Environment disconnected","warning"):s("Environment stopped","info"))}}for(const u of r)d.has(u.id)||s("Environment removed","info")},[t,s])}function jP(t,s,o){const r=y.useRef(t);y.useEffect(()=>{t&&t!==r.current&&(o(t,"error"),s()),r.current=t},[t,s,o])}const TP={working:{message:"Task is now running",variant:"info"},paused:{message:"Task paused",variant:"warning"},complete:{message:"Task complete",variant:"success"},failed:{message:"Task failed to complete",variant:"error"}};function wP(t){return TP[t]}function NP(t,s){if(t===void 0)return[];const o=[],r=new Map;for(const d of t)r.set(d.id,d);const c=new Set;for(const d of s){c.add(d.id);const u=r.get(d.id);if(!u||u.status===d.status)continue;const p=wP(d.status);p&&o.push(p)}for(const d of t)c.has(d.id)||o.push({message:"Task deleted",variant:"info"});return o}function CP(t,s){const o=y.useRef(void 0);y.useEffect(()=>{const r=o.current;o.current=t;const c=NP(r,t);for(const d of c)s(d.message,d.variant)},[t,s])}const EP="_dashboard_16pzm_1",AP="_kpiStrip_16pzm_11",DP="_kpiCard_16pzm_23",RP="_kpiValue_16pzm_68",MP="_kpiLabel_16pzm_76",IP="_bodyGrid_16pzm_84",OP="_section_16pzm_96",BP="_sectionHeader_16pzm_109",LP="_sectionIcon_16pzm_118",zP="_sectionTitle_16pzm_123",$P="_sectionCount_16pzm_131",PP="_sectionBody_16pzm_138",UP="_emptyHint_16pzm_143",HP="_sessionRow_16pzm_150",VP="_sessionPrompt_16pzm_177",qP="_sessionEnv_16pzm_186",GP="_sessionRuntime_16pzm_192",FP="_sessionStatus_16pzm_198",ZP="_statusDot_16pzm_207",KP="_attentionRow_16pzm_233",YP="_attentionTitle_16pzm_259",JP="_attentionMeta_16pzm_267",WP="_reasonBadge_16pzm_274",XP="_bottomGrid_16pzm_301",QP="_envRow_16pzm_312",e9="_envName_16pzm_323",t9="_envStatusBadge_16pzm_333",n9="_workspaceRow_16pzm_369",s9="_workspaceTop_16pzm_395",a9="_workspaceName_16pzm_401",i9="_workspaceCounts_16pzm_407",o9="_progressBar_16pzm_415",r9="_progressFill_16pzm_422",pe={dashboard:EP,kpiStrip:AP,kpiCard:DP,kpiValue:RP,kpiLabel:MP,bodyGrid:IP,section:OP,sectionHeader:BP,sectionIcon:LP,sectionTitle:zP,sectionCount:$P,sectionBody:PP,emptyHint:UP,sessionRow:HP,sessionPrompt:VP,sessionEnv:qP,sessionRuntime:GP,sessionStatus:FP,statusDot:ZP,attentionRow:KP,attentionTitle:YP,attentionMeta:JP,reasonBadge:WP,bottomGrid:XP,envRow:QP,envName:e9,envStatusBadge:t9,workspaceRow:n9,workspaceTop:s9,workspaceName:a9,workspaceCounts:i9,progressBar:o9,progressFill:r9};function l9(){return a.jsxs("div",{className:pe.dashboard,"aria-hidden":"true",children:[a.jsx("div",{className:pe.kpiStrip,children:Array.from({length:4},(t,s)=>a.jsxs("div",{className:pe.kpiCard,children:[a.jsx(Ne,{width:"3rem",height:"2rem"}),a.jsx(Ne,{width:"80%",height:"0.75rem"})]},s))}),a.jsxs("div",{className:pe.bodyGrid,children:[a.jsxs("div",{className:pe.section,children:[a.jsxs("div",{className:pe.sectionHeader,children:[a.jsx(Ne,{width:"1rem",height:"1rem",variant:"circular"}),a.jsx(Ne,{width:"8rem",height:"0.75rem"}),a.jsx("span",{className:pe.sectionCount,children:a.jsx(Ne,{width:"1rem",height:"0.75rem"})})]}),a.jsx("div",{className:pe.sectionBody,children:Array.from({length:3},(t,s)=>a.jsxs("div",{className:pe.sessionRow,style:{cursor:"default"},children:[a.jsx(Ne,{width:"60%",height:"0.875rem"}),a.jsx(Ne,{width:"4rem",height:"0.75rem"}),a.jsx(Ne,{width:"3rem",height:"0.75rem"}),a.jsx(Ne,{width:"3rem",height:"0.75rem"})]},s))})]}),a.jsxs("div",{className:pe.section,children:[a.jsxs("div",{className:pe.sectionHeader,children:[a.jsx(Ne,{width:"1rem",height:"1rem",variant:"circular"}),a.jsx(Ne,{width:"8rem",height:"0.75rem"}),a.jsx("span",{className:pe.sectionCount,children:a.jsx(Ne,{width:"1rem",height:"0.75rem"})})]}),a.jsx("div",{className:pe.sectionBody,children:Array.from({length:2},(t,s)=>a.jsxs("div",{className:pe.attentionRow,style:{cursor:"default"},children:[a.jsxs("div",{className:pe.attentionTitle,children:[a.jsx(Ne,{width:"3rem",height:"0.875rem",borderRadius:"var(--radius-sm)"}),a.jsx(Ne,{width:"70%",height:"0.875rem"})]}),a.jsx("div",{className:pe.attentionMeta,children:a.jsx(Ne,{width:"5rem",height:"0.625rem"})})]},s))})]})]}),a.jsxs("div",{className:pe.bottomGrid,children:[a.jsxs("div",{className:pe.section,children:[a.jsxs("div",{className:pe.sectionHeader,children:[a.jsx(Ne,{width:"1rem",height:"1rem",variant:"circular"}),a.jsx(Ne,{width:"9rem",height:"0.75rem"}),a.jsx("span",{className:pe.sectionCount,children:a.jsx(Ne,{width:"1rem",height:"0.75rem"})})]}),a.jsx("div",{className:pe.sectionBody,children:Array.from({length:2},(t,s)=>a.jsxs("div",{className:pe.envRow,children:[a.jsx(Ne,{width:"60%",height:"0.875rem"}),a.jsx(Ne,{width:"4rem",height:"0.875rem",borderRadius:"var(--radius-sm)"})]},s))})]}),a.jsxs("div",{className:pe.section,children:[a.jsxs("div",{className:pe.sectionHeader,children:[a.jsx(Ne,{width:"1rem",height:"1rem",variant:"circular"}),a.jsx(Ne,{width:"6rem",height:"0.75rem"}),a.jsx("span",{className:pe.sectionCount,children:a.jsx(Ne,{width:"1rem",height:"0.75rem"})})]}),a.jsx("div",{className:pe.sectionBody,children:Array.from({length:2},(t,s)=>a.jsxs("div",{className:pe.workspaceRow,style:{cursor:"default"},children:[a.jsxs("div",{className:pe.workspaceTop,children:[a.jsx(Ne,{width:"50%",height:"0.875rem"}),a.jsx(Ne,{width:"2rem",height:"0.75rem"})]}),a.jsx("div",{className:pe.progressBar,children:a.jsx("div",{className:pe.progressFill,style:{width:"0%"}})})]},s))})]})]})]})}const c9={hidden:{opacity:0,y:12},visible:t=>({opacity:1,y:0,transition:{delay:t*.06,duration:.3,ease:"easeOut"}})},nd={hidden:{opacity:0,y:16},visible:t=>({opacity:1,y:0,transition:{delay:.15+t*.08,duration:.35,ease:"easeOut"}})};function d9(t,s,o,r){const c=[`${t} of ${s} tasks completed`];return o>0&&c.push(`${o} in progress`),r>0&&c.push(`${r} failed`),c.join(", ")}function sd({value:t,label:s,accent:o,index:r,testId:c}){return a.jsxs(Nt.div,{className:pe.kpiCard,"data-accent":o,"data-testid":c,variants:c9,initial:"hidden",animate:"visible",custom:r,children:[a.jsx("span",{className:pe.kpiValue,children:t}),a.jsx("span",{className:pe.kpiLabel,children:s})]})}function u9(){const{workspaces:{workspaces:t,workspacesLoading:s},tasks:{tasks:o,tasksLoading:r,loadTasks:c},sessions:{sessions:d,sessionsLoading:u},environments:{environments:p,environmentsLoading:m}}=rt(),g=ct(),v=y.useRef(new Set);y.useEffect(()=>{for(const w of t)v.current.has(w.id)||(v.current.add(w.id),c(w.id).catch(()=>{}))},[t,c]);const _=y.useMemo(()=>C$(d,o,p),[d,o,p]),b=y.useMemo(()=>A$(d,p),[d,p]),x=y.useMemo(()=>E$(o,t),[o,t]),S=y.useMemo(()=>D$(t,o),[t,o,p]);return d.length===0&&o.length===0&&p.length===0&&t.length===0&&(u||r||m||s)?a.jsx(l9,{}):a.jsxs("div",{className:pe.dashboard,"data-testid":"dashboard",children:[a.jsxs("div",{className:pe.kpiStrip,"data-testid":"dashboard-kpi-strip",children:[a.jsx(sd,{value:_.activeSessions,label:"Active Sessions",accent:"green",index:0,testId:"kpi-active-sessions"}),a.jsx(sd,{value:_.blockedTasks,label:"Blocked Tasks",accent:"yellow",index:1,testId:"kpi-blocked-tasks"}),a.jsx(sd,{value:_.attentionTasks,label:"Needs Attention",accent:"red",index:2,testId:"kpi-attention-tasks"}),a.jsx(sd,{value:_.unhealthyEnvironments,label:"Unhealthy Envs",accent:"blue",index:3,testId:"kpi-unhealthy-envs"})]}),a.jsxs("div",{className:pe.bodyGrid,children:[a.jsxs(Nt.div,{className:pe.section,variants:nd,initial:"hidden",animate:"visible",custom:0,"data-testid":"dashboard-active-sessions",children:[a.jsxs("div",{className:pe.sectionHeader,children:[a.jsx("span",{className:pe.sectionIcon,"aria-hidden":"true",children:"●"}),a.jsx("span",{className:pe.sectionTitle,children:"Active Sessions"}),a.jsx("span",{className:pe.sectionCount,children:b.length})]}),a.jsx("div",{className:pe.sectionBody,children:b.length===0?a.jsx("div",{className:pe.emptyHint,children:"No active sessions"}):b.map(({session:w,environmentName:T})=>a.jsxs("button",{type:"button",className:pe.sessionRow,onClick:()=>g(Ld(w.id)),"data-testid":"session-row",children:[a.jsx("span",{className:pe.sessionPrompt,title:w.prompt,children:w.prompt||"—"}),a.jsx("span",{className:pe.sessionEnv,children:T}),a.jsx("span",{className:pe.sessionRuntime,children:w.runtime}),a.jsxs("span",{className:pe.sessionStatus,children:[a.jsx("span",{className:pe.statusDot,"data-status":w.status}),w.status]})]},w.id))})]}),a.jsxs(Nt.div,{className:pe.section,variants:nd,initial:"hidden",animate:"visible",custom:1,"data-testid":"dashboard-needs-attention",children:[a.jsxs("div",{className:pe.sectionHeader,children:[a.jsx("span",{className:pe.sectionIcon,"aria-hidden":"true",children:"⚑"}),a.jsx("span",{className:pe.sectionTitle,children:"Needs Attention"}),a.jsx("span",{className:pe.sectionCount,children:x.length})]}),a.jsx("div",{className:pe.sectionBody,children:x.length===0?a.jsx("div",{className:pe.emptyHint,children:"All clear"}):x.map(({task:w,reason:T,workspaceName:C})=>a.jsxs("button",{type:"button",className:pe.attentionRow,onClick:()=>g($n(w.id)),"data-testid":"attention-row",children:[a.jsxs("div",{className:pe.attentionTitle,children:[a.jsx("span",{className:pe.reasonBadge,"data-reason":T,children:T}),w.title]}),a.jsx("div",{className:pe.attentionMeta,children:a.jsx("span",{children:C})})]},w.id))})]})]}),a.jsxs("div",{className:pe.bottomGrid,children:[a.jsxs(Nt.div,{className:pe.section,variants:nd,initial:"hidden",animate:"visible",custom:2,"data-testid":"dashboard-env-health",children:[a.jsxs("div",{className:pe.sectionHeader,children:[a.jsx("span",{className:pe.sectionIcon,"aria-hidden":"true",children:"◈"}),a.jsx("span",{className:pe.sectionTitle,children:"Environment Health"}),a.jsx("span",{className:pe.sectionCount,children:p.length})]}),a.jsx("div",{className:pe.sectionBody,children:p.length===0?a.jsx("div",{className:pe.emptyHint,children:"No environments configured"}):p.map(w=>a.jsxs("div",{className:pe.envRow,"data-testid":"dashboard-env-row",children:[a.jsx("span",{className:pe.envName,children:w.displayName}),a.jsx("span",{className:pe.envStatusBadge,"data-status":w.status,children:w.status})]},w.id))})]}),a.jsxs(Nt.div,{className:pe.section,variants:nd,initial:"hidden",animate:"visible",custom:3,"data-testid":"dashboard-workspace-snapshot",children:[a.jsxs("div",{className:pe.sectionHeader,children:[a.jsx("span",{className:pe.sectionIcon,"aria-hidden":"true",children:"▦"}),a.jsx("span",{className:pe.sectionTitle,children:"Workspaces"}),a.jsx("span",{className:pe.sectionCount,children:t.length})]}),a.jsx("div",{className:pe.sectionBody,children:S.length===0?a.jsx("div",{className:pe.emptyHint,children:"No workspaces yet"}):S.map(({workspace:w,totalTasks:T,completedTasks:C,workingTasks:D,failedTasks:O})=>{const A=T>0?Math.round(C/T*100):0;return a.jsxs("button",{type:"button",className:pe.workspaceRow,onClick:()=>g(Ri(w.id,w.linkedEnvironmentIds[0])),"data-testid":"workspace-row",children:[a.jsxs("div",{className:pe.workspaceTop,children:[a.jsx("span",{className:pe.workspaceName,children:w.name}),a.jsxs("span",{className:pe.workspaceCounts,"aria-label":d9(C,T,D,O),children:[C,"/",T,D>0&&a.jsxs("span",{style:{color:"var(--accent-green)"},"aria-hidden":"true",children:["▸",D]}),O>0&&a.jsxs("span",{style:{color:"var(--accent-red)"},"aria-hidden":"true",children:["✗",O]})]})]}),T>0&&a.jsx("div",{className:pe.progressBar,children:a.jsx("div",{className:pe.progressFill,style:{width:`${A}%`}})})]},w.id)})})]})]})]})}const f9="_panelContainer_1udy7_1",p9="_emptyState_1udy7_8",m9="_workspaceSummary_1udy7_17",h9="_workspaceSummaryTitle_1udy7_28",g9="_workspaceSummarySubtitle_1udy7_32",v9="_header_1udy7_36",y9="_headerInfo_1udy7_71",b9="_headerTitle_1udy7_106",_9="_taskStatusBadge_1udy7_128",x9="_taskBranch_1udy7_137",k9="_taskBlockedBadge_1udy7_143",S9="_tabBar_1udy7_277",j9="_tab_1udy7_277",T9="_active_1udy7_303",w9="_eventScroll_1udy7_308",N9="_tabContent_1udy7_314",C9="_noContext_1udy7_319",E9="_overviewContent_1udy7_325",A9="_overviewDashboard_1udy7_334",D9="_overviewHero_1udy7_340",R9="_overviewSection_1udy7_347",M9="_overviewLabel_1udy7_353",I9="_envRow_1udy7_360",O9="_timeline_1udy7_366",B9="_timelineRow_1udy7_372",L9="_waitingMessage_1udy7_379",z9="_errorMessage_1udy7_383",$9="_emptyCta_1udy7_387",P9="_ctaTitle_1udy7_399",U9="_ctaDescription_1udy7_405",H9="_ctaButton_1udy7_412",V9="_workspaceHeader_1udy7_533",q9="_workspaceName_1udy7_558",G9="_workspaceMeta_1udy7_571",F9="_metaRow_1udy7_579",Z9="_metaLabel_1udy7_592",K9="_metaValue_1udy7_607",Y9="_archiveButton_1udy7_617",J9="_repoLink_1udy7_647",W9="_metaToggle_1udy7_657",X9="_metaToggleArrow_1udy7_678",Q9="_metaToggleArrowOpen_1udy7_683",eU="_progressBarContainer_1udy7_687",tU="_progressBar_1udy7_687",nU="_progressFill_1udy7_703",sU="_progressLabel_1udy7_710",aU="_metaTimestamps_1udy7_717",iU="_metaTimestamp_1udy7_717",oU="_metaPlaceholder_1udy7_739",rU="_linkedEnvList_1udy7_744",lU="_linkedEnvChip_1udy7_750",cU="_chipDismiss_1udy7_762",dU="_linkError_1udy7_777",uU="_linkEnvSelect_1udy7_782",Y={panelContainer:f9,emptyState:p9,workspaceSummary:m9,workspaceSummaryTitle:h9,workspaceSummarySubtitle:g9,header:v9,headerInfo:y9,headerTitle:b9,taskStatusBadge:_9,taskBranch:x9,taskBlockedBadge:k9,tabBar:S9,tab:j9,active:T9,eventScroll:w9,tabContent:N9,noContext:C9,overviewContent:E9,overviewDashboard:A9,overviewHero:D9,overviewSection:R9,overviewLabel:M9,envRow:I9,timeline:O9,timelineRow:B9,waitingMessage:L9,errorMessage:z9,emptyCta:$9,ctaTitle:P9,ctaDescription:U9,ctaButton:H9,workspaceHeader:V9,workspaceName:q9,workspaceMeta:G9,metaRow:F9,metaLabel:Z9,metaValue:K9,archiveButton:Y9,repoLink:J9,metaToggle:W9,metaToggleArrow:X9,metaToggleArrowOpen:Q9,progressBarContainer:eU,progressBar:tU,progressFill:nU,progressLabel:sU,metaTimestamps:aU,metaTimestamp:iU,metaPlaceholder:oU,linkedEnvList:rU,linkedEnvChip:lU,chipDismiss:cU,linkError:dU,linkEnvSelect:uU};function fU(){return a.jsx("div",{className:Y.emptyState,children:"Select a task or click + to create one"})}function pU(){return a.jsx("div",{className:Y.emptyState,children:"Select an environment to manage its workspaces, or add a new one."})}function mU(){const{workspaces:{workspaces:t},environments:{environments:s}}=rt(),o=ct(),r=s.length>0;return t.length>0?a.jsx(u9,{}):a.jsxs("div",{className:Y.emptyCta,"data-testid":"welcome-cta",children:[a.jsx("div",{className:Y.ctaTitle,children:"Welcome to Grackle"}),a.jsx("div",{className:Y.ctaDescription,children:"Organize your work into workspaces and let agents tackle the tasks."}),a.jsx("button",{className:Y.ctaButton,onClick:()=>o(ax),disabled:!r,"data-testid":"welcome-create-button",children:"Create Your First Workspace"}),!r&&a.jsx("div",{className:Y.ctaDescription,children:"Add an environment first before creating a workspace."})]})}const hU="_panelContainer_1rih4_1",gU="_chatHeader_1rih4_9",vU="_chatHeaderInfo_1rih4_38",yU="_chatHeaderActions_1rih4_44",bU="_detailButton_1rih4_50",_U="_emptyState_1rih4_64",xU="_emptyTitle_1rih4_76",kU="_emptyDescription_1rih4_82",SU="_emptyHint_1rih4_88",Kt={panelContainer:hU,chatHeader:gU,chatHeaderInfo:vU,chatHeaderActions:yU,detailButton:bU,emptyState:_U,emptyTitle:xU,emptyDescription:kU,emptyHint:SU};function Fp(){return a.jsx("div",{className:Kt.panelContainer,"aria-hidden":"true",children:a.jsxs("div",{style:{flex:1,overflow:"hidden",padding:"var(--space-md)",display:"flex",flexDirection:"column",gap:"var(--space-md)"},children:[a.jsx(Ne,{width:"65%",height:"2.5rem",borderRadius:"var(--radius-sm)"}),a.jsx(Ne,{width:"85%",height:"4rem",borderRadius:"var(--radius-sm)"}),a.jsx(Ne,{width:"45%",height:"2rem",borderRadius:"var(--radius-sm)"}),a.jsx(Ne,{width:"75%",height:"3rem",borderRadius:"var(--radius-sm)"}),a.jsx(Ne,{width:"55%",height:"2.5rem",borderRadius:"var(--radius-sm)"})]})})}function jU({hasLocalEnvironment:t}){return a.jsxs("div",{className:Kt.emptyState,"data-testid":"chat-empty-state",children:[a.jsx("div",{className:Kt.emptyTitle,children:"Welcome to Grackle"}),a.jsx("div",{className:Kt.emptyDescription,children:t?"Type a message below to start chatting with the System agent. It can help you plan work, create tasks, and coordinate agents.":"Add a local environment in Settings to start chatting."}),!t&&a.jsx("div",{className:Kt.emptyHint,children:"Go to Settings → Environments to add one."})]})}function TU({streamName:t}){return a.jsxs("div",{className:Kt.emptyState,"data-testid":"stream-no-session-state",children:[a.jsx("div",{className:Kt.emptyTitle,children:t}),a.jsx("div",{className:Kt.emptyDescription,children:"No active sessions on this stream."})]})}function wU(){return a.jsxs("div",{className:Kt.emptyState,"data-testid":"stream-not-found-state",children:[a.jsx("div",{className:Kt.emptyTitle,children:"Stream not found"}),a.jsxs("div",{className:Kt.emptyDescription,children:["This stream no longer exists or hasn't been created yet."," ",a.jsx(_l,{to:dl,children:"Back to System"})]})]})}function NU(){return a.jsxs("div",{className:Kt.emptyState,"data-testid":"stream-unavailable-state",children:[a.jsx("div",{className:Kt.emptyTitle,children:"Stream unavailable"}),a.jsxs("div",{className:Kt.emptyDescription,children:["The stream could not be loaded. It may have been deleted, or there may be a temporary network problem."," ",a.jsx(_l,{to:dl,children:"Back to System"})]})]})}function y_(){const{streamId:t}=Hn(),{tasks:{tasks:s,tasksLoading:o,startTask:r},sessions:{sessions:c,sessionsLoading:d,events:u,eventsDropped:p,taskSessions:m,loadTaskSessions:g,loadSessionEvents:v,kill:_,stopGraceful:b,sendInput:x,spawn:S},environments:{environments:j,provisionEnvironment:w},personas:{personas:T},streams:{streams:C,streamsLoading:D,streamsLoadedOnce:O,streamsLoadError:A}}=rt(),{showToast:I}=gn(),[$,B]=y.useState(!1),P=y.useRef(void 0),[X,H]=y.useState(),Q=s.find(be=>be.id===$r),he=t===void 0&&Q!=null&&Q.latestSessionId?c.find(be=>be.id===Q.latestSessionId)??(m[$r]??[]).find(be=>be.id===Q.latestSessionId):void 0;y.useEffect(()=>{t===void 0&&g($r).catch(()=>{})},[t,g]),y.useEffect(()=>{t===void 0&&(Q!=null&&Q.latestSessionId)&&g($r).catch(()=>{})},[t,Q==null?void 0:Q.latestSessionId,g]);const W=t!==void 0?C.find(be=>be.id===t):void 0,ie=y.useMemo(()=>!W||W.subscribers.length===0?void 0:(W.subscribers.find(_e=>_e.permission==="rw")??W.subscribers[0]).sessionId,[W]),L=ie!==void 0?c.find(be=>be.id===ie):void 0,E=t===void 0?he:L;y.useEffect(()=>{E&&E.id!==P.current&&(P.current=E.id,v(E.id).catch(()=>{}))},[E==null?void 0:E.id,v]),y.useEffect(()=>{P.current=void 0,B(!1)},[t]);const J=y.useMemo(()=>{if(!E)return[];const be=u.filter(fe=>fe.sessionId===E.id);return _h(bh(be))},[u,E==null?void 0:E.id]),me=j.find(be=>be.adapterType==="local"&&be.status==="connected"),q=E!==void 0&&E.status!=="stopped"&&E.status!=="suspended",de=(E==null?void 0:E.status)==="idle";y.useEffect(()=>{X&&E&&de&&(x(E.id,X).catch(()=>{I("Failed to send message","error")}),H(void 0))},[X,de,E==null?void 0:E.id,x,I]);const re=y.useCallback((be,fe,_e,ke)=>{ke&&H(ke),r(be,fe,_e).catch(()=>{})},[r]);if(t===void 0&&!Q&&(d||o))return a.jsx(Fp,{});if(t!==void 0&&!W&&(D||!O))return a.jsx(Fp,{});if(t!==void 0&&W&&d&&!E)return a.jsx(Fp,{});if(t!==void 0&&!W)return a.jsx("div",{className:Kt.panelContainer,"data-testid":"chat-page",children:a.jsx(al,{events:[],eventsDropped:0,emptyState:A?a.jsx(NU,{}):a.jsx(wU,{}),onShowToast:I})});const xe=t!==void 0&&W?W.name:void 0;return a.jsxs("div",{className:Kt.panelContainer,"data-testid":"chat-page",children:[q&&a.jsxs("div",{className:Kt.chatHeader,children:[a.jsxs("span",{className:Kt.chatHeaderInfo,children:[xe&&a.jsxs("strong",{children:[xe," — "]}),"Session: ",E.id.slice(0,8)," | ",E.runtime," | ",E.status]}),a.jsxs("div",{className:Kt.chatHeaderActions,children:[W&&a.jsx("button",{className:Kt.detailButton,onClick:()=>B(be=>!be),"aria-label":"Stream details","aria-expanded":$,"data-testid":"stream-detail-toggle",children:"Info"}),a.jsx(ox,{label:"Stop",onClick:()=>{b(E.id).catch(()=>{})},variant:"danger",size:"sm","data-testid":"stop-split-button",options:[{label:"Stop",description:"Graceful shutdown",onClick:()=>{b(E.id).catch(()=>{})}},{label:"Kill",description:"Force kill",onClick:()=>{_(E.id).catch(()=>{})}}]})]})]}),t!==void 0&&W&&!E&&!d&&a.jsx(al,{events:[],eventsDropped:0,emptyState:a.jsx(TU,{streamName:W.name}),onShowToast:I}),(t===void 0||E)&&a.jsx(al,{events:J,eventsDropped:p,emptyState:t===void 0?a.jsx(jU,{hasLocalEnvironment:!!me}):void 0,onShowToast:I}),t===void 0&&me&&q&&a.jsx(rl,{mode:"send",sessionId:E.id,environmentId:E.environmentId,personas:T,environments:j,onSendInput:(be,fe)=>{x(be,fe).catch(()=>{I("Failed to send message","error")})},onSpawn:(be,fe,_e)=>{S(be,fe,_e).catch(()=>{})},onStartTask:(be,fe,_e)=>{r(be,fe,_e).catch(()=>{})},onProvisionEnvironment:be=>{w(be).catch(()=>{})},onShowToast:I}),t===void 0&&me&&!q&&a.jsx(rl,{mode:"start",taskId:$r,environmentId:me.id,personas:T,environments:j,onSendInput:(be,fe)=>{x(be,fe).catch(()=>{I("Failed to send message","error")})},onSpawn:(be,fe,_e)=>{S(be,fe,_e).catch(()=>{})},onStartTask:re,onProvisionEnvironment:be=>{w(be).catch(()=>{})},onShowToast:I}),$&&W&&a.jsx(_z,{stream:W,onClose:()=>B(!1)})]})}function CU(){const t=x$(),[s]=Im(),o=s.get("env")??"",{sessions:{sendInput:r,spawn:c},tasks:{startTask:d},personas:{personas:u},environments:{environments:p,provisionEnvironment:m}}=rt(),{showToast:g}=gn();return a.jsxs("div",{className:Y.panelContainer,children:[a.jsx(xs,{segments:t}),a.jsx("div",{className:Y.emptyState,children:"Enter a prompt below to start a new session"}),a.jsx(rl,{mode:"spawn",environmentId:o,showPersonaSelect:!0,personas:u,environments:p,onSendInput:(v,_)=>{r(v,_).catch(()=>{g("Failed to send message","error")})},onSpawn:(v,_,b)=>{c(v,_,b).catch(()=>{})},onStartTask:(v,_,b)=>{d(v,_,b).catch(()=>{})},onProvisionEnvironment:v=>{m(v).catch(()=>{})},onShowToast:g})]})}function EU(){return a.jsxs("div",{className:Y.panelContainer,"aria-hidden":"true",children:[a.jsxs("div",{className:Y.header,children:[a.jsx("span",{children:a.jsx(Ne,{width:"10rem",height:"0.875rem"})}),a.jsx("span",{className:Y.headerInfo,children:a.jsx(Ne,{width:"16rem",height:"0.875rem"})})]}),a.jsx("div",{className:Y.eventScroll,children:a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"var(--space-md)"},children:[a.jsx(Ne,{width:"70%",height:"2.5rem",borderRadius:"var(--radius-sm)"}),a.jsx(Ne,{width:"90%",height:"4rem",borderRadius:"var(--radius-sm)"}),a.jsx(Ne,{width:"50%",height:"2rem",borderRadius:"var(--radius-sm)"}),a.jsx(Ne,{width:"80%",height:"3.5rem",borderRadius:"var(--radius-sm)"}),a.jsx(Ne,{width:"60%",height:"2.5rem",borderRadius:"var(--radius-sm)"})]})})]})}function AU({sessionId:t,session:s,isActive:o,onStop:r,onKill:c}){return a.jsxs("div",{className:Y.header,children:[a.jsxs("span",{children:["Session: ",t.slice(0,8),s&&` | ${s.runtime} | ${s.endReason||s.status}`,s!=null&&s.inputTokens||s!=null&&s.outputTokens||s!=null&&s.costMillicents?` | ${zo((s.inputTokens??0)+(s.outputTokens??0))} tokens · ${Ms(s.costMillicents??0)}`:""]}),a.jsxs("span",{className:Y.headerInfo,children:[s&&a.jsx("span",{children:s.prompt.length>60?s.prompt.slice(0,60)+"...":s.prompt}),o&&a.jsx(ox,{label:"Stop",onClick:r,variant:"danger",size:"sm","data-testid":"stop-split-button",options:[{label:"Stop",description:"Graceful shutdown",onClick:r},{label:"Kill",description:"Force kill",onClick:c}]})]})]})}function DU({session:t}){const s=t&&(t.status==="stopped"||t.status==="suspended"),o=s?`Session ${t.endReason||t.status} with no events recorded.`:"Waiting for events...";return a.jsx("div",{className:s?Y.errorMessage:Y.waitingMessage,children:o})}function RU(){const{sessionId:t}=Hn(),{sessions:{events:s,eventsDropped:o,sessions:r,sessionsLoading:c,kill:d,stopGraceful:u,loadSessionEvents:p,sendInput:m,spawn:g},tasks:{startTask:v},personas:{personas:_},environments:{environments:b,provisionEnvironment:x}}=rt(),{showToast:S}=gn(),j=y.useRef(void 0),w=k$(t),T=r.find(O=>O.id===t)??void 0,C=y.useMemo(()=>{const O=t?s.filter(A=>A.sessionId===t):[];return _h(bh(O))},[s,t]);if(y.useEffect(()=>{t&&t!==j.current&&(j.current=t,p(t).catch(()=>{}))},[t,p]),!T&&c)return a.jsx(EU,{});if(!t)return a.jsx("div",{className:Y.emptyState,children:"No session selected"});const D=(T==null?void 0:T.status)==="running"||(T==null?void 0:T.status)==="idle";return a.jsxs("div",{className:Y.panelContainer,children:[a.jsx(xs,{segments:w}),a.jsx(AU,{sessionId:t,session:T,isActive:D,onStop:()=>{u(t).catch(()=>{})},onKill:()=>{d(t).catch(()=>{})}}),a.jsx(al,{events:C,eventsDropped:o,emptyState:a.jsx(DU,{session:T}),onShowToast:S,sessions:r,currentSessionId:t,environments:b,personas:_,onForward:(O,A)=>m(O,A)}),D&&a.jsx(rl,{mode:"send",sessionId:t,environmentId:T.environmentId,personas:_,environments:b,onSendInput:(O,A)=>{m(O,A).catch(()=>{S("Failed to send message","error")})},onSpawn:(O,A,I)=>{g(O,A,I).catch(()=>{})},onStartTask:(O,A,I)=>{v(O,A,I).catch(()=>{})},onProvisionEnvironment:O=>{x(O).catch(()=>{})},onShowToast:S})]})}function MU(t){if(!t)return!1;const s=t.tagName;return!!(s==="INPUT"||s==="TEXTAREA"||s==="SELECT"||t.isContentEditable)}function la(t,s){const o=y.useRef(s);o.current=s;const{key:r,ctrl:c=!1,shift:d=!1,suppressInInputs:u=!0,enabled:p=!0}=t;y.useEffect(()=>{if(!p)return;const m=g=>{if(u&&MU(document.activeElement??void 0))return;const v=g.ctrlKey||g.metaKey;c===v&&(d&&!g.shiftKey||g.key===r&&o.current())};return document.addEventListener("keydown",m),()=>{document.removeEventListener("keydown",m)}},[r,c,d,u,p])}function IU(){return a.jsxs("div",{className:Y.panelContainer,"aria-hidden":"true",children:[a.jsx("div",{className:Y.workspaceHeader,children:a.jsx("span",{className:Y.workspaceName,children:a.jsx(Ne,{width:"12rem",height:"1.25rem"})})}),a.jsx("div",{className:Y.metaToggle,style:{cursor:"default"},children:a.jsx(Ne,{width:"4rem",height:"0.625rem"})}),a.jsxs("div",{className:Y.progressBarContainer,children:[a.jsx("div",{className:Y.progressBar,children:a.jsx("div",{className:Y.progressFill,style:{width:"0%"}})}),a.jsx(Ne,{width:"2rem",height:"0.625rem"})]}),a.jsxs("div",{className:Y.tabBar,role:"tablist","aria-label":"Workspace view",children:[a.jsx("span",{className:`${Y.tab} ${Y.active}`,children:"Graph"}),a.jsx("span",{className:Y.tab,children:"Board"}),a.jsx("span",{className:Y.tab,children:"Tasks"})]}),a.jsx("div",{className:Y.overviewContent,children:Array.from({length:3},(t,s)=>a.jsx(jd,{lines:2},s))})]})}function b_(t){if(!t)return"";const s=new Date(t);if(isNaN(s.getTime()))return"";const r=Date.now()-s.getTime();if(r<0)return"just now";const c=Math.floor(r/6e4);if(c<1)return"just now";if(c<60)return`${c}m ago`;const d=Math.floor(c/60);if(d<24)return`${d}h ago`;const u=Math.floor(d/24);return u<30?`${u}d ago`:s.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}const Zp=100;function OU(t){try{const s=new URL(t);return s.protocol!=="http:"&&s.protocol!=="https:"?void 0:s.toString()}catch{return}}function BU(){const{workspaceId:t,environmentId:s}=Hn(),o=ct(),{tasks:{tasks:r},environments:{environments:c},workspaces:{workspaces:d,workspacesLoading:u,archiveWorkspace:p,updateWorkspace:m,linkEnvironment:g,unlinkEnvironment:v,linkOperationError:_,clearLinkOperationError:b},personas:{personas:x},sessions:{sessions:S},usageCache:j,loadUsage:w}=rt(),{resolvedThemeId:T}=ak(),[C,D]=y.useState("tasks"),[O,A]=y.useState(!1),[I,$]=y.useState(null),[B,P]=y.useState(!1),X=y.useRef(void 0),H=d.find(q=>q.id===t),Q=s??(H==null?void 0:H.linkedEnvironmentIds[0])??"",he=S$(t,Q,d,c);la({key:"1"},()=>D("graph")),la({key:"2"},()=>D("board")),la({key:"3"},()=>D("tasks")),y.useEffect(()=>{const q=X.current;X.current=t,!(q===void 0||q===t)&&I!==null&&$(null)},[t,I]);const W=S.reduce((q,de)=>q+(de.costMillicents??0),0);y.useEffect(()=>{t&&w("workspace",t).catch(()=>{})},[t,w,W]);const ie=t?j[`workspace:${t}`]:void 0,L=r.filter(q=>q.workspaceId===t),E=L.filter(q=>q.status==="complete").length,J=L.length,me=J>0?Math.round(E/J*100):0;return!H&&u?a.jsx(IU,{}):a.jsxs("div",{className:Y.panelContainer,children:[a.jsx(xs,{segments:he}),a.jsxs("div",{className:Y.workspaceHeader,children:[a.jsx("span",{className:Y.workspaceName,"data-testid":"workspace-name",children:a.jsx(Zt,{value:(H==null?void 0:H.name)||"",onSave:q=>{H&&m(H.id,{name:q}).catch(()=>{})},validate:q=>{const de=q.trim();if(!de)return"Name is required";if(de.length>Zp)return`Max ${Zp} characters`},maxLength:Zp,fieldId:"name",activeFieldId:I,onActivate:$,ariaLabel:"Workspace name",renderDisplay:q=>q||t||void 0,"data-testid":"edit-name"})}),a.jsx("button",{className:Y.archiveButton,onClick:()=>A(!0),title:"Archive workspace","data-testid":"archive-workspace-button",children:"Archive"})]}),a.jsxs("button",{className:Y.metaToggle,onClick:()=>P(!B),"aria-expanded":!B,"aria-controls":"workspace-meta-panel","data-testid":"meta-toggle",children:[a.jsx("span",{className:`${Y.metaToggleArrow} ${B?"":Y.metaToggleArrowOpen}`,children:"▶"}),"Details"]}),!B&&a.jsxs("div",{className:Y.workspaceMeta,"data-testid":"workspace-meta",id:"workspace-meta-panel",children:[a.jsxs("div",{className:Y.metaRow,children:[a.jsx("span",{className:Y.metaLabel,children:"Description"}),a.jsx("div",{className:Y.metaValue,children:a.jsx(ym,{value:(H==null?void 0:H.description)||"",onSave:q=>{H&&m(H.id,{description:q}).catch(()=>{})},fieldId:"description",activeFieldId:I,onActivate:$,renderDisplay:q=>q?a.jsx("span",{className:Y.overviewMarkdown,children:a.jsx(Ad,{remarkPlugins:[Dd],children:q})}):void 0,placeholder:"No description",ariaLabel:"Workspace description","data-testid":"edit-description"})})]}),a.jsxs("div",{className:Y.metaRow,children:[a.jsx("span",{className:Y.metaLabel,children:"Repository"}),a.jsx("div",{className:Y.metaValue,children:a.jsx(Zt,{value:(H==null?void 0:H.repoUrl)||"",onSave:q=>{H&&m(H.id,{repoUrl:q}).catch(()=>{})},validate:q=>{const de=q.trim();if(de&&!/^https?:\/\/.+/.test(de))return"Must be a valid http(s) URL"},fieldId:"repoUrl",activeFieldId:I,onActivate:$,renderDisplay:q=>{const de=OU(q);return de?a.jsx("a",{className:Y.repoLink,href:de,target:"_blank",rel:"noopener noreferrer",onClick:re=>re.stopPropagation(),children:q}):q?a.jsx("span",{children:q}):void 0},placeholder:"No repository",ariaLabel:"Workspace repository URL","data-testid":"edit-repo"})})]}),a.jsxs("div",{className:Y.metaRow,children:[a.jsx("span",{className:Y.metaLabel,children:"Environments"}),a.jsx("div",{className:Y.metaValue,"data-testid":"linked-environments",children:H?a.jsxs("span",{className:Y.linkedEnvList,children:[(()=>{const q=[...new Set(H.linkedEnvironmentIds)];return q.length===0?a.jsx("span",{className:Y.metaPlaceholder,children:"None"}):q.map(de=>{const re=c.find(xe=>xe.id===de);return a.jsxs("span",{className:Y.linkedEnvChip,"data-testid":`linked-env-${de}`,children:[(re==null?void 0:re.displayName)||de,a.jsx("button",{className:Y.chipDismiss,onClick:()=>{v(H.id,de).catch(()=>{})},title:`Unlink ${(re==null?void 0:re.displayName)||de}`,"aria-label":`Unlink ${(re==null?void 0:re.displayName)||de}`,"data-testid":`unlink-env-${de}`,disabled:q.length<=1,children:"x"})]},de)})})(),(()=>{const q=new Set(H.linkedEnvironmentIds),de=c.filter(re=>!q.has(re.id));return de.length===0?null:a.jsxs("select",{className:Y.linkEnvSelect,value:"",onChange:re=>{re.target.value&&g(H.id,re.target.value).catch(()=>{})},"aria-label":"Link environment","data-testid":"link-env-select",children:[a.jsx("option",{value:"",children:"+ Link"}),de.map(re=>a.jsx("option",{value:re.id,children:re.displayName||re.id},re.id))]})})(),_&&a.jsxs("span",{className:Y.linkError,"data-testid":"link-operation-error",role:"alert",children:[_,a.jsx("button",{className:Y.chipDismiss,onClick:b,"aria-label":"Dismiss error","data-testid":"dismiss-link-error",children:"x"})]})]}):a.jsx("span",{className:Y.metaPlaceholder,children:"None"})})]}),a.jsxs("div",{className:Y.metaRow,children:[a.jsx("span",{className:Y.metaLabel,children:"Persona"}),a.jsx("div",{className:Y.metaValue,children:a.jsx(Td,{value:(H==null?void 0:H.defaultPersonaId)||"",onSave:q=>{H&&m(H.id,{defaultPersonaId:q}).catch(()=>{})},options:[{value:"",label:"(Inherit)"},...x.map(q=>({value:q.id,label:q.name}))],fieldId:"defaultPersonaId",activeFieldId:I,onActivate:$,renderDisplay:q=>{const de=x.find(re=>re.id===q);if(de)return a.jsx("span",{children:de.name})},placeholder:(H==null?void 0:H.defaultPersonaId)||"(Inherit)",ariaLabel:"Workspace default persona","data-testid":"edit-persona"})})]}),a.jsxs("div",{className:Y.metaRow,children:[a.jsx("span",{className:Y.metaLabel,children:"Worktrees"}),a.jsx("div",{className:Y.metaValue,children:a.jsx(RI,{checked:(H==null?void 0:H.useWorktrees)??!0,onChange:q=>{H&&m(H.id,{useWorktrees:q}).catch(()=>{})},label:"Enable worktree isolation","data-testid":"worktree-toggle"})})]}),a.jsxs("div",{className:Y.metaRow,children:[a.jsx("span",{className:Y.metaLabel,children:"Working Dir"}),a.jsx("div",{className:Y.metaValue,children:a.jsx(Zt,{value:(H==null?void 0:H.workingDirectory)||"",onSave:q=>{H&&m(H.id,{workingDirectory:q}).catch(()=>{})},fieldId:"workingDirectory",activeFieldId:I,onActivate:$,placeholder:"Default (server default)",ariaLabel:"Working directory","data-testid":"edit-working-directory"})})]}),H&&a.jsxs("div",{className:Y.metaTimestamps,children:[a.jsxs("span",{className:Y.metaTimestamp,children:["Created ",b_(H.createdAt)]}),H.updatedAt&&H.updatedAt!==H.createdAt&&a.jsxs("span",{className:Y.metaTimestamp,children:["· Updated ",b_(H.updatedAt)]})]})]}),J>0&&a.jsxs("div",{className:Y.progressBarContainer,"data-testid":"progress-bar",children:[a.jsx("div",{className:Y.progressBar,children:a.jsx("div",{className:Y.progressFill,style:{width:`${me}%`}})}),a.jsxs("span",{className:Y.progressLabel,children:[E,"/",J]})]}),ie&&ie.costMillicents>0&&a.jsx("div",{className:Y.progressBarContainer,children:a.jsxs("span",{className:Y.progressLabel,children:["Usage: ",Ms(ie.costMillicents)," (",ie.sessionCount," session",ie.sessionCount!==1?"s":"",")"]})}),H&&(H.tokenBudget>0||H.costBudgetMillicents>0)&&a.jsx("div",{className:Y.progressBarContainer,children:a.jsxs("span",{className:Y.progressLabel,children:["Budget:"," ",H.tokenBudget>0&&a.jsxs(a.Fragment,{children:["Tokens: ",zo(((ie==null?void 0:ie.inputTokens)??0)+((ie==null?void 0:ie.outputTokens)??0))," / ",zo(H.tokenBudget)]}),H.tokenBudget>0&&H.costBudgetMillicents>0&&" | ",H.costBudgetMillicents>0&&a.jsxs(a.Fragment,{children:["Cost: ",Ms((ie==null?void 0:ie.costMillicents)??0)," / ",Ms(H.costBudgetMillicents)]})]})}),a.jsxs("div",{className:Y.tabBar,role:"tablist","aria-label":"Workspace view",children:[a.jsx("button",{role:"tab","aria-selected":C==="graph",className:`${Y.tab} ${C==="graph"?Y.active:""}`,onClick:()=>D("graph"),children:"Graph"}),a.jsx("button",{role:"tab","aria-selected":C==="board",className:`${Y.tab} ${C==="board"?Y.active:""}`,onClick:()=>D("board"),"data-testid":"board-tab",children:"Board"}),a.jsx("button",{role:"tab","aria-selected":C==="tasks",className:`${Y.tab} ${C==="tasks"?Y.active:""}`,onClick:()=>D("tasks"),children:"Tasks"})]}),C==="tasks"&&J>0&&a.jsxs("div",{className:Y.workspaceSummary,children:[a.jsx("span",{className:Y.workspaceSummaryTitle,children:`${E}/${J} tasks complete`}),a.jsx("span",{className:Y.workspaceSummarySubtitle,children:"Select a task or click + to create one"})]}),C==="tasks"&&J===0&&a.jsxs("div",{className:Y.emptyCta,children:[a.jsx("button",{className:Y.ctaButton,onClick:()=>o(zi(t,void 0,Q)),children:"Create Task"}),a.jsx("div",{className:Y.ctaDescription,children:"Break your work into tasks and let agents tackle them"})]}),C==="board"&&a.jsx(Fz,{workspaceId:t,environmentId:Q,tasks:r,sessions:S,personas:x,environments:c}),C==="graph"&&a.jsx(GN,{workspaceId:t,environmentId:Q,tasks:r,resolvedThemeId:T}),a.jsx(Ls,{isOpen:O,title:"Archive Workspace?",description:"This will hide the workspace from the sidebar. Tasks will not be deleted.",confirmLabel:"Archive",onConfirm:()=>{H&&(p(H.id).catch(()=>{}),o("/",{replace:!0})),A(!1)},onCancel:()=>A(!1)})]})}const LU="_container_3pgew_1",zU="_header_3pgew_8",$U="_headerTitle_3pgew_35",PU="_headerActions_3pgew_44",UU="_body_3pgew_51",HU="_btnPrimary_3pgew_63",VU="_btnGhost_3pgew_94",qU="_error_3pgew_116",Fa={container:LU,header:zU,headerTitle:$U,headerActions:PU,body:UU,btnPrimary:HU,btnGhost:VU,error:qU};function GU(t){const s={};return t.name.trim()||(s.name="Name is required"),t.repoUrl.trim()&&!/^https?:\/\/.+/i.test(t.repoUrl.trim())&&(s.repoUrl="Must be a valid http(s) URL"),t.environmentId||(s.environmentId="Environment is required"),Object.keys(s).length>0?s:void 0}const FU=[{label:"Home",url:Ii},{label:"New Workspace",url:void 0}];function ZU(){const[t]=Im(),s=t.get("environment")??void 0,{environments:{environments:o},personas:{personas:r},workspaces:{createWorkspace:c,workspaceCreating:d}}=rt(),{showToast:u}=gn(),p=ct(),[m,g]=y.useState(()=>{var w;return s$(void 0,s||((w=o[0])==null?void 0:w.id))}),[v,_]=y.useState(),[b,x]=y.useState();y.useEffect(()=>{s||m.environmentId||o.length===0||g(w=>{var T;return w.environmentId?w:{...w,environmentId:((T=o[0])==null?void 0:T.id)??""}})},[o,s,m.environmentId]);const S=()=>{const w=GU(m);if(w){_(w),x(void 0);return}_(void 0),x(void 0),c(m.name.trim(),m.description,m.repoUrl.trim(),m.environmentId,m.defaultPersonaId,m.useWorktrees,m.workingDirectory,()=>{u("Workspace created","success"),p(Ii,{replace:!0})},T=>{x(T)}).catch(()=>{})},j=()=>{p(s?Mi(s):Ii,{replace:!0})};return a.jsxs("div",{className:Fa.container,children:[a.jsxs("div",{className:Fa.header,children:[a.jsx("div",{className:Fa.headerTitle,children:a.jsx(xs,{segments:FU})}),a.jsxs("div",{className:Fa.headerActions,children:[a.jsx("button",{className:Fa.btnGhost,onClick:j,disabled:d,"data-testid":"workspace-create-cancel",children:"Cancel"}),a.jsx("button",{className:Fa.btnPrimary,onClick:S,disabled:d||!m.name.trim()||!m.environmentId,"data-testid":"workspace-create-save",children:d?a.jsx(B1,{size:"sm",label:"Creating"}):"Create Workspace"})]})]}),a.jsxs("div",{className:Fa.body,children:[a.jsx(i$,{values:m,onChange:w=>{g(w),_(void 0),x(void 0)},environments:o,personas:r,errors:v,disabled:d,autoFocusName:!0}),b&&a.jsx("div",{className:Fa.error,"data-testid":"workspace-create-submit-error",children:b})]})]})}function __(){const{workspaceId:t,environmentId:s}=Hn(),[o]=Im(),r=t??o.get("workspace")??"",c=o.get("parent")??void 0,{tasks:{tasks:d,createTask:u,updateTask:p},workspaces:{workspaces:m},personas:{personas:g}}=rt(),{showToast:v}=gn();return a.jsx(W1,{mode:"new",workspaceId:r,parentTaskId:c,environmentId:s,tasks:d,workspaces:m,personas:g,onCreateTask:(_,b,x,S,j,w,T,C,D)=>{u(_,b,x,S,j,w,T,C,D).catch(()=>{})},onUpdateTask:(_,b,x,S,j)=>{p(_,b,x,S,j).catch(()=>{})},onShowToast:v})}function KU(){return a.jsxs("div",{className:Y.panelContainer,"aria-hidden":"true",children:[a.jsx("div",{className:Y.header,children:a.jsxs("span",{className:Y.headerTitle,children:[a.jsx(Ne,{width:"12rem",height:"1rem"}),a.jsx(Ne,{width:"4rem",height:"1rem",borderRadius:"var(--radius-full)"})]})}),a.jsxs("div",{className:Y.tabBar,role:"tablist","aria-label":"Task view",children:[a.jsx("span",{className:`${Y.tab} ${Y.active}`,children:"Overview"}),a.jsx("span",{className:Y.tab,children:"Stream"}),a.jsx("span",{className:Y.tab,children:"Findings"})]}),a.jsx("div",{className:Y.overviewContent,children:a.jsxs("div",{className:Y.overviewDashboard,children:[a.jsx("div",{className:Y.overviewHero,children:a.jsx(Ne,{width:"5rem",height:"1.5rem",borderRadius:"var(--radius-full)"})}),a.jsxs("div",{className:Y.overviewSection,children:[a.jsx("div",{className:Y.overviewLabel,children:"Description"}),a.jsx(vm,{lines:2})]}),a.jsxs("div",{className:Y.overviewSection,children:[a.jsx("div",{className:Y.overviewLabel,children:"Environment"}),a.jsxs("div",{className:Y.envRow,children:[a.jsx(Ne,{width:"0.5rem",height:"0.5rem",variant:"circular"}),a.jsx(Ne,{width:"8rem",height:"0.875rem"})]})]}),a.jsxs("div",{className:Y.overviewSection,children:[a.jsx("div",{className:Y.overviewLabel,children:"Dependencies"}),a.jsx(vm,{lines:2})]}),a.jsxs("div",{className:Y.overviewSection,children:[a.jsx("div",{className:Y.overviewLabel,children:"Timeline"}),a.jsx("div",{className:Y.timeline,children:Array.from({length:4},(t,s)=>a.jsxs("div",{className:Y.timelineRow,children:[a.jsx(Ne,{width:"4rem",height:"0.75rem"}),a.jsx(Ne,{width:"10rem",height:"0.75rem"})]},s))})]})]})})]})}function Za(){const{taskId:t,workspaceId:s,environmentId:o}=Hn(),r=Yt(),c=ct(),{showToast:d}=gn(),{sessions:{events:u,eventsDropped:p,sessions:m,loadSessionEvents:g,taskSessions:v,loadTaskSessions:_,sendInput:b,spawn:x,kill:S},tasks:{tasks:j,tasksLoading:w,startTask:T,stopTask:C,resumeTask:D,deleteTask:O,createTask:A,updateTask:I},environments:{environments:$,provisionEnvironment:B},findings:{findings:P,loadFindings:X},workspaces:{workspaces:H},personas:{personas:Q},usageCache:he,loadUsage:W}=rt(),ie=y.useRef(void 0),L=y.useRef(void 0),E=y.useRef(void 0),J=y.useRef(void 0),me=y.useRef(void 0),q=r.pathname.endsWith("/stream")?"stream":r.pathname.endsWith("/findings")?"findings":"overview",de=r.pathname.endsWith("/edit"),[re,xe]=y.useState(q),[be,fe]=y.useState(!1),[_e,ke]=y.useState(void 0),[Le,Ot]=y.useState(""),[Vn,oe]=y.useState(de),Je=y.useRef(q),Ht=y.useRef(de),ne=j.find(De=>De.id===t),Ct=(ne==null?void 0:ne.workspaceId)||void 0,Bt=H.find(De=>De.id===Ct);y.useEffect(()=>{q!==Je.current&&(Je.current=q,q!==re&&xe(q))},[q,re]),y.useEffect(()=>{de!==Ht.current&&(Ht.current=de,de!==Vn&&oe(de))},[de,Vn]),y.useEffect(()=>{if(Le===""){if(Bt!=null&&Bt.linkedEnvironmentIds[0])Ot(Bt.linkedEnvironmentIds[0]);else if($.length>0){const De=$.find(We=>We.status==="connected");Ot((De==null?void 0:De.id)??$[0].id)}}},[Le,Bt==null?void 0:Bt.linkedEnvironmentIds[0],$]);const Lt=ne?v[ne.id]??[]:[];let Pe;_e&&Lt.some(De=>De.id===_e)?Pe=_e:Pe=(ne==null?void 0:ne.latestSessionId)||void 0;const rn=()=>{fe(!0)},ha=()=>{if(!ne)return;O(ne.id).catch(()=>{}),fe(!1);const De=o??(Bt==null?void 0:Bt.linkedEnvironmentIds[0]);c(ne.workspaceId&&De?Ri(ne.workspaceId,De):"/",{replace:!0})};y.useEffect(()=>{(ne==null?void 0:ne.id)!==L.current&&(L.current=ne==null?void 0:ne.id,ke(void 0),Ot(""),oe(de))},[ne==null?void 0:ne.id,de]),y.useEffect(()=>{if(!(ne!=null&&ne.id))return;const De=ne.id!==J.current,We=ne.latestSessionId!==me.current;(De||We)&&(J.current=ne.id,me.current=ne.latestSessionId,_(ne.id).catch(()=>{}))},[ne==null?void 0:ne.id,ne==null?void 0:ne.latestSessionId,_]),y.useEffect(()=>{if((ne==null?void 0:ne.status)!==E.current){const De=E.current===void 0;E.current=ne==null?void 0:ne.status;const We=(ne==null?void 0:ne.status)==="not_started"?"overview":(ne==null?void 0:ne.status)==="working"||(ne==null?void 0:ne.status)==="paused"?"stream":(ne==null?void 0:ne.status)==="complete"?"findings":void 0;We&&We!==re&&!(De&&q!=="overview")&&xe(We)}},[ne==null?void 0:ne.status,re,q]);const us=y.useMemo(()=>new Map(j.map(De=>[De.id,De])),[j]),ei=y.useMemo(()=>{const De=Pe?u.filter(We=>We.sessionId===Pe):[];return _h(bh(De))},[u,Pe]),ga=ne?ne.dependsOn.some(De=>{const We=us.get(De);return We!==void 0&&We.status!=="complete"}):!1,en=y.useMemo(()=>j$(t,o,H,$,us),[t,o,H,$,us]);y.useEffect(()=>{Pe&&Pe!==ie.current&&(ie.current=Pe,g(Pe).catch(()=>{}))},[Pe,g]),y.useEffect(()=>{re==="findings"&&Ct&&X(Ct).catch(()=>{})},[re,Ct,X]);const Pi=Lt.reduce((De,We)=>De+(We.costMillicents??0),0);y.useEffect(()=>{ne&&(W("task",ne.id).catch(()=>{}),ne.childTaskIds.length>0&&W("task_tree",ne.id).catch(()=>{}))},[ne==null?void 0:ne.id,ne==null?void 0:ne.childTaskIds.length,W,Pi]);const va=ne?`task:${ne.id}`:"",ti=va in he?he[va]:void 0,Ss=ne?`task_tree:${ne.id}`:"",Ui=ne&&ne.childTaskIds.length>0&&Ss in he?he[Ss]:void 0,qn=De=>{xe(De),c($n(t,De==="overview"?void 0:De,s,o))};return la({key:"1"},()=>qn("overview")),la({key:"2"},()=>qn("stream")),la({key:"3"},()=>qn("findings")),!ne&&w?a.jsx(KU,{}):a.jsxs("div",{className:Y.panelContainer,children:[a.jsx(xs,{segments:en}),a.jsxs("div",{className:Y.header,children:[a.jsxs("span",{className:Y.headerTitle,children:[a.jsx("span",{"data-testid":"task-title",children:(ne==null?void 0:ne.title)||t}),ne&&a.jsx("span",{className:Y.taskStatusBadge,"data-testid":"task-status",children:ne.status}),(ne==null?void 0:ne.branch)&&a.jsx("span",{className:Y.taskBranch,children:ne.branch}),ga&&a.jsx("span",{className:Y.taskBlockedBadge,children:"blocked"})]}),ne&&a.jsx(jL,{task:ne,sessionId:Pe,isBlocked:ga,onStart:()=>{T(ne.id,void 0,Le).catch(()=>{})},onResume:()=>{D(ne.id).catch(()=>{})},onStop:()=>{C(ne.id).catch(()=>{})},onPause:()=>{Pe&&S(Pe).catch(()=>{})},onDelete:rn,onEdit:()=>oe(!0)})]}),a.jsxs("div",{className:Y.tabBar,role:"tablist","aria-label":"Task view",children:[a.jsx("button",{role:"tab","aria-selected":re==="overview",className:`${Y.tab} ${re==="overview"?Y.active:""}`,onClick:()=>qn("overview"),children:"Overview"}),a.jsx("button",{role:"tab","aria-selected":re==="stream",className:`${Y.tab} ${re==="stream"?Y.active:""}`,onClick:()=>qn("stream"),children:"Stream"}),a.jsx("button",{role:"tab","aria-selected":re==="findings",className:`${Y.tab} ${re==="findings"?Y.active:""}`,onClick:()=>qn("findings"),children:"Findings"})]}),a.jsxs(ls,{mode:"wait",children:[re==="overview"&&a.jsx(Nt.div,{initial:{opacity:0,y:4},animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.15},className:Y.overviewContent,"data-testid":"task-overview",children:Vn&&ne?a.jsx(W1,{mode:"edit",taskId:ne.id,workspaceId:Ct,environmentId:o,tasks:j,workspaces:H,personas:Q,onCreateTask:(De,We,tn,jt,vn,nn,Hi,Vi,qi)=>{A(De,We,tn,jt,vn,nn,Hi,Vi,qi).catch(()=>{})},onUpdateTask:(De,We,tn,jt,vn)=>{I(De,We,tn,jt,vn).catch(()=>{})},onEditDone:()=>{de?c($n(ne.id,void 0,s,o),{replace:!0}):oe(!1)},onShowToast:d}):ne?a.jsx(u8,{task:ne,tasksById:us,environments:$,workspaces:H,taskSessions:Lt,selectedEnvId:Le,taskUsage:ti,treeUsage:Ui}):a.jsx("div",{className:Y.waitingMessage,children:"No additional details"})},"overview"),re==="stream"&&a.jsxs(Nt.div,{initial:{opacity:0,y:4},animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.15},style:{display:"flex",flexDirection:"column",flex:1,overflow:"hidden"},children:[a.jsx(u6,{taskSessions:Lt,selectedSessionId:Pe,onSelect:De=>ke(De)}),a.jsx(al,{events:ei,eventsDropped:p,emptyState:!Pe&&ne?ga?a.jsx("div",{className:Y.emptyCta,"data-testid":"stream-blocked-message",children:a.jsx("div",{className:Y.ctaDescription,children:"This task is blocked by incomplete dependencies"})}):a.jsxs("div",{className:Y.emptyCta,children:[a.jsx("button",{"data-testid":"stream-start-cta",className:Y.ctaButton,onClick:()=>{T(ne.id,void 0,Le).catch(()=>{})},children:"Start Task"}),a.jsx("div",{className:Y.ctaDescription,children:"Click to begin agent execution"})]}):Pe&&ei.length===0?a.jsx("div",{className:Y.waitingMessage,children:"Waiting for events..."}):void 0,onShowToast:d})]},"stream"),re==="findings"&&a.jsx(Nt.div,{initial:{opacity:0,y:4},animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.15},className:Y.tabContent,children:Ct?a.jsx(Y1,{findings:P.filter(De=>De.workspaceId===Ct)}):a.jsx("div",{className:Y.noContext,children:"Navigate to a task within a workspace to view findings"})},"findings")]}),(()=>{if(!ne||ne.status!=="working"&&ne.status!=="paused")return;const De=Pe?m.find(We=>We.id===Pe):void 0;if(!(!De||De.status==="stopped"))return a.jsx(rl,{mode:"send",sessionId:De.id,environmentId:De.environmentId,personas:Q,environments:$,onSendInput:(We,tn)=>{b(We,tn).catch(()=>{d("Failed to send message","error")})},onSpawn:(We,tn,jt)=>{x(We,tn,jt).catch(()=>{})},onStartTask:(We,tn,jt)=>{T(We,tn,jt).catch(()=>{})},onProvisionEnvironment:We=>{B(We).catch(()=>{})},onShowToast:d})})(),ne&&a.jsx(Ls,{isOpen:be,title:"Delete Task?",description:`"${ne.title}" will be permanently removed.`,onConfirm:ha,onCancel:()=>fe(!1)})]})}function YU(){const{environments:{environments:t,addEnvironment:s,updateEnvironment:o},codespaces:{codespaces:r,codespaceError:c,codespaceListError:d,codespaceCreating:u,listCodespaces:p,createCodespace:m}}=rt(),{showToast:g}=gn();return a.jsx(X1,{mode:"new",environments:t,onAddEnvironment:(v,_,b)=>{s(v,_,b).catch(()=>{})},onUpdateEnvironment:(v,_)=>{o(v,_).catch(()=>{})},onListCodespaces:()=>{p().catch(()=>{})},codespaces:r,codespaceError:c,codespaceListError:d,codespaceCreating:u,onCreateCodespace:(v,_)=>{m(v,_).catch(()=>{})},onShowToast:g})}function JU(){const{environmentId:t}=Hn(),{environments:{environments:s,addEnvironment:o,updateEnvironment:r},codespaces:{codespaces:c,codespaceError:d,codespaceListError:u,codespaceCreating:p,listCodespaces:m,createCodespace:g}}=rt(),{showToast:v}=gn();return a.jsx(X1,{mode:"edit",environmentId:t,environments:s,onAddEnvironment:(_,b,x)=>{o(_,b,x).catch(()=>{})},onUpdateEnvironment:(_,b)=>{r(_,b).catch(()=>{})},onListCodespaces:()=>{m().catch(()=>{})},codespaces:c,codespaceError:d,codespaceListError:u,codespaceCreating:p,onCreateCodespace:(_,b)=>{g(_,b).catch(()=>{})},onShowToast:v})}const WU="_layout_11u79_1",XU="_content_11u79_8",QU="_tabPanel_11u79_14",ol={layout:WU,content:XU,tabPanel:QU};function eH(){const t=_$();return a.jsxs("div",{className:ol.layout,children:[a.jsx(xs,{segments:t}),a.jsx("div",{className:ol.content,children:a.jsx(ma,{})})]})}const tH="_container_144a4_1",nH="_envHeader_144a4_6",sH="_envTitleRow_144a4_10",aH="_statusDot_144a4_16",iH="_envName_144a4_21",oH="_statusBadge_144a4_27",rH="_envMeta_144a4_33",lH="_metaTag_144a4_39",cH="_actions_144a4_51",dH="_provisionMessage_144a4_59",uH="_errorMessage_144a4_64",fH="_section_144a4_69",pH="_sectionHeader_144a4_73",mH="_cardList_144a4_121",hH="_card_144a4_121",gH="_cardHeader_144a4_138",vH="_cardName_144a4_144",yH="_cardActions_144a4_149",bH="_cardDescription_144a4_154",_H="_cardMeta_144a4_160",xH="_repoLink_144a4_166",kH="_empty_144a4_174",SH="_errorHint_144a4_180",jH="_btnPrimary_144a4_186",TH="_btnOutline_144a4_220",wH="_btnSmall_144a4_247",NH="_btnDanger_144a4_273",Re={container:tH,envHeader:nH,envTitleRow:sH,statusDot:aH,envName:iH,statusBadge:oH,envMeta:rH,metaTag:lH,actions:cH,provisionMessage:dH,errorMessage:uH,section:fH,sectionHeader:pH,cardList:mH,card:hH,cardHeader:gH,cardName:vH,cardActions:yH,cardDescription:bH,cardMeta:_H,repoLink:xH,empty:kH,errorHint:SH,btnPrimary:jH,btnOutline:TH,btnSmall:wH,btnDanger:NH};function CH(){return a.jsxs("div",{className:Re.container,"aria-hidden":"true",children:[a.jsxs("div",{className:Re.envHeader,children:[a.jsxs("div",{className:Re.envTitleRow,children:[a.jsx(Ne,{width:"0.875rem",height:"0.875rem",variant:"circular"}),a.jsx(Ne,{width:"12rem",height:"1.5rem"}),a.jsx(Ne,{width:"4rem",height:"0.875rem"})]}),a.jsxs("div",{className:Re.envMeta,children:[a.jsx(Ne,{width:"6rem",height:"1.25rem",borderRadius:"var(--radius-sm)"}),a.jsx(Ne,{width:"5rem",height:"1.25rem",borderRadius:"var(--radius-sm)"}),a.jsx(Ne,{width:"4.5rem",height:"1.25rem",borderRadius:"var(--radius-sm)"})]})]}),a.jsxs("div",{className:Re.actions,children:[a.jsx(Ne,{width:"5rem",height:"2rem",borderRadius:"var(--radius-sm)"}),a.jsx(Ne,{width:"4rem",height:"2rem",borderRadius:"var(--radius-sm)"})]}),a.jsxs("div",{className:Re.section,children:[a.jsx("div",{className:Re.sectionHeader,children:a.jsx("h3",{style:{margin:0},children:"Workspaces"})}),a.jsxs("div",{className:Re.cardList,children:[a.jsx(jd,{lines:2}),a.jsx(jd,{lines:2})]})]})]})}const EH={connected:"var(--accent-green)",sleeping:"var(--accent-yellow)",error:"var(--accent-red)",disconnected:"var(--text-tertiary)",connecting:"var(--accent-blue)"};function AH(){const{environmentId:t}=Hn(),s=ct(),{environments:{environments:o,environmentsLoading:r,provisionStatus:c,provisionEnvironment:d,stopEnvironment:u,removeEnvironment:p},workspaces:{workspaces:m,archiveWorkspace:g,linkEnvironment:v,unlinkEnvironment:_,linkOperationError:b,clearLinkOperationError:x},sessions:{sessions:S}}=rt(),[j,w]=y.useState(!1),[T,C]=y.useState(!1),[D,O]=y.useState(void 0),A=o.find(E=>E.id===t);if(!A&&r)return a.jsx(CH,{});if(!t||!A)return a.jsx(rs,{to:Lo,replace:!0});const I=m.filter(E=>E.linkedEnvironmentIds.includes(A.id)),$=S.filter(E=>E.environmentId===A.id),B=$.reduce((E,J)=>E+(J.costMillicents??0),0),P=EH[A.status]||"var(--text-tertiary)",X=A.status==="connected",H=A.status==="connecting",Q=A.status==="disconnected"||A.status==="error"||A.status==="sleeping",he=A.id in c?c[A.id]:void 0,W=()=>{p(A.id).catch(()=>{}),w(!1),s(Lo,{replace:!0})},ie=()=>{C(!1),d(A.id,!0).catch(()=>{})},L=E=>{g(E).catch(()=>{}),O(void 0)};return a.jsxs("div",{className:Re.container,children:[a.jsx(Ls,{isOpen:j,title:"Delete Environment?",description:`"${A.displayName||A.id}" will be permanently removed along with all its data.`,onConfirm:W,onCancel:()=>w(!1)}),a.jsx(Ls,{isOpen:T,title:"Reprovision Environment?",description:"This will kill any active session and force a fresh provision cycle. The environment will be temporarily disconnected.",confirmLabel:"Reprovision",onConfirm:ie,onCancel:()=>C(!1)}),a.jsxs("div",{className:Re.envHeader,children:[a.jsxs("div",{className:Re.envTitleRow,children:[a.jsx("span",{className:Re.statusDot,style:{color:P},children:"●"}),a.jsx("h2",{className:Re.envName,children:A.displayName||A.id}),a.jsx("span",{className:Re.statusBadge,style:{color:P},children:A.status})]}),a.jsxs("div",{className:Re.envMeta,children:[a.jsxs("span",{className:Re.metaTag,children:["Adapter: ",A.adapterType]}),$.length>0&&a.jsxs("span",{className:Re.metaTag,children:[$.length," session",$.length!==1?"s":""]}),B>0&&a.jsxs("span",{className:Re.metaTag,children:["Cost: ",Ms(B)]})]})]}),a.jsxs("div",{className:Re.actions,children:[X&&a.jsxs(a.Fragment,{children:[a.jsx("button",{className:Re.btnPrimary,onClick:()=>s(tx(A.id)),children:"New Chat"}),a.jsx("button",{className:Re.btnOutline,onClick:()=>{u(A.id).catch(()=>{})},children:"Stop"}),a.jsx("button",{className:Re.btnOutline,onClick:()=>C(!0),disabled:he!==void 0,"data-testid":"env-reprovision-btn",children:"Reprovision"})]}),Q&&a.jsx("button",{className:Re.btnPrimary,onClick:()=>{d(A.id).catch(()=>{})},children:A.status==="error"?"Retry":A.status==="sleeping"?"Wake":"Connect"}),H&&he!==void 0&&a.jsx("span",{className:Re.provisionMessage,children:he.message}),A.status==="error"&&(he==null?void 0:he.stage)==="error"&&a.jsx("span",{className:Re.errorMessage,children:he.message}),a.jsx("button",{className:Re.btnOutline,onClick:()=>s(IN(A.id)),"data-testid":"env-edit-btn",children:"Edit Config"}),a.jsx("button",{className:Re.btnDanger,onClick:()=>w(!0),children:"Delete"})]}),a.jsxs("div",{className:Re.section,children:[a.jsxs("div",{className:Re.sectionHeader,children:[a.jsx("h3",{children:"Workspaces"}),a.jsx("button",{className:Re.btnPrimary,onClick:()=>s(`${ax}?environment=${encodeURIComponent(A.id)}`),"data-testid":"workspace-create-button",children:"+ New Workspace"}),(()=>{const E=m.filter(J=>!J.linkedEnvironmentIds.includes(A.id)&&J.status==="active");return E.length===0?null:a.jsxs("select",{className:Re.btnPrimary,value:"",onChange:J=>{J.target.value&&v(J.target.value,A.id).catch(()=>{})},"aria-label":"Link a workspace","data-testid":"link-workspace-select",children:[a.jsx("option",{value:"",children:"+ Link Workspace"}),E.map(J=>a.jsx("option",{value:J.id,children:J.name},J.id))]})})()]}),b&&a.jsxs("p",{className:Re.errorHint,"data-testid":"link-operation-error",role:"alert",children:[b,a.jsx("button",{className:Re.btnSmall,onClick:x,"aria-label":"Dismiss error","data-testid":"dismiss-link-error",children:"Dismiss"})]}),I.length===0&&a.jsx("p",{className:Re.empty,"data-testid":"linked-workspaces-empty",children:"No workspaces yet. Create one to get started."}),a.jsx("div",{className:Re.cardList,"data-testid":"linked-workspaces-list",children:I.map(E=>a.jsx(DH,{workspace:E,confirmArchiveId:D,onOpen:()=>s(Ri(E.id,A.id)),onArchive:()=>O(E.id),onConfirmArchive:()=>L(E.id),onCancelArchive:()=>O(void 0),onUnlink:()=>{_(E.id,A.id).catch(()=>{})}},E.id))})]})]})}function DH({workspace:t,confirmArchiveId:s,onOpen:o,onArchive:r,onConfirmArchive:c,onCancelArchive:d,onUnlink:u}){const p=s===t.id,m=t.repoUrl&&/^https?:\/\//.test(t.repoUrl);return a.jsxs("div",{className:Re.card,"data-testid":"workspace-card","data-workspace-id":t.id,children:[a.jsxs("div",{className:Re.cardHeader,children:[a.jsx("strong",{className:Re.cardName,children:t.name}),a.jsxs("div",{className:Re.cardActions,children:[a.jsx("button",{className:Re.btnSmall,onClick:o,children:"Open"}),a.jsx("button",{className:Re.btnSmall,onClick:u,disabled:t.linkedEnvironmentIds.length<=1,"data-testid":`unlink-workspace-${t.id}`,children:"Unlink"}),p?a.jsxs(a.Fragment,{children:[a.jsx("button",{className:Re.btnDanger,onClick:c,children:"Confirm"}),a.jsx("button",{className:Re.btnSmall,onClick:d,children:"Cancel"})]}):a.jsx("button",{className:Re.btnSmall,onClick:r,children:"Archive"})]})]}),t.description&&a.jsx("p",{className:Re.cardDescription,children:t.description}),t.repoUrl&&a.jsx("div",{className:Re.cardMeta,children:m?a.jsx("a",{href:t.repoUrl,target:"_blank",rel:"noopener noreferrer",className:Re.repoLink,children:t.repoUrl}):a.jsx("span",{children:t.repoUrl})})]})}const RH={credentials:"Credentials",personas:"Personas",schedules:"Schedules",appearance:"Appearance",about:"About",shortcuts:"Shortcuts",plugins:"Plugins"};function MH(){const s=Yt().pathname.replace(/^\/settings\/?/,"").split("/")[0],o=RH[s],r=b$(o);return a.jsxs("div",{className:ol.layout,children:[a.jsx(xs,{segments:r}),a.jsx("div",{className:ol.content,children:a.jsx("div",{className:ol.tabPanel,children:a.jsx(ma,{})},s)})]})}function IH(){const{tokens:{tokens:t,setToken:s,deleteToken:o},credentials:{credentialProviders:r,updateCredentialProviders:c}}=rt(),{showToast:d}=gn();return a.jsxs(a.Fragment,{children:[a.jsx(V8,{credentialProviders:r,onUpdateCredentialProviders:u=>{c(u).catch(()=>{})}}),a.jsx(KB,{tokens:t,onSetToken:(u,p,m,g,v)=>{s(u,p,m,g,v).catch(()=>{})},onDeleteToken:u=>{o(u).catch(()=>{})},onShowToast:d})]})}function OH(){const{personas:{personas:t,deletePersona:s},appDefaultPersonaId:o,setAppDefaultPersonaId:r}=rt(),{showToast:c}=gn(),d=ct();return a.jsx(n7,{personas:t,appDefaultPersonaId:o,onDeletePersona:async u=>{try{await s(u)}catch(p){throw console.error("Failed to delete persona",{personaId:u,error:p}),c("Failed to delete persona","error"),p}},onSetAppDefaultPersonaId:async u=>{try{await r(u)}catch(p){console.error("Failed to set app default persona ID",{personaId:u,error:p}),c("Failed to set app default persona","error")}},onNavigateToNew:()=>d(BN),onNavigateToPersona:u=>d(nx(u))})}const BH="_container_1ooin_1",LH="_form_1ooin_7",zH="_formActions_1ooin_75",$H="_editableSection_1ooin_82",PH="_defaultBadge_1ooin_93",UH="_typeToggle_1ooin_107",HH="_scriptEditor_1ooin_121",VH="_optional_1ooin_128",bs={container:BH,form:LH,formActions:zH,editableSection:$H,defaultBadge:PH,typeToggle:UH,scriptEditor:HH,optional:VH},x_=[{value:"claude-code",label:"claude-code"},{value:"codex",label:"codex"},{value:"copilot",label:"copilot"},{value:"goose",label:"goose"},{value:"stub",label:"stub"},{value:"claude-code-acp",label:"claude-code-acp (experimental)"},{value:"codex-acp",label:"codex-acp (experimental)"},{value:"copilot-acp",label:"copilot-acp (experimental)"}],k_=[{value:"genaiscript",label:"genaiscript"}],qH="0";function S_(){const{personaId:t}=Hn(),s=ct(),{showToast:o}=gn(),{personas:{personas:r,createPersona:c,updatePersona:d,deletePersona:u},appDefaultPersonaId:p,setAppDefaultPersonaId:m}=rt(),g=t===void 0,v=g?void 0:r.find(b=>b.id===t);if(!g&&r.length>0&&!v)return a.jsx(rs,{to:rp,replace:!0});const _=[{label:"Settings",url:Ei},{label:"Personas",url:rp},{label:g?"New Persona":(v==null?void 0:v.name)??"Persona",url:void 0}];return a.jsxs("div",{className:bs.container,children:[a.jsx(xs,{segments:_}),a.jsx(GH,{existing:v,isNew:g,appDefaultPersonaId:p,onCreatePersona:c,onUpdatePersona:d,onDeletePersona:u,onSetAppDefaultPersonaId:m,onDone:()=>{s(rp)},showToast:o})]})}function GH({existing:t,isNew:s,appDefaultPersonaId:o,onCreatePersona:r,onUpdatePersona:c,onDeletePersona:d,onSetAppDefaultPersonaId:u,onDone:p,showToast:m}){const g=ct(),[v,_]=y.useState((t==null?void 0:t.name)??""),[b,x]=y.useState((t==null?void 0:t.description)??""),[S,j]=y.useState((t==null?void 0:t.systemPrompt)??""),[w,T]=y.useState((t==null?void 0:t.runtime)??"claude-code"),[C,D]=y.useState((t==null?void 0:t.model)??"sonnet"),[O,A]=y.useState((t==null?void 0:t.maxTurns)??0),[I,$]=y.useState((t==null?void 0:t.type)==="script"?"script":"agent"),[B,P]=y.useState((t==null?void 0:t.script)??""),[X,H]=y.useState((t==null?void 0:t.allowedMcpTools)??[]),[Q,he]=y.useState(!1),[W,ie]=y.useState(null),[L,E]=y.useState(!!s);y.useEffect(()=>{if(!s&&t&&!L){E(!0),_(t.name),x(t.description),j(t.systemPrompt);const oe=t.type==="script"?"script":"agent";T(oe==="script"?t.runtime||"genaiscript":t.runtime),D(t.model),A(t.maxTurns),$(oe),P(t.script||""),H(t.allowedMcpTools)}},[s,t,L]);const J=oe=>{$(oe),oe==="script"?T("genaiscript"):w==="genaiscript"&&T("claude-code")},me=!s&&t===void 0,q=v.trim().length>0&&!me&&S.trim().length>0&&(I==="script"?B.trim().length>0:!!w&&!!C),de=s&&q,re=!s&&o===(t==null?void 0:t.id),xe=!s&&t&&!re&&I==="agent"&&!!w&&!!C,be=(oe,Je)=>{if(!oe.trim())return`${Je} is required`},fe=oe=>{if(oe.preventDefault(),!(me||!q)){if(t){c(t.id,v,b,S,w,C,O,I,B).then(()=>{m("Persona updated","success"),p()},()=>{m("Failed to save persona","error")});return}r(v,b,S,w,C,O,I,B,X).then(Je=>{m("Persona created","success"),g(nx(Je.id),{replace:!0})},()=>{m("Failed to save persona","error")})}},_e=()=>{t&&d(t.id).then(()=>{m("Persona deleted","success"),p()},()=>{m("Failed to delete persona","error")})},ke=async(oe,Je,Ht,ne)=>oe().then(()=>{Je(),m(Ht,"success")},()=>{m(ne,"error")}),Le=(oe,Je)=>{if(!t)return;const Ht=oe==="type"?String(Je):I,ne=oe==="runtime"?String(Je):oe==="type"?String(Je)==="script"?"genaiscript":w==="genaiscript"?"claude-code":w:w,Ct=oe==="model"?String(Je):C,Bt=oe==="maxTurns"?Number(Je):O,Lt=oe==="systemPrompt"?String(Je):S,Pe=oe==="script"?String(Je):B;ke(()=>c(t.id,oe==="name"?String(Je):v,oe==="description"?String(Je):b,Lt,ne,Ct,Bt,Ht,Pe),()=>{if(oe==="type"){const rn=String(Je)==="script"?"script":"agent";$(rn),T(ne)}oe==="runtime"&&T(String(Je)),oe==="name"&&_(String(Je)),oe==="description"&&x(String(Je)),oe==="systemPrompt"&&j(String(Je)),oe==="model"&&D(String(Je)),oe==="maxTurns"&&A(Number(Je)),oe==="script"&&P(String(Je))},"Persona updated","Failed to update persona").catch(()=>{})},Ot=oe=>{fe(oe)},Vn=()=>{t&&u(t.id).then(()=>{m("Set as app default","success")},()=>{m("Failed to set app default","error")})};return a.jsxs(a.Fragment,{children:[me?a.jsxs("div",{className:bs.form,children:[a.jsx("h3",{children:"Edit Persona"}),a.jsx("p",{children:"Loading persona..."})]}):s?a.jsxs("form",{onSubmit:Ot,className:bs.form,children:[a.jsx("h3",{children:"Create Persona"}),a.jsxs("div",{className:bs.typeToggle,"data-testid":"persona-type-toggle",children:[a.jsxs("label",{children:[a.jsx("input",{type:"radio",name:"personaType",value:"agent",checked:I==="agent",onChange:()=>J("agent")}),"Agent"]}),a.jsxs("label",{children:[a.jsx("input",{type:"radio",name:"personaType",value:"script",checked:I==="script",onChange:()=>J("script")}),"Script"]})]}),a.jsxs("label",{children:["Name",a.jsx("input",{type:"text",value:v,onChange:oe=>_(oe.target.value),placeholder:I==="script"?"e.g. Nightly Report":"e.g. Frontend Engineer",required:!0,"data-testid":"persona-detail-name"})]}),a.jsxs("label",{children:["Description",a.jsx("input",{type:"text",value:b,onChange:oe=>x(oe.target.value),placeholder:"Brief description...","data-testid":"persona-detail-description"})]}),a.jsxs("label",{children:["Runtime",a.jsx("select",{value:w,onChange:oe=>T(oe.target.value),"data-testid":"persona-runtime-select",children:(I==="script"?k_:x_).map(oe=>a.jsx("option",{value:oe.value,children:oe.label},oe.value))})]}),I==="agent"&&a.jsxs(a.Fragment,{children:[a.jsxs("label",{children:["Model",a.jsx("input",{type:"text",value:C,onChange:oe=>D(oe.target.value),placeholder:"e.g. sonnet","data-testid":"persona-detail-model"})]}),a.jsxs("label",{children:["Max Turns",a.jsx("input",{type:"number",value:O,onChange:oe=>A(parseInt(oe.target.value,10)||0),min:0,"data-testid":"persona-detail-max-turns"})]}),a.jsxs("label",{children:["System Prompt",a.jsx("textarea",{value:S,onChange:oe=>j(oe.target.value),placeholder:"You are a senior frontend engineer...",rows:10,required:!0,"data-testid":"persona-detail-prompt"})]})]}),I==="script"&&a.jsxs(a.Fragment,{children:[a.jsxs("label",{children:["Model ",a.jsx("span",{className:bs.optional,children:"(optional)"}),a.jsx("input",{type:"text",value:C,onChange:oe=>D(oe.target.value),placeholder:"e.g. sonnet (leave empty for script-only)","data-testid":"persona-detail-model"})]}),a.jsxs("label",{children:["System Prompt",a.jsx("textarea",{value:S,onChange:oe=>j(oe.target.value),placeholder:"Context for the script...",rows:4,required:!0,"data-testid":"persona-detail-prompt"})]}),a.jsxs("label",{children:["Script",a.jsx("textarea",{value:B,onChange:oe=>P(oe.target.value),placeholder:`script({ model: "openai:gpt-4o" });
731
731
 
732
732
  const grackle = await host.mcpServer({
733
733
  id: "grackle",
@@ -741,4 +741,4 @@ const grackle = await host.mcpServer({
741
741
  url: env.vars.GRACKLE_MCP_URL,
742
742
  });
743
743
 
744
- $\`Summarize the current tasks.\`;`,ariaLabel:"Persona script","data-testid":"persona-script-editor"})]}),I==="agent"&&a.jsxs("div",{children:[a.jsx("label",{children:"Allowed MCP Tools"}),a.jsx(l_,{selectedTools:X,onChange:oe=>{H(oe),ke(()=>c(t.id,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,oe),()=>{},"MCP tools updated","Failed to update MCP tools").catch(()=>{})}})]})]}),!xe&&!re&&a.jsx("p",{style:{fontSize:"var(--font-size-xs)",color:"var(--text-tertiary)",marginTop:"var(--space-xs)"},children:"Only agent personas with a runtime and model can be set as app default."})]}):null,a.jsx(Ls,{isOpen:Q,title:"Delete Persona?",description:`"${t==null?void 0:t.name}" will be permanently removed.`,confirmLabel:"Delete",onConfirm:_e,onCancel:()=>he(!1)})]})}function FH(){const{schedules:{schedules:t,deleteSchedule:s,updateSchedule:o},personas:{personas:r}}=rt(),{showToast:c}=gn(),d=ct();return a.jsx(D7,{schedules:t,personas:r,onDeleteSchedule:async u=>{try{await s(u)}catch(p){throw console.error("Failed to delete schedule",{scheduleId:u,error:p}),c("Failed to delete schedule","error"),p}},onToggleEnabled:async(u,p)=>{try{return await o(u,p)}catch(m){throw console.error("Failed to update schedule",{scheduleId:u,error:m}),c("Failed to update schedule","error"),m}},onNavigateToNew:()=>d(LN),onNavigateToSchedule:u=>d(sx(u))})}const ZH="_container_1g4qh_1",KH="_form_1g4qh_7",YH="_formActions_1g4qh_66",JH="_editableSection_1g4qh_73",WH="_helperText_1g4qh_84",XH="_metaSection_1g4qh_90",QH="_optional_1g4qh_108",eV="_readonlyValue_1g4qh_113",Bn={container:ZH,form:KH,formActions:YH,editableSection:JH,helperText:WH,metaSection:XH,optional:QH,readonlyValue:eV};function j_(){const{scheduleId:t}=Hn(),s=ct(),{showToast:o}=gn(),{schedules:{schedules:r,schedulesLoading:c,createSchedule:d,updateSchedule:u,deleteSchedule:p},personas:{personas:m},workspaces:{workspaces:g}}=rt(),v=t===void 0,_=v?void 0:r.find(x=>x.id===t);if(!v&&!c&&r.length>0&&!_)return a.jsx(rs,{to:lp,replace:!0});const b=[{label:"Settings",url:Ei},{label:"Schedules",url:lp},{label:v?"New Schedule":(_==null?void 0:_.title)??"Schedule",url:void 0}];return a.jsxs("div",{className:Bn.container,children:[a.jsx(xs,{segments:b}),a.jsx(tV,{existing:_,isNew:v,personas:m,workspaces:g,onCreateSchedule:d,onUpdateSchedule:u,onDeleteSchedule:p,onDone:()=>{s(lp)},showToast:o})]})}function tV({existing:t,isNew:s,personas:o,workspaces:r,onCreateSchedule:c,onUpdateSchedule:d,onDeleteSchedule:u,onDone:p,showToast:m}){var L;const g=ct(),[v,_]=y.useState((t==null?void 0:t.title)??""),[b,x]=y.useState((t==null?void 0:t.description)??""),[S,j]=y.useState((t==null?void 0:t.scheduleExpression)??""),[w,T]=y.useState((t==null?void 0:t.personaId)??""),[C,D]=y.useState((t==null?void 0:t.workspaceId)??""),[O,A]=y.useState(!1),[I,$]=y.useState(null);y.useEffect(()=>{s||t&&I===null&&(_(t.title),x(t.description),j(t.scheduleExpression),T(t.personaId),D(t.workspaceId))},[s,t,I]);const B=!s&&t===void 0,P=s&&v.trim().length>0&&S.trim().length>0&&w.length>0,X=o.map(E=>({value:E.id,label:E.name})),H=[{value:"",label:"System-level (no workspace)"},...r.map(E=>({value:E.id,label:E.name}))],Q=E=>{E.preventDefault(),P&&c(v,b,S,w,C||void 0).then(J=>{m("Schedule created","success"),g(sx(J.id),{replace:!0})},()=>{m("Failed to create schedule","error")})},he=(E,J)=>{t&&d(t.id,{[E]:J}).then(()=>{m("Schedule updated","success"),E==="title"&&_(String(J)),E==="description"&&x(String(J)),E==="scheduleExpression"&&j(String(J)),E==="personaId"&&T(String(J))},()=>{m("Failed to update schedule","error")})},W=()=>{if(!t)return;const E=!t.enabled;d(t.id,{enabled:E}).then(()=>{m(E?"Schedule enabled":"Schedule disabled","success")},()=>{m("Failed to update schedule","error")})},ie=()=>{t&&u(t.id).then(()=>{m("Schedule deleted","success"),p()},()=>{m("Failed to delete schedule","error")})};return a.jsxs(a.Fragment,{children:[B?a.jsxs("div",{className:Bn.form,children:[a.jsx("h3",{children:"Edit Schedule"}),a.jsx("p",{children:"Loading schedule..."})]}):s?a.jsxs("form",{onSubmit:Q,className:Bn.form,children:[a.jsx("h3",{children:"Create Schedule"}),a.jsxs("label",{children:["Title",a.jsx("input",{type:"text",value:v,onChange:E=>_(E.target.value),placeholder:"e.g. Nightly Review",required:!0,"data-testid":"schedule-detail-title"})]}),a.jsxs("label",{children:["Description ",a.jsx("span",{className:Bn.optional,children:"(optional)"}),a.jsx("input",{type:"text",value:b,onChange:E=>x(E.target.value),placeholder:"Brief description...","data-testid":"schedule-detail-description"})]}),a.jsxs("label",{children:["Schedule Expression",a.jsx("input",{type:"text",value:S,onChange:E=>j(E.target.value),placeholder:"e.g. 30s, 5m, 1h, or 0 9 * * MON",required:!0,"data-testid":"schedule-detail-expression"}),a.jsxs("p",{className:Bn.helperText,children:["Interval: ",a.jsx("code",{children:"30s"}),", ",a.jsx("code",{children:"5m"}),", ",a.jsx("code",{children:"1h"}),", ",a.jsx("code",{children:"1d"})," (min 10s)  |  Cron: ",a.jsx("code",{children:"0 9 * * MON"})," (standard 5-field cron syntax)"]})]}),a.jsxs("label",{children:["Persona",a.jsxs("select",{value:w,onChange:E=>T(E.target.value),required:!0,"data-testid":"schedule-detail-persona",children:[a.jsx("option",{value:"",children:"Select a persona..."}),X.map(E=>a.jsx("option",{value:E.value,children:E.label},E.value))]})]}),a.jsxs("label",{children:["Workspace ",a.jsx("span",{className:Bn.optional,children:"(optional)"}),a.jsx("select",{value:C,onChange:E=>D(E.target.value),"data-testid":"schedule-detail-workspace",children:H.map(E=>a.jsx("option",{value:E.value,children:E.label},E.value))})]}),a.jsxs("div",{className:Bn.formActions,children:[a.jsx(on,{type:"submit",variant:"primary",size:"md",disabled:!P,"data-testid":"schedule-detail-save",children:"Create"}),a.jsx(on,{type:"button",variant:"outline",size:"md",onClick:p,"data-testid":"schedule-detail-cancel",children:"Cancel"})]})]}):t?a.jsxs("div",{className:Bn.form,children:[a.jsx("h3",{children:"Edit Schedule"}),a.jsxs("div",{className:Bn.formActions,children:[a.jsx(on,{type:"button",variant:"outline",size:"md",onClick:p,"data-testid":"schedule-detail-cancel",children:"Back to Schedules"}),a.jsx(on,{type:"button",variant:t.enabled?"ghost":"primary",size:"md",onClick:W,"data-testid":"schedule-detail-toggle",children:t.enabled?"Disable":"Enable"}),a.jsx(on,{type:"button",variant:"danger",size:"md",onClick:()=>A(!0),"data-testid":"schedule-detail-delete",children:"Delete"})]}),a.jsxs("div",{className:Bn.editableSection,children:[a.jsxs("label",{children:["Title",a.jsx(Zt,{value:v,onSave:E=>{he("title",E)},validate:E=>E.trim()?void 0:"Title is required",fieldId:"schedule-title",activeFieldId:I,onActivate:$,ariaLabel:"Schedule title","data-testid":"schedule-detail-title"})]}),a.jsxs("label",{children:["Description",a.jsx(Zt,{value:b,onSave:E=>{he("description",E)},fieldId:"schedule-description",activeFieldId:I,onActivate:$,placeholder:"Brief description...",ariaLabel:"Schedule description","data-testid":"schedule-detail-description"})]}),a.jsxs("label",{children:["Schedule Expression",a.jsx(Zt,{value:S,onSave:E=>{he("scheduleExpression",E)},validate:E=>E.trim()?void 0:"Schedule expression is required",fieldId:"schedule-expression",activeFieldId:I,onActivate:$,placeholder:"e.g. 30s, 5m, 1h, or 0 9 * * MON",ariaLabel:"Schedule expression","data-testid":"schedule-detail-expression"})]}),a.jsxs("label",{children:["Persona",a.jsx(Td,{value:w,onSave:E=>{he("personaId",E)},options:X,fieldId:"schedule-persona",activeFieldId:I,onActivate:$,ariaLabel:"Schedule persona","data-testid":"schedule-detail-persona"})]}),a.jsxs("label",{children:["Workspace ",a.jsx("span",{className:Bn.optional,children:"(optional — set at creation)"}),a.jsx("span",{className:Bn.readonlyValue,"data-testid":"schedule-detail-workspace",children:((L=r.find(E=>E.id===t.workspaceId))==null?void 0:L.name)??"System-level (no workspace)"})]})]}),a.jsxs("div",{className:Bn.metaSection,children:[t.lastRunAt?a.jsxs("span",{children:["Last run: ",Ho(t.lastRunAt)]}):a.jsx("span",{children:"Last run: Never"}),t.enabled&&t.nextRunAt?a.jsxs("span",{children:["Next run: ",q1(t.nextRunAt)]}):null,t.runCount>0&&a.jsxs("span",{children:["Total runs: ",t.runCount]}),a.jsxs("span",{children:["Created: ",Ho(t.createdAt)]})]})]}):null,a.jsx(Ls,{isOpen:O,title:"Delete Schedule?",description:`"${t==null?void 0:t.title}" will be permanently removed. Tasks already created by this schedule will not be affected.`,confirmLabel:"Delete",onConfirm:ie,onCancel:()=>A(!1)})]})}function nV(){const{themeId:t,resolvedThemeId:s,setTheme:o,preferSystem:r,setPreferSystem:c}=ak();return a.jsx(YB,{themeId:t,resolvedThemeId:s,onSetTheme:o,preferSystem:r,onSetPreferSystem:c})}function sV(){const[t,s]=y.useState(void 0);return y.useEffect(()=>{let o=!1;return(async()=>{try{const c=await Fe.getVersionStatus({});o||s({currentVersion:c.currentVersion,latestVersion:c.latestVersion,updateAvailable:c.updateAvailable,isDocker:c.isDocker})}catch{}})().catch(()=>{}),()=>{o=!0}},[]),t}function aV(){const{connectionStatus:t,environments:{environments:s},sessions:{sessions:o}}=rt(),r=sV();return a.jsxs(a.Fragment,{children:[r&&a.jsx(YO,{currentVersion:r.currentVersion,latestVersion:r.latestVersion,updateAvailable:r.updateAvailable,isDocker:r.isDocker}),a.jsx(XB,{connectionStatus:t,environments:s,sessions:o})]})}function iV(){return a.jsx(U8,{})}function oV(){const{plugins:{plugins:t,pluginsLoading:s,setPluginEnabled:o}}=rt();return a.jsx(f8,{plugins:t,loading:s,onSetPluginEnabled:(r,c)=>{o(r,c).catch(()=>{})}})}const T_=zi();function rV(){const t=ct();return la({key:"?"},()=>{t(zN)}),la({key:"n"},()=>{t(T_)}),la({key:"N"},()=>{t(T_)}),a.jsx(a.Fragment,{})}function Ko(t){const s=m$();y.useLayoutEffect(()=>(s(t),()=>{s(void 0)}),[t,s])}function lV(){const{workspaces:{workspaces:t},tasks:{tasks:s}}=rt(),o=y.useMemo(()=>a.jsx(TO,{workspaces:t,tasks:s}),[t,s]);return Ko(o),a.jsx(ma,{})}function cV(){const{environments:{environments:t}}=rt(),s=y.useMemo(()=>a.jsx(O5,{environments:t}),[t]);return Ko(s),a.jsx(ma,{})}function dV(){const t=y.useMemo(()=>a.jsx(B7,{}),[]);return Ko(t),a.jsx(ma,{})}function uV(){const{findings:{findings:t,loadFindings:s,loadAllFindings:o}}=rt(),{workspaceId:r,environmentId:c}=Hn();y.useEffect(()=>{r?s(r).catch(()=>{}):o().catch(()=>{})},[r,s,o]);const d=y.useMemo(()=>a.jsx(F5,{findings:t,workspaceId:r,environmentId:c}),[t,r,c]);return Ko(d),a.jsx(ma,{})}function fV(){const{knowledge:t,workspaces:{workspaces:s}}=rt(),o=y.useCallback(p=>{t.search(p).catch(()=>{})},[t]),r=y.useCallback(()=>{t.clearSearch()},[t]),c=y.useCallback(p=>{t.selectNode(p).catch(()=>{})},[t]),d=y.useCallback(p=>{t.loadRecent(p||void 0).catch(()=>{})},[t]),u=y.useMemo(()=>a.jsx(GI,{nodes:t.graphData.nodes,workspaces:s,loading:t.loading,searchQuery:t.searchQuery,onSearch:o,onClearSearch:r,onSelectNode:c,onWorkspaceChange:d}),[t,s,o,r,c,d]);return Ko(u),a.jsx(ma,{})}function pV(){const{streams:{streams:t,streamsLoading:s,streamsLoadError:o,streamsLoadedOnce:r,loadStreams:c}}=rt(),d=y.useCallback(()=>{c().catch(()=>{})},[c]),u=y.useMemo(()=>a.jsx(K7,{streams:t,loading:s,streamsLoadError:o,streamsLoadedOnce:r,onRefresh:d}),[t,s,o,r,d]);return Ko(u),a.jsx(ma,{})}const mV="_container_ce571_1",hV="_title_ce571_6",Cd={container:mV,title:hV};function gV(){return a.jsxs("div",{className:Cd.container,"aria-hidden":"true",children:[a.jsx("h1",{className:Cd.title,children:"Findings"}),a.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"var(--space-sm)"},children:Array.from({length:4},(t,s)=>a.jsx(jd,{lines:3},s))})]})}function w_(){const{environmentId:t,workspaceId:s}=Hn(),{findings:{findings:o,findingsLoading:r,loadFindings:c},workspaces:{workspaces:d},environments:{environments:u}}=rt(),p=ct();y.useEffect(()=>{s&&c(s).catch(()=>{})},[s,c]);const m=y.useCallback(v=>{p(Qp(v,s,t))},[p,s,t]);if(r)return a.jsx(gV,{});const g=s&&t?uk("Findings",s,t,d,u).slice(0,-1):w$();return a.jsxs("div",{className:Cd.container,"data-testid":"findings-list-page",children:[a.jsx(xs,{segments:g}),a.jsx("h1",{className:Cd.title,children:"Findings"}),a.jsx(Y1,{findings:o,onFindingClick:m})]})}const vV="_container_1wwpb_1",yV="_notFound_1wwpb_6",bV="_header_1wwpb_12",_V="_categoryBadge_1wwpb_19",xV="_title_1wwpb_28",kV="_content_1wwpb_35",SV="_tags_1wwpb_77",jV="_tag_1wwpb_77",TV="_meta_1wwpb_92",wV="_metaTimestamp_1wwpb_100",NV="_metaLink_1wwpb_105",xn={container:vV,notFound:yV,header:bV,categoryBadge:_V,title:xV,content:kV,tags:SV,tag:jV,meta:TV,metaTimestamp:wV,metaLink:NV};function N_(){const{findingId:t,environmentId:s,workspaceId:o}=Hn(),{findings:{selectedFinding:r,findingLoading:c,loadFinding:d},workspaces:{workspaces:u},environments:{environments:p}}=rt(),m=ct();if(y.useEffect(()=>{t&&d(t).catch(()=>{})},[t,d]),c)return a.jsx("div",{className:xn.container,"data-testid":"finding-detail-page",children:a.jsx("div",{className:xn.notFound,children:"Loading..."})});if(!r)return a.jsx("div",{className:xn.container,"data-testid":"finding-detail-page",children:a.jsx("div",{className:xn.notFound,children:"Finding not found."})});const g=uk(r.title,o,s,u,p),v=wd(r.category);return a.jsxs("div",{className:xn.container,"data-testid":"finding-detail-page",children:[a.jsx(xs,{segments:g}),a.jsxs("div",{className:xn.header,children:[a.jsx("span",{className:xn.categoryBadge,style:{background:v.bg,color:v.text},children:r.category}),a.jsx("h1",{className:xn.title,children:r.title})]}),r.content&&a.jsx("div",{className:xn.content,children:a.jsx(Ad,{remarkPlugins:[Dd],children:r.content})}),r.tags.length>0&&a.jsx("div",{className:xn.tags,children:r.tags.map(_=>a.jsx("span",{className:xn.tag,children:_},_))}),a.jsxs("div",{className:xn.meta,children:[a.jsx("span",{className:xn.metaTimestamp,title:r.createdAt,children:Ho(r.createdAt)}),r.taskId&&a.jsx("button",{type:"button",className:xn.metaLink,onClick:()=>{m($n(r.taskId))},children:"View Task"}),r.sessionId&&a.jsx("button",{type:"button",className:xn.metaLink,onClick:()=>{m(Ld(r.sessionId))},children:"View Session"})]})]})}const CV="_wizard_1260s_1",EV="_container_1260s_10",AV="_stepContent_1260s_19",DV="_logoArea_1260s_28",RV="_logoImage_1260s_32",MV="_heading_1260s_41",IV="_tagline_1260s_49",OV="_subtitle_1260s_56",BV="_featureList_1260s_64",LV="_runtimeGrid_1260s_89",zV="_runtimeCard_1260s_101",$V="_runtimeName_1260s_133",PV="_runtimeDescription_1260s_139",UV="_buttonRow_1260s_144",HV="_primaryButton_1260s_151",VV="_ghostButton_1260s_185",qV="_dots_1260s_213",GV="_dot_1260s_213",Ye={wizard:CV,container:EV,stepContent:AV,logoArea:DV,logoImage:RV,heading:MV,tagline:IV,subtitle:OV,featureList:BV,runtimeGrid:LV,runtimeCard:zV,runtimeName:$V,runtimeDescription:PV,buttonRow:UV,primaryButton:HV,ghostButton:VV,dots:qV,dot:GV};function FV({onNext:t}){return a.jsxs("div",{className:Ye.stepContent,"data-testid":"setup-welcome",children:[a.jsx("div",{className:Ye.logoArea,children:a.jsx("img",{src:"/grackle-logo.png",alt:"Grackle",className:Ye.logoImage})}),a.jsx("h1",{className:Ye.heading,children:"Welcome to Grackle"}),a.jsx("p",{className:Ye.tagline,children:"Multi-agent orchestration for software teams"}),a.jsx("button",{type:"button",className:Ye.primaryButton,onClick:t,"data-testid":"setup-get-started",children:"Get Started"})]})}function ZV({onNext:t,onBack:s}){return a.jsxs("div",{className:Ye.stepContent,"data-testid":"setup-about",children:[a.jsx("h2",{className:Ye.heading,children:"What is Grackle?"}),a.jsxs("ul",{className:Ye.featureList,children:[a.jsx("li",{children:"Run Claude, Copilot, and Codex agents side by side"}),a.jsx("li",{children:"Provision and control dev environments — SSH, Codespaces, or local"}),a.jsx("li",{children:"Organize work into workspaces with agent-executable tasks"}),a.jsx("li",{children:"Customize agent behavior with personas, tools, and MCP servers"}),a.jsx("li",{children:"Live-stream agent sessions with full terminal replay"})]}),a.jsxs("div",{className:Ye.buttonRow,children:[a.jsx("button",{type:"button",className:Ye.ghostButton,onClick:s,children:"Back"}),a.jsx("button",{type:"button",className:Ye.primaryButton,onClick:t,"data-testid":"setup-about-next",children:"Next"})]})]})}const KV=[{id:"claude-code",name:"Claude Code",description:"Anthropic's agentic coding tool"},{id:"copilot",name:"Copilot Coding Agent",description:"GitHub's AI pair programmer"},{id:"codex",name:"Codex CLI",description:"OpenAI's coding agent"},{id:"goose",name:"Goose",description:"Block's open-source AI coding agent"}];function YV({currentRuntime:t,onFinish:s,onBack:o,finishDisabled:r}){const[c,d]=y.useState(t||"claude-code");return y.useEffect(()=>{t&&d(t)},[t]),a.jsxs("div",{className:Ye.stepContent,"data-testid":"setup-runtime",children:[a.jsx("h2",{className:Ye.heading,children:"Choose Your Runtime"}),a.jsx("p",{className:Ye.subtitle,children:"Select the primary agent runtime for your workspace. You can change this later."}),a.jsx("div",{className:Ye.runtimeGrid,children:KV.map(u=>a.jsxs("button",{type:"button",className:Ye.runtimeCard,"data-selected":c===u.id,"aria-pressed":c===u.id,"data-testid":`runtime-card-${u.id}`,onClick:()=>d(u.id),children:[a.jsx("span",{className:Ye.runtimeName,children:u.name}),a.jsx("span",{className:Ye.runtimeDescription,children:u.description})]},u.id))}),a.jsxs("div",{className:Ye.buttonRow,children:[a.jsx("button",{type:"button",className:Ye.ghostButton,onClick:o,children:"Back"}),a.jsx("button",{type:"button",className:Ye.primaryButton,onClick:()=>{s(c)},disabled:r,"data-testid":"setup-runtime-next",children:"Next"})]})]})}function JV(){return typeof Notification<"u"}function WV({onFinish:t,onBack:s,finishDisabled:o}){const r=JV(),c=r&&Notification.permission!=="default";function d(){r&&Notification.requestPermission().catch(()=>{}),t()}return a.jsxs("div",{className:Ye.stepContent,"data-testid":"setup-notifications",children:[a.jsx("h2",{className:Ye.heading,children:"Stay in the Loop"}),a.jsx("p",{className:Ye.subtitle,children:"Grackle can send you a browser notification when an agent needs your input, so you never miss an important moment."}),c?a.jsx("p",{className:Ye.subtitle,children:Notification.permission==="granted"?"Notifications are already enabled.":"Notifications have been blocked. You can change this in your browser settings."}):null,a.jsxs("div",{className:Ye.buttonRow,children:[a.jsx("button",{type:"button",className:Ye.ghostButton,onClick:s,disabled:o,children:"Back"}),!c&&r?a.jsxs(a.Fragment,{children:[a.jsx("button",{type:"button",className:Ye.ghostButton,onClick:t,disabled:o,"data-testid":"setup-notifications-skip",children:"Skip"}),a.jsx("button",{type:"button",className:Ye.primaryButton,onClick:d,disabled:o,"data-testid":"setup-notifications-enable",children:"Enable Notifications"})]}):a.jsx("button",{type:"button",className:Ye.primaryButton,onClick:t,disabled:o,"data-testid":"setup-finish",children:"Finish"})]})]})}const XV=4,C_={"claude-code":"sonnet",copilot:"gpt-4o",codex:"o3",goose:""};function QV(){const{personas:{personas:t,updatePersona:s},completeOnboarding:o,onboardingCompleted:r}=rt(),{showToast:c}=gn(),d=ct(),[u,p]=y.useState(0),[m,g]=y.useState("claude-code"),[v,_]=y.useState(!1),b=t.find(j=>j.id==="claude-code"),x=y.useCallback(j=>{g(j),p(3)},[]),S=y.useCallback(()=>{const j=m;_(!0);const w=[];if(b&&j!==b.runtime){const C=C_[j]??"sonnet";w.push(s(b.id,void 0,void 0,void 0,j,C))}const T=t.find(C=>C.id===hy);if(T&&j!==T.runtime){const C=C_[j]??"sonnet";w.push(s(hy,void 0,void 0,void 0,j,C))}Promise.all(w).then(()=>o()).then(()=>{d("/",{replace:!0})},()=>{c("Failed to update runtime -- please try again","error"),_(!1)})},[m,b,t,s,o,d,c]);return r===!0?a.jsx(rs,{to:"/",replace:!0}):a.jsx("div",{className:Ye.wizard,"data-testid":"setup-wizard",children:a.jsxs("div",{className:Ye.container,children:[a.jsx(ls,{mode:"wait",children:a.jsxs(Nt.div,{initial:{opacity:0,x:40},animate:{opacity:1,x:0},exit:{opacity:0,x:-40},transition:{duration:.2,ease:"easeInOut"},children:[u===0&&a.jsx(FV,{onNext:()=>p(1)}),u===1&&a.jsx(ZV,{onNext:()=>p(2),onBack:()=>p(0)}),u===2&&a.jsx(YV,{currentRuntime:m,onFinish:x,onBack:()=>p(1),finishDisabled:!b}),u===3&&a.jsx(WV,{onFinish:S,onBack:()=>p(2),finishDisabled:v})]},u)}),a.jsx("div",{className:Ye.dots,children:Array.from({length:XV},(j,w)=>a.jsx("span",{className:Ye.dot,"data-active":w===u},w))})]})})}const eq="_root_zndgp_1",tq="_body_zndgp_7",nq="_main_zndgp_19",sq="_sidebarWrapper_zndgp_26",aq="_overlay_zndgp_51",Qr={root:eq,body:tq,main:nq,sidebarWrapper:sq,overlay:aq},iq=y.lazy(()=>aj(()=>import("./KnowledgePage-DgnY2L9q.js"),__vite__mapDeps([0,1,2,3,4])).then(t=>({default:t.KnowledgePage}))),gk=typeof window<"u"&&new URLSearchParams(window.location.search).has("mock");function oq({tabs:t}){const{connectionStatus:s,environments:{environments:o},sessions:{sessions:r},tasks:{tasks:c}}=rt(),{toasts:d,dismissToast:u}=gn(),p=Yt(),m=p$(),g=m!==void 0,[v,_]=y.useState(!1),b=y.useCallback(()=>_(x=>!x),[]);return y.useEffect(()=>{_(!1)},[p.pathname]),y.useEffect(()=>{if(!v)return;const x=S=>{S.key==="Escape"&&_(!1)};return document.addEventListener("keydown",x),()=>{document.removeEventListener("keydown",x)}},[v]),a.jsxs(a.Fragment,{children:[a.jsx(a5,{connectionStatus:s,environments:o,sessions:r,onToggleSidebar:g?b:void 0,sidebarOpen:v}),a.jsx(u5,{tabs:t}),a.jsxs("div",{className:Qr.body,children:[g&&a.jsx("div",{className:Qr.sidebarWrapper,"data-sidebar-open":v,children:a.jsx(v5,{content:m})}),g&&v&&a.jsx("div",{className:Qr.overlay,"data-testid":"drawer-overlay",onClick:()=>_(!1)}),a.jsxs("div",{className:Qr.main,children:[a.jsx(ma,{}),a.jsx(T5,{sessions:r,tasks:c,environments:o})]})]}),a.jsx(zO,{toasts:d,onDismiss:u}),a.jsx(rV,{})]})}function rq(){const{sessions:{lastSpawnedId:t},environments:{environments:s,operationError:o,clearOperationError:r},tasks:{tasks:c},connectionStatus:d,onboardingCompleted:u}=rt(),{pluginNames:p}=xh(),{showToast:m}=gn();SP(s,m),CP(c,m),jP(o,r,m);const g=ct(),v=Yt();if(y.useEffect(()=>{t&&!v.pathname.includes("/tasks/")&&g(Ld(t),{replace:!0})},[t,g,v.pathname]),d==="connected"&&u===!1)return a.jsx(rs,{to:"/setup",replace:!0});const _=K$(p);return a.jsx(f$,{children:a.jsxs("div",{className:Qr.root,children:[gk&&a.jsx(mC,{}),a.jsx(oq,{tabs:_})]})})}function Kp(){const{workspaceId:t}=Hn(),{workspaces:{workspaces:s}}=rt(),o=Yt(),r=s.find(g=>g.id===t),c=r!=null&&r.linkedEnvironmentIds?[...r.linkedEnvironmentIds].sort()[0]:void 0;if(!c)return s.length===0?void 0:a.jsx(rs,{to:"/environments",replace:!0});const d=encodeURIComponent(t),u=`/workspaces/${d}`,p=o.pathname.startsWith(u)?o.pathname.slice(u.length):"",m=`/environments/${encodeURIComponent(c)}/workspaces/${d}${p}${o.search}${o.hash}`;return a.jsx(rs,{to:m,replace:!0})}function lq(){const{pluginNames:t}=xh(),s=t.includes("orchestration"),o=t.includes("knowledge");return a.jsxs(Xw,{children:[a.jsx(we,{path:"setup",element:a.jsx(QV,{})}),a.jsxs(we,{element:a.jsx(rq,{}),children:[a.jsx(we,{index:!0,element:a.jsx(mU,{})}),a.jsx(we,{path:"sessions/new",element:a.jsx(CU,{})}),a.jsxs(we,{element:a.jsx(pV,{}),children:[a.jsx(we,{path:"chat",element:a.jsx(y_,{})}),a.jsx(we,{path:"chat/:streamId",element:a.jsx(y_,{})})]}),a.jsx(we,{path:"sessions/:sessionId",element:a.jsx(RU,{})}),o&&a.jsx(we,{element:a.jsx(fV,{}),children:a.jsx(we,{path:"knowledge",element:a.jsx(y.Suspense,{fallback:a.jsx(L1,{}),children:a.jsx(iq,{})})})}),s&&a.jsxs(we,{element:a.jsx(lV,{}),children:[a.jsx(we,{path:"tasks",element:a.jsx(fU,{})}),a.jsx(we,{path:"tasks/new",element:a.jsx(__,{})}),a.jsx(we,{path:"tasks/:taskId",element:a.jsx(Za,{})}),a.jsx(we,{path:"tasks/:taskId/edit",element:a.jsx(Za,{})}),a.jsx(we,{path:"tasks/:taskId/stream",element:a.jsx(Za,{})}),a.jsx(we,{path:"tasks/:taskId/findings",element:a.jsx(Za,{})})]}),s&&a.jsxs(we,{element:a.jsx(uV,{}),children:[a.jsx(we,{path:"findings",element:a.jsx(w_,{})}),a.jsx(we,{path:"findings/:findingId",element:a.jsx(N_,{})}),a.jsx(we,{path:"environments/:environmentId/workspaces/:workspaceId/findings",element:a.jsx(w_,{})}),a.jsx(we,{path:"environments/:environmentId/workspaces/:workspaceId/findings/:findingId",element:a.jsx(N_,{})})]}),a.jsxs(we,{element:a.jsx(cV,{}),children:[a.jsx(we,{path:"workspaces",element:a.jsx(rs,{to:"/environments",replace:!0})}),a.jsx(we,{path:"workspaces/new",element:a.jsx(ZU,{})}),a.jsx(we,{path:"workspaces/:workspaceId",element:a.jsx(Kp,{})}),a.jsx(we,{path:"workspaces/:workspaceId/tasks/:taskId",element:a.jsx(Kp,{})}),a.jsx(we,{path:"workspaces/:workspaceId/tasks/:taskId/*",element:a.jsx(Kp,{})}),a.jsx(we,{path:"environments/:environmentId/workspaces/:workspaceId",element:a.jsx(BU,{})}),a.jsx(we,{path:"environments/:environmentId/workspaces/:workspaceId/tasks/new",element:a.jsx(__,{})}),a.jsx(we,{path:"environments/:environmentId/workspaces/:workspaceId/tasks/:taskId",element:a.jsx(Za,{})}),a.jsx(we,{path:"environments/:environmentId/workspaces/:workspaceId/tasks/:taskId/edit",element:a.jsx(Za,{})}),a.jsx(we,{path:"environments/:environmentId/workspaces/:workspaceId/tasks/:taskId/stream",element:a.jsx(Za,{})}),a.jsx(we,{path:"environments/:environmentId/workspaces/:workspaceId/tasks/:taskId/findings",element:a.jsx(Za,{})}),a.jsxs(we,{path:"environments",element:a.jsx(eH,{}),children:[a.jsx(we,{index:!0,element:a.jsx(pU,{})}),a.jsx(we,{path:"new",element:a.jsx(YU,{})}),a.jsx(we,{path:":environmentId",element:a.jsx(AH,{})}),a.jsx(we,{path:":environmentId/edit",element:a.jsx(JU,{})})]})]}),a.jsx(we,{element:a.jsx(dV,{}),children:a.jsxs(we,{path:"settings",element:a.jsx(MH,{}),children:[a.jsx(we,{index:!0,element:a.jsx(rs,{to:"credentials",replace:!0})}),a.jsx(we,{path:"environments",element:a.jsx(rs,{to:"/environments",replace:!0})}),a.jsx(we,{path:"credentials",element:a.jsx(IH,{})}),a.jsx(we,{path:"tokens",element:a.jsx(rs,{to:"../credentials",replace:!0})}),a.jsx(we,{path:"personas",element:a.jsx(OH,{})}),a.jsx(we,{path:"personas/new",element:a.jsx(S_,{})}),a.jsx(we,{path:"personas/:personaId",element:a.jsx(S_,{})}),a.jsx(we,{path:"schedules",element:a.jsx(FH,{})}),a.jsx(we,{path:"schedules/new",element:a.jsx(j_,{})}),a.jsx(we,{path:"schedules/:scheduleId",element:a.jsx(j_,{})}),a.jsx(we,{path:"appearance",element:a.jsx(nV,{})}),a.jsx(we,{path:"shortcuts",element:a.jsx(iV,{})}),a.jsx(we,{path:"plugins",element:a.jsx(oV,{})}),a.jsx(we,{path:"about",element:a.jsx(aV,{})})]})}),a.jsx(we,{path:"*",element:a.jsx(rs,{to:"/",replace:!0})})]})]})}const cq=1e4;function dq(){const{onboardingCompleted:t}=rt(),[s,o]=y.useState(!1);y.useEffect(()=>{if(t!==void 0)return;const c=setTimeout(()=>o(!0),cq);return()=>clearTimeout(c)},[t]);const r=t===void 0&&!s;return a.jsx(ls,{mode:"wait",children:r?a.jsx(Nt.div,{initial:{opacity:1},exit:{opacity:0},transition:{duration:.25},children:a.jsx(L1,{})},"splash"):a.jsx(Nt.div,{initial:{opacity:0},animate:{opacity:1},transition:{duration:.25},style:{minHeight:"100vh"},children:a.jsx(SN,{basename:"/".replace(/\/$/,""),children:a.jsx(lq,{})})},"app")})}function uq(){const t=gk?U$:kP;return a.jsx(q$,{children:a.jsx(u$,{children:a.jsx(r$,{children:a.jsx(t,{children:a.jsx(dq,{})})})})})}tj.createRoot(document.getElementById("root")).render(a.jsx(y.StrictMode,{children:a.jsx(uq,{})}));export{xs as B,ix as K,rt as a,Qp as f,Ld as s,$n as t,ct as u};
744
+ $\`Summarize the current tasks.\`;`,ariaLabel:"Persona script","data-testid":"persona-script-editor"})]}),I==="agent"&&a.jsxs("div",{children:[a.jsx("label",{children:"Allowed MCP Tools"}),a.jsx(l_,{selectedTools:X,onChange:oe=>{H(oe),ke(()=>c(t.id,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,oe),()=>{},"MCP tools updated","Failed to update MCP tools").catch(()=>{})}})]})]}),!xe&&!re&&a.jsx("p",{style:{fontSize:"var(--font-size-xs)",color:"var(--text-tertiary)",marginTop:"var(--space-xs)"},children:"Only agent personas with a runtime and model can be set as app default."})]}):null,a.jsx(Ls,{isOpen:Q,title:"Delete Persona?",description:`"${t==null?void 0:t.name}" will be permanently removed.`,confirmLabel:"Delete",onConfirm:_e,onCancel:()=>he(!1)})]})}function FH(){const{schedules:{schedules:t,deleteSchedule:s,updateSchedule:o},personas:{personas:r}}=rt(),{showToast:c}=gn(),d=ct();return a.jsx(D7,{schedules:t,personas:r,onDeleteSchedule:async u=>{try{await s(u)}catch(p){throw console.error("Failed to delete schedule",{scheduleId:u,error:p}),c("Failed to delete schedule","error"),p}},onToggleEnabled:async(u,p)=>{try{return await o(u,p)}catch(m){throw console.error("Failed to update schedule",{scheduleId:u,error:m}),c("Failed to update schedule","error"),m}},onNavigateToNew:()=>d(LN),onNavigateToSchedule:u=>d(sx(u))})}const ZH="_container_1g4qh_1",KH="_form_1g4qh_7",YH="_formActions_1g4qh_66",JH="_editableSection_1g4qh_73",WH="_helperText_1g4qh_84",XH="_metaSection_1g4qh_90",QH="_optional_1g4qh_108",eV="_readonlyValue_1g4qh_113",Bn={container:ZH,form:KH,formActions:YH,editableSection:JH,helperText:WH,metaSection:XH,optional:QH,readonlyValue:eV};function j_(){const{scheduleId:t}=Hn(),s=ct(),{showToast:o}=gn(),{schedules:{schedules:r,schedulesLoading:c,createSchedule:d,updateSchedule:u,deleteSchedule:p},personas:{personas:m},workspaces:{workspaces:g}}=rt(),v=t===void 0,_=v?void 0:r.find(x=>x.id===t);if(!v&&!c&&r.length>0&&!_)return a.jsx(rs,{to:lp,replace:!0});const b=[{label:"Settings",url:Ei},{label:"Schedules",url:lp},{label:v?"New Schedule":(_==null?void 0:_.title)??"Schedule",url:void 0}];return a.jsxs("div",{className:Bn.container,children:[a.jsx(xs,{segments:b}),a.jsx(tV,{existing:_,isNew:v,personas:m,workspaces:g,onCreateSchedule:d,onUpdateSchedule:u,onDeleteSchedule:p,onDone:()=>{s(lp)},showToast:o})]})}function tV({existing:t,isNew:s,personas:o,workspaces:r,onCreateSchedule:c,onUpdateSchedule:d,onDeleteSchedule:u,onDone:p,showToast:m}){var L;const g=ct(),[v,_]=y.useState((t==null?void 0:t.title)??""),[b,x]=y.useState((t==null?void 0:t.description)??""),[S,j]=y.useState((t==null?void 0:t.scheduleExpression)??""),[w,T]=y.useState((t==null?void 0:t.personaId)??""),[C,D]=y.useState((t==null?void 0:t.workspaceId)??""),[O,A]=y.useState(!1),[I,$]=y.useState(null);y.useEffect(()=>{s||t&&I===null&&(_(t.title),x(t.description),j(t.scheduleExpression),T(t.personaId),D(t.workspaceId))},[s,t,I]);const B=!s&&t===void 0,P=s&&v.trim().length>0&&S.trim().length>0&&w.length>0,X=o.map(E=>({value:E.id,label:E.name})),H=[{value:"",label:"System-level (no workspace)"},...r.map(E=>({value:E.id,label:E.name}))],Q=E=>{E.preventDefault(),P&&c(v,b,S,w,C||void 0).then(J=>{m("Schedule created","success"),g(sx(J.id),{replace:!0})},()=>{m("Failed to create schedule","error")})},he=(E,J)=>{t&&d(t.id,{[E]:J}).then(()=>{m("Schedule updated","success"),E==="title"&&_(String(J)),E==="description"&&x(String(J)),E==="scheduleExpression"&&j(String(J)),E==="personaId"&&T(String(J))},()=>{m("Failed to update schedule","error")})},W=()=>{if(!t)return;const E=!t.enabled;d(t.id,{enabled:E}).then(()=>{m(E?"Schedule enabled":"Schedule disabled","success")},()=>{m("Failed to update schedule","error")})},ie=()=>{t&&u(t.id).then(()=>{m("Schedule deleted","success"),p()},()=>{m("Failed to delete schedule","error")})};return a.jsxs(a.Fragment,{children:[B?a.jsxs("div",{className:Bn.form,children:[a.jsx("h3",{children:"Edit Schedule"}),a.jsx("p",{children:"Loading schedule..."})]}):s?a.jsxs("form",{onSubmit:Q,className:Bn.form,children:[a.jsx("h3",{children:"Create Schedule"}),a.jsxs("label",{children:["Title",a.jsx("input",{type:"text",value:v,onChange:E=>_(E.target.value),placeholder:"e.g. Nightly Review",required:!0,"data-testid":"schedule-detail-title"})]}),a.jsxs("label",{children:["Description ",a.jsx("span",{className:Bn.optional,children:"(optional)"}),a.jsx("input",{type:"text",value:b,onChange:E=>x(E.target.value),placeholder:"Brief description...","data-testid":"schedule-detail-description"})]}),a.jsxs("label",{children:["Schedule Expression",a.jsx("input",{type:"text",value:S,onChange:E=>j(E.target.value),placeholder:"e.g. 30s, 5m, 1h, or 0 9 * * MON",required:!0,"data-testid":"schedule-detail-expression"}),a.jsxs("p",{className:Bn.helperText,children:["Interval: ",a.jsx("code",{children:"30s"}),", ",a.jsx("code",{children:"5m"}),", ",a.jsx("code",{children:"1h"}),", ",a.jsx("code",{children:"1d"})," (min 10s)  |  Cron: ",a.jsx("code",{children:"0 9 * * MON"})," (standard 5-field cron syntax)"]})]}),a.jsxs("label",{children:["Persona",a.jsxs("select",{value:w,onChange:E=>T(E.target.value),required:!0,"data-testid":"schedule-detail-persona",children:[a.jsx("option",{value:"",children:"Select a persona..."}),X.map(E=>a.jsx("option",{value:E.value,children:E.label},E.value))]})]}),a.jsxs("label",{children:["Workspace ",a.jsx("span",{className:Bn.optional,children:"(optional)"}),a.jsx("select",{value:C,onChange:E=>D(E.target.value),"data-testid":"schedule-detail-workspace",children:H.map(E=>a.jsx("option",{value:E.value,children:E.label},E.value))})]}),a.jsxs("div",{className:Bn.formActions,children:[a.jsx(on,{type:"submit",variant:"primary",size:"md",disabled:!P,"data-testid":"schedule-detail-save",children:"Create"}),a.jsx(on,{type:"button",variant:"outline",size:"md",onClick:p,"data-testid":"schedule-detail-cancel",children:"Cancel"})]})]}):t?a.jsxs("div",{className:Bn.form,children:[a.jsx("h3",{children:"Edit Schedule"}),a.jsxs("div",{className:Bn.formActions,children:[a.jsx(on,{type:"button",variant:"outline",size:"md",onClick:p,"data-testid":"schedule-detail-cancel",children:"Back to Schedules"}),a.jsx(on,{type:"button",variant:t.enabled?"ghost":"primary",size:"md",onClick:W,"data-testid":"schedule-detail-toggle",children:t.enabled?"Disable":"Enable"}),a.jsx(on,{type:"button",variant:"danger",size:"md",onClick:()=>A(!0),"data-testid":"schedule-detail-delete",children:"Delete"})]}),a.jsxs("div",{className:Bn.editableSection,children:[a.jsxs("label",{children:["Title",a.jsx(Zt,{value:v,onSave:E=>{he("title",E)},validate:E=>E.trim()?void 0:"Title is required",fieldId:"schedule-title",activeFieldId:I,onActivate:$,ariaLabel:"Schedule title","data-testid":"schedule-detail-title"})]}),a.jsxs("label",{children:["Description",a.jsx(Zt,{value:b,onSave:E=>{he("description",E)},fieldId:"schedule-description",activeFieldId:I,onActivate:$,placeholder:"Brief description...",ariaLabel:"Schedule description","data-testid":"schedule-detail-description"})]}),a.jsxs("label",{children:["Schedule Expression",a.jsx(Zt,{value:S,onSave:E=>{he("scheduleExpression",E)},validate:E=>E.trim()?void 0:"Schedule expression is required",fieldId:"schedule-expression",activeFieldId:I,onActivate:$,placeholder:"e.g. 30s, 5m, 1h, or 0 9 * * MON",ariaLabel:"Schedule expression","data-testid":"schedule-detail-expression"})]}),a.jsxs("label",{children:["Persona",a.jsx(Td,{value:w,onSave:E=>{he("personaId",E)},options:X,fieldId:"schedule-persona",activeFieldId:I,onActivate:$,ariaLabel:"Schedule persona","data-testid":"schedule-detail-persona"})]}),a.jsxs("label",{children:["Workspace ",a.jsx("span",{className:Bn.optional,children:"(optional — set at creation)"}),a.jsx("span",{className:Bn.readonlyValue,"data-testid":"schedule-detail-workspace",children:((L=r.find(E=>E.id===t.workspaceId))==null?void 0:L.name)??"System-level (no workspace)"})]})]}),a.jsxs("div",{className:Bn.metaSection,children:[t.lastRunAt?a.jsxs("span",{children:["Last run: ",Ho(t.lastRunAt)]}):a.jsx("span",{children:"Last run: Never"}),t.enabled&&t.nextRunAt?a.jsxs("span",{children:["Next run: ",q1(t.nextRunAt)]}):null,t.runCount>0&&a.jsxs("span",{children:["Total runs: ",t.runCount]}),a.jsxs("span",{children:["Created: ",Ho(t.createdAt)]})]})]}):null,a.jsx(Ls,{isOpen:O,title:"Delete Schedule?",description:`"${t==null?void 0:t.title}" will be permanently removed. Tasks already created by this schedule will not be affected.`,confirmLabel:"Delete",onConfirm:ie,onCancel:()=>A(!1)})]})}function nV(){const{themeId:t,resolvedThemeId:s,setTheme:o,preferSystem:r,setPreferSystem:c}=ak();return a.jsx(YB,{themeId:t,resolvedThemeId:s,onSetTheme:o,preferSystem:r,onSetPreferSystem:c})}function sV(){const[t,s]=y.useState(void 0);return y.useEffect(()=>{let o=!1;return(async()=>{try{const c=await Fe.getVersionStatus({});o||s({currentVersion:c.currentVersion,latestVersion:c.latestVersion,updateAvailable:c.updateAvailable,isDocker:c.isDocker})}catch{}})().catch(()=>{}),()=>{o=!0}},[]),t}function aV(){const{connectionStatus:t,environments:{environments:s},sessions:{sessions:o}}=rt(),r=sV();return a.jsxs(a.Fragment,{children:[r&&a.jsx(YO,{currentVersion:r.currentVersion,latestVersion:r.latestVersion,updateAvailable:r.updateAvailable,isDocker:r.isDocker}),a.jsx(XB,{connectionStatus:t,environments:s,sessions:o})]})}function iV(){return a.jsx(U8,{})}function oV(){const{plugins:{plugins:t,pluginsLoading:s,setPluginEnabled:o}}=rt();return a.jsx(f8,{plugins:t,loading:s,onSetPluginEnabled:(r,c)=>{o(r,c).catch(()=>{})}})}const T_=zi();function rV(){const t=ct();return la({key:"?"},()=>{t(zN)}),la({key:"n"},()=>{t(T_)}),la({key:"N"},()=>{t(T_)}),a.jsx(a.Fragment,{})}function Ko(t){const s=m$();y.useLayoutEffect(()=>(s(t),()=>{s(void 0)}),[t,s])}function lV(){const{workspaces:{workspaces:t},tasks:{tasks:s}}=rt(),o=y.useMemo(()=>a.jsx(TO,{workspaces:t,tasks:s}),[t,s]);return Ko(o),a.jsx(ma,{})}function cV(){const{environments:{environments:t}}=rt(),s=y.useMemo(()=>a.jsx(O5,{environments:t}),[t]);return Ko(s),a.jsx(ma,{})}function dV(){const t=y.useMemo(()=>a.jsx(B7,{}),[]);return Ko(t),a.jsx(ma,{})}function uV(){const{findings:{findings:t,loadFindings:s,loadAllFindings:o}}=rt(),{workspaceId:r,environmentId:c}=Hn();y.useEffect(()=>{r?s(r).catch(()=>{}):o().catch(()=>{})},[r,s,o]);const d=y.useMemo(()=>a.jsx(F5,{findings:t,workspaceId:r,environmentId:c}),[t,r,c]);return Ko(d),a.jsx(ma,{})}function fV(){const{knowledge:t,workspaces:{workspaces:s}}=rt(),o=y.useCallback(p=>{t.search(p).catch(()=>{})},[t]),r=y.useCallback(()=>{t.clearSearch()},[t]),c=y.useCallback(p=>{t.selectNode(p).catch(()=>{})},[t]),d=y.useCallback(p=>{t.loadRecent(p||void 0).catch(()=>{})},[t]),u=y.useMemo(()=>a.jsx(GI,{nodes:t.graphData.nodes,workspaces:s,loading:t.loading,searchQuery:t.searchQuery,onSearch:o,onClearSearch:r,onSelectNode:c,onWorkspaceChange:d}),[t,s,o,r,c,d]);return Ko(u),a.jsx(ma,{})}function pV(){const{streams:{streams:t,streamsLoading:s,streamsLoadError:o,streamsLoadedOnce:r,loadStreams:c}}=rt(),d=y.useCallback(()=>{c().catch(()=>{})},[c]),u=y.useMemo(()=>a.jsx(K7,{streams:t,loading:s,streamsLoadError:o,streamsLoadedOnce:r,onRefresh:d}),[t,s,o,r,d]);return Ko(u),a.jsx(ma,{})}const mV="_container_ce571_1",hV="_title_ce571_6",Cd={container:mV,title:hV};function gV(){return a.jsxs("div",{className:Cd.container,"aria-hidden":"true",children:[a.jsx("h1",{className:Cd.title,children:"Findings"}),a.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"var(--space-sm)"},children:Array.from({length:4},(t,s)=>a.jsx(jd,{lines:3},s))})]})}function w_(){const{environmentId:t,workspaceId:s}=Hn(),{findings:{findings:o,findingsLoading:r,loadFindings:c},workspaces:{workspaces:d},environments:{environments:u}}=rt(),p=ct();y.useEffect(()=>{s&&c(s).catch(()=>{})},[s,c]);const m=y.useCallback(v=>{p(Qp(v,s,t))},[p,s,t]);if(r)return a.jsx(gV,{});const g=s&&t?uk("Findings",s,t,d,u).slice(0,-1):w$();return a.jsxs("div",{className:Cd.container,"data-testid":"findings-list-page",children:[a.jsx(xs,{segments:g}),a.jsx("h1",{className:Cd.title,children:"Findings"}),a.jsx(Y1,{findings:o,onFindingClick:m})]})}const vV="_container_1wwpb_1",yV="_notFound_1wwpb_6",bV="_header_1wwpb_12",_V="_categoryBadge_1wwpb_19",xV="_title_1wwpb_28",kV="_content_1wwpb_35",SV="_tags_1wwpb_77",jV="_tag_1wwpb_77",TV="_meta_1wwpb_92",wV="_metaTimestamp_1wwpb_100",NV="_metaLink_1wwpb_105",xn={container:vV,notFound:yV,header:bV,categoryBadge:_V,title:xV,content:kV,tags:SV,tag:jV,meta:TV,metaTimestamp:wV,metaLink:NV};function N_(){const{findingId:t,environmentId:s,workspaceId:o}=Hn(),{findings:{selectedFinding:r,findingLoading:c,loadFinding:d},workspaces:{workspaces:u},environments:{environments:p}}=rt(),m=ct();if(y.useEffect(()=>{t&&d(t).catch(()=>{})},[t,d]),c)return a.jsx("div",{className:xn.container,"data-testid":"finding-detail-page",children:a.jsx("div",{className:xn.notFound,children:"Loading..."})});if(!r)return a.jsx("div",{className:xn.container,"data-testid":"finding-detail-page",children:a.jsx("div",{className:xn.notFound,children:"Finding not found."})});const g=uk(r.title,o,s,u,p),v=wd(r.category);return a.jsxs("div",{className:xn.container,"data-testid":"finding-detail-page",children:[a.jsx(xs,{segments:g}),a.jsxs("div",{className:xn.header,children:[a.jsx("span",{className:xn.categoryBadge,style:{background:v.bg,color:v.text},children:r.category}),a.jsx("h1",{className:xn.title,children:r.title})]}),r.content&&a.jsx("div",{className:xn.content,children:a.jsx(Ad,{remarkPlugins:[Dd],children:r.content})}),r.tags.length>0&&a.jsx("div",{className:xn.tags,children:r.tags.map(_=>a.jsx("span",{className:xn.tag,children:_},_))}),a.jsxs("div",{className:xn.meta,children:[a.jsx("span",{className:xn.metaTimestamp,title:r.createdAt,children:Ho(r.createdAt)}),r.taskId&&a.jsx("button",{type:"button",className:xn.metaLink,onClick:()=>{m($n(r.taskId))},children:"View Task"}),r.sessionId&&a.jsx("button",{type:"button",className:xn.metaLink,onClick:()=>{m(Ld(r.sessionId))},children:"View Session"})]})]})}const CV="_wizard_1260s_1",EV="_container_1260s_10",AV="_stepContent_1260s_19",DV="_logoArea_1260s_28",RV="_logoImage_1260s_32",MV="_heading_1260s_41",IV="_tagline_1260s_49",OV="_subtitle_1260s_56",BV="_featureList_1260s_64",LV="_runtimeGrid_1260s_89",zV="_runtimeCard_1260s_101",$V="_runtimeName_1260s_133",PV="_runtimeDescription_1260s_139",UV="_buttonRow_1260s_144",HV="_primaryButton_1260s_151",VV="_ghostButton_1260s_185",qV="_dots_1260s_213",GV="_dot_1260s_213",Ye={wizard:CV,container:EV,stepContent:AV,logoArea:DV,logoImage:RV,heading:MV,tagline:IV,subtitle:OV,featureList:BV,runtimeGrid:LV,runtimeCard:zV,runtimeName:$V,runtimeDescription:PV,buttonRow:UV,primaryButton:HV,ghostButton:VV,dots:qV,dot:GV};function FV({onNext:t}){return a.jsxs("div",{className:Ye.stepContent,"data-testid":"setup-welcome",children:[a.jsx("div",{className:Ye.logoArea,children:a.jsx("img",{src:"/grackle-logo.png",alt:"Grackle",className:Ye.logoImage})}),a.jsx("h1",{className:Ye.heading,children:"Welcome to Grackle"}),a.jsx("p",{className:Ye.tagline,children:"Multi-agent orchestration for software teams"}),a.jsx("button",{type:"button",className:Ye.primaryButton,onClick:t,"data-testid":"setup-get-started",children:"Get Started"})]})}function ZV({onNext:t,onBack:s}){return a.jsxs("div",{className:Ye.stepContent,"data-testid":"setup-about",children:[a.jsx("h2",{className:Ye.heading,children:"What is Grackle?"}),a.jsxs("ul",{className:Ye.featureList,children:[a.jsx("li",{children:"Run Claude, Copilot, and Codex agents side by side"}),a.jsx("li",{children:"Provision and control dev environments — SSH, Codespaces, or local"}),a.jsx("li",{children:"Organize work into workspaces with agent-executable tasks"}),a.jsx("li",{children:"Customize agent behavior with personas, tools, and MCP servers"}),a.jsx("li",{children:"Live-stream agent sessions with full terminal replay"})]}),a.jsxs("div",{className:Ye.buttonRow,children:[a.jsx("button",{type:"button",className:Ye.ghostButton,onClick:s,children:"Back"}),a.jsx("button",{type:"button",className:Ye.primaryButton,onClick:t,"data-testid":"setup-about-next",children:"Next"})]})]})}const KV=[{id:"claude-code",name:"Claude Code",description:"Anthropic's agentic coding tool"},{id:"copilot",name:"Copilot Coding Agent",description:"GitHub's AI pair programmer"},{id:"codex",name:"Codex CLI",description:"OpenAI's coding agent"},{id:"goose",name:"Goose",description:"Block's open-source AI coding agent"}];function YV({currentRuntime:t,onFinish:s,onBack:o,finishDisabled:r}){const[c,d]=y.useState(t||"claude-code");return y.useEffect(()=>{t&&d(t)},[t]),a.jsxs("div",{className:Ye.stepContent,"data-testid":"setup-runtime",children:[a.jsx("h2",{className:Ye.heading,children:"Choose Your Runtime"}),a.jsx("p",{className:Ye.subtitle,children:"Select the primary agent runtime for your workspace. You can change this later."}),a.jsx("div",{className:Ye.runtimeGrid,children:KV.map(u=>a.jsxs("button",{type:"button",className:Ye.runtimeCard,"data-selected":c===u.id,"aria-pressed":c===u.id,"data-testid":`runtime-card-${u.id}`,onClick:()=>d(u.id),children:[a.jsx("span",{className:Ye.runtimeName,children:u.name}),a.jsx("span",{className:Ye.runtimeDescription,children:u.description})]},u.id))}),a.jsxs("div",{className:Ye.buttonRow,children:[a.jsx("button",{type:"button",className:Ye.ghostButton,onClick:o,children:"Back"}),a.jsx("button",{type:"button",className:Ye.primaryButton,onClick:()=>{s(c)},disabled:r,"data-testid":"setup-runtime-next",children:"Next"})]})]})}function JV(){return typeof Notification<"u"}function WV({onFinish:t,onBack:s,finishDisabled:o}){const r=JV(),c=r&&Notification.permission!=="default";function d(){r&&Notification.requestPermission().catch(()=>{}),t()}return a.jsxs("div",{className:Ye.stepContent,"data-testid":"setup-notifications",children:[a.jsx("h2",{className:Ye.heading,children:"Stay in the Loop"}),a.jsx("p",{className:Ye.subtitle,children:"Grackle can send you a browser notification when an agent needs your input, so you never miss an important moment."}),c?a.jsx("p",{className:Ye.subtitle,children:Notification.permission==="granted"?"Notifications are already enabled.":"Notifications have been blocked. You can change this in your browser settings."}):null,a.jsxs("div",{className:Ye.buttonRow,children:[a.jsx("button",{type:"button",className:Ye.ghostButton,onClick:s,disabled:o,children:"Back"}),!c&&r?a.jsxs(a.Fragment,{children:[a.jsx("button",{type:"button",className:Ye.ghostButton,onClick:t,disabled:o,"data-testid":"setup-notifications-skip",children:"Skip"}),a.jsx("button",{type:"button",className:Ye.primaryButton,onClick:d,disabled:o,"data-testid":"setup-notifications-enable",children:"Enable Notifications"})]}):a.jsx("button",{type:"button",className:Ye.primaryButton,onClick:t,disabled:o,"data-testid":"setup-finish",children:"Finish"})]})]})}const XV=4,C_={"claude-code":"sonnet",copilot:"gpt-4o",codex:"o3",goose:""};function QV(){const{personas:{personas:t,updatePersona:s},completeOnboarding:o,onboardingCompleted:r}=rt(),{showToast:c}=gn(),d=ct(),[u,p]=y.useState(0),[m,g]=y.useState("claude-code"),[v,_]=y.useState(!1),b=t.find(j=>j.id==="claude-code"),x=y.useCallback(j=>{g(j),p(3)},[]),S=y.useCallback(()=>{const j=m;_(!0);const w=[];if(b&&j!==b.runtime){const C=C_[j]??"sonnet";w.push(s(b.id,void 0,void 0,void 0,j,C))}const T=t.find(C=>C.id===hy);if(T&&j!==T.runtime){const C=C_[j]??"sonnet";w.push(s(hy,void 0,void 0,void 0,j,C))}Promise.all(w).then(()=>o()).then(()=>{d("/",{replace:!0})},()=>{c("Failed to update runtime -- please try again","error"),_(!1)})},[m,b,t,s,o,d,c]);return r===!0?a.jsx(rs,{to:"/",replace:!0}):a.jsx("div",{className:Ye.wizard,"data-testid":"setup-wizard",children:a.jsxs("div",{className:Ye.container,children:[a.jsx(ls,{mode:"wait",children:a.jsxs(Nt.div,{initial:{opacity:0,x:40},animate:{opacity:1,x:0},exit:{opacity:0,x:-40},transition:{duration:.2,ease:"easeInOut"},children:[u===0&&a.jsx(FV,{onNext:()=>p(1)}),u===1&&a.jsx(ZV,{onNext:()=>p(2),onBack:()=>p(0)}),u===2&&a.jsx(YV,{currentRuntime:m,onFinish:x,onBack:()=>p(1),finishDisabled:!b}),u===3&&a.jsx(WV,{onFinish:S,onBack:()=>p(2),finishDisabled:v})]},u)}),a.jsx("div",{className:Ye.dots,children:Array.from({length:XV},(j,w)=>a.jsx("span",{className:Ye.dot,"data-active":w===u},w))})]})})}const eq="_root_zndgp_1",tq="_body_zndgp_7",nq="_main_zndgp_19",sq="_sidebarWrapper_zndgp_26",aq="_overlay_zndgp_51",Qr={root:eq,body:tq,main:nq,sidebarWrapper:sq,overlay:aq},iq=y.lazy(()=>aj(()=>import("./KnowledgePage-DC4SWTgI.js"),__vite__mapDeps([0,1,2,3,4])).then(t=>({default:t.KnowledgePage}))),gk=typeof window<"u"&&new URLSearchParams(window.location.search).has("mock");function oq({tabs:t}){const{connectionStatus:s,environments:{environments:o},sessions:{sessions:r},tasks:{tasks:c}}=rt(),{toasts:d,dismissToast:u}=gn(),p=Yt(),m=p$(),g=m!==void 0,[v,_]=y.useState(!1),b=y.useCallback(()=>_(x=>!x),[]);return y.useEffect(()=>{_(!1)},[p.pathname]),y.useEffect(()=>{if(!v)return;const x=S=>{S.key==="Escape"&&_(!1)};return document.addEventListener("keydown",x),()=>{document.removeEventListener("keydown",x)}},[v]),a.jsxs(a.Fragment,{children:[a.jsx(a5,{connectionStatus:s,environments:o,sessions:r,onToggleSidebar:g?b:void 0,sidebarOpen:v}),a.jsx(u5,{tabs:t}),a.jsxs("div",{className:Qr.body,children:[g&&a.jsx("div",{className:Qr.sidebarWrapper,"data-sidebar-open":v,children:a.jsx(v5,{content:m})}),g&&v&&a.jsx("div",{className:Qr.overlay,"data-testid":"drawer-overlay",onClick:()=>_(!1)}),a.jsxs("div",{className:Qr.main,children:[a.jsx(ma,{}),a.jsx(T5,{sessions:r,tasks:c,environments:o})]})]}),a.jsx(zO,{toasts:d,onDismiss:u}),a.jsx(rV,{})]})}function rq(){const{sessions:{lastSpawnedId:t},environments:{environments:s,operationError:o,clearOperationError:r},tasks:{tasks:c},connectionStatus:d,onboardingCompleted:u}=rt(),{pluginNames:p}=xh(),{showToast:m}=gn();SP(s,m),CP(c,m),jP(o,r,m);const g=ct(),v=Yt();if(y.useEffect(()=>{t&&!v.pathname.includes("/tasks/")&&g(Ld(t),{replace:!0})},[t,g,v.pathname]),d==="connected"&&u===!1)return a.jsx(rs,{to:"/setup",replace:!0});const _=K$(p);return a.jsx(f$,{children:a.jsxs("div",{className:Qr.root,children:[gk&&a.jsx(mC,{}),a.jsx(oq,{tabs:_})]})})}function Kp(){const{workspaceId:t}=Hn(),{workspaces:{workspaces:s}}=rt(),o=Yt(),r=s.find(g=>g.id===t),c=r!=null&&r.linkedEnvironmentIds?[...r.linkedEnvironmentIds].sort()[0]:void 0;if(!c)return s.length===0?void 0:a.jsx(rs,{to:"/environments",replace:!0});const d=encodeURIComponent(t),u=`/workspaces/${d}`,p=o.pathname.startsWith(u)?o.pathname.slice(u.length):"",m=`/environments/${encodeURIComponent(c)}/workspaces/${d}${p}${o.search}${o.hash}`;return a.jsx(rs,{to:m,replace:!0})}function lq(){const{pluginNames:t}=xh(),s=t.includes("orchestration"),o=t.includes("knowledge");return a.jsxs(Xw,{children:[a.jsx(we,{path:"setup",element:a.jsx(QV,{})}),a.jsxs(we,{element:a.jsx(rq,{}),children:[a.jsx(we,{index:!0,element:a.jsx(mU,{})}),a.jsx(we,{path:"sessions/new",element:a.jsx(CU,{})}),a.jsxs(we,{element:a.jsx(pV,{}),children:[a.jsx(we,{path:"chat",element:a.jsx(y_,{})}),a.jsx(we,{path:"chat/:streamId",element:a.jsx(y_,{})})]}),a.jsx(we,{path:"sessions/:sessionId",element:a.jsx(RU,{})}),o&&a.jsx(we,{element:a.jsx(fV,{}),children:a.jsx(we,{path:"knowledge",element:a.jsx(y.Suspense,{fallback:a.jsx(L1,{}),children:a.jsx(iq,{})})})}),s&&a.jsxs(we,{element:a.jsx(lV,{}),children:[a.jsx(we,{path:"tasks",element:a.jsx(fU,{})}),a.jsx(we,{path:"tasks/new",element:a.jsx(__,{})}),a.jsx(we,{path:"tasks/:taskId",element:a.jsx(Za,{})}),a.jsx(we,{path:"tasks/:taskId/edit",element:a.jsx(Za,{})}),a.jsx(we,{path:"tasks/:taskId/stream",element:a.jsx(Za,{})}),a.jsx(we,{path:"tasks/:taskId/findings",element:a.jsx(Za,{})})]}),s&&a.jsxs(we,{element:a.jsx(uV,{}),children:[a.jsx(we,{path:"findings",element:a.jsx(w_,{})}),a.jsx(we,{path:"findings/:findingId",element:a.jsx(N_,{})}),a.jsx(we,{path:"environments/:environmentId/workspaces/:workspaceId/findings",element:a.jsx(w_,{})}),a.jsx(we,{path:"environments/:environmentId/workspaces/:workspaceId/findings/:findingId",element:a.jsx(N_,{})})]}),a.jsxs(we,{element:a.jsx(cV,{}),children:[a.jsx(we,{path:"workspaces",element:a.jsx(rs,{to:"/environments",replace:!0})}),a.jsx(we,{path:"workspaces/new",element:a.jsx(ZU,{})}),a.jsx(we,{path:"workspaces/:workspaceId",element:a.jsx(Kp,{})}),a.jsx(we,{path:"workspaces/:workspaceId/tasks/:taskId",element:a.jsx(Kp,{})}),a.jsx(we,{path:"workspaces/:workspaceId/tasks/:taskId/*",element:a.jsx(Kp,{})}),a.jsx(we,{path:"environments/:environmentId/workspaces/:workspaceId",element:a.jsx(BU,{})}),a.jsx(we,{path:"environments/:environmentId/workspaces/:workspaceId/tasks/new",element:a.jsx(__,{})}),a.jsx(we,{path:"environments/:environmentId/workspaces/:workspaceId/tasks/:taskId",element:a.jsx(Za,{})}),a.jsx(we,{path:"environments/:environmentId/workspaces/:workspaceId/tasks/:taskId/edit",element:a.jsx(Za,{})}),a.jsx(we,{path:"environments/:environmentId/workspaces/:workspaceId/tasks/:taskId/stream",element:a.jsx(Za,{})}),a.jsx(we,{path:"environments/:environmentId/workspaces/:workspaceId/tasks/:taskId/findings",element:a.jsx(Za,{})}),a.jsxs(we,{path:"environments",element:a.jsx(eH,{}),children:[a.jsx(we,{index:!0,element:a.jsx(pU,{})}),a.jsx(we,{path:"new",element:a.jsx(YU,{})}),a.jsx(we,{path:":environmentId",element:a.jsx(AH,{})}),a.jsx(we,{path:":environmentId/edit",element:a.jsx(JU,{})})]})]}),a.jsx(we,{element:a.jsx(dV,{}),children:a.jsxs(we,{path:"settings",element:a.jsx(MH,{}),children:[a.jsx(we,{index:!0,element:a.jsx(rs,{to:"credentials",replace:!0})}),a.jsx(we,{path:"environments",element:a.jsx(rs,{to:"/environments",replace:!0})}),a.jsx(we,{path:"credentials",element:a.jsx(IH,{})}),a.jsx(we,{path:"tokens",element:a.jsx(rs,{to:"../credentials",replace:!0})}),a.jsx(we,{path:"personas",element:a.jsx(OH,{})}),a.jsx(we,{path:"personas/new",element:a.jsx(S_,{})}),a.jsx(we,{path:"personas/:personaId",element:a.jsx(S_,{})}),a.jsx(we,{path:"schedules",element:a.jsx(FH,{})}),a.jsx(we,{path:"schedules/new",element:a.jsx(j_,{})}),a.jsx(we,{path:"schedules/:scheduleId",element:a.jsx(j_,{})}),a.jsx(we,{path:"appearance",element:a.jsx(nV,{})}),a.jsx(we,{path:"shortcuts",element:a.jsx(iV,{})}),a.jsx(we,{path:"plugins",element:a.jsx(oV,{})}),a.jsx(we,{path:"about",element:a.jsx(aV,{})})]})}),a.jsx(we,{path:"*",element:a.jsx(rs,{to:"/",replace:!0})})]})]})}const cq=1e4;function dq(){const{onboardingCompleted:t}=rt(),[s,o]=y.useState(!1);y.useEffect(()=>{if(t!==void 0)return;const c=setTimeout(()=>o(!0),cq);return()=>clearTimeout(c)},[t]);const r=t===void 0&&!s;return a.jsx(ls,{mode:"wait",children:r?a.jsx(Nt.div,{initial:{opacity:1},exit:{opacity:0},transition:{duration:.25},children:a.jsx(L1,{})},"splash"):a.jsx(Nt.div,{initial:{opacity:0},animate:{opacity:1},transition:{duration:.25},style:{minHeight:"100vh"},children:a.jsx(SN,{basename:"/".replace(/\/$/,""),children:a.jsx(lq,{})})},"app")})}function uq(){const t=gk?U$:kP;return a.jsx(q$,{children:a.jsx(u$,{children:a.jsx(r$,{children:a.jsx(t,{children:a.jsx(dq,{})})})})})}tj.createRoot(document.getElementById("root")).render(a.jsx(y.StrictMode,{children:a.jsx(uq,{})}));export{xs as B,ix as K,rt as a,Qp as f,Ld as s,$n as t,ct as u};