@adhdev/daemon-standalone 1.0.54-rc.5 → 1.0.54-rc.7

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.
@@ -116,6 +116,6 @@ The newest runtime for each provider session will be kept and older duplicates w
116
116
  from { opacity: 0; transform: translateX(40px); }
117
117
  to { opacity: 1; transform: translateX(0); }
118
118
  }
119
- `})]})}function PL({daemonIds:e,meshId:t,sendData:n,onRevisionAdvance:a}){const r=l.useRef(new Map),o=l.useRef(a);o.current=a;const i=[...new Set(e.filter(Boolean))].sort().join(",");l.useEffect(()=>{r.current=new Map},[i,t]),l.useEffect(()=>{if(!t||!n)return;const c=[...new Set(e.filter(Boolean))];if(c.length===0)return;const d=c.map(p=>ys.subscribe({sendData:n},p,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${p}`,params:{includeSessions:!0}},u=>{if(u.topic!=="daemon.metadata")return;const m=u.meshStateRevisions;if(!m)return;const f=m[t]??m["*"];if(typeof f!="number")return;const g=r.current.get(p);r.current.set(p,f),g!==void 0&&f>g&&o.current()}));return()=>{for(const p of d)p()}},[i,t,n])}const Xf={meshHostDaemonSection:!1,createDaemonPicker:!1,addNodeDaemonPicker:!1,queueSection:!0,coordinatorPrompt:!0,nodeInstruction:!0,hermesMcpConfig:!0,reviewInbox:!0},Zf=l.createContext(null);function DL(){const e=l.useContext(Zf);if(!e)throw new Error("useRepoMeshContext must be used inside RepoMeshProvider");return e}const ao="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function yl({workspaces:e,value:t,onChange:n,autoFocus:a}){const{t:r}=ke("common"),[o,i]=l.useState(!1),c=new Set(e.map(p=>p.path)),d=o?"__custom":c.has(t)?t:"";return e.length===0||o?s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx("input",{type:"text",className:ao,value:t,autoFocus:a,placeholder:r("setupWizard.machines.workspacePlaceholder"),onChange:p=>n(p.target.value)}),e.length>0&&s.jsx("button",{type:"button",className:"self-start text-[10px] text-accent-primary hover:underline",onClick:()=>i(!1),children:r("setupWizard.machines.pickFromKnown")})]}):s.jsxs("select",{className:ao,value:d,onChange:p=>{p.target.value==="__custom"?(i(!0),n("")):n(p.target.value)},children:[s.jsx("option",{value:"",children:r("setupWizard.machines.workspaceSelectPlaceholder")}),e.map(p=>s.jsx("option",{value:p.path,children:p.label||p.path},p.path)),s.jsx("option",{value:"__custom",children:r("setupWizard.machines.workspaceCustom")})]})}function ro(e){var t;return!!(e!=null&&e.success)&&((t=e==null?void 0:e.plan)==null?void 0:t.kind)!==void 0&&e.plan.kind!=="create_mesh_and_onboard"}function eg(e,t){const[n,a]=l.useState(!1),r=l.useRef(null);return l.useEffect(()=>(e?r.current=setTimeout(()=>a(!0),t):a(!1),()=>{r.current&&clearTimeout(r.current)}),[e,t]),e&&n}function tg({plan:e,loading:t}){var i,c,d;const{t:n}=ke("common"),a=eg(t,250);let r=null,o="text-[11px] text-text-muted";return a?r=n("setupWizard.machines.planChecking"):(e==null?void 0:e.success)===!1?(o="text-[11px] text-red-400",r=s.jsxs(s.Fragment,{children:[e.error,e.action?` ${e.action}`:""]})):ro(e)?(o="text-[11px] text-amber-400",r=((i=e.plan)==null?void 0:i.summary)||n("setupWizard.machines.planExists")):e&&(o="text-[11px] text-emerald-400",r=n("setupWizard.machines.planOk",{identity:((c=e.discovery)==null?void 0:c.repoIdentity)||((d=e.discovery)==null?void 0:d.repoRoot)||""})),s.jsx("p",{className:`${o} min-h-[1.4em]`,children:r})}function IL(e){var t;return e.creating||e.planLoading||!e.name.trim()||e.showDaemonPicker&&!e.daemonId||((t=e.plan)==null?void 0:t.success)===!1||ro(e.plan)?!0:e.workspace.trim()?!1:!e.repoRemoteUrl.trim()&&!e.repoIdentity.trim()}function sg(e){var _,P;const{variant:t="page",showDaemonPicker:n,daemons:a,daemonLabel:r,name:o,onNameChange:i,daemonId:c,onDaemonIdChange:d,workspace:p,onWorkspaceChange:u,workspaces:m,plan:f,planLoading:g,repoRemoteUrl:k,onRepoRemoteUrlChange:h,repoIdentity:x,onRepoIdentityChange:S,manualOpen:b,onManualOpenChange:w,creating:C,warning:v,onCreate:y,onCancel:j}=e,{t:N}=ke("common"),A=IL({creating:C,planLoading:g,plan:f,name:o,workspace:p,showDaemonPicker:n,daemonId:c,repoRemoteUrl:k,repoIdentity:x}),T=eg(g,250),L=b||!!k.trim()||!!x.trim(),D=n&&a.length>0&&s.jsxs("select",{className:t==="wizard"?ao:"input w-full",value:c,onChange:B=>d(B.target.value),children:[s.jsx("option",{value:"",children:N("setupWizard.machines.machineSelectPlaceholder")}),a.map(B=>s.jsx("option",{value:B.id,children:r(B)},B.id))]}),M=L?s.jsxs(s.Fragment,{children:[s.jsx(Tt,{label:N("repoMesh.list.remoteUrl"),hint:N("repoMesh.list.remoteUrlHint"),children:s.jsx(xs,{value:k,onChange:B=>h(B.target.value),placeholder:"https://github.com/user/repo"})}),s.jsx(Tt,{label:N("repoMesh.list.repoIdentity"),hint:N("repoMesh.list.repoIdentityHint"),children:s.jsx(xs,{value:x,onChange:B=>S(B.target.value),placeholder:"github.com/user/repo"})})]}):s.jsx("button",{type:"button",className:"self-start text-xs text-text-muted hover:text-text-primary underline underline-offset-2 mb-3 bg-transparent border-none cursor-pointer p-0",onClick:()=>w(!0),children:N("repoMesh.list.advancedIdentityToggle")});return t==="wizard"?s.jsxs("div",{className:"flex flex-col gap-2.5 rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2.5",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:N("setupWizard.machines.meshName")}),s.jsx("input",{type:"text",className:ao,value:o,onChange:B=>i(B.target.value)})]}),n&&a.length>1&&s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:N("setupWizard.machines.machine")}),D]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:N("setupWizard.machines.workspace")}),s.jsx(yl,{workspaces:m,value:p,onChange:u})]}),s.jsx(tg,{plan:f,loading:g}),v&&s.jsx("p",{className:"text-[11px] text-amber-400",children:v}),s.jsx("div",{className:"flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:y,disabled:A,children:N(C?"setupWizard.machines.creating":"setupWizard.machines.create")})})]}):s.jsxs(s.Fragment,{children:[s.jsx("h3",{className:"text-base font-bold mb-4",children:N("repoMesh.list.createTitle")}),n&&s.jsx(Tt,{label:N("repoMesh.list.createOnMachine"),hint:N("repoMesh.list.createOnMachineHint"),children:a.length===0?s.jsx("select",{className:"input w-full",disabled:!0,children:s.jsx("option",{value:"",children:N("repoMesh.list.noConnectedDaemon")})}):D}),s.jsx(Tt,{label:N("repoMesh.list.workspace"),hint:N("repoMesh.list.workspaceHint"),children:s.jsx(yl,{workspaces:m,value:p,onChange:u})}),(T||f)&&s.jsx(Mt,{variant:(f==null?void 0:f.success)===!1?"error":ro(f)?"warning":"info",className:"mb-4",children:T?N("setupWizard.machines.planChecking"):(f==null?void 0:f.success)===!1?`${(f==null?void 0:f.code)||"onboarding_blocked"}: ${(f==null?void 0:f.error)||"Git discovery failed"} ${(f==null?void 0:f.action)||""}`:ro(f)?((_=f.plan)==null?void 0:_.summary)||N("setupWizard.machines.planExists"):`${((P=f.plan)==null?void 0:P.summary)||"Git repository detected."} No changes will be made until you click Create.`}),s.jsx(Tt,{label:N("repoMesh.list.name"),children:s.jsx(xs,{value:o,onChange:B=>i(B.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx("div",{className:"flex flex-col",children:M}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:y,disabled:A,children:N(C?"repoMesh.list.creating":"repoMesh.list.create")}),j&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:j,disabled:C,children:N("repoMesh.list.cancel")})]})]})}function LL({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("polyline",{points:"23 4 23 10 17 10"}),s.jsx("polyline",{points:"1 20 1 14 7 14"}),s.jsx("path",{d:"M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"})]})}function RL({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),s.jsx("circle",{cx:"18",cy:"6",r:"3"}),s.jsx("circle",{cx:"6",cy:"18",r:"3"}),s.jsx("path",{d:"M18 9a9 9 0 0 1-9 9"})]})}function EL({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("polyline",{points:"3 6 5 6 21 6"}),s.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]})}function _L({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function HL({status:e}){const n={online:{color:"#22c55e",label:"Online"},dirty:{color:"#f59e0b",label:"Dirty",title:"Workspace has uncommitted changes"},offline:{color:"#6b7280",label:"Offline"},degraded:{color:"#ef4444",label:"Degraded",title:"P2P connection to this node is down or timed out — often transient. Wait and retry, or re-establish the node's connection."},enabled:{color:"#22c55e",label:"Enabled"},pending:{color:"#a855f7",label:"Pending"},assigned:{color:"#3b82f6",label:"Assigned"},completed:{color:"#22c55e",label:"Completed"},failed:{color:"#ef4444",label:"Failed"},unknown:{color:"#6b7280",label:"Unknown"}}[e]||{color:"#6b7280",label:e};return s.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] font-semibold px-2 py-0.5 rounded-md",style:{background:n.color+"15",color:n.color,border:`1px solid ${n.color}25`},title:n.title,children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full",style:{background:n.color}}),n.label]})}function $L(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function FL({meshes:e,loading:t,error:n,onDismissError:a,daemons:r,features:o,showCreate:i,onToggleCreate:c,createName:d,onCreateNameChange:p,createRepoIdentity:u,onCreateRepoIdentityChange:m,createRepoRemoteUrl:f,onCreateRepoRemoteUrlChange:g,newMeshDaemonId:k,onNewMeshDaemonIdChange:h,newMeshWorkspace:x,onNewMeshWorkspaceChange:S,createPickerWorkspaces:b,createOnboardingPlan:w,createPlanLoading:C,creating:v,createWarning:y,onDismissCreateWarning:j,onSelectMesh:N,onCreate:A,onCancelCreate:T}){const{t:L}=ke("common"),D=o.maxMeshes!=null&&e.length>=o.maxMeshes,[M,_]=l.useState(!1);return s.jsxs(Qa,{icon:s.jsx(cs,{}),title:L("repoMesh.list.title"),subtitle:L("repoMesh.list.count",{count:e.length}),widthClassName:"max-w-5xl",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:c,disabled:D,title:D?L("repoMesh.list.meshLimitReached",{max:o.maxMeshes}):void 0,children:L("repoMesh.list.createMesh")}),children:[D&&s.jsx(Mt,{variant:"info",className:"mb-4",children:L("repoMesh.list.meshLimitBanner",{max:o.maxMeshes})}),n&&s.jsx(Mt,{variant:"error",onDismiss:a,className:"mb-4",children:n}),y&&s.jsx(Mt,{variant:"warning",onDismiss:j,className:"mb-4",children:y}),i&&s.jsx(bt,{className:"mb-5 border-accent/40 animate-[fadeIn_0.3s_ease-out]",children:s.jsx(sg,{variant:"page",showDaemonPicker:o.createDaemonPicker,daemons:r,daemonLabel:$L,name:d,onNameChange:p,daemonId:k,onDaemonIdChange:h,workspace:x,onWorkspaceChange:S,workspaces:b,plan:w,planLoading:C,repoRemoteUrl:f,onRepoRemoteUrlChange:g,repoIdentity:u,onRepoIdentityChange:m,manualOpen:M,onManualOpenChange:_,creating:v,onCreate:A,onCancel:T})}),t?s.jsx("div",{className:"text-sm text-text-muted p-4",children:L("repoMesh.list.loading")}):e.length===0?s.jsx(Ja,{icon:s.jsx(cs,{}),title:L("repoMesh.list.emptyTitle"),description:r.length>0?L("repoMesh.list.emptyWithDaemons"):L("repoMesh.list.emptyNoDaemons"),action:s.jsx("button",{className:"btn btn-primary btn-sm",disabled:!r.length,onClick:c,children:L("repoMesh.list.createFirst")})}):s.jsx("div",{className:"flex flex-col gap-2.5",children:e.map(P=>{var B;return s.jsx("button",{type:"button",onClick:()=>N(P.id),className:"w-full text-left bg-bg-glass border border-border-subtle rounded-xl px-5 py-4 transition-colors hover:border-border-default hover:bg-bg-secondary/70",children:s.jsxs("div",{className:"flex justify-between items-start",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx(cs,{size:16}),s.jsx("span",{className:"font-bold text-sm",children:P.name})]}),s.jsxs("div",{className:"text-[12px] text-text-muted flex items-center gap-2",children:[s.jsx("span",{className:"font-mono",children:P.repoIdentity||P.repo_identity||L("repoMesh.list.noRepoIdentity")}),(P.defaultBranch||P.default_branch)&&s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(RL,{size:11}),P.defaultBranch||P.default_branch]})]})]}),s.jsxs("div",{className:"text-right text-[11px] text-text-muted shrink-0 ml-4",children:[s.jsx("div",{children:new Date(P.createdAt||P.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric"})}),s.jsxs("div",{className:"text-text-muted/60",children:[((B=P.nodes)==null?void 0:B.length)??P.nodeCount??0," ",L("repoMesh.list.nodesSuffix")]})]})]})},P.id)})})]})}function BL(e){const t=new Map;for(const n of e)n!=null&&n.id&&t.set(n.id,ln(n.availableProviders||[]));return t}function WL(e,t){const n=String(e.daemon_id||e.daemonId||"");return n&&t.has(n)?t.get(n):!n&&t.size===1?[...t.values()][0]:[]}function OL(e,t){const n=new Map;for(const c of t)c!=null&&c.id&&n.set(c.id,Array.isArray(c.availableProviders)?c.availableProviders:[]);const a=new Set,r=[];let o=0,i=0;for(const c of Array.isArray(e)?e:[]){const d=String((c==null?void 0:c.daemon_id)||(c==null?void 0:c.daemonId)||""),p=d?n.get(d):n.size===1?[...n.values()][0]:void 0;if(!p||p.length===0){i++;continue}o++;for(const u of p){const m=String((u==null?void 0:u.type)||(u==null?void 0:u.id)||"").trim();!m||a.has(m)||(a.add(m),r.push(u))}}return r.sort((c,d)=>String((c==null?void 0:c.type)||(c==null?void 0:c.id)||"").localeCompare(String((d==null?void 0:d.type)||(d==null?void 0:d.id)||""))),{providers:r,reportedNodeCount:o,unreportedNodeCount:i}}function UL(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{},n=new Set,a=[],r=o=>{const i=typeof o=="string"?o.trim():"";!i||n.has(i)||(n.add(i),a.push(i))};for(const o of tm(t.slots))r(o.provider);if(Array.isArray(t.providerPriority))for(const o of t.providerPriority)r(o);return a}function GL(e){var d,p;const t=e,n=[],a=Array.isArray(t.capabilities)?t.capabilities:[];for(const u of a){const m=typeof u=="string"?u.trim():"";m&&n.push({tag:m,custom:!0})}const r=(((d=t.userOverrides)==null?void 0:d.platform)||t.reportedPlatform||"").toString().trim(),o=(((p=t.userOverrides)==null?void 0:p.arch)||t.reportedArch||"").toString().trim();r&&n.push({tag:`os=${r}`,custom:!1}),o&&n.push({tag:`arch=${o}`,custom:!1});for(const u of UL(t.policy))n.push({tag:`provider=${u}`,custom:!1});const i=typeof t.worktreeBranch=="string"?t.worktreeBranch.trim():"";t.isLocalWorktree===!0&&i&&n.push({tag:`worktree=${i}`,custom:!1});const c=new Set;return n.filter(u=>c.has(u.tag)?!1:(c.add(u.tag),!0))}const qL=["","low","medium","high"],zL={easy:"Easy",medium:"Medium",difficult:"Difficult",freeform:"Freeform"};function Ku(e){return{provider:e.provider||"",model:e.model||"",thinkingLevel:e.thinkingLevel||"",difficulty:Array.isArray(e.difficulty)?e.difficulty:[],capability:Array.isArray(e.capability)?e.capability:[],maxParallel:e.maxParallel!=null?String(e.maxParallel):""}}function Vu(e){const t=e.provider.trim();if(!t)return null;const n=e.model.trim(),a=e.thinkingLevel.trim()||void 0,r=Number(e.maxParallel),o=Number.isFinite(r)&&r>0?Math.floor(r):void 0;return{provider:t,...n?{model:n}:{},...a?{thinkingLevel:a}:{},...e.difficulty.length?{difficulty:e.difficulty}:{},...e.capability.length?{capability:e.capability}:{},...o!==void 0?{maxParallel:o}:{}}}function KL(){return{provider:"",model:"",thinkingLevel:"",difficulty:[],capability:[],maxParallel:""}}const fn="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function VL({slots:e,availableProviders:t,saving:n,onSave:a}){const{t:r}=ke("common"),[o,i]=l.useState(()=>e.map(Ku)),c=l.useMemo(()=>JSON.stringify(e),[e]);l.useEffect(()=>{i(e.map(Ku))},[c]);const d=l.useMemo(()=>[...new Set(t.map(b=>b.type).filter(Boolean))],[t]),p=l.useMemo(()=>uh(t),[t]),u=l.useMemo(()=>{const b=o.map(Vu).filter(Boolean);return JSON.stringify(b)!==JSON.stringify(e)},[o,e]),m=(b,w)=>i(C=>C.map((v,y)=>y===b?{...v,...w}:v)),f=(b,w)=>i(C=>C.map((v,y)=>{var A;if(y!==b)return v;const j=((A=p.get(w))==null?void 0:A.models)??[],N=!v.model||j.length===0||j.includes(v.model);return{...v,provider:w,...N?{}:{model:""}}})),g=b=>i(w=>w.filter((C,v)=>v!==b)),k=()=>i(b=>[...b,KL()]),h=(b,w)=>i(C=>{const v=b+w;if(v<0||v>=C.length)return C;const y=[...C];return[y[b],y[v]]=[y[v],y[b]],y}),x=(b,w)=>i(C=>C.map((v,y)=>{if(y!==b)return v;const j=v.difficulty.includes(w);return{...v,difficulty:j?v.difficulty.filter(N=>N!==w):[...v.difficulty,w]}})),S=()=>a(o.map(Vu).filter(Boolean));return s.jsxs("div",{className:"flex flex-col gap-2",onClick:b=>b.stopPropagation(),children:[o.length===0&&s.jsx("div",{className:"text-[12px] text-text-muted",children:r("repoMesh.slotEditor.empty")}),o.map((b,w)=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/40 p-2.5",children:[s.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[s.jsxs("span",{className:"text-[11px] font-semibold text-text-muted",children:["#",w+1]}),s.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-border-subtle text-text-muted hover:text-text-primary disabled:opacity-40",disabled:w===0,onClick:()=>h(w,-1),title:r("repoMesh.slotEditor.moveUp"),children:"↑"}),s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-border-subtle text-text-muted hover:text-text-primary disabled:opacity-40",disabled:w===o.length-1,onClick:()=>h(w,1),title:r("repoMesh.slotEditor.moveDown"),children:"↓"}),s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-status-error/30 text-status-error hover:bg-status-error/10",onClick:()=>g(w),"aria-label":r("repoMesh.slotEditor.removeSlot"),children:s.jsx(Dt,{size:12})})]})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:r("repoMesh.slotEditor.provider")}),d.length>0?s.jsxs("select",{className:fn,value:b.provider,onChange:C=>f(w,C.target.value),children:[s.jsx("option",{value:"",children:r("repoMesh.slotEditor.select")}),d.map(C=>s.jsx("option",{value:C,children:C},C)),b.provider&&!d.includes(b.provider)&&s.jsx("option",{value:b.provider,children:b.provider})]}):s.jsx("input",{className:fn,value:b.provider,placeholder:"claude-cli",onChange:C=>m(w,{provider:C.target.value})})]}),(()=>{var N;const C=p.get(b.provider),v=(C==null?void 0:C.models)??[],y=(N=C==null?void 0:C.thinking)!=null&&N.length?["",...C.thinking]:qL,j=!!b.model&&v.length>0&&!v.includes(b.model);return s.jsxs(s.Fragment,{children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:r("repoMesh.slotEditor.model")}),v.length>0&&!j?s.jsxs("select",{className:fn,value:v.includes(b.model)?b.model:"",onChange:A=>m(w,{model:A.target.value==="__custom__"?" ":A.target.value}),children:[s.jsx("option",{value:"",children:r("repoMesh.slotEditor.providerDefault")}),v.map(A=>s.jsx("option",{value:A,children:A},A)),s.jsx("option",{value:"__custom__",children:r("repoMesh.slotEditor.custom")})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:fn,value:b.model.trim(),placeholder:b.provider?`${b.provider} model`:r("repoMesh.slotEditor.modelPlaceholder"),onChange:A=>m(w,{model:A.target.value})}),v.length>0&&s.jsx("button",{type:"button",className:"self-start bg-transparent border-none cursor-pointer p-0 text-[10px] text-text-muted hover:underline",onClick:()=>m(w,{model:""}),children:r("repoMesh.slotEditor.backToModelList")})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:r("repoMesh.slotEditor.thinking")}),s.jsx("select",{className:fn,value:b.thinkingLevel,onChange:A=>m(w,{thinkingLevel:A.target.value}),children:y.map(A=>s.jsx("option",{value:A,children:A||r("repoMesh.slotEditor.thinkingDefault")},A||"_default"))})]})]})})()]}),s.jsxs("div",{className:"mt-2",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:r("repoMesh.slotEditor.difficulty")}),s.jsx("div",{className:"mt-1 flex flex-wrap gap-1.5",children:em.map(C=>{const v=b.difficulty.includes(C);return s.jsx("button",{type:"button",className:`rounded-full border px-2.5 py-0.5 text-[11px] font-medium transition-colors ${v?"border-accent-primary/60 bg-accent-primary/15 text-accent-primary":"border-border-subtle bg-bg-primary/60 text-text-muted hover:text-text-primary"}`,onClick:()=>x(w,C),children:zL[C]},C)})})]}),s.jsxs("div",{className:"mt-2 grid grid-cols-1 sm:grid-cols-2 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:r("repoMesh.slotEditor.capabilityTags")}),s.jsx("input",{className:fn,value:b.capability.join(", "),placeholder:"worktree, os=darwin",onChange:C=>m(w,{capability:C.target.value.split(",").map(v=>v.trim()).filter(Boolean)})})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:r("repoMesh.slotEditor.maxParallel")}),s.jsx("input",{type:"number",inputMode:"numeric",min:1,className:fn,value:b.maxParallel,placeholder:r("repoMesh.slotEditor.maxParallelPlaceholder"),onChange:C=>m(w,{maxParallel:C.target.value})})]})]})]},w)),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-1",onClick:k,children:[s.jsx(Hl,{size:13})," ",r("repoMesh.slotEditor.addSlot")]}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm ml-auto",onClick:S,disabled:!!n||!u,children:r(n?"repoMesh.slotEditor.saving":"repoMesh.slotEditor.saveSlots")})]})]})}function YL(e){const t=e.capabilities;return Array.isArray(t)?t.map(n=>typeof n=="string"?n.trim():"").filter(Boolean):[]}const QL=["os=","arch=","provider=","worktree=","converge="];function JL({node:e,saving:t,onSave:n}){const{t:a}=ke("common"),r=l.useMemo(()=>GL(e).filter(h=>!h.custom),[e]),o=l.useMemo(()=>YL(e),[e]),[i,c]=l.useState(o),[d,p]=l.useState(""),u=JSON.stringify(i)!==JSON.stringify(o),f=(h=>{const x=h.trim();return x?/\s/.test(x)?a("repoMesh.tagEditor.noSpaces"):QL.some(S=>x.toLowerCase().startsWith(S))?a("repoMesh.tagEditor.reservedPrefix"):i.includes(x)?a("repoMesh.tagEditor.alreadyAdded"):null:null})(d);function g(){const h=d.trim();!h||f||(c(x=>[...x,h]),p(""))}function k(h){c(x=>x.filter(S=>S!==h))}return s.jsxs("div",{className:"mt-2",onClick:h=>h.stopPropagation(),children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wide text-text-muted mr-1",children:a("repoMesh.tagEditor.routingTags")}),r.map(h=>s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-1.5 py-0.5 font-mono text-[10px] text-text-muted",title:a("repoMesh.tagEditor.autoDerivedTitle"),children:h.tag},h.tag)),i.map(h=>s.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-accent-primary/40 bg-accent-primary/10 px-1.5 py-0.5 font-mono text-[10px] text-accent-primary",title:a("repoMesh.tagEditor.customTagTitle"),children:[h,s.jsx("button",{type:"button",className:"text-accent-primary/70 hover:text-accent-primary bg-transparent border-none cursor-pointer p-0 leading-none",onClick:()=>k(h),disabled:t,"aria-label":a("repoMesh.tagEditor.remove",{tag:h}),children:"×"})]},h))]}),s.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-2",children:[s.jsx("input",{type:"text",value:d,onChange:h=>p(h.target.value),onKeyDown:h=>{h.key==="Enter"&&(h.preventDefault(),g())},placeholder:a("repoMesh.tagEditor.addPlaceholder"),disabled:t,className:"min-w-[12rem] flex-1 px-2 py-1 rounded-lg bg-bg-secondary border border-border-subtle text-[12px] text-text-primary"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:g,disabled:t||!d.trim()||!!f,children:a("repoMesh.tagEditor.add")}),u&&s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>n(i),disabled:t,children:a(t?"repoMesh.tagEditor.saving":"repoMesh.tagEditor.saveTags")})]}),f&&s.jsx("div",{className:"mt-1 text-[11px] text-amber-400",children:f}),i.length===0&&r.length===0&&s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:a("repoMesh.tagEditor.empty")})]})}function XL(e,t){const n=t;return[...Array.isArray(n==null?void 0:n.cliSessions)?n.cliSessions:[],...Array.isArray(n==null?void 0:n.acpSessions)?n.acpSessions:[],...Array.isArray(n==null?void 0:n.sessions)?n.sessions:[]].filter(r=>{var o;return((o=r==null?void 0:r.settings)==null?void 0:o.meshNodeId)===e.id||(r==null?void 0:r.workspace)===e.workspace}).map(r=>{var o;return{id:r.sessionId||r.id||r.instanceId||"unknown",provider:r.providerType||r.cliType||r.acpType||r.type||"unknown",status:r.status||((o=r.activeChat)==null?void 0:o.status)||"unknown"}})}function ZL(e,t){var n;return(e==null?void 0:e.ownerName)||(e==null?void 0:e.userName)||((n=e==null?void 0:e.user)==null?void 0:n.name)||t||"You"}function Yu({nodes:e,meshQueue:t,activeDaemon:n,daemons:a,userName:r,features:o,providersByDaemonId:i,savingNodeSlotsId:c,onUpdateNodeSlots:d,savingNodeCapabilitiesId:p,onUpdateNodeCapabilities:u,nodeSystemPromptDrafts:m,onNodeSystemPromptDraftChange:f,savingNodeSystemPromptId:g,onSaveNodeSystemPrompt:k,selectedNodeId:h,onSelectNode:x,onRemoveNode:S}){const{t:b}=ke("common");return e.length===0?s.jsx(Ja,{icon:s.jsx(An,{}),title:b("repoMesh.nodeList.emptyTitle"),description:b("repoMesh.nodeList.emptyDescription")}):s.jsx("div",{className:"flex flex-col gap-2",children:e.map(w=>{var A;const C=n2(w),v=e2(w,t),y=XL(w,n),j=h===w.id,N=w.status||w.machine_status||(v.length>0||y.length>0?"active":"enabled");return s.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary transition-colors ${o.addNodeDaemonPicker?"bg-bg-glass border-border-subtle rounded-xl px-5 py-4":`cursor-pointer ${j?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`}`,role:o.addNodeDaemonPicker?void 0:"button",tabIndex:o.addNodeDaemonPicker?void 0:0,onClick:o.addNodeDaemonPicker?void 0:()=>x(j?null:w.id),onKeyDown:o.addNodeDaemonPicker?void 0:T=>{(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),x(j?null:w.id))},children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[o.addNodeDaemonPicker?s.jsx("span",{className:"font-semibold text-sm text-text-primary truncate",children:w.machine_label||w.machine_nickname||w.hostname||w.workspace}):s.jsx("span",{className:"text-sm font-medium",children:w.workspace.split("/").pop()}),o.addNodeDaemonPicker&&s.jsx(HL,{status:N}),o.addNodeDaemonPicker&&s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:b("repoMesh.nodeList.setupInventory")})]}),o.addNodeDaemonPicker&&s.jsx("div",{className:"text-[11px] text-text-muted",children:b("repoMesh.nodeList.ownerMachine",{owner:ZL(a.find(T=>T.id===String(w.daemon_id||"")),r),machine:w.machine_label||w.daemon_id||w.workspace})}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:w.workspace}),s.jsx(JL,{node:w,saving:p===w.id,onSave:T=>u(w,T)}),o.addNodeDaemonPicker&&s.jsx("div",{className:"mt-2 text-[11px] text-amber-300",children:b("repoMesh.nodeList.liveDetailGraphOwned")}),s.jsxs("div",{className:"mt-3 max-w-2xl",onClick:T=>T.stopPropagation(),children:[s.jsx(Tt,{label:b("repoMesh.nodeList.slotsLabel"),hint:b("repoMesh.nodeList.slotsHint"),children:s.jsx(VL,{slots:Array.isArray((A=w.policy)==null?void 0:A.slots)?w.policy.slots:[],availableProviders:WL(w,i),saving:c===w.id,onSave:T=>d(w,T)})}),o.nodeInstruction&&s.jsxs(Tt,{label:b("repoMesh.nodeList.nodeInstruction"),hint:b("repoMesh.nodeList.nodeInstructionHint"),children:[s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:3,value:m[w.id]??"",onChange:T=>{const L=T.target.value;f(w.id,L)},onClick:T=>T.stopPropagation(),disabled:g===w.id,placeholder:b("repoMesh.nodeList.nodeInstructionPlaceholder")}),s.jsx("div",{className:"mt-2 flex items-center gap-2",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:T=>{T.stopPropagation(),k(w)},disabled:g===w.id,children:g===w.id?b("repoMesh.nodeList.saving"):b("repoMesh.nodeList.saveInstruction")})})]})]})]}),s.jsx("button",{className:`transition-colors bg-transparent border-none cursor-pointer ${o.addNodeDaemonPicker?"btn btn-sm text-text-muted hover:text-red-400":"text-text-muted hover:text-red-400"}`,onClick:T=>{T.stopPropagation(),S(w.id)},title:b("repoMesh.nodeList.removeNode"),children:s.jsx(EL,{size:14})})]}),s.jsxs("details",{className:"mt-3 group",onClick:T=>T.stopPropagation(),children:[s.jsxs("summary",{className:"cursor-pointer select-none text-[12px] text-text-muted hover:text-text-secondary inline-flex items-center gap-1",children:[s.jsx("span",{className:"transition-transform group-open:rotate-90","aria-hidden":!0,children:"▸"})," ",b("repoMesh.nodeList.details")]}),s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary/60 p-3 text-[12px] text-text-muted",children:[s.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:b("repoMesh.nodeList.nodeId")})," ",s.jsx("span",{className:"font-mono break-all",children:w.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:b("repoMesh.nodeList.launchReady")})," ",s.jsx("span",{className:C.configured?"text-green-400":"text-amber-400",children:C.configured?b("repoMesh.nodeList.launchReadyYes"):b("repoMesh.nodeList.launchReadyNo")})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:b("repoMesh.nodeList.repoRoot")})," ",s.jsx("span",{className:"font-mono break-all",children:w.repoRoot||w.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:b("repoMesh.nodeList.activeSessionsLabel")})," ",y.length]}),o.addNodeDaemonPicker&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:b("repoMesh.nodeList.added")})," ",new Date(w.created_at||w.createdAt||Date.now()).toLocaleDateString()]})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:b("repoMesh.nodeList.activeQueueAssignments")}),v.length===0?s.jsx("div",{children:b("repoMesh.nodeList.noActiveAssignment")}):s.jsx("ul",{className:"m-0 pl-4",children:v.map(T=>s.jsx("li",{className:"font-mono",children:t2(T)},T.id))})]}),y.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:b("repoMesh.nodeList.activeSessions")}),s.jsx("ul",{className:"m-0 pl-4",children:y.map(T=>s.jsxs("li",{className:"font-mono",children:[T.provider," / ",T.status," / ",T.id]},T.id))})]})]})]})]},w.id)})})}function e2(e,t){return t.filter(n=>n.status!=="assigned"?!1:(n.assignedNodeId||n.nodeId)===e.id)}function t2(e){const t=e.assignedSessionId||e.sessionId||"unassigned session",n=e.message.length>80?`${e.message.slice(0,77)}…`:e.message;return`${t}: ${n}`}function s2(e){var r,o;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((r=e.policy)==null?void 0:r.providerPriority)?e.policy.providerPriority:[],n=new Set,a=t.map(i=>typeof i=="string"?i.trim():"").filter(Boolean).filter(i=>n.has(i)?!1:(n.add(i),!0));return a.length?a:$0((o=e.policy)==null?void 0:o.slots)}function n2(e){const t=s2(e);return t.length?{configured:!0,label:t.join(" → ")}:{configured:!1,label:"not configured",launchBlockedMessage:"No provider configured on this node — task launch is blocked until a capability slot or provider priority is set."}}function wl(e){return e.isLocalWorktree===!0}function oo(e){return e&&(e.machineNickname||e.nickname||e.hostname||(e.id?Tf(e.id):void 0))||"Unknown"}function a2(e){return String(e.daemon_id||e.daemonId||"")}function r2(e,t){const n=new Map(t.map(o=>[o.id,o])),a=[],r=new Map;for(const o of e){const i=a2(o);r.has(i)||(r.set(i,[]),a.push(i)),r.get(i).push(o)}return a.map(o=>{const i=r.get(o),c=o?n.get(o):void 0,d=i[0],p=o?c?oo(c):(d==null?void 0:d.machine_label)||(d==null?void 0:d.machine_nickname)||(d==null?void 0:d.hostname)||o:oo(c),u=(c==null?void 0:c.status)==="online",m=i.reduce((f,g)=>{var k;return f+(Array.isArray((k=g.policy)==null?void 0:k.slots)?g.policy.slots.length:0)},0);return{key:o,label:p,online:u,nodes:i,slotCount:m}})}function o2({groups:e,activeKey:t,onChange:n}){const{t:a}=ke("common");return s.jsx("div",{className:"flex items-center gap-1 px-1 border-b border-border-subtle mb-4 overflow-x-auto",role:"tablist","aria-label":a("repoMesh.nodeList.machineTabsLabel"),children:e.map(r=>{const o=r.key===t;return s.jsxs("button",{type:"button",role:"tab","aria-selected":o,onClick:()=>n(r.key),className:`flex items-center gap-2 px-3 py-2.5 text-[13px] font-medium border-b-2 -mb-px transition-colors cursor-pointer whitespace-nowrap ${o?"border-accent text-accent":"border-transparent text-text-muted hover:text-text-secondary"}`,children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${r.online?"bg-green-400":"bg-neutral-500"}`}),s.jsx("span",{className:"truncate max-w-[160px]",children:r.label}),s.jsx("span",{className:"text-[11px] text-text-muted font-normal",children:a("repoMesh.nodeList.machineTabCounts",{nodes:r.nodes.length,slots:r.slotCount})})]},r.key)})})}function i2({nodes:e,meshQueue:t,activeDaemon:n,daemons:a,selectedMeshId:r,userName:o,features:i,coordinatorDaemonId:c,availableCliProviders:d,savingNodeSlotsId:p,onUpdateNodeSlots:u,savingNodeCapabilitiesId:m,onUpdateNodeCapabilities:f,nodeSystemPromptDrafts:g,onNodeSystemPromptDraftChange:k,savingNodeSystemPromptId:h,onSaveNodeSystemPrompt:x,selectedNodeId:S,onSelectNode:b,showAddNode:w,onShowAddNode:C,onCancelAddNode:v,nodeWorkspace:y,onNodeWorkspaceChange:j,nodeProviderPriority:N,onNodeProviderPriorityChange:A,nodeDaemonId:T,onNodeDaemonIdChange:L,nodeCustomPath:D,onNodeCustomPathChange:M,nodePickerWorkspaces:_,nodePickerProviders:P,nodeOnboardingPlan:B,nodePlanLoading:R,attachableDaemons:O,onAddNode:H,onRemoveNode:$}){var Ce,le,U;const{t:I}=ke("common"),W=l.useMemo(()=>BL(a),[a]),F=l.useMemo(()=>e.filter(J=>!wl(J)),[e]),z=l.useMemo(()=>i.addNodeDaemonPicker?r2(F,a):[],[i.addNodeDaemonPicker,F,a]),[Q,ne]=l.useState(null),oe=z.some(J=>J.key===Q)?Q:((Ce=z[0])==null?void 0:Ce.key)??"";return s.jsxs(bt,{title:i.addNodeDaemonPicker?I("repoMesh.nodeList.title",{count:F.length}):I("repoMesh.nodeList.titleNoCount"),description:i.addNodeDaemonPicker?I("repoMesh.nodeList.descriptionCloud"):I("repoMesh.nodeList.descriptionStandalone"),children:[i.addNodeDaemonPicker&&s.jsxs("div",{className:"mb-4 rounded-xl border border-border-subtle bg-bg-secondary/60 p-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:I("repoMesh.nodeList.daemonCandidates")}),s.jsx("div",{className:"text-[12px] text-text-muted",children:I("repoMesh.nodeList.daemonCandidatesHint")})]}),s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:I("repoMesh.nodeList.available",{count:O.length})})]}),a.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:I("repoMesh.nodeList.noDaemonsAvailable")}):O.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:I("repoMesh.nodeList.allDaemonsAttached")}):s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:O.map(J=>s.jsxs("button",{type:"button",className:`text-left rounded-lg border px-3 py-2 transition-colors min-w-0 ${J.id===c?"border-accent-primary/50 bg-accent-primary/10":"border-border-subtle bg-bg-primary hover:border-border-default"}`,onClick:()=>{L(J.id),j(""),M(!1),A(Pn(ln(J.availableProviders||[]))),C()},children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-sm font-medium truncate min-w-0",children:oo(J)}),J.id===c&&s.jsx("span",{className:"text-[10px] text-accent-primary shrink-0",children:I("repoMesh.nodeList.selectedHost")})]}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted font-mono truncate",children:J.id}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:I("repoMesh.nodeList.workspacesDetected",{count:(J.workspaces||[]).length})})]},J.id))})]}),!w&&s.jsxs("button",{className:"btn btn-primary btn-sm mb-4 inline-flex items-center gap-1.5",onClick:C,children:[s.jsx(_L,{size:13})," ",i.addNodeDaemonPicker?I("repoMesh.nodeList.attachMachine"):I("repoMesh.nodeList.addNode")]}),w&&s.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-accent-primary/30 bg-bg-glass animate-[fadeIn_0.3s_ease-out]",children:[s.jsxs("div",{className:"flex justify-between items-center mb-3",children:[s.jsx("h4",{className:"text-sm font-bold",children:i.addNodeDaemonPicker?I("repoMesh.nodeList.attachMachineTitle"):I("repoMesh.nodeList.addNodeTitle")}),s.jsx("button",{onClick:()=>{v(),L(""),M(!1)},className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(Dt,{size:16})})]}),i.addNodeDaemonPicker&&s.jsx(Tt,{label:I("repoMesh.nodeList.machine"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:T,onChange:J=>{var ee;L(J.target.value),j(""),M(!1),A(Pn(ln(((ee=a.find(Y=>Y.id===J.target.value))==null?void 0:ee.availableProviders)||[])))},children:[s.jsx("option",{value:"",children:I("repoMesh.nodeList.selectMachine")}),a.map(J=>s.jsx("option",{value:J.id,children:oo(J)},J.id))]})}),(i.addNodeDaemonPicker?T:!0)&&s.jsx(Tt,{label:I("repoMesh.nodeList.workspacePath"),children:i.addNodeDaemonPicker&&!D&&_.length>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex flex-col gap-1.5 mb-2",children:_.map(J=>s.jsxs("button",{type:"button",className:`text-left text-xs px-3 py-2 rounded-lg border transition-colors ${y===J.path?"border-accent-primary bg-accent-primary/10 text-text-primary":"border-border-subtle bg-bg-primary hover:bg-violet-500/10 text-text-primary"}`,onClick:()=>j(J.path),children:[s.jsx("span",{className:"font-medium block truncate",children:J.label||J.path.split("/").pop()}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:J.path})]},J.id||J.path))}),s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{M(!0),j("")},children:I("repoMesh.nodeList.enterCustomPath")})]}):s.jsx(s.Fragment,{children:i.addNodeDaemonPicker?s.jsxs(s.Fragment,{children:[s.jsx(xs,{value:y,onChange:J=>j(J.target.value),placeholder:"/Users/dev/projects/myapp",onKeyDown:J=>{J.key==="Enter"&&H()}}),_.length>0&&s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0 mt-1",onClick:()=>{M(!1),j("")},children:I("repoMesh.nodeList.pickFromSaved")})]}):(()=>{var Y;const J=Array.isArray(n==null?void 0:n.workspaces)?n.workspaces:[],ee=`mesh-add-node-workspaces-${r||"new"}`;return s.jsxs(s.Fragment,{children:[s.jsx(xs,{value:y,onChange:ve=>j(ve.target.value),placeholder:((Y=J[0])==null?void 0:Y.path)||"/Users/dev/projects/myapp",list:J.length>0?ee:void 0,autoFocus:!0}),J.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("datalist",{id:ee,children:J.map(ve=>s.jsx("option",{value:ve.path,children:ve.label||ve.path},ve.id||ve.path))}),s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:J.slice(0,6).map(ve=>s.jsx("button",{type:"button",onClick:()=>j(ve.path),className:"text-[11px] px-2 py-0.5 rounded-full border border-border-subtle hover:border-accent-primary/50 text-text-muted hover:text-text-primary transition-colors bg-transparent cursor-pointer",title:ve.path,children:ve.label||ve.path.split("/").filter(Boolean).pop()||ve.path},ve.id||ve.path))})]})]})})()})}),(R||B)&&s.jsx(Mt,{variant:(B==null?void 0:B.success)===!1?"error":"info",className:"mb-4",children:R?"Inspecting Git repository (read-only)…":B!=null&&B.success?`${((le=B.plan)==null?void 0:le.summary)||"Compatible Git workspace detected."} Adding remains an explicit action.`:`${(B==null?void 0:B.code)||"onboarding_blocked"}: ${(B==null?void 0:B.error)||"Git discovery failed"} ${(B==null?void 0:B.action)||""}`}),s.jsx(Tt,{label:I("repoMesh.nodeList.preferredTools"),hint:I("repoMesh.nodeList.preferredToolsHint"),children:s.jsx(Uj,{value:N,availableProviders:i.addNodeDaemonPicker?P:d,onChange:A})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:H,disabled:R||(B==null?void 0:B.success)===!1||!y.trim()||i.addNodeDaemonPicker&&!T,className:"btn btn-primary btn-sm",children:I("repoMesh.nodeList.add")}),s.jsx("button",{onClick:()=>{v(),L(""),M(!1)},className:"btn btn-secondary btn-sm",children:I("repoMesh.nodeList.cancel")})]})]}),F.length===0?s.jsx(Ja,{icon:s.jsx(An,{}),title:I("repoMesh.nodeList.emptyTitle"),description:I("repoMesh.nodeList.emptyDescription")}):i.addNodeDaemonPicker?s.jsxs(s.Fragment,{children:[z.length>1&&s.jsx(o2,{groups:z,activeKey:oe,onChange:ne}),s.jsx(Yu,{nodes:((U=z.find(J=>J.key===oe))==null?void 0:U.nodes)||F,meshQueue:t,activeDaemon:n,daemons:a,userName:o,features:i,providersByDaemonId:W,savingNodeSlotsId:p,onUpdateNodeSlots:u,savingNodeCapabilitiesId:m,onUpdateNodeCapabilities:f,nodeSystemPromptDrafts:g,onNodeSystemPromptDraftChange:k,savingNodeSystemPromptId:h,onSaveNodeSystemPrompt:x,selectedNodeId:S,onSelectNode:b,onRemoveNode:$})]}):s.jsx(Yu,{nodes:F,meshQueue:t,activeDaemon:n,daemons:a,userName:o,features:i,providersByDaemonId:W,savingNodeSlotsId:p,onUpdateNodeSlots:u,savingNodeCapabilitiesId:m,onUpdateNodeCapabilities:f,nodeSystemPromptDrafts:g,onNodeSystemPromptDraftChange:k,savingNodeSystemPromptId:h,onSaveNodeSystemPrompt:x,selectedNodeId:S,onSelectNode:b,onRemoveNode:$})]})}const l2=["claude-cli","codex-cli","gemini-cli","hermes-cli","antigravity-cli"],c2=[{kind:"rca",labelKey:"meshGraph.magiKind.kindRca",hint:"rca"},{kind:"design",labelKey:"meshGraph.magiKind.kindDesign",hint:"design"},{kind:"claim_audit",labelKey:"meshGraph.magiKind.kindClaimAudit",hint:"claim_audit"},{kind:"freeform",labelKey:"meshGraph.magiKind.kindFreeform",hint:"freeform"}];function d2(){return{nodeId:"",provider:"",model:"",n:""}}function Qu(e){var t;return(t=e.providers)!=null&&t.length?e.providers.filter(Boolean):(e.providerPriority??[]).filter(Boolean)}function u2(e){return{nodeId:e.nodeId??"",provider:e.provider??"",model:e.model??"",n:e.n!=null?String(e.n):""}}function p2(e){const t=[];for(let n=0;n<e.length;n++){const a=e[n],r=a.provider.trim();if(!r)return{error:{code:"provider_required",slot:n+1}};const o=a.nodeId.trim(),i=a.model.trim(),c=a.n.trim();let d;if(c){const p=Number(c);if(!Number.isFinite(p)||p<1)return{error:{code:"replica_min",slot:n+1}};d=Math.floor(p)}t.push({provider:r,...o?{nodeId:o}:{},...i?{model:i}:{},...d!==void 0?{n:d}:{}})}return t.length===0?{error:{code:"no_slot"}}:{slots:t}}function m2({status:e,daemonId:t,sendDaemonCommand:n,availableProviders:a}){const{t:r}=ke(),{theme:o}=Ls(),i=l.useMemo(()=>Rs(o),[o]),c=l.useMemo(()=>uh(a),[a]),[d,p]=l.useState({}),[u,m]=l.useState(!1),[f,g]=l.useState(null),[k,h]=l.useState({}),[x,S]=l.useState(null),b=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(F=>({nodeId:F.nodeId,machineLabel:F.machineLabel,providers:F.providers,providerPriority:F.providerPriority,isLocalWorktree:F.isLocalWorktree,worktreeBranch:F.worktreeBranch})),[e==null?void 0:e.nodes]),w=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(F=>F.nodeId),[e==null?void 0:e.nodes]),C=l.useMemo(()=>new Set(b.filter(wl).map(F=>F.nodeId)),[b]),v=l.useMemo(()=>Object.fromEntries(b.filter(wl).map(F=>[F.nodeId,F.worktreeBranch])),[b]),y=l.useMemo(()=>Object.fromEntries(((e==null?void 0:e.nodes)??[]).map(F=>[F.nodeId,F.machineLabel||F.nodeId])),[e==null?void 0:e.nodes]),j=l.useMemo(()=>{const F={};for(const z of b)F[z.nodeId]=Qu(z);return F},[b]),N=l.useMemo(()=>{const F=[...new Set(b.flatMap(Qu).filter(Boolean))];return[...new Set([...F,...l2])].sort()},[b]),A=!!t&&!!n,T=F=>F&&typeof F=="object"&&"result"in F?F.result:F,L=e==null?void 0:e.meshId,D=l.useCallback(async()=>{if(!(!t||!n)){m(!0),g(null);try{const F=await n(t,"magi_kind_panel_list",{...L?{meshId:L}:{}}),z=T(F);if((z==null?void 0:z.success)===!1)throw new Error(z.error||r("meshGraph.magiKind.errorLoad"));p(z!=null&&z.kindPanels&&typeof z.kindPanels=="object"?z.kindPanels:{}),h({})}catch(F){g((F==null?void 0:F.message)||r("meshGraph.magiKind.errorLoad"))}finally{m(!1)}}},[t,n,L,r]);l.useEffect(()=>{D()},[D]);const M=l.useCallback(F=>{if(k[F])return k[F];const z=d[F];return z?z.map(u2):[]},[k,d]),_=(F,z)=>{h(Q=>({...Q,[F]:z}))},P=(F,z,Q)=>{const ne=M(F);_(F,ne.map((oe,Ce)=>Ce===z?{...oe,...Q}:oe))},B=F=>{_(F,[...M(F),d2()])},R=(F,z)=>{_(F,M(F).filter((Q,ne)=>ne!==z))},O=l.useCallback(async F=>{if(!t||!n)return;const z=p2(M(F));if("error"in z){const Q=z.error,ne=Q.code==="provider_required"?r("meshGraph.magiKind.errorSlotProvider",{slot:Q.slot}):Q.code==="replica_min"?r("meshGraph.magiKind.errorSlotReplica",{slot:Q.slot}):r("meshGraph.magiKind.errorNoSlot");g(`${F}: ${ne}`);return}S(F),g(null);try{const Q=await n(t,"magi_kind_panel_set",{kind:F,slots:z.slots,...L?{meshId:L}:{}}),ne=T(Q);if((ne==null?void 0:ne.success)===!1)throw new Error(ne.error||r("meshGraph.magiKind.errorSave"));await D()}catch(Q){g((Q==null?void 0:Q.message)||r("meshGraph.magiKind.errorSave"))}finally{S(null)}},[t,n,M,D,L,r]),H=l.useCallback(async F=>{if(!(!t||!n)&&confirm(r("meshGraph.magiKind.removeConfirm",{kind:F}))){S(F),g(null);try{const z=await n(t,"magi_kind_panel_remove",{kind:F,...L?{meshId:L}:{}}),Q=T(z);if((Q==null?void 0:Q.success)===!1)throw new Error(Q.error||r("meshGraph.magiKind.errorRemove"));await D()}catch(z){g((z==null?void 0:z.message)||r("meshGraph.magiKind.errorRemove"))}finally{S(null)}}},[t,n,D,L,r]),$=`w-full rounded-lg border px-2.5 py-1.5 text-xs ${i.isDark?"border-white/10 bg-slate-950/40 text-slate-100 placeholder:text-slate-500":"border-slate-300 bg-white text-slate-900 placeholder:text-slate-400"}`,I="btn btn-primary btn-sm",W="btn btn-secondary btn-sm";return s.jsxs("div",{className:"flex flex-col gap-3 p-1",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("p",{className:`text-[12px] ${i.textSecondary}`,children:r("meshGraph.magiKind.intro")}),s.jsx("div",{className:"ml-auto flex items-center gap-2",children:s.jsx("button",{type:"button",className:W,onClick:()=>void D(),disabled:u||!A,children:r(u?"meshGraph.magiKind.loading":"meshGraph.magiKind.refresh")})})]}),!A&&s.jsx("div",{className:`rounded-xl border p-3 text-[12px] ${i.textSecondary} ${i.isDark?"border-white/10":"border-slate-200"}`,children:r("meshGraph.magiKind.connectPrompt")}),f&&s.jsx("div",{className:"rounded-xl border border-rose-500/30 bg-rose-500/10 px-3 py-2 text-[12px] text-rose-300",children:f}),s.jsx("div",{className:"flex flex-col gap-3",children:c2.map(({kind:F,labelKey:z,hint:Q})=>{const ne=M(F),oe=!!d[F],Ce=x===F;return s.jsxs("div",{className:`${i.cardClass} rounded-2xl p-4 flex flex-col gap-3`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[13px] font-semibold ${i.textPrimary}`,children:r(z)}),s.jsx("span",{className:`font-mono text-[10px] ${i.textMuted}`,children:Q}),s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${oe?"border-emerald-400/30 bg-emerald-500/10 text-emerald-300":"border-slate-400/20 bg-slate-500/10 text-slate-300"}`,children:oe?r("meshGraph.magiKind.agentCount",{count:d[F].length}):r("meshGraph.magiKind.off")})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[ne.length===0&&s.jsx("div",{className:`rounded-xl border p-2.5 text-[11px] ${i.textSecondary} ${i.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:r("meshGraph.magiKind.noAgents")}),ne.map((le,U)=>{const J=le.nodeId?j[le.nodeId]??[]:[],ee=le.nodeId&&J.length?J:N;return s.jsxs("div",{className:`rounded-xl border p-2.5 grid grid-cols-1 sm:grid-cols-[1fr_1fr_1fr_auto_auto] gap-x-2 gap-y-1 items-start ${i.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:r("meshGraph.magiKind.machine")}),s.jsxs("select",{className:$,value:le.nodeId,onChange:Y=>P(F,U,{nodeId:Y.target.value}),title:r("meshGraph.magiKind.machineTitle"),children:[s.jsx("option",{value:"",children:r("meshGraph.magiKind.anyMachine")}),w.map(Y=>{const ve=C.has(Y),pe=ve?r("meshGraph.magiKind.worktreeSuffix",{label:y[Y]??Y,branch:v[Y]||r("meshGraph.magiKind.worktreeUnknownBranch")}):y[Y]??Y;return s.jsx("option",{value:Y,disabled:ve,title:ve?r("meshGraph.magiKind.worktreeDisabledTitle"):void 0,children:pe},Y)}),le.nodeId&&!w.includes(le.nodeId)&&s.jsx("option",{value:le.nodeId,children:r("meshGraph.magiKind.offlineSuffix",{label:y[le.nodeId]??le.nodeId})})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsxs("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:[r("meshGraph.magiKind.provider")," *"]}),s.jsxs("select",{className:$,value:le.provider,onChange:Y=>P(F,U,{provider:Y.target.value}),title:r("meshGraph.magiKind.providerTitle"),children:[s.jsx("option",{value:"",children:r("meshGraph.magiKind.selectProvider")}),ee.map(Y=>s.jsx("option",{value:Y,children:Y},Y)),le.provider&&!ee.includes(le.provider)&&s.jsx("option",{value:le.provider,children:le.provider})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:r("meshGraph.magiKind.model")}),(()=>{var pe;const Y=(le.provider?(pe=c.get(le.provider))==null?void 0:pe.models:void 0)??[],ve=!!le.model&&Y.length>0&&!Y.includes(le.model);return Y.length>0&&!ve?s.jsxs("select",{className:$,value:Y.includes(le.model)?le.model:"",title:r("meshGraph.magiKind.modelTitle"),onChange:te=>P(F,U,{model:te.target.value==="__custom__"?" ":te.target.value}),children:[s.jsx("option",{value:"",children:r("meshGraph.magiKind.modelDefault")}),Y.map(te=>s.jsx("option",{value:te,children:te},te)),s.jsx("option",{value:"__custom__",children:r("meshGraph.magiKind.modelCustom")})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:$,value:le.model.trim(),placeholder:r("meshGraph.magiKind.modelDefault"),title:r("meshGraph.magiKind.modelTitle"),onChange:te=>P(F,U,{model:te.target.value})}),Y.length>0&&s.jsx("button",{type:"button",className:`self-start bg-transparent border-none cursor-pointer p-0 text-[10px] ${i.textSecondary} hover:underline`,onClick:()=>P(F,U,{model:""}),children:r("meshGraph.magiKind.backToModelList")})]})})()]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:r("meshGraph.magiKind.copies")}),s.jsx("input",{className:`${$} sm:w-16`,value:le.n,placeholder:"1",inputMode:"numeric",title:r("meshGraph.magiKind.copiesTitle"),onChange:Y=>P(F,U,{n:Y.target.value})})]}),s.jsx("button",{type:"button",className:`${W} sm:mt-[18px] inline-flex h-8 w-8 items-center justify-center p-0`,onClick:()=>R(F,U),"aria-label":r("meshGraph.magiKind.removeAgent"),title:r("meshGraph.magiKind.removeAgent"),children:"✕"})]},U)}),s.jsx("div",{children:s.jsx("button",{type:"button",className:W,onClick:()=>B(F),disabled:!A,children:r("meshGraph.magiKind.addAgent")})})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",className:I,onClick:()=>void O(F),disabled:Ce||!A,children:r(Ce?"meshGraph.magiKind.saving":"meshGraph.magiKind.save")}),s.jsx("button",{type:"button",className:W,onClick:()=>void H(F),disabled:Ce||!A||!oe,title:r(oe?"meshGraph.magiKind.removeBindingTitle":"meshGraph.magiKind.removeBindingDisabledTitle"),children:r("meshGraph.magiKind.removeBinding")})]})]},F)})})]})}const Wn={sessionMinRemainingPercent:10,weeklyMinRemainingPercent:15,sessionResetImminentMinutes:5,staleAfterMinutes:30,spreadBonusMax:30,sessionAxisWeeklyHeadroomPercent:40},kl=60*1e3;function Ju(e){return e===void 0||!Number.isFinite(e)?"":String(e/kl)}function Sl(e){const t=e??{};return{sessionMinRemainingPercent:t.sessionMinRemainingPercent!==void 0?String(t.sessionMinRemainingPercent):"",weeklyMinRemainingPercent:t.weeklyMinRemainingPercent!==void 0?String(t.weeklyMinRemainingPercent):"",sessionResetImminentMinutes:Ju(t.sessionResetImminentMs),staleAfterMinutes:Ju(t.staleAfterMs),spreadBonusMax:t.spreadBonusMax!==void 0?String(t.spreadBonusMax):"",sessionAxisWeeklyHeadroomPercent:t.sessionAxisWeeklyHeadroomPercent!==void 0?String(t.sessionAxisWeeklyHeadroomPercent):""}}function h2(e,t){const n=t.trim();if(!n)return null;const a=Number(n);if(!Number.isFinite(a))return"notANumber";const r=e==="sessionMinRemainingPercent"||e==="weeklyMinRemainingPercent"||e==="sessionAxisWeeklyHeadroomPercent";return r&&(a<0||a>100)?"percentRange":!r&&a<0?"negative":null}function Cl(e){const t={},n=p=>{const u=p.trim();if(!u)return;const m=Number(u);return Number.isFinite(m)?m:void 0},a=n(e.sessionMinRemainingPercent);a!==void 0&&(t.sessionMinRemainingPercent=a);const r=n(e.weeklyMinRemainingPercent);r!==void 0&&(t.weeklyMinRemainingPercent=r);const o=n(e.sessionResetImminentMinutes);o!==void 0&&(t.sessionResetImminentMs=o*kl);const i=n(e.staleAfterMinutes);i!==void 0&&(t.staleAfterMs=i*kl);const c=n(e.spreadBonusMax);c!==void 0&&(t.spreadBonusMax=c);const d=n(e.sessionAxisWeeklyHeadroomPercent);return d!==void 0&&(t.sessionAxisWeeklyHeadroomPercent=d),t}const f2="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs",g2="w-full rounded-lg border border-red-500/60 bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function b2({quotaRouting:e,saving:t,error:n,onSave:a}){const{t:r}=ke("common"),[o,i]=l.useState(()=>Sl(e)),c=l.useCallback((k,h)=>{i(x=>({...x,[k]:h}))},[]),d=l.useMemo(()=>{const k={};for(const h of Object.keys(o)){const x=h2(h,o[h]);x&&(k[h]=x)}return k},[o]),p=Object.keys(d).length>0,u=l.useMemo(()=>JSON.stringify(Cl(o))!==JSON.stringify(x2(e)),[o,e]),m=l.useCallback(()=>{p||a(Cl(o))},[o,p,a]),f=l.useCallback(()=>{i(Sl(null))},[]),g=[{key:"sessionMinRemainingPercent",label:r("setupWizard.quotaPolicy.sessionMin"),hint:r("setupWizard.quotaPolicy.sessionMinHint"),placeholder:Wn.sessionMinRemainingPercent,unit:"%"},{key:"weeklyMinRemainingPercent",label:r("setupWizard.quotaPolicy.weeklyMin"),hint:r("setupWizard.quotaPolicy.weeklyMinHint"),placeholder:Wn.weeklyMinRemainingPercent,unit:"%"},{key:"sessionResetImminentMinutes",label:r("setupWizard.quotaPolicy.resetImminent"),hint:r("setupWizard.quotaPolicy.resetImminentHint"),placeholder:Wn.sessionResetImminentMinutes,unit:r("setupWizard.quotaPolicy.minutes")},{key:"staleAfterMinutes",label:r("setupWizard.quotaPolicy.staleAfter"),hint:r("setupWizard.quotaPolicy.staleAfterHint"),placeholder:Wn.staleAfterMinutes,unit:r("setupWizard.quotaPolicy.minutes")},{key:"spreadBonusMax",label:r("setupWizard.quotaPolicy.spreadBonus"),hint:r("setupWizard.quotaPolicy.spreadBonusHint"),placeholder:Wn.spreadBonusMax,unit:""},{key:"sessionAxisWeeklyHeadroomPercent",label:r("setupWizard.quotaPolicy.sessionAxisWeeklyHeadroom"),hint:r("setupWizard.quotaPolicy.sessionAxisWeeklyHeadroomHint"),placeholder:Wn.sessionAxisWeeklyHeadroomPercent,unit:"%"}];return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:r("setupWizard.quotaPolicy.title")}),s.jsx("p",{className:"mt-1 text-[11px] leading-relaxed text-text-muted",children:r("setupWizard.quotaPolicy.description")})]}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 sm:grid-cols-2",children:g.map(k=>{const h=d[k.key];return s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsxs("span",{className:"text-[11px] text-text-muted",children:[k.label,k.unit?` (${k.unit})`:""]}),s.jsx("input",{type:"number",inputMode:"decimal",className:h?g2:f2,value:o[k.key],placeholder:String(k.placeholder),onChange:x=>c(k.key,x.target.value)}),s.jsx("span",{className:`text-[10px] leading-snug ${h?"text-red-400":"text-text-muted"}`,children:h?r(`setupWizard.quotaPolicy.errors.${h}`):k.hint})]},k.key)})}),s.jsx("p",{className:"text-[10px] leading-relaxed text-text-muted",children:r("setupWizard.quotaPolicy.blankMeansDefault")}),n?s.jsx("p",{className:"text-[11px] text-red-400",children:n}):null,s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:f,children:r("setupWizard.quotaPolicy.useDefaults")}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm ml-auto",onClick:m,disabled:!!t||p||!u,children:r(t?"setupWizard.quotaPolicy.saving":"setupWizard.quotaPolicy.save")})]})]})}function x2(e){return Cl(Sl(e))}function ng(e,t,n,a){const{t:r}=ke(),[o,i]=l.useState(!1),[c,d]=l.useState(null),[p,u]=l.useState(null),[m,f]=l.useState(null),g=l.useCallback(async()=>{if(!e||!t){d(r("repoMesh.promptPreview.connectPrompt"));return}i(!0),d(null);try{const k=await a(e,"coordinator_prompt_preview",{meshId:t,cliType:n}),h=k!=null&&k.result&&typeof k.result=="object"?k.result:k;if(!(h!=null&&h.success))return d((h==null?void 0:h.error)||r("repoMesh.promptPreview.errorRender")),null;const x=typeof h.prompt=="string"?h.prompt:"";return u(x),f(typeof h.bytes=="number"?h.bytes:null),x}catch(k){return d((k==null?void 0:k.message)||String(k)),null}finally{i(!1)}},[e,t,n,a,r]);return{loading:o,error:c,prompt:p,bytes:m,load:g}}function v2({daemonId:e,meshId:t,cliType:n,sendCommand:a,defaultOpen:r=!1}){const{t:o}=ke(),[i,c]=l.useState(r),{loading:d,error:p,prompt:u,bytes:m,load:f}=ng(e,t,n,a),g=l.useRef(!1);l.useEffect(()=>{i&&!g.current&&(g.current=!0,f())},[i,f]);const k=l.useCallback(()=>{c(h=>!h)},[]);return s.jsxs("div",{className:"mt-2",children:[s.jsxs("button",{type:"button",onClick:k,className:"inline-flex items-center gap-1 text-[12px] text-accent-primary bg-transparent border-none cursor-pointer p-0",children:[s.jsx("span",{className:`transition-transform ${i?"rotate-90":""}`,"aria-hidden":!0,children:"▸"}),o(i?"repoMesh.promptPreview.hide":"repoMesh.promptPreview.view"),s.jsxs("span",{className:"text-text-muted",children:["(",n,")"]})]}),i&&s.jsxs("div",{className:"mt-2",children:[d&&s.jsx("div",{className:"text-[12px] text-text-muted",children:o("repoMesh.promptPreview.rendering")}),p&&s.jsxs("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:[p,s.jsx("button",{type:"button",onClick:()=>void f(),className:"ml-2 underline bg-transparent border-none cursor-pointer text-amber-300",children:o("repoMesh.promptPreview.retry")})]}),!d&&!p&&u!==null&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between text-[11px] text-text-muted",children:[s.jsx("span",{children:o("repoMesh.promptPreview.info")}),m!==null&&s.jsxs("span",{children:[(m/1024).toFixed(1)," KB"]})]}),s.jsx("textarea",{readOnly:!0,value:u,rows:14,className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-[12px] text-text-secondary font-mono",onFocus:h=>h.currentTarget.select()})]})]})]})}function y2({daemonId:e,meshId:t,cliType:n,sendCommand:a,disabled:r,hasContent:o,onApply:i}){const{t:c}=ke(),{loading:d,load:p}=ng(e,t,n,a),u=l.useCallback(async()=>{if(o&&!window.confirm(c("repoMesh.detail.startFromDefaultConfirm")))return;const m=await p();typeof m=="string"&&i(m)},[o,p,i,c]);return s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm mt-2",onClick:()=>void u(),disabled:r||d||!e||!t,title:c("repoMesh.detail.startFromDefaultTitle"),children:c(d?"repoMesh.promptPreview.rendering":"repoMesh.detail.startFromDefault")})}const w2=[{token:"meshName",description:"This mesh's display name.",example:"my-app"},{token:"repo",description:"Repo identity (owner/repo or workspace path).",example:"vilmire/adhdev"},{token:"defaultBranch",description:"The mesh's default branch.",example:"main"},{token:"cliType",description:"The coordinator CLI type this prompt is being rendered for.",example:"claude-cli"},{token:"nodes",description:"Live node status table, or the configured node list if no live status is available.",example:"(rendered node table)"},{token:"mission",description:"Current mission section, when a mission is active. Empty otherwise.",example:"(mission summary or empty)"},{token:"recentActivity",description:"Recent mesh activity summary. Empty when none.",example:"(recent activity or empty)"},{token:"operatingNotes",description:"Accumulated operating notes for this mesh. Empty when none.",example:"(operating notes or empty)"},{token:"policy",description:"The mesh's effective policy section (safety, scheduling, etc.).",example:"(rendered policy section)"},{token:"tools",description:"The canonical MCP tools reference table.",example:"(tools table)"},{token:"workflow",description:"The standard coordinator workflow guidance section.",example:"(workflow section)"},{token:"onboarding",description:"Onboarding/reinit guidance section.",example:"(onboarding section)"},{token:"rules",description:"CLI-type-specific and policy-derived rules section.",example:"(rules section)"},{token:"toolExposurePreflight",description:"Preflight guidance for verifying tool exposure before relying on it.",example:"(preflight section)"}],k2=e=>e&&typeof e=="object"&&"result"in e?e.result:e;function S2(e){const t=k2(e);return t&&typeof t=="object"&&t.status&&typeof t.status=="object"&&Array.isArray(t.status.missions)?t.status:t}function C2(e){const t=e==null?void 0:e.missions;return Array.isArray(t)?t:[]}function j2(e){return typeof e.goal=="string"&&e.goal?{text:e.goal,truncated:!1}:{text:e.goalPreview??"",truncated:e.goalTruncated===!0}}const N2=["active","paused","completed","abandoned"];function Xu(e){return(e.status||"active").toLowerCase()}const A2=8;function T2({status:e,daemonId:t,meshId:n,sendCommand:a}){const{t:r}=ke("common"),o=l.useMemo(()=>C2(e),[e]),[i,c]=l.useState({}),[d,p]=l.useState({}),[u,m]=l.useState(!1),[f,g]=l.useState(null),[k,h]=l.useState("active"),[x,S]=l.useState(!1),b=l.useMemo(()=>{const A={};for(const T of o){const L=Xu(T);A[L]=(A[L]||0)+1}return A},[o]),w=l.useMemo(()=>k==="all"?o:o.filter(A=>Xu(A)===k),[o,k]),C=x?w:w.slice(0,A2),v=w.length-C.length,y=!!t&&o.length>0,j=l.useCallback(async()=>{if(t){m(!0),g(null);try{const A=await a(t,"mesh_status",{meshId:n,verbose:!0}),T=S2(A),L=Array.isArray(T==null?void 0:T.missions)?T.missions:[],D={};for(const M of L)M.id&&typeof M.goal=="string"&&M.goal&&(D[M.id]=M.goal);c(M=>({...M,...D}))}catch(A){g(A instanceof Error?A.message:r("repoMesh.missions.errorFetch"))}finally{m(!1)}}},[t,n,a,r]),N=l.useCallback(A=>{p(T=>({...T,[A]:!T[A]})),!d[A]&&!i[A]&&j()},[d,i,j]);return o.length===0?null:s.jsxs(bt,{title:r("repoMesh.missions.title"),description:r("repoMesh.missions.description"),children:[f&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400",children:f}),s.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-1.5",children:[N2.filter(A=>(b[A]||0)>0).map(A=>s.jsxs("button",{type:"button",onClick:()=>{h(A),S(!1)},className:`rounded-full border px-2.5 py-0.5 text-[11px] capitalize transition-colors ${k===A?"border-accent-primary text-accent-primary":"border-border-subtle text-text-muted hover:text-text-secondary"}`,children:[A," ",b[A]]},A)),s.jsxs("button",{type:"button",onClick:()=>{h("all"),S(!1)},className:`rounded-full border px-2.5 py-0.5 text-[11px] transition-colors ${k==="all"?"border-accent-primary text-accent-primary":"border-border-subtle text-text-muted hover:text-text-secondary"}`,children:["All ",o.length]})]}),w.length===0&&s.jsx("div",{className:"text-[12px] text-text-muted",children:r("repoMesh.missions.empty",{status:k})}),s.jsx("div",{className:"flex flex-col gap-2",children:C.map(A=>{var B;const T=d[A.id]===!0,L=i[A.id],D=j2(A),M=T&&L?L:D.text,_=T&&!L&&D.truncated,P=((B=A.tasks)==null?void 0:B.total)??0;return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 px-3 py-2.5",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-text-primary",title:A.title,children:A.title||A.id}),A.status&&s.jsx("span",{className:"shrink-0 rounded-full border border-border-subtle px-2 py-0.5 text-[10px] uppercase tracking-wide text-text-muted",children:A.status}),P>0&&s.jsx("span",{className:"shrink-0 text-[11px] text-text-muted",children:r("repoMesh.missions.taskCount",{count:P})})]}),M&&s.jsxs("div",{className:`mt-1.5 whitespace-pre-wrap text-[12px] leading-5 text-text-secondary ${T?"max-h-72 overflow-y-auto":"line-clamp-2"}`,children:[M,_&&s.jsx("span",{className:"text-text-muted",children:r("repoMesh.missions.goalUnavailable")})]}),(D.truncated||L)&&y&&s.jsx("button",{type:"button",className:"mt-1.5 text-[12px] text-accent-primary hover:underline disabled:opacity-50",onClick:()=>N(A.id),disabled:u,children:r(T?"repoMesh.missions.showLess":u&&!L?"repoMesh.missions.loading":"repoMesh.missions.showFullGoal")})]},A.id)})}),v>0&&s.jsx("button",{type:"button",className:"mt-2 text-[12px] text-accent-primary hover:underline",onClick:()=>S(!0),children:r("repoMesh.missions.showMore",{count:v})})]})}function Zu(e,t){if(t)return e.modes.find(n=>n.id===t)}function M2(e){return e.modes.find(t=>t.strategy==="pty-parse-default"&&Gs(t)!=="dangerous")}function P2({config:e,requestedModeId:t,machineAutoApproveEnabled:n,machineDangerousAllowed:a}){const r=Zu(e,e.default),o=r==null?void 0:r.id,i=(t==null?void 0:t.trim())||void 0;if(!n)return{status:"disabled",requestedModeId:i,providerDefaultModeId:o,requestedModeUnknown:!1,downgraded:!1};const c=Zu(e,i),d=!!i&&!c,p=c??r;if(!p||p.strategy==="post-boot-command")return{status:"none",requestedModeId:i,providerDefaultModeId:o,requestedModeUnknown:d,downgraded:!1};if(Gs(p)==="dangerous"&&!a){const u=M2(e);return{status:u?"downgraded":"none",requestedModeId:i,providerDefaultModeId:o,effectiveMode:u,requestedModeUnknown:d,downgraded:!0}}return{status:d?"invalid_fallback":"requested",requestedModeId:i,providerDefaultModeId:o,effectiveMode:p,requestedModeUnknown:d,downgraded:!1}}function D2(e){const t=[];for(const n of e||[]){if(!n||n.category!=="cli")continue;const a=n.autoApproveModes;if(!a||!Array.isArray(a.modes)||a.modes.length===0)continue;const r=String(n.type||n.id||"").trim();r&&t.push({type:r,label:String(n.displayName||n.name||r),autoApproveModes:a})}return t}function I2({hostDaemonId:e,hostOnline:t,hostWorkspace:n,meshProviders:a,unreportedNodeCount:r=0,machineAutoApproveEnabled:o,machineDangerousAllowed:i,onUpdatePolicy:c,savingPolicy:d,sendCommand:p}){const{t:u}=ke("common"),m=l.useMemo(()=>D2(a),[a]),[f,g]=l.useState({}),[k,h]=l.useState(!1),[x,S]=l.useState(null),[b,w]=l.useState(!1),[C,v]=l.useState(null),[y,j]=l.useState(!1),[N,A]=l.useState(null),[T,L]=l.useState(!1),D=!!e&&t&&!!n,M=!!c&&!d,_=l.useCallback(async()=>{var H,$,I;if(D){h(!0),S(null);try{const W=await p(e,"read_mesh_json_config",{workspace:n}),F=(W==null?void 0:W.result)??W,z=((H=F==null?void 0:F.providerDefaults)==null?void 0:H.autoApproveModes)||((I=($=F==null?void 0:F.config)==null?void 0:$.providerDefaults)==null?void 0:I.autoApproveModes),Q={};if(z&&typeof z=="object")for(const[ne,oe]of Object.entries(z))typeof oe=="string"&&oe.trim()&&(Q[ne]=oe.trim());g(Q)}catch(W){S((W==null?void 0:W.message)||u("repoMesh.providerAutoApprove.loadError"))}finally{h(!1)}}},[D,e,n,p,u]);l.useEffect(()=>{_()},[_]);const P=l.useCallback((H,$)=>{j(!1),g(I=>{const W={...I};return $&&$.trim()?W[H]=$.trim():delete W[H],W})},[]),B=l.useCallback((H,$)=>{if(Gs($)==="dangerous"){A({type:H,mode:$});return}P(H,$.id)},[P]),R=l.useCallback(()=>{N&&P(N.type,N.mode.id),A(null)},[P,N]),O=l.useCallback(async()=>{if(D){w(!0),v(null),j(!1);try{const H=await p(e,"set_mesh_provider_defaults",{workspace:n,autoApproveModes:f,merge:!1,write:!0}),$=(H==null?void 0:H.result)??H;if(($==null?void 0:$.success)===!1)throw new Error(($==null?void 0:$.error)||u("repoMesh.providerAutoApprove.saveError"));j(!0),await _()}catch(H){v((H==null?void 0:H.message)||u("repoMesh.providerAutoApprove.saveError"))}finally{w(!1)}}},[D,e,n,_,f,p,u]);return s.jsxs(bt,{title:u("repoMesh.providerAutoApprove.title"),description:u("repoMesh.providerAutoApprove.subtitle"),collapsible:!0,defaultOpen:!1,children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/40 p-3.5",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:u("repoMesh.providerAutoApprove.machineSection.title")}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:u("repoMesh.providerAutoApprove.machineSection.hint")}),s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2 text-[11px]",children:[s.jsx("span",{className:`rounded-full border px-2 py-0.5 font-semibold ${o?"border-status-online/25 bg-status-online/10 text-status-online":"border-border-subtle bg-surface-secondary/40 text-text-muted"}`,children:u(o?"repoMesh.providerAutoApprove.machineSection.autoApproveOn":"repoMesh.providerAutoApprove.machineSection.autoApproveOff")}),s.jsx("span",{className:`rounded-full border px-2 py-0.5 font-semibold ${i?"border-status-error/30 bg-status-error/10 text-status-error":"border-border-subtle bg-surface-secondary/40 text-text-muted"}`,children:u(i?"repoMesh.providerAutoApprove.machineSection.dangerousOn":"repoMesh.providerAutoApprove.machineSection.dangerousOff")})]}),s.jsxs("div",{className:"mt-3 space-y-2",children:[s.jsx(ep,{label:u("repoMesh.providerAutoApprove.machineSection.autoApproveToggleLabel"),hint:u("repoMesh.providerAutoApprove.machineSection.autoApproveToggleHint"),checked:o,disabled:!M,onChange:H=>c==null?void 0:c({delegatedWorkerAutoApprove:H})}),s.jsx(ep,{label:u("repoMesh.providerAutoApprove.machineSection.dangerousToggleLabel"),hint:u(o?"repoMesh.providerAutoApprove.machineSection.dangerousToggleHint":"repoMesh.providerAutoApprove.machineSection.dangerousDisabledHint"),checked:i,disabled:!M||!o,onChange:H=>{H?L(!0):c==null||c({delegatedWorkerDangerousModeAllow:!1})}})]})]}),D?k?s.jsx("div",{className:"text-[13px] text-text-muted",children:u("repoMesh.providerAutoApprove.loading")}):m.length===0?s.jsx("div",{className:"text-[13px] text-text-muted",children:r>0?u("repoMesh.providerAutoApprove.awaitingNodes",{count:r}):u("repoMesh.providerAutoApprove.noProviders")}):s.jsxs("div",{className:"space-y-6",children:[x&&s.jsx(Mt,{variant:"error",onDismiss:()=>S(null),children:x}),r>0&&s.jsx("div",{className:"text-[11px] text-text-muted",children:u("repoMesh.providerAutoApprove.partialInventory",{count:r})}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:u("repoMesh.providerAutoApprove.repoSection.title")}),s.jsx("div",{className:"text-[11px] text-text-muted",children:u("repoMesh.providerAutoApprove.repoSection.hint")})]}),s.jsx("div",{className:"space-y-5",children:m.map(H=>{const $=f[H.type],I=P2({config:H.autoApproveModes,requestedModeId:$,machineAutoApproveEnabled:o,machineDangerousAllowed:i});return s.jsxs("div",{className:"rounded-xl border border-border-subtle p-3.5",children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary",children:H.label}),s.jsx("button",{type:"button",className:"text-[11px] text-text-muted underline decoration-dotted hover:text-text-primary disabled:opacity-40",onClick:()=>P(H.type,void 0),disabled:!$||b,children:u("repoMesh.providerAutoApprove.repoSection.clear")})]}),s.jsx(lf,{config:H.autoApproveModes,selectedModeId:$||"",disabled:b,onSelectMode:W=>B(H.type,W)}),!$&&s.jsx("div",{className:"mt-1.5 text-[11px] text-text-muted",children:u("repoMesh.providerAutoApprove.repoSection.usesProviderDefault")}),s.jsx(L2,{effective:I,config:H.autoApproveModes})]},H.type)})}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:u("repoMesh.providerAutoApprove.effectiveSection.title")}),s.jsx("div",{className:"text-[11px] text-text-muted",children:u("repoMesh.providerAutoApprove.effectiveSection.hint")})]}),C&&s.jsx(Mt,{variant:"error",onDismiss:()=>v(null),children:C}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("button",{type:"button",className:"rounded-lg bg-accent-primary px-4 py-2 text-sm font-semibold text-white disabled:opacity-50",onClick:()=>void O(),disabled:b,children:u(b?"repoMesh.providerAutoApprove.saving":"repoMesh.providerAutoApprove.save")}),y&&s.jsx("span",{className:"text-[12px] text-status-online",children:u("repoMesh.providerAutoApprove.saved")})]})]}):s.jsx("div",{className:"text-[13px] text-text-muted",children:u("repoMesh.providerAutoApprove.noHostDaemon")}),T&&s.jsx(jo,{title:u("repoMesh.providerAutoApprove.machineSection.confirmTitle"),description:u("repoMesh.providerAutoApprove.machineSection.confirmDescription"),details:[{label:u("repoMesh.providerAutoApprove.machineSection.confirmScopeLabel"),value:u("repoMesh.providerAutoApprove.machineSection.confirmScopeValue")},{label:u("repoMesh.providerAutoApprove.machineSection.confirmEffectLabel"),value:u("repoMesh.providerAutoApprove.machineSection.confirmEffectValue")}],confirmLabel:u("repoMesh.providerAutoApprove.machineSection.confirmConfirm"),onConfirm:()=>{L(!1),c==null||c({delegatedWorkerDangerousModeAllow:!0})},onCancel:()=>L(!1)}),N&&s.jsx(cf,{mode:N.mode,onConfirm:R,onCancel:()=>A(null)}),N&&s.jsx("div",{className:"fixed inset-x-0 bottom-6 z-[60] mx-auto max-w-lg px-4",children:s.jsxs("div",{className:"rounded-xl border border-status-error/40 bg-bg-primary p-3.5 shadow-lg",children:[s.jsx("div",{className:"text-sm font-semibold text-status-error",children:u("repoMesh.providerAutoApprove.dangerous.sharedWarningTitle")}),s.jsx("div",{className:"mt-1 text-[12px] text-text-muted",children:u("repoMesh.providerAutoApprove.dangerous.sharedWarning")})]})})]})}function L2({effective:e,config:t}){var c,d,p;const{t:n}=ke("common"),a=u=>{var m;return(u?(m=t.modes.find(f=>f.id===u))==null?void 0:m.label:void 0)||u||""};let r,o="ok";switch(e.status){case"requested":r=n("repoMesh.providerAutoApprove.effectiveSection.statusRequested",{mode:((c=e.effectiveMode)==null?void 0:c.label)||""});break;case"invalid_fallback":r=n("repoMesh.providerAutoApprove.effectiveSection.statusInvalidFallback",{mode:((d=e.effectiveMode)==null?void 0:d.label)||""}),o="warn";break;case"downgraded":r=n("repoMesh.providerAutoApprove.effectiveSection.statusDowngraded",{requested:a(e.requestedModeId)||a(e.providerDefaultModeId),mode:((p=e.effectiveMode)==null?void 0:p.label)||""}),o="warn";break;case"disabled":r=n("repoMesh.providerAutoApprove.effectiveSection.statusDisabled"),o="muted";break;default:r=n("repoMesh.providerAutoApprove.effectiveSection.statusNone"),o="muted"}const i=o==="ok"?"border-status-online/25 bg-status-online/5 text-text-secondary":o==="warn"?"border-status-warning/30 bg-status-warning/5 text-status-warning":"border-border-subtle bg-surface-secondary/30 text-text-muted";return s.jsxs("div",{className:`mt-3 flex items-center gap-2 rounded-lg border px-3 py-2 text-[12px] ${i}`,children:[e.effectiveMode&&s.jsx(of,{risk:Gs(e.effectiveMode)}),s.jsx("span",{className:"min-w-0",children:r})]})}function ep({label:e,hint:t,checked:n,disabled:a=!1,onChange:r}){return s.jsxs("button",{type:"button",role:"switch","aria-checked":n,className:"flex w-full items-center justify-between gap-3 rounded-xl border border-border-subtle bg-bg-primary/60 px-3.5 py-2.5 text-left disabled:opacity-50",onClick:()=>r(!n),disabled:a,children:[s.jsxs("span",{children:[s.jsx("span",{className:"block text-[13px] font-semibold text-text-primary",children:e}),s.jsx("span",{className:"mt-0.5 block text-[11px] text-text-muted",children:t})]}),s.jsx("span",{className:`relative h-6 w-11 shrink-0 rounded-full transition-colors ${n?"bg-accent-primary":"bg-surface-secondary"}`,children:s.jsx("span",{className:`absolute top-0.5 h-5 w-5 rounded-full bg-white shadow transition-transform ${n?"translate-x-5":"translate-x-0.5"}`})})]})}function kr(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function R2({daemons:e,coordinatorDaemonId:t,onCoordinatorDaemonIdChange:n,isHostNodeAttached:a,selectedHostNode:r,hostPinned:o,hostLabel:i,hostOnline:c,hostRebindDaemonId:d,onHostRebindDaemonIdChange:p,settingMeshHost:u,onSetMeshHost:m}){const{t:f}=ke("common");if(o)return s.jsxs(bt,{title:f("repoMesh.host.title"),description:f("repoMesh.host.descriptionSet"),children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[s.jsxs("span",{className:`inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-[13px] text-text-primary ${c?"border-accent-primary/40 bg-accent-primary/10":"border-amber-500/40 bg-amber-500/10"}`,children:[s.jsx("span",{className:"text-text-muted",children:f("repoMesh.host.hostLabel")}),s.jsx("span",{className:"font-medium",children:i||f("repoMesh.host.unknown")}),s.jsxs("span",{className:c?"text-text-muted":"text-amber-400",children:["· ",f(c?"repoMesh.host.online":"repoMesh.host.offline")]})]}),(r==null?void 0:r.workspace)&&s.jsxs("span",{className:"text-[12px] text-text-muted",children:[f("repoMesh.host.hostNode")," ",s.jsx("span",{className:"font-mono text-text-secondary",children:r.workspace})]})]}),!c&&s.jsxs("div",{className:"mt-4",children:[s.jsxs(Mt,{variant:"warning",className:"mb-3",children:[s.jsx("strong",{children:f("repoMesh.host.hostOffline")})," ",f("repoMesh.host.hostOfflineText")]}),e.length>0?s.jsx(Tt,{label:f("repoMesh.host.reconnectToCommand"),hint:f("repoMesh.host.reconnectToCommandHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:d,onChange:h=>p(h.target.value),children:[s.jsx("option",{value:"",children:f("repoMesh.host.waitForHost")}),e.map(h=>s.jsx("option",{value:h.id,children:kr(h)},h.id))]})}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:f("repoMesh.host.noDaemonsToRoute")})]})]});const g=e.find(h=>h.id===t),k=m&&t?s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>m(t),disabled:!!u,children:f(u?"repoMesh.host.settingHost":"repoMesh.host.setHostAction")}):null;return s.jsxs(bt,{title:f("repoMesh.host.title"),description:f("repoMesh.host.descriptionUnset"),children:[s.jsxs(Mt,{variant:"info",className:"mb-4",children:[s.jsx("strong",{children:f("repoMesh.host.setHostBanner")})," ",f("repoMesh.host.setHostBannerText")]}),e.length>0?s.jsxs(s.Fragment,{children:[t?s.jsx("div",{className:"mb-3 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:a?s.jsxs(s.Fragment,{children:["Will host on ",s.jsx("span",{className:"font-medium text-text-primary",children:kr(g)}),r!=null&&r.workspace?s.jsxs(s.Fragment,{children:[" · setup node ",s.jsx("span",{className:"font-mono text-text-secondary",children:r.workspace})]}):null,". ",f("repoMesh.host.confirmSetsHost")]}):s.jsxs(s.Fragment,{children:["Will host on ",s.jsx("span",{className:"font-medium text-text-primary",children:kr(g)}),". ",f("repoMesh.host.attachNodeThenSetHost")]})}):s.jsx(Tt,{label:f("repoMesh.host.hostDaemon"),hint:f("repoMesh.host.hostDaemonHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:"",onChange:h=>n(h.target.value),children:[s.jsx("option",{value:"",children:f("repoMesh.host.resolvingHost")}),e.map(h=>s.jsx("option",{value:h.id,children:kr(h)},h.id))]})}),k&&s.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[k,s.jsx("span",{className:"text-[12px] text-text-muted",children:f("repoMesh.host.setHostActionHint")})]})]}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:f("repoMesh.host.noDaemonsToHost")})]})}function E2({meshId:e,availableCliAgents:t}){const{t:n}=ke(),a=t.find(o=>{const i=o.id.toLowerCase();return i==="hermes-cli"||i.includes("hermes")||o.name.toLowerCase().includes("hermes")}),r=Eh(a==null?void 0:a.meshCoordinator,{meshId:e});return r?s.jsx(bt,{title:n("repoMesh.hermesMcp.title"),description:n("repoMesh.hermesMcp.description"),children:s.jsx(rf,{setup:r,providerName:(a==null?void 0:a.name)||n("repoMesh.hermesMcp.fallbackProvider")})}):null}const Ri=[{value:"preserve",label:"Preserve history and runtimes",description:"Keep completed chat history and leave live runtimes alone."},{value:"stop",label:"Stop live runtimes only",description:"Release running session processes, but keep chat records/transcripts."},{value:"delete_stopped",label:"Delete stopped sessions only",description:"Clean completed/stopped chat clutter without killing live runtimes."},{value:"stop_and_delete",label:"Stop and delete sessions",description:"Stop matching runtimes, then remove their session records/transcripts."}],_2=[{value:"smart",labelKey:"repoMesh.detail.distributionSmart",descriptionKey:"repoMesh.detail.distributionSmartDescription"},{value:"in_order",labelKey:"repoMesh.detail.distributionInOrder",descriptionKey:"repoMesh.detail.distributionInOrderDescription"}];function H2(e){return e==="smart"?"fitness":"first_eligible"}function $2(e,t){const n=e||"first_eligible";return n==="fitness"||n==="least_loaded"||n==="round_robin"||n==="priority_only"&&t!=null&&t.priorityConfigured?"smart":"in_order"}const F2={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,allowAutoPublishSubmoduleMainCommits:!1,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,schedulingStrategy:"first_eligible",sessionCleanupOnNodeRemove:"preserve"};function jl(e){return{...F2,...(e==null?void 0:e.policy)||{}}}function B2(e){return{routeId:`mesh-settings:${e.meshId}`,daemonId:e.daemonId,agentName:e.meshName,agentType:"mesh",status:"idle",title:e.meshName,messages:[],workspaceName:e.meshName,displayPrimary:e.meshName,displaySecondary:"Mesh observability",streamSource:"native",tabKey:`mesh-settings:${e.meshId}`,coordinator:{meshId:e.meshId,role:"coordinator"},settings:{meshCoordinatorFor:e.meshId}}}function W2({selectedMesh:e,error:t,onDismissError:n,onBack:a,onDelete:r,displayedMeshStatus:o,graphLoading:i,graphError:c,onRefreshGraph:d,savingPolicy:p,onUpdatePolicy:u,coordinatorPromptDraft:m,onCoordinatorPromptDraftChange:f,savingCoordinatorPrompt:g,onSaveCoordinatorPrompt:k,daemons:h,coordinatorDaemonId:x,onCoordinatorDaemonIdChange:S,coordinatorCliType:b,isHostNodeAttached:w,selectedHostNode:C,hostPinned:v,hostLabel:y,hostOnline:j,hostRebindDaemonId:N,onHostRebindDaemonIdChange:A,settingMeshHost:T,onSetMeshHost:L,activeDaemon:D,activeDaemonId:M,meshQueue:_,userName:P,availableCliProviders:B,savingNodeSlotsId:R,onUpdateNodeSlots:O,savingNodeCapabilitiesId:H,onUpdateNodeCapabilities:$,nodeSystemPromptDrafts:I,onNodeSystemPromptDraftChange:W,savingNodeSystemPromptId:F,onSaveNodeSystemPrompt:z,selectedNodeId:Q,onSelectNode:ne,showAddNode:oe,onShowAddNode:Ce,onCancelAddNode:le,nodeWorkspace:U,onNodeWorkspaceChange:J,nodeProviderPriority:ee,onNodeProviderPriorityChange:Y,nodeDaemonId:ve,onNodeDaemonIdChange:pe,nodeCustomPath:te,onNodeCustomPathChange:me,nodePickerWorkspaces:V,nodePickerProviders:q,nodeOnboardingPlan:se,nodePlanLoading:de,attachableDaemons:K,onAddNode:fe,onRemoveNode:ie,availableCliAgents:ue,features:ye,sendCommand:Ie}){const{t:E}=ke("common"),Z=jl(e),we=e.nodes||[],ge=l.useMemo(()=>OL(we,h),[we,h]),be=we.some(st=>{var Le;const X=Number((Le=st.policy)==null?void 0:Le.schedulingPriority);return Number.isFinite(X)&&X!==0}),Pe=!Z.schedulingStrategy,Me=l.useMemo(()=>we.some(st=>{var X;return Array.isArray((X=st.policy)==null?void 0:X.slots)&&st.policy.slots.length>0}),[we]),We=Pe&&(Me||we.length>=2)?"smart":null,[Be,Xe]=l.useState(!1),at=!!M&&!!e.id;return s.jsxs(Qa,{icon:s.jsx(cs,{}),title:e.name,subtitle:e.repoIdentity||e.repo_identity||"Repo Mesh",widthClassName:"max-w-5xl",actions:s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:a,children:E("repoMesh.detail.back")}),s.jsxs("button",{className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:()=>d(!0),disabled:i,children:[s.jsx(LL,{size:13}),E(i?"repoMesh.detail.probing":"repoMesh.detail.refresh")]}),s.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>r(e.id),children:E("repoMesh.detail.delete")})]}),children:[t&&s.jsx(Mt,{variant:"error",onDismiss:n,className:"mb-4",children:t}),(()=>{var rt;const st=s.jsxs(s.Fragment,{children:[ye.meshHostDaemonSection&&s.jsx(R2,{daemons:h,coordinatorDaemonId:x,onCoordinatorDaemonIdChange:S,isHostNodeAttached:w,selectedHostNode:C,hostPinned:v,hostLabel:y,hostOnline:j,hostRebindDaemonId:N,onHostRebindDaemonIdChange:G=>{A(G),d()},settingMeshHost:T,onSetMeshHost:L}),s.jsxs(bt,{title:E("repoMesh.detail.observabilityTitle"),description:E("repoMesh.detail.observabilityDescription"),children:[c&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2",children:c}),s.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[s.jsxs("button",{type:"button",className:"btn btn-primary btn-sm inline-flex items-center gap-1.5",onClick:()=>Xe(!0),disabled:!at,title:E(at?"repoMesh.detail.observabilityOpenTitle":"repoMesh.detail.observabilityDisabledTitle"),children:[s.jsx(cs,{size:14}),E("repoMesh.detail.observabilityOpen")]}),s.jsx("span",{className:"text-[12px] text-text-muted",children:E("repoMesh.detail.observabilityHint")})]})]}),s.jsx(i2,{nodes:we,meshQueue:_,activeDaemon:D,daemons:h,selectedMeshId:e.id,userName:P,features:{addNodeDaemonPicker:ye.addNodeDaemonPicker,nodeInstruction:ye.nodeInstruction},coordinatorDaemonId:x,availableCliProviders:B,savingNodeSlotsId:R,onUpdateNodeSlots:O,savingNodeCapabilitiesId:H,onUpdateNodeCapabilities:$,nodeSystemPromptDrafts:I,onNodeSystemPromptDraftChange:W,savingNodeSystemPromptId:F,onSaveNodeSystemPrompt:z,selectedNodeId:Q,onSelectNode:ne,showAddNode:oe,onShowAddNode:Ce,onCancelAddNode:le,nodeWorkspace:U,onNodeWorkspaceChange:J,nodeProviderPriority:ee,onNodeProviderPriorityChange:Y,nodeDaemonId:ve,onNodeDaemonIdChange:pe,nodeCustomPath:te,onNodeCustomPathChange:me,nodePickerWorkspaces:V,nodePickerProviders:q,nodeOnboardingPlan:se,nodePlanLoading:de,attachableDaemons:K,onAddNode:fe,onRemoveNode:ie})]}),X=s.jsxs(s.Fragment,{children:[s.jsxs(bt,{title:E("repoMesh.detail.schedulingTitle"),description:E("repoMesh.detail.schedulingDescription"),children:[s.jsxs("fieldset",{className:"border-none p-0 m-0",children:[s.jsx("legend",{className:"text-[13px] font-medium text-text-secondary mb-2",children:E("repoMesh.detail.distribution")}),s.jsx("div",{className:"flex flex-col gap-2",children:_2.map(G=>{const ce=$2(Z.schedulingStrategy,{priorityConfigured:be})===G.value;return s.jsxs("label",{className:`flex items-start gap-3 rounded-lg border px-3 py-2.5 cursor-pointer transition-colors ${ce?"border-accent-primary/60 bg-accent-primary/10":"border-border-subtle bg-bg-secondary/60 hover:border-border-default"}`,children:[s.jsx("input",{type:"radio",name:"mesh-distribution",className:"mt-0.5 accent-[var(--accent-primary)]",value:G.value,checked:ce,disabled:p,onChange:()=>u({schedulingStrategy:H2(G.value)})}),s.jsxs("span",{className:"min-w-0",children:[s.jsxs("span",{className:"flex items-center gap-2 text-sm text-text-primary",children:[E(G.labelKey),We===G.value&&s.jsx("span",{className:"rounded-full border border-accent-primary/40 bg-accent-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-accent-primary",children:E("repoMesh.detail.recommended")})]}),s.jsx("span",{className:"block text-[12px] text-text-muted",children:E(G.descriptionKey)})]})]},G.value)})})]}),p&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:E("repoMesh.detail.saving")})]}),s.jsx(bt,{title:E("repoMesh.detail.visibilityTitle"),description:E("repoMesh.detail.visibilityDescription"),children:s.jsx(Tt,{label:E("repoMesh.detail.visibilityLabel"),hint:E("repoMesh.detail.visibilityHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:Z.spawnedSessionVisibility==="visible"?"visible":"hidden",onChange:G=>u({spawnedSessionVisibility:G.target.value==="visible"?"visible":"hidden"}),disabled:p,children:[s.jsx("option",{value:"hidden",children:E("repoMesh.detail.visibilityHidden")}),s.jsx("option",{value:"visible",children:E("repoMesh.detail.visibilityVisible")})]})})}),o&&s.jsx(bt,{title:E("repoMesh.detail.magiTitle"),description:E("repoMesh.detail.magiDescription"),children:s.jsx(m2,{status:o,daemonId:M,sendDaemonCommand:Ie,availableProviders:B})}),s.jsx(bt,{children:s.jsx(b2,{quotaRouting:Z.quotaRouting??null,saving:p,error:t,onSave:G=>u({quotaRouting:G})})}),s.jsx(I2,{hostDaemonId:x,hostOnline:j,hostWorkspace:(C==null?void 0:C.workspace)||"",meshProviders:ge.providers,unreportedNodeCount:ge.unreportedNodeCount,machineAutoApproveEnabled:Z.delegatedWorkerAutoApprove!==!1,machineDangerousAllowed:Z.delegatedWorkerDangerousModeAllow===!0,onUpdatePolicy:u,savingPolicy:p,sendCommand:Ie})]}),Le=s.jsx(s.Fragment,{children:ye.coordinatorPrompt&&s.jsx(bt,{title:E("repoMesh.detail.coordinatorPromptTitle"),collapsible:!0,defaultOpen:!1,badge:s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:E("repoMesh.detail.advanced")}),description:E("repoMesh.detail.coordinatorPromptDescription"),children:s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 p-3",children:[s.jsx("div",{className:"text-[13px] font-semibold mb-1",children:E("repoMesh.detail.thisMesh")}),s.jsx("p",{className:"text-[12px] text-text-muted mb-3",children:E("repoMesh.detail.thisMeshHint",{name:e.name})}),s.jsx(v2,{daemonId:M,meshId:e.id,cliType:b,sendCommand:Ie,defaultOpen:!0}),s.jsxs(Tt,{label:E("repoMesh.detail.overrideLabel"),hint:E("repoMesh.detail.overrideHint"),className:"mt-3",children:[s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:6,value:m.override,onChange:G=>f({...m,override:G.target.value}),disabled:g,placeholder:E("repoMesh.detail.overridePlaceholder")}),s.jsx(y2,{daemonId:M,meshId:e.id,cliType:b,sendCommand:Ie,disabled:g,hasContent:!!m.override.trim(),onApply:G=>f({...m,override:G})})]}),s.jsx(Tt,{label:E("repoMesh.detail.appendLabel"),hint:E("repoMesh.detail.appendHint"),children:s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:4,value:m.append,onChange:G=>f({...m,append:G.target.value}),disabled:g,placeholder:E("repoMesh.detail.appendPlaceholder")})}),s.jsxs("details",{className:"mt-2 text-[12px] text-text-muted",children:[s.jsx("summary",{className:"cursor-pointer select-none",children:E("repoMesh.detail.availablePlaceholders")}),s.jsx("p",{className:"mt-1",children:E("repoMesh.detail.placeholdersIntro")}),s.jsx("div",{className:"mt-2 overflow-x-auto",children:s.jsx("table",{className:"w-full text-left border-collapse",children:s.jsx("tbody",{children:w2.map(G=>s.jsxs("tr",{className:"border-t border-border-subtle/60 align-top",children:[s.jsx("td",{className:"py-1 pr-3 font-mono whitespace-nowrap text-text-secondary",children:`{{${G.token}}}`}),s.jsx("td",{className:"py-1 pr-3",children:G.description}),s.jsx("td",{className:"py-1 font-mono text-text-muted/80",children:G.example})]},G.token))})})})]}),s.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:k,disabled:g,children:E(g?"repoMesh.detail.saving":"repoMesh.detail.saveCoordinatorPrompt")}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>f({override:"",append:""}),disabled:g,title:E("repoMesh.detail.clearTitle"),children:E("repoMesh.detail.clear")})]})]})})}),_e=s.jsxs(s.Fragment,{children:[s.jsx(T2,{status:o,daemonId:M,meshId:e.id,sendCommand:Ie}),s.jsxs(bt,{title:E("repoMesh.detail.safetyTitle"),collapsible:!0,defaultOpen:!1,badge:s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:E("repoMesh.detail.advanced")}),description:E("repoMesh.detail.safetyDescription"),children:[s.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:[{label:E("repoMesh.detail.checkpointBefore"),key:"requirePreTaskCheckpoint",opts:[["no","No"],["yes","Yes"]],val:G=>G?"yes":"no",parse:G=>G==="yes"},{label:E("repoMesh.detail.checkpointAfter"),key:"requirePostTaskCheckpoint",opts:[["yes","Yes"],["no","No"]],val:G=>G?"yes":"no",parse:G=>G==="yes"},{label:E("repoMesh.detail.pushApproval"),key:"requireApprovalForPush",opts:[["required",E("repoMesh.detail.requireApprovalBeforePush")],["not_required",E("repoMesh.detail.doNotRequireApproval")]],val:G=>G?"required":"not_required",parse:G=>G==="required"},{label:E("repoMesh.detail.destructiveGitApproval"),key:"requireApprovalForDestructiveGit",opts:[["required",E("repoMesh.detail.requireApproval")],["not_required",E("repoMesh.detail.doNotRequireApproval")]],val:G=>G?"required":"not_required",parse:G=>G==="required"},{label:E("repoMesh.detail.uncommittedChanges"),key:"dirtyWorkspaceBehavior",opts:[["warn",E("repoMesh.detail.warnAndContinue")],["block",E("repoMesh.detail.blockTask")],["checkpoint_then_continue",E("repoMesh.detail.checkpointThenContinue")]],val:G=>G||"warn",parse:G=>G},{label:E("repoMesh.detail.autoPublishSubmodule"),key:"allowAutoPublishSubmoduleMainCommits",opts:[["disabled",E("repoMesh.detail.requireExplicitApproval")],["enabled",E("repoMesh.detail.allowRefineryPublish")]],val:G=>G?"enabled":"disabled",parse:G=>G==="enabled"}].map(({label:G,key:re,opts:ce,val:xe,parse:Se})=>s.jsx(Tt,{label:G,children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:xe(Z[re]),onChange:Ae=>u({[re]:Se(Ae.target.value)}),disabled:p,children:ce.map(([Ae,Ee])=>s.jsx("option",{value:Ae,children:Ee},Ae))})},re))}),(()=>{const G=Z.autoFastForward&&typeof Z.autoFastForward=="object"?Z.autoFastForward:{},re=G.enabled!==!1,ce=G.remoteNodes===!0,xe=G.mode==="continuous"?"continuous":"idle",Se=Ae=>u({autoFastForward:{...G,...Ae}});return s.jsxs("div",{className:"mt-4 grid gap-4 sm:grid-cols-2",children:[s.jsx(Tt,{label:E("repoMesh.detail.autoFastForward"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:re?"enabled":"disabled",onChange:Ae=>Se({enabled:Ae.target.value==="enabled"}),disabled:p,children:[s.jsx("option",{value:"enabled",children:E("repoMesh.detail.ffEnabled")}),s.jsx("option",{value:"disabled",children:E("repoMesh.detail.ffDisabled")})]})}),s.jsx(Tt,{label:E("repoMesh.detail.includeRemoteNodes"),hint:E("repoMesh.detail.includeRemoteNodesHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:ce?"yes":"no",onChange:Ae=>Se({remoteNodes:Ae.target.value==="yes"}),disabled:p||!re,children:[s.jsx("option",{value:"no",children:E("repoMesh.detail.remoteNo")}),s.jsx("option",{value:"yes",children:E("repoMesh.detail.remoteYes")})]})}),s.jsx(Tt,{label:E("repoMesh.detail.detectionMode"),hint:E("repoMesh.detail.detectionModeHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:xe,onChange:Ae=>Se({mode:Ae.target.value==="continuous"?"continuous":"idle"}),disabled:p||!re||!ce,children:[s.jsx("option",{value:"idle",children:E("repoMesh.detail.idleEdgeOnly")}),s.jsx("option",{value:"continuous",children:E("repoMesh.detail.continuousScan")})]})})]})})(),s.jsxs("div",{className:"mt-4 rounded-xl border border-amber-500/25 bg-amber-500/10 p-4",children:[s.jsx(Tt,{label:E("repoMesh.detail.sessionCleanupLabel"),hint:E("repoMesh.detail.sessionCleanupHint"),children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:Z.sessionCleanupOnNodeRemove||"preserve",onChange:G=>u({sessionCleanupOnNodeRemove:G.target.value}),disabled:p,children:Ri.map(G=>s.jsx("option",{value:G.value,children:G.label},G.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((rt=Ri.find(G=>G.value===Z.sessionCleanupOnNodeRemove))==null?void 0:rt.description)||Ri[0].description})]}),p&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:E("repoMesh.detail.saving")})]})]}),nt=[{key:"nodes",label:E("repoMesh.detail.tabNodes"),content:st},{key:"scheduling",label:E("repoMesh.detail.tabScheduling"),content:X},{key:"prompts",label:E("repoMesh.detail.tabPrompts"),content:s.jsxs(s.Fragment,{children:[Le,ye.hermesMcpConfig&&s.jsx(E2,{meshId:e.id,availableCliAgents:ue}),ye.meshHostDaemonSection&&s.jsxs(Mt,{variant:"info",className:"mt-4",children:[s.jsx("strong",{children:E("repoMesh.detail.mcpMode")})," ",s.jsxs("code",{className:"bg-bg-secondary px-1 rounded text-xs",children:["adhdev mcp --repo-mesh ",e.id]})," ",E("repoMesh.detail.mcpDescription")]})]})},{key:"advanced",label:E("repoMesh.detail.tabAdvanced"),content:_e}];return s.jsxs(s.Fragment,{children:[s.jsx(f1,{tabs:nt,ariaLabel:E("repoMesh.detail.tabsAriaLabel"),className:"flex flex-col gap-4"}),Be&&at&&s.jsx(Kf,{activeConv:B2({meshId:e.id,daemonId:M,meshName:e.name}),sendDaemonCommand:Ie,onClose:()=>Xe(!1)})]})})()]})}const va=new Map;async function ag(e){var r,o,i,c,d,p,u,m,f,g,k;const{sendCommand:t,unwrapResult:n}=e,a={meshCreated:!1,meshId:"",error:null,warning:null,plan:null};try{const h=e.reusablePlan??n(await t(e.targetDaemonId,"plan_mesh_onboarding",{workspace:e.workspace||void 0,operation:"auto",meshInventory:e.meshInventory}));if(a.plan=h,(h==null?void 0:h.success)===!1)return{...a,error:`${h.code||"onboarding_blocked"}: ${h.error}${h.action?` ${h.action}`:""}`};if(((r=h==null?void 0:h.plan)==null?void 0:r.kind)!=="create_mesh_and_onboard")return{...a,error:((o=h==null?void 0:h.plan)==null?void 0:o.summary)||"A compatible mesh already exists; add this workspace to it instead of creating a duplicate mesh."};const x={name:e.name.trim()};(e.repoRemoteUrl||(d=(c=(i=h==null?void 0:h.discovery)==null?void 0:i.origin)==null?void 0:c.urls)!=null&&d[0])&&(x.repoRemoteUrl=e.repoRemoteUrl||h.discovery.origin.urls[0]),(e.repoIdentity||(p=h==null?void 0:h.discovery)!=null&&p.repoIdentity)&&(x.repoIdentity=e.repoIdentity||h.discovery.repoIdentity),(u=h==null?void 0:h.discovery)!=null&&u.defaultBranch&&(x.defaultBranch=h.discovery.defaultBranch);const S=await t(e.targetDaemonId,"create_mesh",x),b=n(S);if((b==null?void 0:b.success)===!1)return{...a,error:b.error||"Create failed"};const w=typeof((m=b==null?void 0:b.mesh)==null?void 0:m.id)=="string"?b.mesh.id:"",C={...a,meshCreated:!0,meshId:w};if(!w||!e.attachWorkspace||!e.workspace)return C;try{const v=await t(e.targetDaemonId,"add_mesh_node",{meshId:w,daemonId:e.targetDaemonId,machineId:e.machineId,workspace:((f=h==null?void 0:h.discovery)==null?void 0:f.repoRoot)||e.workspace,repoRoot:(g=h==null?void 0:h.discovery)==null?void 0:g.repoRoot,isLocalWorktree:((k=h==null?void 0:h.discovery)==null?void 0:k.isLinkedWorktree)===!0,role:"host",providerPriority:e.providerPriority}),y=n(v);return(y==null?void 0:y.success)===!1?{...C,warning:tp(y.error||"add_mesh_node failed")}:C}catch(v){return{...C,warning:tp((v==null?void 0:v.message)||"add_mesh_node failed")}}}catch(h){return{...a,error:(h==null?void 0:h.message)||"Create failed"}}}function tp(e){return`Mesh created, but attaching the workspace failed: ${e}. Add the workspace from the mesh's node list.`}function sp(e,t){return e===t?!0:e.length!==t.length?!1:JSON.stringify(e)===JSON.stringify(t)}function rg({daemons:e,primaryDaemonId:t,sendCommand:n,unwrapResult:a,normalizeMesh:r,features:o,loadDaemonMetadata:i}){const c=e.map(le=>le.id).filter(Boolean).sort().join(","),[d,p]=l.useState(()=>va.get(c)??[]),[u,m]=l.useState(null),[f,g]=l.useState(()=>!va.has(c)),[k,h]=l.useState(null),[x,S]=l.useState(!1),[b,w]=l.useState(!1),[C,v]=l.useState(null),[y,j]=l.useState(""),[N,A]=l.useState(""),[T,L]=l.useState(""),[D,M]=l.useState(""),[_,P]=l.useState(""),[B,R]=l.useState(null),[O,H]=l.useState(!1),$=o.createDaemonPicker?D:t,I=l.useMemo(()=>e.find(le=>le.id===$),[e,$]),W=(I==null?void 0:I.workspaces)||[],F=l.useMemo(()=>ln((I==null?void 0:I.availableProviders)||[]),[I]);l.useEffect(()=>{!i||!$||!I||!(!I.workspaces||!I.availableProviders)||Promise.resolve(i($,{minFreshMs:3e4})).catch(()=>{})},[i,$,I]),l.useEffect(()=>{if(!x||!$||!_){R(null);return}let le=!1;return H(!0),n($,"plan_mesh_onboarding",{workspace:_,operation:"auto",meshInventory:d}).then(U=>{if(le)return;const J=a(U);R(J),J!=null&&J.success&&(A(ee=>{var Y;return ee||((Y=J.discovery)==null?void 0:Y.repoIdentity)||""}),L(ee=>{var Y,ve,pe,te,me,V;return ee||((pe=(ve=(Y=J.discovery)==null?void 0:Y.origin)==null?void 0:ve.urls)==null?void 0:pe[0])||((V=(me=(te=J.discovery)==null?void 0:te.upstream)==null?void 0:me.urls)==null?void 0:V[0])||""}),j(ee=>{var Y,ve;return ee||`${String(((Y=J.discovery)==null?void 0:Y.repoIdentity)||((ve=J.discovery)==null?void 0:ve.repoRoot)||"").split(/[\\/]/).filter(Boolean).pop()||"repo"}-mesh`}))}).catch(U=>{le||R({success:!1,error:(U==null?void 0:U.message)||"Git discovery failed"})}).finally(()=>{le||H(!1)}),()=>{le=!0}},[x,$,_,d,n,a]);const z=l.useMemo(()=>e.map(le=>le.id).filter(Boolean).sort().join(","),[e]),Q=l.useCallback(async(le=!1)=>{const U=le||va.has(z);g(J=>U?J:!0);try{if(o.createDaemonPicker){const J=await Promise.allSettled(e.map(async ve=>{if(!ve.id)return[];const pe=await n(ve.id,"list_meshes",{}),te=a(pe);if((te==null?void 0:te.success)===!1)throw new Error(te.error||"Failed to load meshes");return(Array.isArray(te==null?void 0:te.meshes)?te.meshes:[]).map(me=>r(me,ve.id)).filter(me=>me.id)})),ee=new Map;for(const ve of J)if(ve.status==="fulfilled")for(const pe of ve.value)ee.has(pe.id)||ee.set(pe.id,pe);const Y=Array.from(ee.values());p(ve=>sp(ve,Y)?ve:Y),va.set(z,Y),h(null)}else{if(!t)return;const J=await n(t,"list_meshes");if(J!=null&&J.success){const ee=(J.meshes||[]).map(Y=>r(Y,t));p(Y=>sp(Y,ee)?Y:ee),va.set(z,ee),h(null)}else h((J==null?void 0:J.error)||"Failed to load meshes")}}catch(J){h((J==null?void 0:J.message)||"Failed to load meshes")}finally{g(!1)}},[z,t,n,a,r,o.createDaemonPicker]);async function ne(){const le=o.createDaemonPicker?D:t;if(!le||!y.trim())return;const U=T.trim(),J=N.trim(),ee=_.trim();if(!(!ee&&!U&&!J)&&!b){w(!0),v(null);try{const Y=await ag({targetDaemonId:le,name:y,repoRemoteUrl:U,repoIdentity:J,workspace:ee,attachWorkspace:!!ee,machineId:I==null?void 0:I.machineId,providerPriority:Pn(F),meshInventory:d,sendCommand:n,unwrapResult:a,reusablePlan:!O&&B?B:void 0});if(Y.plan!==null&&R(Y.plan),Y.warning&&v(Y.warning),!Y.meshCreated){h(Y.error||"Create failed");return}S(!1),j(""),A(""),L(""),P(""),await Q(),Y.meshId&&m(Y.meshId)}finally{w(!1)}}}async function oe(le){var J;if(!confirm("Delete this mesh? This cannot be undone."))return;const U=((J=d.find(ee=>ee.id===le))==null?void 0:J.__sourceDaemonId)||t;try{const ee=await n(U,"delete_mesh",{meshId:le}),Y=a(ee);if((Y==null?void 0:Y.success)===!1)throw new Error(Y.error||"Failed to delete");u===le&&m(null),await Q()}catch(ee){h((ee==null?void 0:ee.message)||"Delete failed")}}function Ce(){S(!1),j(""),A(""),L(""),P(""),R(null),v(null)}return{meshes:d,setMeshes:p,selectedMeshId:u,setSelectedMeshId:m,loading:f,error:k,setError:h,showCreate:x,setShowCreate:S,creating:b,createWarning:C,setCreateWarning:v,createName:y,setCreateName:j,createRepoIdentity:N,setCreateRepoIdentity:A,createRepoRemoteUrl:T,setCreateRepoRemoteUrl:L,newMeshDaemonId:D,setNewMeshDaemonId:M,newMeshWorkspace:_,setNewMeshWorkspace:P,createPickerWorkspaces:W,createPickerProviders:F,createOnboardingPlan:B,createPlanLoading:O,loadMeshes:Q,handleCreate:ne,handleDelete:oe,cancelCreate:Ce}}function O2({selectedMesh:e,selectedMeshId:t,primaryDaemonId:n,activeDaemonId:a,daemons:r,sendCommand:o,unwrapResult:i,loadLiveMesh:c,resolveCommandTarget:d,launchCoordinator:p,features:u,loadMeshes:m,loadQueue:f,queueSection:g,setError:k}){const[h,x]=l.useState(null),[S,b]=l.useState(!1),[w,C]=l.useState(""),[v,y]=l.useState([]),[j,N]=l.useState(""),[A,T]=l.useState(!1),[L,D]=l.useState(null),[M,_]=l.useState(!1),[P,B]=l.useState(""),[R,O]=l.useState(!1),[H,$]=l.useState(!1),[I,W]=l.useState(null),[F,z]=l.useState(!1),[Q,ne]=l.useState({override:"",append:""}),[oe,Ce]=l.useState(!1),[le,U]=l.useState({}),[J,ee]=l.useState(null),Y=l.useMemo(()=>r.find(Z=>Z.id===j),[r,j]),ve=(Y==null?void 0:Y.workspaces)||[],pe=l.useMemo(()=>ln((Y==null?void 0:Y.availableProviders)||[]),[Y]);l.useEffect(()=>{if(!S||!t||!w.trim()){D(null);return}const Z=u.addNodeDaemonPicker?j:(e==null?void 0:e.__sourceDaemonId)||n;if(!Z)return;let we=!1;return _(!0),o(Z,"plan_mesh_onboarding",{workspace:w.trim(),meshId:t,inlineMesh:e,operation:"add_existing"}).then(ge=>{we||D(i(ge))}).catch(ge=>{we||D({success:!1,error:(ge==null?void 0:ge.message)||"Git discovery failed"})}).finally(()=>{we||_(!1)}),()=>{we=!0}},[S,t,e,w,j,n,u.addNodeDaemonPicker,o,i]);async function te(){var ge,be,Pe;const Z=(e==null?void 0:e.__sourceDaemonId)||n;if(!t||!Z)return;const we=w.trim();if(we)try{const Me=u.addNodeDaemonPicker?j:Z,We=await o(Me,"plan_mesh_onboarding",{workspace:we,meshId:t,inlineMesh:e,operation:"add_existing"}),Be=i(We);if(D(Be),(Be==null?void 0:Be.success)===!1)throw new Error(`${Be.code||"onboarding_blocked"}: ${Be.error}${Be.action?` ${Be.action}`:""}`);const Xe={meshId:t,workspace:((ge=Be==null?void 0:Be.discovery)==null?void 0:ge.repoRoot)||we,repoRoot:(be=Be==null?void 0:Be.discovery)==null?void 0:be.repoRoot,isLocalWorktree:((Pe=Be==null?void 0:Be.discovery)==null?void 0:Pe.isLinkedWorktree)===!0};u.addNodeDaemonPicker&&j&&(Xe.daemonId=j,Xe.machineId=Y==null?void 0:Y.machineId),Xe.providerPriority=Va(v);const at=await o(Z,"add_mesh_node",Xe),st=i(at);if((st==null?void 0:st.success)===!1)throw new Error(st.error||"Add node failed");b(!1),C(""),y([]),N(""),T(!1),await m(),g||await f(t)}catch(Me){k((Me==null?void 0:Me.message)||"Add node failed")}}async function me(Z){var Pe;if(!e)return;const we=jl(e),ge=((Pe=[{value:"preserve",label:"Preserve history and runtimes"},{value:"stop",label:"Stop live runtimes only"},{value:"delete_stopped",label:"Delete stopped sessions only"},{value:"stop_and_delete",label:"Stop and delete sessions"}].find(Me=>Me.value===we.sessionCleanupOnNodeRemove))==null?void 0:Pe.label)||"Preserve history and runtimes";if(!confirm(`Remove this node?
119
+ `})]})}function PL({daemonIds:e,meshId:t,sendData:n,onRevisionAdvance:a}){const r=l.useRef(new Map),o=l.useRef(a);o.current=a;const i=[...new Set(e.filter(Boolean))].sort().join(",");l.useEffect(()=>{r.current=new Map},[i,t]),l.useEffect(()=>{if(!t||!n)return;const c=[...new Set(e.filter(Boolean))];if(c.length===0)return;const d=c.map(p=>ys.subscribe({sendData:n},p,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${p}`,params:{includeSessions:!0}},u=>{if(u.topic!=="daemon.metadata")return;const m=u.meshStateRevisions;if(!m)return;const f=m[t]??m["*"];if(typeof f!="number")return;const g=r.current.get(p);r.current.set(p,f),g!==void 0&&f>g&&o.current()}));return()=>{for(const p of d)p()}},[i,t,n])}const Xf={meshHostDaemonSection:!1,createDaemonPicker:!1,addNodeDaemonPicker:!1,queueSection:!0,coordinatorPrompt:!0,nodeInstruction:!0,hermesMcpConfig:!0,reviewInbox:!0},Zf=l.createContext(null);function DL(){const e=l.useContext(Zf);if(!e)throw new Error("useRepoMeshContext must be used inside RepoMeshProvider");return e}const ao="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function yl({workspaces:e,value:t,onChange:n,autoFocus:a}){const{t:r}=ke("common"),[o,i]=l.useState(!1),c=new Set(e.map(p=>p.path)),d=o?"__custom":c.has(t)?t:"";return e.length===0||o?s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx("input",{type:"text",className:ao,value:t,autoFocus:a,placeholder:r("setupWizard.machines.workspacePlaceholder"),onChange:p=>n(p.target.value)}),e.length>0&&s.jsx("button",{type:"button",className:"self-start text-[10px] text-accent-primary hover:underline",onClick:()=>i(!1),children:r("setupWizard.machines.pickFromKnown")})]}):s.jsxs("select",{className:ao,value:d,onChange:p=>{p.target.value==="__custom"?(i(!0),n("")):n(p.target.value)},children:[s.jsx("option",{value:"",children:r("setupWizard.machines.workspaceSelectPlaceholder")}),e.map(p=>s.jsx("option",{value:p.path,children:p.label||p.path},p.path)),s.jsx("option",{value:"__custom",children:r("setupWizard.machines.workspaceCustom")})]})}function ro(e){var t;return!!(e!=null&&e.success)&&((t=e==null?void 0:e.plan)==null?void 0:t.kind)!==void 0&&e.plan.kind!=="create_mesh_and_onboard"}function eg(e,t){const[n,a]=l.useState(!1),r=l.useRef(null);return l.useEffect(()=>(e?r.current=setTimeout(()=>a(!0),t):a(!1),()=>{r.current&&clearTimeout(r.current)}),[e,t]),e&&n}function tg({plan:e,loading:t}){var i,c,d;const{t:n}=ke("common"),a=eg(t,250);let r=null,o="text-[11px] text-text-muted";return a?r=n("setupWizard.machines.planChecking"):(e==null?void 0:e.success)===!1?(o="text-[11px] text-red-400",r=s.jsxs(s.Fragment,{children:[e.error,e.action?` ${e.action}`:""]})):ro(e)?(o="text-[11px] text-amber-400",r=((i=e.plan)==null?void 0:i.summary)||n("setupWizard.machines.planExists")):e&&(o="text-[11px] text-emerald-400",r=n("setupWizard.machines.planOk",{identity:((c=e.discovery)==null?void 0:c.repoIdentity)||((d=e.discovery)==null?void 0:d.repoRoot)||""})),s.jsx("p",{className:`${o} min-h-[1.4em]`,children:r})}function IL(e){var t;return e.creating||e.planLoading||!e.name.trim()||e.showDaemonPicker&&!e.daemonId||((t=e.plan)==null?void 0:t.success)===!1||ro(e.plan)?!0:e.workspace.trim()?!1:!e.repoRemoteUrl.trim()&&!e.repoIdentity.trim()}function sg(e){var _,P;const{variant:t="page",showDaemonPicker:n,daemons:a,daemonLabel:r,name:o,onNameChange:i,daemonId:c,onDaemonIdChange:d,workspace:p,onWorkspaceChange:u,workspaces:m,plan:f,planLoading:g,repoRemoteUrl:k,onRepoRemoteUrlChange:h,repoIdentity:x,onRepoIdentityChange:S,manualOpen:b,onManualOpenChange:w,creating:C,warning:v,onCreate:y,onCancel:j}=e,{t:N}=ke("common"),A=IL({creating:C,planLoading:g,plan:f,name:o,workspace:p,showDaemonPicker:n,daemonId:c,repoRemoteUrl:k,repoIdentity:x}),T=eg(g,250),L=b||!!k.trim()||!!x.trim(),D=n&&a.length>0&&s.jsxs("select",{className:t==="wizard"?ao:"input w-full",value:c,onChange:B=>d(B.target.value),children:[s.jsx("option",{value:"",children:N("setupWizard.machines.machineSelectPlaceholder")}),a.map(B=>s.jsx("option",{value:B.id,children:r(B)},B.id))]}),M=L?s.jsxs(s.Fragment,{children:[s.jsx(Tt,{label:N("repoMesh.list.remoteUrl"),hint:N("repoMesh.list.remoteUrlHint"),children:s.jsx(xs,{value:k,onChange:B=>h(B.target.value),placeholder:"https://github.com/user/repo"})}),s.jsx(Tt,{label:N("repoMesh.list.repoIdentity"),hint:N("repoMesh.list.repoIdentityHint"),children:s.jsx(xs,{value:x,onChange:B=>S(B.target.value),placeholder:"github.com/user/repo"})})]}):s.jsx("button",{type:"button",className:"self-start text-xs text-text-muted hover:text-text-primary underline underline-offset-2 mb-3 bg-transparent border-none cursor-pointer p-0",onClick:()=>w(!0),children:N("repoMesh.list.advancedIdentityToggle")});return t==="wizard"?s.jsxs("div",{className:"flex flex-col gap-2.5 rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2.5",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:N("setupWizard.machines.meshName")}),s.jsx("input",{type:"text",className:ao,value:o,onChange:B=>i(B.target.value)})]}),n&&a.length>1&&s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:N("setupWizard.machines.machine")}),D]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:N("setupWizard.machines.workspace")}),s.jsx(yl,{workspaces:m,value:p,onChange:u})]}),s.jsx(tg,{plan:f,loading:g}),v&&s.jsx("p",{className:"text-[11px] text-amber-400",children:v}),s.jsx("div",{className:"flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:y,disabled:A,children:N(C?"setupWizard.machines.creating":"setupWizard.machines.create")})})]}):s.jsxs(s.Fragment,{children:[s.jsx("h3",{className:"text-base font-bold mb-4",children:N("repoMesh.list.createTitle")}),n&&s.jsx(Tt,{label:N("repoMesh.list.createOnMachine"),hint:N("repoMesh.list.createOnMachineHint"),children:a.length===0?s.jsx("select",{className:"input w-full",disabled:!0,children:s.jsx("option",{value:"",children:N("repoMesh.list.noConnectedDaemon")})}):D}),s.jsx(Tt,{label:N("repoMesh.list.workspace"),hint:N("repoMesh.list.workspaceHint"),children:s.jsx(yl,{workspaces:m,value:p,onChange:u})}),(T||f)&&s.jsx(Mt,{variant:(f==null?void 0:f.success)===!1?"error":ro(f)?"warning":"info",className:"mb-4",children:T?N("setupWizard.machines.planChecking"):(f==null?void 0:f.success)===!1?`${(f==null?void 0:f.code)||"onboarding_blocked"}: ${(f==null?void 0:f.error)||"Git discovery failed"} ${(f==null?void 0:f.action)||""}`:ro(f)?((_=f.plan)==null?void 0:_.summary)||N("setupWizard.machines.planExists"):`${((P=f.plan)==null?void 0:P.summary)||"Git repository detected."} No changes will be made until you click Create.`}),s.jsx(Tt,{label:N("repoMesh.list.name"),children:s.jsx(xs,{value:o,onChange:B=>i(B.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx("div",{className:"flex flex-col",children:M}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:y,disabled:A,children:N(C?"repoMesh.list.creating":"repoMesh.list.create")}),j&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:j,disabled:C,children:N("repoMesh.list.cancel")})]})]})}function LL({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("polyline",{points:"23 4 23 10 17 10"}),s.jsx("polyline",{points:"1 20 1 14 7 14"}),s.jsx("path",{d:"M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"})]})}function RL({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),s.jsx("circle",{cx:"18",cy:"6",r:"3"}),s.jsx("circle",{cx:"6",cy:"18",r:"3"}),s.jsx("path",{d:"M18 9a9 9 0 0 1-9 9"})]})}function EL({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("polyline",{points:"3 6 5 6 21 6"}),s.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]})}function _L({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function HL({status:e}){const n={online:{color:"#22c55e",label:"Online"},dirty:{color:"#f59e0b",label:"Dirty",title:"Workspace has uncommitted changes"},offline:{color:"#6b7280",label:"Offline"},degraded:{color:"#ef4444",label:"Degraded",title:"P2P connection to this node is down or timed out — often transient. Wait and retry, or re-establish the node's connection."},enabled:{color:"#22c55e",label:"Enabled"},pending:{color:"#a855f7",label:"Pending"},assigned:{color:"#3b82f6",label:"Assigned"},completed:{color:"#22c55e",label:"Completed"},failed:{color:"#ef4444",label:"Failed"},unknown:{color:"#6b7280",label:"Unknown"}}[e]||{color:"#6b7280",label:e};return s.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] font-semibold px-2 py-0.5 rounded-md",style:{background:n.color+"15",color:n.color,border:`1px solid ${n.color}25`},title:n.title,children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full",style:{background:n.color}}),n.label]})}function $L(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function FL({meshes:e,loading:t,error:n,onDismissError:a,daemons:r,features:o,showCreate:i,onToggleCreate:c,createName:d,onCreateNameChange:p,createRepoIdentity:u,onCreateRepoIdentityChange:m,createRepoRemoteUrl:f,onCreateRepoRemoteUrlChange:g,newMeshDaemonId:k,onNewMeshDaemonIdChange:h,newMeshWorkspace:x,onNewMeshWorkspaceChange:S,createPickerWorkspaces:b,createOnboardingPlan:w,createPlanLoading:C,creating:v,createWarning:y,onDismissCreateWarning:j,onSelectMesh:N,onCreate:A,onCancelCreate:T}){const{t:L}=ke("common"),D=o.maxMeshes!=null&&e.length>=o.maxMeshes,[M,_]=l.useState(!1);return s.jsxs(Qa,{icon:s.jsx(cs,{}),title:L("repoMesh.list.title"),subtitle:L("repoMesh.list.count",{count:e.length}),widthClassName:"max-w-5xl",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:c,disabled:D,title:D?L("repoMesh.list.meshLimitReached",{max:o.maxMeshes}):void 0,children:L("repoMesh.list.createMesh")}),children:[D&&s.jsx(Mt,{variant:"info",className:"mb-4",children:L("repoMesh.list.meshLimitBanner",{max:o.maxMeshes})}),n&&s.jsx(Mt,{variant:"error",onDismiss:a,className:"mb-4",children:n}),y&&s.jsx(Mt,{variant:"warning",onDismiss:j,className:"mb-4",children:y}),i&&s.jsx(bt,{className:"mb-5 border-accent/40 animate-[fadeIn_0.3s_ease-out]",children:s.jsx(sg,{variant:"page",showDaemonPicker:o.createDaemonPicker,daemons:r,daemonLabel:$L,name:d,onNameChange:p,daemonId:k,onDaemonIdChange:h,workspace:x,onWorkspaceChange:S,workspaces:b,plan:w,planLoading:C,repoRemoteUrl:f,onRepoRemoteUrlChange:g,repoIdentity:u,onRepoIdentityChange:m,manualOpen:M,onManualOpenChange:_,creating:v,onCreate:A,onCancel:T})}),t?s.jsx("div",{className:"text-sm text-text-muted p-4",children:L("repoMesh.list.loading")}):e.length===0?s.jsx(Ja,{icon:s.jsx(cs,{}),title:L("repoMesh.list.emptyTitle"),description:r.length>0?L("repoMesh.list.emptyWithDaemons"):L("repoMesh.list.emptyNoDaemons"),action:s.jsx("button",{className:"btn btn-primary btn-sm",disabled:!r.length,onClick:c,children:L("repoMesh.list.createFirst")})}):s.jsx("div",{className:"flex flex-col gap-2.5",children:e.map(P=>{var B;return s.jsx("button",{type:"button",onClick:()=>N(P.id),className:"w-full text-left bg-bg-glass border border-border-subtle rounded-xl px-5 py-4 transition-colors hover:border-border-default hover:bg-bg-secondary/70",children:s.jsxs("div",{className:"flex justify-between items-start",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx(cs,{size:16}),s.jsx("span",{className:"font-bold text-sm",children:P.name})]}),s.jsxs("div",{className:"text-[12px] text-text-muted flex items-center gap-2",children:[s.jsx("span",{className:"font-mono",children:P.repoIdentity||P.repo_identity||L("repoMesh.list.noRepoIdentity")}),(P.defaultBranch||P.default_branch)&&s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(RL,{size:11}),P.defaultBranch||P.default_branch]})]})]}),s.jsxs("div",{className:"text-right text-[11px] text-text-muted shrink-0 ml-4",children:[s.jsx("div",{children:new Date(P.createdAt||P.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric"})}),s.jsxs("div",{className:"text-text-muted/60",children:[((B=P.nodes)==null?void 0:B.length)??P.nodeCount??0," ",L("repoMesh.list.nodesSuffix")]})]})]})},P.id)})})]})}function BL(e){const t=new Map;for(const n of e)n!=null&&n.id&&t.set(n.id,ln(n.availableProviders||[]));return t}function WL(e,t){const n=String(e.daemon_id||e.daemonId||"");return n&&t.has(n)?t.get(n):!n&&t.size===1?[...t.values()][0]:[]}function OL(e,t){const n=new Map;for(const c of t)c!=null&&c.id&&n.set(c.id,Array.isArray(c.availableProviders)?c.availableProviders:[]);const a=new Set,r=[];let o=0,i=0;for(const c of Array.isArray(e)?e:[]){const d=String((c==null?void 0:c.daemon_id)||(c==null?void 0:c.daemonId)||""),p=d?n.get(d):n.size===1?[...n.values()][0]:void 0;if(!p||p.length===0){i++;continue}o++;for(const u of p){const m=String((u==null?void 0:u.type)||(u==null?void 0:u.id)||"").trim();!m||a.has(m)||(a.add(m),r.push(u))}}return r.sort((c,d)=>String((c==null?void 0:c.type)||(c==null?void 0:c.id)||"").localeCompare(String((d==null?void 0:d.type)||(d==null?void 0:d.id)||""))),{providers:r,reportedNodeCount:o,unreportedNodeCount:i}}function UL(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{},n=new Set,a=[],r=o=>{const i=typeof o=="string"?o.trim():"";!i||n.has(i)||(n.add(i),a.push(i))};for(const o of tm(t.slots))r(o.provider);if(Array.isArray(t.providerPriority))for(const o of t.providerPriority)r(o);return a}function GL(e){var d,p;const t=e,n=[],a=Array.isArray(t.capabilities)?t.capabilities:[];for(const u of a){const m=typeof u=="string"?u.trim():"";m&&n.push({tag:m,custom:!0})}const r=(((d=t.userOverrides)==null?void 0:d.platform)||t.reportedPlatform||"").toString().trim(),o=(((p=t.userOverrides)==null?void 0:p.arch)||t.reportedArch||"").toString().trim();r&&n.push({tag:`os=${r}`,custom:!1}),o&&n.push({tag:`arch=${o}`,custom:!1});for(const u of UL(t.policy))n.push({tag:`provider=${u}`,custom:!1});const i=typeof t.worktreeBranch=="string"?t.worktreeBranch.trim():"";t.isLocalWorktree===!0&&i&&n.push({tag:`worktree=${i}`,custom:!1});const c=new Set;return n.filter(u=>c.has(u.tag)?!1:(c.add(u.tag),!0))}const qL=["","low","medium","high"],zL={easy:"Easy",medium:"Medium",difficult:"Difficult",freeform:"Freeform"};function Ku(e){return{provider:e.provider||"",model:e.model||"",thinkingLevel:e.thinkingLevel||"",difficulty:Array.isArray(e.difficulty)?e.difficulty:[],capability:Array.isArray(e.capability)?e.capability:[],maxParallel:e.maxParallel!=null?String(e.maxParallel):""}}function Vu(e){const t=e.provider.trim();if(!t)return null;const n=e.model.trim(),a=e.thinkingLevel.trim()||void 0,r=Number(e.maxParallel),o=Number.isFinite(r)&&r>0?Math.floor(r):void 0;return{provider:t,...n?{model:n}:{},...a?{thinkingLevel:a}:{},...e.difficulty.length?{difficulty:e.difficulty}:{},...e.capability.length?{capability:e.capability}:{},...o!==void 0?{maxParallel:o}:{}}}function KL(){return{provider:"",model:"",thinkingLevel:"",difficulty:[],capability:[],maxParallel:""}}const fn="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function VL({slots:e,availableProviders:t,saving:n,onSave:a}){const{t:r}=ke("common"),[o,i]=l.useState(()=>e.map(Ku)),c=l.useMemo(()=>JSON.stringify(e),[e]);l.useEffect(()=>{i(e.map(Ku))},[c]);const d=l.useMemo(()=>[...new Set(t.map(b=>b.type).filter(Boolean))],[t]),p=l.useMemo(()=>uh(t),[t]),u=l.useMemo(()=>{const b=o.map(Vu).filter(Boolean);return JSON.stringify(b)!==JSON.stringify(e)},[o,e]),m=(b,w)=>i(C=>C.map((v,y)=>y===b?{...v,...w}:v)),f=(b,w)=>i(C=>C.map((v,y)=>{var A;if(y!==b)return v;const j=((A=p.get(w))==null?void 0:A.models)??[],N=!v.model||j.length===0||j.includes(v.model);return{...v,provider:w,...N?{}:{model:""}}})),g=b=>i(w=>w.filter((C,v)=>v!==b)),k=()=>i(b=>[...b,KL()]),h=(b,w)=>i(C=>{const v=b+w;if(v<0||v>=C.length)return C;const y=[...C];return[y[b],y[v]]=[y[v],y[b]],y}),x=(b,w)=>i(C=>C.map((v,y)=>{if(y!==b)return v;const j=v.difficulty.includes(w);return{...v,difficulty:j?v.difficulty.filter(N=>N!==w):[...v.difficulty,w]}})),S=()=>a(o.map(Vu).filter(Boolean));return s.jsxs("div",{className:"flex flex-col gap-2",onClick:b=>b.stopPropagation(),children:[o.length===0&&s.jsx("div",{className:"text-[12px] text-text-muted",children:r("repoMesh.slotEditor.empty")}),o.map((b,w)=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/40 p-2.5",children:[s.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[s.jsxs("span",{className:"text-[11px] font-semibold text-text-muted",children:["#",w+1]}),s.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-border-subtle text-text-muted hover:text-text-primary disabled:opacity-40",disabled:w===0,onClick:()=>h(w,-1),title:r("repoMesh.slotEditor.moveUp"),children:"↑"}),s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-border-subtle text-text-muted hover:text-text-primary disabled:opacity-40",disabled:w===o.length-1,onClick:()=>h(w,1),title:r("repoMesh.slotEditor.moveDown"),children:"↓"}),s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-status-error/30 text-status-error hover:bg-status-error/10",onClick:()=>g(w),"aria-label":r("repoMesh.slotEditor.removeSlot"),children:s.jsx(Dt,{size:12})})]})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:r("repoMesh.slotEditor.provider")}),d.length>0?s.jsxs("select",{className:fn,value:b.provider,onChange:C=>f(w,C.target.value),children:[s.jsx("option",{value:"",children:r("repoMesh.slotEditor.select")}),d.map(C=>s.jsx("option",{value:C,children:C},C)),b.provider&&!d.includes(b.provider)&&s.jsx("option",{value:b.provider,children:b.provider})]}):s.jsx("input",{className:fn,value:b.provider,placeholder:"claude-cli",onChange:C=>m(w,{provider:C.target.value})})]}),(()=>{var N;const C=p.get(b.provider),v=(C==null?void 0:C.models)??[],y=(N=C==null?void 0:C.thinking)!=null&&N.length?["",...C.thinking]:qL,j=!!b.model&&v.length>0&&!v.includes(b.model);return s.jsxs(s.Fragment,{children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:r("repoMesh.slotEditor.model")}),v.length>0&&!j?s.jsxs("select",{className:fn,value:v.includes(b.model)?b.model:"",onChange:A=>m(w,{model:A.target.value==="__custom__"?" ":A.target.value}),children:[s.jsx("option",{value:"",children:r("repoMesh.slotEditor.providerDefault")}),v.map(A=>s.jsx("option",{value:A,children:A},A)),s.jsx("option",{value:"__custom__",children:r("repoMesh.slotEditor.custom")})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:fn,value:b.model.trim(),placeholder:b.provider?`${b.provider} model`:r("repoMesh.slotEditor.modelPlaceholder"),onChange:A=>m(w,{model:A.target.value})}),v.length>0&&s.jsx("button",{type:"button",className:"self-start bg-transparent border-none cursor-pointer p-0 text-[10px] text-text-muted hover:underline",onClick:()=>m(w,{model:""}),children:r("repoMesh.slotEditor.backToModelList")})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:r("repoMesh.slotEditor.thinking")}),s.jsx("select",{className:fn,value:b.thinkingLevel,onChange:A=>m(w,{thinkingLevel:A.target.value}),children:y.map(A=>s.jsx("option",{value:A,children:A||r("repoMesh.slotEditor.thinkingDefault")},A||"_default"))})]})]})})()]}),s.jsxs("div",{className:"mt-2",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:r("repoMesh.slotEditor.difficulty")}),s.jsx("div",{className:"mt-1 flex flex-wrap gap-1.5",children:em.map(C=>{const v=b.difficulty.includes(C);return s.jsx("button",{type:"button",className:`rounded-full border px-2.5 py-0.5 text-[11px] font-medium transition-colors ${v?"border-accent-primary/60 bg-accent-primary/15 text-accent-primary":"border-border-subtle bg-bg-primary/60 text-text-muted hover:text-text-primary"}`,onClick:()=>x(w,C),children:zL[C]},C)})})]}),s.jsxs("div",{className:"mt-2 grid grid-cols-1 sm:grid-cols-2 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:r("repoMesh.slotEditor.capabilityTags")}),s.jsx("input",{className:fn,value:b.capability.join(", "),placeholder:"worktree, os=darwin",onChange:C=>m(w,{capability:C.target.value.split(",").map(v=>v.trim()).filter(Boolean)})})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:r("repoMesh.slotEditor.maxParallel")}),s.jsx("input",{type:"number",inputMode:"numeric",min:1,className:fn,value:b.maxParallel,placeholder:r("repoMesh.slotEditor.maxParallelPlaceholder"),onChange:C=>m(w,{maxParallel:C.target.value})})]})]})]},w)),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-1",onClick:k,children:[s.jsx(Hl,{size:13})," ",r("repoMesh.slotEditor.addSlot")]}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm ml-auto",onClick:S,disabled:!!n||!u,children:r(n?"repoMesh.slotEditor.saving":"repoMesh.slotEditor.saveSlots")})]})]})}function YL(e){const t=e.capabilities;return Array.isArray(t)?t.map(n=>typeof n=="string"?n.trim():"").filter(Boolean):[]}const QL=["os=","arch=","provider=","worktree=","converge="];function JL({node:e,saving:t,onSave:n}){const{t:a}=ke("common"),r=l.useMemo(()=>GL(e).filter(h=>!h.custom),[e]),o=l.useMemo(()=>YL(e),[e]),[i,c]=l.useState(o),[d,p]=l.useState(""),u=JSON.stringify(i)!==JSON.stringify(o),f=(h=>{const x=h.trim();return x?/\s/.test(x)?a("repoMesh.tagEditor.noSpaces"):QL.some(S=>x.toLowerCase().startsWith(S))?a("repoMesh.tagEditor.reservedPrefix"):i.includes(x)?a("repoMesh.tagEditor.alreadyAdded"):null:null})(d);function g(){const h=d.trim();!h||f||(c(x=>[...x,h]),p(""))}function k(h){c(x=>x.filter(S=>S!==h))}return s.jsxs("div",{className:"mt-2",onClick:h=>h.stopPropagation(),children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wide text-text-muted mr-1",children:a("repoMesh.tagEditor.routingTags")}),r.map(h=>s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-1.5 py-0.5 font-mono text-[10px] text-text-muted",title:a("repoMesh.tagEditor.autoDerivedTitle"),children:h.tag},h.tag)),i.map(h=>s.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-accent-primary/40 bg-accent-primary/10 px-1.5 py-0.5 font-mono text-[10px] text-accent-primary",title:a("repoMesh.tagEditor.customTagTitle"),children:[h,s.jsx("button",{type:"button",className:"text-accent-primary/70 hover:text-accent-primary bg-transparent border-none cursor-pointer p-0 leading-none",onClick:()=>k(h),disabled:t,"aria-label":a("repoMesh.tagEditor.remove",{tag:h}),children:"×"})]},h))]}),s.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-2",children:[s.jsx("input",{type:"text",value:d,onChange:h=>p(h.target.value),onKeyDown:h=>{h.key==="Enter"&&(h.preventDefault(),g())},placeholder:a("repoMesh.tagEditor.addPlaceholder"),disabled:t,className:"min-w-[12rem] flex-1 px-2 py-1 rounded-lg bg-bg-secondary border border-border-subtle text-[12px] text-text-primary"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:g,disabled:t||!d.trim()||!!f,children:a("repoMesh.tagEditor.add")}),u&&s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>n(i),disabled:t,children:a(t?"repoMesh.tagEditor.saving":"repoMesh.tagEditor.saveTags")})]}),f&&s.jsx("div",{className:"mt-1 text-[11px] text-amber-400",children:f}),i.length===0&&r.length===0&&s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:a("repoMesh.tagEditor.empty")})]})}function XL(e,t){const n=t;return[...Array.isArray(n==null?void 0:n.cliSessions)?n.cliSessions:[],...Array.isArray(n==null?void 0:n.acpSessions)?n.acpSessions:[],...Array.isArray(n==null?void 0:n.sessions)?n.sessions:[]].filter(r=>{var o;return((o=r==null?void 0:r.settings)==null?void 0:o.meshNodeId)===e.id||(r==null?void 0:r.workspace)===e.workspace}).map(r=>{var o;return{id:r.sessionId||r.id||r.instanceId||"unknown",provider:r.providerType||r.cliType||r.acpType||r.type||"unknown",status:r.status||((o=r.activeChat)==null?void 0:o.status)||"unknown"}})}function ZL(e,t){var n;return(e==null?void 0:e.ownerName)||(e==null?void 0:e.userName)||((n=e==null?void 0:e.user)==null?void 0:n.name)||t||"You"}function Yu({nodes:e,meshQueue:t,activeDaemon:n,daemons:a,userName:r,features:o,providersByDaemonId:i,savingNodeSlotsId:c,onUpdateNodeSlots:d,savingNodeCapabilitiesId:p,onUpdateNodeCapabilities:u,nodeSystemPromptDrafts:m,onNodeSystemPromptDraftChange:f,savingNodeSystemPromptId:g,onSaveNodeSystemPrompt:k,selectedNodeId:h,onSelectNode:x,onRemoveNode:S}){const{t:b}=ke("common");return e.length===0?s.jsx(Ja,{icon:s.jsx(An,{}),title:b("repoMesh.nodeList.emptyTitle"),description:b("repoMesh.nodeList.emptyDescription")}):s.jsx("div",{className:"flex flex-col gap-2",children:e.map(w=>{var A;const C=n2(w),v=e2(w,t),y=XL(w,n),j=h===w.id,N=w.status||w.machine_status||(v.length>0||y.length>0?"active":"enabled");return s.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary transition-colors ${o.addNodeDaemonPicker?"bg-bg-glass border-border-subtle rounded-xl px-5 py-4":`cursor-pointer ${j?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`}`,role:o.addNodeDaemonPicker?void 0:"button",tabIndex:o.addNodeDaemonPicker?void 0:0,onClick:o.addNodeDaemonPicker?void 0:()=>x(j?null:w.id),onKeyDown:o.addNodeDaemonPicker?void 0:T=>{(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),x(j?null:w.id))},children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[o.addNodeDaemonPicker?s.jsx("span",{className:"font-semibold text-sm text-text-primary truncate",children:w.machine_label||w.machine_nickname||w.hostname||w.workspace}):s.jsx("span",{className:"text-sm font-medium",children:w.workspace.split("/").pop()}),o.addNodeDaemonPicker&&s.jsx(HL,{status:N}),o.addNodeDaemonPicker&&s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:b("repoMesh.nodeList.setupInventory")})]}),o.addNodeDaemonPicker&&s.jsx("div",{className:"text-[11px] text-text-muted",children:b("repoMesh.nodeList.ownerMachine",{owner:ZL(a.find(T=>T.id===String(w.daemon_id||"")),r),machine:w.machine_label||w.daemon_id||w.workspace})}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:w.workspace}),s.jsx(JL,{node:w,saving:p===w.id,onSave:T=>u(w,T)}),o.addNodeDaemonPicker&&s.jsx("div",{className:"mt-2 text-[11px] text-amber-300",children:b("repoMesh.nodeList.liveDetailGraphOwned")}),s.jsxs("div",{className:"mt-3 max-w-2xl",onClick:T=>T.stopPropagation(),children:[s.jsx(Tt,{label:b("repoMesh.nodeList.slotsLabel"),hint:b("repoMesh.nodeList.slotsHint"),children:s.jsx(VL,{slots:Array.isArray((A=w.policy)==null?void 0:A.slots)?w.policy.slots:[],availableProviders:WL(w,i),saving:c===w.id,onSave:T=>d(w,T)})}),o.nodeInstruction&&s.jsxs(Tt,{label:b("repoMesh.nodeList.nodeInstruction"),hint:b("repoMesh.nodeList.nodeInstructionHint"),children:[s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:3,value:m[w.id]??"",onChange:T=>{const L=T.target.value;f(w.id,L)},onClick:T=>T.stopPropagation(),disabled:g===w.id,placeholder:b("repoMesh.nodeList.nodeInstructionPlaceholder")}),s.jsx("div",{className:"mt-2 flex items-center gap-2",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:T=>{T.stopPropagation(),k(w)},disabled:g===w.id,children:g===w.id?b("repoMesh.nodeList.saving"):b("repoMesh.nodeList.saveInstruction")})})]})]})]}),s.jsx("button",{className:`transition-colors bg-transparent border-none cursor-pointer ${o.addNodeDaemonPicker?"btn btn-sm text-text-muted hover:text-red-400":"text-text-muted hover:text-red-400"}`,onClick:T=>{T.stopPropagation(),S(w.id)},title:b("repoMesh.nodeList.removeNode"),children:s.jsx(EL,{size:14})})]}),s.jsxs("details",{className:"mt-3 group",onClick:T=>T.stopPropagation(),children:[s.jsxs("summary",{className:"cursor-pointer select-none text-[12px] text-text-muted hover:text-text-secondary inline-flex items-center gap-1",children:[s.jsx("span",{className:"transition-transform group-open:rotate-90","aria-hidden":!0,children:"▸"})," ",b("repoMesh.nodeList.details")]}),s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary/60 p-3 text-[12px] text-text-muted",children:[s.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:b("repoMesh.nodeList.nodeId")})," ",s.jsx("span",{className:"font-mono break-all",children:w.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:b("repoMesh.nodeList.launchReady")})," ",s.jsx("span",{className:C.configured?"text-green-400":"text-amber-400",children:C.configured?b("repoMesh.nodeList.launchReadyYes"):b("repoMesh.nodeList.launchReadyNo")})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:b("repoMesh.nodeList.repoRoot")})," ",s.jsx("span",{className:"font-mono break-all",children:w.repoRoot||w.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:b("repoMesh.nodeList.activeSessionsLabel")})," ",y.length]}),o.addNodeDaemonPicker&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:b("repoMesh.nodeList.added")})," ",new Date(w.created_at||w.createdAt||Date.now()).toLocaleDateString()]})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:b("repoMesh.nodeList.activeQueueAssignments")}),v.length===0?s.jsx("div",{children:b("repoMesh.nodeList.noActiveAssignment")}):s.jsx("ul",{className:"m-0 pl-4",children:v.map(T=>s.jsx("li",{className:"font-mono",children:t2(T)},T.id))})]}),y.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:b("repoMesh.nodeList.activeSessions")}),s.jsx("ul",{className:"m-0 pl-4",children:y.map(T=>s.jsxs("li",{className:"font-mono",children:[T.provider," / ",T.status," / ",T.id]},T.id))})]})]})]})]},w.id)})})}function e2(e,t){return t.filter(n=>n.status!=="assigned"?!1:(n.assignedNodeId||n.nodeId)===e.id)}function t2(e){const t=e.assignedSessionId||e.sessionId||"unassigned session",n=e.message.length>80?`${e.message.slice(0,77)}…`:e.message;return`${t}: ${n}`}function s2(e){var r,o;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((r=e.policy)==null?void 0:r.providerPriority)?e.policy.providerPriority:[],n=new Set,a=t.map(i=>typeof i=="string"?i.trim():"").filter(Boolean).filter(i=>n.has(i)?!1:(n.add(i),!0));return a.length?a:$0((o=e.policy)==null?void 0:o.slots)}function n2(e){const t=s2(e);return t.length?{configured:!0,label:t.join(" → ")}:{configured:!1,label:"not configured",launchBlockedMessage:"No provider configured on this node — task launch is blocked until a capability slot or provider priority is set."}}function wl(e){return e.isLocalWorktree===!0}function oo(e){return e&&(e.machineNickname||e.nickname||e.hostname||(e.id?Tf(e.id):void 0))||"Unknown"}function a2(e){return String(e.daemon_id||e.daemonId||"")}function r2(e,t){const n=new Map(t.map(o=>[o.id,o])),a=[],r=new Map;for(const o of e){const i=a2(o);r.has(i)||(r.set(i,[]),a.push(i)),r.get(i).push(o)}return a.map(o=>{const i=r.get(o),c=o?n.get(o):void 0,d=i[0],p=o?c?oo(c):(d==null?void 0:d.machine_label)||(d==null?void 0:d.machine_nickname)||(d==null?void 0:d.hostname)||o:oo(c),u=(c==null?void 0:c.status)==="online",m=i.reduce((f,g)=>{var k;return f+(Array.isArray((k=g.policy)==null?void 0:k.slots)?g.policy.slots.length:0)},0);return{key:o,label:p,online:u,nodes:i,slotCount:m}})}function o2({groups:e,activeKey:t,onChange:n}){const{t:a}=ke("common");return s.jsx("div",{className:"flex items-center gap-1 px-1 border-b border-border-subtle mb-4 overflow-x-auto",role:"tablist","aria-label":a("repoMesh.nodeList.machineTabsLabel"),children:e.map(r=>{const o=r.key===t;return s.jsxs("button",{type:"button",role:"tab","aria-selected":o,onClick:()=>n(r.key),className:`flex items-center gap-2 px-3 py-2.5 text-[13px] font-medium border-b-2 -mb-px transition-colors cursor-pointer whitespace-nowrap ${o?"border-accent text-accent":"border-transparent text-text-muted hover:text-text-secondary"}`,children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${r.online?"bg-green-400":"bg-neutral-500"}`}),s.jsx("span",{className:"truncate max-w-[160px]",children:r.label}),s.jsx("span",{className:"text-[11px] text-text-muted font-normal",children:a("repoMesh.nodeList.machineTabCounts",{nodes:r.nodes.length,slots:r.slotCount})})]},r.key)})})}function i2({nodes:e,meshQueue:t,activeDaemon:n,daemons:a,selectedMeshId:r,userName:o,features:i,coordinatorDaemonId:c,availableCliProviders:d,savingNodeSlotsId:p,onUpdateNodeSlots:u,savingNodeCapabilitiesId:m,onUpdateNodeCapabilities:f,nodeSystemPromptDrafts:g,onNodeSystemPromptDraftChange:k,savingNodeSystemPromptId:h,onSaveNodeSystemPrompt:x,selectedNodeId:S,onSelectNode:b,showAddNode:w,onShowAddNode:C,onCancelAddNode:v,nodeWorkspace:y,onNodeWorkspaceChange:j,nodeProviderPriority:N,onNodeProviderPriorityChange:A,nodeDaemonId:T,onNodeDaemonIdChange:L,nodeCustomPath:D,onNodeCustomPathChange:M,nodePickerWorkspaces:_,nodePickerProviders:P,nodeOnboardingPlan:B,nodePlanLoading:R,attachableDaemons:O,onAddNode:H,onRemoveNode:$}){var Ce,le,U;const{t:I}=ke("common"),W=l.useMemo(()=>BL(a),[a]),F=l.useMemo(()=>e.filter(J=>!wl(J)),[e]),z=l.useMemo(()=>i.addNodeDaemonPicker?r2(F,a):[],[i.addNodeDaemonPicker,F,a]),[Q,ne]=l.useState(null),oe=z.some(J=>J.key===Q)?Q:((Ce=z[0])==null?void 0:Ce.key)??"";return s.jsxs(bt,{title:i.addNodeDaemonPicker?I("repoMesh.nodeList.title",{count:F.length}):I("repoMesh.nodeList.titleNoCount"),description:i.addNodeDaemonPicker?I("repoMesh.nodeList.descriptionCloud"):I("repoMesh.nodeList.descriptionStandalone"),children:[i.addNodeDaemonPicker&&s.jsxs("div",{className:"mb-4 rounded-xl border border-border-subtle bg-bg-secondary/60 p-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:I("repoMesh.nodeList.daemonCandidates")}),s.jsx("div",{className:"text-[12px] text-text-muted",children:I("repoMesh.nodeList.daemonCandidatesHint")})]}),s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:I("repoMesh.nodeList.available",{count:O.length})})]}),a.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:I("repoMesh.nodeList.noDaemonsAvailable")}):O.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:I("repoMesh.nodeList.allDaemonsAttached")}):s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:O.map(J=>s.jsxs("button",{type:"button",className:`text-left rounded-lg border px-3 py-2 transition-colors min-w-0 ${J.id===c?"border-accent-primary/50 bg-accent-primary/10":"border-border-subtle bg-bg-primary hover:border-border-default"}`,onClick:()=>{L(J.id),j(""),M(!1),A(Pn(ln(J.availableProviders||[]))),C()},children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-sm font-medium truncate min-w-0",children:oo(J)}),J.id===c&&s.jsx("span",{className:"text-[10px] text-accent-primary shrink-0",children:I("repoMesh.nodeList.selectedHost")})]}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted font-mono truncate",children:J.id}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:I("repoMesh.nodeList.workspacesDetected",{count:(J.workspaces||[]).length})})]},J.id))})]}),!w&&s.jsxs("button",{className:"btn btn-primary btn-sm mb-4 inline-flex items-center gap-1.5",onClick:C,children:[s.jsx(_L,{size:13})," ",i.addNodeDaemonPicker?I("repoMesh.nodeList.attachMachine"):I("repoMesh.nodeList.addNode")]}),w&&s.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-accent-primary/30 bg-bg-glass animate-[fadeIn_0.3s_ease-out]",children:[s.jsxs("div",{className:"flex justify-between items-center mb-3",children:[s.jsx("h4",{className:"text-sm font-bold",children:i.addNodeDaemonPicker?I("repoMesh.nodeList.attachMachineTitle"):I("repoMesh.nodeList.addNodeTitle")}),s.jsx("button",{onClick:()=>{v(),L(""),M(!1)},className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(Dt,{size:16})})]}),i.addNodeDaemonPicker&&s.jsx(Tt,{label:I("repoMesh.nodeList.machine"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:T,onChange:J=>{var ee;L(J.target.value),j(""),M(!1),A(Pn(ln(((ee=a.find(Y=>Y.id===J.target.value))==null?void 0:ee.availableProviders)||[])))},children:[s.jsx("option",{value:"",children:I("repoMesh.nodeList.selectMachine")}),a.map(J=>s.jsx("option",{value:J.id,children:oo(J)},J.id))]})}),(i.addNodeDaemonPicker?T:!0)&&s.jsx(Tt,{label:I("repoMesh.nodeList.workspacePath"),children:i.addNodeDaemonPicker&&!D&&_.length>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex flex-col gap-1.5 mb-2",children:_.map(J=>s.jsxs("button",{type:"button",className:`text-left text-xs px-3 py-2 rounded-lg border transition-colors ${y===J.path?"border-accent-primary bg-accent-primary/10 text-text-primary":"border-border-subtle bg-bg-primary hover:bg-violet-500/10 text-text-primary"}`,onClick:()=>j(J.path),children:[s.jsx("span",{className:"font-medium block truncate",children:J.label||J.path.split("/").pop()}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:J.path})]},J.id||J.path))}),s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{M(!0),j("")},children:I("repoMesh.nodeList.enterCustomPath")})]}):s.jsx(s.Fragment,{children:i.addNodeDaemonPicker?s.jsxs(s.Fragment,{children:[s.jsx(xs,{value:y,onChange:J=>j(J.target.value),placeholder:"/Users/dev/projects/myapp",onKeyDown:J=>{J.key==="Enter"&&H()}}),_.length>0&&s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0 mt-1",onClick:()=>{M(!1),j("")},children:I("repoMesh.nodeList.pickFromSaved")})]}):(()=>{var Y;const J=Array.isArray(n==null?void 0:n.workspaces)?n.workspaces:[],ee=`mesh-add-node-workspaces-${r||"new"}`;return s.jsxs(s.Fragment,{children:[s.jsx(xs,{value:y,onChange:ve=>j(ve.target.value),placeholder:((Y=J[0])==null?void 0:Y.path)||"/Users/dev/projects/myapp",list:J.length>0?ee:void 0,autoFocus:!0}),J.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("datalist",{id:ee,children:J.map(ve=>s.jsx("option",{value:ve.path,children:ve.label||ve.path},ve.id||ve.path))}),s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:J.slice(0,6).map(ve=>s.jsx("button",{type:"button",onClick:()=>j(ve.path),className:"text-[11px] px-2 py-0.5 rounded-full border border-border-subtle hover:border-accent-primary/50 text-text-muted hover:text-text-primary transition-colors bg-transparent cursor-pointer",title:ve.path,children:ve.label||ve.path.split("/").filter(Boolean).pop()||ve.path},ve.id||ve.path))})]})]})})()})}),(R||B)&&s.jsx(Mt,{variant:(B==null?void 0:B.success)===!1?"error":"info",className:"mb-4",children:R?"Inspecting Git repository (read-only)…":B!=null&&B.success?`${((le=B.plan)==null?void 0:le.summary)||"Compatible Git workspace detected."} Adding remains an explicit action.`:`${(B==null?void 0:B.code)||"onboarding_blocked"}: ${(B==null?void 0:B.error)||"Git discovery failed"} ${(B==null?void 0:B.action)||""}`}),s.jsx(Tt,{label:I("repoMesh.nodeList.preferredTools"),hint:I("repoMesh.nodeList.preferredToolsHint"),children:s.jsx(Uj,{value:N,availableProviders:i.addNodeDaemonPicker?P:d,onChange:A})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:H,disabled:R||(B==null?void 0:B.success)===!1||!y.trim()||i.addNodeDaemonPicker&&!T,className:"btn btn-primary btn-sm",children:I("repoMesh.nodeList.add")}),s.jsx("button",{onClick:()=>{v(),L(""),M(!1)},className:"btn btn-secondary btn-sm",children:I("repoMesh.nodeList.cancel")})]})]}),F.length===0?s.jsx(Ja,{icon:s.jsx(An,{}),title:I("repoMesh.nodeList.emptyTitle"),description:I("repoMesh.nodeList.emptyDescription")}):i.addNodeDaemonPicker?s.jsxs(s.Fragment,{children:[z.length>1&&s.jsx(o2,{groups:z,activeKey:oe,onChange:ne}),s.jsx(Yu,{nodes:((U=z.find(J=>J.key===oe))==null?void 0:U.nodes)||F,meshQueue:t,activeDaemon:n,daemons:a,userName:o,features:i,providersByDaemonId:W,savingNodeSlotsId:p,onUpdateNodeSlots:u,savingNodeCapabilitiesId:m,onUpdateNodeCapabilities:f,nodeSystemPromptDrafts:g,onNodeSystemPromptDraftChange:k,savingNodeSystemPromptId:h,onSaveNodeSystemPrompt:x,selectedNodeId:S,onSelectNode:b,onRemoveNode:$})]}):s.jsx(Yu,{nodes:F,meshQueue:t,activeDaemon:n,daemons:a,userName:o,features:i,providersByDaemonId:W,savingNodeSlotsId:p,onUpdateNodeSlots:u,savingNodeCapabilitiesId:m,onUpdateNodeCapabilities:f,nodeSystemPromptDrafts:g,onNodeSystemPromptDraftChange:k,savingNodeSystemPromptId:h,onSaveNodeSystemPrompt:x,selectedNodeId:S,onSelectNode:b,onRemoveNode:$})]})}const l2=["claude-cli","codex-cli","gemini-cli","hermes-cli","antigravity-cli"],c2=[{kind:"rca",labelKey:"meshGraph.magiKind.kindRca",hint:"rca"},{kind:"design",labelKey:"meshGraph.magiKind.kindDesign",hint:"design"},{kind:"claim_audit",labelKey:"meshGraph.magiKind.kindClaimAudit",hint:"claim_audit"},{kind:"freeform",labelKey:"meshGraph.magiKind.kindFreeform",hint:"freeform"}];function d2(){return{nodeId:"",provider:"",model:"",n:""}}function Qu(e){var t;return(t=e.providers)!=null&&t.length?e.providers.filter(Boolean):(e.providerPriority??[]).filter(Boolean)}function u2(e){return{nodeId:e.nodeId??"",provider:e.provider??"",model:e.model??"",n:e.n!=null?String(e.n):""}}function p2(e){const t=[];for(let n=0;n<e.length;n++){const a=e[n],r=a.provider.trim();if(!r)return{error:{code:"provider_required",slot:n+1}};const o=a.nodeId.trim(),i=a.model.trim(),c=a.n.trim();let d;if(c){const p=Number(c);if(!Number.isFinite(p)||p<1)return{error:{code:"replica_min",slot:n+1}};d=Math.floor(p)}t.push({provider:r,...o?{nodeId:o}:{},...i?{model:i}:{},...d!==void 0?{n:d}:{}})}return t.length===0?{error:{code:"no_slot"}}:{slots:t}}function m2({status:e,daemonId:t,sendDaemonCommand:n,availableProviders:a}){const{t:r}=ke(),{theme:o}=Ls(),i=l.useMemo(()=>Rs(o),[o]),c=l.useMemo(()=>uh(a),[a]),[d,p]=l.useState({}),[u,m]=l.useState(!1),[f,g]=l.useState(null),[k,h]=l.useState({}),[x,S]=l.useState(null),b=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(F=>({nodeId:F.nodeId,machineLabel:F.machineLabel,providers:F.providers,providerPriority:F.providerPriority,isLocalWorktree:F.isLocalWorktree,worktreeBranch:F.worktreeBranch})),[e==null?void 0:e.nodes]),w=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(F=>F.nodeId),[e==null?void 0:e.nodes]),C=l.useMemo(()=>new Set(b.filter(wl).map(F=>F.nodeId)),[b]),v=l.useMemo(()=>Object.fromEntries(b.filter(wl).map(F=>[F.nodeId,F.worktreeBranch])),[b]),y=l.useMemo(()=>Object.fromEntries(((e==null?void 0:e.nodes)??[]).map(F=>[F.nodeId,F.machineLabel||F.nodeId])),[e==null?void 0:e.nodes]),j=l.useMemo(()=>{const F={};for(const z of b)F[z.nodeId]=Qu(z);return F},[b]),N=l.useMemo(()=>{const F=[...new Set(b.flatMap(Qu).filter(Boolean))];return[...new Set([...F,...l2])].sort()},[b]),A=!!t&&!!n,T=F=>F&&typeof F=="object"&&"result"in F?F.result:F,L=e==null?void 0:e.meshId,D=l.useCallback(async()=>{if(!(!t||!n)){m(!0),g(null);try{const F=await n(t,"magi_kind_panel_list",{...L?{meshId:L}:{}}),z=T(F);if((z==null?void 0:z.success)===!1)throw new Error(z.error||r("meshGraph.magiKind.errorLoad"));p(z!=null&&z.kindPanels&&typeof z.kindPanels=="object"?z.kindPanels:{}),h({})}catch(F){g((F==null?void 0:F.message)||r("meshGraph.magiKind.errorLoad"))}finally{m(!1)}}},[t,n,L,r]);l.useEffect(()=>{D()},[D]);const M=l.useCallback(F=>{if(k[F])return k[F];const z=d[F];return z?z.map(u2):[]},[k,d]),_=(F,z)=>{h(Q=>({...Q,[F]:z}))},P=(F,z,Q)=>{const ne=M(F);_(F,ne.map((oe,Ce)=>Ce===z?{...oe,...Q}:oe))},B=F=>{_(F,[...M(F),d2()])},R=(F,z)=>{_(F,M(F).filter((Q,ne)=>ne!==z))},O=l.useCallback(async F=>{if(!t||!n)return;const z=p2(M(F));if("error"in z){const Q=z.error,ne=Q.code==="provider_required"?r("meshGraph.magiKind.errorSlotProvider",{slot:Q.slot}):Q.code==="replica_min"?r("meshGraph.magiKind.errorSlotReplica",{slot:Q.slot}):r("meshGraph.magiKind.errorNoSlot");g(`${F}: ${ne}`);return}S(F),g(null);try{const Q=await n(t,"magi_kind_panel_set",{kind:F,slots:z.slots,...L?{meshId:L}:{}}),ne=T(Q);if((ne==null?void 0:ne.success)===!1)throw new Error(ne.error||r("meshGraph.magiKind.errorSave"));await D()}catch(Q){g((Q==null?void 0:Q.message)||r("meshGraph.magiKind.errorSave"))}finally{S(null)}},[t,n,M,D,L,r]),H=l.useCallback(async F=>{if(!(!t||!n)&&confirm(r("meshGraph.magiKind.removeConfirm",{kind:F}))){S(F),g(null);try{const z=await n(t,"magi_kind_panel_remove",{kind:F,...L?{meshId:L}:{}}),Q=T(z);if((Q==null?void 0:Q.success)===!1)throw new Error(Q.error||r("meshGraph.magiKind.errorRemove"));await D()}catch(z){g((z==null?void 0:z.message)||r("meshGraph.magiKind.errorRemove"))}finally{S(null)}}},[t,n,D,L,r]),$=`w-full rounded-lg border px-2.5 py-1.5 text-xs ${i.isDark?"border-white/10 bg-slate-950/40 text-slate-100 placeholder:text-slate-500":"border-slate-300 bg-white text-slate-900 placeholder:text-slate-400"}`,I="btn btn-primary btn-sm",W="btn btn-secondary btn-sm";return s.jsxs("div",{className:"flex flex-col gap-3 p-1",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("p",{className:`text-[12px] ${i.textSecondary}`,children:r("meshGraph.magiKind.intro")}),s.jsx("div",{className:"ml-auto flex items-center gap-2",children:s.jsx("button",{type:"button",className:W,onClick:()=>void D(),disabled:u||!A,children:r(u?"meshGraph.magiKind.loading":"meshGraph.magiKind.refresh")})})]}),!A&&s.jsx("div",{className:`rounded-xl border p-3 text-[12px] ${i.textSecondary} ${i.isDark?"border-white/10":"border-slate-200"}`,children:r("meshGraph.magiKind.connectPrompt")}),f&&s.jsx("div",{className:"rounded-xl border border-rose-500/30 bg-rose-500/10 px-3 py-2 text-[12px] text-rose-300",children:f}),s.jsx("div",{className:"flex flex-col gap-3",children:c2.map(({kind:F,labelKey:z,hint:Q})=>{const ne=M(F),oe=!!d[F],Ce=x===F;return s.jsxs("div",{className:`${i.cardClass} rounded-2xl p-4 flex flex-col gap-3`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[13px] font-semibold ${i.textPrimary}`,children:r(z)}),s.jsx("span",{className:`font-mono text-[10px] ${i.textMuted}`,children:Q}),s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${oe?"border-emerald-400/30 bg-emerald-500/10 text-emerald-300":"border-slate-400/20 bg-slate-500/10 text-slate-300"}`,children:oe?r("meshGraph.magiKind.agentCount",{count:d[F].length}):r("meshGraph.magiKind.off")})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[ne.length===0&&s.jsx("div",{className:`rounded-xl border p-2.5 text-[11px] ${i.textSecondary} ${i.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:r("meshGraph.magiKind.noAgents")}),ne.map((le,U)=>{const J=le.nodeId?j[le.nodeId]??[]:[],ee=le.nodeId&&J.length?J:N;return s.jsxs("div",{className:`rounded-xl border p-2.5 grid grid-cols-1 sm:grid-cols-[1fr_1fr_1fr_auto_auto] gap-x-2 gap-y-1 items-start ${i.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:r("meshGraph.magiKind.machine")}),s.jsxs("select",{className:$,value:le.nodeId,onChange:Y=>P(F,U,{nodeId:Y.target.value}),title:r("meshGraph.magiKind.machineTitle"),children:[s.jsx("option",{value:"",children:r("meshGraph.magiKind.anyMachine")}),w.map(Y=>{const ve=C.has(Y),pe=ve?r("meshGraph.magiKind.worktreeSuffix",{label:y[Y]??Y,branch:v[Y]||r("meshGraph.magiKind.worktreeUnknownBranch")}):y[Y]??Y;return s.jsx("option",{value:Y,disabled:ve,title:ve?r("meshGraph.magiKind.worktreeDisabledTitle"):void 0,children:pe},Y)}),le.nodeId&&!w.includes(le.nodeId)&&s.jsx("option",{value:le.nodeId,children:r("meshGraph.magiKind.offlineSuffix",{label:y[le.nodeId]??le.nodeId})})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsxs("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:[r("meshGraph.magiKind.provider")," *"]}),s.jsxs("select",{className:$,value:le.provider,onChange:Y=>P(F,U,{provider:Y.target.value}),title:r("meshGraph.magiKind.providerTitle"),children:[s.jsx("option",{value:"",children:r("meshGraph.magiKind.selectProvider")}),ee.map(Y=>s.jsx("option",{value:Y,children:Y},Y)),le.provider&&!ee.includes(le.provider)&&s.jsx("option",{value:le.provider,children:le.provider})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:r("meshGraph.magiKind.model")}),(()=>{var pe;const Y=(le.provider?(pe=c.get(le.provider))==null?void 0:pe.models:void 0)??[],ve=!!le.model&&Y.length>0&&!Y.includes(le.model);return Y.length>0&&!ve?s.jsxs("select",{className:$,value:Y.includes(le.model)?le.model:"",title:r("meshGraph.magiKind.modelTitle"),onChange:te=>P(F,U,{model:te.target.value==="__custom__"?" ":te.target.value}),children:[s.jsx("option",{value:"",children:r("meshGraph.magiKind.modelDefault")}),Y.map(te=>s.jsx("option",{value:te,children:te},te)),s.jsx("option",{value:"__custom__",children:r("meshGraph.magiKind.modelCustom")})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:$,value:le.model.trim(),placeholder:r("meshGraph.magiKind.modelDefault"),title:r("meshGraph.magiKind.modelTitle"),onChange:te=>P(F,U,{model:te.target.value})}),Y.length>0&&s.jsx("button",{type:"button",className:`self-start bg-transparent border-none cursor-pointer p-0 text-[10px] ${i.textSecondary} hover:underline`,onClick:()=>P(F,U,{model:""}),children:r("meshGraph.magiKind.backToModelList")})]})})()]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:r("meshGraph.magiKind.copies")}),s.jsx("input",{className:`${$} sm:w-16`,value:le.n,placeholder:"1",inputMode:"numeric",title:r("meshGraph.magiKind.copiesTitle"),onChange:Y=>P(F,U,{n:Y.target.value})})]}),s.jsx("button",{type:"button",className:`${W} sm:mt-[18px] inline-flex h-8 w-8 items-center justify-center p-0`,onClick:()=>R(F,U),"aria-label":r("meshGraph.magiKind.removeAgent"),title:r("meshGraph.magiKind.removeAgent"),children:"✕"})]},U)}),s.jsx("div",{children:s.jsx("button",{type:"button",className:W,onClick:()=>B(F),disabled:!A,children:r("meshGraph.magiKind.addAgent")})})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",className:I,onClick:()=>void O(F),disabled:Ce||!A,children:r(Ce?"meshGraph.magiKind.saving":"meshGraph.magiKind.save")}),s.jsx("button",{type:"button",className:W,onClick:()=>void H(F),disabled:Ce||!A||!oe,title:r(oe?"meshGraph.magiKind.removeBindingTitle":"meshGraph.magiKind.removeBindingDisabledTitle"),children:r("meshGraph.magiKind.removeBinding")})]})]},F)})})]})}const Wn={sessionMinRemainingPercent:10,weeklyMinRemainingPercent:15,sessionResetImminentMinutes:5,staleAfterMinutes:30,spreadBonusMax:30,sessionAxisWeeklyHeadroomPercent:40},kl=60*1e3;function Ju(e){return e===void 0||!Number.isFinite(e)?"":String(e/kl)}function Sl(e){const t=e??{};return{sessionMinRemainingPercent:t.sessionMinRemainingPercent!==void 0?String(t.sessionMinRemainingPercent):"",weeklyMinRemainingPercent:t.weeklyMinRemainingPercent!==void 0?String(t.weeklyMinRemainingPercent):"",sessionResetImminentMinutes:Ju(t.sessionResetImminentMs),staleAfterMinutes:Ju(t.staleAfterMs),spreadBonusMax:t.spreadBonusMax!==void 0?String(t.spreadBonusMax):"",sessionAxisWeeklyHeadroomPercent:t.sessionAxisWeeklyHeadroomPercent!==void 0?String(t.sessionAxisWeeklyHeadroomPercent):""}}function h2(e,t){const n=t.trim();if(!n)return null;const a=Number(n);if(!Number.isFinite(a))return"notANumber";const r=e==="sessionMinRemainingPercent"||e==="weeklyMinRemainingPercent"||e==="sessionAxisWeeklyHeadroomPercent";return r&&(a<0||a>100)?"percentRange":!r&&a<0?"negative":null}function Cl(e){const t={},n=p=>{const u=p.trim();if(!u)return;const m=Number(u);return Number.isFinite(m)?m:void 0},a=n(e.sessionMinRemainingPercent);a!==void 0&&(t.sessionMinRemainingPercent=a);const r=n(e.weeklyMinRemainingPercent);r!==void 0&&(t.weeklyMinRemainingPercent=r);const o=n(e.sessionResetImminentMinutes);o!==void 0&&(t.sessionResetImminentMs=o*kl);const i=n(e.staleAfterMinutes);i!==void 0&&(t.staleAfterMs=i*kl);const c=n(e.spreadBonusMax);c!==void 0&&(t.spreadBonusMax=c);const d=n(e.sessionAxisWeeklyHeadroomPercent);return d!==void 0&&(t.sessionAxisWeeklyHeadroomPercent=d),t}const f2="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs",g2="w-full rounded-lg border border-red-500/60 bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function b2({quotaRouting:e,saving:t,error:n,onSave:a}){const{t:r}=ke("common"),[o,i]=l.useState(()=>Sl(e)),c=l.useCallback((k,h)=>{i(x=>({...x,[k]:h}))},[]),d=l.useMemo(()=>{const k={};for(const h of Object.keys(o)){const x=h2(h,o[h]);x&&(k[h]=x)}return k},[o]),p=Object.keys(d).length>0,u=l.useMemo(()=>JSON.stringify(Cl(o))!==JSON.stringify(x2(e)),[o,e]),m=l.useCallback(()=>{p||a(Cl(o))},[o,p,a]),f=l.useCallback(()=>{i(Sl(null))},[]),g=[{key:"sessionMinRemainingPercent",label:r("setupWizard.quotaPolicy.sessionMin"),hint:r("setupWizard.quotaPolicy.sessionMinHint"),placeholder:Wn.sessionMinRemainingPercent,unit:"%"},{key:"weeklyMinRemainingPercent",label:r("setupWizard.quotaPolicy.weeklyMin"),hint:r("setupWizard.quotaPolicy.weeklyMinHint"),placeholder:Wn.weeklyMinRemainingPercent,unit:"%"},{key:"sessionResetImminentMinutes",label:r("setupWizard.quotaPolicy.resetImminent"),hint:r("setupWizard.quotaPolicy.resetImminentHint"),placeholder:Wn.sessionResetImminentMinutes,unit:r("setupWizard.quotaPolicy.minutes")},{key:"staleAfterMinutes",label:r("setupWizard.quotaPolicy.staleAfter"),hint:r("setupWizard.quotaPolicy.staleAfterHint"),placeholder:Wn.staleAfterMinutes,unit:r("setupWizard.quotaPolicy.minutes")},{key:"spreadBonusMax",label:r("setupWizard.quotaPolicy.spreadBonus"),hint:r("setupWizard.quotaPolicy.spreadBonusHint"),placeholder:Wn.spreadBonusMax,unit:""},{key:"sessionAxisWeeklyHeadroomPercent",label:r("setupWizard.quotaPolicy.sessionAxisWeeklyHeadroom"),hint:r("setupWizard.quotaPolicy.sessionAxisWeeklyHeadroomHint"),placeholder:Wn.sessionAxisWeeklyHeadroomPercent,unit:"%"}];return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:r("setupWizard.quotaPolicy.title")}),s.jsx("p",{className:"mt-1 text-[11px] leading-relaxed text-text-muted",children:r("setupWizard.quotaPolicy.description")})]}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 sm:grid-cols-2",children:g.map(k=>{const h=d[k.key];return s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsxs("span",{className:"text-[11px] text-text-muted",children:[k.label,k.unit?` (${k.unit})`:""]}),s.jsx("input",{type:"number",inputMode:"decimal",className:h?g2:f2,value:o[k.key],placeholder:String(k.placeholder),onChange:x=>c(k.key,x.target.value)}),s.jsx("span",{className:`text-[10px] leading-snug ${h?"text-red-400":"text-text-muted"}`,children:h?r(`setupWizard.quotaPolicy.errors.${h}`):k.hint})]},k.key)})}),s.jsx("p",{className:"text-[10px] leading-relaxed text-text-muted",children:r("setupWizard.quotaPolicy.blankMeansDefault")}),n?s.jsx("p",{className:"text-[11px] text-red-400",children:n}):null,s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:f,children:r("setupWizard.quotaPolicy.useDefaults")}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm ml-auto",onClick:m,disabled:!!t||p||!u,children:r(t?"setupWizard.quotaPolicy.saving":"setupWizard.quotaPolicy.save")})]})]})}function x2(e){return Cl(Sl(e))}function ng(e,t,n,a){const{t:r}=ke(),[o,i]=l.useState(!1),[c,d]=l.useState(null),[p,u]=l.useState(null),[m,f]=l.useState(null),g=l.useCallback(async()=>{if(!e||!t){d(r("repoMesh.promptPreview.connectPrompt"));return}i(!0),d(null);try{const k=await a(e,"coordinator_prompt_preview",{meshId:t,cliType:n}),h=k!=null&&k.result&&typeof k.result=="object"?k.result:k;if(!(h!=null&&h.success))return d((h==null?void 0:h.error)||r("repoMesh.promptPreview.errorRender")),null;const x=typeof h.prompt=="string"?h.prompt:"";return u(x),f(typeof h.bytes=="number"?h.bytes:null),x}catch(k){return d((k==null?void 0:k.message)||String(k)),null}finally{i(!1)}},[e,t,n,a,r]);return{loading:o,error:c,prompt:p,bytes:m,load:g}}function v2({daemonId:e,meshId:t,cliType:n,sendCommand:a,defaultOpen:r=!1}){const{t:o}=ke(),[i,c]=l.useState(r),{loading:d,error:p,prompt:u,bytes:m,load:f}=ng(e,t,n,a),g=l.useRef(!1);l.useEffect(()=>{i&&!g.current&&(g.current=!0,f())},[i,f]);const k=l.useCallback(()=>{c(h=>!h)},[]);return s.jsxs("div",{className:"mt-2",children:[s.jsxs("button",{type:"button",onClick:k,className:"inline-flex items-center gap-1 text-[12px] text-accent-primary bg-transparent border-none cursor-pointer p-0",children:[s.jsx("span",{className:`transition-transform ${i?"rotate-90":""}`,"aria-hidden":!0,children:"▸"}),o(i?"repoMesh.promptPreview.hide":"repoMesh.promptPreview.view"),s.jsxs("span",{className:"text-text-muted",children:["(",n,")"]})]}),i&&s.jsxs("div",{className:"mt-2",children:[d&&s.jsx("div",{className:"text-[12px] text-text-muted",children:o("repoMesh.promptPreview.rendering")}),p&&s.jsxs("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:[p,s.jsx("button",{type:"button",onClick:()=>void f(),className:"ml-2 underline bg-transparent border-none cursor-pointer text-amber-300",children:o("repoMesh.promptPreview.retry")})]}),!d&&!p&&u!==null&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between text-[11px] text-text-muted",children:[s.jsx("span",{children:o("repoMesh.promptPreview.info")}),m!==null&&s.jsxs("span",{children:[(m/1024).toFixed(1)," KB"]})]}),s.jsx("textarea",{readOnly:!0,value:u,rows:14,className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-[12px] text-text-secondary font-mono",onFocus:h=>h.currentTarget.select()})]})]})]})}function y2({daemonId:e,meshId:t,cliType:n,sendCommand:a,disabled:r,hasContent:o,onApply:i}){const{t:c}=ke(),{loading:d,load:p}=ng(e,t,n,a),u=l.useCallback(async()=>{if(o&&!window.confirm(c("repoMesh.detail.startFromDefaultConfirm")))return;const m=await p();typeof m=="string"&&i(m)},[o,p,i,c]);return s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm mt-2",onClick:()=>void u(),disabled:r||d||!e||!t,title:c("repoMesh.detail.startFromDefaultTitle"),children:c(d?"repoMesh.promptPreview.rendering":"repoMesh.detail.startFromDefault")})}const w2=[{token:"meshName",description:"This mesh's display name.",example:"my-app"},{token:"repo",description:"Repo identity (owner/repo or workspace path).",example:"vilmire/adhdev"},{token:"defaultBranch",description:"The mesh's default branch.",example:"main"},{token:"cliType",description:"The coordinator CLI type this prompt is being rendered for.",example:"claude-cli"},{token:"nodes",description:"Live node status table, or the configured node list if no live status is available.",example:"(rendered node table)"},{token:"mission",description:"Current mission section, when a mission is active. Empty otherwise.",example:"(mission summary or empty)"},{token:"recentActivity",description:"Recent mesh activity summary. Empty when none.",example:"(recent activity or empty)"},{token:"operatingNotes",description:"Accumulated operating notes for this mesh. Empty when none.",example:"(operating notes or empty)"},{token:"policy",description:"The mesh's effective policy section (safety, scheduling, etc.).",example:"(rendered policy section)"},{token:"tools",description:"The canonical MCP tools reference table.",example:"(tools table)"},{token:"workflow",description:"The standard coordinator workflow guidance section.",example:"(workflow section)"},{token:"onboarding",description:"Onboarding/reinit guidance section.",example:"(onboarding section)"},{token:"rules",description:"CLI-type-specific and policy-derived rules section.",example:"(rules section)"},{token:"toolExposurePreflight",description:"Preflight guidance for verifying tool exposure before relying on it.",example:"(preflight section)"}],k2=e=>e&&typeof e=="object"&&"result"in e?e.result:e;function S2(e){const t=k2(e);return t&&typeof t=="object"&&t.status&&typeof t.status=="object"&&Array.isArray(t.status.missions)?t.status:t}function C2(e){const t=e==null?void 0:e.missions;return Array.isArray(t)?t:[]}function j2(e){return typeof e.goal=="string"&&e.goal?{text:e.goal,truncated:!1}:{text:e.goalPreview??"",truncated:e.goalTruncated===!0}}const N2=["active","paused","completed","abandoned"];function Xu(e){return(e.status||"active").toLowerCase()}const A2=8;function T2({status:e,daemonId:t,meshId:n,sendCommand:a}){const{t:r}=ke("common"),o=l.useMemo(()=>C2(e),[e]),[i,c]=l.useState({}),[d,p]=l.useState({}),[u,m]=l.useState(!1),[f,g]=l.useState(null),[k,h]=l.useState("active"),[x,S]=l.useState(!1),b=l.useMemo(()=>{const A={};for(const T of o){const L=Xu(T);A[L]=(A[L]||0)+1}return A},[o]),w=l.useMemo(()=>k==="all"?o:o.filter(A=>Xu(A)===k),[o,k]),C=x?w:w.slice(0,A2),v=w.length-C.length,y=!!t&&o.length>0,j=l.useCallback(async()=>{if(t){m(!0),g(null);try{const A=await a(t,"mesh_status",{meshId:n,verbose:!0}),T=S2(A),L=Array.isArray(T==null?void 0:T.missions)?T.missions:[],D={};for(const M of L)M.id&&typeof M.goal=="string"&&M.goal&&(D[M.id]=M.goal);c(M=>({...M,...D}))}catch(A){g(A instanceof Error?A.message:r("repoMesh.missions.errorFetch"))}finally{m(!1)}}},[t,n,a,r]),N=l.useCallback(A=>{p(T=>({...T,[A]:!T[A]})),!d[A]&&!i[A]&&j()},[d,i,j]);return o.length===0?null:s.jsxs(bt,{title:r("repoMesh.missions.title"),description:r("repoMesh.missions.description"),children:[f&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400",children:f}),s.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-1.5",children:[N2.filter(A=>(b[A]||0)>0).map(A=>s.jsxs("button",{type:"button",onClick:()=>{h(A),S(!1)},className:`rounded-full border px-2.5 py-0.5 text-[11px] capitalize transition-colors ${k===A?"border-accent-primary text-accent-primary":"border-border-subtle text-text-muted hover:text-text-secondary"}`,children:[A," ",b[A]]},A)),s.jsxs("button",{type:"button",onClick:()=>{h("all"),S(!1)},className:`rounded-full border px-2.5 py-0.5 text-[11px] transition-colors ${k==="all"?"border-accent-primary text-accent-primary":"border-border-subtle text-text-muted hover:text-text-secondary"}`,children:["All ",o.length]})]}),w.length===0&&s.jsx("div",{className:"text-[12px] text-text-muted",children:r("repoMesh.missions.empty",{status:k})}),s.jsx("div",{className:"flex flex-col gap-2",children:C.map(A=>{var B;const T=d[A.id]===!0,L=i[A.id],D=j2(A),M=T&&L?L:D.text,_=T&&!L&&D.truncated,P=((B=A.tasks)==null?void 0:B.total)??0;return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 px-3 py-2.5",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-text-primary",title:A.title,children:A.title||A.id}),A.status&&s.jsx("span",{className:"shrink-0 rounded-full border border-border-subtle px-2 py-0.5 text-[10px] uppercase tracking-wide text-text-muted",children:A.status}),P>0&&s.jsx("span",{className:"shrink-0 text-[11px] text-text-muted",children:r("repoMesh.missions.taskCount",{count:P})})]}),M&&s.jsxs("div",{className:`mt-1.5 whitespace-pre-wrap text-[12px] leading-5 text-text-secondary ${T?"max-h-72 overflow-y-auto":"line-clamp-2"}`,children:[M,_&&s.jsx("span",{className:"text-text-muted",children:r("repoMesh.missions.goalUnavailable")})]}),(D.truncated||L)&&y&&s.jsx("button",{type:"button",className:"mt-1.5 text-[12px] text-accent-primary hover:underline disabled:opacity-50",onClick:()=>N(A.id),disabled:u,children:r(T?"repoMesh.missions.showLess":u&&!L?"repoMesh.missions.loading":"repoMesh.missions.showFullGoal")})]},A.id)})}),v>0&&s.jsx("button",{type:"button",className:"mt-2 text-[12px] text-accent-primary hover:underline",onClick:()=>S(!0),children:r("repoMesh.missions.showMore",{count:v})})]})}function Zu(e,t){if(t)return e.modes.find(n=>n.id===t)}function M2(e){return e.modes.find(t=>t.strategy==="pty-parse-default"&&Gs(t)!=="dangerous")}function P2({config:e,requestedModeId:t,machineAutoApproveEnabled:n,machineDangerousAllowed:a}){const r=Zu(e,e.default),o=r==null?void 0:r.id,i=(t==null?void 0:t.trim())||void 0;if(!n)return{status:"disabled",requestedModeId:i,providerDefaultModeId:o,requestedModeUnknown:!1,downgraded:!1};const c=Zu(e,i),d=!!i&&!c,p=c??r;if(!p||p.strategy==="post-boot-command")return{status:"none",requestedModeId:i,providerDefaultModeId:o,requestedModeUnknown:d,downgraded:!1};if(Gs(p)==="dangerous"&&!a){const u=M2(e);return{status:u?"downgraded":"none",requestedModeId:i,providerDefaultModeId:o,effectiveMode:u,requestedModeUnknown:d,downgraded:!0}}return{status:d?"invalid_fallback":"requested",requestedModeId:i,providerDefaultModeId:o,effectiveMode:p,requestedModeUnknown:d,downgraded:!1}}function D2(e){const t=[];for(const n of e||[]){if(!n||n.category!=="cli")continue;const a=n.autoApproveModes;if(!a||!Array.isArray(a.modes)||a.modes.length===0)continue;const r=String(n.type||n.id||"").trim();r&&t.push({type:r,label:String(n.displayName||n.name||r),autoApproveModes:a})}return t}function I2({hostDaemonId:e,hostOnline:t,hostWorkspace:n,meshProviders:a,unreportedNodeCount:r=0,machineAutoApproveEnabled:o,machineDangerousAllowed:i,onUpdatePolicy:c,savingPolicy:d,sendCommand:p}){const{t:u}=ke("common"),m=l.useMemo(()=>D2(a),[a]),[f,g]=l.useState({}),[k,h]=l.useState(!1),[x,S]=l.useState(null),[b,w]=l.useState(!1),[C,v]=l.useState(null),[y,j]=l.useState(!1),[N,A]=l.useState(null),[T,L]=l.useState(!1),D=!!e&&t&&!!n,M=!!c&&!d,_=l.useCallback(async()=>{var H,$,I;if(D){h(!0),S(null);try{const W=await p(e,"read_mesh_json_config",{workspace:n}),F=(W==null?void 0:W.result)??W,z=((H=F==null?void 0:F.providerDefaults)==null?void 0:H.autoApproveModes)||((I=($=F==null?void 0:F.config)==null?void 0:$.providerDefaults)==null?void 0:I.autoApproveModes),Q={};if(z&&typeof z=="object")for(const[ne,oe]of Object.entries(z))typeof oe=="string"&&oe.trim()&&(Q[ne]=oe.trim());g(Q)}catch(W){S((W==null?void 0:W.message)||u("repoMesh.providerAutoApprove.loadError"))}finally{h(!1)}}},[D,e,n,p,u]);l.useEffect(()=>{_()},[_]);const P=l.useCallback((H,$)=>{j(!1),g(I=>{const W={...I};return $&&$.trim()?W[H]=$.trim():delete W[H],W})},[]),B=l.useCallback((H,$)=>{if(Gs($)==="dangerous"){A({type:H,mode:$});return}P(H,$.id)},[P]),R=l.useCallback(()=>{N&&P(N.type,N.mode.id),A(null)},[P,N]),O=l.useCallback(async()=>{if(D){w(!0),v(null),j(!1);try{const H=await p(e,"set_mesh_provider_defaults",{workspace:n,autoApproveModes:f,merge:!1,write:!0}),$=(H==null?void 0:H.result)??H;if(($==null?void 0:$.success)===!1)throw new Error(($==null?void 0:$.error)||u("repoMesh.providerAutoApprove.saveError"));j(!0),await _()}catch(H){v((H==null?void 0:H.message)||u("repoMesh.providerAutoApprove.saveError"))}finally{w(!1)}}},[D,e,n,_,f,p,u]);return s.jsxs(bt,{title:u("repoMesh.providerAutoApprove.title"),description:u("repoMesh.providerAutoApprove.subtitle"),collapsible:!0,defaultOpen:!1,children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/40 p-3.5",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:u("repoMesh.providerAutoApprove.machineSection.title")}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:u("repoMesh.providerAutoApprove.machineSection.hint")}),s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2 text-[11px]",children:[s.jsx("span",{className:`rounded-full border px-2 py-0.5 font-semibold ${o?"border-status-online/25 bg-status-online/10 text-status-online":"border-border-subtle bg-surface-secondary/40 text-text-muted"}`,children:u(o?"repoMesh.providerAutoApprove.machineSection.autoApproveOn":"repoMesh.providerAutoApprove.machineSection.autoApproveOff")}),s.jsx("span",{className:`rounded-full border px-2 py-0.5 font-semibold ${i?"border-status-error/30 bg-status-error/10 text-status-error":"border-border-subtle bg-surface-secondary/40 text-text-muted"}`,children:u(i?"repoMesh.providerAutoApprove.machineSection.dangerousOn":"repoMesh.providerAutoApprove.machineSection.dangerousOff")})]}),s.jsxs("div",{className:"mt-3 space-y-2",children:[s.jsx(ep,{label:u("repoMesh.providerAutoApprove.machineSection.autoApproveToggleLabel"),hint:u("repoMesh.providerAutoApprove.machineSection.autoApproveToggleHint"),checked:o,disabled:!M,onChange:H=>c==null?void 0:c({delegatedWorkerAutoApprove:H})}),s.jsx(ep,{label:u("repoMesh.providerAutoApprove.machineSection.dangerousToggleLabel"),hint:u(o?"repoMesh.providerAutoApprove.machineSection.dangerousToggleHint":"repoMesh.providerAutoApprove.machineSection.dangerousDisabledHint"),checked:i,disabled:!M||!o,onChange:H=>{H?L(!0):c==null||c({delegatedWorkerDangerousModeAllow:!1})}})]})]}),D?k?s.jsx("div",{className:"text-[13px] text-text-muted",children:u("repoMesh.providerAutoApprove.loading")}):m.length===0?s.jsx("div",{className:"text-[13px] text-text-muted",children:r>0?u("repoMesh.providerAutoApprove.awaitingNodes",{count:r}):u("repoMesh.providerAutoApprove.noProviders")}):s.jsxs("div",{className:"space-y-6",children:[x&&s.jsx(Mt,{variant:"error",onDismiss:()=>S(null),children:x}),r>0&&s.jsx("div",{className:"text-[11px] text-text-muted",children:u("repoMesh.providerAutoApprove.partialInventory",{count:r})}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:u("repoMesh.providerAutoApprove.repoSection.title")}),s.jsx("div",{className:"text-[11px] text-text-muted",children:u("repoMesh.providerAutoApprove.repoSection.hint")})]}),s.jsx("div",{className:"space-y-5",children:m.map(H=>{const $=f[H.type],I=P2({config:H.autoApproveModes,requestedModeId:$,machineAutoApproveEnabled:o,machineDangerousAllowed:i});return s.jsxs("div",{className:"rounded-xl border border-border-subtle p-3.5",children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary",children:H.label}),s.jsx("button",{type:"button",className:"text-[11px] text-text-muted underline decoration-dotted hover:text-text-primary disabled:opacity-40",onClick:()=>P(H.type,void 0),disabled:!$||b,children:u("repoMesh.providerAutoApprove.repoSection.clear")})]}),s.jsx(lf,{config:H.autoApproveModes,selectedModeId:$||"",disabled:b,onSelectMode:W=>B(H.type,W)}),!$&&s.jsx("div",{className:"mt-1.5 text-[11px] text-text-muted",children:u("repoMesh.providerAutoApprove.repoSection.usesProviderDefault")}),s.jsx(L2,{effective:I,config:H.autoApproveModes})]},H.type)})}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:u("repoMesh.providerAutoApprove.effectiveSection.title")}),s.jsx("div",{className:"text-[11px] text-text-muted",children:u("repoMesh.providerAutoApprove.effectiveSection.hint")})]}),C&&s.jsx(Mt,{variant:"error",onDismiss:()=>v(null),children:C}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("button",{type:"button",className:"rounded-lg bg-accent-primary px-4 py-2 text-sm font-semibold text-white disabled:opacity-50",onClick:()=>void O(),disabled:b,children:u(b?"repoMesh.providerAutoApprove.saving":"repoMesh.providerAutoApprove.save")}),y&&s.jsx("span",{className:"text-[12px] text-status-online",children:u("repoMesh.providerAutoApprove.saved")})]})]}):s.jsx("div",{className:"text-[13px] text-text-muted",children:u("repoMesh.providerAutoApprove.noHostDaemon")}),T&&s.jsx(jo,{title:u("repoMesh.providerAutoApprove.machineSection.confirmTitle"),description:u("repoMesh.providerAutoApprove.machineSection.confirmDescription"),details:[{label:u("repoMesh.providerAutoApprove.machineSection.confirmScopeLabel"),value:u("repoMesh.providerAutoApprove.machineSection.confirmScopeValue")},{label:u("repoMesh.providerAutoApprove.machineSection.confirmEffectLabel"),value:u("repoMesh.providerAutoApprove.machineSection.confirmEffectValue")}],confirmLabel:u("repoMesh.providerAutoApprove.machineSection.confirmConfirm"),onConfirm:()=>{L(!1),c==null||c({delegatedWorkerDangerousModeAllow:!0})},onCancel:()=>L(!1)}),N&&s.jsx(cf,{mode:N.mode,onConfirm:R,onCancel:()=>A(null)}),N&&s.jsx("div",{className:"fixed inset-x-0 bottom-6 z-[60] mx-auto max-w-lg px-4",children:s.jsxs("div",{className:"rounded-xl border border-status-error/40 bg-bg-primary p-3.5 shadow-lg",children:[s.jsx("div",{className:"text-sm font-semibold text-status-error",children:u("repoMesh.providerAutoApprove.dangerous.sharedWarningTitle")}),s.jsx("div",{className:"mt-1 text-[12px] text-text-muted",children:u("repoMesh.providerAutoApprove.dangerous.sharedWarning")})]})})]})}function L2({effective:e,config:t}){var c,d,p;const{t:n}=ke("common"),a=u=>{var m;return(u?(m=t.modes.find(f=>f.id===u))==null?void 0:m.label:void 0)||u||""};let r,o="ok";switch(e.status){case"requested":r=n("repoMesh.providerAutoApprove.effectiveSection.statusRequested",{mode:((c=e.effectiveMode)==null?void 0:c.label)||""});break;case"invalid_fallback":r=n("repoMesh.providerAutoApprove.effectiveSection.statusInvalidFallback",{mode:((d=e.effectiveMode)==null?void 0:d.label)||""}),o="warn";break;case"downgraded":r=n("repoMesh.providerAutoApprove.effectiveSection.statusDowngraded",{requested:a(e.requestedModeId)||a(e.providerDefaultModeId),mode:((p=e.effectiveMode)==null?void 0:p.label)||""}),o="warn";break;case"disabled":r=n("repoMesh.providerAutoApprove.effectiveSection.statusDisabled"),o="muted";break;default:r=n("repoMesh.providerAutoApprove.effectiveSection.statusNone"),o="muted"}const i=o==="ok"?"border-status-online/25 bg-status-online/5 text-text-secondary":o==="warn"?"border-status-warning/30 bg-status-warning/5 text-status-warning":"border-border-subtle bg-surface-secondary/30 text-text-muted";return s.jsxs("div",{className:`mt-3 flex items-center gap-2 rounded-lg border px-3 py-2 text-[12px] ${i}`,children:[e.effectiveMode&&s.jsx(of,{risk:Gs(e.effectiveMode)}),s.jsx("span",{className:"min-w-0",children:r})]})}function ep({label:e,hint:t,checked:n,disabled:a=!1,onChange:r}){return s.jsxs("button",{type:"button",role:"switch","aria-checked":n,className:"flex w-full items-center justify-between gap-3 rounded-xl border border-border-subtle bg-bg-primary/60 px-3.5 py-2.5 text-left disabled:opacity-50",onClick:()=>r(!n),disabled:a,children:[s.jsxs("span",{children:[s.jsx("span",{className:"block text-[13px] font-semibold text-text-primary",children:e}),s.jsx("span",{className:"mt-0.5 block text-[11px] text-text-muted",children:t})]}),s.jsx("span",{className:`relative h-6 w-11 shrink-0 rounded-full transition-colors ${n?"bg-accent-primary":"bg-surface-secondary"}`,children:s.jsx("span",{className:`absolute top-0.5 h-5 w-5 rounded-full bg-white shadow transition-transform ${n?"translate-x-5":"translate-x-0.5"}`})})]})}function kr(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function R2({daemons:e,coordinatorDaemonId:t,onCoordinatorDaemonIdChange:n,isHostNodeAttached:a,selectedHostNode:r,hostPinned:o,hostLabel:i,hostOnline:c,hostRebindDaemonId:d,onHostRebindDaemonIdChange:p,settingMeshHost:u,onSetMeshHost:m}){const{t:f}=ke("common");if(o)return s.jsxs(bt,{title:f("repoMesh.host.title"),description:f("repoMesh.host.descriptionSet"),children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[s.jsxs("span",{className:`inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-[13px] text-text-primary ${c?"border-accent-primary/40 bg-accent-primary/10":"border-amber-500/40 bg-amber-500/10"}`,children:[s.jsx("span",{className:"text-text-muted",children:f("repoMesh.host.hostLabel")}),s.jsx("span",{className:"font-medium",children:i||f("repoMesh.host.unknown")}),s.jsxs("span",{className:c?"text-text-muted":"text-amber-400",children:["· ",f(c?"repoMesh.host.online":"repoMesh.host.offline")]})]}),(r==null?void 0:r.workspace)&&s.jsxs("span",{className:"text-[12px] text-text-muted",children:[f("repoMesh.host.hostNode")," ",s.jsx("span",{className:"font-mono text-text-secondary",children:r.workspace})]})]}),!c&&s.jsxs("div",{className:"mt-4",children:[s.jsxs(Mt,{variant:"warning",className:"mb-3",children:[s.jsx("strong",{children:f("repoMesh.host.hostOffline")})," ",f("repoMesh.host.hostOfflineText")]}),e.length>0?s.jsx(Tt,{label:f("repoMesh.host.reconnectToCommand"),hint:f("repoMesh.host.reconnectToCommandHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:d,onChange:h=>p(h.target.value),children:[s.jsx("option",{value:"",children:f("repoMesh.host.waitForHost")}),e.map(h=>s.jsx("option",{value:h.id,children:kr(h)},h.id))]})}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:f("repoMesh.host.noDaemonsToRoute")})]})]});const g=e.find(h=>h.id===t),k=m&&t?s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>m(t),disabled:!!u,children:f(u?"repoMesh.host.settingHost":"repoMesh.host.setHostAction")}):null;return s.jsxs(bt,{title:f("repoMesh.host.title"),description:f("repoMesh.host.descriptionUnset"),children:[s.jsxs(Mt,{variant:"info",className:"mb-4",children:[s.jsx("strong",{children:f("repoMesh.host.setHostBanner")})," ",f("repoMesh.host.setHostBannerText")]}),e.length>0?s.jsxs(s.Fragment,{children:[t?s.jsx("div",{className:"mb-3 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:a?s.jsxs(s.Fragment,{children:["Will host on ",s.jsx("span",{className:"font-medium text-text-primary",children:kr(g)}),r!=null&&r.workspace?s.jsxs(s.Fragment,{children:[" · setup node ",s.jsx("span",{className:"font-mono text-text-secondary",children:r.workspace})]}):null,". ",f("repoMesh.host.confirmSetsHost")]}):s.jsxs(s.Fragment,{children:["Will host on ",s.jsx("span",{className:"font-medium text-text-primary",children:kr(g)}),". ",f("repoMesh.host.attachNodeThenSetHost")]})}):s.jsx(Tt,{label:f("repoMesh.host.hostDaemon"),hint:f("repoMesh.host.hostDaemonHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:"",onChange:h=>n(h.target.value),children:[s.jsx("option",{value:"",children:f("repoMesh.host.resolvingHost")}),e.map(h=>s.jsx("option",{value:h.id,children:kr(h)},h.id))]})}),k&&s.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[k,s.jsx("span",{className:"text-[12px] text-text-muted",children:f("repoMesh.host.setHostActionHint")})]})]}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:f("repoMesh.host.noDaemonsToHost")})]})}function E2({meshId:e,availableCliAgents:t}){const{t:n}=ke(),a=t.find(o=>{const i=o.id.toLowerCase();return i==="hermes-cli"||i.includes("hermes")||o.name.toLowerCase().includes("hermes")}),r=Eh(a==null?void 0:a.meshCoordinator,{meshId:e});return r?s.jsx(bt,{title:n("repoMesh.hermesMcp.title"),description:n("repoMesh.hermesMcp.description"),children:s.jsx(rf,{setup:r,providerName:(a==null?void 0:a.name)||n("repoMesh.hermesMcp.fallbackProvider")})}):null}const Ri=[{value:"preserve",label:"Preserve history and runtimes",description:"Keep completed chat history and leave live runtimes alone."},{value:"stop",label:"Stop live runtimes only",description:"Release running session processes, but keep chat records/transcripts."},{value:"delete_stopped",label:"Delete stopped sessions only",description:"Clean completed/stopped chat clutter without killing live runtimes."},{value:"stop_and_delete",label:"Stop and delete sessions",description:"Stop matching runtimes, then remove their session records/transcripts."}],_2=[{value:"smart",labelKey:"repoMesh.detail.distributionSmart",descriptionKey:"repoMesh.detail.distributionSmartDescription"},{value:"in_order",labelKey:"repoMesh.detail.distributionInOrder",descriptionKey:"repoMesh.detail.distributionInOrderDescription"}];function H2(e){return e==="smart"?"fitness":"first_eligible"}function $2(e,t){const n=e||"first_eligible";return n==="fitness"||n==="least_loaded"||n==="round_robin"||n==="priority_only"&&t!=null&&t.priorityConfigured?"smart":"in_order"}const F2={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,allowAutoPublishSubmoduleMainCommits:!1,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,schedulingStrategy:"first_eligible",sessionCleanupOnNodeRemove:"preserve"};function jl(e){return{...F2,...(e==null?void 0:e.policy)||{}}}function B2(e){return{routeId:`mesh-settings:${e.meshId}`,daemonId:e.daemonId,agentName:e.meshName,agentType:"mesh",status:"idle",title:e.meshName,messages:[],workspaceName:e.meshName,displayPrimary:e.meshName,displaySecondary:"Mesh observability",streamSource:"native",tabKey:`mesh-settings:${e.meshId}`,coordinator:{meshId:e.meshId,role:"coordinator"},settings:{meshCoordinatorFor:e.meshId}}}function W2({selectedMesh:e,error:t,onDismissError:n,onBack:a,onDelete:r,displayedMeshStatus:o,graphLoading:i,graphError:c,onRefreshGraph:d,savingPolicy:p,onUpdatePolicy:u,coordinatorPromptDraft:m,onCoordinatorPromptDraftChange:f,savingCoordinatorPrompt:g,onSaveCoordinatorPrompt:k,daemons:h,coordinatorDaemonId:x,onCoordinatorDaemonIdChange:S,coordinatorCliType:b,isHostNodeAttached:w,selectedHostNode:C,hostPinned:v,hostLabel:y,hostOnline:j,hostRebindDaemonId:N,onHostRebindDaemonIdChange:A,settingMeshHost:T,onSetMeshHost:L,activeDaemon:D,activeDaemonId:M,meshQueue:_,userName:P,availableCliProviders:B,savingNodeSlotsId:R,onUpdateNodeSlots:O,savingNodeCapabilitiesId:H,onUpdateNodeCapabilities:$,nodeSystemPromptDrafts:I,onNodeSystemPromptDraftChange:W,savingNodeSystemPromptId:F,onSaveNodeSystemPrompt:z,selectedNodeId:Q,onSelectNode:ne,showAddNode:oe,onShowAddNode:Ce,onCancelAddNode:le,nodeWorkspace:U,onNodeWorkspaceChange:J,nodeProviderPriority:ee,onNodeProviderPriorityChange:Y,nodeDaemonId:ve,onNodeDaemonIdChange:pe,nodeCustomPath:te,onNodeCustomPathChange:me,nodePickerWorkspaces:V,nodePickerProviders:q,nodeOnboardingPlan:se,nodePlanLoading:de,attachableDaemons:K,onAddNode:fe,onRemoveNode:ie,availableCliAgents:ue,features:ye,sendCommand:Ie}){const{t:E}=ke("common"),Z=jl(e),we=e.nodes||[],ge=l.useMemo(()=>OL(we,h),[we,h]),be=we.some(st=>{var Le;const X=Number((Le=st.policy)==null?void 0:Le.schedulingPriority);return Number.isFinite(X)&&X!==0}),Pe=!Z.schedulingStrategy,Me=l.useMemo(()=>we.some(st=>{var X;return Array.isArray((X=st.policy)==null?void 0:X.slots)&&st.policy.slots.length>0}),[we]),We=Pe&&(Me||we.length>=2)?"smart":null,[Be,Xe]=l.useState(!1),at=!!M&&!!e.id;return s.jsxs(Qa,{icon:s.jsx(cs,{}),title:e.name,subtitle:e.repoIdentity||e.repo_identity||"Repo Mesh",widthClassName:"max-w-5xl",actions:s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:a,children:E("repoMesh.detail.back")}),s.jsxs("button",{className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:()=>d(!0),disabled:i,children:[s.jsx(LL,{size:13}),E(i?"repoMesh.detail.probing":"repoMesh.detail.refresh")]}),s.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>r(e.id),children:E("repoMesh.detail.delete")})]}),children:[t&&s.jsx(Mt,{variant:"error",onDismiss:n,className:"mb-4",children:t}),(()=>{var rt;const st=s.jsxs(s.Fragment,{children:[ye.meshHostDaemonSection&&s.jsx(R2,{daemons:h,coordinatorDaemonId:x,onCoordinatorDaemonIdChange:S,isHostNodeAttached:w,selectedHostNode:C,hostPinned:v,hostLabel:y,hostOnline:j,hostRebindDaemonId:N,onHostRebindDaemonIdChange:G=>{A(G),d()},settingMeshHost:T,onSetMeshHost:L}),s.jsxs(bt,{title:E("repoMesh.detail.observabilityTitle"),description:E("repoMesh.detail.observabilityDescription"),children:[c&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2",children:c}),s.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[s.jsxs("button",{type:"button",className:"btn btn-primary btn-sm inline-flex items-center gap-1.5",onClick:()=>Xe(!0),disabled:!at,title:E(at?"repoMesh.detail.observabilityOpenTitle":"repoMesh.detail.observabilityDisabledTitle"),children:[s.jsx(cs,{size:14}),E("repoMesh.detail.observabilityOpen")]}),s.jsx("span",{className:"text-[12px] text-text-muted",children:E("repoMesh.detail.observabilityHint")})]})]}),s.jsx(i2,{nodes:we,meshQueue:_,activeDaemon:D,daemons:h,selectedMeshId:e.id,userName:P,features:{addNodeDaemonPicker:ye.addNodeDaemonPicker,nodeInstruction:ye.nodeInstruction},coordinatorDaemonId:x,availableCliProviders:B,savingNodeSlotsId:R,onUpdateNodeSlots:O,savingNodeCapabilitiesId:H,onUpdateNodeCapabilities:$,nodeSystemPromptDrafts:I,onNodeSystemPromptDraftChange:W,savingNodeSystemPromptId:F,onSaveNodeSystemPrompt:z,selectedNodeId:Q,onSelectNode:ne,showAddNode:oe,onShowAddNode:Ce,onCancelAddNode:le,nodeWorkspace:U,onNodeWorkspaceChange:J,nodeProviderPriority:ee,onNodeProviderPriorityChange:Y,nodeDaemonId:ve,onNodeDaemonIdChange:pe,nodeCustomPath:te,onNodeCustomPathChange:me,nodePickerWorkspaces:V,nodePickerProviders:q,nodeOnboardingPlan:se,nodePlanLoading:de,attachableDaemons:K,onAddNode:fe,onRemoveNode:ie})]}),X=s.jsxs(s.Fragment,{children:[s.jsxs(bt,{title:E("repoMesh.detail.schedulingTitle"),description:E("repoMesh.detail.schedulingDescription"),children:[s.jsxs("fieldset",{className:"border-none p-0 m-0",children:[s.jsx("legend",{className:"text-[13px] font-medium text-text-secondary mb-2",children:E("repoMesh.detail.distribution")}),s.jsx("div",{className:"flex flex-col gap-2",children:_2.map(G=>{const ce=$2(Z.schedulingStrategy,{priorityConfigured:be})===G.value;return s.jsxs("label",{className:`flex items-start gap-3 rounded-lg border px-3 py-2.5 cursor-pointer transition-colors ${ce?"border-accent-primary/60 bg-accent-primary/10":"border-border-subtle bg-bg-secondary/60 hover:border-border-default"}`,children:[s.jsx("input",{type:"radio",name:"mesh-distribution",className:"mt-0.5 accent-[var(--accent-primary)]",value:G.value,checked:ce,disabled:p,onChange:()=>u({schedulingStrategy:H2(G.value)})}),s.jsxs("span",{className:"min-w-0",children:[s.jsxs("span",{className:"flex items-center gap-2 text-sm text-text-primary",children:[E(G.labelKey),We===G.value&&s.jsx("span",{className:"rounded-full border border-accent-primary/40 bg-accent-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-accent-primary",children:E("repoMesh.detail.recommended")})]}),s.jsx("span",{className:"block text-[12px] text-text-muted",children:E(G.descriptionKey)})]})]},G.value)})})]}),p&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:E("repoMesh.detail.saving")})]}),s.jsx(bt,{title:E("repoMesh.detail.visibilityTitle"),description:E("repoMesh.detail.visibilityDescription"),children:s.jsx(Tt,{label:E("repoMesh.detail.visibilityLabel"),hint:E("repoMesh.detail.visibilityHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:Z.spawnedSessionVisibility==="visible"?"visible":"hidden",onChange:G=>u({spawnedSessionVisibility:G.target.value==="visible"?"visible":"hidden"}),disabled:p,children:[s.jsx("option",{value:"hidden",children:E("repoMesh.detail.visibilityHidden")}),s.jsx("option",{value:"visible",children:E("repoMesh.detail.visibilityVisible")})]})})}),o&&s.jsx(bt,{title:E("repoMesh.detail.magiTitle"),description:E("repoMesh.detail.magiDescription"),children:s.jsx(m2,{status:o,daemonId:M,sendDaemonCommand:Ie,availableProviders:B})}),s.jsx(bt,{children:s.jsx(b2,{quotaRouting:Z.quotaRouting??null,saving:p,error:t,onSave:G=>u({quotaRouting:G})})}),s.jsx(I2,{hostDaemonId:x,hostOnline:j,hostWorkspace:(C==null?void 0:C.workspace)||"",meshProviders:ge.providers,unreportedNodeCount:ge.unreportedNodeCount,machineAutoApproveEnabled:Z.delegatedWorkerAutoApprove!==!1,machineDangerousAllowed:Z.delegatedWorkerDangerousModeAllow===!0,onUpdatePolicy:u,savingPolicy:p,sendCommand:Ie})]}),Le=s.jsx(s.Fragment,{children:ye.coordinatorPrompt&&s.jsx(bt,{title:E("repoMesh.detail.coordinatorPromptTitle"),collapsible:!0,defaultOpen:!1,badge:s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:E("repoMesh.detail.advanced")}),description:E("repoMesh.detail.coordinatorPromptDescription"),children:s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 p-3",children:[s.jsx("div",{className:"text-[13px] font-semibold mb-1",children:E("repoMesh.detail.thisMesh")}),s.jsx("p",{className:"text-[12px] text-text-muted mb-3",children:E("repoMesh.detail.thisMeshHint",{name:e.name})}),s.jsx(v2,{daemonId:M,meshId:e.id,cliType:b,sendCommand:Ie,defaultOpen:!0}),s.jsxs(Tt,{label:E("repoMesh.detail.overrideLabel"),hint:E("repoMesh.detail.overrideHint"),className:"mt-3",children:[s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:6,value:m.override,onChange:G=>f({...m,override:G.target.value}),disabled:g,placeholder:E("repoMesh.detail.overridePlaceholder")}),s.jsx(y2,{daemonId:M,meshId:e.id,cliType:b,sendCommand:Ie,disabled:g,hasContent:!!m.override.trim(),onApply:G=>f({...m,override:G})})]}),s.jsx(Tt,{label:E("repoMesh.detail.appendLabel"),hint:E("repoMesh.detail.appendHint"),children:s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:4,value:m.append,onChange:G=>f({...m,append:G.target.value}),disabled:g,placeholder:E("repoMesh.detail.appendPlaceholder")})}),s.jsxs("details",{className:"mt-2 text-[12px] text-text-muted",children:[s.jsx("summary",{className:"cursor-pointer select-none",children:E("repoMesh.detail.availablePlaceholders")}),s.jsx("p",{className:"mt-1",children:E("repoMesh.detail.placeholdersIntro")}),s.jsx("div",{className:"mt-2 overflow-x-auto",children:s.jsx("table",{className:"w-full text-left border-collapse",children:s.jsx("tbody",{children:w2.map(G=>s.jsxs("tr",{className:"border-t border-border-subtle/60 align-top",children:[s.jsx("td",{className:"py-1 pr-3 font-mono whitespace-nowrap text-text-secondary",children:`{{${G.token}}}`}),s.jsx("td",{className:"py-1 pr-3",children:G.description}),s.jsx("td",{className:"py-1 font-mono text-text-muted/80",children:G.example})]},G.token))})})})]}),s.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:k,disabled:g,children:E(g?"repoMesh.detail.saving":"repoMesh.detail.saveCoordinatorPrompt")}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>f({override:"",append:""}),disabled:g,title:E("repoMesh.detail.clearTitle"),children:E("repoMesh.detail.clear")})]})]})})}),_e=s.jsxs(s.Fragment,{children:[s.jsx(T2,{status:o,daemonId:M,meshId:e.id,sendCommand:Ie}),s.jsxs(bt,{title:E("repoMesh.detail.safetyTitle"),collapsible:!0,defaultOpen:!1,badge:s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:E("repoMesh.detail.advanced")}),description:E("repoMesh.detail.safetyDescription"),children:[s.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:[{label:E("repoMesh.detail.checkpointBefore"),key:"requirePreTaskCheckpoint",opts:[["no","No"],["yes","Yes"]],val:G=>G?"yes":"no",parse:G=>G==="yes"},{label:E("repoMesh.detail.checkpointAfter"),key:"requirePostTaskCheckpoint",opts:[["yes","Yes"],["no","No"]],val:G=>G?"yes":"no",parse:G=>G==="yes"},{label:E("repoMesh.detail.pushApproval"),key:"requireApprovalForPush",opts:[["required",E("repoMesh.detail.requireApprovalBeforePush")],["not_required",E("repoMesh.detail.doNotRequireApproval")]],val:G=>G?"required":"not_required",parse:G=>G==="required"},{label:E("repoMesh.detail.uncommittedChanges"),key:"dirtyWorkspaceBehavior",opts:[["warn",E("repoMesh.detail.warnAndContinue")],["block",E("repoMesh.detail.blockTask")],["checkpoint_then_continue",E("repoMesh.detail.checkpointThenContinue")]],val:G=>G||"warn",parse:G=>G},{label:E("repoMesh.detail.autoPublishSubmodule"),key:"allowAutoPublishSubmoduleMainCommits",opts:[["disabled",E("repoMesh.detail.requireExplicitApproval")],["enabled",E("repoMesh.detail.allowRefineryPublish")]],val:G=>G?"enabled":"disabled",parse:G=>G==="enabled"}].map(({label:G,key:re,opts:ce,val:xe,parse:Se})=>s.jsx(Tt,{label:G,children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:xe(Z[re]),onChange:Ae=>u({[re]:Se(Ae.target.value)}),disabled:p,children:ce.map(([Ae,Ee])=>s.jsx("option",{value:Ae,children:Ee},Ae))})},re))}),(()=>{const G=Z.autoFastForward&&typeof Z.autoFastForward=="object"?Z.autoFastForward:{},re=G.enabled!==!1,ce=G.remoteNodes===!0,xe=G.mode==="continuous"?"continuous":"idle",Se=Ae=>u({autoFastForward:{...G,...Ae}});return s.jsxs("div",{className:"mt-4 grid gap-4 sm:grid-cols-2",children:[s.jsx(Tt,{label:E("repoMesh.detail.autoFastForward"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:re?"enabled":"disabled",onChange:Ae=>Se({enabled:Ae.target.value==="enabled"}),disabled:p,children:[s.jsx("option",{value:"enabled",children:E("repoMesh.detail.ffEnabled")}),s.jsx("option",{value:"disabled",children:E("repoMesh.detail.ffDisabled")})]})}),s.jsx(Tt,{label:E("repoMesh.detail.includeRemoteNodes"),hint:E("repoMesh.detail.includeRemoteNodesHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:ce?"yes":"no",onChange:Ae=>Se({remoteNodes:Ae.target.value==="yes"}),disabled:p||!re,children:[s.jsx("option",{value:"no",children:E("repoMesh.detail.remoteNo")}),s.jsx("option",{value:"yes",children:E("repoMesh.detail.remoteYes")})]})}),s.jsx(Tt,{label:E("repoMesh.detail.detectionMode"),hint:E("repoMesh.detail.detectionModeHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:xe,onChange:Ae=>Se({mode:Ae.target.value==="continuous"?"continuous":"idle"}),disabled:p||!re||!ce,children:[s.jsx("option",{value:"idle",children:E("repoMesh.detail.idleEdgeOnly")}),s.jsx("option",{value:"continuous",children:E("repoMesh.detail.continuousScan")})]})})]})})(),s.jsxs("div",{className:"mt-4 rounded-xl border border-amber-500/25 bg-amber-500/10 p-4",children:[s.jsx(Tt,{label:E("repoMesh.detail.sessionCleanupLabel"),hint:E("repoMesh.detail.sessionCleanupHint"),children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:Z.sessionCleanupOnNodeRemove||"preserve",onChange:G=>u({sessionCleanupOnNodeRemove:G.target.value}),disabled:p,children:Ri.map(G=>s.jsx("option",{value:G.value,children:G.label},G.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((rt=Ri.find(G=>G.value===Z.sessionCleanupOnNodeRemove))==null?void 0:rt.description)||Ri[0].description})]}),p&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:E("repoMesh.detail.saving")})]})]}),nt=[{key:"nodes",label:E("repoMesh.detail.tabNodes"),content:st},{key:"scheduling",label:E("repoMesh.detail.tabScheduling"),content:X},{key:"prompts",label:E("repoMesh.detail.tabPrompts"),content:s.jsxs(s.Fragment,{children:[Le,ye.hermesMcpConfig&&s.jsx(E2,{meshId:e.id,availableCliAgents:ue}),ye.meshHostDaemonSection&&s.jsxs(Mt,{variant:"info",className:"mt-4",children:[s.jsx("strong",{children:E("repoMesh.detail.mcpMode")})," ",s.jsxs("code",{className:"bg-bg-secondary px-1 rounded text-xs",children:["adhdev mcp --repo-mesh ",e.id]})," ",E("repoMesh.detail.mcpDescription")]})]})},{key:"advanced",label:E("repoMesh.detail.tabAdvanced"),content:_e}];return s.jsxs(s.Fragment,{children:[s.jsx(f1,{tabs:nt,ariaLabel:E("repoMesh.detail.tabsAriaLabel"),className:"flex flex-col gap-4"}),Be&&at&&s.jsx(Kf,{activeConv:B2({meshId:e.id,daemonId:M,meshName:e.name}),sendDaemonCommand:Ie,onClose:()=>Xe(!1)})]})})()]})}const va=new Map;async function ag(e){var r,o,i,c,d,p,u,m,f,g,k;const{sendCommand:t,unwrapResult:n}=e,a={meshCreated:!1,meshId:"",error:null,warning:null,plan:null};try{const h=e.reusablePlan??n(await t(e.targetDaemonId,"plan_mesh_onboarding",{workspace:e.workspace||void 0,operation:"auto",meshInventory:e.meshInventory}));if(a.plan=h,(h==null?void 0:h.success)===!1)return{...a,error:`${h.code||"onboarding_blocked"}: ${h.error}${h.action?` ${h.action}`:""}`};if(((r=h==null?void 0:h.plan)==null?void 0:r.kind)!=="create_mesh_and_onboard")return{...a,error:((o=h==null?void 0:h.plan)==null?void 0:o.summary)||"A compatible mesh already exists; add this workspace to it instead of creating a duplicate mesh."};const x={name:e.name.trim()};(e.repoRemoteUrl||(d=(c=(i=h==null?void 0:h.discovery)==null?void 0:i.origin)==null?void 0:c.urls)!=null&&d[0])&&(x.repoRemoteUrl=e.repoRemoteUrl||h.discovery.origin.urls[0]),(e.repoIdentity||(p=h==null?void 0:h.discovery)!=null&&p.repoIdentity)&&(x.repoIdentity=e.repoIdentity||h.discovery.repoIdentity),(u=h==null?void 0:h.discovery)!=null&&u.defaultBranch&&(x.defaultBranch=h.discovery.defaultBranch);const S=await t(e.targetDaemonId,"create_mesh",x),b=n(S);if((b==null?void 0:b.success)===!1)return{...a,error:b.error||"Create failed"};const w=typeof((m=b==null?void 0:b.mesh)==null?void 0:m.id)=="string"?b.mesh.id:"",C={...a,meshCreated:!0,meshId:w};if(!w||!e.attachWorkspace||!e.workspace)return C;try{const v=await t(e.targetDaemonId,"add_mesh_node",{meshId:w,daemonId:e.targetDaemonId,machineId:e.machineId,workspace:((f=h==null?void 0:h.discovery)==null?void 0:f.repoRoot)||e.workspace,repoRoot:(g=h==null?void 0:h.discovery)==null?void 0:g.repoRoot,isLocalWorktree:((k=h==null?void 0:h.discovery)==null?void 0:k.isLinkedWorktree)===!0,role:"host",providerPriority:e.providerPriority}),y=n(v);return(y==null?void 0:y.success)===!1?{...C,warning:tp(y.error||"add_mesh_node failed")}:C}catch(v){return{...C,warning:tp((v==null?void 0:v.message)||"add_mesh_node failed")}}}catch(h){return{...a,error:(h==null?void 0:h.message)||"Create failed"}}}function tp(e){return`Mesh created, but attaching the workspace failed: ${e}. Add the workspace from the mesh's node list.`}function sp(e,t){return e===t?!0:e.length!==t.length?!1:JSON.stringify(e)===JSON.stringify(t)}function rg({daemons:e,primaryDaemonId:t,sendCommand:n,unwrapResult:a,normalizeMesh:r,features:o,loadDaemonMetadata:i}){const c=e.map(le=>le.id).filter(Boolean).sort().join(","),[d,p]=l.useState(()=>va.get(c)??[]),[u,m]=l.useState(null),[f,g]=l.useState(()=>!va.has(c)),[k,h]=l.useState(null),[x,S]=l.useState(!1),[b,w]=l.useState(!1),[C,v]=l.useState(null),[y,j]=l.useState(""),[N,A]=l.useState(""),[T,L]=l.useState(""),[D,M]=l.useState(""),[_,P]=l.useState(""),[B,R]=l.useState(null),[O,H]=l.useState(!1),$=o.createDaemonPicker?D:t,I=l.useMemo(()=>e.find(le=>le.id===$),[e,$]),W=(I==null?void 0:I.workspaces)||[],F=l.useMemo(()=>ln((I==null?void 0:I.availableProviders)||[]),[I]);l.useEffect(()=>{!i||!$||!I||!(!I.workspaces||!I.availableProviders)||Promise.resolve(i($,{minFreshMs:3e4})).catch(()=>{})},[i,$,I]),l.useEffect(()=>{if(!x||!$||!_){R(null);return}let le=!1;return H(!0),n($,"plan_mesh_onboarding",{workspace:_,operation:"auto",meshInventory:d}).then(U=>{if(le)return;const J=a(U);R(J),J!=null&&J.success&&(A(ee=>{var Y;return ee||((Y=J.discovery)==null?void 0:Y.repoIdentity)||""}),L(ee=>{var Y,ve,pe,te,me,V;return ee||((pe=(ve=(Y=J.discovery)==null?void 0:Y.origin)==null?void 0:ve.urls)==null?void 0:pe[0])||((V=(me=(te=J.discovery)==null?void 0:te.upstream)==null?void 0:me.urls)==null?void 0:V[0])||""}),j(ee=>{var Y,ve;return ee||`${String(((Y=J.discovery)==null?void 0:Y.repoIdentity)||((ve=J.discovery)==null?void 0:ve.repoRoot)||"").split(/[\\/]/).filter(Boolean).pop()||"repo"}-mesh`}))}).catch(U=>{le||R({success:!1,error:(U==null?void 0:U.message)||"Git discovery failed"})}).finally(()=>{le||H(!1)}),()=>{le=!0}},[x,$,_,d,n,a]);const z=l.useMemo(()=>e.map(le=>le.id).filter(Boolean).sort().join(","),[e]),Q=l.useCallback(async(le=!1)=>{const U=le||va.has(z);g(J=>U?J:!0);try{if(o.createDaemonPicker){const J=await Promise.allSettled(e.map(async ve=>{if(!ve.id)return[];const pe=await n(ve.id,"list_meshes",{}),te=a(pe);if((te==null?void 0:te.success)===!1)throw new Error(te.error||"Failed to load meshes");return(Array.isArray(te==null?void 0:te.meshes)?te.meshes:[]).map(me=>r(me,ve.id)).filter(me=>me.id)})),ee=new Map;for(const ve of J)if(ve.status==="fulfilled")for(const pe of ve.value)ee.has(pe.id)||ee.set(pe.id,pe);const Y=Array.from(ee.values());p(ve=>sp(ve,Y)?ve:Y),va.set(z,Y),h(null)}else{if(!t)return;const J=await n(t,"list_meshes");if(J!=null&&J.success){const ee=(J.meshes||[]).map(Y=>r(Y,t));p(Y=>sp(Y,ee)?Y:ee),va.set(z,ee),h(null)}else h((J==null?void 0:J.error)||"Failed to load meshes")}}catch(J){h((J==null?void 0:J.message)||"Failed to load meshes")}finally{g(!1)}},[z,t,n,a,r,o.createDaemonPicker]);async function ne(){const le=o.createDaemonPicker?D:t;if(!le||!y.trim())return;const U=T.trim(),J=N.trim(),ee=_.trim();if(!(!ee&&!U&&!J)&&!b){w(!0),v(null);try{const Y=await ag({targetDaemonId:le,name:y,repoRemoteUrl:U,repoIdentity:J,workspace:ee,attachWorkspace:!!ee,machineId:I==null?void 0:I.machineId,providerPriority:Pn(F),meshInventory:d,sendCommand:n,unwrapResult:a,reusablePlan:!O&&B?B:void 0});if(Y.plan!==null&&R(Y.plan),Y.warning&&v(Y.warning),!Y.meshCreated){h(Y.error||"Create failed");return}S(!1),j(""),A(""),L(""),P(""),await Q(),Y.meshId&&m(Y.meshId)}finally{w(!1)}}}async function oe(le){var J;if(!confirm("Delete this mesh? This cannot be undone."))return;const U=((J=d.find(ee=>ee.id===le))==null?void 0:J.__sourceDaemonId)||t;try{const ee=await n(U,"delete_mesh",{meshId:le}),Y=a(ee);if((Y==null?void 0:Y.success)===!1)throw new Error(Y.error||"Failed to delete");u===le&&m(null),await Q()}catch(ee){h((ee==null?void 0:ee.message)||"Delete failed")}}function Ce(){S(!1),j(""),A(""),L(""),P(""),R(null),v(null)}return{meshes:d,setMeshes:p,selectedMeshId:u,setSelectedMeshId:m,loading:f,error:k,setError:h,showCreate:x,setShowCreate:S,creating:b,createWarning:C,setCreateWarning:v,createName:y,setCreateName:j,createRepoIdentity:N,setCreateRepoIdentity:A,createRepoRemoteUrl:T,setCreateRepoRemoteUrl:L,newMeshDaemonId:D,setNewMeshDaemonId:M,newMeshWorkspace:_,setNewMeshWorkspace:P,createPickerWorkspaces:W,createPickerProviders:F,createOnboardingPlan:B,createPlanLoading:O,loadMeshes:Q,handleCreate:ne,handleDelete:oe,cancelCreate:Ce}}function O2({selectedMesh:e,selectedMeshId:t,primaryDaemonId:n,activeDaemonId:a,daemons:r,sendCommand:o,unwrapResult:i,loadLiveMesh:c,resolveCommandTarget:d,launchCoordinator:p,features:u,loadMeshes:m,loadQueue:f,queueSection:g,setError:k}){const[h,x]=l.useState(null),[S,b]=l.useState(!1),[w,C]=l.useState(""),[v,y]=l.useState([]),[j,N]=l.useState(""),[A,T]=l.useState(!1),[L,D]=l.useState(null),[M,_]=l.useState(!1),[P,B]=l.useState(""),[R,O]=l.useState(!1),[H,$]=l.useState(!1),[I,W]=l.useState(null),[F,z]=l.useState(!1),[Q,ne]=l.useState({override:"",append:""}),[oe,Ce]=l.useState(!1),[le,U]=l.useState({}),[J,ee]=l.useState(null),Y=l.useMemo(()=>r.find(Z=>Z.id===j),[r,j]),ve=(Y==null?void 0:Y.workspaces)||[],pe=l.useMemo(()=>ln((Y==null?void 0:Y.availableProviders)||[]),[Y]);l.useEffect(()=>{if(!S||!t||!w.trim()){D(null);return}const Z=u.addNodeDaemonPicker?j:(e==null?void 0:e.__sourceDaemonId)||n;if(!Z)return;let we=!1;return _(!0),o(Z,"plan_mesh_onboarding",{workspace:w.trim(),meshId:t,inlineMesh:e,operation:"add_existing"}).then(ge=>{we||D(i(ge))}).catch(ge=>{we||D({success:!1,error:(ge==null?void 0:ge.message)||"Git discovery failed"})}).finally(()=>{we||_(!1)}),()=>{we=!0}},[S,t,e,w,j,n,u.addNodeDaemonPicker,o,i]);async function te(){var ge,be,Pe;const Z=(e==null?void 0:e.__sourceDaemonId)||n;if(!t||!Z)return;const we=w.trim();if(we)try{const Me=u.addNodeDaemonPicker?j:Z,We=await o(Me,"plan_mesh_onboarding",{workspace:we,meshId:t,inlineMesh:e,operation:"add_existing"}),Be=i(We);if(D(Be),(Be==null?void 0:Be.success)===!1)throw new Error(`${Be.code||"onboarding_blocked"}: ${Be.error}${Be.action?` ${Be.action}`:""}`);const Xe={meshId:t,workspace:((ge=Be==null?void 0:Be.discovery)==null?void 0:ge.repoRoot)||we,repoRoot:(be=Be==null?void 0:Be.discovery)==null?void 0:be.repoRoot,isLocalWorktree:((Pe=Be==null?void 0:Be.discovery)==null?void 0:Pe.isLinkedWorktree)===!0};u.addNodeDaemonPicker&&j&&(Xe.daemonId=j,Xe.machineId=Y==null?void 0:Y.machineId),Xe.providerPriority=Va(v);const at=await o(Z,"add_mesh_node",Xe),st=i(at);if((st==null?void 0:st.success)===!1)throw new Error(st.error||"Add node failed");b(!1),C(""),y([]),N(""),T(!1),await m(),g||await f(t)}catch(Me){k((Me==null?void 0:Me.message)||"Add node failed")}}async function me(Z){var Pe;if(!e)return;const we=jl(e),ge=((Pe=[{value:"preserve",label:"Preserve history and runtimes"},{value:"stop",label:"Stop live runtimes only"},{value:"delete_stopped",label:"Delete stopped sessions only"},{value:"stop_and_delete",label:"Stop and delete sessions"}].find(Me=>Me.value===we.sessionCleanupOnNodeRemove))==null?void 0:Pe.label)||"Preserve history and runtimes";if(!confirm(`Remove this node?
120
120
 
121
121
  Node removal cleanup policy: ${ge}`))return;const be=e.__sourceDaemonId||n;try{const Me=await o(be,"remove_mesh_node",{meshId:e.id,nodeId:Z}),We=i(Me);if((We==null?void 0:We.success)===!1)throw new Error(We.error||"Remove failed");h===Z&&x(null),await m(),g||await f(t)}catch(Me){k((Me==null?void 0:Me.message)||"Remove node failed")}}async function V(Z){if(!e)return;const we={...jl(e),...Z},ge=e.__sourceDaemonId||n;try{z(!0),k(null);const be=await o(ge,"update_mesh",{meshId:e.id,policy:we}),Pe=i(be);if((Pe==null?void 0:Pe.success)===!1)throw new Error(Pe.error||"Policy update failed");await m()}catch(be){k((be==null?void 0:be.message)||"Policy update failed")}finally{z(!1)}}const[q,se]=l.useState(null);async function de(Z,we){if(!t)return;const ge=(e==null?void 0:e.__sourceDaemonId)||n;try{se(Z.id),k(null);const be=await o(ge,"update_mesh_node",{meshId:t,nodeId:Z.id,policy:{slots:we}}),Pe=i(be);if((Pe==null?void 0:Pe.success)===!1){k(Pe.error||"Node slots update failed");return}await m()}catch(be){k((be==null?void 0:be.message)||"Node slots update failed")}finally{se(null)}}const[K,fe]=l.useState(null);async function ie(Z,we){if(!t)return;const ge=(e==null?void 0:e.__sourceDaemonId)||n,be=we.map(Pe=>Pe.trim()).filter(Boolean);try{fe(Z.id),k(null);const Pe=await o(ge,"update_mesh_node",{meshId:t,nodeId:Z.id,capabilities:be}),Me=i(Pe);if((Me==null?void 0:Me.success)===!1){k(Me.error||"Node tag update failed");return}await m()}catch(Pe){k((Pe==null?void 0:Pe.message)||"Node tag update failed")}finally{fe(null)}}async function ue(){if(!n||!t)return;const we={...(e==null?void 0:e.coordinator)||{}};Q.override.trim()?we.systemPromptOverride=Q.override:delete we.systemPromptOverride,Q.append.trim()?we.systemPromptAppend=Q.append:delete we.systemPromptAppend,delete we.systemPromptSuffix;try{Ce(!0),k(null);const ge=await o(n,"update_mesh",{meshId:t,coordinator:we}),be=i(ge);if((be==null?void 0:be.success)===!1){k(be.error||"Coordinator prompt save failed");return}await m()}catch(ge){k((ge==null?void 0:ge.message)||"Coordinator prompt save failed")}finally{Ce(!1)}}async function ye(Z){if(!n||!t)return;const we=(le[Z.id]||"").trim();try{ee(Z.id),k(null);const ge=await o(n,"update_mesh_node",{meshId:t,nodeId:Z.id,systemPrompt:we}),be=i(ge);if((be==null?void 0:be.success)===!1){k(be.error||"Node instruction save failed");return}await m()}catch(ge){k((ge==null?void 0:ge.message)||"Node instruction save failed")}finally{ee(null)}}async function Ie(Z){if(!(!e||!Z)){k(null),W(null);try{$(!0);const we=(e.nodes||[]).find(Pe=>Zs(String(Pe.daemon_id||Pe.daemonId||""),Z)),ge=await o(Z,"set_mesh_host",{meshId:e.id,hostDaemonId:Z,...we!=null&&we.id?{hostNodeId:we.id}:{}}),be=i(ge);if((be==null?void 0:be.success)===!1){k(be.error||"Setting the mesh host failed");return}await m()}catch(we){k((we==null?void 0:we.message)||"Setting the mesh host failed")}finally{$(!1)}}}async function E(){if(e){k(null),W(null);try{O(!0);const Z=c?await c(a,e.id,e):null,we=d(a,e.id,e,e.nodes||[],Z);if("error"in we)throw new Error(we.error);const ge=await p(we.targetDaemonId,{meshId:e.id,inlineMesh:we.inlineMesh,coordinatorNodeId:we.coordinatorNodeId,cliType:P.trim()||void 0});W(ge.message)}catch(Z){k((Z==null?void 0:Z.message)||"Coordinator launch failed")}finally{O(!1)}}}return{selectedNodeId:h,setSelectedNodeId:x,showAddNode:S,setShowAddNode:b,nodeWorkspace:w,setNodeWorkspace:C,nodeProviderPriority:v,setNodeProviderPriority:y,nodeDaemonId:j,setNodeDaemonId:N,nodeCustomPath:A,setNodeCustomPath:T,nodePickerWorkspaces:ve,nodePickerProviders:pe,nodeOnboardingPlan:L,nodePlanLoading:M,coordinatorCliType:P,setCoordinatorCliType:B,launchingCoordinator:R,launchResult:I,settingMeshHost:H,savingPolicy:F,coordinatorPromptDraft:Q,setCoordinatorPromptDraft:ne,savingCoordinatorPrompt:oe,nodeSystemPromptDrafts:le,setNodeSystemPromptDrafts:U,savingNodeSystemPromptId:J,savingNodeSlotsId:q,savingNodeCapabilitiesId:K,handleAddNode:te,handleRemoveNode:me,handleUpdatePolicy:V,handleUpdateNodeSlots:de,handleUpdateNodeCapabilities:ie,handleSaveCoordinatorPrompt:ue,handleSaveNodeSystemPrompt:ye,handleLaunchCoordinator:E,handleSetMeshHost:Ie}}function U2(e){const t=e.filter(a=>a.status==="pending"||a.status==="assigned"),n=e.filter(a=>a.status==="completed"||a.status==="failed"||a.status==="cancelled");return{active:t.length,historical:n.length,activeCounts:{pending:t.filter(a=>a.status==="pending").length,assigned:t.filter(a=>a.status==="assigned").length},historicalCounts:{completed:n.filter(a=>a.status==="completed").length,failed:n.filter(a=>a.status==="failed").length},counts:{pending:e.filter(a=>a.status==="pending").length,assigned:e.filter(a=>a.status==="assigned").length,completed:e.filter(a=>a.status==="completed").length,failed:e.filter(a=>a.status==="failed").length},staleAssignedCount:e.filter(a=>a.staleAssigned).length,recent:e.slice(0,20)}}function G2({primaryDaemonId:e,activeDaemonId:t,sendCommand:n,unwrapResult:a,loadLiveMesh:r,resolveCommandTarget:o}){const[i,c]=l.useState([]),[d,p]=l.useState(null),[u,m]=l.useState(!1),[f,g]=l.useState(null),k=l.useCallback(async x=>{if(!e||!x){c([]);return}try{const S=await n(e,"get_mesh_queue",{meshId:x});c(S!=null&&S.success?Array.isArray(S.queue)?S.queue:[]:[])}catch{c([])}},[e,n]);async function h(x){var S,b;if(x){m(!0),g(null);try{const w=r?await r(t,x.id,x):null,C=o(t,x.id,x,x.nodes||[],w);if("error"in C)throw new Error(C.error);const v=await n(C.targetDaemonId,"get_mesh_queue",{meshId:x.id}),y=a(v);if((y==null?void 0:y.success)===!1)throw new Error(y.error||"Queue load failed");const j=Array.isArray(((S=y==null?void 0:y.result)==null?void 0:S.rows)??(y==null?void 0:y.rows)??(y==null?void 0:y.queue))?((b=y==null?void 0:y.result)==null?void 0:b.rows)??(y==null?void 0:y.rows)??(y==null?void 0:y.queue):[];p(U2(j))}catch(w){g((w==null?void 0:w.message)||"Queue load failed")}finally{m(!1)}}}return{meshQueue:i,setMeshQueue:c,queueSummary:d,queueLoading:u,queueError:f,loadQueue:k,handleLoadQueue:h}}function q2(e){return!e||typeof e!="object"?!1:e._bootstrapFallback===!0}const og=new Map;function ig(e){return e?og.get(e)??null:null}function z2(e,t){!e||!t||og.set(e,t)}function K2({selectedMeshId:e,loadMeshStatus:t,extractStatus:n,normalizeNode:a,gateIncompleteGraph:r}){const[o,i]=l.useState(()=>ig(e)),[c,d]=l.useState(!1),[p,u]=l.useState(null),[m,f]=l.useState("idle"),[g,k]=l.useState(!1),h=l.useRef(!1);async function x(S,b=e,w=!1){if(!(!S||!b))try{d(!w&&o===null),f(w?"settling":"first_paint"),u(null);const C=await t(S,b,{refresh:w,retryProfile:w?"settled":"interactive"});k(q2(C));const v=n(C),y=a&&v?{...v,nodes:(v.nodes??[]).map(j=>a(j,v.meshId??b,""))}:v;if(y){if(r&&!w&&o!==null&&!hM(Cf(y))){f("settling"),h.current||(h.current=!0,Promise.resolve().then(()=>x(S,b,!0)).finally(()=>{h.current=!1}));return}i(y),z2(b,y),f("settled")}else i(null),u("mesh_status returned an unexpected payload."),f("idle")}catch(C){o||i(null),u((C==null?void 0:C.message)||"Failed to load mesh graph"),f("idle")}finally{d(!1)}}return{meshGraphStatus:o,setMeshGraphStatus:i,graphLoading:c,graphError:p,setGraphError:u,graphProvenance:m,graphBootstrapFallback:g,loadGraph:x}}function np(e){return!e||e.hostSynthesized?{hostDaemonId:"",hostNodeId:""}:{hostDaemonId:String(e.hostDaemonId||""),hostNodeId:String(e.hostNodeId||"")}}function V2(e,t,n,a,r){if(!e.length)return"";const o=String(r||"");if(o){const d=e.find(p=>Zs(p.id,o));return d?d.id:o}const i=t.find(d=>d.role==="host"),c=String((i==null?void 0:i.daemon_id)||(i==null?void 0:i.daemonId)||"");if(c){const d=e.find(p=>Zs(p.id,c));if(d)return d.id}return""}function Y2(e){var r;if(!e)return"null";const t=[...e.nodes??[]].map(o=>{var i,c,d,p,u,m;return[o.nodeId,o.health,((i=o.git)==null?void 0:i.branch)??"",((c=o.git)==null?void 0:c.headCommit)??"",(d=o.git)!=null&&d.dirty?"1":"0",((p=o.git)==null?void 0:p.ahead)??0,((u=o.git)==null?void 0:u.behind)??0,(m=o.git)!=null&&m.hasConflicts?"1":"0",[...o.activeSessions??[]].sort().join(",")].join("|")}).sort().join(";"),n=(r=e.queue)==null?void 0:r.summary,a=n?[n.pending,n.assigned,n.completed,n.failed,n.cancelled].join(","):"";return`${t}::${a}`}const Q2=4,J2=3e4;function X2(){return{lastFingerprint:null,stableTicks:0,backedOff:!1}}function Nl(e){e.stableTicks=0,e.backedOff=!1}function Z2(e,t){const n=Y2(t);return e.lastFingerprint===null?(e.lastFingerprint=n,e.backedOff):n!==e.lastFingerprint?(e.lastFingerprint=n,Nl(e),!1):(e.stableTicks+=1,e.stableTicks>=Q2&&(e.backedOff=!0),e.backedOff)}function eR(e,t){return e.backedOff?Math.max(t,J2):t}const tR=7e3,sR=45e3;function nR(){const e=DL(),{sendCommand:t,sendData:n,daemons:a,userName:r,loadMeshStatus:o,launchCoordinator:i,loadLiveMesh:c,extractStatus:d,unwrapResult:p,normalizeMesh:u,normalizeNode:m,resolveCommandTarget:f,features:g,gateIncompleteGraph:k}=e,h=ca(),x=a[0],S=(x==null?void 0:x.id)||"",b=l.useMemo(()=>((x==null?void 0:x.availableProviders)||[]).filter(lt=>lt.category==="cli").map(lt=>({id:lt.type||lt.id,name:lt.displayName||lt.name||lt.type,meshCoordinator:lt.meshCoordinator})),[x]),w=l.useMemo(()=>ln((x==null?void 0:x.availableProviders)||[]),[x]),{meshes:C,selectedMeshId:v,setSelectedMeshId:y,loading:j,error:N,setError:A,showCreate:T,setShowCreate:L,createName:D,setCreateName:M,createRepoIdentity:_,setCreateRepoIdentity:P,createRepoRemoteUrl:B,setCreateRepoRemoteUrl:R,newMeshDaemonId:O,setNewMeshDaemonId:H,newMeshWorkspace:$,setNewMeshWorkspace:I,createPickerWorkspaces:W,createOnboardingPlan:F,createPlanLoading:z,creating:Q,createWarning:ne,setCreateWarning:oe,loadMeshes:Ce,handleCreate:le,handleDelete:U,cancelCreate:J}=rg({daemons:a,primaryDaemonId:S,sendCommand:t,unwrapResult:p,normalizeMesh:u,features:g,loadDaemonMetadata:h}),ee=C.find(Fe=>Fe.id===v)||null,{meshGraphStatus:Y,setMeshGraphStatus:ve,graphLoading:pe,graphError:te,setGraphError:me,loadGraph:V}=K2({selectedMeshId:v,loadMeshStatus:o,extractStatus:d,normalizeNode:m,gateIncompleteGraph:k}),[q,se]=l.useState(""),[de,K]=l.useState(""),fe=g.meshHostDaemonSection?q:S,{meshQueue:ie,loadQueue:ue}=G2({primaryDaemonId:S,activeDaemonId:fe,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:f}),{selectedNodeId:ye,setSelectedNodeId:Ie,showAddNode:E,setShowAddNode:Z,nodeWorkspace:we,setNodeWorkspace:ge,nodeProviderPriority:be,setNodeProviderPriority:Pe,nodeDaemonId:Me,setNodeDaemonId:We,nodeCustomPath:Be,setNodeCustomPath:Xe,nodePickerWorkspaces:at,nodePickerProviders:st,nodeOnboardingPlan:X,nodePlanLoading:Le,coordinatorCliType:_e,savingPolicy:nt,coordinatorPromptDraft:rt,setCoordinatorPromptDraft:G,savingCoordinatorPrompt:re,nodeSystemPromptDrafts:ce,setNodeSystemPromptDrafts:xe,savingNodeSystemPromptId:Se,savingNodeSlotsId:Ae,savingNodeCapabilitiesId:Ee,handleAddNode:Re,handleRemoveNode:Qe,handleUpdatePolicy:et,handleUpdateNodeSlots:Je,handleUpdateNodeCapabilities:Oe,handleSaveCoordinatorPrompt:Ye,handleSaveNodeSystemPrompt:tt,settingMeshHost:$e,handleSetMeshHost:he}=O2({selectedMesh:ee,selectedMeshId:v,primaryDaemonId:S,activeDaemonId:fe,daemons:a,availableCliProviders:w,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:f,launchCoordinator:i,features:{addNodeDaemonPicker:g.addNodeDaemonPicker},loadMeshes:Ce,loadQueue:ue,queueSection:g.queueSection,setError:A}),je=l.useMemo(()=>a.find(Fe=>Fe.id===fe)||x,[a,fe,x]),Ne=l.useMemo(()=>new Set(((ee==null?void 0:ee.nodes)||[]).map(Fe=>String(Fe.daemon_id||Fe.daemonId||""))),[ee]),He=l.useMemo(()=>a.filter(Fe=>Fe.id&&!Ne.has(Fe.id)&&!Xp(Fe)),[a,Ne]),Ue=(ee==null?void 0:ee.nodes)||[],dt=l.useMemo(()=>Ue.find(Fe=>Zs(String(Fe.daemon_id||Fe.daemonId||""),q)),[Ue,q]),Ke=g.meshHostDaemonSection?!!dt:!0,ut=l.useMemo(()=>{if(!g.meshHostDaemonSection||!ee)return{pinned:!1,daemonId:"",label:"",online:!1,hostNode:void 0};const Fe=ee.meshHost,lt=Y!=null&&Y.meshId&&String(Y.meshId)===String(ee.id??"")?Y.meshHost:void 0,es=lt!=null&&lt.hostDaemonId?lt:Fe??lt,ns=np(es),js=ns.hostDaemonId,Ys=Ue.find(Fs=>Fs.role==="host"),cn=ns.hostNodeId||String((Ys==null?void 0:Ys.id)||""),ae=cn?Ue.find(Fs=>String(Fs.id)===cn):void 0,ze=String((ae==null?void 0:ae.daemon_id)||(ae==null?void 0:ae.daemonId)||""),Ge=js||ze;if(!Ge)return{pinned:!1,daemonId:"",label:"",online:!1,hostNode:void 0};const Nt=a.find(Fs=>js&&Zs(Fs.id,js))||(ze?a.find(Fs=>Zs(Fs.id,ze)):void 0);if(Nt)return{pinned:!0,daemonId:Nt.id,label:aR(Nt),online:!0,hostNode:ae};const dn=String((ae==null?void 0:ae.machineLabel)||"")||String((ae==null?void 0:ae.workspace)||"")||Ge;return{pinned:!0,daemonId:Ge,label:dn,online:!1,hostNode:ae}},[ee,Ue,a,Y,g.meshHostDaemonSection]),zt=ut.daemonId,Et=ut.online,ps=ut.pinned?ut.hostNode:dt,Zt=l.useMemo(()=>!g.meshHostDaemonSection||!ut.pinned?"":!Et&&de&&a.some(Fe=>Fe.id===de)?de:zt,[g.meshHostDaemonSection,ut.pinned,Et,de,a,zt]),_s=l.useMemo(()=>Y?[...new Set((Y.nodes??[]).map(Fe=>String(Fe.daemonId||Fe.daemon_id||"")).filter(Boolean))]:[],[Y]),De=zf({status:Y,daemonId:fe||null,extraDaemonIds:_s,meshId:v,sendData:n});l.useEffect(()=>{const Fe=(ee==null?void 0:ee.coordinator)||{};G({override:typeof Fe.systemPromptOverride=="string"?Fe.systemPromptOverride:"",append:typeof Fe.systemPromptAppend=="string"?Fe.systemPromptAppend:typeof Fe.systemPromptSuffix=="string"?Fe.systemPromptSuffix:""}),xe(Object.fromEntries(((ee==null?void 0:ee.nodes)||[]).map(lt=>[lt.id,typeof lt.systemPrompt=="string"?lt.systemPrompt:""])))},[ee]),l.useEffect(()=>{const Fe=g.addNodeDaemonPicker?Pn(st):Pn(w);E&&be.length===0&&Fe.length>0&&Pe(Fe)},[E,w,st,be.length,g.addNodeDaemonPicker]),l.useEffect(()=>{const Fe=new Set(((ee==null?void 0:ee.nodes)||[]).map(lt=>lt.id));ye&&!Fe.has(ye)&&Ie(null)},[ee,ye]);const Ze=l.useMemo(()=>{if(!(!(Y!=null&&Y.meshId)||String(Y.meshId)!==String((ee==null?void 0:ee.id)??"")))return np(Y.meshHost).hostDaemonId||void 0},[Y,ee]),It=l.useMemo(()=>V2(a,Ue,fe,S,Ze),[a,Ue,fe,S,Ze]);l.useEffect(()=>{if(!g.meshHostDaemonSection)return;if(!a.length&&!ut.pinned){se("");return}const Fe=ut.pinned?Zt:It;Fe&&!Zs(Fe,q)&&se(Fe)},[a,q,ut.pinned,Zt,It,g.meshHostDaemonSection]),l.useEffect(()=>{de&&(Et||!a.some(Fe=>Fe.id===de))&&K("")},[Et,de,a]),l.useEffect(()=>{if(g.createDaemonPicker){if(!a.length){H("");return}(!O||!a.some(Fe=>Fe.id===O))&&H(a[0].id)}},[a,O,g.createDaemonPicker]),l.useEffect(()=>{var Fe;if(!g.createDaemonPicker||!O){I("");return}if(!W.length){I("");return}W.some(lt=>lt.path===$)||I(((Fe=W[0])==null?void 0:Fe.path)||"")},[O,$,W,g.createDaemonPicker]);const pt=l.useRef(null),Yt=l.useRef(X2()),_t=g.meshStatePushRefresh?sR:tR,[Qt,Cs]=l.useState(_t);l.useEffect(()=>{if(!v)return;const Fe=pt.current!==v;if(pt.current=v,Fe){Nl(Yt.current),Cs(_t);const lt=ig(v);ve(lt),me(null),V(fe,v,lt!==null)}else me(null),V(fe,v,!0)},[v,fe]);const Hs=l.useRef(V);Hs.current=V;const ms=l.useRef(!1),ss=l.useRef(()=>{});ss.current=()=>{ms.current||!v||!fe||(ms.current=!0,Promise.resolve(Hs.current(fe,v,!0)).finally(()=>{ms.current=!1}))},l.useEffect(()=>{Z2(Yt.current,Y),Cs(eR(Yt.current,_t))},[Y,_t]),PL({daemonIds:l.useMemo(()=>[fe,..._s].filter(Boolean),[fe,_s]),meshId:v,sendData:n,onRevisionAdvance:()=>{typeof document<"u"&&document.visibilityState!=="visible"||ss.current()}}),l.useEffect(()=>{if(!v||!fe||typeof document>"u")return;let Fe=null;const lt=()=>{document.visibilityState==="visible"&&ss.current()},es=()=>{Fe===null&&(Fe=setInterval(lt,Qt))},ns=()=>{Fe!==null&&(clearInterval(Fe),Fe=null)},js=()=>{document.visibilityState==="visible"?es():ns()};return document.visibilityState==="visible"&&es(),document.addEventListener("visibilitychange",js),()=>{ns(),document.removeEventListener("visibilitychange",js)}},[v,fe,Qt]),l.useEffect(()=>{g.queueSection||ue(v)},[v,g.queueSection]);const Vs=l.useMemo(()=>a.map(Fe=>Fe.id).filter(Boolean).sort().join(","),[a]),$s=l.useRef(!1);return l.useEffect(()=>{Ce($s.current),$s.current=!0},[Vs]),S?ee?s.jsx(W2,{selectedMesh:ee,error:N,onDismissError:()=>A(null),onBack:()=>{y(null),ve(null)},onDelete:U,displayedMeshStatus:De,graphLoading:pe,graphError:te,onRefreshGraph:()=>{Nl(Yt.current),V(fe,v,!0)},savingPolicy:nt,onUpdatePolicy:et,coordinatorPromptDraft:rt,onCoordinatorPromptDraftChange:G,savingCoordinatorPrompt:re,onSaveCoordinatorPrompt:Ye,daemons:a,coordinatorDaemonId:q,onCoordinatorDaemonIdChange:se,coordinatorCliType:_e,isHostNodeAttached:Ke,selectedHostNode:ps,hostPinned:ut.pinned,hostLabel:ut.label,hostOnline:Et,hostRebindDaemonId:de,onHostRebindDaemonIdChange:Fe=>K(Fe),settingMeshHost:$e,onSetMeshHost:he,activeDaemon:je,activeDaemonId:fe,meshQueue:ie,userName:r,availableCliProviders:w,savingNodeSlotsId:Ae,onUpdateNodeSlots:Je,savingNodeCapabilitiesId:Ee,onUpdateNodeCapabilities:Oe,nodeSystemPromptDrafts:ce,onNodeSystemPromptDraftChange:(Fe,lt)=>xe(es=>({...es,[Fe]:lt})),savingNodeSystemPromptId:Se,onSaveNodeSystemPrompt:tt,selectedNodeId:ye,onSelectNode:Ie,showAddNode:E,onShowAddNode:()=>Z(!0),onCancelAddNode:()=>Z(!1),nodeWorkspace:we,onNodeWorkspaceChange:ge,nodeProviderPriority:be,onNodeProviderPriorityChange:Pe,nodeDaemonId:Me,onNodeDaemonIdChange:We,nodeCustomPath:Be,onNodeCustomPathChange:Xe,nodePickerWorkspaces:at,nodePickerProviders:st,nodeOnboardingPlan:X,nodePlanLoading:Le,attachableDaemons:He,onAddNode:Re,onRemoveNode:Qe,availableCliAgents:b,features:{coordinatorPrompt:g.coordinatorPrompt,meshHostDaemonSection:g.meshHostDaemonSection,hermesMcpConfig:g.hermesMcpConfig,addNodeDaemonPicker:g.addNodeDaemonPicker,nodeInstruction:g.nodeInstruction},sendCommand:t}):s.jsx(FL,{meshes:C,loading:j,error:N,onDismissError:()=>A(null),daemons:a,features:{createDaemonPicker:g.createDaemonPicker,maxMeshes:g.maxMeshes},showCreate:T,onToggleCreate:()=>L(!T),createName:D,onCreateNameChange:M,createRepoIdentity:_,onCreateRepoIdentityChange:P,createRepoRemoteUrl:B,onCreateRepoRemoteUrlChange:R,newMeshDaemonId:O,onNewMeshDaemonIdChange:H,newMeshWorkspace:$,onNewMeshWorkspaceChange:I,createPickerWorkspaces:W,createOnboardingPlan:F,createPlanLoading:z,creating:Q,createWarning:ne,onDismissCreateWarning:()=>oe(null),onSelectMesh:y,onCreate:le,onCancelCreate:J}):s.jsx(Qa,{icon:s.jsx(cs,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",children:s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Waiting for daemon connection..."})})}function aR(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function rR({children:e}){const{sendCommand:t,sendData:n}=St(),{ides:a}=Ss(),r=l.useMemo(()=>a.filter(i=>i.daemonMode||i.type==="adhdev-daemon").map(i=>i),[a]),o=l.useMemo(()=>({sendCommand:t,sendData:n,daemons:r,userName:void 0,loadMeshStatus:async(i,c)=>t(i,"mesh_status",{meshId:c}),launchCoordinator:async(i,c)=>{var f;const d={meshId:c.meshId};c.cliType&&(d.cliType=c.cliType);const p=await t(i,"launch_mesh_coordinator",d),u=(p==null?void 0:p.result)??p;if((u==null?void 0:u.success)===!1)throw new Error(u.error||"Coordinator launch failed");const m=(u==null?void 0:u.sessionId)||((f=u==null?void 0:u.session)==null?void 0:f.id)||(u==null?void 0:u.targetSessionId);return{sessionId:m,message:m?`Coordinator launched (${m})`:"Coordinator launch command sent"}},loadLiveMesh:void 0,extractStatus:Vl,unwrapResult:i=>i,normalizeMesh:(i,c)=>i,normalizeNode:(i,c,d)=>i,resolveCommandTarget:i=>({targetDaemonId:i}),features:Xf}),[t,n,r]);return s.jsx(Zf.Provider,{value:o,children:e})}function oR(e){const{daemons:t,features:n,meshes:a,meshesLoading:r,selectedMeshId:o,onSelectMesh:i,createMode:c,onCreateModeChange:d,createName:p,onCreateNameChange:u,createDaemonId:m,onCreateDaemonIdChange:f,createWorkspace:g,onCreateWorkspaceChange:k,createPickerWorkspaces:h,createPlan:x,createPlanLoading:S,creating:b,createWarning:w,onCreate:C,createRepoRemoteUrl:v,onCreateRepoRemoteUrlChange:y,createRepoIdentity:j,onCreateRepoIdentityChange:N,createManualOpen:A,onCreateManualOpenChange:T,nodes:L,attachableDaemons:D,attachDaemonId:M,onAttachDaemonIdChange:_,attachWorkspace:P,onAttachWorkspaceChange:B,attachPickerWorkspaces:R,attachPlan:O,attachPlanLoading:H,attaching:$,onAttach:I,renderInstallOnboarding:W,nodeLabel:F,daemonLabel:z}=e,{t:Q}=ke("common");if(t.length===0)return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:Q("setupWizard.machines.title")}),s.jsx("p",{className:"mt-1 text-[11px] leading-relaxed text-text-muted",children:Q("setupWizard.machines.noMachinesDescription")})]}),W?W():s.jsx("p",{className:"text-[11px] text-text-muted",children:Q("setupWizard.machines.noMachinesFallback")})]});const ne=$||H||(O==null?void 0:O.success)===!1||!P.trim()||n.addNodeDaemonPicker&&!M;return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:Q("setupWizard.machines.title")}),s.jsx("p",{className:"mt-1 text-[11px] leading-relaxed text-text-muted",children:Q("setupWizard.machines.description")})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[a.map(oe=>{const Ce=!c&&o===oe.id;return s.jsx("button",{type:"button",onClick:()=>{d(!1),i(oe.id)},className:`flex items-center gap-2 rounded-lg border px-3 py-2 text-left transition-colors ${Ce?"border-accent-primary/60 bg-accent-primary/10":"border-border-subtle bg-bg-secondary/60 hover:border-border-default"}`,children:s.jsxs("span",{className:"min-w-0",children:[s.jsx("span",{className:"block truncate text-sm text-text-primary",children:oe.name}),s.jsxs("span",{className:"block truncate text-[11px] text-text-muted",children:[oe.repoIdentity||oe.repoRemoteUrl||""," · ",Q("setupWizard.machines.nodeCount",{count:(oe.nodes||[]).length})]})]})},oe.id)}),s.jsx("button",{type:"button",onClick:()=>d(!0),className:`flex items-center gap-2 rounded-lg border px-3 py-2 text-left transition-colors ${c?"border-accent-primary/60 bg-accent-primary/10":"border-dashed border-border-subtle bg-bg-secondary/40 hover:border-border-default"}`,children:s.jsxs("span",{className:"text-sm text-text-primary",children:["+ ",Q("setupWizard.machines.createNew")]})}),r&&a.length===0&&s.jsx("p",{className:"text-[11px] text-text-muted",children:Q("setupWizard.machines.loadingMeshes")})]}),c&&s.jsx(sg,{variant:"wizard",showDaemonPicker:n.createDaemonPicker,daemons:t,daemonLabel:z,name:p,onNameChange:u,daemonId:m,onDaemonIdChange:f,workspace:g,onWorkspaceChange:k,workspaces:h,plan:x,planLoading:S,repoRemoteUrl:v,onRepoRemoteUrlChange:y,repoIdentity:j,onRepoIdentityChange:N,manualOpen:A,onManualOpenChange:T,creating:b,warning:w,onCreate:C}),!c&&o&&s.jsxs("div",{className:"flex flex-col gap-2.5 rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2.5",children:[L.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5",children:L.map(oe=>s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] text-text-secondary",children:F(oe)},oe.id))}),s.jsx("span",{className:"text-[11px] font-medium text-text-secondary",children:Q("setupWizard.machines.attachTitle")}),n.addNodeDaemonPicker&&(D.length>0?s.jsx("div",{className:"flex flex-wrap gap-1.5",children:D.map(oe=>{const Ce=M===oe.id;return s.jsx("button",{type:"button",onClick:()=>_(oe.id),className:`rounded-full border px-2.5 py-1 text-[11px] transition-colors ${Ce?"border-accent-primary/60 bg-accent-primary/10 text-text-primary":"border-border-subtle bg-bg-secondary text-text-secondary hover:border-border-default"}`,children:z(oe)},oe.id)})}):s.jsx("p",{className:"text-[11px] text-text-muted",children:Q("setupWizard.machines.allMachinesAttached")})),(!n.addNodeDaemonPicker||M)&&s.jsxs(s.Fragment,{children:[s.jsx(yl,{workspaces:R,value:P,onChange:B}),s.jsx(tg,{plan:O,loading:H}),s.jsx("div",{className:"flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:I,disabled:ne,children:Q($?"setupWizard.machines.attaching":"setupWizard.machines.addMachine")})})]})]})]})}function iR(e){var t;return e.machineNickname||e.nickname||e.hostname||((t=e.user)==null?void 0:t.name)||e.id}function lR(e){const t=e;return t.machine_label||t.machineLabel||t.hostname||String(e.workspace||"").split(/[\\/]/).filter(Boolean).pop()||e.id}function cR({daemons:e,features:t,sendCommand:n,unwrapResult:a,normalizeMesh:r,loadDaemonMetadata:o,initialMeshId:i,onClose:c,renderInstallOnboarding:d}){var we,ge;const{t:p}=ke("common"),u=((we=e[0])==null?void 0:we.id)||"",{meshes:m,loading:f,error:g,setError:k,loadMeshes:h,selectedMeshId:x,setSelectedMeshId:S}=rg({daemons:e,primaryDaemonId:u,sendCommand:n,unwrapResult:a,normalizeMesh:r,features:{createDaemonPicker:t.createDaemonPicker,addNodeDaemonPicker:t.addNodeDaemonPicker},loadDaemonMetadata:o});l.useEffect(()=>{h()},[h]);const b=l.useRef(m);b.current=m;const w=l.useMemo(()=>m.map(be=>be.id).sort().join(","),[m]),C=l.useRef(n);C.current=n;const v=l.useRef(a);v.current=a,l.useEffect(()=>{x||m.length===0||(i&&m.some(be=>be.id===i)?S(i):m.length===1&&S(m[0].id))},[m,x,i,S]);const y=l.useMemo(()=>m.find(be=>be.id===x)??null,[m,x]),j=l.useMemo(()=>(y==null?void 0:y.nodes)||[],[y]),N=l.useCallback(be=>(be==null?void 0:be.__sourceDaemonId)||u,[u]),[A,T]=l.useState(!1),[L,D]=l.useState(""),[M,_]=l.useState(""),[P,B]=l.useState(""),[R,O]=l.useState(null),[H,$]=l.useState(!1),[I,W]=l.useState(!1),[F,z]=l.useState(null),[Q,ne]=l.useState(""),[oe,Ce]=l.useState(""),[le,U]=l.useState(!1),J=t.createDaemonPicker&&M||u,ee=l.useMemo(()=>e.find(be=>be.id===J),[e,J]),Y=(ee==null?void 0:ee.workspaces)||[];l.useEffect(()=>{if(!A||!J||!P.trim()){O(null),$(!1);return}let be=!1;const Pe=setTimeout(()=>{be||($(!0),C.current(J,"plan_mesh_onboarding",{workspace:P.trim(),operation:"auto",meshInventory:b.current}).then(Me=>{if(be)return;const We=v.current(Me);O(We),We!=null&&We.success&&(D(Be=>{var Xe,at;return Be||`${String(((Xe=We.discovery)==null?void 0:Xe.repoIdentity)||((at=We.discovery)==null?void 0:at.repoRoot)||"").split(/[\\/]/).filter(Boolean).pop()||"repo"}-mesh`}),Ce(Be=>{var Xe;return Be||((Xe=We.discovery)==null?void 0:Xe.repoIdentity)||""}),ne(Be=>{var Xe,at,st,X,Le,_e;return Be||((st=(at=(Xe=We.discovery)==null?void 0:Xe.origin)==null?void 0:at.urls)==null?void 0:st[0])||((_e=(Le=(X=We.discovery)==null?void 0:X.upstream)==null?void 0:Le.urls)==null?void 0:_e[0])||""}))}).catch(Me=>{be||O({success:!1,error:(Me==null?void 0:Me.message)||"Git discovery failed"})}).finally(()=>{be||$(!1)}))},300);return()=>{be=!0,clearTimeout(Pe)}},[A,J,P,w]);const ve=l.useCallback(async()=>{const be=J,Pe=P.trim(),Me=Q.trim(),We=oe.trim();if(!(!be||!L.trim()||I)&&!(!Pe&&!Me&&!We)){W(!0),z(null),k(null);try{const Be=await ag({targetDaemonId:be,name:L,repoRemoteUrl:Me,repoIdentity:We,workspace:Pe,attachWorkspace:!!Pe,machineId:ee==null?void 0:ee.machineId,providerPriority:Pn(ln((ee==null?void 0:ee.availableProviders)||[])),meshInventory:m,sendCommand:n,unwrapResult:a});if(Be.warning&&z(Be.warning),!Be.meshCreated){k(Be.error||p("setupWizard.machines.createFailed"));return}await h(!0),Be.meshId&&S(Be.meshId),T(!1)}finally{W(!1)}}},[J,L,P,Q,oe,I,ee,m,n,a,h,S,k,p]),[pe,te]=l.useState(""),[me,V]=l.useState(""),[q,se]=l.useState(null),[de,K]=l.useState(!1),[fe,ie]=l.useState(!1),ue=l.useMemo(()=>{if(!t.addNodeDaemonPicker)return[];const be=new Set(j.map(Pe=>String(Pe.daemon_id||Pe.daemonId||"")));return e.filter(Pe=>Pe.id&&!be.has(Pe.id)&&!Xp(Pe))},[t.addNodeDaemonPicker,j,e]),ye=l.useMemo(()=>e.find(be=>be.id===pe),[e,pe]),Ie=t.addNodeDaemonPicker?(ye==null?void 0:ye.workspaces)||[]:((ge=e.find(be=>be.id===u))==null?void 0:ge.workspaces)||[];l.useEffect(()=>{if(A||!x||!me.trim()){se(null);return}const be=t.addNodeDaemonPicker?pe:N(y);if(!be)return;let Pe=!1;return K(!0),n(be,"plan_mesh_onboarding",{workspace:me.trim(),meshId:x,inlineMesh:y,operation:"add_existing"}).then(Me=>{Pe||se(a(Me))}).catch(Me=>{Pe||se({success:!1,error:(Me==null?void 0:Me.message)||"Git discovery failed"})}).finally(()=>{Pe||K(!1)}),()=>{Pe=!0}},[A,x,y,me,pe,t.addNodeDaemonPicker,N,n,a]);const E=l.useCallback(async()=>{var Me,We,Be,Xe;const be=N(y);if(!x||!be||fe)return;const Pe=me.trim();if(Pe){ie(!0),k(null);try{const at=t.addNodeDaemonPicker?pe:be,st=await n(at,"plan_mesh_onboarding",{workspace:Pe,meshId:x,inlineMesh:y,operation:"add_existing"}),X=a(st);if(se(X),(X==null?void 0:X.success)===!1)throw new Error(`${X.code||"onboarding_blocked"}: ${X.error}${X.action?` ${X.action}`:""}`);const Le={meshId:x,workspace:((Me=X==null?void 0:X.discovery)==null?void 0:Me.repoRoot)||Pe,repoRoot:(We=X==null?void 0:X.discovery)==null?void 0:We.repoRoot,isLocalWorktree:((Be=X==null?void 0:X.discovery)==null?void 0:Be.isLinkedWorktree)===!0};t.addNodeDaemonPicker&&pe&&(Le.daemonId=pe,Le.machineId=ye==null?void 0:ye.machineId),Le.providerPriority=Pn(ln(((Xe=t.addNodeDaemonPicker?ye:e[0])==null?void 0:Xe.availableProviders)||[]));const _e=await n(be,"add_mesh_node",Le),nt=a(_e);if((nt==null?void 0:nt.success)===!1)throw new Error(nt.error||"Add node failed");V(""),se(null),await h(!0)}catch(at){k((at==null?void 0:at.message)||"Add node failed")}finally{ie(!1)}}},[y,x,me,pe,ye,fe,t.addNodeDaemonPicker,N,e,n,a,h,k]),Z=!A&&!!y&&j.length>0;return s.jsxs("div",{className:"mx-auto flex w-full max-w-2xl flex-col gap-4 p-4",children:[s.jsxs("div",{children:[s.jsx("h2",{className:"text-base font-semibold text-text-primary",children:p("setupWizard.title")}),s.jsx("p",{className:"mt-1.5 text-[11px] text-text-muted",children:p("setupWizard.machines.description")})]}),g&&s.jsx("p",{className:"text-[11px] text-red-400",children:g}),s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary p-4",children:s.jsx(oR,{daemons:e,features:t,meshes:m,meshesLoading:f,selectedMeshId:x,onSelectMesh:be=>{S(be),V(""),te("")},createMode:A,onCreateModeChange:T,createName:L,onCreateNameChange:D,createDaemonId:M,onCreateDaemonIdChange:_,createWorkspace:P,onCreateWorkspaceChange:B,createPickerWorkspaces:Y,createPlan:R,createPlanLoading:H,creating:I,createWarning:F,onCreate:ve,createRepoRemoteUrl:Q,onCreateRepoRemoteUrlChange:ne,createRepoIdentity:oe,onCreateRepoIdentityChange:Ce,createManualOpen:le,onCreateManualOpenChange:U,nodes:j,attachableDaemons:ue,attachDaemonId:pe,onAttachDaemonIdChange:be=>{te(be),V("")},attachWorkspace:me,onAttachWorkspaceChange:V,attachPickerWorkspaces:Ie,attachPlan:q,attachPlanLoading:de,attaching:fe,onAttach:E,renderInstallOnboarding:d,nodeLabel:lR,daemonLabel:iR})}),s.jsx("div",{className:"flex items-center gap-2",children:s.jsx("div",{className:"ml-auto flex items-center gap-2",children:s.jsx("button",{type:"button",className:Z?"btn btn-primary btn-sm":"btn btn-secondary btn-sm",onClick:c,children:p(Z?"setupWizard.continueToMesh":"setupWizard.close")})})})]})}function Tc(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function dR(e){if(typeof window>"u")return e;const t=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),n=Tc();return n&&!t.searchParams.has("token")&&t.searchParams.set("token",n),e.startsWith("http://")||e.startsWith("https://")?t.toString():`${t.pathname}${t.search}${t.hash}`}async function Ts(e,t){return await fetch(dR(e),{credentials:"same-origin",...t})}function lg(){if(typeof window>"u")return;const e=new URL(window.location.href);e.searchParams.has("token")&&(e.searchParams.delete("token"),window.history.replaceState({},"",`${e.pathname}${e.search}${e.hash}`))}class uR{constructor(){it(this,"adapters",new Map);it(this,"states",new Map);it(this,"runtimeListeners",new Map);it(this,"screenshotCallbacks",new Map);it(this,"statusCallbacks",new Set);it(this,"stateChangeCallbacks",new Set);it(this,"ptyInputSender",null)}resolveDaemonId(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const n of this.adapters.keys())if(n.startsWith("standalone"))return n}return null}register(t,n){this.adapters.set(t,n),this.states.set(t,n.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,n){this.states.set(t,n);const a=this.resolveDaemonId(t)||t;this.stateChangeCallbacks.forEach(r=>r(a,n))}onStateChange(t){return this.stateChangeCallbacks.add(t),()=>{this.stateChangeCallbacks.delete(t)}}retryConnection(t){}get(t){const n=this.resolveDaemonId(t);return n?this.adapters.get(n):void 0}getState(t){const n=this.resolveDaemonId(t);return n&&this.states.get(n)||"disconnected"}registerPtyInputSender(t){this.ptyInputSender=t}sendData(t,n){return!1}sendPtyInput(t,n,a){return this.ptyInputSender?this.ptyInputSender(t,n,a):!1}onScreenshot(t,n){return this.screenshotCallbacks.set(t,n),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,n){this.screenshotCallbacks.forEach(a=>a(t,n))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,n){this.statusCallbacks.forEach(a=>a(t,n))}emitRuntimeSnapshot(t,n,a=0,r=!1,o,i){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:a,text:n,truncated:r,cols:o,rows:i})}emitSessionOutput(t,n,a){!t||typeof n!="string"||!n||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof a=="number"?{seq:a}:{},data:n})}onRuntimeEvent(t,n){const a=this.runtimeListeners.get(t)||new Set;return a.add(n),this.runtimeListeners.set(t,a),()=>{const r=this.runtimeListeners.get(t);r&&(r.delete(n),r.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,n,a){if(!n)return{success:!1,error:"sessionId is required"};const r=new URL(`/api/v1/runtime/${encodeURIComponent(n)}/snapshot`,window.location.origin);typeof(a==null?void 0:a.sinceSeq)=="number"&&r.searchParams.set("sinceSeq",String(a.sinceSeq));const o=await Ts(`${r.pathname}${r.search}`);if(!o.ok){let c=`Runtime snapshot unavailable (${o.status})`;try{const d=await o.json();d!=null&&d.error&&(c=d.error)}catch{}return{success:!1,error:c}}const i=await o.json();return this.emitRuntimeEvent(n,{type:"runtime_snapshot",sessionId:n,seq:typeof i.seq=="number"?i.seq:0,text:typeof i.text=="string"?i.text:"",truncated:!!i.truncated,cols:typeof i.cols=="number"?i.cols:void 0,rows:typeof i.rows=="number"?i.rows:void 0,force:!!(a!=null&&a.force)}),{success:!0}}emitRuntimeEvent(t,n){var a;(a=this.runtimeListeners.get(t))==null||a.forEach(r=>r(n))}}const As=new uR;function pR(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,n=Tc();return n?`${t}?token=${encodeURIComponent(n)}`:t}const Sr=pR(),ap=3e3,mR=3e4;let gs=null,hR=0;const io=new Map;let gn=null,Ia=null;function rp(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function ya(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function fR(e){return e==="connected"?"connected":e}async function La(e,t,n){const a=ph(e,n||{}),r=gs;if(r&&r.readyState===WebSocket.OPEN){const o=`req_${++hR}_${Date.now()}`;return new Promise((i,c)=>{const d=setTimeout(()=>{io.delete(o),c(new Error(`WS command timeout: ${t}`))},3e4);io.set(o,{resolve:p=>{clearTimeout(d),i(p)},reject:p=>{clearTimeout(d),c(p)}}),r.send(JSON.stringify({type:"command",requestId:o,data:{type:t,payload:a.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function Al(e,t){const n=gs;if(!n||n.readyState!==WebSocket.OPEN||!t||t.type!=="subscribe"&&t.type!=="unsubscribe")return!1;try{return n.send(JSON.stringify(t)),!0}catch{return!1}}function cg(e,t,n){const a=gs;if(!a||a.readyState!==WebSocket.OPEN)return!1;const r=ph(e,{sessionId:t,targetSessionId:t,data:n});try{return a.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:r.payload}})),!0}catch{return!1}}As.registerPtyInputSender(cg);class gR{constructor(t){it(this,"daemonId");it(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(gs==null?void 0:gs.readyState)===WebSocket.OPEN}get connectionState(){return(gs==null?void 0:gs.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,n){return La(this.daemonId,t,n)}async sendInput(t,n){return La(this.daemonId,"cdp_remote_action",{action:t,params:n,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,gn&&(clearInterval(gn),gn=null);const n=async()=>{if(this.hasCommandChannel)try{const a=await La(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(a!=null&&a.success&&(a!=null&&a.base64)){const r=await fetch(`data:image/jpeg;base64,${a.base64}`).then(o=>o.blob());As.emitScreenshot(this.daemonId,r)}}catch{}};n(),gn=setInterval(n,2e3)}stopScreenshots(t){gn&&(clearInterval(gn),gn=null)}}let rs=null;function bR(e){return(!rs||rs.daemonId!==e)&&(rs=new gR(e)),rs}function xR({children:e}){const t=l.useRef(Ra()),n=Ra();t.current=n;const{setUserName:a}=Ss(),r=l.useRef(a);r.current=a;const o=l.useRef(null),i=l.useRef(null),[,c]=l.useState("disconnected"),d=l.useCallback((h,x)=>{c(h),Ia==null||Ia(h,x)},[]),p=l.useRef(null),u=l.useRef(),m=l.useRef(ap),f=l.useRef(!0),g=l.useRef(!1),k=l.useRef("initial_connect");return l.useEffect(()=>{f.current=!0,g.current=!1;function h(){var b,w;if(!f.current||((b=p.current)==null?void 0:b.readyState)===WebSocket.OPEN||((w=p.current)==null?void 0:w.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${Sr}...`),ya("connect_attempt",{url:Sr,reason:k.current,delayMs:m.current});let S;try{S=new WebSocket(Sr)}catch(C){console.error("[Standalone WS] Failed to create WebSocket:",C),x();return}p.current=S,S.onopen=()=>{if(!f.current){S.close();return}d("connected"),m.current=ap,ya("open",{url:Sr,reason:k.current}),ys.resubscribeAll({sendData:Al}),console.log("[Standalone WS] Connected")},gs=S,S.onmessage=C=>{var v,y;try{const j=JSON.parse(C.data);if((j.type==="command_result"||j.type==="error")&&j.requestId){const N=io.get(j.requestId);N&&(io.delete(j.requestId),j.type==="error"?N.reject(new Error(((v=j.data)==null?void 0:v.message)||"Command failed")):N.resolve(j.data));return}if(j.type==="session_output"){const N=j.sessionId||j.cliId||j.cliType;N&&As.emitSessionOutput(N,typeof j.data=="string"?j.data:"",typeof j.seq=="number"?j.seq:void 0);return}if(j.type==="runtime_snapshot"){As.emitRuntimeSnapshot(j.sessionId,typeof j.text=="string"?j.text:"",typeof j.seq=="number"?j.seq:0,!!j.truncated,typeof j.cols=="number"?j.cols:void 0,typeof j.rows=="number"?j.rows:void 0);return}if(j.type==="topic_update"){const N=j.update;N&&ys.publish(N);return}if(j.type==="status"||j.type==="initial_state"){const N=j.data;if(!N)return;const{injectEntries:A,markLoaded:T,getIdes:L}=t.current,D=N.instanceId||"standalone",M=L().find(B=>B.id===D),_=bR(D);As.register(D,_),As.setState(D,"connected"),d("connected",D),As.emitStatus(D,N);const P=Wr(N,{daemonId:D,existingDaemon:M,existingEntries:L()});rp("ws_status",{type:j.type,daemonId:D,sessions:(N.sessions||[]).map(B=>({id:B.id,parentId:B.parentId,providerType:B.providerType,kind:B.kind,transport:B.transport,unread:B.unread,inboxBucket:B.inboxBucket,lastSeenAt:B.lastSeenAt,lastUpdated:B.lastUpdated,title:B.title})),recentLaunches:(N.recentLaunches||[]).map(B=>({id:B.id,providerType:B.providerType,kind:B.kind,workspace:B.workspace,lastLaunchedAt:B.lastLaunchedAt}))}),rp("entries",{daemonId:D,entries:P.filter(B=>B.type!=="adhdev-daemon").map(B=>({id:B.id,type:B.type,unread:B.unread,inboxBucket:B.inboxBucket,lastSeenAt:B.lastSeenAt,lastUpdated:B.lastUpdated,sessionId:B.sessionId}))}),P.length>0&&A(P,{authoritativeDaemonIds:[D]}),T(),i.current!==D&&((y=o.current)==null||y.call(o),i.current=D,o.current=ys.subscribe({sendData:Al},D,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${D}`,params:{includeSessions:!0}},B=>{if(B.topic!=="daemon.metadata")return;const R=t.current.getIdes(),O=R.find($=>$.id===D),H=Wr(B.status,{daemonId:D,existingDaemon:O,existingEntries:R,timestamp:B.timestamp});H.length>0&&t.current.injectEntries(H,{authoritativeDaemonIds:[D]}),B.userName&&r.current&&r.current(B.userName)}))}}catch(j){console.error("[Standalone WS] Parse error:",j)}},S.onclose=C=>{f.current&&(rs==null||rs.stopScreenshots(),rs&&As.setState(rs.daemonId,"disconnected"),d("disconnected"),p.current=null,k.current=`close:${C.code}${C.wasClean?":clean":":unclean"}`,ya("close",{code:C.code,reason:C.reason||"",wasClean:C.wasClean}),x())},S.onerror=C=>{g.current||!f.current||(k.current="error",ya("error",{message:C instanceof Event?"event":String(C),readyState:S.readyState}),console.warn("[Standalone WS] Error, will reconnect:",C))}}function x(){if(!f.current)return;clearTimeout(u.current);const S=m.current;console.log(`[Standalone WS] Reconnecting in ${S}ms...`),ya("schedule_reconnect",{reason:k.current,delayMs:S}),u.current=setTimeout(()=>{m.current=Math.min(m.current*1.5,mR),h()},S)}return h(),()=>{var S;f.current=!1,g.current=!0,(S=o.current)==null||S.call(o),o.current=null,i.current=null,clearTimeout(u.current),p.current&&(p.current.onerror=null,p.current.onclose=null,p.current.close(),p.current=null,gs=null),rs&&(rs.stopScreenshots(),As.unregister(rs.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function vR({children:e}){const[t,n]=l.useState("disconnected"),[a,r]=l.useState(null);l.useEffect(()=>(Ia=(i,c)=>{n(i),c&&r(c)},()=>{Ia=null}),[]);const o=l.useMemo(()=>{const i=t==="connected",c=fR(t),d={};return a&&(d[a]=c),d.standalone=c,{wsStatus:t,isConnected:i,connectionStates:d,usesP2P:!1}},[t,a]);return s.jsx(Xg,{connectionOverrides:o,children:s.jsx(xR,{children:e})})}const dg="adhdev_standalone_font_preferences",Nn={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Lo=[{id:"default",label:"Default",family:"var(--font-sans)",description:"Current dashboard sans stack"},{id:"system-ui",label:"System UI",family:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Use the browser/OS default UI font"},{id:"inter",label:"Inter",family:'"Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Match the current product default explicitly"},{id:"pretendard",label:"Pretendard",family:'"Pretendard", "Noto Sans KR", system-ui, sans-serif',description:"Crisp Korean-first sans fallback stack"},{id:"noto-sans-kr",label:"Noto Sans KR",family:'"Noto Sans KR", "Apple SD Gothic Neo", "Malgun Gothic", "Segoe UI", sans-serif',description:"Wide CJK coverage with neutral metrics"},{id:"serif",label:"Serif",family:'"Iowan Old Style", "Apple Garamond", "Times New Roman", serif',description:"Reading-focused serif stack for long replies"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS font-family stack"}],Wa=[{id:"default",label:"Default mono",family:'ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',description:"Current monospace stack"},{id:"jetbrains-mono",label:"JetBrains Mono",family:'"JetBrains Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Readable coding font with strong punctuation"},{id:"fira-code",label:"Fira Code",family:'"Fira Code", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Popular ligature-friendly code font"},{id:"cascadia-code",label:"Cascadia Code",family:'"Cascadia Code", "Cascadia Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Windows-friendly modern coding font"},{id:"berkeley-mono",label:"Berkeley Mono",family:'"Berkeley Mono", "SF Mono", ui-monospace, Menlo, Consolas, monospace',description:"Editorial-feeling mono stack if installed"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS monospace stack"}],yR=new Set(Lo.map(e=>e.id)),wR=new Set(Wa.map(e=>e.id));function Ms(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Rr("chat",t.chat),code:Rr("code",t.code),terminal:Rr("terminal",t.terminal)}}function Rr(e,t){const n=Nn[e],a=t&&typeof t=="object"&&!Array.isArray(t)?t:{},r=typeof a.preset=="string"?a.preset.trim():"",o=typeof a.customFamily=="string"?a.customFamily.trim():"";return(e==="chat"?yR:wR).has(r)?r==="custom"?o?{preset:"custom",customFamily:o}:n:{preset:r}:n}function Er(e,t){var r;const n=Rr(e,t);if(n.preset==="custom"&&n.customFamily)return n.customFamily;const a=e==="chat"?Lo:Wa;return((r=a.find(o=>o.id===n.preset))==null?void 0:r.family)||a[0].family}function kR(e){const t=Ms(e),n=Er("chat",t.chat),a=Er("code",t.code),r=Er("terminal",t.terminal);return{"--chat-font-family":n,"--chat-code-font-family":a,"--chat-terminal-font-family":r,"--chat-tool-font-family":r}}function xn(e,t=document.documentElement){const n=Ms(e),a=kR(n);t.setAttribute("data-standalone-fonts","custom");for(const[r,o]of Object.entries(a))t.style.setProperty(r,o);return n}function Tl(e){const t=Ms(e);try{localStorage.setItem(dg,JSON.stringify(t))}catch{}return t}function SR(){try{const e=localStorage.getItem(dg);if(e)return Ms(JSON.parse(e))}catch{}return Nn}function CR(){return xn(SR())}function wa(e,t){var a;const n=e==="chat"?Lo:Wa;return((a=n.find(r=>r.id===t))==null?void 0:a.label)||n[0].label}function jR({children:e}){const t=oa(),n=Pl(),{t:a}=ke("common"),r=l.useMemo(()=>[{id:"dashboard",path:"/dashboard",icon:s.jsx(kp,{}),label:a("nav.dashboard"),active:n.pathname.startsWith("/dashboard"),onSelect:()=>t("/dashboard")},{id:"machine",path:"/machines",icon:s.jsx(sn,{}),label:a("nav.machines"),active:n.pathname.startsWith("/machines"),onSelect:()=>t("/machines")},{id:"mesh",path:"/mesh",icon:s.jsx(cs,{}),label:a("nav.mesh"),active:n.pathname.startsWith("/mesh")||n.pathname.startsWith("/setup"),onSelect:()=>t("/mesh")},{id:"settings",path:"/settings",icon:s.jsx(Oa,{}),label:a("nav.settings"),active:n.pathname.startsWith("/settings"),onSelect:()=>t("/settings")}],[n.pathname,t,a]),o=l.useMemo(()=>[{id:"docs",label:s.jsxs(s.Fragment,{children:[s.jsx("span",{children:a("nav.docs")}),s.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:s.jsx(Sp,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:a("nav.docs")},{id:"about",label:a("nav.about"),icon:s.jsx(co,{}),active:n.pathname==="/about",onSelect:()=>t("/about"),title:a("nav.about")}],[n.pathname,t,a]);return s.jsx(i1,{brand:({collapsed:i})=>s.jsxs(s.Fragment,{children:[s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&s.jsx("span",{children:"ADHDev"})]}),navItems:r,footerItems:o,footerInfo:({collapsed:i})=>i?null:s.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","1.0.53"]}),footerActions:({collapsed:i,toggleCollapsed:c})=>s.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:c,title:a(i?"standalone.layout.expandSidebar":"standalone.layout.collapseSidebar"),children:[s.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&s.jsx("span",{className:"text-xs",children:a("standalone.layout.collapse")})]}),children:e})}function NR(){const e=oa(),{sendCommand:t}=St(),{ides:n}=Ss(),a=l.useMemo(()=>n.filter(r=>r.daemonMode||r.type==="adhdev-daemon").map(r=>r),[n]);return s.jsx(cR,{daemons:a,features:Xf,sendCommand:t,unwrapResult:r=>r,normalizeMesh:r=>r,onClose:()=>e("/mesh")})}const AR=[{icon:s.jsx(sn,{size:16}),key:"localFirst"},{icon:s.jsx(Ds,{size:16}),key:"chatRelay"},{icon:s.jsx(El,{size:16}),key:"screenshots"},{icon:s.jsx(us,{size:16}),key:"remoteControl"},{icon:s.jsx(Ea,{size:16}),key:"multiIde"},{icon:s.jsx(Sp,{size:16}),key:"cliAcp"}],TR=[{icon:s.jsx(mo,{size:16}),key:"anywhere"},{icon:s.jsx(kp,{size:16}),key:"p2pStream"},{icon:s.jsx(ia,{size:16}),key:"mobileNotifications"},{icon:s.jsx(lb,{size:16}),key:"restApi"},{icon:s.jsx(db,{size:16}),key:"enterpriseControls"}],MR=[{key:"chatRelay",selfhost:!0,cloud:!0},{key:"screenshots",selfhost:!0,cloud:!0},{key:"remoteControl",selfhost:!0,cloud:!0},{key:"multiIde",selfhost:!0,cloud:!0},{key:"extensionCli",selfhost:!0,cloud:!0},{key:"anyNetwork",selfhost:!1,cloud:!0},{key:"webrtc",selfhost:!1,cloud:!0},{key:"mobilePush",selfhost:!1,cloud:!0},{key:"restApi",selfhost:!1,cloud:!0},{key:"multiMachineDashboards",selfhost:!1,cloud:!0},{key:"ssoRbacAuditLogs",selfhost:!1,cloud:!0}];function PR(){const{t:e}=ke("common");return s.jsxs(Qa,{icon:s.jsx(co,{className:"text-text-primary"}),title:e("standalone.about.title"),subtitle:e("standalone.about.subtitle"),widthClassName:"max-w-5xl",actions:s.jsxs("div",{className:"px-3 py-1 text-[11px] font-semibold tracking-wide rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/20",children:["SELFHOST v","1.0.53"]}),children:[s.jsx(bt,{children:s.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[s.jsxs("div",{className:"max-w-2xl",children:[s.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:e("standalone.about.selfHostedEdition")}),s.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-text-primary mb-2",children:e("standalone.about.headline")}),s.jsx("p",{className:"text-sm text-text-muted leading-relaxed",children:e("standalone.about.description")})]}),s.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.docs")}),s.jsx("a",{href:"https://github.com/vilmire/adhdev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.github")}),s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.tryCloud")})]})]})}),s.jsx(bt,{title:e("standalone.about.includedSection"),description:e("standalone.about.includedDescription"),children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:AR.map(t=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-bg-secondary text-text-secondary border border-border-subtle",children:t.icon}),e("standalone.about.features."+t.key+".title")]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e("standalone.about.features."+t.key+".desc")})]},t.key))})}),s.jsx(bt,{title:e("standalone.about.inventorySection"),description:e("standalone.about.inventoryDescription"),children:s.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:mh.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:fh.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:hh.map(t=>`${t.icon} ${t.name}`)}].map(t=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[s.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:t.label}),s.jsx("div",{className:"flex flex-col gap-1.5",children:t.items.map(n=>s.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:n},n))})]},t.label))})}),s.jsx(bt,{title:e("standalone.about.cloudExtrasSection"),description:e("standalone.about.cloudExtrasDescription"),children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:TR.map(t=>s.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:t.icon}),e("standalone.about.extras."+t.key+".title")]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e("standalone.about.extras."+t.key+".desc")})]},t.key))})}),s.jsx(bt,{title:e("standalone.about.comparisonSection"),description:e("standalone.about.comparisonDescription"),children:s.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:s.jsxs("table",{className:"w-full text-[13px]",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"bg-bg-secondary",children:[s.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:e("standalone.about.featureHeader")}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:e("standalone.about.selfhostHeader")}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:e("standalone.about.cloudHeader")})]})}),s.jsx("tbody",{children:MR.map((t,n)=>s.jsxs("tr",{className:n%2===0?"bg-bg-glass":"bg-transparent",children:[s.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:e("standalone.about.comparison."+t.key)}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:t.selfhost?s.jsx("span",{className:"text-emerald-500",children:"✓"}):s.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:s.jsx("span",{className:"text-emerald-500",children:"✓"})})]},t.key))})]})})}),s.jsx(Ja,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"mx-auto h-12 w-12 opacity-80"}),title:e("standalone.about.cloudOptional"),description:e("standalone.about.cloudOptionalDescription"),action:s.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:e("standalone.about.compareCloud")}),s.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[s.jsx(vb,{size:14,className:"mr-1"}),e("standalone.about.discord")]})]})})]})}function Ei(e,t,n){return{...e,[t]:n}}function _i({surface:e,title:t,description:n,value:a,options:r,onChange:o}){const{t:i}=ke("common");return s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:t}),s.jsx("div",{className:"text-xs text-text-muted mt-1",children:n})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(u1,{value:a.preset,onChange:c=>{const d=c.target.value;o(d==="custom"?{preset:"custom",customFamily:a.customFamily||""}:{preset:d})},children:r.map(c=>s.jsx("option",{value:c.id,children:c.label},c.id))}),a.preset==="custom"&&s.jsx(xs,{type:"text",className:"font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:a.customFamily||"",onChange:c=>o({preset:"custom",customFamily:c.target.value})}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[s.jsx("span",{className:"font-medium text-text-secondary",children:i("standalone.fonts.resolvedStack")})," ",s.jsx("span",{className:"font-mono break-all",children:Er(e,a)})]})]})]})}function DR({value:e,savedValue:t,saving:n=!1,error:a,notice:r,onChange:o,onSave:i,onResetToSaved:c,onResetToDefaults:d}){const{t:p}=ke("common"),u=JSON.stringify(e)!==JSON.stringify(t);return s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:p("standalone.fonts.fontOverridesNotice")}),a&&s.jsx(Mt,{variant:"error",children:a}),r&&s.jsx(Mt,{variant:"success",children:r}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(_i,{surface:"chat",title:p("standalone.fonts.chat"),description:p("standalone.fonts.chatDescription"),value:e.chat,options:Lo,onChange:m=>o(Ei(e,"chat",m))}),s.jsx(_i,{surface:"code",title:p("standalone.fonts.code"),description:p("standalone.fonts.codeDescription"),value:e.code,options:Wa,onChange:m=>o(Ei(e,"code",m))}),s.jsx(_i,{surface:"terminal",title:p("standalone.fonts.terminal"),description:p("standalone.fonts.terminalDescription"),value:e.terminal,options:Wa,onChange:m=>o(Ei(e,"terminal",m))})]}),s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:p("standalone.fonts.livePreview")}),s.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",wa("chat",e.chat.preset)," · Code: ",wa("code",e.code.preset)," · Terminal: ",wa("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[p("standalone.fonts.defaults")," ",wa("chat",Nn.chat.preset)," / ",wa("code",Nn.code.preset)]})]}),s.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:s.jsxs("div",{className:"chat-container-content",children:[s.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:s.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[s.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[s.jsx("span",{className:"chat-sender",children:"Hermes"}),s.jsx("span",{className:"chat-time",children:"now"})]}),s.jsxs("div",{className:"chat-markdown",children:[s.jsxs("p",{children:["Readable prose, ",s.jsx("strong",{children:"bold text"}),", and ",s.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),s.jsx("pre",{children:s.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),s.jsxs("div",{className:"chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"▸"}),s.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),s.jsxs("div",{className:"chat-msg-terminal",children:[s.jsx("div",{className:"chat-msg-header",children:"Terminal"}),s.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx(Us,{type:"button",variant:"primary",size:"sm",onClick:i,disabled:n||!u,children:p(n?"standalone.fonts.saving":"standalone.fonts.saveFontSettings")}),s.jsx(Us,{type:"button",variant:"secondary",size:"sm",onClick:c,disabled:n||!u,children:p("standalone.fonts.revertToSaved")}),s.jsx(Us,{type:"button",variant:"secondary",size:"sm",onClick:d,disabled:n,children:p("standalone.fonts.resetToDefaults")})]})]})}function IR(){const{t:e}=ke("common"),{ides:t}=Ss(),n=t.find(U=>U.type==="adhdev-daemon"),a=(n==null?void 0:n.detectedIdes)||[],{sendCommand:r}=St(),{userName:o}=Ss(),[i,c]=l.useState(o||""),[d,p]=l.useState(null),[u,m]=l.useState(null),[f,g]=l.useState(Nn),[k,h]=l.useState(!1),[x,S]=l.useState(""),[b,w]=l.useState(""),[C,v]=l.useState("127.0.0.1"),[y,j]=l.useState(""),[N,A]=l.useState(""),[T,L]=l.useState(""),[D,M]=l.useState(""),[_,P]=l.useState(""),[B,R]=l.useState(!1),O=async()=>{const J=await(await Ts("/auth/session")).json();p(J)},H=async()=>{const J=await(await Ts("/api/v1/standalone/preferences")).json();m(J),v(J.standaloneBindHost);const ee=Ms(J.standaloneFontPreferences);g(ee),xn(ee),Tl(ee)};l.useEffect(()=>{o!==void 0&&c(o)},[o]),l.useEffect(()=>{Promise.all([O(),H()]).catch(U=>{M(U instanceof Error?U.message:String(U))})},[]),l.useEffect(()=>{xn(f)},[f]);const $=U=>{const J=U.target.value.trim();n!=null&&n.id&&J!==o&&r(n.id,"set_user_name",{userName:J}).catch(console.error)},[I,W]=l.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),F=U=>{W(U);try{localStorage.setItem("adhdev_sound",U?"1":"0")}catch{}},z=async()=>{S(""),w(""),h(!0);try{const U=Ms(f),J=await Ts("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:U})}),ee=await J.json();if(!J.ok)throw new Error((ee==null?void 0:ee.error)||"Failed to save standalone font preferences");const Y=Ms(ee.standaloneFontPreferences);m(ee),g(Y),xn(Y),Tl(Y),w(e("standalone.settings.fontsSaved"))}catch(U){S(U instanceof Error?U.message:String(U))}finally{h(!1)}},Q=()=>{const U=Ms(u==null?void 0:u.standaloneFontPreferences);S(""),w(""),g(U),xn(U)},ne=()=>{S(""),w(""),g(Nn),xn(Nn)},oe=async()=>{M(""),P(""),R(!0);try{const U=await Ts("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:C})}),J=await U.json();if(!U.ok)throw new Error((J==null?void 0:J.error)||"Failed to save standalone network preference");m(J),v(J.standaloneBindHost),P(J.standaloneBindHost==="0.0.0.0"?e("standalone.settings.networkSavedAll"):e("standalone.settings.networkSavedLocal"))}catch(U){M(U instanceof Error?U.message:String(U))}finally{R(!1)}},Ce=async()=>{if(M(""),P(""),N.trim().length<4){M(e("standalone.settings.passwordTooShort"));return}if(N!==T){M(e("standalone.settings.passwordMismatch"));return}R(!0);try{const U=await Ts("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,newPassword:N})}),J=await U.json();if(!U.ok)throw new Error((J==null?void 0:J.error)||"Failed to save password");p(J),await H(),j(""),A(""),L(""),P(d!=null&&d.hasPasswordAuth?e("standalone.settings.passwordUpdated"):e("standalone.settings.passwordEnabled")),lg()}catch(U){M(U instanceof Error?U.message:String(U))}finally{R(!1)}},le=async()=>{M(""),P(""),R(!0);try{const U=await Ts("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,clear:!0})}),J=await U.json();if(!U.ok)throw new Error((J==null?void 0:J.error)||"Failed to clear password");p(J),await H(),j(""),A(""),L(""),P(e("standalone.settings.passwordDisabled"))}catch(U){M(U instanceof Error?U.message:String(U))}finally{R(!1)}};return s.jsxs(Qa,{icon:s.jsx(Oa,{className:"text-text-primary"}),title:e("standalone.settings.title"),subtitle:e("standalone.settings.subtitle"),widthClassName:"max-w-5xl",children:[s.jsx(Mt,{variant:"info",children:e("standalone.settings.infoNotice")}),(d==null?void 0:d.publicHostWarning)&&s.jsx(Mt,{variant:"warning",children:e("standalone.settings.publicHostWarning")}),s.jsx(bt,{title:e("standalone.settings.daemonSection"),description:e("standalone.settings.daemonDescription"),children:s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[s.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.versionLabel")}),s.jsxs("span",{className:"font-mono text-xs text-text-primary",children:["v","1.0.53"]})]}),s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[s.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.statusLabel")}),s.jsx("span",{className:`text-xs font-medium ${n?"text-green-400":"text-yellow-400"}`,children:e(n?"standalone.settings.statusRunning":"standalone.settings.statusNotConnected")})]}),s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[s.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.currentBindLabel")}),s.jsx("span",{className:"font-mono text-xs text-text-primary",children:(u==null?void 0:u.currentBindHost)||(d==null?void 0:d.boundHost)||"127.0.0.1"})]}),s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[s.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.defaultBindLabel")}),s.jsx("span",{className:"font-mono text-xs text-text-primary",children:(u==null?void 0:u.standaloneBindHost)||"127.0.0.1"})]}),s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[s.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.authLabel")}),s.jsx("span",{className:"text-xs text-text-primary",children:d!=null&&d.hasPasswordAuth?e("standalone.settings.authPassword"):d!=null&&d.hasTokenAuth?e("standalone.settings.authToken"):e("standalone.settings.authNone")})]})]})}),s.jsx(bt,{title:e("standalone.settings.networkSection"),description:e("standalone.settings.networkDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:e("standalone.settings.networkHint")}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:C==="127.0.0.1",onChange:()=>v("127.0.0.1")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:e("standalone.settings.localhostLabel")}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:e("standalone.settings.localhostHint")})]})]}),s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:C==="0.0.0.0",onChange:()=>v("0.0.0.0")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:e("standalone.settings.allInterfacesLabel")}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:e("standalone.settings.allInterfacesHint")})]})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx(Us,{type:"button",variant:"primary",size:"sm",onClick:()=>{oe()},disabled:B,children:e(B?"standalone.settings.saving":"standalone.settings.saveNetworkMode")}),s.jsx("span",{className:"text-xs text-text-muted",children:e("standalone.settings.networkRestartHint",{host:(u==null?void 0:u.currentBindHost)||(d==null?void 0:d.boundHost)||"127.0.0.1"})})]})]})}),s.jsx(bt,{title:e("standalone.settings.securitySection"),description:e("standalone.settings.securityDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:d!=null&&d.hasPasswordAuth?e("standalone.settings.passwordSet"):e("standalone.settings.passwordNotSet")}),D&&s.jsx(Mt,{variant:"error",children:D}),_&&s.jsx(Mt,{variant:"success",children:_}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx(xs,{type:"password",placeholder:d!=null&&d.hasPasswordAuth?e("standalone.settings.currentPasswordPlaceholder"):e("standalone.settings.currentPasswordFirstTimePlaceholder"),value:y,onChange:U=>j(U.target.value)}),s.jsx(xs,{type:"password",placeholder:d!=null&&d.hasPasswordAuth?e("standalone.settings.newPasswordPlaceholder"):e("standalone.settings.newPasswordFirstTimePlaceholder"),value:N,onChange:U=>A(U.target.value)}),s.jsx(xs,{type:"password",className:"md:col-span-2",placeholder:e("standalone.settings.confirmPasswordPlaceholder"),value:T,onChange:U=>L(U.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Us,{type:"button",variant:"primary",size:"sm",onClick:()=>{Ce()},disabled:B,children:B?e("standalone.settings.saving"):d!=null&&d.hasPasswordAuth?e("standalone.settings.updatePassword"):e("standalone.settings.enablePassword")}),(d==null?void 0:d.hasPasswordAuth)&&s.jsx(Us,{type:"button",variant:"danger",size:"sm",onClick:()=>{le()},disabled:B,children:e("standalone.settings.disablePassword")})]})]})}),s.jsx(bt,{title:e("standalone.settings.detectedIdesSection"),description:e("standalone.settings.detectedIdesDescription"),children:a.length===0?s.jsx("p",{className:"text-sm text-text-muted",children:e("standalone.settings.noIdesDetected")}):s.jsx("div",{className:"flex flex-col gap-2",children:a.map(U=>s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${U.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium text-text-primary",children:U.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:U.type})]},U.type))})}),s.jsx(bt,{title:e("standalone.settings.machineSection"),description:e("standalone.settings.machineDescription"),children:s.jsx(w1,{ides:t,emptyMessage:e("standalone.settings.daemonNotConnected")})}),s.jsx(bt,{title:e("standalone.settings.appearanceSection"),description:e("standalone.settings.appearanceDescription"),children:s.jsx(F1,{themeDescription:e("standalone.settings.themeDescription"),mobileDescription:e("standalone.settings.mobileDescription"),fontsSlot:s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:e("standalone.settings.fontsLabel")}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:e("standalone.settings.fontsDescription")}),s.jsx(DR,{value:f,savedValue:Ms(u==null?void 0:u.standaloneFontPreferences),saving:k,error:x,notice:b,onChange:g,onSave:()=>{z()},onResetToSaved:Q,onResetToDefaults:ne})]})})}),s.jsx(bt,{title:e("standalone.settings.notificationsSection"),description:e("standalone.settings.notificationsDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(g1,{}),s.jsx(bn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(xb,{size:15})," ",e("standalone.settings.soundEffectsLabel")]}),description:e("standalone.settings.soundEffectsDescription"),checked:I,onChange:F})]})}),s.jsx(bt,{title:e("standalone.settings.profileSection"),description:e("standalone.settings.profileDescription"),children:s.jsx("div",{className:"flex flex-col gap-3",children:s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-4 bg-bg-glass rounded-xl border border-border-subtle hover:border-border-default transition-colors",children:[s.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[s.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[s.jsx(ib,{size:16,className:"text-text-secondary"})," ",e("standalone.settings.displayNameLabel")]}),s.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:e("standalone.settings.displayNameHint")})]}),s.jsx(xs,{type:"text",className:"w-48 text-right",placeholder:e("standalone.settings.displayNamePlaceholder"),value:i,onChange:U=>c(U.target.value),onBlur:$,onKeyDown:U=>{U.key==="Enter"&&U.currentTarget.blur()}})]})})})]})}const LR=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],ja="adhdev_onboarding_done",RR=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],ER={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function _R({onDone:e}){const{t}=ke("common"),[n,a]=l.useState([]),[r,o]=l.useState(new Set(LR)),[i,c]=l.useState(!0),[d,p]=l.useState(null),[u,m]=l.useState(!1),[f,g]=l.useState(null),[k,h]=l.useState("all");l.useEffect(()=>{let y=!1;return fetch("https://api.adhf.dev/api/v1/registry/providers?sort=popular&limit=100").then(async N=>{if(!N.ok)throw new Error(`HTTP ${N.status}`);const A=await N.text();try{return JSON.parse(A)}catch{throw new Error(`unexpected non-JSON response (${N.headers.get("content-type")??"unknown content type"})`)}}).then(N=>{y||a(N.providers??[])}).catch(N=>{y||p(N instanceof Error?N.message:String(N))}).finally(()=>{y||c(!1)}),()=>{y=!0}},[]);const x=n.filter(y=>k==="all"||y.category===k),S=["cli","ide","extension","acp"].map(y=>({category:y,items:x.filter(j=>j.category===y)})).filter(y=>y.items.length>0),b=l.useCallback(y=>{o(j=>{const N=new Set(j);return N.has(y)?N.delete(y):N.add(y),N})},[]),w=l.useCallback(async()=>{if(r.size===0){localStorage.setItem(ja,"1"),e();return}m(!0);const y=[];for(const j of r)try{const A=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:j})})).json().catch(()=>({}));y.push({type:j,ok:!!A.success,error:A.error})}catch(N){y.push({type:j,ok:!1,error:N instanceof Error?N.message:String(N)})}g(y),m(!1),y.every(j=>j.ok)&&localStorage.setItem(ja,"1")},[r,e]),C=l.useCallback(()=>{localStorage.setItem(ja,"1"),e()},[e]),v=l.useCallback(()=>{f&&f.every(y=>y.ok)?e():u||C()},[f,u,e,C]);return s.jsx(xm,{open:!0,onClose:v,size:"lg",contentClassName:"max-w-2xl",title:t("standalone.onboarding.title"),footer:s.jsxs("div",{className:"flex w-full items-center gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:t(r.size!==1?"standalone.onboarding.selectedCount_other":"standalone.onboarding.selectedCount_one",{count:r.size})}),s.jsxs("div",{className:"ml-auto flex gap-2",children:[s.jsx(Us,{variant:"secondary",size:"sm",onClick:C,disabled:u,children:t("standalone.onboarding.skip")}),s.jsx(Us,{variant:"primary",size:"sm",onClick:()=>{f?(localStorage.setItem(ja,"1"),e()):w()},disabled:u||!f&&r.size===0,children:u?t("standalone.onboarding.installing"):f?t("standalone.onboarding.done"):t("standalone.onboarding.installCount",{count:r.size})})]})]}),children:s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsx("div",{className:"text-[12px] text-text-muted",children:t("standalone.onboarding.intro")}),!i&&!d&&n.length>0&&s.jsx("div",{className:"flex gap-1 flex-wrap border-b border-border-subtle pb-2",children:RR.map(y=>{const j=y.key==="all"?n.length:n.filter(N=>N.category===y.key).length;return j===0&&y.key!=="all"?null:s.jsxs("button",{onClick:()=>h(y.key),className:`machine-btn text-[10px] px-2 py-0.5 ${k===y.key?"bg-accent-primary/12 border-accent-primary/40 text-accent-primary":""}`,children:[y.label," ",s.jsxs("span",{className:"opacity-60",children:["(",j,")"]})]},y.key)})}),i&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.loadingRegistry")}),!i&&d&&s.jsx(Mt,{variant:"error",children:t("standalone.onboarding.loadError",{error:d})}),!i&&!d&&x.length===0&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.noProviders")}),!i&&!d&&x.length>0&&s.jsx("div",{className:"flex flex-col gap-4",children:S.map(y=>s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:ER[y.category]??y.category}),s.jsx("div",{className:"grid gap-1.5",children:y.items.map(j=>{var L;const N=r.has(j.type),A=f==null?void 0:f.find(D=>D.type===j.type),T=((L=j.manifest)==null?void 0:L.details)??"";return s.jsxs("label",{className:`flex items-center gap-3 px-3 py-2 rounded-xl border cursor-pointer transition-colors ${N?"bg-accent-primary/[0.06] border-accent-primary/30":"bg-bg-glass border-border-subtle hover:bg-bg-glass-hover"}`,children:[s.jsx("input",{type:"checkbox",checked:N,onChange:()=>b(j.type),disabled:u,className:"shrink-0"}),s.jsx(Ya,{type:j.type,label:j.displayName??j.type,size:18,className:"shrink-0"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[13px] font-medium text-text-primary truncate",children:j.displayName}),T&&s.jsx("div",{className:"text-[10px] text-text-muted truncate",children:T})]}),A&&s.jsx("span",{className:`text-[10px] font-semibold ${A.ok?"text-status-online":"text-status-error"}`,children:A.ok?t("standalone.onboarding.installed"):t("standalone.onboarding.installFailed",{error:A.error??"failed"})})]},j.type)})})]},y.category))})]})})}function HR(){try{return localStorage.getItem(ja)==="1"}catch{return!1}}Qj();D1();k0();CR();const $R=vp({baseUrl:"",getToken:Tc});function FR({children:e}){const{t}=ke("common"),[n,a]=l.useState(null),[r,o]=l.useState(!0),[i,c]=l.useState(""),[d,p]=l.useState(""),[u,m]=l.useState(!1),f=async()=>{o(!0),p("");try{const h=await(await Ts("/auth/session")).json();a(h)}catch(k){p(k instanceof Error?k.message:String(k))}finally{o(!1)}};l.useEffect(()=>{f()},[]),l.useEffect(()=>{if(!n||n.required&&!n.authenticated)return;let k=!1;return(async()=>{try{const h=await Ts("/api/v1/standalone/preferences");if(!h.ok)return;const x=await h.json();if(k)return;const S=Ms(x.standaloneFontPreferences);xn(S),Tl(S)}catch{}})(),()=>{k=!0}},[n==null?void 0:n.authenticated,n==null?void 0:n.required]);const g=async k=>{k.preventDefault(),m(!0),p("");try{const h=await Ts("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),x=await h.json();if(!h.ok)throw new Error((x==null?void 0:x.error)||"Login failed");a(x),c(""),lg()}catch(h){p(h instanceof Error?h.message:String(h))}finally{m(!1)}};return r?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:t("standalone.auth.loading")}):n?!n.required||n.authenticated?s.jsx(s.Fragment,{children:e}):s.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:s.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:t("standalone.auth.signInTitle")}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:n.hasPasswordAuth?t("standalone.auth.passwordProtected"):t("standalone.auth.tokenProtected")})]}),n.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:g,children:[s.jsx(xs,{type:"password",value:i,onChange:k=>c(k.target.value),placeholder:t("standalone.auth.passwordPlaceholder"),autoFocus:!0}),s.jsx(Us,{type:"submit",variant:"primary",disabled:u||!i,className:"justify-center",children:t(u?"standalone.auth.signingIn":"standalone.auth.unlock")})]}):s.jsx(Mt,{variant:"warning",children:t("standalone.auth.noPasswordEnabled")}),d&&s.jsx(Mt,{variant:"error",children:d})]})}):s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:t("standalone.auth.loadError",{error:d||"unknown error"})})}function op(){const{t:e}=ke("common"),{ides:t,initialLoaded:n}=Ss();if(!n)return s.jsx("div",{className:"p-10 text-center text-text-muted",children:e("standalone.machine.loading")});const a=t.find(r=>r.daemonMode||r.type==="adhdev-daemon");return a?s.jsx(Fi,{to:`/machines/${a.id}`,replace:!0}):s.jsx(Fi,{to:"/dashboard",replace:!0})}function BR(){const[e,t]=l.useState(!1);return l.useEffect(()=>{let n=!1;if(!HR())return fetch("/api/v1/providers/installed").then(a=>a.ok?a.json():{providers:[]}).then(a=>{n||(a.providers??[]).length===0&&t(!0)}).catch(()=>{}),()=>{n=!0}},[]),e?s.jsx(_R,{onDone:()=>t(!1)}):null}function WR(){const{t:e}=ke("common"),{ides:t}=Ss(),n=l.useMemo(()=>{for(const u of t)if(u.activeInteractivePrompt)return u.instanceId??u.id;return null},[t]),{promptSession:a,hasActivePrompt:r,responseError:o,isSubmitting:i,submit:c,cancel:d,reopen:p}=jh(n);return r?s.jsxs("div",{className:"relative",children:[!a&&s.jsx("button",{type:"button",onClick:p,className:"fixed bottom-4 right-4 z-[79] btn btn-primary btn-sm shadow-lg",children:e("standalone.machine.awaitingInput")}),s.jsx(zp,{promptSession:a,isSubmitting:i,error:o,onSubmit:c,onCancel:d})]}):null}function OR(){const e=l.useMemo(()=>({sendCommand:La,sendData:Al,sendPtyInput:cg}),[]);return s.jsx(Eg,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(tb,{client:$R,children:s.jsx(FR,{children:s.jsx(vR,{children:s.jsx(nb,{value:e,children:s.jsxs(Pb,{sendDaemonCommand:La,children:[s.jsx(WR,{}),s.jsxs(jR,{children:[s.jsx(BR,{}),s.jsxs(_g,{children:[s.jsx(Bs,{path:"/dashboard",element:s.jsx(vI,{})}),s.jsx(Bs,{path:"/machine",element:s.jsx(op,{})}),s.jsx(Bs,{path:"/machines/:id",element:s.jsx(ML,{})}),s.jsx(Bs,{path:"/machines",element:s.jsx(op,{})}),s.jsx(Bs,{path:"/about",element:s.jsx(PR,{})}),s.jsx(Bs,{path:"/settings",element:s.jsx(IR,{})}),s.jsx(Bs,{path:"/mesh",element:s.jsx(rR,{children:s.jsx(nR,{})})}),s.jsx(Bs,{path:"/setup",element:s.jsx(NR,{})}),s.jsx(Bs,{path:"*",element:s.jsx(Fi,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}HC({connectionManager:As});Hg(document.getElementById("root")).render(s.jsx(OR,{}));