@mindexec/cli 0.2.380 → 0.2.382

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.
Files changed (20) hide show
  1. package/package.json +1 -1
  2. package/wwwroot/assets/{AdminDashboardPage-CS4O7czp.js → AdminDashboardPage-FNblYU8t.js} +1 -1
  3. package/wwwroot/assets/{AppSidebar-C39X2rK2.js → AppSidebar-BvftUzzb.js} +2 -2
  4. package/wwwroot/assets/{AuthPages-Cv8JGasI.js → AuthPages-D8C-Ozrp.js} +1 -1
  5. package/wwwroot/assets/{CodePage-CtcukAw7.js → CodePage-BGATDRar.js} +1 -1
  6. package/wwwroot/assets/{CompanyCorePage-CVw3X796.js → CompanyCorePage-Di4pU7hi.js} +1 -1
  7. package/wwwroot/assets/{ExecutionModePage-BxZvRmyD.js → ExecutionModePage-DUD0ObAq.js} +1 -1
  8. package/wwwroot/assets/MindCanvas-Bm3Wtjb6.js +49 -0
  9. package/wwwroot/assets/MindCanvas-DtqOZnoW.css +1 -0
  10. package/wwwroot/assets/{PlanMasterPage-juSUgUYZ.js → PlanMasterPage-FPAEsd3D.js} +1 -1
  11. package/wwwroot/assets/{PricingPage-_hfu-aoA.js → PricingPage-GyyNbudR.js} +1 -1
  12. package/wwwroot/assets/{ToolPages-n6d8tLbT.js → ToolPages-Zm_oC47S.js} +1 -1
  13. package/wwwroot/assets/{YouTubeSearchPage-52qOcKbo.js → YouTubeSearchPage-GghzHObU.js} +1 -1
  14. package/wwwroot/assets/{canvas-runtime-D3amtMwe.js → canvas-runtime-CF8ukxQK.js} +3 -3
  15. package/wwwroot/assets/{index-CRFVvbLN.js → index-Dp7yFpgv.js} +2 -2
  16. package/wwwroot/assets/{storage-RP5Dyxmq.js → storage-CcZMLcgs.js} +1 -1
  17. package/wwwroot/assets/{supabaseAuthAdapter-CuJuASQT.js → supabaseAuthAdapter-CjOxTXgI.js} +1 -1
  18. package/wwwroot/index.html +2 -2
  19. package/wwwroot/assets/MindCanvas-B21Tzcf1.js +0 -49
  20. package/wwwroot/assets/MindCanvas-Dbwuzfbv.css +0 -1
@@ -1,4 +1,4 @@
1
- import{r as p,j as a}from"./vendor-react-BXzpOyCS.js";import{R as g}from"./app-runtime-xD2Z3NdN.js";import{S as gi,L as fi,P as bi,I as ja,U as yi,a as ki,b as Ti,X as Po,K as ma,V as Ii,C as vi,B as Ci,c as ko,d as xi,e as wi,R as vo,f as rn,g as Si,M as Mi,h as Na,i as Da,j as Oa,k as _a,l as Ri,m as Fa,n as Pi,o as Ai,F as Ei,p as Li,H as ji,q as Ni,r as Di,s as Ba,t as Oi,G as _i,u as Fi,v as Bi,w as Gi,x as Ui,y as zi,T as $i,z as Vi}from"./vendor-icons-DE3gIReG.js";const Qe=Object.freeze({status:"/api/remote/status",devices:"/api/remote/devices",frames:"/api/remote/frames",hostTarget:"/api/remote/host-target",agentStatus:"/api/remote/agent/status",agentConnect:"/api/remote/agent/connect",agentDisconnect:"/api/remote/agent/disconnect",deviceTasksTemplate:"/api/remote/devices/{deviceId}/tasks",taskBatch:"/api/remote/tasks"}),Ga=Object.freeze({frames:"/api/remote/frames/ws",input:"/api/remote/input/ws"});function qi(e){return Qe.deviceTasksTemplate.replace("{deviceId}",encodeURIComponent(e))}function Ua(e){return $a(e==null?void 0:e.remoteFrameWsPath,Ga.frames)}function za(e){return $a(e==null?void 0:e.remoteInputWsPath,Ga.input)}function $a(e,t){return typeof e=="string"?e.trim():t}const Zo={},Wi="http://127.0.0.1:5147",Va="MindExec.AllowHostedLocalBridge",Ki=new Set(["4173","5173"]);function Qt(e){return e.replace(/\/+$/,"")}function Hi(){return((Zo==null?void 0:Zo.VITE_LOCAL_BRIDGE_URL)||"").trim()}function Xi(){if(typeof window>"u")return"";const{protocol:e,hostname:t,port:o,origin:n}=window.location,r=t.toLowerCase();return(e==="http:"||e==="https:")&&(r==="localhost"||r==="127.0.0.1"||r==="::1")&&o&&!Ki.has(o)?n:""}function j(){return Qt(Hi()||Xi()||Wi)}function Yi(){const e=window.location.hostname.toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"}function Qi(){try{return window.localStorage.getItem(Va)==="true"}catch{return!1}}function qa(e){try{e&&window.localStorage.setItem(Va,"true")}catch{}}function Pt(){return Yi()||Qi()}function Wa(e){const t=String((e==null?void 0:e.bridgeToken)||"").trim();if(t)return{header:(e==null?void 0:e.bridgeTokenHeader)||"X-Bridge-Token",token:t}}async function D(e,t,o={}){const n=new AbortController,r=window.setTimeout(()=>n.abort(),o.timeoutMs??4200),s=new Headers;s.set("Accept","application/json"),s.set("Cache-Control","no-store"),s.set("Pragma","no-cache"),o.body!==void 0&&s.set("Content-Type","application/json"),o.auth&&s.set(o.auth.header,o.auth.token);try{const c=await fetch(`${Qt(e)}${t}`,{method:o.method||(o.body===void 0?"GET":"POST"),headers:s,body:o.body===void 0?void 0:JSON.stringify(o.body),cache:"no-store",signal:n.signal}),m=await c.text(),l=m?JSON.parse(m):null;if(!c.ok){const b=(l==null?void 0:l.error)||(l==null?void 0:l.message)||`LocalBridge request failed: ${c.status}`;throw new Error(b)}return l}finally{window.clearTimeout(r)}}function Ji(e){return e instanceof DOMException&&e.name==="AbortError"?"LocalBridge probe timed out.":e instanceof SyntaxError?"LocalBridge returned a non-JSON response.":e instanceof Error?e.message||"LocalBridge is unavailable.":String(e||"LocalBridge is unavailable.")}async function In(e=j()){var t;try{const o=await D(e,"/api/status?refresh=1",{timeoutMs:4200});return g.emit("localBridge.status",{baseUrl:e,connected:!0,projectOpen:((t=o.project)==null?void 0:t.isOpen)===!0}),{state:"connected",baseUrl:e,status:o}}catch(o){const n=Ji(o);return g.emit("localBridge.status",{baseUrl:e,connected:!1,message:n}),{state:"unavailable",baseUrl:e,message:n}}}async function Qc(e,t=j()){return D(t,"/api/auth/session",{auth:e,timeoutMs:6500})}async function Jc(e,t,o=j()){return g.emit("localBridge.authSession.save.request",{baseUrl:o,hasContent:!!e.trim()}),D(o,"/api/auth/session",{method:"POST",body:{content:e},auth:t,timeoutMs:6500})}async function Zc(e,t=j()){return g.emit("localBridge.authSession.clear.request",{baseUrl:t}),D(t,"/api/auth/session",{method:"DELETE",auth:e,timeoutMs:6500})}async function ed(e,t,o=j()){return D(o,"/project/open",{method:"POST",body:{path:e},auth:t,timeoutMs:15e3})}async function td(e=j(),t=18,o=1200){var r,s;let n={state:"idle",baseUrl:e};for(let c=0;c<t;c+=1){if(n=await In(e),n.state==="connected"&&((s=(r=n.status)==null?void 0:r.project)!=null&&s.isOpen))return n;await new Promise(m=>{window.setTimeout(m,o)})}return n}async function od(e,t=j()){return D(t,"/project/symbols",{auth:e,timeoutMs:12e3})}async function nd(e,t=j()){return D(t,"/project/graph",{auth:e,timeoutMs:12e3})}async function ad(e="standard",t,o=j()){const n=`?level=${encodeURIComponent(e)}`;return D(o,`/project/ai-context${n}`,{auth:t,timeoutMs:14e3})}async function rd(e,t=j()){return g.emit("localBridge.codex.capabilities.request",{baseUrl:t}),D(t,"/api/codex/capabilities",{auth:e,timeoutMs:12e3})}async function id(e,t=j()){return g.emit("localBridge.modelCatalog.request",{baseUrl:t}),D(t,"/api/model-catalog",{auth:e,timeoutMs:16e3})}async function sd(e,t=5,o,n=j()){return g.emit("localBridge.web.search.request",{baseUrl:n,maxResults:t}),D(n,"/api/web/search",{method:"POST",body:{query:e,maxResults:t},auth:o,timeoutMs:24e3})}async function ld(e,t=6e3,o,n=j()){return g.emit("localBridge.web.fetch.request",{baseUrl:n,maxChars:t}),D(n,"/api/web/fetch",{method:"POST",body:{url:e,maxChars:t},auth:o,timeoutMs:24e3})}async function cd(e,t,o=j()){return g.emit("localBridge.browser.open.request",{baseUrl:o}),D(o,"/api/browser/open",{method:"POST",body:{url:e},auth:t,timeoutMs:24e3})}async function dd(e,t=4e3,o,n=j()){return g.emit("localBridge.browser.snapshot.request",{baseUrl:n,maxChars:t}),D(n,"/api/browser/snapshot",{method:"POST",body:{sessionId:e,maxChars:t},auth:o,timeoutMs:18e3})}async function ud(e,t="hero",o=3e3,n,r=j()){return g.emit("localBridge.browser.extract.request",{baseUrl:r,scope:t,maxChars:o}),D(r,"/api/browser/extract",{method:"POST",body:{sessionId:e,scope:t,maxChars:o},auth:n,timeoutMs:18e3})}async function pd(e,t,o=j()){return g.emit("localBridge.evidence.save.request",{baseUrl:o,kind:e.kind||"evidence"}),D(o,"/api/evidence/save",{method:"POST",body:e,auth:t,timeoutMs:18e3})}async function md(e,t,o=j()){var n;return g.emit("localBridge.concept.defineComposite.request",{baseUrl:o,hasSignature:!!((n=e.signature)!=null&&n.trim())}),D(o,"/api/concept/define-composite",{method:"POST",body:e,auth:t,timeoutMs:18e3})}async function hd(e,t=j()){return g.emit("localBridge.concept.status.request",{baseUrl:t}),D(t,"/api/concept/status",{method:"GET",auth:e,timeoutMs:12e3})}async function gd(e,t,o=j()){return g.emit("localBridge.concept.row.request",{baseUrl:o,id:e}),D(o,`/api/concept/row?id=${encodeURIComponent(e)}`,{method:"GET",auth:t,timeoutMs:12e3})}async function fd(e,t=j()){return g.emit("localBridge.concept.embed.readiness.request",{baseUrl:t}),D(t,"/api/concept/embed/readiness",{method:"GET",auth:e,timeoutMs:12e3})}async function bd(e,t=j()){return D(t,"/project/close",{method:"POST",auth:e,timeoutMs:12e3})}async function yd(e=j()){return D(e,"/api/workspace",{timeoutMs:4200})}async function kd(e,t,o=j()){return D(o,"/api/workspace/browse",{method:"POST",body:{initialPath:e||""},auth:t,timeoutMs:12e4})}async function Td(e,t,o=j()){return D(o,"/api/workspace/set",{method:"POST",body:{path:e},auth:t,timeoutMs:3e4})}async function Id(e,t,o=j()){return g.emit("localBridge.dir.list.request",{baseUrl:o}),D(o,"/api/dir/list",{method:"POST",body:{path:e},auth:t,timeoutMs:12e3})}async function vd(e=j()){return D(e,"/project/change-feed",{timeoutMs:4200})}async function Ka(e,t=j()){return D(t,Qe.status,{auth:e,timeoutMs:4200})}async function Zi(e,t=j()){return D(t,Qe.agentStatus,{auth:e,timeoutMs:4200})}async function Ha(e,t=j(),o={}){const n=o.includeDataUrl?"?includeDataUrl=true":"";return D(t,`${Qe.devices}${n}`,{auth:e,timeoutMs:6500})}async function Xa(e,t,o=j()){return D(o,Qe.frames,{method:"POST",body:{deviceIds:e,includeThumbnail:!0,includeLive:!0},auth:t,timeoutMs:6500})}async function ha(e,t,o,n=j(),r={}){return D(n,Qe.hostTarget,{method:"POST",body:{nodeId:e,enabled:t,leaseMs:r.leaseMs??6e4},auth:o,timeoutMs:6500})}async function es(e,t,o=j()){return D(o,Qe.agentConnect,{method:"POST",body:e,auth:t,timeoutMs:3e4})}async function ts(e="react-remote-monitor",t,o=j()){return D(o,Qe.agentDisconnect,{method:"POST",body:{reason:e},auth:t,timeoutMs:12e3})}async function Ya(e,t,o,n=j()){return D(n,qi(e),{method:"POST",body:t,auth:o,timeoutMs:12e3})}async function os(e,t,o=j()){return D(o,Qe.taskBatch,{method:"POST",body:e,auth:t,timeoutMs:16e3})}async function Cd(e,t=j()){const o=new URLSearchParams;return o.set("q",e.q),o.set("order",e.order||"relevance"),o.set("publishedWithin",e.publishedWithin||"any"),o.set("videoDuration",e.videoDuration||"any"),o.set("eventType",e.eventType||"any"),o.set("safeSearch",e.safeSearch||"moderate"),e.relevanceLanguage&&o.set("relevanceLanguage",e.relevanceLanguage),e.regionCode&&o.set("regionCode",e.regionCode),e.maxResults&&o.set("maxResults",String(e.maxResults)),e.pageToken&&o.set("pageToken",e.pageToken),D(t,`/api/youtube/search?${o.toString()}`,{timeoutMs:16e3})}function We(e){return`/api/company-core${e.startsWith("/")?e:`/${e}`}`}async function xd(e,t=j()){return g.emit("companyCore.bridge.request",{method:"GET",path:"/health"}),D(t,We("/health"),{auth:e,timeoutMs:6500})}async function wd(e,t=j()){return g.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies"}),D(t,We("/api/companies"),{auth:e,timeoutMs:12e3})}async function Sd(e=20,t,o=j()){const n=Math.max(1,Math.min(100,Math.round(e)));return g.emit("companyCore.bridge.request",{method:"GET",path:"/api/company-runs",limit:n}),D(o,We(`/api/company-runs?limit=${n}`),{auth:t,timeoutMs:12e3})}async function Md(e,t,o=j()){const n=encodeURIComponent(e);return g.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies/:id/snapshot"}),D(o,We(`/api/companies/${n}/snapshot`),{auth:t,timeoutMs:12e3})}async function Rd(e,t,o=j()){const n=encodeURIComponent(e);return g.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies/:id/approvals"}),D(o,We(`/api/companies/${n}/approvals?pendingOnly=false`),{auth:t,timeoutMs:12e3})}async function Pd(e,t,o=j()){const n=encodeURIComponent(e);return g.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies/:id/artifacts"}),D(o,We(`/api/companies/${n}/artifacts`),{auth:t,timeoutMs:12e3})}async function Ad(e,t,o=j()){const n=encodeURIComponent(e);return g.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies/:id/publishing-jobs"}),D(o,We(`/api/companies/${n}/publishing-jobs?limit=100`),{auth:t,timeoutMs:12e3})}async function Ed(e,t,o=j()){const n=encodeURIComponent(e);return g.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies/:id/growth"}),D(o,We(`/api/companies/${n}/growth?limit=100`),{auth:t,timeoutMs:12e3})}async function Ld(e,t,o=j()){const n=encodeURIComponent(e);return g.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies/:id/revenue"}),D(o,We(`/api/companies/${n}/revenue?limit=100`),{auth:t,timeoutMs:12e3})}async function jd(e,t,o=j()){const n=encodeURIComponent(e);return g.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies/:id/reflections"}),D(o,We(`/api/companies/${n}/reflections?limit=50`),{auth:t,timeoutMs:12e3})}async function Nd(e,t,o=j()){return D(o,"/api/codex/thread/run",{method:"POST",body:e,auth:t,timeoutMs:18e4})}async function Dd(e,t=j()){return D(t,"/api/file/read",{method:"POST",body:{path:e},timeoutMs:3e4})}async function Od(e,t=j()){const o=new AbortController,n=window.setTimeout(()=>o.abort(),3e4);try{const r=await fetch(`${Qt(t)}/api/file/read-raw?path=${encodeURIComponent(e)}`,{method:"GET",headers:{Accept:"application/octet-stream","Cache-Control":"no-store",Pragma:"no-cache"},cache:"no-store",signal:o.signal});if(!r.ok)throw new Error(`LocalBridge raw file read failed: ${r.status}`);return new Uint8Array(await r.arrayBuffer())}finally{window.clearTimeout(n)}}async function _d(e,t,o,n=j()){return D(n,"/api/file/write",{method:"POST",body:{path:e,content:t,encoding:"utf8"},auth:o,timeoutMs:3e4})}async function Fd(e,t,o,n=j()){const r=new AbortController,s=window.setTimeout(()=>r.abort(),3e4),c=new Headers;c.set("Accept","application/json"),c.set("Content-Type","application/octet-stream"),c.set("Cache-Control","no-store"),c.set("Pragma","no-cache"),c.set(o.header,o.token);try{const m=new ArrayBuffer(t.byteLength);new Uint8Array(m).set(t);const l=await fetch(`${Qt(n)}/api/file/write-raw?path=${encodeURIComponent(e)}`,{method:"PUT",headers:c,body:m,cache:"no-store",signal:r.signal}),b=await l.json().catch(()=>null);if(!l.ok){const k=(b==null?void 0:b.error)||(b==null?void 0:b.message)||`LocalBridge raw file write failed: ${l.status}`;throw new Error(k)}return b}finally{window.clearTimeout(s)}}async function Bd(e,t,o=j()){return D(o,"/api/file/delete",{method:"POST",body:{path:e},auth:t,timeoutMs:3e4})}function ns(e,t=j()){const o=String(e||"").trim();if(!o)return;if(/^https?:\/\//i.test(o)||o.startsWith("data:"))return o;const n=o.replace(/\\/g,"/").replace(/^\/+/,"");return`${Qt(t)}/${n}`}const rt="gpt-5.5",as="gemini-3-flash-preview",rs="llama3",Ao=[{id:"gpt-5.5",label:"GPT-5.5",provider:"codex"},{id:"gpt-5.4",label:"GPT-5.4",provider:"codex"},{id:"gpt-5.4-mini",label:"GPT-5.4 mini",provider:"codex"},{id:"gpt-5.3-codex-spark",label:"GPT-5.3 Codex Spark",provider:"codex"},{id:rs,label:"llama3",provider:"ollama"},{id:"llama3.2",label:"llama3.2",provider:"ollama"},{id:"openrouter/auto",label:"Auto Router",provider:"openrouter"},{id:"openai/gpt-chat-latest",label:"GPT Chat Latest",provider:"openrouter"},{id:"anthropic/claude-sonnet-4.5",label:"Claude Sonnet 4.5",provider:"openrouter"},{id:"google/gemini-2.5-pro",label:"Gemini 2.5 Pro",provider:"openrouter"},{id:"google/gemini-2.5-flash",label:"Gemini 2.5 Flash",provider:"openrouter"},{id:as,label:"Gemini 3 Flash Preview",provider:"gemini-cli"},{id:"gemini-3-pro-preview",label:"Gemini 3 Pro Preview",provider:"gemini-cli"},{id:"gemini-2.5-flash",label:"Gemini 2.5 Flash",provider:"gemini-cli"},{id:"gemini-2.5-pro",label:"Gemini 2.5 Pro",provider:"gemini-cli"},{id:"gemini-2.5-flash-lite-preview-06-17",label:"Gemini 2.5 Flash Lite Preview",provider:"gemini-cli"}],is=new Map([["",rt],["openai: gpt-4.1 mini",rt],["gpt-4.1 mini",rt],["gpt-5.3-codex",rt],["gpt-5.2",rt],["gpt-5.2-codex",rt]]);function Lt(e){const t=String(e??"").trim().replace(/^["']|["']$/g,""),o=t.toLowerCase();return is.get(o)??t}function ss(e){const t=Lt(e);return t.includes("/")||t.includes(":")}function ls(e,t=Ao){const o=Lt(e);return t.find(n=>n.id===o)??null}function Qa(e){switch(e){case"codex":return"Codex";case"ollama":return"Ollama";case"gemini-cli":return"Gemini CLI";case"openrouter":return"OpenRouter";default:return e}}function ho(e,t){const o=new Map(t.map((n,r)=>[n,r]));return e.map((n,r)=>({option:n,index:r})).filter(({option:n})=>o.has(n.provider)).sort((n,r)=>{const s=o.get(n.option.provider)??Number.MAX_SAFE_INTEGER,c=o.get(r.option.provider)??Number.MAX_SAFE_INTEGER;return s-c||n.index-r.index}).map(({option:n})=>n)}function cs(e,t=Ao){switch(e){case"Local Ollama":return ho(t,["ollama","openrouter"]);case"OpenAI Codex":return ho(t,["codex","openrouter"]);case"Gemini CLI":return ho(t,["gemini-cli"]);case"Managed Cloud":case"BYOK":default:return ho(t,["openrouter"])}}function Gd(...e){const t=new Map;for(const o of e)for(const n of o??[]){const r=Lt(n.id);if(!r)continue;const s=t.get(r);t.set(r,s?{...s,...n,id:r}:{...n,id:r})}return Array.from(t.values())}function ds(e){return e.startsWith("gemini-")?"gemini-cli":e.startsWith("llama")?"ollama":ss(e)?"openrouter":"codex"}function us(e,t=Ao){const o=e.aiProvider??"OpenAI Codex",n=cs(o,t),r=Lt(e.model);return r&&!n.some(s=>s.id===r)?[{id:r,label:`${r} (custom)`,provider:ds(r)},...n]:n}const vn="gpt-image-2",Cn="google/veo-2",ps="1:1",ms="16:9",Co="codex-image:",sn="codex:",hs=["1024x1024","1536x1024","1024x1536"],gs=[{id:"low",label:"Low"},{id:"medium",label:"Mid"},{id:"high",label:"High"}],fs=Ao.filter(e=>e.provider==="codex").flatMap(e=>gs.map(t=>({id:To(e.id,t.id),label:`Codex Image ${t.label} (${e.label})`,provider:"OpenAI Codex",mode:"Image",supportedSizes:hs}))),bs=[{id:"gpt-image-2",label:"GPT Image 2",provider:"OpenAI",mode:"Image",supportedSizes:["custom"]},{id:"Tongyi-MAI/Z-Image-Turbo:free",label:"Z-Image Turbo",provider:"ImageRouter",mode:"Image",supportedSizes:["custom"]},...fs],ys=[{id:"google/veo-2",label:"Google Veo 2",provider:"ImageRouter",mode:"Video",supportedSizes:["1280x720","720x1280"]},{id:"runway/gen-3",label:"Runway Gen-3",provider:"ImageRouter",mode:"Video",supportedSizes:["1280x720","720x1280"]}],Ja=[{id:"1:1",label:"1:1",ratio:1,size:"1024x1024",width:1024,height:1024},{id:"4:3",label:"4:3",ratio:4/3,size:"1152x864",width:1152,height:864},{id:"3:4",label:"3:4",ratio:3/4,size:"864x1152",width:864,height:1152},{id:"16:9",label:"16:9",ratio:16/9,size:"1280x720",width:1280,height:720},{id:"9:16",label:"9:16",ratio:9/16,size:"720x1280",width:720,height:1280}],xn={id:"auto",label:"Auto",resolvedSize:null,note:"Adapter decides the final render size."},ga=.16;function Eo(e,t){return(t==null?void 0:t[e])??(e==="Image"?bs:ys)}function Ud(e,...t){const o=new Map;for(const n of t)for(const r of n??[]){if(r.mode!==e)continue;const s=wn(e,r.id);if(!s)continue;const c=o.get(s);o.set(s,c?{...c,...r,id:s,mode:e}:{...r,id:s,mode:e})}return Array.from(o.values())}function wn(e,t){const o=Sn(t),n=e==="Image"?vn:Cn;if(!o)return n;if(e==="Image"){const r=Ts(o);if(r)return r;if(vs(o))return xs(o)}else{const r=Is(o);if(r)return r}return Mn(e,o)??o}function ln(e,t,o){const n=e==="Image"?t.imageRouterImageModel:t.imageRouterVideoModel,r=wn(e,n),s=e==="Image"?vn:Cn,c=Eo(e,o),m=c.find(l=>l.id===r)??c.find(l=>l.id===s);return m||{id:r??s,label:r??s,provider:"Saved",mode:e,supportedSizes:e==="Image"?["custom"]:[]}}function Za(e,t){if(e.supportedSizes.map(r=>r.toLowerCase()).includes("custom"))return fa(t);const n=e.supportedSizes.map(r=>ws(r)).filter(r=>!!r);return n.length>0?n:t==="Image"?fa(t):[xn]}function cn(e,t,o){const n=Za(t,e),r=e==="Image"?ps:ms;return n.find(s=>s.id===o)??n.find(s=>s.id===r)??n[0]??xn}function ks(e){switch(e){case"1:1":return"aspect-swatch--square";case"4:3":return"aspect-swatch--wide";case"3:4":return"aspect-swatch--portrait";case"16:9":return"aspect-swatch--cinema";case"9:16":return"aspect-swatch--vertical";default:return"aspect-swatch--auto"}}function dn(e){return e.resolvedSize??"auto"}function fa(e){const t=e==="Image"?"Image":"Video";return[xn,...Ja.map(o=>({id:o.id,label:o.label,resolvedSize:o.size,width:o.width,height:o.height,note:`${t} adapter hint: ${o.size}.`}))]}function Sn(e){return String(e??"").trim().replace(/^["']|["']$/g,"").trim()}function dt(e){return e.trim().toLowerCase().replace(/\s+/g," ")}function Ts(e){const t=dt(e);return["gpt-image-2","gpt image 2","gpt-image2","openai/gpt-image-2","openai:gpt-image-2","openai gpt-image-2","openai gpt image 2"].includes(t)?vn:["tongyi-mai/z-image-turbo:free","z-image-turbo","z-image turbo","z image turbo","image-router/z-image-turbo","imagerouter z-image turbo"].includes(t)?"Tongyi-MAI/Z-Image-Turbo:free":Mn("Image",e)}function Is(e){const t=dt(e);return["google/veo-2","google veo 2","google/veo2","google veo2","veo-2","veo2"].includes(t)?Cn:Mn("Video",e)}function Mn(e,t){const o=dt(t),n=Eo(e).find(r=>dt(r.id)===o||dt(r.label)===o);return(n==null?void 0:n.id)??null}function vs(e){const t=dt(e);return t.startsWith(Co)||t.startsWith(sn)||t.startsWith("codex image")}function Cs(e){const t=dt(Sn(e));return t==="low"?"low":t==="mid"||t==="medium"?"medium":t==="high"?"high":"medium"}function To(e,t){const o=Lt(e)||rt;return`${Co}${o}:${Cs(t)}`}function xs(e,t=rt){const o=Sn(e),n=dt(o);let r="";if(n.startsWith(Co)?r=o.slice(Co.length).trim():n.startsWith(sn)?r=o.slice(sn.length).trim():n.startsWith("codex image")&&(r=o.replace(/^codex\s+image\s*/i,"").trim()),!r)return To(t,"medium");const s=r.lastIndexOf(":");return s>0&&s<r.length-1?To(r.slice(0,s),r.slice(s+1)):To(t,r)}function ws(e){const t=Ss(e);if(!t)return null;const o=t.width/t.height,n=Ja.map(s=>({definition:s,delta:Math.abs(s.ratio-o)})).sort((s,c)=>s.delta-c.delta)[0];return{id:n&&n.delta<=ga?n.definition.id:`${t.width}:${t.height}`,label:n&&n.delta<=ga?n.definition.label:e,resolvedSize:`${t.width}x${t.height}`,width:t.width,height:t.height,note:`Model native size: ${t.width}x${t.height}.`}}function Ss(e){const t=e.trim().match(/^(\d{2,5})x(\d{2,5})$/i);if(!t)return null;const o=Number(t[1]),n=Number(t[2]);return!Number.isFinite(o)||!Number.isFinite(n)||o<=0||n<=0?null:{width:o,height:n}}const Ms=[{id:"blank",label:"New Mind Canvas",description:"완전히 빈 실행 캔버스를 새로 만듭니다.",iconClass:"fa-solid fa-plus",prompt:"생성할 보드를 선택하세요.",quickCreateTemplateId:"blank-core",options:[]},{id:"business",label:"Business",description:"아이디어를 수익 모델, MVP, 실행 계획으로 바꾸는 비즈니스 설계 보드를 만듭니다.",iconClass:"fa-solid fa-lightbulb",prompt:"어떤 비즈니스 구조로 시작할까요?",options:[{id:"saas",label:"SaaS",description:"구독형 SaaS 비즈니스",templateId:"business-core"},{id:"mobile",label:"모바일 앱",description:"앱 중심 실행 보드",templateId:"business-core"},{id:"automation",label:"AI 자동화",description:"자동화 서비스 구조",templateId:"business-core"},{id:"education",label:"교육 상품",description:"코스/강의형 사업",templateId:"business-core"},{id:"unknown",label:"아직 모름",description:"아이디어 탐색 중심",templateId:"business-core"}]},{id:"build",label:"Build",description:"PRD, 데이터, 결제, 배포까지 한 흐름으로 정리한 서비스 개발 보드를 만듭니다.",iconClass:"fa-solid fa-hammer",prompt:"어떤 방식으로 제품을 만들고 싶나요?",options:[{id:"webapp",label:"웹앱",description:"웹앱 MVP 빌드",templateId:"build-core"},{id:"saas_mvp",label:"SaaS MVP",description:"구독형 SaaS 출시",templateId:"build-core"},{id:"aitool",label:"AI 도구",description:"AI 기반 서비스 구현",templateId:"build-core"},{id:"internal",label:"내부 도구",description:"팀/개인 생산성 도구",templateId:"build-core"}]},{id:"launch",label:"Launch",description:"랜딩 카피, 채널 게시물, 일정까지 묶인 마케팅 런치 보드를 만듭니다.",iconClass:"fa-solid fa-bullhorn",prompt:"어떤 런치 흐름에 맞춰 보드를 만들까요?",options:[{id:"product_hunt",label:"Product Hunt",description:"런치 페이지 중심",templateId:"launch-core"},{id:"social",label:"X / LinkedIn",description:"소셜 런치 중심",templateId:"launch-core"},{id:"community",label:"커뮤니티",description:"커뮤니티 배포 중심",templateId:"launch-core"},{id:"demo",label:"데모 영상",description:"데모 자산 준비 중심",templateId:"launch-core"}]},{id:"more",label:"More",description:"콘텐츠, 학습, 책, 음악처럼 다음 확장용 실행 보드를 불러옵니다.",iconClass:"fa-solid fa-ellipsis",prompt:"다음으로 확장할 실행 보드를 골라보세요.",options:[{id:"content",label:"콘텐츠",description:"영상/콘텐츠 제작",templateId:"content-core"},{id:"learn",label:"학습",description:"출시형 학습 보드",templateId:"learn-core"},{id:"book",label:"책",description:"전자책/스토리 제작",templateId:"book-core"},{id:"music",label:"음악",description:"오디오 제작 스튜디오",templateId:"music-core"}]}],Rs=JSON.parse('[{"id":"blank-core","version":"0.1.0","tier":"core","status":"stable","boardTitle":"Canvas {{timestampShort}}","inputs":[],"nodes":[]},{"id":"business-core","version":"0.1.0","tier":"core","status":"stable","boardTitle":"비즈니스 설계 · {{optionLabel}}","inputs":[{"key":"businessIdea","type":"textarea","label":"어떤 비즈니스를 만들고 싶나요?","description":"한두 문장으로 해결하려는 문제와 아이디어를 적어보세요.","placeholder":"예: AI가 회의록을 정리하고 후속 업무를 자동으로 배정해주는 SaaS","required":true},{"key":"targetUser","type":"text","label":"주요 고객은 누구인가요?","description":"처음 돈을 낼 가능성이 큰 사용자군을 적어보세요.","placeholder":"예: 스타트업 팀 리드, 프리랜서 운영자"},{"key":"businessGoal","type":"select","label":"이번 보드의 목표","description":"지금 가장 먼저 해결하고 싶은 목표를 고르세요.","defaultValue":"validate","options":[{"value":"validate","label":"아이디어 검증"},{"value":"mvp","label":"MVP 설계"},{"value":"monetize","label":"수익화 설계"}]}],"nodes":[{"id":"idea","contentType":"memo","title":"사업 아이디어","body":"{{businessIdea}}","x":-520,"y":-40,"z":0,"width":360,"height":240,"metadata":{"memoColor":"amber","memoIcon":"lightbulb"}},{"id":"target","contentType":"note","title":"타깃 고객","body":"첫 고객 후보: {{targetUser}}\\n\\n1. 첫 고객군 3개\\n2. 각 고객의 급한 문제\\n3. 왜 지금 해결해야 하는지","x":-120,"y":-180,"z":0,"width":340,"height":220},{"id":"problem","contentType":"note","title":"문제 정의","body":"이번 목표는 {{businessGoal}}입니다.\\n불편함이 아니라 비용, 시간, 리스크처럼 돈이 되는 문제를 적어보세요.","x":280,"y":-180,"z":0,"width":340,"height":220},{"id":"revenue","contentType":"note","title":"수익 모델 후보","body":"구독 / 일회성 판매 / 크레딧 / 서비스형 결합 모델을 비교해보세요.","x":680,"y":-180,"z":0,"width":340,"height":220},{"id":"mvp","contentType":"note","title":"MVP 기능","body":"핵심 문제를 해결하는 기능만 3개 이하로 제한하세요.","x":-120,"y":120,"z":0,"width":340,"height":220},{"id":"pricing","contentType":"note","title":"가격 정책","body":"무료 체험, 기본 요금제, 업셀 지점을 함께 적어보세요.","x":280,"y":120,"z":0,"width":340,"height":220},{"id":"first100","contentType":"note","title":"첫 100명 전략","body":"직접 판매, 커뮤니티, 콘텐츠, 파트너십 중 가장 빠른 채널을 고르세요.","x":680,"y":120,"z":0,"width":340,"height":220},{"id":"plan7","contentType":"note","title":"7일 실행 계획","body":"오늘부터 7일 동안 해야 할 일만 날짜별로 적어 실행 가능한 일정으로 바꾸세요.","x":1080,"y":-20,"z":0,"width":340,"height":260}]},{"id":"build-core","version":"0.1.0","tier":"core","status":"stable","boardTitle":"서비스 개발 · {{productName}}","inputs":[{"key":"productName","type":"text","label":"무엇을 만들고 있나요?","description":"보드 상단과 노드에 바로 반영될 제품 이름을 적어보세요.","placeholder":"예: MeetingPilot","required":true},{"key":"productGoal","type":"textarea","label":"이번 MVP의 핵심 가치는 무엇인가요?","description":"사용자가 왜 이 제품을 써야 하는지 한두 문장으로 적어보세요.","placeholder":"예: 회의 후 5분 안에 실행 항목이 정리되도록 한다.","required":true},{"key":"stackOpinion","type":"select","label":"기본 빌드 흐름","description":"처음 버전에서 따라갈 구현 흐름을 고르세요.","defaultValue":"supabase-cloudflare","options":[{"value":"supabase-cloudflare","label":"Supabase + Cloudflare"},{"value":"webapp-default","label":"표준 웹앱 MVP"},{"value":"ai-tooling","label":"AI 도구 중심"}]}],"nodes":[{"id":"overview","contentType":"memo","title":"서비스 개요","body":"{{productName}}\\n\\n{{productGoal}}","x":-520,"y":-40,"z":0,"width":360,"height":240,"metadata":{"memoColor":"sky","memoIcon":"hammer"}},{"id":"prd","contentType":"note","title":"PRD","body":"제품: {{productName}}\\n문제, 사용자 흐름, 필수 기능, 제외 기능을 한 장으로 정리하세요.","x":-120,"y":-180,"z":0,"width":340,"height":220},{"id":"prompt","contentType":"note","title":"개발 프롬프트","body":"외부 개발 도구나 Codex에 넘길 구현 프롬프트 초안을 작성하세요.\\n기본 흐름: {{stackOpinion}}","x":280,"y":-180,"z":0,"width":340,"height":220},{"id":"db","contentType":"note","title":"DB 설계","body":"핵심 테이블, 관계, 최소 필수 컬럼만 먼저 정의하세요.","x":680,"y":-180,"z":0,"width":340,"height":220},{"id":"auth","contentType":"note","title":"Auth / 권한","body":"로그인, 역할, 온보딩, 접근 제어 시나리오를 적어보세요.","x":-120,"y":120,"z":0,"width":340,"height":220},{"id":"payment","contentType":"note","title":"결제 흐름","body":"요금제, 결제 성공/실패, 환불, 사용량 제한까지 연결하세요.","x":280,"y":120,"z":0,"width":340,"height":220},{"id":"deploy","contentType":"note","title":"배포 체크리스트","body":"환경 변수, 도메인, 모니터링, 오류 추적 준비 상태를 확인하세요.","x":680,"y":120,"z":0,"width":340,"height":220},{"id":"ops","contentType":"note","title":"운영 / 고객지원","body":"문의, 환불, 버그 리포트, 관리자 대시보드 항목을 정리하세요.","x":1080,"y":-180,"z":0,"width":340,"height":220},{"id":"qa","contentType":"note","title":"출시 전 QA","body":"결제, 로그인, 온보딩, 모바일 화면, 오류 복구 시나리오를 최종 점검하세요.","x":1080,"y":120,"z":0,"width":340,"height":220}]},{"id":"launch-core","version":"0.1.0","tier":"core","status":"stable","boardTitle":"마케팅 런치 · {{productName}}","inputs":[{"key":"productName","type":"text","label":"무엇을 홍보하나요?","description":"제품명이나 캠페인 이름을 적어보세요.","placeholder":"예: MeetingPilot","required":true},{"key":"targetAudience","type":"text","label":"주요 타깃은 누구인가요?","description":"메시지를 맞출 대표 사용자군을 적어보세요.","placeholder":"예: 스타트업 팀 리드, 솔로 파운더"},{"key":"launchGoal","type":"select","label":"이번 런치의 목표","description":"보드가 최우선으로 도와줄 목표를 고르세요.","defaultValue":"signups","options":[{"value":"signups","label":"가입 전환"},{"value":"waitlist","label":"대기자 확보"},{"value":"sales","label":"첫 결제 만들기"}]}],"nodes":[{"id":"positioning","contentType":"memo","title":"포지셔닝","body":"{{productName}}\\n주요 타깃: {{targetAudience}}\\n이번 목표: {{launchGoal}}","x":-520,"y":-40,"z":0,"width":360,"height":240,"metadata":{"memoColor":"rose","memoIcon":"bullhorn"}},{"id":"landing","contentType":"note","title":"랜딩페이지 카피","body":"헤드라인, 서브카피, CTA, 신뢰 요소를 빠르게 초안화하세요.","x":-120,"y":-180,"z":0,"width":340,"height":220},{"id":"channelCopy","contentType":"note","title":"채널별 소개문","body":"Product Hunt / X / LinkedIn / 커뮤니티용 소개문을 각각 다르게 써보세요.","x":280,"y":-180,"z":0,"width":340,"height":220},{"id":"community","contentType":"note","title":"커뮤니티 포스트","body":"홍보가 아니라 문제 해결 경험 공유 형태로 바꿔보세요.","x":680,"y":-180,"z":0,"width":340,"height":220},{"id":"demoChecklist","contentType":"note","title":"데모 영상 체크리스트","body":"문제 제시, 해결 시연, CTA 순서로 필요한 장면을 정리하세요.","x":-120,"y":120,"z":0,"width":340,"height":220},{"id":"assets","contentType":"note","title":"스크린샷 자산","body":"대표 화면, 비교 장면, 후기/증거 이미지를 수집하세요.","x":280,"y":120,"z":0,"width":340,"height":220},{"id":"schedule","contentType":"note","title":"배포 일정","body":"오늘, 내일, 일주일 안에 배포할 채널과 시간을 적어보세요.","x":680,"y":120,"z":0,"width":340,"height":220},{"id":"metrics","contentType":"note","title":"성과 기록","body":"방문, 가입, 결제, 반응이 좋았던 메시지를 한곳에 적재하세요.","x":1080,"y":-20,"z":0,"width":340,"height":260}]},{"id":"content-core","version":"0.1.0","tier":"preview","status":"experimental","boardTitle":"콘텐츠 제작 · {{contentTheme}}","inputs":[{"key":"contentTheme","type":"text","label":"무슨 콘텐츠를 만들까요?","description":"영상/게시물의 핵심 주제를 적어보세요.","placeholder":"예: AI 회의 요약 도구 소개 영상","required":true},{"key":"contentChannel","type":"select","label":"주요 채널","description":"초기 기획을 맞출 채널을 골라보세요.","defaultValue":"youtube","options":[{"value":"youtube","label":"YouTube"},{"value":"shorts","label":"Shorts / Reels"},{"value":"blog","label":"블로그 / 글"}]}],"nodes":[{"id":"contentPlan","contentType":"memo","title":"콘텐츠 기획","body":"{{contentTheme}}\\n주요 채널: {{contentChannel}}","x":-420,"y":-20,"z":0,"width":360,"height":240,"metadata":{"memoColor":"violet","memoIcon":"film"}},{"id":"script","contentType":"note","title":"대본","body":"오프닝 훅, 핵심 포인트, CTA를 써보세요.","x":0,"y":-160,"z":0,"width":340,"height":220},{"id":"scenes","contentType":"note","title":"장면 구성","body":"장면별 메시지와 필요한 시각 자료를 나누세요.","x":400,"y":-160,"z":0,"width":340,"height":220},{"id":"imagePrompts","contentType":"note","title":"이미지 프롬프트","body":"썸네일/컷신용 이미지 프롬프트를 작성하세요.","x":0,"y":120,"z":0,"width":340,"height":220},{"id":"videoPrompts","contentType":"note","title":"영상 프롬프트","body":"카메라 움직임, 분위기, 길이를 정의하세요.","x":400,"y":120,"z":0,"width":340,"height":220},{"id":"distribution","contentType":"note","title":"배포 체크","body":"제목, 설명, 썸네일, 업로드 일정까지 확인하세요.","x":800,"y":-20,"z":0,"width":340,"height":260}]},{"id":"learn-core","version":"0.1.0","tier":"preview","status":"experimental","boardTitle":"출시형 학습 · {{learningGoal}}","inputs":[{"key":"learningGoal","type":"text","label":"어떤 결과물을 목표로 배우나요?","description":"단순 문법보다 만들고 싶은 산출물을 적어보세요.","placeholder":"예: 첫 번째 SaaS MVP 출시","required":true}],"nodes":[{"id":"goal","contentType":"memo","title":"학습 목표","body":"{{learningGoal}}","x":-420,"y":-20,"z":0,"width":360,"height":240,"metadata":{"memoColor":"emerald","memoIcon":"graduation-cap"}},{"id":"basics","contentType":"note","title":"기초 개념","body":"지금 부족한 문법과 개념을 적어 우선순위를 정하세요.","x":0,"y":-160,"z":0,"width":340,"height":220},{"id":"smallFeature","contentType":"note","title":"작은 기능 만들기","body":"작게 끝낼 수 있는 기능 단위를 나누세요.","x":400,"y":-160,"z":0,"width":340,"height":220},{"id":"api","contentType":"note","title":"API 사용","body":"연동할 API와 테스트 시나리오를 정리하세요.","x":0,"y":120,"z":0,"width":340,"height":220},{"id":"dbAuth","contentType":"note","title":"DB / Auth","body":"저장 구조와 로그인 흐름을 간단히 설계하세요.","x":400,"y":120,"z":0,"width":340,"height":220},{"id":"ship","contentType":"note","title":"배포","body":"배포까지 필요한 최소 단계만 체크리스트로 적으세요.","x":800,"y":-20,"z":0,"width":340,"height":260}]},{"id":"book-core","version":"0.1.0","tier":"preview","status":"experimental","boardTitle":"책/전자책 · {{bookTopic}}","inputs":[{"key":"bookTopic","type":"text","label":"어떤 책을 만들까요?","description":"주제나 제목 초안을 적어보세요.","placeholder":"예: 솔로 파운더를 위한 AI 실행 가이드","required":true},{"key":"readerType","type":"text","label":"누구를 위한 책인가요?","description":"대표 독자층을 한 줄로 적어보세요.","placeholder":"예: 첫 제품을 만들려는 1인 창업자"}],"nodes":[{"id":"bookConcept","contentType":"memo","title":"책 컨셉","body":"{{bookTopic}}\\n대표 독자: {{readerType}}","x":-420,"y":-20,"z":0,"width":360,"height":240,"metadata":{"memoColor":"amber","memoIcon":"book-open"}},{"id":"toc","contentType":"note","title":"목차","body":"큰 장과 소장 흐름을 먼저 정리하세요.","x":0,"y":-160,"z":0,"width":340,"height":220},{"id":"chapters","contentType":"note","title":"챕터 초안","body":"핵심 메시지와 사례를 장별로 메모하세요.","x":400,"y":-160,"z":0,"width":340,"height":220},{"id":"cover","contentType":"note","title":"삽화 / 표지","body":"필요한 비주얼 자산 목록을 정리하세요.","x":0,"y":120,"z":0,"width":340,"height":220},{"id":"edit","contentType":"note","title":"교정 / 편집","body":"말투, 중복, 흐름, CTA 점검 포인트를 적으세요.","x":400,"y":120,"z":0,"width":340,"height":220},{"id":"export","contentType":"note","title":"Export","body":"PDF/EPUB/배포 채널까지 마무리 작업을 적으세요.","x":800,"y":-20,"z":0,"width":340,"height":260}]},{"id":"music-core","version":"0.1.0","tier":"preview","status":"experimental","boardTitle":"음악 제작 · {{trackMood}}","inputs":[{"key":"trackMood","type":"text","label":"어떤 분위기의 트랙을 만들까요?","description":"감정이나 사용 장면을 짧게 적어보세요.","placeholder":"예: 밤 작업용 로파이 집중 트랙","required":true},{"key":"musicGenre","type":"select","label":"기본 장르","description":"가장 가까운 출발 장르를 골라보세요.","defaultValue":"lofi","options":[{"value":"lofi","label":"Lo-fi"},{"value":"ambient","label":"Ambient"},{"value":"pop","label":"Pop"},{"value":"cinematic","label":"Cinematic"}]}],"nodes":[{"id":"musicConcept","contentType":"memo","title":"음악 컨셉","body":"{{trackMood}}\\n기본 장르: {{musicGenre}}","x":-420,"y":-20,"z":0,"width":360,"height":240,"metadata":{"memoColor":"pink","memoIcon":"music"}},{"id":"references","contentType":"note","title":"레퍼런스","body":"참고곡과 참고 포인트를 나열하세요.","x":0,"y":-160,"z":0,"width":340,"height":220},{"id":"vocals","contentType":"note","title":"보컬 / 악기","body":"보컬 타입과 핵심 악기 구성을 적어보세요.","x":400,"y":-160,"z":0,"width":340,"height":220},{"id":"lyrics","contentType":"note","title":"가사","body":"주제, 반복 훅, 금지 표현을 정리하세요.","x":0,"y":120,"z":0,"width":340,"height":220},{"id":"generationPrompt","contentType":"note","title":"생성 프롬프트","body":"음향, 구조, 분위기 지시문을 모아두세요.","x":400,"y":120,"z":0,"width":340,"height":220},{"id":"versions","contentType":"note","title":"버전 비교","body":"mp3 결과물과 수정 포인트를 기록하세요.","x":800,"y":-20,"z":0,"width":340,"height":260}]}]'),Ps={launchers:Ms,templates:Rs},ba={en:{"launcher.blank.title":"New Mind Canvas","launcher.blank.desc":"Create a clean execution canvas.","launcher.blank.prompt":"Choose the board you want to create.","launcher.business.title":"Business","launcher.business.desc":"Turn an idea into a revenue model, MVP, and execution plan.","launcher.business.prompt":"What business structure should we start with?","launcher.business.option.saas.title":"SaaS","launcher.business.option.saas.desc":"Subscription SaaS business","launcher.business.option.mobile.title":"Mobile App","launcher.business.option.mobile.desc":"Mobile-first execution board","launcher.business.option.automation.title":"AI Automation","launcher.business.option.automation.desc":"Automation service structure","launcher.business.option.education.title":"Education Product","launcher.business.option.education.desc":"Course or lecture business","launcher.business.option.unknown.title":"Not sure yet","launcher.business.option.unknown.desc":"Explore possible ideas","launcher.build.title":"Build","launcher.build.desc":"Organize a service build from PRD, data, billing, and deployment.","launcher.build.prompt":"What kind of product should we build?","launcher.build.option.webapp.title":"Web App","launcher.build.option.webapp.desc":"Build a web MVP","launcher.build.option.saas_mvp.title":"SaaS MVP","launcher.build.option.saas_mvp.desc":"Launch a subscription SaaS","launcher.build.option.aitool.title":"AI Tool","launcher.build.option.aitool.desc":"Implement an AI-powered service","launcher.build.option.internal.title":"Internal Tool","launcher.build.option.internal.desc":"Team or personal productivity tool","launcher.launch.title":"Launch","launcher.launch.desc":"Plan landing copy, channel posts, assets, and launch schedule.","launcher.launch.prompt":"What launch flow should we prepare?","launcher.launch.option.product_hunt.title":"Product Hunt","launcher.launch.option.product_hunt.desc":"Prepare a launch page","launcher.launch.option.social.title":"X / LinkedIn","launcher.launch.option.social.desc":"Plan social launch posts","launcher.launch.option.community.title":"Community","launcher.launch.option.community.desc":"Plan community distribution","launcher.launch.option.demo.title":"Demo Video","launcher.launch.option.demo.desc":"Prepare a demo asset","launcher.more.title":"More","launcher.more.desc":"Open more execution boards for content, learning, books, and music.","launcher.more.prompt":"Choose the next execution board.","launcher.more.option.content.title":"Content","launcher.more.option.content.desc":"Start video or content production","launcher.more.option.learn.title":"Learn","launcher.more.option.learn.desc":"Create a launch-focused learning board","launcher.more.option.book.title":"Book","launcher.more.option.book.desc":"Start an ebook or story board","launcher.more.option.music.title":"Music","launcher.more.option.music.desc":"Start an audio production studio","templateCard.eyebrow":"Template","templateCard.generate":"Generate","templateCard.noInputs":"No inputs needed.","templateCard.generating":"Generating nodes...","templateCard.generated":"Generated {0} nodes below.","templateCard.failed":"Template generation failed.","templateCard.required":"{0} is required.","template.blank-core.boardTitle":"Canvas {{timestampShort}}","template.business-core.boardTitle":"Business Design - {{optionLabel}}","template.business-core.input.businessIdea.label":"What business do you want to build?","template.business-core.input.businessIdea.desc":"Write the problem and idea you want to solve in one or two sentences.","template.business-core.input.businessIdea.placeholder":"Example: A SaaS that summarizes meetings and assigns follow-up work automatically","template.business-core.input.targetUser.label":"Who is the primary customer?","template.business-core.input.targetUser.desc":"Write the user group most likely to pay first.","template.business-core.input.targetUser.placeholder":"Example: startup team leads, freelance operators","template.business-core.input.businessGoal.label":"Goal for this board","template.business-core.input.businessGoal.desc":"Choose what you want to solve first.","template.business-core.input.businessGoal.option.validate":"Validate the idea","template.business-core.input.businessGoal.option.mvp":"Design the MVP","template.business-core.input.businessGoal.option.monetize":"Design monetization","template.business-core.node.idea.title":"Business Idea","template.business-core.node.idea.body":"{{businessIdea}}","template.business-core.node.target.title":"Target Customers","template.business-core.node.target.body":`First customer candidates: {{targetUser}}
1
+ import{r as p,j as a}from"./vendor-react-BXzpOyCS.js";import{R as h}from"./app-runtime-xD2Z3NdN.js";import{S as hi,L as fi,P as bi,I as ja,U as yi,a as ki,b as Ti,X as Po,K as ma,V as Ii,C as vi,B as Ci,c as ko,d as xi,e as wi,R as vo,f as rn,g as Si,M as Ri,h as Na,i as Da,j as Oa,k as _a,l as Mi,m as Fa,n as Pi,o as Ai,F as Ei,p as Li,H as ji,q as Ni,r as Di,s as Ba,t as Oi,G as _i,u as Fi,v as Bi,w as Gi,x as Ui,y as zi,T as $i,z as Vi}from"./vendor-icons-DE3gIReG.js";const Qe=Object.freeze({status:"/api/remote/status",devices:"/api/remote/devices",frames:"/api/remote/frames",hostTarget:"/api/remote/host-target",agentStatus:"/api/remote/agent/status",agentConnect:"/api/remote/agent/connect",agentDisconnect:"/api/remote/agent/disconnect",deviceTasksTemplate:"/api/remote/devices/{deviceId}/tasks",taskBatch:"/api/remote/tasks"}),Ga=Object.freeze({frames:"/api/remote/frames/ws",input:"/api/remote/input/ws"});function qi(e){return Qe.deviceTasksTemplate.replace("{deviceId}",encodeURIComponent(e))}function Ua(e){return $a(e==null?void 0:e.remoteFrameWsPath,Ga.frames)}function za(e){return $a(e==null?void 0:e.remoteInputWsPath,Ga.input)}function $a(e,t){return typeof e=="string"?e.trim():t}const Wi="pages";function Hi(e){const t=(e??"").trim().replace(/\/+$/g,"");if(!t)return"";if(!t.includes("://"))return t;try{const o=new URL(t);return`${o.protocol}//${o.host}`.replace(/\/+$/g,"")}catch{return t}}function Ki(e,t="0"){return`${Hi(e)}/api/status?mindexecOrigin=${Wi}&cb=${encodeURIComponent(t)}`}const Zo={},Xi="http://127.0.0.1:5147",Va="MindExec.AllowHostedLocalBridge",Yi=new Set(["4173","5173"]);function Qt(e){return e.replace(/\/+$/,"")}function Qi(){return((Zo==null?void 0:Zo.VITE_LOCAL_BRIDGE_URL)||"").trim()}function Ji(){if(typeof window>"u")return"";const{protocol:e,hostname:t,port:o,origin:n}=window.location,r=t.toLowerCase();return(e==="http:"||e==="https:")&&(r==="localhost"||r==="127.0.0.1"||r==="::1")&&o&&!Yi.has(o)?n:""}function j(){return Qt(Qi()||Ji()||Xi)}function Zi(){const e=window.location.hostname.toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"}function es(){try{return window.localStorage.getItem(Va)==="true"}catch{return!1}}function qa(e){try{e&&window.localStorage.setItem(Va,"true")}catch{}}function Pt(){return Zi()||es()}function Wa(e){const t=String((e==null?void 0:e.bridgeToken)||"").trim();if(t)return{header:(e==null?void 0:e.bridgeTokenHeader)||"X-Bridge-Token",token:t}}async function D(e,t,o={}){const n=new AbortController,r=window.setTimeout(()=>n.abort(),o.timeoutMs??4200),s=new Headers;s.set("Accept","application/json"),o.noCacheHeaders!==!1&&(s.set("Cache-Control","no-store"),s.set("Pragma","no-cache")),o.body!==void 0&&s.set("Content-Type","application/json"),o.auth&&s.set(o.auth.header,o.auth.token);try{const c=/^https?:\/\//i.test(t)?t:`${Qt(e)}${t}`,m=await fetch(c,{method:o.method||(o.body===void 0?"GET":"POST"),headers:s,body:o.body===void 0?void 0:JSON.stringify(o.body),cache:"no-store",signal:n.signal}),l=await m.text(),b=l?JSON.parse(l):null;if(!m.ok){const k=(b==null?void 0:b.error)||(b==null?void 0:b.message)||`LocalBridge request failed: ${m.status}`;throw new Error(k)}return b}finally{window.clearTimeout(r)}}function ts(e){return e instanceof DOMException&&e.name==="AbortError"?"LocalBridge probe timed out.":e instanceof SyntaxError?"LocalBridge returned a non-JSON response.":e instanceof TypeError&&/failed to fetch|network|cors/i.test(e.message)?"LocalBridge is unavailable or blocked by browser CORS/Private Network Access.":e instanceof Error?e.message||"LocalBridge is unavailable.":String(e||"LocalBridge is unavailable.")}async function In(e=j()){var t;try{const o=await D(e,Ki(e,Date.now().toString(36)),{timeoutMs:4200,noCacheHeaders:!1});return h.emit("localBridge.status",{baseUrl:e,connected:!0,projectOpen:((t=o.project)==null?void 0:t.isOpen)===!0}),{state:"connected",baseUrl:e,status:o}}catch(o){const n=ts(o);return h.emit("localBridge.status",{baseUrl:e,connected:!1,message:n}),{state:"unavailable",baseUrl:e,message:n}}}async function ed(e,t=j()){return D(t,"/api/auth/session",{auth:e,timeoutMs:6500})}async function td(e,t,o=j()){return h.emit("localBridge.authSession.save.request",{baseUrl:o,hasContent:!!e.trim()}),D(o,"/api/auth/session",{method:"POST",body:{content:e},auth:t,timeoutMs:6500})}async function od(e,t=j()){return h.emit("localBridge.authSession.clear.request",{baseUrl:t}),D(t,"/api/auth/session",{method:"DELETE",auth:e,timeoutMs:6500})}async function nd(e,t,o=j()){return D(o,"/project/open",{method:"POST",body:{path:e},auth:t,timeoutMs:15e3})}async function ad(e=j(),t=18,o=1200){var r,s;let n={state:"idle",baseUrl:e};for(let c=0;c<t;c+=1){if(n=await In(e),n.state==="connected"&&((s=(r=n.status)==null?void 0:r.project)!=null&&s.isOpen))return n;await new Promise(m=>{window.setTimeout(m,o)})}return n}async function rd(e,t=j()){return D(t,"/project/symbols",{auth:e,timeoutMs:12e3})}async function id(e,t=j()){return D(t,"/project/graph",{auth:e,timeoutMs:12e3})}async function sd(e="standard",t,o=j()){const n=`?level=${encodeURIComponent(e)}`;return D(o,`/project/ai-context${n}`,{auth:t,timeoutMs:14e3})}async function ld(e,t=j()){return h.emit("localBridge.codex.capabilities.request",{baseUrl:t}),D(t,"/api/codex/capabilities",{auth:e,timeoutMs:12e3})}async function cd(e,t=j()){return h.emit("localBridge.modelCatalog.request",{baseUrl:t}),D(t,"/api/model-catalog",{auth:e,timeoutMs:16e3})}async function dd(e,t=5,o,n=j()){return h.emit("localBridge.web.search.request",{baseUrl:n,maxResults:t}),D(n,"/api/web/search",{method:"POST",body:{query:e,maxResults:t},auth:o,timeoutMs:24e3})}async function ud(e,t=6e3,o,n=j()){return h.emit("localBridge.web.fetch.request",{baseUrl:n,maxChars:t}),D(n,"/api/web/fetch",{method:"POST",body:{url:e,maxChars:t},auth:o,timeoutMs:24e3})}async function pd(e,t,o=j()){return h.emit("localBridge.browser.open.request",{baseUrl:o}),D(o,"/api/browser/open",{method:"POST",body:{url:e},auth:t,timeoutMs:24e3})}async function md(e,t=4e3,o,n=j()){return h.emit("localBridge.browser.snapshot.request",{baseUrl:n,maxChars:t}),D(n,"/api/browser/snapshot",{method:"POST",body:{sessionId:e,maxChars:t},auth:o,timeoutMs:18e3})}async function gd(e,t="hero",o=3e3,n,r=j()){return h.emit("localBridge.browser.extract.request",{baseUrl:r,scope:t,maxChars:o}),D(r,"/api/browser/extract",{method:"POST",body:{sessionId:e,scope:t,maxChars:o},auth:n,timeoutMs:18e3})}async function hd(e,t,o=j()){return h.emit("localBridge.evidence.save.request",{baseUrl:o,kind:e.kind||"evidence"}),D(o,"/api/evidence/save",{method:"POST",body:e,auth:t,timeoutMs:18e3})}async function fd(e,t,o=j()){var n;return h.emit("localBridge.concept.defineComposite.request",{baseUrl:o,hasSignature:!!((n=e.signature)!=null&&n.trim())}),D(o,"/api/concept/define-composite",{method:"POST",body:e,auth:t,timeoutMs:18e3})}async function bd(e,t=j()){return h.emit("localBridge.concept.status.request",{baseUrl:t}),D(t,"/api/concept/status",{method:"GET",auth:e,timeoutMs:12e3})}async function yd(e,t,o=j()){return h.emit("localBridge.concept.row.request",{baseUrl:o,id:e}),D(o,`/api/concept/row?id=${encodeURIComponent(e)}`,{method:"GET",auth:t,timeoutMs:12e3})}async function kd(e,t=j()){return h.emit("localBridge.concept.embed.readiness.request",{baseUrl:t}),D(t,"/api/concept/embed/readiness",{method:"GET",auth:e,timeoutMs:12e3})}async function Td(e,t=j()){return D(t,"/project/close",{method:"POST",auth:e,timeoutMs:12e3})}async function Id(e=j()){return D(e,"/api/workspace",{timeoutMs:4200})}async function vd(e,t,o=j()){return D(o,"/api/workspace/browse",{method:"POST",body:{initialPath:e||""},auth:t,timeoutMs:12e4})}async function Cd(e,t,o=j()){return D(o,"/api/workspace/set",{method:"POST",body:{path:e},auth:t,timeoutMs:3e4})}async function xd(e,t,o=j()){return h.emit("localBridge.dir.list.request",{baseUrl:o}),D(o,"/api/dir/list",{method:"POST",body:{path:e},auth:t,timeoutMs:12e3})}async function wd(e=j()){return D(e,"/project/change-feed",{timeoutMs:4200})}async function Ha(e,t=j()){return D(t,Qe.status,{auth:e,timeoutMs:4200})}async function os(e,t=j()){return D(t,Qe.agentStatus,{auth:e,timeoutMs:4200})}async function Ka(e,t=j(),o={}){const n=o.includeDataUrl?"?includeDataUrl=true":"";return D(t,`${Qe.devices}${n}`,{auth:e,timeoutMs:6500})}async function Xa(e,t,o=j()){return D(o,Qe.frames,{method:"POST",body:{deviceIds:e,includeThumbnail:!0,includeLive:!0},auth:t,timeoutMs:6500})}async function ga(e,t,o,n=j(),r={}){return D(n,Qe.hostTarget,{method:"POST",body:{nodeId:e,enabled:t,leaseMs:r.leaseMs??6e4},auth:o,timeoutMs:6500})}async function ns(e,t,o=j()){return D(o,Qe.agentConnect,{method:"POST",body:e,auth:t,timeoutMs:3e4})}async function as(e="react-remote-monitor",t,o=j()){return D(o,Qe.agentDisconnect,{method:"POST",body:{reason:e},auth:t,timeoutMs:12e3})}async function Ya(e,t,o,n=j()){return D(n,qi(e),{method:"POST",body:t,auth:o,timeoutMs:12e3})}async function rs(e,t,o=j()){return D(o,Qe.taskBatch,{method:"POST",body:e,auth:t,timeoutMs:16e3})}async function Sd(e,t=j()){const o=new URLSearchParams;return o.set("q",e.q),o.set("order",e.order||"relevance"),o.set("publishedWithin",e.publishedWithin||"any"),o.set("videoDuration",e.videoDuration||"any"),o.set("eventType",e.eventType||"any"),o.set("safeSearch",e.safeSearch||"moderate"),e.relevanceLanguage&&o.set("relevanceLanguage",e.relevanceLanguage),e.regionCode&&o.set("regionCode",e.regionCode),e.maxResults&&o.set("maxResults",String(e.maxResults)),e.pageToken&&o.set("pageToken",e.pageToken),D(t,`/api/youtube/search?${o.toString()}`,{timeoutMs:16e3})}function We(e){return`/api/company-core${e.startsWith("/")?e:`/${e}`}`}async function Rd(e,t=j()){return h.emit("companyCore.bridge.request",{method:"GET",path:"/health"}),D(t,We("/health"),{auth:e,timeoutMs:6500})}async function Md(e,t=j()){return h.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies"}),D(t,We("/api/companies"),{auth:e,timeoutMs:12e3})}async function Pd(e=20,t,o=j()){const n=Math.max(1,Math.min(100,Math.round(e)));return h.emit("companyCore.bridge.request",{method:"GET",path:"/api/company-runs",limit:n}),D(o,We(`/api/company-runs?limit=${n}`),{auth:t,timeoutMs:12e3})}async function Ad(e,t,o=j()){const n=encodeURIComponent(e);return h.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies/:id/snapshot"}),D(o,We(`/api/companies/${n}/snapshot`),{auth:t,timeoutMs:12e3})}async function Ed(e,t,o=j()){const n=encodeURIComponent(e);return h.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies/:id/approvals"}),D(o,We(`/api/companies/${n}/approvals?pendingOnly=false`),{auth:t,timeoutMs:12e3})}async function Ld(e,t,o=j()){const n=encodeURIComponent(e);return h.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies/:id/artifacts"}),D(o,We(`/api/companies/${n}/artifacts`),{auth:t,timeoutMs:12e3})}async function jd(e,t,o=j()){const n=encodeURIComponent(e);return h.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies/:id/publishing-jobs"}),D(o,We(`/api/companies/${n}/publishing-jobs?limit=100`),{auth:t,timeoutMs:12e3})}async function Nd(e,t,o=j()){const n=encodeURIComponent(e);return h.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies/:id/growth"}),D(o,We(`/api/companies/${n}/growth?limit=100`),{auth:t,timeoutMs:12e3})}async function Dd(e,t,o=j()){const n=encodeURIComponent(e);return h.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies/:id/revenue"}),D(o,We(`/api/companies/${n}/revenue?limit=100`),{auth:t,timeoutMs:12e3})}async function Od(e,t,o=j()){const n=encodeURIComponent(e);return h.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies/:id/reflections"}),D(o,We(`/api/companies/${n}/reflections?limit=50`),{auth:t,timeoutMs:12e3})}async function _d(e,t,o=j()){return D(o,"/api/codex/thread/run",{method:"POST",body:e,auth:t,timeoutMs:18e4})}async function Fd(e,t=j()){return D(t,"/api/file/read",{method:"POST",body:{path:e},timeoutMs:3e4})}async function Bd(e,t=j()){const o=new AbortController,n=window.setTimeout(()=>o.abort(),3e4);try{const r=await fetch(`${Qt(t)}/api/file/read-raw?path=${encodeURIComponent(e)}`,{method:"GET",headers:{Accept:"application/octet-stream","Cache-Control":"no-store",Pragma:"no-cache"},cache:"no-store",signal:o.signal});if(!r.ok)throw new Error(`LocalBridge raw file read failed: ${r.status}`);return new Uint8Array(await r.arrayBuffer())}finally{window.clearTimeout(n)}}async function Gd(e,t,o,n=j()){return D(n,"/api/file/write",{method:"POST",body:{path:e,content:t,encoding:"utf8"},auth:o,timeoutMs:3e4})}async function Ud(e,t,o,n=j()){const r=new AbortController,s=window.setTimeout(()=>r.abort(),3e4),c=new Headers;c.set("Accept","application/json"),c.set("Content-Type","application/octet-stream"),c.set("Cache-Control","no-store"),c.set("Pragma","no-cache"),c.set(o.header,o.token);try{const m=new ArrayBuffer(t.byteLength);new Uint8Array(m).set(t);const l=await fetch(`${Qt(n)}/api/file/write-raw?path=${encodeURIComponent(e)}`,{method:"PUT",headers:c,body:m,cache:"no-store",signal:r.signal}),b=await l.json().catch(()=>null);if(!l.ok){const k=(b==null?void 0:b.error)||(b==null?void 0:b.message)||`LocalBridge raw file write failed: ${l.status}`;throw new Error(k)}return b}finally{window.clearTimeout(s)}}async function zd(e,t,o=j()){return D(o,"/api/file/delete",{method:"POST",body:{path:e},auth:t,timeoutMs:3e4})}function is(e,t=j()){const o=String(e||"").trim();if(!o)return;if(/^https?:\/\//i.test(o)||o.startsWith("data:"))return o;const n=o.replace(/\\/g,"/").replace(/^\/+/,"");return`${Qt(t)}/${n}`}const rt="gpt-5.5",ss="gemini-3-flash-preview",ls="llama3",Ao=[{id:"gpt-5.5",label:"GPT-5.5",provider:"codex"},{id:"gpt-5.4",label:"GPT-5.4",provider:"codex"},{id:"gpt-5.4-mini",label:"GPT-5.4 mini",provider:"codex"},{id:"gpt-5.3-codex-spark",label:"GPT-5.3 Codex Spark",provider:"codex"},{id:ls,label:"llama3",provider:"ollama"},{id:"llama3.2",label:"llama3.2",provider:"ollama"},{id:"openrouter/auto",label:"Auto Router",provider:"openrouter"},{id:"openai/gpt-chat-latest",label:"GPT Chat Latest",provider:"openrouter"},{id:"anthropic/claude-sonnet-4.5",label:"Claude Sonnet 4.5",provider:"openrouter"},{id:"google/gemini-2.5-pro",label:"Gemini 2.5 Pro",provider:"openrouter"},{id:"google/gemini-2.5-flash",label:"Gemini 2.5 Flash",provider:"openrouter"},{id:ss,label:"Gemini 3 Flash Preview",provider:"gemini-cli"},{id:"gemini-3-pro-preview",label:"Gemini 3 Pro Preview",provider:"gemini-cli"},{id:"gemini-2.5-flash",label:"Gemini 2.5 Flash",provider:"gemini-cli"},{id:"gemini-2.5-pro",label:"Gemini 2.5 Pro",provider:"gemini-cli"},{id:"gemini-2.5-flash-lite-preview-06-17",label:"Gemini 2.5 Flash Lite Preview",provider:"gemini-cli"}],cs=new Map([["",rt],["openai: gpt-4.1 mini",rt],["gpt-4.1 mini",rt],["gpt-5.3-codex",rt],["gpt-5.2",rt],["gpt-5.2-codex",rt]]);function Lt(e){const t=String(e??"").trim().replace(/^["']|["']$/g,""),o=t.toLowerCase();return cs.get(o)??t}function ds(e){const t=Lt(e);return t.includes("/")||t.includes(":")}function us(e,t=Ao){const o=Lt(e);return t.find(n=>n.id===o)??null}function Qa(e){switch(e){case"codex":return"Codex";case"ollama":return"Ollama";case"gemini-cli":return"Gemini CLI";case"openrouter":return"OpenRouter";default:return e}}function go(e,t){const o=new Map(t.map((n,r)=>[n,r]));return e.map((n,r)=>({option:n,index:r})).filter(({option:n})=>o.has(n.provider)).sort((n,r)=>{const s=o.get(n.option.provider)??Number.MAX_SAFE_INTEGER,c=o.get(r.option.provider)??Number.MAX_SAFE_INTEGER;return s-c||n.index-r.index}).map(({option:n})=>n)}function ps(e,t=Ao){switch(e){case"Local Ollama":return go(t,["ollama","openrouter"]);case"OpenAI Codex":return go(t,["codex","openrouter"]);case"Gemini CLI":return go(t,["gemini-cli"]);case"Managed Cloud":case"BYOK":default:return go(t,["openrouter"])}}function $d(...e){const t=new Map;for(const o of e)for(const n of o??[]){const r=Lt(n.id);if(!r)continue;const s=t.get(r);t.set(r,s?{...s,...n,id:r}:{...n,id:r})}return Array.from(t.values())}function ms(e){return e.startsWith("gemini-")?"gemini-cli":e.startsWith("llama")?"ollama":ds(e)?"openrouter":"codex"}function gs(e,t=Ao){const o=e.aiProvider??"OpenAI Codex",n=ps(o,t),r=Lt(e.model);return r&&!n.some(s=>s.id===r)?[{id:r,label:`${r} (custom)`,provider:ms(r)},...n]:n}const vn="gpt-image-2",Cn="google/veo-2",hs="1:1",fs="16:9",Co="codex-image:",sn="codex:",bs=["1024x1024","1536x1024","1024x1536"],ys=[{id:"low",label:"Low"},{id:"medium",label:"Mid"},{id:"high",label:"High"}],ks=Ao.filter(e=>e.provider==="codex").flatMap(e=>ys.map(t=>({id:To(e.id,t.id),label:`Codex Image ${t.label} (${e.label})`,provider:"OpenAI Codex",mode:"Image",supportedSizes:bs}))),Ts=[{id:"gpt-image-2",label:"GPT Image 2",provider:"OpenAI",mode:"Image",supportedSizes:["custom"]},{id:"Tongyi-MAI/Z-Image-Turbo:free",label:"Z-Image Turbo",provider:"ImageRouter",mode:"Image",supportedSizes:["custom"]},...ks],Is=[{id:"google/veo-2",label:"Google Veo 2",provider:"ImageRouter",mode:"Video",supportedSizes:["1280x720","720x1280"]},{id:"runway/gen-3",label:"Runway Gen-3",provider:"ImageRouter",mode:"Video",supportedSizes:["1280x720","720x1280"]}],Ja=[{id:"1:1",label:"1:1",ratio:1,size:"1024x1024",width:1024,height:1024},{id:"4:3",label:"4:3",ratio:4/3,size:"1152x864",width:1152,height:864},{id:"3:4",label:"3:4",ratio:3/4,size:"864x1152",width:864,height:1152},{id:"16:9",label:"16:9",ratio:16/9,size:"1280x720",width:1280,height:720},{id:"9:16",label:"9:16",ratio:9/16,size:"720x1280",width:720,height:1280}],xn={id:"auto",label:"Auto",resolvedSize:null,note:"Adapter decides the final render size."},ha=.16;function Eo(e,t){return(t==null?void 0:t[e])??(e==="Image"?Ts:Is)}function Vd(e,...t){const o=new Map;for(const n of t)for(const r of n??[]){if(r.mode!==e)continue;const s=wn(e,r.id);if(!s)continue;const c=o.get(s);o.set(s,c?{...c,...r,id:s,mode:e}:{...r,id:s,mode:e})}return Array.from(o.values())}function wn(e,t){const o=Sn(t),n=e==="Image"?vn:Cn;if(!o)return n;if(e==="Image"){const r=Cs(o);if(r)return r;if(ws(o))return Rs(o)}else{const r=xs(o);if(r)return r}return Rn(e,o)??o}function ln(e,t,o){const n=e==="Image"?t.imageRouterImageModel:t.imageRouterVideoModel,r=wn(e,n),s=e==="Image"?vn:Cn,c=Eo(e,o),m=c.find(l=>l.id===r)??c.find(l=>l.id===s);return m||{id:r??s,label:r??s,provider:"Saved",mode:e,supportedSizes:e==="Image"?["custom"]:[]}}function Za(e,t){if(e.supportedSizes.map(r=>r.toLowerCase()).includes("custom"))return fa(t);const n=e.supportedSizes.map(r=>Ms(r)).filter(r=>!!r);return n.length>0?n:t==="Image"?fa(t):[xn]}function cn(e,t,o){const n=Za(t,e),r=e==="Image"?hs:fs;return n.find(s=>s.id===o)??n.find(s=>s.id===r)??n[0]??xn}function vs(e){switch(e){case"1:1":return"aspect-swatch--square";case"4:3":return"aspect-swatch--wide";case"3:4":return"aspect-swatch--portrait";case"16:9":return"aspect-swatch--cinema";case"9:16":return"aspect-swatch--vertical";default:return"aspect-swatch--auto"}}function dn(e){return e.resolvedSize??"auto"}function fa(e){const t=e==="Image"?"Image":"Video";return[xn,...Ja.map(o=>({id:o.id,label:o.label,resolvedSize:o.size,width:o.width,height:o.height,note:`${t} adapter hint: ${o.size}.`}))]}function Sn(e){return String(e??"").trim().replace(/^["']|["']$/g,"").trim()}function dt(e){return e.trim().toLowerCase().replace(/\s+/g," ")}function Cs(e){const t=dt(e);return["gpt-image-2","gpt image 2","gpt-image2","openai/gpt-image-2","openai:gpt-image-2","openai gpt-image-2","openai gpt image 2"].includes(t)?vn:["tongyi-mai/z-image-turbo:free","z-image-turbo","z-image turbo","z image turbo","image-router/z-image-turbo","imagerouter z-image turbo"].includes(t)?"Tongyi-MAI/Z-Image-Turbo:free":Rn("Image",e)}function xs(e){const t=dt(e);return["google/veo-2","google veo 2","google/veo2","google veo2","veo-2","veo2"].includes(t)?Cn:Rn("Video",e)}function Rn(e,t){const o=dt(t),n=Eo(e).find(r=>dt(r.id)===o||dt(r.label)===o);return(n==null?void 0:n.id)??null}function ws(e){const t=dt(e);return t.startsWith(Co)||t.startsWith(sn)||t.startsWith("codex image")}function Ss(e){const t=dt(Sn(e));return t==="low"?"low":t==="mid"||t==="medium"?"medium":t==="high"?"high":"medium"}function To(e,t){const o=Lt(e)||rt;return`${Co}${o}:${Ss(t)}`}function Rs(e,t=rt){const o=Sn(e),n=dt(o);let r="";if(n.startsWith(Co)?r=o.slice(Co.length).trim():n.startsWith(sn)?r=o.slice(sn.length).trim():n.startsWith("codex image")&&(r=o.replace(/^codex\s+image\s*/i,"").trim()),!r)return To(t,"medium");const s=r.lastIndexOf(":");return s>0&&s<r.length-1?To(r.slice(0,s),r.slice(s+1)):To(t,r)}function Ms(e){const t=Ps(e);if(!t)return null;const o=t.width/t.height,n=Ja.map(s=>({definition:s,delta:Math.abs(s.ratio-o)})).sort((s,c)=>s.delta-c.delta)[0];return{id:n&&n.delta<=ha?n.definition.id:`${t.width}:${t.height}`,label:n&&n.delta<=ha?n.definition.label:e,resolvedSize:`${t.width}x${t.height}`,width:t.width,height:t.height,note:`Model native size: ${t.width}x${t.height}.`}}function Ps(e){const t=e.trim().match(/^(\d{2,5})x(\d{2,5})$/i);if(!t)return null;const o=Number(t[1]),n=Number(t[2]);return!Number.isFinite(o)||!Number.isFinite(n)||o<=0||n<=0?null:{width:o,height:n}}const As=[{id:"blank",label:"New Mind Canvas",description:"완전히 빈 실행 캔버스를 새로 만듭니다.",iconClass:"fa-solid fa-plus",prompt:"생성할 보드를 선택하세요.",quickCreateTemplateId:"blank-core",options:[]},{id:"business",label:"Business",description:"아이디어를 수익 모델, MVP, 실행 계획으로 바꾸는 비즈니스 설계 보드를 만듭니다.",iconClass:"fa-solid fa-lightbulb",prompt:"어떤 비즈니스 구조로 시작할까요?",options:[{id:"saas",label:"SaaS",description:"구독형 SaaS 비즈니스",templateId:"business-core"},{id:"mobile",label:"모바일 앱",description:"앱 중심 실행 보드",templateId:"business-core"},{id:"automation",label:"AI 자동화",description:"자동화 서비스 구조",templateId:"business-core"},{id:"education",label:"교육 상품",description:"코스/강의형 사업",templateId:"business-core"},{id:"unknown",label:"아직 모름",description:"아이디어 탐색 중심",templateId:"business-core"}]},{id:"build",label:"Build",description:"PRD, 데이터, 결제, 배포까지 한 흐름으로 정리한 서비스 개발 보드를 만듭니다.",iconClass:"fa-solid fa-hammer",prompt:"어떤 방식으로 제품을 만들고 싶나요?",options:[{id:"webapp",label:"웹앱",description:"웹앱 MVP 빌드",templateId:"build-core"},{id:"saas_mvp",label:"SaaS MVP",description:"구독형 SaaS 출시",templateId:"build-core"},{id:"aitool",label:"AI 도구",description:"AI 기반 서비스 구현",templateId:"build-core"},{id:"internal",label:"내부 도구",description:"팀/개인 생산성 도구",templateId:"build-core"}]},{id:"launch",label:"Launch",description:"랜딩 카피, 채널 게시물, 일정까지 묶인 마케팅 런치 보드를 만듭니다.",iconClass:"fa-solid fa-bullhorn",prompt:"어떤 런치 흐름에 맞춰 보드를 만들까요?",options:[{id:"product_hunt",label:"Product Hunt",description:"런치 페이지 중심",templateId:"launch-core"},{id:"social",label:"X / LinkedIn",description:"소셜 런치 중심",templateId:"launch-core"},{id:"community",label:"커뮤니티",description:"커뮤니티 배포 중심",templateId:"launch-core"},{id:"demo",label:"데모 영상",description:"데모 자산 준비 중심",templateId:"launch-core"}]},{id:"more",label:"More",description:"콘텐츠, 학습, 책, 음악처럼 다음 확장용 실행 보드를 불러옵니다.",iconClass:"fa-solid fa-ellipsis",prompt:"다음으로 확장할 실행 보드를 골라보세요.",options:[{id:"content",label:"콘텐츠",description:"영상/콘텐츠 제작",templateId:"content-core"},{id:"learn",label:"학습",description:"출시형 학습 보드",templateId:"learn-core"},{id:"book",label:"책",description:"전자책/스토리 제작",templateId:"book-core"},{id:"music",label:"음악",description:"오디오 제작 스튜디오",templateId:"music-core"}]}],Es=JSON.parse('[{"id":"blank-core","version":"0.1.0","tier":"core","status":"stable","boardTitle":"Canvas {{timestampShort}}","inputs":[],"nodes":[]},{"id":"business-core","version":"0.1.0","tier":"core","status":"stable","boardTitle":"비즈니스 설계 · {{optionLabel}}","inputs":[{"key":"businessIdea","type":"textarea","label":"어떤 비즈니스를 만들고 싶나요?","description":"한두 문장으로 해결하려는 문제와 아이디어를 적어보세요.","placeholder":"예: AI가 회의록을 정리하고 후속 업무를 자동으로 배정해주는 SaaS","required":true},{"key":"targetUser","type":"text","label":"주요 고객은 누구인가요?","description":"처음 돈을 낼 가능성이 큰 사용자군을 적어보세요.","placeholder":"예: 스타트업 팀 리드, 프리랜서 운영자"},{"key":"businessGoal","type":"select","label":"이번 보드의 목표","description":"지금 가장 먼저 해결하고 싶은 목표를 고르세요.","defaultValue":"validate","options":[{"value":"validate","label":"아이디어 검증"},{"value":"mvp","label":"MVP 설계"},{"value":"monetize","label":"수익화 설계"}]}],"nodes":[{"id":"idea","contentType":"memo","title":"사업 아이디어","body":"{{businessIdea}}","x":-520,"y":-40,"z":0,"width":360,"height":240,"metadata":{"memoColor":"amber","memoIcon":"lightbulb"}},{"id":"target","contentType":"note","title":"타깃 고객","body":"첫 고객 후보: {{targetUser}}\\n\\n1. 첫 고객군 3개\\n2. 각 고객의 급한 문제\\n3. 왜 지금 해결해야 하는지","x":-120,"y":-180,"z":0,"width":340,"height":220},{"id":"problem","contentType":"note","title":"문제 정의","body":"이번 목표는 {{businessGoal}}입니다.\\n불편함이 아니라 비용, 시간, 리스크처럼 돈이 되는 문제를 적어보세요.","x":280,"y":-180,"z":0,"width":340,"height":220},{"id":"revenue","contentType":"note","title":"수익 모델 후보","body":"구독 / 일회성 판매 / 크레딧 / 서비스형 결합 모델을 비교해보세요.","x":680,"y":-180,"z":0,"width":340,"height":220},{"id":"mvp","contentType":"note","title":"MVP 기능","body":"핵심 문제를 해결하는 기능만 3개 이하로 제한하세요.","x":-120,"y":120,"z":0,"width":340,"height":220},{"id":"pricing","contentType":"note","title":"가격 정책","body":"무료 체험, 기본 요금제, 업셀 지점을 함께 적어보세요.","x":280,"y":120,"z":0,"width":340,"height":220},{"id":"first100","contentType":"note","title":"첫 100명 전략","body":"직접 판매, 커뮤니티, 콘텐츠, 파트너십 중 가장 빠른 채널을 고르세요.","x":680,"y":120,"z":0,"width":340,"height":220},{"id":"plan7","contentType":"note","title":"7일 실행 계획","body":"오늘부터 7일 동안 해야 할 일만 날짜별로 적어 실행 가능한 일정으로 바꾸세요.","x":1080,"y":-20,"z":0,"width":340,"height":260}]},{"id":"build-core","version":"0.1.0","tier":"core","status":"stable","boardTitle":"서비스 개발 · {{productName}}","inputs":[{"key":"productName","type":"text","label":"무엇을 만들고 있나요?","description":"보드 상단과 노드에 바로 반영될 제품 이름을 적어보세요.","placeholder":"예: MeetingPilot","required":true},{"key":"productGoal","type":"textarea","label":"이번 MVP의 핵심 가치는 무엇인가요?","description":"사용자가 왜 이 제품을 써야 하는지 한두 문장으로 적어보세요.","placeholder":"예: 회의 후 5분 안에 실행 항목이 정리되도록 한다.","required":true},{"key":"stackOpinion","type":"select","label":"기본 빌드 흐름","description":"처음 버전에서 따라갈 구현 흐름을 고르세요.","defaultValue":"supabase-cloudflare","options":[{"value":"supabase-cloudflare","label":"Supabase + Cloudflare"},{"value":"webapp-default","label":"표준 웹앱 MVP"},{"value":"ai-tooling","label":"AI 도구 중심"}]}],"nodes":[{"id":"overview","contentType":"memo","title":"서비스 개요","body":"{{productName}}\\n\\n{{productGoal}}","x":-520,"y":-40,"z":0,"width":360,"height":240,"metadata":{"memoColor":"sky","memoIcon":"hammer"}},{"id":"prd","contentType":"note","title":"PRD","body":"제품: {{productName}}\\n문제, 사용자 흐름, 필수 기능, 제외 기능을 한 장으로 정리하세요.","x":-120,"y":-180,"z":0,"width":340,"height":220},{"id":"prompt","contentType":"note","title":"개발 프롬프트","body":"외부 개발 도구나 Codex에 넘길 구현 프롬프트 초안을 작성하세요.\\n기본 흐름: {{stackOpinion}}","x":280,"y":-180,"z":0,"width":340,"height":220},{"id":"db","contentType":"note","title":"DB 설계","body":"핵심 테이블, 관계, 최소 필수 컬럼만 먼저 정의하세요.","x":680,"y":-180,"z":0,"width":340,"height":220},{"id":"auth","contentType":"note","title":"Auth / 권한","body":"로그인, 역할, 온보딩, 접근 제어 시나리오를 적어보세요.","x":-120,"y":120,"z":0,"width":340,"height":220},{"id":"payment","contentType":"note","title":"결제 흐름","body":"요금제, 결제 성공/실패, 환불, 사용량 제한까지 연결하세요.","x":280,"y":120,"z":0,"width":340,"height":220},{"id":"deploy","contentType":"note","title":"배포 체크리스트","body":"환경 변수, 도메인, 모니터링, 오류 추적 준비 상태를 확인하세요.","x":680,"y":120,"z":0,"width":340,"height":220},{"id":"ops","contentType":"note","title":"운영 / 고객지원","body":"문의, 환불, 버그 리포트, 관리자 대시보드 항목을 정리하세요.","x":1080,"y":-180,"z":0,"width":340,"height":220},{"id":"qa","contentType":"note","title":"출시 전 QA","body":"결제, 로그인, 온보딩, 모바일 화면, 오류 복구 시나리오를 최종 점검하세요.","x":1080,"y":120,"z":0,"width":340,"height":220}]},{"id":"launch-core","version":"0.1.0","tier":"core","status":"stable","boardTitle":"마케팅 런치 · {{productName}}","inputs":[{"key":"productName","type":"text","label":"무엇을 홍보하나요?","description":"제품명이나 캠페인 이름을 적어보세요.","placeholder":"예: MeetingPilot","required":true},{"key":"targetAudience","type":"text","label":"주요 타깃은 누구인가요?","description":"메시지를 맞출 대표 사용자군을 적어보세요.","placeholder":"예: 스타트업 팀 리드, 솔로 파운더"},{"key":"launchGoal","type":"select","label":"이번 런치의 목표","description":"보드가 최우선으로 도와줄 목표를 고르세요.","defaultValue":"signups","options":[{"value":"signups","label":"가입 전환"},{"value":"waitlist","label":"대기자 확보"},{"value":"sales","label":"첫 결제 만들기"}]}],"nodes":[{"id":"positioning","contentType":"memo","title":"포지셔닝","body":"{{productName}}\\n주요 타깃: {{targetAudience}}\\n이번 목표: {{launchGoal}}","x":-520,"y":-40,"z":0,"width":360,"height":240,"metadata":{"memoColor":"rose","memoIcon":"bullhorn"}},{"id":"landing","contentType":"note","title":"랜딩페이지 카피","body":"헤드라인, 서브카피, CTA, 신뢰 요소를 빠르게 초안화하세요.","x":-120,"y":-180,"z":0,"width":340,"height":220},{"id":"channelCopy","contentType":"note","title":"채널별 소개문","body":"Product Hunt / X / LinkedIn / 커뮤니티용 소개문을 각각 다르게 써보세요.","x":280,"y":-180,"z":0,"width":340,"height":220},{"id":"community","contentType":"note","title":"커뮤니티 포스트","body":"홍보가 아니라 문제 해결 경험 공유 형태로 바꿔보세요.","x":680,"y":-180,"z":0,"width":340,"height":220},{"id":"demoChecklist","contentType":"note","title":"데모 영상 체크리스트","body":"문제 제시, 해결 시연, CTA 순서로 필요한 장면을 정리하세요.","x":-120,"y":120,"z":0,"width":340,"height":220},{"id":"assets","contentType":"note","title":"스크린샷 자산","body":"대표 화면, 비교 장면, 후기/증거 이미지를 수집하세요.","x":280,"y":120,"z":0,"width":340,"height":220},{"id":"schedule","contentType":"note","title":"배포 일정","body":"오늘, 내일, 일주일 안에 배포할 채널과 시간을 적어보세요.","x":680,"y":120,"z":0,"width":340,"height":220},{"id":"metrics","contentType":"note","title":"성과 기록","body":"방문, 가입, 결제, 반응이 좋았던 메시지를 한곳에 적재하세요.","x":1080,"y":-20,"z":0,"width":340,"height":260}]},{"id":"content-core","version":"0.1.0","tier":"preview","status":"experimental","boardTitle":"콘텐츠 제작 · {{contentTheme}}","inputs":[{"key":"contentTheme","type":"text","label":"무슨 콘텐츠를 만들까요?","description":"영상/게시물의 핵심 주제를 적어보세요.","placeholder":"예: AI 회의 요약 도구 소개 영상","required":true},{"key":"contentChannel","type":"select","label":"주요 채널","description":"초기 기획을 맞출 채널을 골라보세요.","defaultValue":"youtube","options":[{"value":"youtube","label":"YouTube"},{"value":"shorts","label":"Shorts / Reels"},{"value":"blog","label":"블로그 / 글"}]}],"nodes":[{"id":"contentPlan","contentType":"memo","title":"콘텐츠 기획","body":"{{contentTheme}}\\n주요 채널: {{contentChannel}}","x":-420,"y":-20,"z":0,"width":360,"height":240,"metadata":{"memoColor":"violet","memoIcon":"film"}},{"id":"script","contentType":"note","title":"대본","body":"오프닝 훅, 핵심 포인트, CTA를 써보세요.","x":0,"y":-160,"z":0,"width":340,"height":220},{"id":"scenes","contentType":"note","title":"장면 구성","body":"장면별 메시지와 필요한 시각 자료를 나누세요.","x":400,"y":-160,"z":0,"width":340,"height":220},{"id":"imagePrompts","contentType":"note","title":"이미지 프롬프트","body":"썸네일/컷신용 이미지 프롬프트를 작성하세요.","x":0,"y":120,"z":0,"width":340,"height":220},{"id":"videoPrompts","contentType":"note","title":"영상 프롬프트","body":"카메라 움직임, 분위기, 길이를 정의하세요.","x":400,"y":120,"z":0,"width":340,"height":220},{"id":"distribution","contentType":"note","title":"배포 체크","body":"제목, 설명, 썸네일, 업로드 일정까지 확인하세요.","x":800,"y":-20,"z":0,"width":340,"height":260}]},{"id":"learn-core","version":"0.1.0","tier":"preview","status":"experimental","boardTitle":"출시형 학습 · {{learningGoal}}","inputs":[{"key":"learningGoal","type":"text","label":"어떤 결과물을 목표로 배우나요?","description":"단순 문법보다 만들고 싶은 산출물을 적어보세요.","placeholder":"예: 첫 번째 SaaS MVP 출시","required":true}],"nodes":[{"id":"goal","contentType":"memo","title":"학습 목표","body":"{{learningGoal}}","x":-420,"y":-20,"z":0,"width":360,"height":240,"metadata":{"memoColor":"emerald","memoIcon":"graduation-cap"}},{"id":"basics","contentType":"note","title":"기초 개념","body":"지금 부족한 문법과 개념을 적어 우선순위를 정하세요.","x":0,"y":-160,"z":0,"width":340,"height":220},{"id":"smallFeature","contentType":"note","title":"작은 기능 만들기","body":"작게 끝낼 수 있는 기능 단위를 나누세요.","x":400,"y":-160,"z":0,"width":340,"height":220},{"id":"api","contentType":"note","title":"API 사용","body":"연동할 API와 테스트 시나리오를 정리하세요.","x":0,"y":120,"z":0,"width":340,"height":220},{"id":"dbAuth","contentType":"note","title":"DB / Auth","body":"저장 구조와 로그인 흐름을 간단히 설계하세요.","x":400,"y":120,"z":0,"width":340,"height":220},{"id":"ship","contentType":"note","title":"배포","body":"배포까지 필요한 최소 단계만 체크리스트로 적으세요.","x":800,"y":-20,"z":0,"width":340,"height":260}]},{"id":"book-core","version":"0.1.0","tier":"preview","status":"experimental","boardTitle":"책/전자책 · {{bookTopic}}","inputs":[{"key":"bookTopic","type":"text","label":"어떤 책을 만들까요?","description":"주제나 제목 초안을 적어보세요.","placeholder":"예: 솔로 파운더를 위한 AI 실행 가이드","required":true},{"key":"readerType","type":"text","label":"누구를 위한 책인가요?","description":"대표 독자층을 한 줄로 적어보세요.","placeholder":"예: 첫 제품을 만들려는 1인 창업자"}],"nodes":[{"id":"bookConcept","contentType":"memo","title":"책 컨셉","body":"{{bookTopic}}\\n대표 독자: {{readerType}}","x":-420,"y":-20,"z":0,"width":360,"height":240,"metadata":{"memoColor":"amber","memoIcon":"book-open"}},{"id":"toc","contentType":"note","title":"목차","body":"큰 장과 소장 흐름을 먼저 정리하세요.","x":0,"y":-160,"z":0,"width":340,"height":220},{"id":"chapters","contentType":"note","title":"챕터 초안","body":"핵심 메시지와 사례를 장별로 메모하세요.","x":400,"y":-160,"z":0,"width":340,"height":220},{"id":"cover","contentType":"note","title":"삽화 / 표지","body":"필요한 비주얼 자산 목록을 정리하세요.","x":0,"y":120,"z":0,"width":340,"height":220},{"id":"edit","contentType":"note","title":"교정 / 편집","body":"말투, 중복, 흐름, CTA 점검 포인트를 적으세요.","x":400,"y":120,"z":0,"width":340,"height":220},{"id":"export","contentType":"note","title":"Export","body":"PDF/EPUB/배포 채널까지 마무리 작업을 적으세요.","x":800,"y":-20,"z":0,"width":340,"height":260}]},{"id":"music-core","version":"0.1.0","tier":"preview","status":"experimental","boardTitle":"음악 제작 · {{trackMood}}","inputs":[{"key":"trackMood","type":"text","label":"어떤 분위기의 트랙을 만들까요?","description":"감정이나 사용 장면을 짧게 적어보세요.","placeholder":"예: 밤 작업용 로파이 집중 트랙","required":true},{"key":"musicGenre","type":"select","label":"기본 장르","description":"가장 가까운 출발 장르를 골라보세요.","defaultValue":"lofi","options":[{"value":"lofi","label":"Lo-fi"},{"value":"ambient","label":"Ambient"},{"value":"pop","label":"Pop"},{"value":"cinematic","label":"Cinematic"}]}],"nodes":[{"id":"musicConcept","contentType":"memo","title":"음악 컨셉","body":"{{trackMood}}\\n기본 장르: {{musicGenre}}","x":-420,"y":-20,"z":0,"width":360,"height":240,"metadata":{"memoColor":"pink","memoIcon":"music"}},{"id":"references","contentType":"note","title":"레퍼런스","body":"참고곡과 참고 포인트를 나열하세요.","x":0,"y":-160,"z":0,"width":340,"height":220},{"id":"vocals","contentType":"note","title":"보컬 / 악기","body":"보컬 타입과 핵심 악기 구성을 적어보세요.","x":400,"y":-160,"z":0,"width":340,"height":220},{"id":"lyrics","contentType":"note","title":"가사","body":"주제, 반복 훅, 금지 표현을 정리하세요.","x":0,"y":120,"z":0,"width":340,"height":220},{"id":"generationPrompt","contentType":"note","title":"생성 프롬프트","body":"음향, 구조, 분위기 지시문을 모아두세요.","x":400,"y":120,"z":0,"width":340,"height":220},{"id":"versions","contentType":"note","title":"버전 비교","body":"mp3 결과물과 수정 포인트를 기록하세요.","x":800,"y":-20,"z":0,"width":340,"height":260}]}]'),Ls={launchers:As,templates:Es},ba={en:{"launcher.blank.title":"New Mind Canvas","launcher.blank.desc":"Create a clean execution canvas.","launcher.blank.prompt":"Choose the board you want to create.","launcher.business.title":"Business","launcher.business.desc":"Turn an idea into a revenue model, MVP, and execution plan.","launcher.business.prompt":"What business structure should we start with?","launcher.business.option.saas.title":"SaaS","launcher.business.option.saas.desc":"Subscription SaaS business","launcher.business.option.mobile.title":"Mobile App","launcher.business.option.mobile.desc":"Mobile-first execution board","launcher.business.option.automation.title":"AI Automation","launcher.business.option.automation.desc":"Automation service structure","launcher.business.option.education.title":"Education Product","launcher.business.option.education.desc":"Course or lecture business","launcher.business.option.unknown.title":"Not sure yet","launcher.business.option.unknown.desc":"Explore possible ideas","launcher.build.title":"Build","launcher.build.desc":"Organize a service build from PRD, data, billing, and deployment.","launcher.build.prompt":"What kind of product should we build?","launcher.build.option.webapp.title":"Web App","launcher.build.option.webapp.desc":"Build a web MVP","launcher.build.option.saas_mvp.title":"SaaS MVP","launcher.build.option.saas_mvp.desc":"Launch a subscription SaaS","launcher.build.option.aitool.title":"AI Tool","launcher.build.option.aitool.desc":"Implement an AI-powered service","launcher.build.option.internal.title":"Internal Tool","launcher.build.option.internal.desc":"Team or personal productivity tool","launcher.launch.title":"Launch","launcher.launch.desc":"Plan landing copy, channel posts, assets, and launch schedule.","launcher.launch.prompt":"What launch flow should we prepare?","launcher.launch.option.product_hunt.title":"Product Hunt","launcher.launch.option.product_hunt.desc":"Prepare a launch page","launcher.launch.option.social.title":"X / LinkedIn","launcher.launch.option.social.desc":"Plan social launch posts","launcher.launch.option.community.title":"Community","launcher.launch.option.community.desc":"Plan community distribution","launcher.launch.option.demo.title":"Demo Video","launcher.launch.option.demo.desc":"Prepare a demo asset","launcher.more.title":"More","launcher.more.desc":"Open more execution boards for content, learning, books, and music.","launcher.more.prompt":"Choose the next execution board.","launcher.more.option.content.title":"Content","launcher.more.option.content.desc":"Start video or content production","launcher.more.option.learn.title":"Learn","launcher.more.option.learn.desc":"Create a launch-focused learning board","launcher.more.option.book.title":"Book","launcher.more.option.book.desc":"Start an ebook or story board","launcher.more.option.music.title":"Music","launcher.more.option.music.desc":"Start an audio production studio","templateCard.eyebrow":"Template","templateCard.generate":"Generate","templateCard.noInputs":"No inputs needed.","templateCard.generating":"Generating nodes...","templateCard.generated":"Generated {0} nodes below.","templateCard.failed":"Template generation failed.","templateCard.required":"{0} is required.","template.blank-core.boardTitle":"Canvas {{timestampShort}}","template.business-core.boardTitle":"Business Design - {{optionLabel}}","template.business-core.input.businessIdea.label":"What business do you want to build?","template.business-core.input.businessIdea.desc":"Write the problem and idea you want to solve in one or two sentences.","template.business-core.input.businessIdea.placeholder":"Example: A SaaS that summarizes meetings and assigns follow-up work automatically","template.business-core.input.targetUser.label":"Who is the primary customer?","template.business-core.input.targetUser.desc":"Write the user group most likely to pay first.","template.business-core.input.targetUser.placeholder":"Example: startup team leads, freelance operators","template.business-core.input.businessGoal.label":"Goal for this board","template.business-core.input.businessGoal.desc":"Choose what you want to solve first.","template.business-core.input.businessGoal.option.validate":"Validate the idea","template.business-core.input.businessGoal.option.mvp":"Design the MVP","template.business-core.input.businessGoal.option.monetize":"Design monetization","template.business-core.node.idea.title":"Business Idea","template.business-core.node.idea.body":"{{businessIdea}}","template.business-core.node.target.title":"Target Customers","template.business-core.node.target.body":`First customer candidates: {{targetUser}}
2
2
 
3
3
  1. Three first customer groups
4
4
  2. Urgent problems for each group
@@ -40,5 +40,5 @@ Base genre: {{musicGenre}}`,"template.music-core.node.references.title":"Referen
40
40
  本次目标:{{launchGoal}}`,"template.launch-core.node.landing.title":"落地页文案","template.launch-core.node.landing.body":"快速起草标题、副文案、CTA 和信任元素。","template.launch-core.node.channelCopy.title":"渠道文案","template.launch-core.node.channelCopy.body":"分别为 Product Hunt、X、LinkedIn 和社区写不同文案。","template.launch-core.node.community.title":"社区帖子","template.launch-core.node.community.body":"改写成问题解决经验分享,而不是广告。","template.launch-core.node.demoChecklist.title":"演示视频检查清单","template.launch-core.node.demoChecklist.body":"按问题、解决方案演示和 CTA 顺序整理所需场景。","template.launch-core.node.assets.title":"截图素材","template.launch-core.node.assets.body":"收集代表页面、对比场景、评价和证明图片。","template.launch-core.node.schedule.title":"发布日程","template.launch-core.node.schedule.body":"写下今天、明天和一周内要发布的渠道与时间。","template.launch-core.node.metrics.title":"成果记录","template.launch-core.node.metrics.body":"集中记录访问、注册、支付和表现好的消息。","template.content-core.boardTitle":"内容制作 - {{contentTheme}}","template.content-core.input.contentTheme.label":"要制作什么内容?","template.content-core.input.contentTheme.desc":"写下视频或帖子的核心主题。","template.content-core.input.contentTheme.placeholder":"例如:AI 会议总结工具介绍视频","template.content-core.input.contentChannel.label":"主要渠道","template.content-core.input.contentChannel.desc":"选择第一版内容要面向的渠道。","template.content-core.input.contentChannel.option.youtube":"YouTube","template.content-core.input.contentChannel.option.shorts":"Shorts / Reels","template.content-core.input.contentChannel.option.blog":"博客 / 文章","template.content-core.node.contentPlan.title":"内容计划","template.content-core.node.contentPlan.body":`{{contentTheme}}
41
41
  主要渠道:{{contentChannel}}`,"template.content-core.node.script.title":"脚本","template.content-core.node.script.body":"写下开场钩子、核心要点和 CTA。","template.content-core.node.scenes.title":"场景结构","template.content-core.node.scenes.body":"拆分每个场景的信息和所需视觉素材。","template.content-core.node.imagePrompts.title":"图片提示词","template.content-core.node.imagePrompts.body":"为缩略图和转场画面编写图片提示词。","template.content-core.node.videoPrompts.title":"视频提示词","template.content-core.node.videoPrompts.body":"定义镜头运动、氛围和时长。","template.content-core.node.distribution.title":"发布检查","template.content-core.node.distribution.body":"检查标题、说明、缩略图和上传日程。","template.learn-core.boardTitle":"面向发布的学习 - {{learningGoal}}","template.learn-core.input.learningGoal.label":"你为了什么成果而学习?","template.learn-core.input.learningGoal.desc":"写下想做出的东西,而不只是语法或理论。","template.learn-core.input.learningGoal.placeholder":"例如:发布我的第一个 SaaS MVP","template.learn-core.node.goal.title":"学习目标","template.learn-core.node.goal.body":"{{learningGoal}}","template.learn-core.node.basics.title":"核心概念","template.learn-core.node.basics.body":"写下目前缺少的语法和概念,并排序优先级。","template.learn-core.node.smallFeature.title":"做一个小功能","template.learn-core.node.smallFeature.body":"拆成足够小、能完成的功能单位。","template.learn-core.node.api.title":"API 使用","template.learn-core.node.api.body":"整理要连接的 API 和测试场景。","template.learn-core.node.dbAuth.title":"DB / Auth","template.learn-core.node.dbAuth.body":"简单设计存储结构和登录流程。","template.learn-core.node.ship.title":"部署","template.learn-core.node.ship.body":"只写部署所需的最小检查清单。","template.book-core.boardTitle":"书籍 / 电子书 - {{bookTopic}}","template.book-core.input.bookTopic.label":"要做什么书?","template.book-core.input.bookTopic.desc":"写下主题或暂定书名。","template.book-core.input.bookTopic.placeholder":"例如:面向独立创始人的 AI 执行指南","template.book-core.input.readerType.label":"这本书写给谁?","template.book-core.input.readerType.desc":"用一行写下代表读者。","template.book-core.input.readerType.placeholder":"例如:正在做第一个产品的独立创始人","template.book-core.node.bookConcept.title":"书籍概念","template.book-core.node.bookConcept.body":`{{bookTopic}}
42
42
  代表读者:{{readerType}}`,"template.book-core.node.toc.title":"目录","template.book-core.node.toc.body":"先整理大章和小节流程。","template.book-core.node.chapters.title":"章节草稿","template.book-core.node.chapters.body":"按章节记录核心信息和案例。","template.book-core.node.cover.title":"插图 / 封面","template.book-core.node.cover.body":"整理需要的视觉素材清单。","template.book-core.node.edit.title":"校对 / 编辑","template.book-core.node.edit.body":"写下语气、重复、流程和 CTA 检查点。","template.book-core.node.export.title":"Export","template.book-core.node.export.body":"完成 PDF、EPUB 和发布渠道的收尾工作。","template.music-core.boardTitle":"音乐制作 - {{trackMood}}","template.music-core.input.trackMood.label":"想做什么氛围的曲子?","template.music-core.input.trackMood.desc":"简短写下情绪或使用场景。","template.music-core.input.trackMood.placeholder":"例如:夜间工作用的 lo-fi 专注曲","template.music-core.input.musicGenre.label":"基础风格","template.music-core.input.musicGenre.desc":"选择最接近的起始风格。","template.music-core.input.musicGenre.option.lofi":"Lo-fi","template.music-core.input.musicGenre.option.ambient":"Ambient","template.music-core.input.musicGenre.option.pop":"Pop","template.music-core.input.musicGenre.option.cinematic":"Cinematic","template.music-core.node.musicConcept.title":"音乐概念","template.music-core.node.musicConcept.body":`{{trackMood}}
43
- 基础风格:{{musicGenre}}`,"template.music-core.node.references.title":"参考","template.music-core.node.references.body":"列出参考曲和想借鉴的点。","template.music-core.node.vocals.title":"人声 / 乐器","template.music-core.node.vocals.body":"写下人声类型和核心乐器配置。","template.music-core.node.lyrics.title":"歌词","template.music-core.node.lyrics.body":"整理主题、重复钩子和禁用表达。","template.music-core.node.generationPrompt.title":"生成提示词","template.music-core.node.generationPrompt.body":"收集音色、结构和氛围指令。","template.music-core.node.versions.title":"版本比较","template.music-core.node.versions.body":"记录 mp3 结果和修改点。"}},Ie={studioNodeType:"studioNodeType",templateNodeId:"templateNodeId",templateRole:"templateRole",compileTarget:"compileTarget",inputKey:"inputKey",inputType:"inputType",inputDescription:"inputDescription",inputPlaceholder:"inputPlaceholder",inputDefaultValue:"inputDefaultValue",inputRequired:"inputRequired",inputOptions:"inputOptions"},As=[{studioNodeType:"template.note",label:"Template Note",shortLabel:"Note"},{studioNodeType:"template.input",label:"Template Input",shortLabel:"Input"},{studioNodeType:"template.prompt",label:"Template Prompt",shortLabel:"Prompt"},{studioNodeType:"template.output",label:"Template Output",shortLabel:"Output"},{studioNodeType:"template.knowledge",label:"Knowledge Reference",shortLabel:"Know"},{studioNodeType:"template.section",label:"Section",shortLabel:"Sect"},{studioNodeType:"template.checklist",label:"Checklist",shortLabel:"List"}],zd=["note","memo","markdown","aiPrompt","output","section","checklist","input"],q={contentType:"templateLauncher",semanticTypeKey:"semanticType",semanticTypeValue:"TemplateLauncher",launcherIdKey:"templateLauncherId",selectedOptionIdKey:"templateLauncherSelectedOptionId",cardVersionKey:"templateCardVersion",cardLockedKey:"templateCardLocked",controllerNodeIdKey:"sourceTemplateControllerNodeId",runIdKey:"sourceTemplateRunId",cardGeneratedKey:"sourceTemplateCardGenerated",localizationManagedKey:"templateLocalizationManaged",localizationLanguageKey:"templateLanguageCode",sourceInputValuesJsonKey:"sourceTemplateInputValuesJson",width:560,height:620,resultTopGap:90},ut=Ps,Es=new Set(["en","ko","ja","zh"]);function yt(e){if(typeof e!="string")return"en";const t=e.trim().toLowerCase();return!t||t==="auto"?"en":Es.has(t)?t:"en"}function le(e,t="",o){const n=yt(o),r=ba[n],s=ba.en,c=r[e];if(c!==void 0)return c;const m=s[e];return n!=="ko"&&m!==void 0?m:t}function Jt(e,t){const o=Ye(e.id);return{...e,label:le(`launcher.${o}.title`,e.label,t),description:le(`launcher.${o}.desc`,e.description,t),prompt:le(`launcher.${o}.prompt`,e.prompt,t),options:e.options.map(n=>qs(e.id,n,t))}}function Kt(e,t){const o=Ye(e.id);return{...e,boardTitle:le(`template.${o}.boardTitle`,e.boardTitle,t),inputs:e.inputs.map(n=>Ws(e.id,n,t)),nodes:e.nodes.map(n=>Ks(e.id,n,t))}}function $d(e){return ut.launchers.map(t=>Jt(t,e))}function Ls(e,t){const o=ut.launchers.find(n=>H(n.id,e));return o?Jt(o,t):null}function Lo(e,t){if(e.options.length!==0)return e.options.find(o=>H(o.id,t||""))??e.options[0]}function js(e,t,o){const n=Lo(e,t),r=(n==null?void 0:n.templateId)||e.quickCreateTemplateId||"",s=ut.templates.find(c=>H(c.id,r));return s?Kt(s,o):null}function Vd(e){const t={};for(const o of(e==null?void 0:e.inputs)??[])t[o.key]=Pn(o);return t}function qd(e,t){if(!e)return"Template is unavailable.";const o=e.inputs.find(n=>n.required&&!String(t[n.key]||"").trim());return o?`${o.label} is required.`:null}function Ns(e,t,o,n){const r=yt(n.appLanguage),s=Jt(e,r),c=Lo(s,t),m=js(s,c==null?void 0:c.id,r);return m?Ds(s,c,m,o,n):null}function Ds(e,t,o,n,r){const s=No(o,n),c=nr(e,t,s),m=new Date().toISOString(),l=ir("template-board"),b=At(o.boardTitle,c).trim()||e.label,k=o.nodes.map((x,v)=>_s(x,e,t,o,c,l,v));return{launcher:e,option:t,template:o,board:{id:l,name:b,updatedAt:m,settings:r,source:{kind:"localStorage",loadedAt:m},nodes:k,edges:[]}}}function er(e,t,o={},n){const r=yt(n),s=Jt(e,r),c=Hs(r),m=el(s,t),l={launcherId:s.id,title:s.label,description:s.description,prompt:s.prompt,iconClass:s.iconClass,selectedOptionId:m??void 0,options:[],inputValues:{},generateLabel:c.generateLabel,noInputsLabel:c.noInputsLabel,generatingMessage:c.generatingMessage,generatedMessageFormat:c.generatedMessageFormat,generationFailedMessage:c.generationFailedMessage,requiredMessageFormat:c.requiredMessageFormat,actionLabel:c.generateLabel};if(s.options.length===0){const k=s.quickCreateTemplateId?ut.templates.find(x=>H(x.id,e.quickCreateTemplateId)):null;if(k){const x=Kt(k,r);l.options.push({id:"",label:s.label,description:s.description,templateId:x.id,inputs:un(x.inputs)})}}else for(const k of s.options){const x=ut.templates.find(V=>H(V.id,k.templateId)),v=x?Kt(x,r):null;l.options.push({id:k.id,label:k.label,description:k.description,templateId:k.templateId,inputs:un((v==null?void 0:v.inputs)??[])})}const b=l.options.find(k=>H(k.id,l.selectedOptionId))??l.options[0];return l.selectedOptionId=b==null?void 0:b.id,l.inputValues=ar((b==null?void 0:b.inputs)??[],o),l}function Wd(e,t,o,n,r={},s){const c=yt(s),m=er(e,t,r,c),l=m.options.find(k=>H(k.id,m.selectedOptionId)),b={[q.semanticTypeKey]:q.semanticTypeValue,[q.launcherIdKey]:e.id,[q.selectedOptionIdKey]:m.selectedOptionId??"",[q.cardVersionKey]:"1.0",[q.cardLockedKey]:"True",[q.localizationLanguageKey]:c,IsNew:"true"};return{id:ir("template-card"),kind:"template-launcher",title:m.title,body:JSON.stringify(m),x:o,y:n,width:q.width,height:q.height,tags:["Template","Launcher",e.label,l==null?void 0:l.label].filter(k=>!!k),metadata:b,aiEnabled:!1}}function Rn(e){var t;return e?e.kind==="template-launcher"?!0:H((t=e.metadata)==null?void 0:t[q.semanticTypeKey],q.semanticTypeValue):!1}function tr(e){try{const t=JSON.parse(String(e||""));return!t||typeof t!="object"||!t.launcherId||!Array.isArray(t.options)?null:{launcherId:String(t.launcherId||""),title:String(t.title||""),description:String(t.description||""),prompt:String(t.prompt||""),iconClass:String(t.iconClass||""),selectedOptionId:t.selectedOptionId===void 0?void 0:String(t.selectedOptionId),options:t.options.map(o=>({id:String(o.id||""),label:String(o.label||""),description:String(o.description||""),templateId:String(o.templateId||""),inputs:un(o.inputs??[])})),inputValues:Object.fromEntries(Object.entries(t.inputValues??{}).map(([o,n])=>[o,String(n??"")])),generateLabel:String(t.generateLabel||t.actionLabel||"Generate"),noInputsLabel:String(t.noInputsLabel||"No inputs needed."),generatingMessage:String(t.generatingMessage||"Generating nodes..."),generatedMessageFormat:String(t.generatedMessageFormat||"Generated {0} nodes below."),generationFailedMessage:String(t.generationFailedMessage||"Template generation failed."),requiredMessageFormat:String(t.requiredMessageFormat||"{0} is required."),actionLabel:String(t.actionLabel||t.generateLabel||"Generate")}}catch{return null}}function Kd(e,t){const o=e.options.find(n=>H(n.id,t))??e.options[0];return{...e,selectedOptionId:o==null?void 0:o.id,inputValues:ar((o==null?void 0:o.inputs)??[],e.inputValues)}}function Hd(e,t,o){return{...e,inputValues:{...e.inputValues,[t]:o}}}function Xd(e){if(!e)return"Template card payload is unavailable.";const t=e.options.find(n=>H(n.id,e.selectedOptionId))??e.options[0];if(!t)return"Template card option is unavailable.";const o=t.inputs.find(n=>n.required&&!String(e.inputValues[n.key]||"").trim());return o?Zs(e.requiredMessageFormat||"{0} is required.",o.label):null}function Yd(e,t,o,n,r=tl()){var Z;if(!Rn(e))return null;const s=(Z=e.metadata)==null?void 0:Z[q.launcherIdKey],c=yt(n.appLanguage),m=s?Ls(s,c):null;if(!m)return null;const l=Lo(m,t),b=Ns(m,(l==null?void 0:l.id)??null,o,n);if(!b)return null;const k=No(b.template,o),x=JSON.stringify(k),v=Math.min(...b.board.nodes.map(E=>E.x)),V=Math.min(...b.board.nodes.map(E=>E.y)),R=e.x,F=e.y+Math.max(e.height,q.height)+q.resultTopGap,J=b.board.nodes.map(E=>({...E,x:R+(E.x-v),y:F+(E.y-V),metadata:{...E.metadata??{},[q.controllerNodeIdKey]:e.id,[q.runIdKey]:r,[q.cardGeneratedKey]:"True",[q.localizationManagedKey]:"True",[q.localizationLanguageKey]:c,[q.sourceInputValuesJsonKey]:x}}));return{launcher:m,option:b.option,template:b.template,runId:r,nodes:J}}function Qd(e,t){const o=yt(t),n=new Map(e.map(c=>[c.id,c]));let r=!1;const s=e.map(c=>{const m=Xs(c,o);if(m)return r=!0,m;const l=Ys(c,n,o);return l?(r=!0,l):c});return{nodes:r?s:e,changed:r,language:o}}function Jd(e){const t=String(e||"").trim()||"Template Studio Draft";return{templateId:jo(t),templateTitle:t,category:"custom",boardTitle:t,version:"0.1.0",tier:"draft",status:"draft"}}function Zd(e,t){const o=[],n=Fs(e),r=t.filter(k=>!!ve(k,Ie.studioNodeType)).sort((k,x)=>k.y-x.y||k.x-x.x||k.id.localeCompare(x.id)),s=r.filter(k=>H(ve(k,Ie.studioNodeType),"template.input")),c=r.filter(k=>!H(ve(k,Ie.studioNodeType),"template.input")),m=Bs(s,o),l=Gs(c,o);r.length===0&&o.push({code:"studio.nodes.empty",message:"Add at least one Template Studio node before compiling."});const b={id:n.templateId,version:n.version,tier:n.tier,status:n.status,boardTitle:n.boardTitle,inputs:m,nodes:l};return Us(b,o),{template:b,manifestJson:JSON.stringify(b,null,2),issues:o}}function jo(e){return String(e||"").trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"template-studio-draft"}function Os(e,t){switch(String(e||"").trim().toLowerCase()||or(t)){case"template.input":return"input";case"template.prompt":return"aiPrompt";case"template.output":return"output";case"template.knowledge":return"memo";case"template.section":return"section";case"template.checklist":return"checklist";default:return t?rr(t.kind):"note"}}function or(e){if(!e)return"template.note";switch(e.kind){case"ai-task":return"template.prompt";case"markdown":return"template.section";case"memo":return"template.knowledge";default:return"template.note"}}function eu(e){const t=As.find(o=>H(o.studioNodeType,e));return(t==null?void 0:t.shortLabel)??"Note"}function _s(e,t,o,n,r,s,c){const m={};for(const[b,k]of Object.entries(e.metadata??{}))m[b]=At(k,r);m.IsNew="true",m.sourceLauncherId=t.id,m.sourceTemplateId=n.id,m.sourceTemplateVersion=n.version,m.sourceTemplateNodeId=e.id,m.templateRole=m.templateRole||e.id,m.templateLauncher=t.id,m.templateId=n.id,m.templateVersion=n.version,m.templateNodeId=e.id,o!=null&&o.id&&(m.sourceOptionId=o.id,m.templateOption=o.id);const l=ol(e.contentType);return{id:`${s}-${e.id||c}`,kind:l,title:At(e.title,r),body:At(e.body,r),x:Number(e.x)||0,y:Number(e.y)||0,width:Math.max(180,Number(e.width)||340),height:Math.max(120,Number(e.height)||220),tags:["Template",t.label,(o==null?void 0:o.label)||n.tier].filter(Boolean),metadata:m}}function No(e,t){const o={};for(const n of e.inputs){const r=String(t[n.key]??"").trim();o[n.key]=r||Pn(n)}return o}function nr(e,t,o){const n=(t==null?void 0:t.label)||e.label,r=(t==null?void 0:t.description)||e.description,s={launcherId:e.id,launcherLabel:e.label,launcherDescription:e.description,optionId:(t==null?void 0:t.id)||"",optionLabel:n,optionDescription:r,selectionLabel:n,timestampShort:nl(new Date)};for(const[c,m]of Object.entries(o))s[c]=m;return s}function At(e,t){let o=e||"";for(const[n,r]of Object.entries(t))o=o.replace(new RegExp(`{{\\s*${al(n)}\\s*}}`,"gi"),r);return o}function Pn(e){var t,o;return e.defaultValue?e.defaultValue:e.type==="select"&&((o=(t=e.options)==null?void 0:t[0])==null?void 0:o.value)||""}function Fs(e){const t=String(e.templateTitle||"").trim()||"Template Studio Draft";return{templateId:jo(e.templateId||t),templateTitle:t,category:String(e.category||"").trim()||"custom",boardTitle:String(e.boardTitle||"").trim()||t,version:String(e.version||"").trim()||"0.1.0",tier:String(e.tier||"").trim()||"draft",status:String(e.status||"").trim()||"draft"}}function Bs(e,t){const o=[],n=new Set;for(const r of e){const s=r.title.trim()||"Input",c=jo(ve(r,Ie.inputKey)||s),m=c.toLowerCase();if(n.has(m)){t.push({code:"studio.input.duplicate",message:`Template Studio input '${c}' is duplicated.`});continue}n.add(m),o.push({key:c,type:zs(ve(r,Ie.inputType)),label:s,description:ve(r,Ie.inputDescription)||r.body,placeholder:ve(r,Ie.inputPlaceholder),defaultValue:ve(r,Ie.inputDefaultValue),required:$s(ve(r,Ie.inputRequired)),options:Vs(ve(r,Ie.inputOptions))})}return o}function Gs(e,t){const o=[],n=new Set;for(const r of e){const s=ve(r,Ie.studioNodeType)||or(r);let c=jo(ve(r,Ie.templateNodeId)||r.title);const m=c.toLowerCase();if(n.has(m)){t.push({code:"studio.node.duplicate",message:`Template Studio node '${c}' is duplicated.`});continue}n.add(m);const l=ve(r,Ie.compileTarget)||Os(s,r),b=ve(r,Ie.templateRole)||s.replace(/^template\./i,"");o.push({id:c,contentType:l,title:r.title.trim(),body:r.body,x:Math.round(r.x),y:Math.round(r.y),width:Math.max(180,Math.round(r.width||340)),height:Math.max(120,Math.round(r.height||220)),metadata:{templateRole:b,studioNodeType:s,compileTarget:l,studioSourceContentType:rr(r.kind)}})}return o}function Us(e,t){const o=new Set;for(const r of e.inputs)r.key||t.push({code:"template.input.key",message:`Template '${e.id}' contains an input with no key.`}),r.label||t.push({code:"template.input.label",message:`Template '${e.id}' input '${r.key}' must define a label.`}),o.has(r.key.toLowerCase())&&t.push({code:"template.inputs.duplicate",message:`Template '${e.id}' contains duplicate input key '${r.key}'.`}),o.add(r.key.toLowerCase());const n=new Set;for(const r of e.nodes)r.id||t.push({code:"template.node.id",message:`Template '${e.id}' contains a node with no id.`}),n.has(r.id.toLowerCase())&&t.push({code:"template.nodes.duplicate",message:`Template '${e.id}' contains duplicate node id '${r.id}'.`}),n.add(r.id.toLowerCase())}function ve(e,t){var n;const o=(n=e.metadata)==null?void 0:n[t];return typeof o=="string"?o.trim():""}function zs(e){const t=e.trim().toLowerCase();return t==="textarea"||t==="select"?t:"text"}function $s(e){return e.trim().toLowerCase()==="true"}function Vs(e){const t=[];for(const o of e.split(/\r?\n/)){const n=o.trim();if(!n)continue;const[r,s]=n.split("|",2).map(c=>c.trim());r&&t.push({value:r,label:s||r})}return t}function qs(e,t,o){const n=Ye(e),r=Ye(t.id);return{...t,label:le(`launcher.${n}.option.${r}.title`,t.label,o),description:le(`launcher.${n}.option.${r}.desc`,t.description,o)}}function Ws(e,t,o){var s;const n=Ye(e),r=Ye(t.key);return{...t,label:le(`template.${n}.input.${r}.label`,t.label,o),description:le(`template.${n}.input.${r}.desc`,t.description,o),placeholder:le(`template.${n}.input.${r}.placeholder`,t.placeholder,o),options:(s=t.options)==null?void 0:s.map(c=>({...c,label:le(`template.${n}.input.${r}.option.${Ye(c.value)}`,c.label,o)}))}}function Ks(e,t,o){const n=Ye(e),r=Ye(t.id);return{...t,title:le(`template.${n}.node.${r}.title`,t.title,o),body:le(`template.${n}.node.${r}.body`,t.body,o),metadata:{...t.metadata??{}}}}function Hs(e){return{generateLabel:le("templateCard.generate","Generate",e),noInputsLabel:le("templateCard.noInputs","No inputs needed.",e),generatingMessage:le("templateCard.generating","Generating nodes...",e),generatedMessageFormat:le("templateCard.generated","Generated {0} nodes below.",e),generationFailedMessage:le("templateCard.failed","Template generation failed.",e),requiredMessageFormat:le("templateCard.required","{0} is required.",e)}}function Xs(e,t){var m,l,b,k;if(!Rn(e))return null;const o=tr(e.body),n=((m=e.metadata)==null?void 0:m[q.launcherIdKey])||(o==null?void 0:o.launcherId),r=n?ut.launchers.find(x=>H(x.id,n)):null;if(!r)return null;const s=(o==null?void 0:o.selectedOptionId)||((l=e.metadata)==null?void 0:l[q.selectedOptionIdKey])||null,c=er(r,s,(o==null?void 0:o.inputValues)??{},t);return e.title===c.title&&e.body===JSON.stringify(c)&&((b=e.metadata)==null?void 0:b[q.localizationLanguageKey])===t?null:{...e,title:c.title,body:JSON.stringify(c),tags:["Template","Launcher",c.title,(k=c.options.find(x=>x.id===c.selectedOptionId))==null?void 0:k.label].filter(x=>!!x),metadata:{...e.metadata??{},[q.launcherIdKey]:r.id,[q.selectedOptionIdKey]:c.selectedOptionId??"",[q.localizationLanguageKey]:t}}}function Ys(e,t,o){if(Rn(e))return null;const n=go(Be(e,"sourceTemplateId"),Be(e,"templateId")),r=go(Be(e,"sourceTemplateNodeId"),Be(e,"templateNodeId")),s=go(Be(e,"sourceLauncherId"),Be(e,"templateLauncher"));if(!n||!r||!s)return null;const c=ut.launchers.find(Z=>H(Z.id,s)),m=ut.templates.find(Z=>H(Z.id,n));if(!c||!m)return null;const l=go(Be(e,"sourceOptionId"),Be(e,"templateOption")),b=Qs(e,t),k=No(Kt(m,o),b),x=en(c,m,r,l,k,"ko"),v=yt(Be(e,q.localizationLanguageKey)||"ko"),V=en(c,m,r,l,k,v),R=en(c,m,r,l,k,o);if(!x||!V||!R)return null;const F=e.title===x.title||e.title===V.title,J=e.body===x.body||e.body===V.body;return!F&&!J?null:{...e,title:F?R.title:e.title,body:J?R.body:e.body,tags:["Template",R.launcherLabel,R.optionLabel].filter(Boolean),metadata:{...e.metadata??{},[q.localizationManagedKey]:"True",[q.localizationLanguageKey]:o,[q.sourceInputValuesJsonKey]:JSON.stringify(k)}}}function en(e,t,o,n,r,s){const c=Jt(e,s),m=Kt(t,s),l=Lo(c,n),b=m.nodes.find(v=>H(v.id,o));if(!b)return null;const k=No(m,r),x=nr(c,l,k);return{title:At(b.title,x),body:At(b.body,x),launcherLabel:c.label,optionLabel:(l==null?void 0:l.label)||c.label}}function Qs(e,t){const o=Js(Be(e,q.sourceInputValuesJsonKey));if(Object.keys(o).length>0)return o;const n=Be(e,q.controllerNodeIdKey),r=n?t.get(n):null,s=tr(r==null?void 0:r.body);return(s==null?void 0:s.inputValues)??{}}function Js(e){if(!e)return{};try{const t=JSON.parse(e);return Object.fromEntries(Object.entries(t??{}).map(([o,n])=>[o,String(n??"")]))}catch{return{}}}function Be(e,t){var n;const o=(n=e.metadata)==null?void 0:n[t];return typeof o=="string"&&o.trim()?o.trim():null}function go(...e){var t;return((t=e.find(o=>typeof o=="string"&&o.trim()))==null?void 0:t.trim())??null}function Ye(e){const t=String(e||"").trim();return t?t.replace(/:/g,"."):"unknown"}function Zs(e,t){return e.includes("{0}")?e.replace("{0}",t):`${t} is required.`}function el(e,t){var o,n,r;return String(t||"").trim()?((n=e.options.find(s=>H(s.id,t)))==null?void 0:n.id)??((r=e.options[0])==null?void 0:r.id):(o=e.options[0])==null?void 0:o.id}function un(e){return e.map(t=>{var o;return{...t,options:(o=t.options)==null?void 0:o.map(n=>({...n}))}})}function ar(e,t){const o={};for(const n of e)o[n.key]=String(t[n.key]??Pn(n));return o}function tl(){const e=new Date,t=(o,n=2)=>`${o}`.padStart(n,"0");return[e.getFullYear(),t(e.getMonth()+1),t(e.getDate()),t(e.getHours()),t(e.getMinutes()),t(e.getSeconds()),t(e.getMilliseconds(),3)].join("")}function rr(e){return e==="ai-task"?"aiPrompt":e==="template-launcher"?q.contentType:e}function ol(e){return H(e,"directory")?"directory":H(e,"pdf")?"pdf":H(e,"file")?"file":H(e,"memo")?"memo":H(e,"markdown")?"markdown":H(e,"csv-table")?"csv-table":H(e,"text")?"text":H(e,"code")?"code":H(e,"mask")?"mask":H(e,"image")?"image":H(e,"embed")?"embed":H(e,"aiPrompt")?"ai-task":H(e,q.contentType)?"template-launcher":"note"}function nl(e){const t=`${e.getMonth()+1}`.padStart(2,"0"),o=`${e.getDate()}`.padStart(2,"0"),n=`${e.getHours()}`.padStart(2,"0"),r=`${e.getMinutes()}`.padStart(2,"0");return`${t}.${o} ${n}:${r}`}function ir(e){return`${e}-${Math.random().toString(36).slice(2,9)}`}function H(e,t){return String(e||"").toLowerCase()===String(t||"").toLowerCase()}function al(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function An(e){var r;let t=null;if(typeof navigator<"u"&&((r=navigator.clipboard)!=null&&r.writeText))try{return await navigator.clipboard.writeText(e),"clipboard"}catch(s){t=s}if(typeof document>"u"||!document.body||typeof document.execCommand!="function")throw t instanceof Error?t:new Error("clipboard-unavailable");const o=document.createElement("textarea"),n=document.activeElement instanceof HTMLElement?document.activeElement:null;o.value=e,o.setAttribute("readonly",""),o.style.position="fixed",o.style.left="-9999px",o.style.top="0",o.style.opacity="0",document.body.appendChild(o),o.focus(),o.select(),o.setSelectionRange(0,e.length);try{if(!document.execCommand("copy"))throw t instanceof Error?t:new Error("clipboard-unavailable");return"fallback"}finally{o.remove(),n==null||n.focus({preventScroll:!0})}}const sr="mindexec.app.language",xo="auto",Ht=[{code:xo,label:"Auto",nativeLabel:"Auto",englishName:"the user's input language",htmlLang:"auto",isAuto:!0,description:"Match the user's input language unless a prompt asks otherwise."},{code:"en",label:"English",nativeLabel:"English",englishName:"English",htmlLang:"en",isAuto:!1,description:"Prefer English for user-facing AI output."},{code:"ko",label:"Korean",nativeLabel:"한국어",englishName:"Korean",htmlLang:"ko",isAuto:!1,description:"Prefer Korean for user-facing AI output."},{code:"ja",label:"Japanese",nativeLabel:"日本語",englishName:"Japanese",htmlLang:"ja",isAuto:!1,description:"Prefer Japanese for user-facing AI output."},{code:"zh",label:"Chinese",nativeLabel:"中文",englishName:"Chinese",htmlLang:"zh",isAuto:!1,description:"Prefer Chinese for user-facing AI output."}];function jt(e){if(typeof e!="string")return xo;const t=e.trim().toLowerCase();return Ht.some(o=>o.code===t)?t:xo}function Do(e){const t=jt(e);return Ht.find(o=>o.code===t)??Ht[0]}function lr(){if(typeof window>"u")return null;try{const e=window.localStorage.getItem(sr);return e===null?null:jt(e)}catch{return null}}function tu(e){return jt(lr()??e??xo)}function ou(e){const t=jt(e);if(typeof window>"u")return t;try{window.localStorage.setItem(sr,t)}catch{}return t}function nu(e){const t=lr()??jt(e.settings.appLanguage);return{...e,settings:{...e.settings,appLanguage:t}}}function au(e){const t=Do(e);return t.isAuto?"Language preference: match the user's input language unless the user explicitly asks for a different language.":`Language preference: respond in ${t.englishName} unless the user explicitly asks for a different language.`}function ru(e){return Do(e).englishName}function iu(e){const t=Do(e);return t.isAuto?"Language preference: if the generated asset includes visible text, captions, labels, or UI copy, match the user's input language unless the prompt explicitly asks for another language.":`Language preference: if the generated asset includes visible text, captions, labels, or UI copy, use ${t.englishName} unless the prompt explicitly asks for another language.`}const En=.001,rl=1,il=5,sl=1.35,ll=1.3,cl=1.45,dl=.002,ul=.01,pl=.03,ml=.002,hl=.015,gl=.05,fl=5,bl=20,yl=100,kl=2,ya=2500,Tl=800,Il=1200,vl=1800,Cl=2600,xl={"deepseek/deepseek-v4-flash":{promptUsdPerToken:14e-8,completionUsdPerToken:28e-8,source:"openrouter"},"deepseek/deepseek-v4-pro":{promptUsdPerToken:435e-9,completionUsdPerToken:87e-8,source:"openrouter"},"deepseek/deepseek-chat-v3-0324":{promptUsdPerToken:14e-8,completionUsdPerToken:28e-8,source:"openrouter"},"gpt-image-2":{averageUsd:.02,source:"imagerouter"},"Tongyi-MAI/Z-Image-Turbo:free":{averageUsd:.02,source:"imagerouter"},"google/veo-2":{averageUsd:.25,maxUsd:.25,source:"imagerouter"},"runway/gen-3":{averageUsd:.2,maxUsd:.2,source:"imagerouter"}};function wl(e){const t=Dl(e.reasoningEffort);return e.mode==="Text"?Al(e.provider,t,e.vendorPricing):e.mode==="Image"&&e.provider==="openai-codex"&&_l(e.modelId)?st("Free",0,"Codex Responses image generation",void 0,"codex",!1):e.mode==="Image"?Ll(e.vendorPricing):e.mode==="Video"?jl(e.vendorPricing):Et("Unavailable")}function Sl(e){const t=e.settings.inputMode==="Image"||e.settings.inputMode==="Video"?e.settings.inputMode:"Text",o=Pl(e.settings,t);return wl({mode:t,provider:Rl(e.settings),modelId:o,reasoningEffort:e.settings.effort,vendorPricing:Ml(o)})}function Ml(e){const t=Fl(e);return xl[t]??null}function Rl(e){switch(e.aiProvider??"OpenAI Codex"){case"Local Ollama":return"local-ollama";case"BYOK":return"byok";case"Managed Cloud":return"managed-cloud";case"Gemini CLI":return"google-gemini-cli";case"OpenAI Codex":default:return"openai-codex"}}function Pl(e,t){return t==="Image"?ln("Image",e).id:t==="Video"?ln("Video",e).id:e.model}function Al(e,t,o){switch(e){case"local-ollama":return st("Free",0,"Local execution",void 0,"ollama",!1);case"byok":return st("ServiceFeeOnly",kl,"BYOK platform fee",void 0,"byok",!1);case"openai-codex":return st("Free",0,"Codex CLI local execution",void 0,"codex",!1);case"google-gemini-cli":return st("Free",0,"Gemini CLI local execution",void 0,"gemini-cli",!1);case"managed-cloud":default:return El(t,o)}}function El(e,t){if(!bt(t==null?void 0:t.promptUsdPerToken)||!bt(t==null?void 0:t.completionUsdPerToken))return Et("Pricing unavailable");const o=Nl(e),n=((t==null?void 0:t.requestUsd)??0)+t.promptUsdPerToken*ya+t.completionUsdPerToken*o,r=n*sl+dl+ml,s=Ln(Math.max(r/En,fl),rl);return st("FixedPoints",s,`Base run (${pn(ya)} in / ${pn(o)} out)`,n,t.source,!0)}function Ll(e){if(!e)return Et("Pricing unavailable");let t=e.averageUsd??e.maxUsd??e.minUsd;if(!bt(t))return Et("Pricing unavailable");bt(e.minUsd)&&(t=Math.max(t,e.minUsd*1.15));const o=t*ll+ul+hl,n=Ln(Math.max(o/En,bl),il);return st("FixedPoints",n,"Base image generation",t,e.source,!0)}function jl(e){if(!e)return Et("Pricing unavailable");let t=0;if(bt(e.maxUsd)&&(t=Math.max(t,e.maxUsd)),bt(e.averageUsd)&&(t=Math.max(t,e.averageUsd*1.25)),bt(e.minUsd)&&(t=Math.max(t,e.minUsd)),t<=0)return Et("Pricing unavailable");const o=t*cl+pl+gl,n=Ln(Math.max(o/En,yl),10);return st("FixedPoints",n,"Base video generation",t,e.source,!0)}function Nl(e){switch(e){case"low":return Tl;case"high":return vl;case"xhigh":return Cl;case"medium":default:return Il}}function Dl(e){switch(String(e??"").trim().toLowerCase()){case"fast":case"low":return"low";case"deep":case"xhigh":return"xhigh";case"high":return"high";case"normal":case"medium":default:return"medium"}}function Ln(e,t){return t<=1?Math.ceil(e):Math.ceil(e/t)*t}function st(e,t,o,n,r,s){return{billingKind:e,displayPoints:t,displayLabel:Ol(t),basisLabel:o,isEstimatedFromCatalog:s,vendorCostUsdSnapshot:n,vendorPricingSource:r}}function Et(e){return{billingKind:"Unavailable",displayPoints:0,displayLabel:e,basisLabel:"Pricing unavailable",isEstimatedFromCatalog:!1}}function Ol(e){return`${pn(e)}P`}function pn(e){return e.toLocaleString("en-US",{maximumFractionDigits:0})}function _l(e){return String(e??"").trim().toLowerCase().startsWith("codex-image:")}function Fl(e){return String(e??"").trim()}function bt(e){return typeof e=="number"&&Number.isFinite(e)}const tn=[{id:"general",label:"General",icon:gi},{id:"language",label:"Language",icon:fi},{id:"connection",label:"Connection",icon:bi},{id:"media",label:"Media",icon:ja},{id:"agent",label:"Agent",icon:yi},{id:"system",label:"System",icon:ki},{id:"about",label:"About",icon:Ti}],Bl=["Managed Cloud","BYOK","OpenAI Codex","Local Ollama"];function Gl(e,t,o){return Number.isFinite(e)?Math.min(o,Math.max(t,Math.round(e))):t}function su({settings:e,onPatchSettings:t,onClose:o}){const[n,r]=p.useState("general"),[s,c]=p.useState("idle"),[m,l]=p.useState(null),b=tn.find(h=>h.id===n)??tn[0],k=us(e),x=Lt(e.model),v=e.aiProvider??"OpenAI Codex",V=zl(x),R=Do(e.appLanguage),F=ka("Image",e),J=ka("Video",e),Z=Object.fromEntries(Ht.map(h=>[h.code,h.isAuto?h.label:`${h.nativeLabel} / ${h.label}`])),E=(h,ee)=>t(h,ee),ue=h=>{const ee=h.currentTarget;let L=0;if(h.key==="PageDown")L=Math.max(160,Math.floor(ee.clientHeight*.86));else if(h.key==="PageUp")L=-Math.max(160,Math.floor(ee.clientHeight*.86));else if(h.key==="ArrowDown")L=44;else if(h.key==="ArrowUp")L=-44;else if(h.key==="End"){h.preventDefault(),ee.scrollTo({top:ee.scrollHeight,behavior:"auto"});return}else if(h.key==="Home"){h.preventDefault(),ee.scrollTo({top:0,behavior:"auto"});return}else return;h.preventDefault(),ee.scrollBy({top:L,behavior:"auto"})},B=async()=>{try{const h=await An(V);c("copied"),g.emit("settings.providerCommand.copy",{provider:v,command:"dataset-generator",method:h,redacted:!0})}catch(h){if($l(m)){c("selected"),g.emit("settings.providerCommand.selectFallback",{provider:v,command:"dataset-generator",message:h instanceof Error?h.message:String(h),redacted:!0});return}c("failed"),g.emit("settings.providerCommand.copyFailed",{provider:v,command:"dataset-generator",message:h instanceof Error?h.message:String(h)})}},pe=(h,ee)=>{const L=wn(h,ee),Y=Eo(h).find(Pe=>Pe.id===L);if(!Y)return;const Oe=h==="Image"?e.imageRouterImageAspectPresetId:e.imageRouterVideoAspectPresetId,W=cn(h,Y,Oe);E(h==="Image"?{imageRouterImageModel:Y.id,imageRouterImageAspectPresetId:W.id}:{imageRouterVideoModel:Y.id,imageRouterVideoAspectPresetId:W.id},`media.${h.toLowerCase()}.model`),g.emit("media.model.select",{mode:h,model:Y.id,aspectPresetId:W.id,requestedSize:dn(W),source:"settings-dialog"})},Ce=(h,ee)=>{const L=h==="Image"?F.model:J.model,Y=cn(h,L,ee);E(h==="Image"?{imageRouterImageAspectPresetId:Y.id}:{imageRouterVideoAspectPresetId:Y.id},`media.${h.toLowerCase()}.aspect`),g.emit("media.aspect.select",{mode:h,model:L.id,aspectPresetId:Y.id,requestedSize:dn(Y),source:"settings-dialog"})};return a.jsx("div",{className:"ai-settings-backdrop","data-testid":"ai-settings-dialog","data-disable-mindcanvas-wheel":"true",onMouseDown:o,children:a.jsxs("section",{className:"ai-settings-dialog","aria-label":"AI settings","data-disable-mindcanvas-hotkeys":"true","data-ai-settings-dialog-surface":"true",onMouseDown:h=>h.stopPropagation(),children:[a.jsx("aside",{className:"ai-settings-tabs","aria-label":"Settings sections",children:tn.map(h=>{const ee=h.icon;return a.jsxs("button",{type:"button",className:n===h.id?"is-active":"","data-testid":`ai-settings-tab-${h.id}`,onClick:()=>r(h.id),children:[a.jsx(ee,{size:15}),a.jsx("span",{children:h.label})]},h.id)})}),a.jsxs("main",{className:"ai-settings-main",children:[a.jsxs("header",{className:"ai-settings-head",children:[a.jsx("strong",{children:b.label}),a.jsx("button",{type:"button",title:"Close settings",onClick:o,children:a.jsx(Po,{size:16})})]}),a.jsxs("div",{className:"ai-settings-body","data-testid":"ai-settings-body",tabIndex:0,onKeyDown:ue,children:[n==="general"&&a.jsxs("div",{className:"settings-grid",children:[a.jsx(xt,{label:"Grid snap",description:"Align new movement to the canvas grid.",checked:e.gridSnap??!0,onChange:h=>E({gridSnap:h},"general.gridSnap")}),a.jsx(De,{label:"Grid type",description:"Background grid rendering mode.",value:e.gridType??"dot",options:["dot","line","particles","spirit"],onChange:h=>E({gridType:h},"general.gridType")}),a.jsx(De,{label:"Cursor position",description:"Where new nodes are placed by default.",value:e.cursorMode??"center",options:["center","lastNode"],onChange:h=>E({cursorMode:h},"general.cursorMode")}),a.jsx(De,{label:"Cursor direction",description:"Direction for sequential node placement.",value:e.cursorDirection,options:["right","down"],onChange:h=>E({cursorDirection:h},"general.cursorDirection")}),a.jsx(De,{label:"Camera trace mode",description:"Whether the camera follows new work.",value:e.cameraTraceMode??"none",options:["none","cursor"],onChange:h=>E({cameraTraceMode:h},"general.cameraTraceMode")}),a.jsx(De,{label:"Image load size",description:"Image nodes use fixed or original sizing.",value:e.imageLoadSize??"default",options:["default","original"],onChange:h=>E({imageLoadSize:h},"general.imageLoadSize")}),a.jsx($t,{label:"AI node width",description:"Default width for new AI task nodes.",value:e.aiNodeDefaultWidth??340,min:220,max:1200,onChange:h=>E({aiNodeDefaultWidth:h},"general.aiNodeDefaultWidth")}),a.jsx($t,{label:"AI node height",description:"Default height for new AI task nodes.",value:e.aiNodeDefaultHeight??196,min:120,max:900,onChange:h=>E({aiNodeDefaultHeight:h},"general.aiNodeDefaultHeight")}),a.jsx(xt,{label:"Show full AI response",description:"Allow AI result nodes to expand for long output.",checked:e.showFullAiResponse??!1,onChange:h=>E({showFullAiResponse:h},"general.showFullAiResponse")}),a.jsx(xt,{label:"Minimap",description:"Display a small navigation minimap in the bottom-right of the canvas.",checked:e.minimapEnabled??!1,onChange:h=>E({minimapEnabled:h},"general.minimapEnabled")}),a.jsx(xt,{label:"Mouse wheel mode",description:"Swap wheel zoom and scroll behavior.",checked:e.wheelMode,onChange:h=>E({wheelMode:h},"general.wheelMode")})]}),n==="language"&&a.jsx("div",{className:"settings-grid settings-grid--compact",children:a.jsx(De,{label:"App Language",description:`Controls the language preference passed into AI runs. ${R.description}`,value:R.code,options:Ht.map(h=>h.code),optionLabels:Z,testId:"app-language-select",onChange:h=>E({appLanguage:jt(h)},"language.appLanguage")})}),n==="connection"&&a.jsxs("div",{className:"settings-stack",children:[a.jsx("section",{className:"settings-radio-group","aria-label":"AI Provider",children:Bl.map(h=>a.jsxs("label",{className:v===h?"is-selected":"",children:[a.jsx("input",{type:"radio",name:"ai-provider",checked:v===h,onChange:()=>E({aiProvider:h},"connection.provider")}),a.jsxs("span",{children:[a.jsx("strong",{children:h}),a.jsx("small",{children:cr(h)})]})]},h))}),a.jsx(Vl,{provider:v,datasetGeneratorCommand:V,copyState:s,onCommandTextAreaRef:l,onCopyDatasetGeneratorCommand:B}),a.jsxs("div",{className:"settings-grid settings-grid--compact",children:[a.jsx(De,{label:"Text model",description:Ul(x),value:x,options:k.map(h=>h.id),optionLabels:Object.fromEntries(k.map(h=>[h.id,`${Qa(h.provider)} · ${h.label}`])),onChange:h=>E({model:h},"connection.model")}),a.jsx(De,{label:"Reasoning effort",description:"Mapped to LocalBridge Codex reasoning effort.",value:e.effort,options:["Fast","Normal","Deep"],onChange:h=>E({effort:h},"connection.effort")}),(e.aiProvider??"OpenAI Codex")==="Local Ollama"&&a.jsx(ql,{label:"Ollama URL",description:"Local Ollama endpoint.",value:e.ollamaEndpoint??"http://localhost:11434",onChange:h=>E({ollamaEndpoint:h},"connection.ollamaEndpoint")}),a.jsx(xt,{label:"ImageRouter mode",description:"Key material remains outside this React board snapshot.",checked:e.imageRouterEnabled??!1,onChange:h=>E({imageRouterEnabled:h},"connection.imageRouterEnabled")}),a.jsx(xt,{label:"Parallel insight bundles",description:"Preserves the original CodeMaster insight bundle switch.",checked:e.codeMasterInsightBundlesEnabled??!0,onChange:h=>E({codeMasterInsightBundlesEnabled:h},"connection.codeMasterInsightBundlesEnabled")}),a.jsx($t,{label:"Bundle timeout",description:"Per insight bundle timeout in milliseconds.",value:e.codeMasterInsightBundleTimeoutMs??18e3,min:5e3,max:6e4,onChange:h=>E({codeMasterInsightBundleTimeoutMs:h},"connection.codeMasterInsightBundleTimeoutMs")}),a.jsx($t,{label:"Retry Count (Std)",description:"Retries for lite and standard CodeMaster insight bundle calls.",value:e.codeMasterInsightBundleRetryCount??2,min:1,max:4,step:1,testId:"codemaster-insight-retry-std",onChange:h=>E({codeMasterInsightBundleRetryCount:h},"connection.codeMasterInsightBundleRetryCount")}),a.jsx($t,{label:"Retry Count (Deep)",description:"Retries for deep CodeMaster insight bundle calls.",value:e.codeMasterInsightBundleRetryCountDeep??3,min:1,max:5,step:1,testId:"codemaster-insight-retry-deep",onChange:h=>E({codeMasterInsightBundleRetryCountDeep:h},"connection.codeMasterInsightBundleRetryCountDeep")})]}),a.jsxs("div",{className:"settings-note",children:[a.jsx(ma,{size:15}),a.jsx("span",{children:"API keys are intentionally not stored in this React board. Live provider adapters must supply and verify secrets separately."})]})]}),n==="media"&&a.jsxs("div",{className:"settings-stack","data-testid":"ai-settings-media-tab",children:[a.jsx(Ta,{mode:"Image",icon:a.jsx(ja,{size:17}),selection:F,onModelChange:h=>pe("Image",h),onAspectChange:h=>Ce("Image",h)}),a.jsx(Ta,{mode:"Video",icon:a.jsx(Ii,{size:17}),selection:J,onModelChange:h=>pe("Video",h),onAspectChange:h=>Ce("Video",h)}),a.jsxs("div",{className:"settings-note",children:[a.jsx(ma,{size:15}),a.jsx("span",{children:"These are adapter hints only. Selecting a media model does not store an API key, invoke ImageRouter, or claim live generation availability."})]})]}),n==="agent"&&a.jsx("div",{className:"settings-grid settings-grid--compact",children:a.jsx(De,{label:"Direct instruction queue",description:"How selected agents receive direct instructions.",value:e.directInstructionQueueMode??"Append",options:["Append","Next","ReplacePending"],onChange:h=>E({directInstructionQueueMode:h},"agent.directInstructionQueueMode")})}),n==="system"&&a.jsxs("div",{className:"settings-grid settings-grid--compact",children:[a.jsx(De,{label:"Execution mode",description:"Concept parses IR locally; PureLLM is direct chat adapter mode.",value:e.executionMode??"Concept",options:["Concept","PureLLM"],onChange:h=>E({executionMode:h},"system.executionMode")}),a.jsxs("div",{className:"settings-note",children:[a.jsx(vi,{size:15}),a.jsx("span",{children:"Changing this setting affects the next run only. It does not claim a live agent has executed."})]})]}),n==="about"&&a.jsxs("div",{className:"settings-about",children:[a.jsx(Ci,{size:34}),a.jsx("strong",{children:"MindExec React"}),a.jsx("span",{children:"Fast local-first MindCanvas shell, rebuilt without Blazor in the render loop."}),a.jsx("small",{children:"AI settings parity slice"})]})]}),a.jsx("footer",{className:"ai-settings-footer",children:a.jsx("button",{type:"button","data-testid":"ai-settings-done",onClick:o,children:"Save"})})]})]})})}function ka(e,t){const o=ln(e,t),n=e==="Image"?t.imageRouterImageAspectPresetId:t.imageRouterVideoAspectPresetId,r=cn(e,o,n);return{model:o,aspect:r,aspectOptions:Za(o,e),requestedSize:dn(r)}}function Ul(e){const t=ls(e);return t?`${Qa(t.provider)} text model used by bottom input and AI Task runs.`:"Custom text model id preserved with this board."}function cr(e){switch(e){case"Managed Cloud":return"Reserved for the hosted paid adapter.";case"BYOK":return"Use a separately configured user key.";case"Local Ollama":return"Local LLM server endpoint.";case"Gemini CLI":return"Hidden Gemini CLI compatibility path.";case"OpenAI Codex":default:return"LocalBridge Codex execution path."}}function zl(e){return["dotnet run --project MindExecution.Tools -c Debug -- --count 50 --out finetune_dataset.jsonl","--baseUrl https://openrouter.ai/api/v1",`--model "${(e.trim()||"openai/gpt-4o-mini").replace(/"/g,'\\"')}"`,'--key "OPENROUTER_API_KEY"',"--httpReferer http://localhost",'--xTitle "MindExec DatasetGenerator"'].join(" ")}function $l(e){return!e||e.value.length===0?!1:(e.focus({preventScroll:!0}),e.select(),e.setSelectionRange(0,e.value.length),!0)}function Vl({provider:e,datasetGeneratorCommand:t,copyState:o,onCommandTextAreaRef:n,onCopyDatasetGeneratorCommand:r}){const s=e==="BYOK"?"BYOK Settings":e==="Local Ollama"?"Ollama Settings":e==="Managed Cloud"?"Managed Cloud":e==="Gemini CLI"?"Gemini CLI":"OpenAI Codex";return a.jsxs("section",{className:"settings-provider-card","data-testid":"ai-settings-provider-guidance","data-provider":e,children:[a.jsx("header",{children:a.jsxs("div",{children:[a.jsx("strong",{"data-testid":"ai-settings-provider-title",children:s}),a.jsx("span",{children:cr(e)})]})}),e==="Managed Cloud"&&a.jsx("div",{className:"settings-provider-card__notice",children:"Managed Cloud is coming soon in this build. Switch to BYOK, OpenAI Codex, or Local Ollama for local execution."}),e==="Gemini CLI"&&a.jsx("div",{className:"settings-provider-card__notice","data-testid":"ai-settings-gemini-hidden-provider",children:"Gemini CLI is hidden in this company build. Switch to BYOK, OpenAI Codex, or Local Ollama to manage connection settings here."}),e==="BYOK"&&a.jsxs("div",{className:"settings-provider-card__section",children:[a.jsx("p",{children:"API key material stays outside this React board. Configure the BYOK adapter or environment before running live OpenRouter calls."}),a.jsxs("div",{className:"settings-provider-card__command-head",children:[a.jsx("strong",{children:"DatasetGenerator Export"}),a.jsx("button",{type:"button","data-testid":"ai-settings-provider-copy-command","data-provider-copy-state":o,onClick:()=>void r(),children:o==="copied"?"Copied":o==="selected"?"Selected":o==="failed"?"Copy failed":"Copy command"})]}),a.jsx("textarea",{readOnly:!0,ref:n,value:t,"data-testid":"ai-settings-provider-dataset-command",className:"settings-provider-card__command","aria-label":"Redacted DatasetGenerator command"}),a.jsx("div",{className:"settings-provider-card__note",children:"This command is redacted; no API key is stored in the board. Replace OPENROUTER_API_KEY only in a trusted shell."})]}),e==="OpenAI Codex"&&a.jsxs("div",{className:"settings-provider-card__section",children:[a.jsx("strong",{children:"Connection Requirements"}),a.jsxs("ol",{children:[a.jsxs("li",{children:["Install MindExec LocalBridge dependencies: ",a.jsx("code",{children:"npm install"})]}),a.jsxs("li",{children:["Sign in once: ",a.jsx("code",{children:"codex login"})]}),a.jsx("li",{children:"Runtime: Codex SDK first, Legacy Exec fallback when SDK is unavailable."})]})]}),e==="Local Ollama"&&a.jsxs("div",{className:"settings-provider-card__section",children:[a.jsx("p",{children:"Ollama model selection is handled from the bottom AI input bar. Keep the local endpoint editable below."}),a.jsxs("div",{className:"settings-provider-card__note",children:["Requires ",a.jsx("code",{children:'OLLAMA_ORIGINS="*"'})," when running Ollama for browser access."]})]}),a.jsxs("div",{className:"settings-provider-card__section settings-provider-card__section--image",children:[a.jsx("strong",{children:"Image Generation"}),a.jsx("p",{children:"Text AI provider and image generation provider are configured separately. ImageRouter API key is adapter-owned and used only for image mode."}),a.jsx("span",{children:"ImageRouter API key: not stored in this React board."})]})]})}function Ta({mode:e,icon:t,selection:o,onModelChange:n,onAspectChange:r}){const s=Eo(e),c=Object.fromEntries(s.map(l=>[l.id,`${l.provider} · ${l.label}`])),m=Object.fromEntries(o.aspectOptions.map(l=>[l.id,`${l.label} · ${l.resolvedSize??"auto"}`]));return a.jsxs("section",{className:"settings-media-section","data-testid":`ai-settings-media-${e.toLowerCase()}`,children:[a.jsxs("header",{children:[a.jsx("span",{className:"settings-media-section__icon",children:t}),a.jsxs("span",{children:[a.jsxs("strong",{children:[e," defaults"]}),a.jsxs("small",{children:[o.model.provider," · ",o.requestedSize]})]})]}),a.jsxs("div",{className:"settings-grid settings-grid--compact",children:[a.jsx(De,{label:`${e} model`,description:"Shared with the bottom input model selector.",value:o.model.id,options:s.map(l=>l.id),optionLabels:c,testId:`ai-settings-${e.toLowerCase()}-model`,onChange:n}),a.jsx(De,{label:`${e} aspect`,description:o.aspect.note,value:o.aspect.id,options:o.aspectOptions.map(l=>l.id),optionLabels:m,testId:`ai-settings-${e.toLowerCase()}-aspect`,swatchClassName:ks(o.aspect.id),onChange:r})]})]})}function xt({label:e,description:t,checked:o,onChange:n}){return a.jsxs("label",{className:"setting-row setting-row--toggle",children:[a.jsxs("span",{children:[a.jsx("strong",{children:e}),a.jsx("small",{children:t})]}),a.jsx("input",{type:"checkbox",checked:o,onChange:r=>n(r.target.checked)})]})}function De({label:e,description:t,value:o,options:n,optionLabels:r,testId:s,swatchClassName:c,onChange:m}){return a.jsxs("label",{className:"setting-row",children:[a.jsxs("span",{children:[a.jsx("strong",{children:e}),a.jsx("small",{children:t})]}),a.jsxs("span",{className:"setting-row__select-wrap",children:[c&&a.jsx("span",{className:`aspect-select__swatch ${c}`}),a.jsx("select",{value:o,"data-testid":s,onChange:l=>m(l.target.value),children:n.map(l=>a.jsx("option",{value:l,children:(r==null?void 0:r[l])??l},l))})]})]})}function $t({label:e,description:t,value:o,min:n,max:r,step:s=1,testId:c,onChange:m}){return a.jsxs("label",{className:"setting-row",children:[a.jsxs("span",{children:[a.jsx("strong",{children:e}),a.jsx("small",{children:t})]}),a.jsx("input",{type:"number",min:n,max:r,step:s,"data-testid":c,value:o,onChange:l=>m(Gl(l.target.valueAsNumber,n,r))})]})}function ql({label:e,description:t,value:o,onChange:n}){return a.jsxs("label",{className:"setting-row",children:[a.jsxs("span",{children:[a.jsx("strong",{children:e}),a.jsx("small",{children:t})]}),a.jsx("input",{type:"text",value:o,onChange:r=>n(r.target.value.slice(0,160))})]})}const Wl=1e3,Ia=1536*1024,Kl=3*1024*1024*3/4,Hl=24,Xl=.65,Yl=16,Ql=.92;function wo(e){if(e.byteLength<5)return null;try{const o=new DataView(e).getUint32(0,!1);if(o<2||o>e.byteLength-4)return null;const n=new TextDecoder().decode(new Uint8Array(e,4,o));return{metadata:Jl(JSON.parse(n)),payload:e.slice(4+o)}}catch{return null}}function Jl(e){const t=Zl(e)?e:{};return{type:Ne(t.type)||"remote.frame.binary",kind:Ne(t.kind)||"live",deviceId:Ne(t.deviceId),frameSeq:fe(t.frameSeq),streamId:Ne(t.streamId),width:fe(t.width),height:fe(t.height),mimeType:Ne(t.mimeType)||"image/jpeg",mode:Ne(t.mode),fps:fe(t.fps),capturedAt:Ne(t.capturedAt),receivedAt:Ne(t.receivedAt),byteLength:fe(t.byteLength),transport:Ne(t.transport),contentHash:Ne(t.contentHash),captureMs:fe(t.captureMs),sameContentStreak:fe(t.sameContentStreak),droppedByAgent:fe(t.droppedByAgent),dirtyRectCount:ec(t.dirtyRectCount??t.dirtyRects??t.dirtyRegionCount),dirtyPixelRatio:ur(t.dirtyPixelRatio??t.dirtyRatio??t.dirtyAreaRatio??t.changedPixelRatio),codec:Ne(t.codec??t.encoder??t.encoding),deltaEncoded:pr(t.deltaEncoded??t.isDeltaEncoded??t.deltaFrame)}}function dr(e,t=0){const o=fe(e.captureMs),n=Math.max(fe(e.byteLength),fe(t)),r=fe(e.sameContentStreak),s=fe(e.droppedByAgent),c=fe(e.dirtyRectCount),m=ur(e.dirtyPixelRatio),l=Ne(e.codec),b=pr(e.deltaEncoded),k={captureMs:o,byteLength:n,sameContentStreak:r,droppedByAgent:s,dirtyRectCount:c,dirtyPixelRatio:m,codec:l,deltaEncoded:b};return n>=Kl?{level:"oversized-frame",overBudget:!0,reason:"RemoteFast frame is near the agent binary frame ceiling.",...k}:o>=Wl?{level:"slow-capture",overBudget:!0,reason:"RemoteFast reported a slow screen capture.",...k}:m>=Ql&&n>=Ia?{level:"inefficient-full-frame",overBudget:!0,reason:"RemoteFast dirty-region metadata shows a near-full-frame update with a large payload.",...k}:m>=Xl&&c>=Yl?{level:"dirty-region-heavy",overBudget:!0,reason:"RemoteFast dirty-region metadata shows many changed regions in one frame.",...k}:n>=Ia?{level:"large-frame",overBudget:!0,reason:"RemoteFast frame payload is large enough to create decode or transport pressure.",...k}:r>=Hl?{level:"stable-duplicate",overBudget:!1,reason:"RemoteFast reports repeated identical content that may be eligible for future delta or skip optimization.",...k}:{level:"nominal",overBudget:!1,reason:"",...k}}function Zl(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function Ne(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):""}function fe(e){const t=Number(e);return Number.isFinite(t)&&t>=0?t:0}function ec(e){return Array.isArray(e)?e.length:Math.round(fe(e))}function ur(e){const t=fe(e);return t<=1?t:t<=100?t/100:1}function pr(e){return typeof e=="boolean"?e:typeof e=="number"?e>0:typeof e=="string"?/^(1|true|yes|on|delta)$/i.test(e.trim()):!1}function mr(e){const t=Xe(e.deviceId,256),o=tc({...e.input,controlLeaseId:e.input.controlLeaseId||e.controlLeaseId});return!t||!o.type?null:{type:"input",requestId:Xe(e.requestId,160),deviceId:t,ack:oc(o.type,e.ack),input:o}}function tc(e={}){const t=Number(e.normalizedX),o=Number(e.normalizedY),n=Number(e.deltaX),r=Number(e.deltaY);return{type:Xe(e.type,48),normalizedX:Number.isFinite(t)?lt(t,0,1):void 0,normalizedY:Number.isFinite(o)?lt(o,0,1):void 0,button:Xe(e.button,24),deltaX:Number.isFinite(n)?lt(n,-4096,4096):0,deltaY:Number.isFinite(r)?lt(r,-4096,4096):0,key:Xe(e.key,80),code:Xe(e.code,80),text:ac(e.text,256),repeat:e.repeat===!0,controlLeaseId:Xe(e.controlLeaseId,128),issuedAt:Xe(e.issuedAt,80)}}function oc(e,t){return t===!0||!/^pointermove$/i.test(String(e||"").trim())}function hr(e){let t;try{const n=typeof e=="string"?JSON.parse(e||"{}"):e;if(!gr(n))return null;t=n}catch{return null}const o=wt(t.type||t.Type);return o==="RemoteInputSocketReady"?{type:o,ok:!0,requestId:"",deviceId:"",inputType:"",commandId:"",error:""}:o!=="RemoteInputResult"&&o!=="RemoteInputError"?null:{type:o,ok:t.ok===!0||t.Ok===!0,requestId:wt(t.requestId||t.RequestId),deviceId:wt(t.deviceId||t.DeviceId),inputType:wt(t.inputType||t.InputType),commandId:wt(t.commandId||t.CommandId),error:wt(t.error||t.Error)}}function nc(e,t,o,n=!1){if(!va(t))return null;const r=va(o)?o:{left:0,top:0,width:t.width,height:t.height};let s=Number(e.clientX)-t.left-r.left,c=Number(e.clientY)-t.top-r.top;return!Number.isFinite(s)||!Number.isFinite(c)||(s<0||c<0||s>r.width||c>r.height)&&!n?null:(s=lt(s,0,r.width),c=lt(c,0,r.height),{normalizedX:lt(s/r.width,0,1),normalizedY:lt(c/r.height,0,1)})}function lt(e,t,o){return Math.max(t,Math.min(o,e))}function va(e){if(!gr(e))return!1;const t=Number(e.width),o=Number(e.height);return Number.isFinite(Number(e.left))&&Number.isFinite(Number(e.top))&&Number.isFinite(t)&&Number.isFinite(o)&&t>0&&o>0}function Xe(e,t){return String(e??"").replace(/\0/g,"").trim().slice(0,t)}function ac(e,t){return Xe(e,t)}function wt(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):""}function gr(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function rc(e,t){const o=Math.max(1,Math.floor(t.visibleBudget)),n=t.searchText.trim(),r=n.length>0||t.visibilityFilter!=="connected"||t.capabilityFilter!=="all",s=ic(e,t.visibilityFilter,n,t.capabilityFilter),c=sc(s,t.groupMode),m=c.length,l=Math.max(1,Math.ceil(Math.max(0,m)/o)),b=Number.isFinite(t.pageIndex)?Math.floor(t.pageIndex):0,k=Math.max(0,Math.min(b,l-1)),x=k*o,v=c.slice(x,x+o),V=v.map(ct).filter(Boolean),R=v.filter(E=>E.connected===!0).map(ct).filter(Boolean),F=new Set(v.map(E=>mn(E,t.groupMode))).size,J=c.filter(E=>E.connected===!0&&Ge(E,"taskDispatch")).map(ct).filter(Boolean),Z=c.filter(E=>E.connected===!0&&Ge(E,"taskDispatch")&&Ge(E,"aiAssist")).map(ct).filter(Boolean);return{filterActive:r,filteredDevices:s,projectedDevices:c,visibleDevices:v,visibleDeviceIds:V,visibleConnectedDeviceIds:R,frameSubscriptionDeviceIdSignature:R.join(","),visibleGroupCount:F,projectedCount:m,filteredCount:s.length,pageCount:l,pageIndex:k,pageStart:x,placeholderSlots:Math.max(0,o-v.length),taskDispatchDeviceIds:J,aiTaskDeviceIds:Z}}function ic(e,t,o,n){const r=o.trim().toLocaleLowerCase();return e.filter(s=>lc(s,t)&&cc(s,n)&&dc(s,r))}function sc(e,t){return[...e].sort((o,n)=>{const r=mn(o,t),s=mn(n,t);if(r!==s)return r.localeCompare(s);const c=hn(o).toLocaleLowerCase(),m=hn(n).toLocaleLowerCase();return c!==m?c.localeCompare(m):ct(o).localeCompare(ct(n))})}function mn(e,t){switch(t){case"activity":return br(e);case"platform":return fr(e).toLocaleLowerCase()||"unknown";case"capability":return yr(e);default:return e.connected===!0?"online":"offline"}}function ct(e){return String(e.deviceId||e.sessionId||e.deviceName||"").trim()}function hn(e){return String(e.deviceName||e.hostname||ct(e)||"Remote device").trim()}function fr(e){var t;return String(((t=e.status)==null?void 0:t.platform)||e.platform||"unknown").trim()}function Ge(e,t){var n;const o=(n=e.capabilities)==null?void 0:n[t];return typeof o=="boolean"?o:typeof o=="number"?o!==0:typeof o=="string"?/^(1|true|yes|on)$/i.test(o):!1}function lc(e,t){return t==="all"?!0:t==="offline"?e.connected!==!0:e.connected===!0}function cc(e,t){switch(t){case"control":return Ge(e,"control");case"task":return Ge(e,"taskDispatch");case"ai":return Ge(e,"aiAssist");default:return!0}}function dc(e,t){var n;return t?[ct(e),hn(e),fr(e),gn(e.arch),gn((n=e.latestTask)==null?void 0:n.status),br(e),yr(e),e.connected===!0?"online live connected":"offline disconnected"].join(" ").toLocaleLowerCase().includes(t):!0}function br(e){var o,n,r,s;const t=gn((o=e.latestTask)==null?void 0:o.status).toLocaleLowerCase();return t==="running"||t==="queued"?`task-${t}`:((n=e.activeLiveStream)==null?void 0:n.active)===!0?"live":Number(((r=e.counters)==null?void 0:r.liveFramesReceived)||0)>0?"live-recent":Number(((s=e.counters)==null?void 0:s.thumbnailFramesReceived)||0)>0?"thumbnail":e.lastStatusAt||e.lastSeenAt?"heartbeat":"idle"}function yr(e){return Ge(e,"aiAssist")?"ai-assist":Ge(e,"taskDispatch")?"task-dispatch":Ge(e,"control")?"control":Ge(e,"thumbnail")||Ge(e,"screen")?"screen":"view-only"}function gn(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):""}const Re=30,uc=1200,pc=4200,Ca=12,kr=8e3,mc=1.5,Tr=42,xa="mindexec:remote-monitor-input-smoke",on="connected-screen-wall",fn=90,Ir=240,vr=1e4,Vt=6e4,fo=25e3,hc=250,Io=2e3,Mt=60,wa=2,gc=96,fc=58,qt=[1,1.5,2.25,3.375],Sa=1,bc=5,yc=72,kc=96,Ma="240px",bn="MindExec.RemoteFleet.AutoHost",yn="MindExec.RemoteFleet.AutoHostNodeId",Cr=["status","activity","platform","capability"],xr=["connected","all","offline"],wr=["all","control","task","ai"],Rt=new Map,Zt=new WeakMap;function Ra(e,t=0){if(typeof window>"u")return!0;const o=window.innerWidth||document.documentElement.clientWidth||0,n=window.innerHeight||document.documentElement.clientHeight||0;return o<=0||n<=0?!0:e.right>=-t&&e.bottom>=-t&&e.left<=o+t&&e.top<=n+t}function Sr(e,t,o){const[n,r]=p.useState(()=>typeof document>"u"?!0:document.visibilityState==="visible"),[s,c]=p.useState(!0),m=p.useRef(null);p.useEffect(()=>{if(typeof document>"u")return;const b=()=>r(document.visibilityState==="visible");return b(),document.addEventListener("visibilitychange",b),()=>document.removeEventListener("visibilitychange",b)},[]),p.useEffect(()=>{const b=e.current;if(!b||typeof IntersectionObserver>"u"){c(!0);return}const k=new IntersectionObserver(x=>{const v=x[0],V=!!(v!=null&&v.isIntersecting||((v==null?void 0:v.intersectionRatio)??0)>0),R=Ra(v?v.boundingClientRect:b.getBoundingClientRect(),240);c(V||R)},{root:null,rootMargin:Ma,threshold:0});return k.observe(b),()=>k.disconnect()},[e]);const l=n&&s;return p.useEffect(()=>{if(m.current===l)return;m.current=l;const b={nodeId:t,visible:l,pageVisible:n,viewportVisible:s,rootMargin:Ma};o==="monitor"?g.emit("remoteMonitor.node.transportVisibility",b):g.emit("remoteControl.node.transportVisibility",b)},[t,n,o,s,l]),l}function lu({node:e,onPatch:t,onCreateRemoteControl:o}){var Zn,ea,ta,oa,na,aa,ra,ia,sa,la,ca,da;const n=kn((Zn=e.metadata)==null?void 0:Zn.RemoteTotal,Re),r=kn((ea=e.metadata)==null?void 0:ea.RemoteConnected,0),s=p.useRef(null),c=p.useRef(null),m=Sr(s,e.id,"monitor"),[l,b]=p.useState(()=>({source:Pt()?"loading":"blocked",loading:!1,message:Pt()?"RemoteHub not checked yet.":"Hosted LocalBridge access is gated.",baseUrl:j(),devices:bo(n,r)})),k=p.useRef(new Map),x=p.useRef(new Set),v=p.useRef(new Map),V=p.useRef(new Map),R=p.useRef(new Map),F=p.useRef(null),J=p.useRef(0),Z=p.useRef(0),E=p.useRef(0),ue=p.useRef(!1),B=p.useRef(0),pe=p.useRef(0),Ce=p.useRef(!1),h=p.useRef(!1),ee=p.useRef(!1),L=p.useRef(""),Y=p.useRef(0),Oe=p.useRef(""),W=p.useRef(null),Pe=p.useRef(!1),_e=p.useRef(0),be=p.useRef(0),A=p.useRef(e.metadata??{}),[xe,Fe]=p.useState(""),[S,Q]=p.useState(!1),[te,ne]=p.useState("locked"),[Nt,ae]=p.useState("Remote input locked."),[_o,we]=p.useState(""),[Se,mt]=p.useState(""),[Dt,de]=p.useState(""),[Me,eo]=p.useState(""),[Je,to]=p.useState(""),[Fo,Ue]=p.useState(""),[kt,Ze]=p.useState(0),[Ke,Bo]=p.useState(Sa),[ze,oo]=p.useState("status"),[Ot,no]=p.useState(""),[Ae,ao]=p.useState("connected"),[Ee,ro]=p.useState("all"),[me,ht]=p.useState(()=>nn(e.id)),et=l.source==="bridge"?l.devices.length:l.devices.length||n,y=Ot.trim(),I=p.useMemo(()=>rc(l.devices,{groupMode:ze,visibilityFilter:Ae,searchText:y,capabilityFilter:Ee,pageIndex:kt,visibleBudget:Re}),[Ee,ze,kt,y,l.devices,Ae]),N=I.filterActive,U=I.filteredDevices,z=I.projectedDevices,O=I.projectedCount,P=I.pageCount,_=I.pageIndex,X=I.pageStart,he=I.visibleDevices,tt=I.visibleDeviceIds,$e=I.visibleConnectedDeviceIds,ot=I.frameSubscriptionDeviceIdSignature,Fn=I.visibleGroupCount,Ur=I.placeholderSlots,Go=`${_+1}/${P}`,Bn=P<=1?100:Math.max(12,100/P),zr=P<=1?0:_/Math.max(1,P-1)*(100-Bn),_t=qt[Ke]??qt[Sa],Gn=Math.round(gc*_t),Un=Math.round(fc*_t),oe=p.useMemo(()=>he.find(i=>it(i)===xe)||he.find(i=>i.connected===!0)||he[0],[xe,he]),K=oe?it(oe):"",Ft=l.devices.filter(i=>i.connected===!0).length,Uo=l.devices.reduce((i,d)=>{var u;return i+Number(((u=d.counters)==null?void 0:u.tasksQueued)||0)},0),io=I.taskDispatchDeviceIds,so=I.aiTaskDeviceIds,zo=io.length,Bt=so.length,$o=l.source==="bridge"?(ta=l.hub)!=null&&ta.started?"Online":((oa=l.hub)==null?void 0:oa.enabled)===!1?"Off":"Ready":l.source==="blocked"?"Gated":l.source,lo=l.source==="bridge"?"Local":l.source==="blocked"?"Gated":"Preview",Vo=Ua((na=l.bridge)==null?void 0:na.status),qo=za((aa=l.bridge)==null?void 0:aa.status),zn=l.source==="bridge"&&!!qo,$n=oe?ce(oe,"control"):!1,Wo=oe?ce(oe,"taskDispatch"):!1,nt=p.useMemo(()=>oe?l.source!=="bridge"?"LocalBridge is not connected.":zn?oe.connected!==!0?"Selected device is offline.":$n?"":"RemoteAgent control capability is disabled.":"Remote input adapter is unavailable.":"No screen selected.",[zn,$n,oe,l.source]),Le=nt==="",Ko=S?Er(te):Le?"Locked":"Off",ie=l.source==="bridge"&&((ra=l.hub)==null?void 0:ra.hostTargetActive)===!0&&l.hub.hostTargetNodeId===e.id,re=p.useMemo(()=>vc(l.hub,ie),[ie,l.hub]),Gt=Ac(l.agent,l.source),co=Nr(l.agent),Ho=Dr(l.agent),Ut=p.useMemo(()=>Mc(l.hub,e.id),[e.id,l.hub]),uo=Ec({source:l.source,hasAuth:!!l.auth,isHostActiveForNode:ie,request:Ut,busy:Se}),po=uo==="",mo=l.source==="bridge"&&!!l.auth&&co&&!Se,Vn=l.source==="bridge"&&!!K&&(oe==null?void 0:oe.connected)===!0&&Wo&&!!Me.trim()&&!Je,qn=l.source==="bridge"&&zo>0&&!!Me.trim()&&!Je,Wn=l.source==="bridge"&&Bt>0&&!!Me.trim()&&!Je,$r=Fo||Dt||_o||(l.source==="bridge"&&oe?`${ft(oe)}: ${Nt}`:l.message),Kn=p.useMemo(()=>wc(l.latestTaskBatch,l.recentTaskBatches),[l.latestTaskBatch,l.recentTaskBatches]),ke=Sc(Kn),gt=l.source==="bridge"&&!!(Kn&&ke);p.useEffect(()=>{A.current=e.metadata??{}},[e.metadata]);const Hn=p.useCallback((i,d)=>{const u=A.current??{},f=Object.entries(d).filter(([C,M])=>u[C]!==M).map(([C])=>C);if(f.length===0)return;const T={...u,...d};A.current=T,t(e.id,{metadata:T}),g.emit("remoteMonitor.node.metadata.patch",{nodeId:e.id,reason:i,keys:f})},[e.id,t]);p.useEffect(()=>{l.loading||Hn("snapshot",Ic({source:l.source,hub:l.hub,baseUrl:l.baseUrl,hubLabel:$o,routeLabel:lo,connected:Ft,total:et,taskCount:Uo,taskDispatchCount:zo,aiCount:Bt,pageLabel:Go,pageStart:X,pageIndex:_,pageCount:P,projectionMode:on,projectedCount:O,visibleBudget:Re,selectedDeviceId:K,inputLabel:Ko,devices:l.devices,latestTaskBatch:l.latestTaskBatch,recentTaskBatches:l.recentTaskBatches,taskFollowActive:gt,taskFollowKey:ke,isHostActiveForNode:ie,registryRouteInfo:re,hostTargetRenewMs:ie?fo:0,autoHostEnabled:me,agent:l.agent,agentStatusLabel:Gt,agentRunning:co,agentReady:Ho,message:l.message}))},[Bt,me,_,Ft,Ho,co,Gt,$o,Ko,ie,P,Go,X,Hn,O,re,lo,K,l.agent,l.baseUrl,l.devices,l.hub,l.latestTaskBatch,l.loading,l.message,l.recentTaskBatches,l.source,gt,ke,Uo,zo,et]),p.useEffect(()=>{kt!==_&&Ze(_)},[_,kt]),p.useEffect(()=>{const i=new Set(tt);for(const d of k.current.keys())i.has(d)||k.current.delete(d)},[tt]),p.useEffect(()=>{g.emit("remoteMonitor.node.frameSubscription",{nodeId:e.id,deviceCount:m?$e.length:0,visibleDeviceCount:$e.length,transportVisible:m,pageIndex:_,pageStart:X,visibleBudget:Re,transportKey:ot})},[_,e.id,X,m,$e.length,ot]),p.useEffect(()=>{if(l.source!=="bridge")return;const i=[re.status,re.reason,re.accountRouteReady?"ready":"local",re.migrationBlocked?"migration":"",ie?"hosting":"inactive"].join("|");Oe.current!==i&&(Oe.current=i,g.emit("remoteMonitor.node.registryRoute",{nodeId:e.id,status:re.status,reason:re.reason,accountRouteReady:re.accountRouteReady,migrationBlocked:re.migrationBlocked,hostTargetActive:ie}))},[ie,e.id,re,l.source]),p.useEffect(()=>{ht(nn(e.id))},[e.id]);const Tt=p.useCallback((i,d)=>{Ze(u=>{const f=Math.max(0,Math.min(P-1,u+i));return f!==u&&g.emit("remoteMonitor.node.page",{nodeId:e.id,from:u,to:f,pageCount:P,visibleBudget:Re,source:d}),f})},[e.id,P]),Xn=p.useCallback((i,d)=>{i.stopPropagation(),Tt(d,"button")},[Tt]),Yn=p.useCallback((i,d)=>{i.preventDefault(),i.stopPropagation(),Bo(u=>{const f=Math.max(0,Math.min(qt.length-1,u+d));return f!==u&&g.emit("remoteMonitor.node.tileScale",{nodeId:e.id,from:u,to:f,scale:qt[f],visibleBudget:Re}),f})},[e.id]);p.useEffect(()=>{var i;(i=c.current)==null||i.scrollTo({left:0,top:0,behavior:"auto"}),_e.current=0},[_,Ke,ot]);const at=p.useCallback(i=>{if(i instanceof HTMLElement){const d=i.closest('[data-testid="remote-monitor-node-wall"]');if(d instanceof HTMLDivElement)return d}return c.current},[]),Qn=p.useCallback(i=>i.scrollWidth>i.clientWidth+1||i.scrollHeight>i.clientHeight+1,[]),Xo=p.useCallback(i=>{if(i.button!==0&&i.button!==1)return;const d=i.target instanceof HTMLElement?i.target:null;if(d!=null&&d.closest('button,input,textarea,select,[contenteditable="true"],[contenteditable=""]'))return;const u=at(i.target);if(u){W.current={active:!0,pointerId:i.pointerId,startX:i.clientX,startY:i.clientY,lastX:i.clientX,lastY:i.clientY,scrollLeft:u.scrollLeft,scrollTop:u.scrollTop,didPan:!1,pageTriggered:!1},i.preventDefault(),i.stopPropagation();try{i.currentTarget.setPointerCapture(i.pointerId)}catch{}}},[at]),Yo=p.useCallback(i=>{const d=W.current;if(!(d!=null&&d.active)||d.pointerId!==i.pointerId)return;const u=at(i.target);if(!u)return;const f=i.clientX-d.startX,T=i.clientY-d.startY;if(!d.didPan&&Math.max(Math.abs(f),Math.abs(T))>=bc&&(d.didPan=!0,Pe.current=!0),d.didPan){u.scrollLeft=d.scrollLeft-f,u.scrollTop=d.scrollTop-T;const C=Math.abs(T)>=Math.abs(f)?T:f;!d.pageTriggered&&P>1&&!Qn(u)&&Math.abs(C)>=yc&&(d.pageTriggered=!0,Tt(C<0?1:-1,"drag"))}d.lastX=i.clientX,d.lastY=i.clientY,i.preventDefault(),i.stopPropagation()},[Qn,Tt,at,P]),It=p.useCallback(i=>{const d=W.current;if(!(!(d!=null&&d.active)||d.pointerId!==i.pointerId)){W.current=null;try{i.currentTarget.releasePointerCapture(i.pointerId)}catch{}if(d.didPan){const u=at(i.target);g.emit("remoteMonitor.node.wallPan",{nodeId:e.id,source:"drag",dx:Math.round(d.lastX-d.startX),dy:Math.round(d.lastY-d.startY),scrollLeft:Math.round((u==null?void 0:u.scrollLeft)??0),scrollTop:Math.round((u==null?void 0:u.scrollTop)??0),pageIndex:_,pageCount:P}),i.preventDefault(),i.stopPropagation()}}},[_,at,e.id,P]),Vr=p.useCallback(i=>{const d=i.target instanceof HTMLElement?i.target:null;if(d!=null&&d.closest('[data-input-active="true"]'))return;const u=at(i.target);if(!u)return;const f=u.scrollLeft,T=u.scrollTop;u.scrollLeft+=i.deltaX,u.scrollTop+=i.deltaY;const C=u.scrollLeft!==f||u.scrollTop!==T;!C&&P>1&&Math.abs(i.deltaY)>=Math.abs(i.deltaX)&&(_e.current+=i.deltaY,Math.abs(_e.current)>=kc&&(Tt(_e.current>0?1:-1,"wheel"),_e.current=0)),g.emit("remoteMonitor.node.wallPan",{nodeId:e.id,source:"wheel",dx:Math.round(i.deltaX),dy:Math.round(i.deltaY),moved:C,scrollLeft:Math.round(u.scrollLeft),scrollTop:Math.round(u.scrollTop),pageIndex:_,pageCount:P}),i.preventDefault(),i.stopPropagation()},[Tt,_,at,e.id,P]),qr=p.useCallback(i=>{i.stopPropagation();const d=Lc(i.target.value);oo(u=>u===d?u:(g.emit("remoteMonitor.node.groupMode",{nodeId:e.id,from:u,to:d,projectedCount:z.length,visibleBudget:Re}),d)),Ze(0)},[z.length,e.id]),Wr=p.useCallback(i=>{i.stopPropagation();const d=i.target.value.slice(0,64);no(u=>u===d?u:(g.emit("remoteMonitor.node.filter",{nodeId:e.id,reason:"search",searchText:d.trim(),visibilityFilter:Ae,capabilityFilter:Ee,projectedCount:z.length,visibleBudget:Re}),d)),Ze(0)},[Ee,z.length,e.id,Ae]),Kr=p.useCallback(i=>{i.stopPropagation();const d=jc(i.target.value);ao(u=>u===d?u:(g.emit("remoteMonitor.node.filter",{nodeId:e.id,reason:"visibility",searchText:y,from:u,to:d,visibilityFilter:d,capabilityFilter:Ee,projectedCount:z.length,visibleBudget:Re}),d)),Ze(0)},[Ee,z.length,e.id,y]),Hr=p.useCallback(i=>{i.stopPropagation();const d=Nc(i.target.value);ro(u=>u===d?u:(g.emit("remoteMonitor.node.filter",{nodeId:e.id,reason:"capability",searchText:y,visibilityFilter:Ae,from:u,to:d,capabilityFilter:d,projectedCount:z.length,visibleBudget:Re}),d)),Ze(0)},[z.length,e.id,y,Ae]),Xr=p.useCallback((i,d)=>{i.stopPropagation();const u=it(d);if(!u||!o)return;const f=Wt(d);o({sourceNodeId:e.id,deviceId:u,deviceName:ft(d),platform:Xt(d),connected:d.connected===!0,baseUrl:l.baseUrl,framePath:f==null?void 0:f.framePath,frameUrl:f==null?void 0:f.frameUrl,dataUrl:f==null?void 0:f.dataUrl,frameSeq:f==null?void 0:f.frameSeq}),g.emit("remoteMonitor.node.controlNode.create",{nodeId:e.id,deviceId:u,source:l.source})},[e.id,o,l.baseUrl,l.source]),se=p.useCallback(async(i="manual")=>{const d=++be.current,u=j();if(b(f=>({...f,loading:!0,baseUrl:u})),!Pt()){const f=bo(n,r);b({source:"blocked",loading:!1,message:"Hosted LocalBridge access is gated.",baseUrl:u,devices:f}),g.emit("remoteMonitor.node.preview",{nodeId:e.id,reason:"hosted-localbridge-gated",total:f.length});return}try{const f=await In(u);if(d!==be.current)return;if(f.state!=="connected"){const Te=bo(n,r);b({source:"unavailable",loading:!1,message:f.message||"LocalBridge is unavailable.",baseUrl:u,bridge:f,devices:Te}),g.emit("remoteMonitor.node.preview",{nodeId:e.id,reason:"localbridge-unavailable",total:Te.length});return}const T=Wa(f.status),C=Zi(T,u).catch(Te=>{g.emit("remoteMonitor.node.agent.status",{nodeId:e.id,reason:i,ok:!1,error:Te instanceof Error?Te.message:String(Te)})}),[M,$,G]=await Promise.all([Ka(T,u),Ha(T,u,{includeDataUrl:!1}),C]);if(d!==be.current)return;const ge=Array.isArray($.devices)?$.devices:[];b({source:"bridge",loading:!1,message:M.started?"RemoteHub online.":M.enabled===!1?M.lastError||"RemoteHub adapter is not configured.":"RemoteHub available.",baseUrl:u,bridge:f,auth:T,hub:M,agent:G,latestTaskBatch:$.latestTaskBatch,recentTaskBatches:Array.isArray($.recentTaskBatches)?$.recentTaskBatches:[],devices:ge}),g.emit("remoteMonitor.node.refresh",{nodeId:e.id,reason:i,total:$.total??ge.length,connected:ge.filter(Te=>Te.connected===!0).length,agentStatus:w(G==null?void 0:G.status),agentRunning:(G==null?void 0:G.running)===!0}),G&&g.emit("remoteMonitor.node.agent.status",{nodeId:e.id,reason:i,ok:!0,status:w(G.status),running:G.running===!0,ready:G.ready===!0})}catch(f){if(d!==be.current)return;const T=bo(n,r);b({source:"unavailable",loading:!1,message:f instanceof Error?f.message:String(f),baseUrl:u,devices:T}),g.emit("remoteMonitor.node.preview",{nodeId:e.id,reason:"remotehub-error",total:T.length})}},[r,n,e.id]);p.useEffect(()=>{se("mount")},[se]);const zt=p.useCallback((i,d,u)=>{const f=Br(R.current,i);if(!f)return!1;const{cached:T,scope:C}=f;return Mo(d,T,x.current,v.current).then(M=>{M&&g.emit("remoteMonitor.node.frameCache",{nodeId:e.id,deviceId:i,frameSeq:pt(T.metadata),scope:C,reason:u})}),!0},[e.id]),Yr=p.useCallback((i,d)=>{i&&(d?(k.current.set(i,d),zt(i,d,"canvas-attach")):k.current.delete(i))},[zt]);p.useEffect(()=>{for(const i of he){const d=it(i),u=k.current.get(d);if(!u)continue;const f=Wt(i),T=Nn(f);l.source==="bridge"&&T?Tn(u,d,f,l.baseUrl,x.current,v.current,R.current).then(C=>{C.painted||C.busy||(C.staleDropped&&g.emit("remoteMonitor.node.frameStaleDropped",{nodeId:e.id,deviceId:d,frameSeq:C.frameSeq,previous:C.previous,source:"projection"}),!(l.source==="bridge"&&zt(d,u,"projection-rerender"))&&Ro(u,i,l.source))}):l.source==="bridge"&&zt(d,u,"projection-rerender")||Ro(u,i,l.source)}},[e.id,zt,l.baseUrl,l.source,he]);const Qo=p.useCallback(async(i,d)=>{const u=w(i.deviceId).trim();if(!u)return;const f=w(i.streamId).trim(),T=Number(i.frameSeq||0)||0,C=Dn(v.current,R.current,u),M=V.current.get(u)||"",$=!!(f&&M&&f!==M);if($&&(v.current.delete(u),g.emit("remoteMonitor.node.frameStreamReset",{nodeId:e.id,deviceId:u,fromStreamId:M,toStreamId:f,previous:C,frameSeq:T})),!$&&T>0&&T<=C){g.emit("remoteMonitor.node.frameStaleDropped",{nodeId:e.id,deviceId:u,frameSeq:T,previous:C,source:"ws"});return}const G=dr(i,d.byteLength);G.level!=="nominal"&&g.emit("remoteMonitor.node.framePressure",{nodeId:e.id,deviceId:u,frameSeq:T,streamId:f,...G});const ge=_r(R.current,u,i,d),Te=k.current.get(u);if(Te){if(x.current.has(u)){g.emit("remoteMonitor.node.frameCache",{nodeId:e.id,deviceId:u,frameSeq:T,scope:"local",reason:"decode-pending"});return}x.current.add(u);try{await On(Te,ge.metadata,ge.payload)&&(T>0&&v.current.set(u,T),f&&V.current.set(u,f),E.current+=1,E.current%12===1&&g.emit("remoteMonitor.node.framePainted",{nodeId:e.id,deviceId:u,frameSeq:T,streamId:i.streamId||"",painted:E.current,source:"ws"}))}catch{}finally{x.current.delete(u);const je=R.current.get(u),He=pt(je==null?void 0:je.metadata),ua=v.current.get(u)||0,pa=k.current.get(u);je&&pa&&(He<=0?ua<=0:He>ua)&&Mo(pa,je,x.current,v.current).then(hi=>{hi&&(E.current+=1,g.emit("remoteMonitor.node.frameCache",{nodeId:e.id,deviceId:u,frameSeq:He,scope:"local",reason:"latest-pending"}),g.emit("remoteMonitor.node.framePainted",{nodeId:e.id,deviceId:u,frameSeq:He,streamId:je.metadata.streamId||"",painted:E.current,source:"ws-cache"}))})}}},[e.id]);p.useEffect(()=>{if(l.source!=="bridge"||!m||!Vo)return;const i=Pa(ot);if(i.length===0)return;let d=!1,u=null,f=0;const T=()=>{var C,M;if(!d){ue.current=!1;try{u=new WebSocket(Ar(l.baseUrl,Vo,(M=(C=l.bridge)==null?void 0:C.status)==null?void 0:M.bridgeToken,i)),u.binaryType="arraybuffer"}catch($){g.emit("remoteMonitor.node.frameWs",{nodeId:e.id,ok:!1,error:$ instanceof Error?$.message:String($)});return}u.onopen=()=>{ue.current=!0,B.current=performance.now(),g.emit("remoteMonitor.node.frameWs",{nodeId:e.id,ok:!0,deviceCount:i.length,fps:Ca}),u==null||u.send(JSON.stringify({type:"subscribe",deviceIds:i,autoStartLive:!0,fps:Ca,maxWidth:640,maxHeight:360,quality:55,mode:"remote-fast"}))},u.onmessage=async $=>{if(!d){if(B.current=performance.now(),$.data instanceof ArrayBuffer){const G=wo($.data);G&&await Qo(G.metadata,G.payload);return}if($.data instanceof Blob){const G=wo(await $.data.arrayBuffer());G&&await Qo(G.metadata,G.payload)}}},u.onerror=()=>{g.emit("remoteMonitor.node.frameWs",{nodeId:e.id,ok:!1,reason:"socket-error"})},u.onclose=()=>{ue.current=!1,d||(f=window.setTimeout(T,1500))}}};return T(),()=>{d=!0,ue.current=!1,window.clearTimeout(f),u==null||u.close()}},[e.id,Qo,Vo,l.baseUrl,(sa=(ia=l.bridge)==null?void 0:ia.status)==null?void 0:sa.bridgeToken,l.source,m,ot]),p.useEffect(()=>{if(l.source!=="bridge"||!m)return;const i=Pa(ot);if(i.length===0)return;let d=!1,u=!1;const f=async()=>{var M;if(!(d||u)&&!(ue.current&&performance.now()-B.current<kr)){u=!0;try{const $=await Xa(i,l.auth,l.baseUrl);if(d||$.ok===!1)return;let G=0,ge=0;for(const Te of $.frames||[]){const je=String(Te.deviceId||"").trim();if(!je)continue;const He=await Tn(k.current.get(je),je,Or(Te),l.baseUrl,x.current,v.current,R.current);He.painted&&(G+=1),He.staleDropped&&(ge+=1,g.emit("remoteMonitor.node.frameStaleDropped",{nodeId:e.id,deviceId:je,frameSeq:He.frameSeq,previous:He.previous,source:"snapshot"}))}g.emit("remoteMonitor.node.frameSnapshot",{nodeId:e.id,deviceCount:i.length,frameCount:((M=$.frames)==null?void 0:M.length)||0,painted:G,staleDropped:ge})}catch{}finally{u=!1}}},T=window.setTimeout(f,200),C=window.setInterval(f,pc);return()=>{d=!0,window.clearTimeout(T),window.clearInterval(C)}},[e.id,l.auth,l.baseUrl,l.source,m,ot]),p.useEffect(()=>{Q(!1),ne("locked"),ae("Remote input locked.")},[K,l.source]),p.useEffect(()=>{!S||Le||(Q(!1),ne("unavailable"),ae(nt||"Remote input unavailable."),g.emit("remoteMonitor.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"control-unavailable",deviceId:K}))},[Le,nt,S,e.id,K]),p.useEffect(()=>{var u,f,T;if(!S){(u=F.current)==null||u.close(),F.current=null,ne("locked");return}if(!Le||!K){ne("unavailable"),ae(nt||"Remote input unavailable.");return}let i=!1,d=null;ne("connecting"),ae("Connecting remote input adapter...");try{d=new WebSocket(Rr(l.baseUrl,qo,(T=(f=l.bridge)==null?void 0:f.status)==null?void 0:T.bridgeToken)),F.current=d}catch(C){const M=C instanceof Error?C.message:String(C);ne("error"),ae(M),g.emit("remoteMonitor.node.input.ws",{nodeId:e.id,ok:!1,deviceId:K,error:M});return}return d.onopen=()=>{i||(ne("ready"),ae("Remote input ready."),g.emit("remoteMonitor.node.input.ws",{nodeId:e.id,ok:!0,deviceId:K}))},d.onmessage=C=>{if(i)return;const M=hr(String(C.data||"{}"));if(M){if(M.type==="RemoteInputSocketReady"){ne("ready");return}g.emit("remoteMonitor.node.input.result",{nodeId:e.id,ok:M.ok,deviceId:M.deviceId||K,inputType:M.inputType,error:M.error}),!M.ok||M.error?ae(M.error||"Remote input failed."):/^pointermove$/i.test(M.inputType)||ae(`${M.inputType||"Input"} queued.`)}},d.onerror=()=>{i||(ne("error"),ae("Remote input socket error."),g.emit("remoteMonitor.node.input.ws",{nodeId:e.id,ok:!1,deviceId:K,reason:"socket-error"}))},d.onclose=()=>{i||(F.current=null,ne("error"),ae("Remote input socket closed."),g.emit("remoteMonitor.node.input.ws",{nodeId:e.id,ok:!1,deviceId:K,reason:"socket-closed"}))},()=>{i=!0,F.current===d&&(F.current=null),d==null||d.close()}},[Le,nt,S,e.id,qo,K,l.baseUrl,(ca=(la=l.bridge)==null?void 0:la.status)==null?void 0:ca.bridgeToken]),p.useEffect(()=>{if(!S)return;const i=d=>{d.key==="Escape"&&(d.preventDefault(),Q(!1),ae("Remote input locked."),g.emit("remoteMonitor.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"escape",deviceId:K}))};return window.addEventListener("keydown",i,!0),()=>window.removeEventListener("keydown",i,!0)},[S,e.id,K]);const Qr=p.useCallback(i=>{i.stopPropagation(),qa(!0),g.emit("remoteMonitor.node.hostedAccess.enabled",{nodeId:e.id}),se("hosted-access-enabled")},[e.id,se]),Jn=p.useCallback(i=>{i.stopPropagation(),se("manual")},[se]),Jr=p.useCallback(async i=>{var d,u,f;if(i.stopPropagation(),!po){de(uo||"RemoteAgent connect unavailable.");return}mt("connect"),de("Connecting RemoteAgent...");try{const T=await es(Ut,l.auth,l.baseUrl);T.agent&&b(M=>M.source==="bridge"?{...M,agent:T.agent,message:M.message}:M);const C=T.ok===!0;de(C?T.alreadyRunning===!0?"RemoteAgent already running.":T.skipped===!0?T.reason||"RemoteAgent connect skipped.":"RemoteAgent connect requested.":T.error||"RemoteAgent connect failed."),g.emit("remoteMonitor.node.agent.connect",{nodeId:e.id,ok:C,alreadyRunning:T.alreadyRunning===!0,skipped:T.skipped===!0,reason:T.reason||"",status:w((d=T.agent)==null?void 0:d.status),managerCount:((u=Ut.managerCandidates)==null?void 0:u.length)??0,error:T.error||""}),C&&await se("agent-connect")}catch(T){const C=T instanceof Error?T.message:String(T);de(C),g.emit("remoteMonitor.node.agent.connect",{nodeId:e.id,ok:!1,managerCount:((f=Ut.managerCandidates)==null?void 0:f.length)??0,error:C})}finally{mt("")}},[po,e.id,se,uo,Ut,l.auth,l.baseUrl]),Zr=p.useCallback(async i=>{var d;if(i.stopPropagation(),!mo){de("RemoteAgent is not running.");return}mt("disconnect"),de("Stopping RemoteAgent...");try{const u=await ts("react-remote-monitor-manual",l.auth,l.baseUrl);u.agent&&b(T=>T.source==="bridge"?{...T,agent:u.agent,message:T.message}:T);const f=u.ok===!0;de(f?"RemoteAgent stopped.":u.error||"RemoteAgent stop failed."),g.emit("remoteMonitor.node.agent.disconnect",{nodeId:e.id,ok:f,status:w((d=u.agent)==null?void 0:d.status),error:u.error||""}),f&&await se("agent-disconnect")}catch(u){const f=u instanceof Error?u.message:String(u);de(f),g.emit("remoteMonitor.node.agent.disconnect",{nodeId:e.id,ok:!1,error:f})}finally{mt("")}},[mo,e.id,se,l.auth,l.baseUrl]),ei=p.useCallback(async i=>{var u;i.stopPropagation();const d=jr(l.hub);try{const f=await An(d);we("Connect command copied."),g.emit("remoteMonitor.node.connectCommand.copy",{nodeId:e.id,ok:!0,method:f,source:l.source,hasPairPreview:!!((u=l.hub)!=null&&u.pairTokenPreview)})}catch(f){we(f instanceof Error?f.message:"Clipboard is unavailable."),g.emit("remoteMonitor.node.connectCommand.copy",{nodeId:e.id,ok:!1})}},[e.id,l.hub,l.source]),vt=p.useCallback(async(i,d)=>{if(l.source!=="bridge"||Ce.current)return!1;Ce.current=!0,we(i?"Requesting host target...":"Clearing host target...");try{const u=await ha(e.id,i,l.auth,l.baseUrl,{leaseMs:Vt});if(u.ok===!0){const f=i&&u.active===!0;Aa(e.id,f),ht(f)}return we(u.ok===!0?u.active?"This monitor node is the host target.":"Host target cleared.":u.error||"Host target update failed."),g.emit("remoteMonitor.node.hostTarget",{nodeId:e.id,reason:d,autoHost:me,ok:u.ok===!0,active:u.active===!0}),await se("host-target"),u.ok===!0&&(i?u.active===!0:u.active!==!0)}catch(u){return we(u instanceof Error?u.message:String(u)),g.emit("remoteMonitor.node.hostTarget",{nodeId:e.id,reason:d,autoHost:me,ok:!1}),!1}finally{Ce.current=!1}},[me,e.id,se,l.auth,l.baseUrl,l.source]),ti=p.useCallback(i=>{i.stopPropagation(),vt(!ie,"manual")},[ie,vt]),oi=p.useCallback(i=>{i.stopPropagation();const d=!me;Aa(e.id,d),ht(d),we(d?"Auto Host enabled for this monitor.":"Auto Host disabled."),g.emit("remoteMonitor.node.autoHost",{nodeId:e.id,enabled:d,source:l.source}),!d&&ie&&vt(!1,"auto-host-disabled")},[me,ie,e.id,vt,l.source]);p.useEffect(()=>{if(l.source!=="bridge"||!me||ie||ee.current)return;if(!nn(e.id)){ht(!1);return}let i=!1;return ee.current=!0,we("Restoring Auto Host..."),g.emit("remoteMonitor.node.autoHost.restore",{nodeId:e.id,requested:!0,source:l.source}),vt(!0,"auto-host-restore").then(d=>{i||(g.emit("remoteMonitor.node.autoHost.restore",{nodeId:e.id,ok:d,source:l.source}),d||we("Auto Host restore failed."))}).finally(()=>{ee.current=!1}),()=>{i=!0}},[me,ie,e.id,vt,l.source]),p.useEffect(()=>{if(l.source!=="bridge"||!ie)return;let i=!1;const d=async()=>{if(!(i||h.current)){h.current=!0;try{const f=await ha(e.id,!0,l.auth,l.baseUrl,{leaseMs:Vt});g.emit("remoteMonitor.node.hostTarget.renew",{nodeId:e.id,ok:f.ok===!0,active:f.active===!0,leaseMs:Vt}),!i&&(f.ok!==!0||f.active!==!0)&&(we(f.error||"Host target renewal lost ownership."),await se("host-target-renew"))}catch(f){g.emit("remoteMonitor.node.hostTarget.renew",{nodeId:e.id,ok:!1,active:!1,leaseMs:Vt,error:f instanceof Error?f.message:String(f)}),i||we(f instanceof Error?f.message:String(f))}finally{h.current=!1}}},u=window.setInterval(()=>{d()},fo);return g.emit("remoteMonitor.node.hostTarget.renew.timer",{nodeId:e.id,active:!0,intervalMs:fo,leaseMs:Vt}),()=>{i=!0,window.clearInterval(u),g.emit("remoteMonitor.node.hostTarget.renew.timer",{nodeId:e.id,active:!1})}},[ie,e.id,se,l.auth,l.baseUrl,l.source]),p.useEffect(()=>{if(l.source!=="bridge"||!gt||!ke){gt||(L.current="",Y.current=0);return}let i=!1,d=0;L.current!==ke&&(L.current=ke,Y.current=0);const u=f=>{window.clearTimeout(d),d=window.setTimeout(async()=>{if(i||L.current!==ke)return;const T=Y.current;if(T>=Mt){g.emit("remoteMonitor.node.task.follow",{nodeId:e.id,active:!1,batchKey:ke,tick:T,maxTicks:Mt,reason:"max-ticks"});return}const C=T+1;Y.current=C,g.emit("remoteMonitor.node.task.follow",{nodeId:e.id,active:!0,batchKey:ke,tick:C,maxTicks:Mt}),await se("task-follow"),!i&&L.current===ke&&Y.current<Mt&&u(Io)},Math.max(0,f))};return g.emit("remoteMonitor.node.task.follow",{nodeId:e.id,active:!0,batchKey:ke,intervalMs:Io,maxTicks:Mt,reason:"start"}),u(hc),()=>{i=!0,window.clearTimeout(d),g.emit("remoteMonitor.node.task.follow",{nodeId:e.id,active:!1,batchKey:ke,tick:Y.current,reason:"cleanup"})}},[e.id,se,l.source,gt,ke]);const ni=p.useCallback(i=>{if(i.stopPropagation(),S){Q(!1),ae("Remote input locked."),g.emit("remoteMonitor.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"manual",deviceId:K});return}if(!Le){ne("unavailable"),ae(nt||"Remote input unavailable."),g.emit("remoteMonitor.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"unavailable",deviceId:K});return}Q(!0),ae("Connecting remote input adapter..."),g.emit("remoteMonitor.node.input.lock",{nodeId:e.id,unlocked:!0,reason:"manual",deviceId:K})},[Le,nt,S,e.id,K]),Ve=p.useCallback(i=>{var $;const d=F.current;if(!S||!Le||!K||(d==null?void 0:d.readyState)!==WebSocket.OPEN){i.ack&&ae(S?"Remote input socket is not ready.":"Remote input locked.");return}const u=`remote-node-input-${Date.now()}-${++J.current}`,{ack:f,...T}=i,C=mr({requestId:u,deviceId:K,ack:f,controlLeaseId:($=l.hub)==null?void 0:$.hostTargetLeaseId,input:T});if(!C){f&&ae("Remote input payload is invalid.");return}const M=w(C.input.type);try{d.send(JSON.stringify(C));const G=++Z.current;(C.ack||G%24===1)&&g.emit("remoteMonitor.node.input.sent",{nodeId:e.id,deviceId:K,inputType:M,sampled:!C.ack,sent:G})}catch(G){const ge=G instanceof Error?G.message:String(G);ne("error"),ae(ge),g.emit("remoteMonitor.node.input.ws",{nodeId:e.id,ok:!1,deviceId:K,error:ge})}},[Le,S,e.id,K,(da=l.hub)==null?void 0:da.hostTargetLeaseId]);p.useEffect(()=>{if(typeof document>"u")return;const i=d=>{const u=d.detail;if(!u||typeof u!="object")return;const f=w(u.nodeId);if(f&&f!==e.id)return;const T=w(u.deviceId);if(T&&T!==K)return;const C=u.input;!C||typeof C!="object"||Array.isArray(C)||Ve({...C,ack:u.ack!==!1})};return document.addEventListener(xa,i),()=>document.removeEventListener(xa,i)},[e.id,K,Ve]);const Ct=p.useCallback((i,d,u,f=!1)=>{const T=So(i,f);return T?(Ve({type:d,...T,button:Pr(i.button),ack:u}),!0):!1},[Ve]),ai=p.useCallback((i,d,u)=>{if(i.stopPropagation(),Fe(d),!u){Xo(i);return}if(Ct(i,"pointerDown",!0,!1)){i.preventDefault(),i.currentTarget.focus();try{i.currentTarget.setPointerCapture(i.pointerId)}catch{}}},[Ct,Xo]),ri=p.useCallback((i,d)=>{var C,M;if(!d){Yo(i);return}const u=performance.now();if(u-pe.current<Tr)return;pe.current=u;const f=((M=(C=i.currentTarget).hasPointerCapture)==null?void 0:M.call(C,i.pointerId))===!0;Ct(i,"pointerMove",!1,f)&&(i.preventDefault(),i.stopPropagation())},[Ct,Yo]),ii=p.useCallback((i,d)=>{if(!d){It(i);return}i.preventDefault(),i.stopPropagation();try{i.currentTarget.releasePointerCapture(i.pointerId)}catch{}Ct(i,"pointerUp",!0,!0)},[Ct,It]),si=p.useCallback((i,d)=>{d||It(i)},[It]),li=p.useCallback((i,d)=>{if(!d)return;const u=So(i,!1);u&&(Ve({type:"wheel",...u,deltaX:i.deltaX,deltaY:i.deltaY,ack:!0}),i.preventDefault(),i.stopPropagation())},[Ve]),ci=p.useCallback((i,d,u)=>{if(!u){(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),i.stopPropagation(),Fe(d));return}i.key!=="Escape"&&(i.preventDefault(),i.stopPropagation(),Ve({type:"keyDown",key:i.key,code:i.code,repeat:i.repeat,ack:!0}))},[Ve]),di=p.useCallback((i,d)=>{!d||i.key==="Escape"||(i.preventDefault(),i.stopPropagation(),Ve({type:"keyUp",key:i.key,code:i.code,repeat:!1,ack:!0}))},[Ve]),Jo=p.useCallback(async(i,d="selected")=>{var M;if(i.preventDefault(),i.stopPropagation(),l.source!=="bridge"){Ue("LocalBridge is not connected.");return}const u=Me.trim();if(!u){Ue("Remote task is empty.");return}if(d==="selected"&&(!K||!Wo||(oe==null?void 0:oe.connected)!==!0)){Ue("Selected device cannot accept remote tasks.");return}if(d==="all"&&io.length<=0){Ue("No task-capable connected devices are available.");return}if(d==="ai"&&so.length<=0){Ue("No AI assist devices are connected.");return}const f=d==="ai"?"ai-assist":"task-only",T=((M=u.split(/\r?\n/)[0])==null?void 0:M.slice(0,96))||"Remote task",C=d==="ai"?so:io;to(d),Ue(d==="selected"?"Queueing selected task...":"Queueing fleet task...");try{const $=d==="selected"?await Ya(K,{instruction:u,title:T,approvalLevel:f},l.auth,l.baseUrl):await os({instruction:u,title:T,approvalLevel:f,deviceIds:C,allConnected:!1},l.auth,l.baseUrl),G=$.ok===!0,ge=d==="selected"?G?1:0:Number("queued"in $?$.queued:0);Ue(G?`Queued ${ge||1} remote task${(ge||1)===1?"":"s"}.`:$.error||"Remote task queue failed."),g.emit("remoteMonitor.node.task.queue",{nodeId:e.id,mode:d,ok:G,queued:ge,approvalLevel:f,deviceId:d==="selected"?K:"",targetCount:d==="selected"?1:C.length,batchId:"batchId"in $?$.batchId:"",error:$.error||""}),G&&(eo(""),await se("task-queued"))}catch($){const G=$ instanceof Error?$.message:String($);Ue(G),g.emit("remoteMonitor.node.task.queue",{nodeId:e.id,mode:d,ok:!1,approvalLevel:f,deviceId:d==="selected"?K:"",targetCount:d==="selected"?1:C.length,error:G})}finally{to("")}},[Bt,so,e.id,se,Wo,oe==null?void 0:oe.connected,K,l.auth,l.baseUrl,l.source,io,Me]),ui=a.jsxs("div",{className:"node-remote-monitor__head-actions",children:[a.jsx("i",{"aria-label":`Remote route ${lo}`}),a.jsxs("span",{className:"node-remote-monitor__head-status","data-testid":"remote-monitor-node-agent-status","data-agent-status":Gt,children:["AGENT ",a.jsx("strong",{children:Gt})]}),a.jsxs("span",{className:`node-remote-monitor__head-status node-remote-monitor__route-status is-${re.tone}`,"data-testid":"remote-monitor-node-registry-route","data-registry-route":re.status,"data-account-route-ready":re.accountRouteReady?"true":"false","data-registry-migration-blocked":re.migrationBlocked?"true":"false",title:re.title,children:["ROUTE ",a.jsx("strong",{children:re.value})]}),l.source==="bridge"?a.jsxs(a.Fragment,{children:[a.jsxs("button",{type:"button","data-testid":"remote-monitor-node-host",onClick:ti,children:[a.jsx(ko,{size:12}),ie?"Clear Host":"Set Host"]}),a.jsxs("button",{type:"button",className:me?"is-active":"","data-testid":"remote-monitor-node-auto-host","data-auto-host-active":me?"true":"false",onClick:oi,title:me?"Disable Auto Host restore for this monitor":"Remember this monitor as the Auto Host target",children:[a.jsx(ko,{size:12}),"Auto"]}),a.jsxs("button",{type:"button","data-testid":"remote-monitor-node-agent-connect",onClick:Jr,disabled:!po,title:po?"Connect managed RemoteAgent":uo,children:[a.jsx(xi,{size:12,className:Se==="connect"?"spin-icon":""}),"Start"]}),a.jsxs("button",{type:"button","data-testid":"remote-monitor-node-agent-disconnect",onClick:Zr,disabled:!mo,title:mo?"Stop managed RemoteAgent":"RemoteAgent is not running",children:[a.jsx(wi,{size:12,className:Se==="disconnect"?"spin-icon":""}),"Stop"]})]}):l.source==="blocked"?a.jsxs("button",{type:"button",onClick:Qr,children:[a.jsx(ko,{size:12}),"Enable"]}):a.jsxs("button",{type:"button",onClick:Jn,children:[a.jsx(vo,{size:12,className:l.loading?"spin-icon":""}),"Refresh"]})]}),pi=a.jsxs("form",{className:"node-remote-monitor__taskbar","data-testid":"remote-monitor-node-taskbar",onSubmit:i=>Jo(i,"selected"),children:[a.jsx("input",{"aria-label":"Remote task",value:Me,maxLength:1200,onChange:i=>eo(i.target.value),onPointerDown:i=>i.stopPropagation(),placeholder:oe?`Task for ${ft(oe)}`:"Remote task"}),a.jsxs("button",{type:"submit",disabled:!Vn,title:Vn?"Queue task for selected device":"Selected device cannot accept remote tasks",children:[a.jsx(rn,{size:12,className:Je==="selected"?"spin-icon":""}),"Selected"]}),a.jsxs("button",{type:"button",disabled:!qn,title:qn?"Queue task for connected devices":"No connected devices can accept tasks",onClick:i=>Jo(i,"all"),children:[a.jsx(rn,{size:12,className:Je==="all"?"spin-icon":""}),"All"]}),a.jsxs("button",{type:"button",disabled:!Wn,title:Wn?"Queue AI assist task for connected AI devices":"No AI assist device is connected",onClick:i=>Jo(i,"ai"),children:[a.jsx(Si,{size:12,className:Je==="ai"?"spin-icon":""}),"AI"]})]}),mi=a.jsxs("div",{className:"node-remote-monitor__footer",children:[a.jsxs("div",{className:"node-remote-monitor__footer-scale","data-testid":"remote-monitor-node-tile-scale","data-tile-scale-index":Ke,"data-tile-scale":_t,children:[a.jsx("button",{type:"button","aria-label":"Shrink remote monitor tiles","data-testid":"remote-monitor-node-tile-shrink",disabled:Ke<=0,onClick:i=>Yn(i,-1),children:a.jsx(Mi,{size:12})}),a.jsx("button",{type:"button","aria-label":"Grow remote monitor tiles","data-testid":"remote-monitor-node-tile-grow",disabled:Ke>=qt.length-1,onClick:i=>Yn(i,1),children:a.jsx(Na,{size:12})})]}),a.jsxs("label",{className:"node-remote-monitor__footer-group","data-testid":"remote-monitor-node-group","data-group-mode":ze,children:[a.jsx("span",{children:"GROUP"}),a.jsx("select",{"aria-label":"Remote monitor grouping","data-testid":"remote-monitor-node-group-mode",value:ze,onPointerDown:i=>i.stopPropagation(),onChange:qr,children:Cr.map(i=>a.jsx("option",{value:i,children:Dc(i)},i))})]}),a.jsxs("label",{className:"node-remote-monitor__footer-filter","data-testid":"remote-monitor-node-filter","data-filter-active":N?"true":"false",children:[a.jsx("span",{children:"FILTER"}),a.jsx("input",{"aria-label":"Remote monitor search","data-testid":"remote-monitor-node-filter-text",value:Ot,maxLength:64,onPointerDown:i=>i.stopPropagation(),onChange:Wr,placeholder:"Any"}),a.jsx("select",{"aria-label":"Remote monitor visibility filter","data-testid":"remote-monitor-node-visibility-filter",value:Ae,onPointerDown:i=>i.stopPropagation(),onChange:Kr,children:xr.map(i=>a.jsx("option",{value:i,children:Oc(i)},i))}),a.jsx("select",{"aria-label":"Remote monitor capability filter","data-testid":"remote-monitor-node-capability-filter",value:Ee,onPointerDown:i=>i.stopPropagation(),onChange:Hr,children:wr.map(i=>a.jsx("option",{value:i,children:_c(i)},i))})]}),a.jsxs("div",{className:"node-remote-monitor__footer-status",children:[a.jsxs("span",{children:[a.jsx("i",{})," HUB ",a.jsx("strong",{children:$o})]}),a.jsxs("span",{children:["CONNECTED ",a.jsxs("strong",{children:[Ft,"/",et]})]}),a.jsxs("span",{children:["TASK ",a.jsx("strong",{children:Uo})]}),a.jsxs("span",{children:["AI ",a.jsx("strong",{children:Bt})]}),a.jsxs("span",{children:["INPUT ",a.jsx("strong",{children:Ko})]}),a.jsxs("span",{children:["PAGE ",a.jsx("strong",{children:Go})]}),a.jsxs("span",{children:[a.jsx("i",{})," ROUTE ",a.jsx("strong",{children:lo})]}),a.jsxs("button",{type:"button","data-testid":"remote-monitor-node-copy-connect",onClick:ei,children:[a.jsx(Da,{size:12}),"Connect"]}),a.jsxs("button",{type:"button","data-testid":"remote-monitor-node-refresh",onClick:Jn,children:[a.jsx(vo,{size:12,className:l.loading?"spin-icon":""}),"Refresh"]}),l.source==="bridge"&&a.jsxs("button",{type:"button","data-testid":"remote-monitor-node-input",onClick:ni,disabled:!Le&&!S,title:S||Le?Nt:nt,children:[S?a.jsx(Oa,{size:12}):a.jsx(_a,{size:12}),S?"Lock":"Unlock"]})]})]});return a.jsxs("div",{ref:s,className:"node-remote-monitor","data-testid":"remote-monitor-node","data-remote-source":l.source,"data-remote-canonical-total":et,"data-remote-connected":Ft,"data-remote-projection":on,"data-remote-projected-count":O,"data-remote-visible-budget":Re,"data-remote-page-index":_,"data-remote-page-count":P,"data-remote-page-start":X,"data-remote-host-active":ie?"true":"false","data-remote-registry-route":re.status,"data-remote-registry-ready":re.accountRouteReady?"true":"false","data-remote-registry-migration-blocked":re.migrationBlocked?"true":"false","data-remote-registry-reason":re.reason,"data-remote-host-renew-ms":ie?fo:0,"data-remote-auto-host":me?"true":"false","data-remote-agent-status":Gt,"data-remote-agent-running":co?"true":"false","data-remote-agent-ready":Ho?"true":"false","data-remote-task-follow-active":gt?"true":"false","data-remote-task-follow-key":ke,"data-remote-task-follow-refresh-ms":gt?Io:0,"data-remote-transport-visible":m?"true":"false","data-remote-frame-subscription-active":m&&$e.length>0?"true":"false","data-remote-tile-scale-index":Ke,"data-remote-tile-scale":_t,"data-remote-tile-min-width":Gn,"data-remote-tile-min-height":Un,"data-remote-group-mode":ze,"data-remote-visible-group-count":Fn,"data-remote-filter-text":y,"data-remote-filter-active":N?"true":"false","data-remote-visibility-filter":Ae,"data-remote-capability-filter":Ee,"data-remote-filtered-count":U.length,"data-disable-mindcanvas-wheel":"true",children:[a.jsxs("div",{className:"node-remote-monitor__surface",children:[a.jsx("div",{className:"node-remote-monitor__head",children:a.jsxs("div",{className:"node-remote-monitor__titlemark",children:[a.jsx("span",{children:a.jsx(Ri,{size:15})}),a.jsxs("div",{children:[a.jsx("small",{children:"REMOTE"}),a.jsx("strong",{children:"Multi Desktop Monitor"})]})]})}),a.jsxs("div",{className:"node-remote-monitor__wall-shell",children:[a.jsxs("div",{ref:c,className:"node-remote-monitor__wall","data-testid":"remote-monitor-node-wall","data-page-index":_,"data-page-count":P,"data-page-start":X,"data-visible-devices":he.length,"data-visible-device-ids":tt.join(","),"data-visible-connected-devices":$e.length,"data-frame-subscription-device-ids":ot,"data-frame-subscription-active":m&&$e.length>0?"true":"false","data-transport-visible":m?"true":"false","data-canonical-device-count":et,"data-connected-device-count":Ft,"data-wall-projection":on,"data-projected-device-count":O,"data-visible-budget":Re,"data-tile-scale-index":Ke,"data-tile-scale":_t,"data-group-mode":ze,"data-visible-group-count":Fn,"data-filter-text":y,"data-filter-active":N?"true":"false","data-visibility-filter":Ae,"data-capability-filter":Ee,"data-filtered-device-count":U.length,style:{"--remote-node-tile-min-width":`${Gn}px`,"--remote-node-tile-min-height":`${Un}px`},onPointerDown:i=>Xo(i),onPointerMove:i=>Yo(i),onPointerUp:i=>It(i),onPointerCancel:i=>It(i),onWheel:Vr,children:[he.map(i=>{const d=it(i),u=ft(i),f=Wt(i),T=d===K,C=S&&Le&&T;return a.jsxs("span",{className:`${i.connected===!0?"is-online":""} ${T?"is-selected":""} ${C?"is-input-active":""}`,"aria-label":`${u} remote desktop`,title:`${u} / ${Xt(i)}`,role:"button",tabIndex:C||T?0:-1,"data-device-id":d,"data-connected":i.connected===!0?"true":"false","data-frame-seq":(f==null?void 0:f.frameSeq)??0,"data-can-control":ce(i,"control")?"true":"false","data-can-dispatch-task":ce(i,"taskDispatch")?"true":"false","data-ai-assist":ce(i,"aiAssist")?"true":"false","data-input-active":C?"true":"false","data-group-mode":ze,"data-group-key":Fc(i,ze),onClick:M=>{if(M.stopPropagation(),Pe.current){Pe.current=!1,M.preventDefault();return}Fe(d)},onDoubleClick:M=>Xr(M,i),onPointerDown:M=>ai(M,d,C),onPointerMove:M=>ri(M,C),onPointerUp:M=>ii(M,C),onPointerCancel:M=>si(M,C),onWheel:M=>li(M,C),onKeyDown:M=>ci(M,d,C),onKeyUp:M=>di(M,C),children:[a.jsx("canvas",{ref:M=>Yr(d,M)}),C&&a.jsxs("em",{children:[a.jsx(Fa,{size:10}),"input"]}),a.jsx("small",{children:u})]},d)}),Array.from({length:Ur},(i,d)=>a.jsx("span",{"aria-label":`Remote desktop slot ${X+he.length+d+1}`,"data-placeholder-slot":"true"},`empty-${_}-${d}`))]}),a.jsxs("div",{className:"node-remote-monitor__pager","aria-label":"Monitor page controls",children:[a.jsx("button",{type:"button","aria-label":"Previous monitor page",disabled:_<=0,onClick:i=>Xn(i,-1),children:a.jsx(Pi,{size:12})}),a.jsx("span",{className:"node-remote-monitor__pager-track",style:{"--remote-node-page-top":`${zr}%`,"--remote-node-page-height":`${Bn}%`},children:a.jsx("strong",{})}),a.jsx("button",{type:"button","aria-label":"Next monitor page",disabled:_>=P-1,onClick:i=>Xn(i,1),children:a.jsx(Ai,{size:12})})]})]})]}),a.jsxs("div",{className:"node-remote-monitor__external-rail","data-testid":"remote-monitor-node-external-rail",onPointerDown:i=>i.stopPropagation(),onClick:i=>i.stopPropagation(),children:[ui,pi,mi,a.jsx("p",{className:"node-remote-monitor__message",children:$r})]})]})}function cu({node:e,onPatch:t}){var oo,Ot,no,Ae,ao,Ee,ro,me,ht,et;const o=Mr(e),n=p.useRef(null),r=Sr(n,e.id,"control"),[s,c]=p.useState(()=>{var y;return{source:Pt()?"loading":"blocked",loading:!1,message:Pt()?"Remote device not checked yet.":"Hosted LocalBridge access is gated.",baseUrl:((y=e.metadata)==null?void 0:y.RemoteBaseUrl)||j(),device:St(e)}}),m=p.useRef(null),l=p.useRef(new Set),b=p.useRef(new Map),k=p.useRef(new Map),x=p.useRef(null),v=p.useRef(0),V=p.useRef(0),R=p.useRef(!1),F=p.useRef(0),J=p.useRef(0),Z=p.useRef(0),E=p.useRef(0),ue=p.useRef(e.metadata??{}),[B,pe]=p.useState(!1),[Ce,h]=p.useState("locked"),[ee,L]=p.useState("Remote input locked."),[Y,Oe]=p.useState(""),[W,Pe]=p.useState(!1),[_e,be]=p.useState(""),A=s.device,xe=A?ft(A):e.title||"Remote device",Fe=A?Xt(A):((oo=e.metadata)==null?void 0:oo.RemoteFleetDevicePlatform)||"unknown",S=Ua((Ot=s.bridge)==null?void 0:Ot.status),Q=za((no=s.bridge)==null?void 0:no.status),te=s.source==="bridge"&&!!o&&(A==null?void 0:A.connected)===!0&&!!Q&&ce(A,"control"),ne=A?ce(A,"taskDispatch"):!1,Nt=s.source==="bridge"&&!!o&&(A==null?void 0:A.connected)===!0&&ne&&!!Y.trim()&&!W,ae=B?Er(Ce):te?"Locked":"Off",_o=_e||ee||s.message;p.useEffect(()=>{ue.current=e.metadata??{}},[e.metadata]);const we=p.useCallback((y,I)=>{const N=ue.current??{},U=Object.entries(I).filter(([O,P])=>N[O]!==P).map(([O])=>O);if(U.length===0)return;const z={...N,...I};ue.current=z,t(e.id,{metadata:z}),g.emit("remoteControl.node.metadata.patch",{nodeId:e.id,reason:y,keys:U})},[e.id,t]),Se=p.useCallback(async(y="manual")=>{const I=++E.current,N=j();if(c(U=>({...U,loading:!0,baseUrl:N})),!o){c({source:"unavailable",loading:!1,message:"Remote control node has no device id.",baseUrl:N,device:St(e)});return}if(!Pt()){c({source:"blocked",loading:!1,message:"Hosted LocalBridge access is gated.",baseUrl:N,device:St(e)}),g.emit("remoteControl.node.preview",{nodeId:e.id,reason:"hosted-localbridge-gated",deviceId:o});return}try{const U=await In(N);if(I!==E.current)return;if(U.state!=="connected"){c({source:"unavailable",loading:!1,message:U.message||"LocalBridge is unavailable.",baseUrl:N,bridge:U,device:St(e)});return}const z=Wa(U.status),[O,P]=await Promise.all([Ka(z,N),Ha(z,N,{includeDataUrl:!1})]);if(I!==E.current)return;const _=(Array.isArray(P.devices)?P.devices:[]).find(he=>it(he)===o),X=_||St(e);c({source:_?"bridge":"unavailable",loading:!1,message:_?`${ft(X)} ${X.connected===!0?"online.":"offline."}`:"Selected remote device is not in the current RemoteHub inventory.",baseUrl:N,bridge:U,auth:z,hub:O,device:X}),g.emit("remoteControl.node.refresh",{nodeId:e.id,reason:y,deviceId:o,found:!!_,connected:X.connected===!0})}catch(U){if(I!==E.current)return;c({source:"unavailable",loading:!1,message:U instanceof Error?U.message:String(U),baseUrl:N,device:St(e)})}},[o,e]);p.useEffect(()=>{Se("mount")},[Se]),p.useEffect(()=>{var y,I,N;we("snapshot",{SemanticType:"RemoteFleetDevice",RemoteFleetSchemaVersion:"remote-fleet-device@1",RemoteFleetDeviceId:o,RemoteFleetDeviceName:xe,RemoteFleetDevicePlatform:Fe,RemoteFleetDeviceConnected:String((A==null?void 0:A.connected)===!0),RemoteFleetDeviceCanControl:String(te),RemoteFleetDeviceCanDispatchTask:String(ne),RemoteFleetDeviceTasksQueued:String(((y=A==null?void 0:A.counters)==null?void 0:y.tasksQueued)||0),RemoteFleetSourceMonitorNodeId:((I=e.metadata)==null?void 0:I.RemoteFleetSourceMonitorNodeId)||"",RemoteInput:ae,RemoteTask:ne?"available":"unavailable",RemoteHub:s.source==="bridge"?((N=s.hub)==null?void 0:N.started)===!0?"Online":"Ready":s.source==="blocked"?"Gated":s.source,RemoteRoute:s.source==="bridge"?"Local":s.source==="blocked"?"Gated":"Preview",RemoteBaseUrl:s.baseUrl,AdapterState:s.source==="bridge"?"localbridge-connected":s.source==="blocked"?"adapter-gated":s.source})},[te,ne,A==null?void 0:A.connected,(Ae=A==null?void 0:A.counters)==null?void 0:Ae.tasksQueued,o,xe,ae,e.metadata,we,Fe,s.baseUrl,(ao=s.hub)==null?void 0:ao.started,s.source]);const mt=p.useCallback((y,I)=>{if(!o)return!1;const N=Br(k.current,o);if(!N)return!1;const{cached:U,scope:z}=N;return Mo(y,U,l.current,b.current).then(O=>{O&&g.emit("remoteControl.node.frameCache",{nodeId:e.id,deviceId:o,frameSeq:pt(U.metadata),scope:z,reason:I})}),!0},[o,e.id]);p.useEffect(()=>{const y=m.current;if(!y||!A)return;const I=Wt(A),N=Nn(I);s.source==="bridge"&&N?Gr(y,N,s.baseUrl).catch(()=>Ro(y,A,s.source)):s.source==="bridge"&&mt(y,"projection-rerender")||Ro(y,A,s.source)},[A,mt,s.baseUrl,s.source]);const Dt=p.useCallback(async(y,I)=>{if(!o||w(y.deviceId).trim()!==o)return;const N=Number(y.frameSeq||0)||0,U=Dn(b.current,k.current,o);if(N>0&&N<=U){g.emit("remoteControl.node.frameStaleDropped",{nodeId:e.id,deviceId:o,frameSeq:N,previous:U,source:"ws"});return}const z=dr(y,I.byteLength);z.level!=="nominal"&&g.emit("remoteControl.node.framePressure",{nodeId:e.id,deviceId:o,frameSeq:N,...z});const O=_r(k.current,o,y,I),P=m.current;if(P){if(l.current.has(o)){g.emit("remoteControl.node.frameCache",{nodeId:e.id,deviceId:o,frameSeq:N,scope:"local",reason:"decode-pending"});return}l.current.add(o);try{await On(P,O.metadata,O.payload)&&(N>0&&b.current.set(o,N),J.current+=1,g.emit("remoteControl.node.framePainted",{nodeId:e.id,deviceId:o,frameSeq:N,painted:J.current,source:"ws"}))}catch{}finally{l.current.delete(o);const _=k.current.get(o),X=pt(_==null?void 0:_.metadata),he=b.current.get(o)||0,tt=m.current;_&&tt&&(X<=0?he<=0:X>he)&&Mo(tt,_,l.current,b.current).then($e=>{$e&&(J.current+=1,g.emit("remoteControl.node.frameCache",{nodeId:e.id,deviceId:o,frameSeq:X,scope:"local",reason:"latest-pending"}),g.emit("remoteControl.node.framePainted",{nodeId:e.id,deviceId:o,frameSeq:X,painted:J.current,source:"ws-cache"}))})}}},[o,e.id]);p.useEffect(()=>{if(s.source!=="bridge"||!o||(A==null?void 0:A.connected)!==!0||!r)return;let y=!1,I=null,N=0;R.current=!1;const U=()=>{var z,O;if(!y){try{I=new WebSocket(Ar(s.baseUrl,S,(O=(z=s.bridge)==null?void 0:z.status)==null?void 0:O.bridgeToken,[o])),I.binaryType="arraybuffer"}catch(P){g.emit("remoteControl.node.frameWs",{nodeId:e.id,ok:!1,error:P instanceof Error?P.message:String(P)});return}I.onopen=()=>{R.current=!0,F.current=performance.now(),g.emit("remoteControl.node.frameWs",{nodeId:e.id,ok:!0,deviceId:o,fps:20}),I==null||I.send(JSON.stringify({type:"subscribe",deviceIds:[o],autoStartLive:!0,fps:20,maxWidth:960,maxHeight:540,quality:62,mode:"remote-fast-control"}))},I.onmessage=async P=>{if(!y){if(F.current=performance.now(),P.data instanceof ArrayBuffer){const _=wo(P.data);_&&await Dt(_.metadata,_.payload)}else if(P.data instanceof Blob){const _=wo(await P.data.arrayBuffer());_&&await Dt(_.metadata,_.payload)}}},I.onerror=()=>{R.current=!1,g.emit("remoteControl.node.frameWs",{nodeId:e.id,ok:!1,deviceId:o,reason:"socket-error"})},I.onclose=()=>{R.current=!1,y||(N=window.setTimeout(U,1500))}}};return U(),()=>{y=!0,R.current=!1,window.clearTimeout(N),I==null||I.close()}},[A==null?void 0:A.connected,o,e.id,Dt,S,s.baseUrl,(ro=(Ee=s.bridge)==null?void 0:Ee.status)==null?void 0:ro.bridgeToken,s.source,r]),p.useEffect(()=>{if(s.source!=="bridge"||!o||(A==null?void 0:A.connected)!==!0||!r)return;let y=!1,I=!1;const N=async()=>{var O;if(!(y||I)&&!(R.current&&performance.now()-F.current<kr)){I=!0;try{const P=await Xa([o],s.auth,s.baseUrl);if(y||P.ok===!1)return;const _=(O=P.frames)==null?void 0:O.find($e=>$e.deviceId===o),X=await Tn(m.current??void 0,o,_?Or(_):void 0,s.baseUrl,l.current,b.current,k.current),he=X.painted?1:0,tt=X.staleDropped?1:0;X.staleDropped&&g.emit("remoteControl.node.frameStaleDropped",{nodeId:e.id,deviceId:o,frameSeq:X.frameSeq,previous:X.previous,source:"snapshot"}),g.emit("remoteControl.node.frameSnapshot",{nodeId:e.id,deviceId:o,frameCount:_?1:0,painted:he,staleDropped:tt})}catch{}finally{I=!1}}},U=window.setTimeout(N,250),z=window.setInterval(N,2500);return()=>{y=!0,window.clearTimeout(U),window.clearInterval(z)}},[A==null?void 0:A.connected,o,e.id,s.auth,s.baseUrl,s.source,r]),p.useEffect(()=>{!B||te||(pe(!1),h("unavailable"),L("Remote input unavailable."),g.emit("remoteControl.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"control-unavailable",deviceId:o}))},[te,o,B,e.id]),p.useEffect(()=>{var N,U,z;if(!B){(N=x.current)==null||N.close(),x.current=null,h("locked");return}if(!te||!o){h("unavailable"),L("Remote input unavailable.");return}let y=!1,I=null;h("connecting"),L("Connecting remote input adapter...");try{I=new WebSocket(Rr(s.baseUrl,Q,(z=(U=s.bridge)==null?void 0:U.status)==null?void 0:z.bridgeToken)),x.current=I}catch(O){h("error");const P=O instanceof Error?O.message:String(O);L(P),g.emit("remoteControl.node.input.ws",{nodeId:e.id,ok:!1,deviceId:o,error:P});return}return I.onopen=()=>{y||(h("ready"),L("Remote input ready."),g.emit("remoteControl.node.input.ws",{nodeId:e.id,ok:!0,deviceId:o}))},I.onmessage=O=>{if(y)return;const P=hr(String(O.data||"{}"));if(P){if(P.type==="RemoteInputSocketReady"){h("ready");return}g.emit("remoteControl.node.input.result",{nodeId:e.id,ok:P.ok,deviceId:P.deviceId||o,inputType:P.inputType,error:P.error}),!P.ok||P.error?L(P.error||"Remote input failed."):/^pointermove$/i.test(P.inputType)||L(`${P.inputType||"Input"} queued.`)}},I.onerror=()=>{y||(h("error"),L("Remote input socket error."),g.emit("remoteControl.node.input.ws",{nodeId:e.id,ok:!1,deviceId:o,reason:"socket-error"}))},I.onclose=()=>{y||(x.current=null,h("error"),L("Remote input socket closed."),g.emit("remoteControl.node.input.ws",{nodeId:e.id,ok:!1,deviceId:o,reason:"socket-closed"}))},()=>{y=!0,x.current===I&&(x.current=null),I==null||I.close()}},[te,o,B,e.id,Q,s.baseUrl,(ht=(me=s.bridge)==null?void 0:me.status)==null?void 0:ht.bridgeToken]),p.useEffect(()=>{if(!B)return;const y=I=>{I.key==="Escape"&&(I.preventDefault(),pe(!1),L("Remote input locked."),g.emit("remoteControl.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"escape",deviceId:o}))};return window.addEventListener("keydown",y,!0),()=>window.removeEventListener("keydown",y,!0)},[o,B,e.id]);const de=p.useCallback(y=>{var _;const I=x.current;if(!B||!te||!o||(I==null?void 0:I.readyState)!==WebSocket.OPEN){y.ack&&L(B?"Remote input socket is not ready.":"Remote input locked.");return}const N=`remote-control-input-${Date.now()}-${++v.current}`,{ack:U,...z}=y,O=mr({requestId:N,deviceId:o,ack:U,controlLeaseId:(_=s.hub)==null?void 0:_.hostTargetLeaseId,input:z});if(!O){U&&L("Remote input payload is invalid.");return}const P=w(O.input.type);try{I.send(JSON.stringify(O));const X=++V.current;(O.ack||X%24===1)&&g.emit("remoteControl.node.input.sent",{nodeId:e.id,deviceId:o,inputType:P,sampled:!O.ack,sent:X})}catch(X){h("error"),L(X instanceof Error?X.message:String(X))}},[te,o,B,e.id,(et=s.hub)==null?void 0:et.hostTargetLeaseId]),Me=p.useCallback((y,I,N,U=!1)=>{const z=So(y,U);return z?(de({type:I,...z,button:Pr(y.button),ack:N}),!0):!1},[de]),eo=p.useCallback(y=>{if(!(!B||!Me(y,"pointerDown",!0,!1))){y.preventDefault(),y.stopPropagation(),y.currentTarget.focus();try{y.currentTarget.setPointerCapture(y.pointerId)}catch{}}},[Me,B]),Je=p.useCallback(y=>{var z,O;if(!B)return;const I=performance.now();if(I-Z.current<Tr)return;Z.current=I;const N=((O=(z=y.currentTarget).hasPointerCapture)==null?void 0:O.call(z,y.pointerId))===!0;Me(y,"pointerMove",!1,N)&&(y.preventDefault(),y.stopPropagation())},[Me,B]),to=p.useCallback(y=>{if(B){y.preventDefault(),y.stopPropagation();try{y.currentTarget.releasePointerCapture(y.pointerId)}catch{}Me(y,"pointerUp",!0,!0)}},[Me,B]),Fo=p.useCallback(y=>{if(!B)return;const I=So(y,!1);I&&(de({type:"wheel",...I,deltaX:y.deltaX,deltaY:y.deltaY,ack:!0}),y.preventDefault(),y.stopPropagation())},[B,de]),Ue=p.useCallback(y=>{!B||y.key==="Escape"||(y.preventDefault(),y.stopPropagation(),de({type:"keyDown",key:y.key,code:y.code,repeat:y.repeat,ack:!0}))},[B,de]),kt=p.useCallback(y=>{!B||y.key==="Escape"||(y.preventDefault(),y.stopPropagation(),de({type:"keyUp",key:y.key,code:y.code,repeat:!1,ack:!0}))},[B,de]),Ze=p.useCallback(y=>{y.stopPropagation(),qa(!0),Se("hosted-access-enabled")},[Se]),Ke=p.useCallback(y=>{if(y.stopPropagation(),B){pe(!1),L("Remote input locked."),g.emit("remoteControl.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"manual",deviceId:o});return}if(!te){h("unavailable"),L("Remote input unavailable."),g.emit("remoteControl.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"unavailable",deviceId:o});return}pe(!0),L("Connecting remote input adapter..."),g.emit("remoteControl.node.input.lock",{nodeId:e.id,unlocked:!0,reason:"manual",deviceId:o})},[te,o,B,e.id]),Bo=p.useCallback(y=>{y.stopPropagation(),Se("manual")},[Se]),ze=p.useCallback(async y=>{var z;if(y.preventDefault(),y.stopPropagation(),s.source!=="bridge"){be("LocalBridge is not connected.");return}const I=Y.trim();if(!I){be("Remote task is empty.");return}if(!o||(A==null?void 0:A.connected)!==!0||!ne){be("This device cannot accept remote tasks.");return}const N="task-only",U=((z=I.split(/\r?\n/)[0])==null?void 0:z.slice(0,96))||"Remote task";Pe(!0),be("Queueing device task...");try{const O=await Ya(o,{instruction:I,title:U,approvalLevel:N},s.auth,s.baseUrl),P=O.ok===!0;be(P?"Queued remote task.":O.error||"Remote task queue failed."),g.emit("remoteControl.node.task.queue",{nodeId:e.id,ok:P,deviceId:o,approvalLevel:N,queued:P?1:0,taskId:O.taskId||"",commandId:O.commandId||"",error:O.error||""}),P&&(Oe(""),await Se("task-queued"))}catch(O){const P=O instanceof Error?O.message:String(O);be(P),g.emit("remoteControl.node.task.queue",{nodeId:e.id,ok:!1,deviceId:o,approvalLevel:N,queued:0,error:P})}finally{Pe(!1)}},[ne,A==null?void 0:A.connected,o,e.id,Se,s.auth,s.baseUrl,s.source,Y]);return a.jsxs("div",{ref:n,className:"node-remote-control","data-testid":"remote-control-node","data-remote-source":s.source,"data-remote-transport-visible":r?"true":"false","data-remote-frame-subscription-active":r&&s.source==="bridge"&&(A==null?void 0:A.connected)===!0?"true":"false",onPointerDown:y=>y.stopPropagation(),children:[a.jsxs("div",{className:"node-remote-control__bar",children:[a.jsx("strong",{title:xe,children:xe}),a.jsx("span",{children:Fe}),a.jsx("button",{type:"button",title:"Refresh remote device",onClick:Bo,children:a.jsx(vo,{size:12,className:s.loading?"spin-icon":""})}),s.source==="blocked"?a.jsxs("button",{type:"button",onClick:Ze,children:[a.jsx(ko,{size:12}),"Enable"]}):a.jsxs("button",{type:"button",disabled:!te&&!B,onClick:Ke,children:[B?a.jsx(Oa,{size:12}):a.jsx(_a,{size:12}),B?"Lock":"Unlock"]})]}),a.jsxs("div",{className:`node-remote-control__screen ${B&&te?"is-input-active":""}`,tabIndex:B&&te?0:-1,onPointerDown:eo,onPointerMove:Je,onPointerUp:to,onWheel:Fo,onKeyDown:Ue,onKeyUp:kt,children:[a.jsx("canvas",{ref:m}),B&&te&&a.jsxs("em",{children:[a.jsx(Fa,{size:11}),"input"]})]}),a.jsxs("form",{className:"node-remote-control__taskbar","data-testid":"remote-control-node-taskbar",onSubmit:ze,children:[a.jsx("input",{"aria-label":"Remote control task",value:Y,maxLength:1200,onChange:y=>Oe(y.target.value),onPointerDown:y=>y.stopPropagation(),placeholder:ne?`Task for ${xe}`:"Task unavailable"}),a.jsxs("button",{type:"submit",disabled:!Nt,title:Nt?"Queue task for this device":"This device cannot accept remote tasks",children:[a.jsx(rn,{size:12,className:W?"spin-icon":""}),"Queue"]})]}),a.jsxs("div",{className:"node-remote-control__footer",children:[a.jsxs("span",{children:["DEVICE ",a.jsx("strong",{children:o||"missing"})]}),a.jsxs("span",{children:["STATE ",a.jsx("strong",{children:(A==null?void 0:A.connected)===!0?"online":"offline"})]}),a.jsxs("span",{children:["INPUT ",a.jsx("strong",{children:ae})]}),a.jsxs("span",{children:["TASK ",a.jsx("strong",{children:ne?"ready":"off"})]}),a.jsxs("span",{children:["ROUTE ",a.jsx("strong",{children:s.source==="bridge"?"Local":s.source==="blocked"?"Gated":"Preview"})]})]}),a.jsx("p",{className:"node-remote-control__message",children:_o})]})}function Mr(e){var t,o,n;return w(((t=e.metadata)==null?void 0:t.RemoteFleetDeviceId)||((o=e.metadata)==null?void 0:o.RemoteSelectedDeviceId)||((n=e.metadata)==null?void 0:n.DeviceId)).trim()}function St(e){var n,r,s,c,m,l,b,k,x,v,V,R,F;const t=new Date().toISOString();return{deviceId:Mr(e)||"remote-control-preview",deviceName:((n=e.metadata)==null?void 0:n.RemoteFleetDeviceName)||e.title||"Remote device",platform:((r=e.metadata)==null?void 0:r.RemoteFleetDevicePlatform)||"unknown",arch:((s=e.metadata)==null?void 0:s.RemoteFleetDeviceArch)||"",connected:/^(1|true|yes|online)$/i.test(((c=e.metadata)==null?void 0:c.RemoteFleetDeviceConnected)||""),lastSeenAt:t,capabilities:{control:/^(1|true|yes|on)$/i.test(((m=e.metadata)==null?void 0:m.RemoteFleetDeviceCanControl)||""),taskDispatch:/^(1|true|yes|on)$/i.test(((l=e.metadata)==null?void 0:l.RemoteFleetDeviceCanDispatchTask)||"")},latestLiveFrame:(b=e.metadata)!=null&&b.RemoteFleetLatestFramePath||(k=e.metadata)!=null&&k.RemoteFleetLatestFrameUrl||(x=e.metadata)!=null&&x.RemoteFleetLatestFrameDataUrl?{framePath:(v=e.metadata)==null?void 0:v.RemoteFleetLatestFramePath,frameUrl:(V=e.metadata)==null?void 0:V.RemoteFleetLatestFrameUrl,dataUrl:(R=e.metadata)==null?void 0:R.RemoteFleetLatestFrameDataUrl,frameSeq:kn((F=e.metadata)==null?void 0:F.RemoteFleetLatestFrameSeq,0)}:void 0}}function kn(e,t){const o=Number(e);return Number.isFinite(o)&&o>=0?o:t}function w(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):""}function ye(e,t){const o=Number(e);return Number.isFinite(o)?o:t}function ce(e,t){var n;const o=(n=e.capabilities)==null?void 0:n[t];return typeof o=="boolean"?o:typeof o=="number"?o!==0:typeof o=="string"?/^(1|true|yes|on)$/i.test(o):!1}function Rr(e,t,o){const n=e.replace(/^http:/i,"ws:").replace(/^https:/i,"wss:").replace(/\/+$/,""),r=t||"/api/remote/input/ws",s=new URLSearchParams;o&&s.set("token",o);const c=s.toString();return c?`${n}${r}?${c}`:`${n}${r}`}function Pr(e){return e===2?"right":e===1?"middle":"left"}function So(e,t=!1){const o=Tc(e.currentTarget);if(!o)return null;const n=o.getBoundingClientRect();if(n.width<=0||n.height<=0)return null;const r=Zt.get(o)??{left:0,top:0,width:n.width,height:n.height};return nc(e,n,r,t)}function Tc(e){return e instanceof HTMLCanvasElement?e:e.querySelector("canvas")}function Pa(e){return e.split(",").map(t=>t.trim()).filter(Boolean)}function Ar(e,t,o,n){const r=e.replace(/^http:/i,"ws:").replace(/^https:/i,"wss:").replace(/\/+$/,""),s=t||"/api/remote/frames/ws",c=new URLSearchParams;o&&c.set("token",o),n.length>0&&c.set("devices",n.join(","));const m=c.toString();return m?`${r}${s}?${m}`:`${r}${s}`}function Er(e){switch(e){case"ready":return"ready";case"connecting":return"connecting";case"unavailable":return"unavailable";case"error":return"error";default:return"locked"}}function bo(e,t){const o=new Date().toISOString(),n=Math.max(12,Math.min(uc,Math.floor(e||Re)));return Array.from({length:n},(r,s)=>({deviceId:`remote-node-preview-${s+1}`,deviceName:`Remote ${String(s+1).padStart(2,"0")}`,platform:s%4===0?"linux":"win32",arch:"x64",connected:s<t,lastSeenAt:o,capabilities:{control:!1}}))}function nn(e){if(typeof window>"u")return!1;try{const t=window.localStorage.getItem(bn);if(String(t||"").trim().toLowerCase()!=="true")return!1;const o=String(window.localStorage.getItem(yn)||"").trim(),n=String(e||"").trim();return!o||o===n}catch{return!1}}function Aa(e,t){if(!(typeof window>"u"))try{t?(window.localStorage.setItem(bn,"true"),window.localStorage.setItem(yn,String(e||"").trim())):(window.localStorage.removeItem(bn),window.localStorage.removeItem(yn))}catch{}}function Ic({source:e,hub:t,baseUrl:o,hubLabel:n,routeLabel:r,connected:s,total:c,taskCount:m,taskDispatchCount:l,aiCount:b,pageLabel:k,pageStart:x,pageIndex:v,pageCount:V,projectionMode:R,projectedCount:F,visibleBudget:J,selectedDeviceId:Z,inputLabel:E,devices:ue,latestTaskBatch:B,recentTaskBatches:pe,taskFollowActive:Ce,taskFollowKey:h,isHostActiveForNode:ee,registryRouteInfo:L,hostTargetRenewMs:Y,autoHostEnabled:Oe,agent:W,agentStatusLabel:Pe,agentRunning:_e,agentReady:be,message:A}){const xe=jn(t),Fe=ee?"hosting":(t==null?void 0:t.hostTargetActive)===!0?"other-monitor":"inactive",S=xc(ue);return{SemanticType:"RemoteFleetMonitor",RemoteFleetSchemaVersion:"remote-fleet@1",RemoteFleetViewMode:"all-devices",RemoteFleetLastRefreshAtUtc:new Date().toISOString(),RemoteFleetHubStatus:(t==null?void 0:t.started)===!0?"online":e==="blocked"?"gated":e==="bridge"?"ready":e,RemoteFleetHubEndpoint:xe,RemoteFleetManagerPackage:w(t==null?void 0:t.managerPackage)||"@mindexec/cli",RemoteFleetManagerVersion:w(t==null?void 0:t.managerVersion),RemoteFleetAgentPackage:w(t==null?void 0:t.agentPackage)||"@mindexec/remote",RemoteFleetPairTokenPreview:w(t==null?void 0:t.pairTokenPreview)||"<pair-token>",RemoteFleetConnectCommand:jr(t),RemoteFleetDeviceCount:String(c),RemoteFleetConnectedDeviceCount:String(s),RemoteFleetDevicesJson:JSON.stringify(S),RemoteFleetLatestTaskBatchJson:B?JSON.stringify(Ea(B)):"",RemoteFleetRecentTaskBatchesJson:JSON.stringify((pe??[]).slice(0,6).map(Ea)),RemoteFleetTaskFollowActive:String(Ce),RemoteFleetTaskFollowKey:h,RemoteFleetTaskFollowRefreshMs:String(Ce?Io:0),RemoteFleetTaskFollowMaxTicks:String(Mt),RemoteFleetProjectionMode:R,RemoteFleetProjectedDeviceCount:String(F),RemoteFleetCanvasPagination:`${R}:${v+1}/${V}`,RemoteFleetHostTargetState:Fe,RemoteFleetHostTargetNodeId:w(t==null?void 0:t.hostTargetNodeId),RemoteFleetHostTargetLeaseId:w(t==null?void 0:t.hostTargetLeaseId),RemoteFleetRegistryStatus:L.status,RemoteFleetRegistryReason:L.reason,RemoteFleetAccountRouteReady:String(L.accountRouteReady),RemoteFleetRegistryMigrationBlocked:String(L.migrationBlocked),RemoteFleetHostTargetRenewMs:String(Y),RemoteFleetAutoHost:String(Oe),RemoteFleetHostTargetEndpoint:w(t==null?void 0:t.hostTargetEndpoint)||xe,RemoteFleetHostTargetActivatedAtUtc:w(t==null?void 0:t.hostTargetActivatedAt),RemoteFleetHostTargetUpdatedAtUtc:w(t==null?void 0:t.hostTargetUpdatedAt),RemoteFleetHostTargetExpiresAtUtc:w(t==null?void 0:t.hostTargetExpiresAt),RemoteAgentStatus:Pe,RemoteAgentRunning:String(_e),RemoteAgentReady:String(be),RemoteAgentManager:w(W==null?void 0:W.manager),RemoteAgentLeaseId:w(W==null?void 0:W.leaseId),RemoteAgentNodeId:w(W==null?void 0:W.nodeId),RemoteAgentUpdatedAtUtc:w(W==null?void 0:W.updatedAt),RemoteAgentLastError:w((W==null?void 0:W.lastError)||(W==null?void 0:W.reconnectReason)),RemoteFleetLastError:e==="bridge"?w(t==null?void 0:t.lastError):A,RemoteHub:n,RemoteRoute:r,RemoteRegistryRoute:L.status,RemoteRegistryReason:L.reason,RemoteConnected:String(s),RemoteTotal:String(c),RemoteProjected:String(F),RemoteProjection:R,RemotePage:k,RemotePageStart:String(x),RemoteVisibleBudget:String(J),RemoteSelectedDeviceId:Z,RemoteInput:E,RemoteTasksQueued:String(m),RemoteTaskDevices:String(l),RemoteAiDevices:String(b),RemoteBaseUrl:o,AdapterState:e==="bridge"?"localbridge-connected":e==="blocked"?"adapter-gated":e}}function vc(e,t){const o=w(e==null?void 0:e.agentEndpointRouteReason).trim(),n=(e==null?void 0:e.agentEndpointAccountRouteReady)===!0,r=Lr(o);return(t?"account":(e==null?void 0:e.hostTargetActive)===!0?"other-monitor":"idle")==="other-monitor"?{status:"other-monitor",value:"Other",tone:"default",reason:o,accountRouteReady:n,migrationBlocked:r,title:o||"Another monitor currently owns the host route."}:t?n?{status:"account",value:"Account",tone:"online",reason:o||"ok",accountRouteReady:!0,migrationBlocked:!1,title:"Published to the account route registry for same-account agent pairing."}:Cc(o)?{status:"blocked",value:"Blocked",tone:"warn",reason:o,accountRouteReady:!1,migrationBlocked:r,title:r?"Account route registry needs the Supabase remote_host_targets migration.":o||"The local host is active, but account route publishing failed."}:{status:"local",value:"Local",tone:"warn",reason:o,accountRouteReady:!1,migrationBlocked:r,title:o||"The local host is active, but account route publishing is not available."}:{status:"idle",value:"Idle",tone:"default",reason:o,accountRouteReady:n,migrationBlocked:r,title:o||"No active host route."}}function Lr(e){return/registry-table-unavailable|PGRST20[25]|remote_host_targets|set_remote_host_target|clear_remote_host_target/i.test(String(e||""))}function Cc(e){return Lr(e)||/invalid-manager-endpoint|blocked|failed|error|unavailable|unauthori[sz]ed|forbidden/i.test(String(e||""))}function jn(e){const t=w(e==null?void 0:e.agentEndpoint).trim();if(t)return t;const o=w((e==null?void 0:e.agentHost)||(e==null?void 0:e.host)).trim()||"127.0.0.1",n=Number((e==null?void 0:e.port)||5197);return`${o}:${Number.isFinite(n)&&n>0?n:5197}`}function jr(e){const t=jn(e),o=w(e==null?void 0:e.pairTokenPreview).trim()||"<pair-token>";return`npx @mindexec/remote connect --manager ${t} --pair ${o}`}function xc(e){return e.filter(t=>t.connected===!0).map(t=>{var r,s,c,m,l,b,k,x,v,V,R;const o=Wt(t),n=t.latestTask;return{deviceId:it(t),sessionId:w(t.sessionId),name:ft(t),hostname:w(t.hostname),platform:Xt(t),arch:w(t.arch),agentVersion:w(t.agentVersion),connected:t.connected===!0,lastSeenAt:w(t.lastSeenAt),lastStatusAt:w(t.lastStatusAt),computerAgentEnabled:ce(t,"taskDispatch"),controlEnabled:ce(t,"control"),thumbnailEnabled:ce(t,"thumbnail")||ce(t,"screen"),liveStreamEnabled:ce(t,"liveStream"),aiAssistEnabled:ce(t,"aiAssist"),aiModel:w((r=t.capabilities)==null?void 0:r.aiModel),aiProvider:w((s=t.capabilities)==null?void 0:s.aiProvider),thumbnailFrameUrl:w(((c=t.latestThumbnail)==null?void 0:c.frameUrl)||((m=t.latestThumbnail)==null?void 0:m.framePath)),liveFrameUrl:w(((l=t.latestLiveFrame)==null?void 0:l.frameUrl)||((b=t.latestLiveFrame)==null?void 0:b.framePath)),latestFrameSeq:pt(o),liveStreamActive:((k=t.activeLiveStream)==null?void 0:k.active)===!0,liveStreamId:w((x=t.activeLiveStream)==null?void 0:x.streamId),liveStreamFps:ye((v=t.activeLiveStream)==null?void 0:v.fps,0),latestTaskBatchId:w(n==null?void 0:n.batchId),latestTaskId:w(n==null?void 0:n.taskId),latestTaskStatus:w(n==null?void 0:n.status),latestTaskApprovalLevel:w(n==null?void 0:n.approvalLevel),latestTaskResultModel:w(n==null?void 0:n.resultModel),latestTaskResultResponseId:w(n==null?void 0:n.resultResponseId),latestTaskResultSummary:w(n==null?void 0:n.resultSummary),tasksQueued:ye((V=t.counters)==null?void 0:V.tasksQueued,0),taskResultsReceived:ye((R=t.counters)==null?void 0:R.taskResultsReceived,0)}})}function Ea(e){return{batchId:w(e.batchId),title:w(e.title),instructionPreview:w(e.instructionPreview),approvalLevel:w(e.approvalLevel),status:w(e.status),requestedAt:w(e.requestedAt),updatedAt:w(e.updatedAt),total:ye(e.total,0),queued:ye(e.queued,0),pending:ye(e.pending,0),completed:ye(e.completed,0),failed:ye(e.failed,0),timedOut:ye(e.timedOut,0)}}function wc(e,t){return La(e)?e:(t??[]).find(La)}function Sc(e){if(!e)return"";const t=w(e.batchId).trim();return t||[w(e.title).trim(),w(e.requestedAt).trim(),w(e.updatedAt).trim(),String(ye(e.total,0)||"")].filter(Boolean).join(":")}function La(e){if(!e)return!1;const t=w(e.status).trim().toLocaleLowerCase(),o=ye(e.pending,0),n=ye(e.total,0),r=ye(e.completed,0),s=ye(e.failed,0),c=ye(e.timedOut,0);return["completed","completed-with-failures","failed","cancelled","canceled","done"].includes(t)?!1:o>0||["running","queued","pending","targeted","dispatching","in-progress"].includes(t)?!0:n>0&&r+s+c<n}function Mc(e,t){const o=Rc(e);return{manager:o[0]||"",managerCandidates:o,pairToken:w(e==null?void 0:e.pairToken).trim(),leaseId:w(e==null?void 0:e.hostTargetLeaseId).trim(),nodeId:t,engine:"auto",source:"react-remote-monitor"}}function Rc(e){const t=Array.isArray(e==null?void 0:e.agentEndpointCandidateDetails)?e.agentEndpointCandidateDetails:[],o=[e==null?void 0:e.hostTargetEndpoint,...Array.isArray(e==null?void 0:e.hostTargetEndpointCandidates)?e.hostTargetEndpointCandidates:[],e==null?void 0:e.agentEndpoint,...Array.isArray(e==null?void 0:e.agentEndpointCandidates)?e.agentEndpointCandidates:[],...t.map(s=>s.endpoint||s.address),jn(e)],n=new Set,r=[];for(const s of o){const c=Pc(s),m=c.toLowerCase();if(!(!c||n.has(m))&&(n.add(m),r.push(c),r.length>=12))break}return r}function Pc(e){const t=w(e).trim(),o=t.match(/^(\[[^\]]+\]|[^:\s]+):(\d{1,5})$/);if(!o)return"";const n=Number(o[2]);return!Number.isInteger(n)||n<=0||n>65535?"":t}function Ac(e,t){if(t==="blocked")return"gated";if(t!=="bridge")return t;if(!e)return"unknown";const o=w(e.status).trim().toLowerCase();return Dr(e)?"ready":o||(Nr(e)?"running":"idle")}function Nr(e){const t=w(e==null?void 0:e.status).trim().toLowerCase();return(e==null?void 0:e.running)===!0||t==="running"||t==="starting"}function Dr(e){const t=w(e==null?void 0:e.status).trim().toLowerCase();return(e==null?void 0:e.ready)===!0||t==="ready"}function Ec({source:e,hasAuth:t,isHostActiveForNode:o,request:n,busy:r}){return r?"RemoteAgent action is already running.":e!=="bridge"?"LocalBridge is not connected.":t?o?"This monitor is already the active host target.":n.manager?n.pairToken?"":"RemoteAgent pair token is missing.":"RemoteAgent manager endpoint is missing.":"LocalBridge auth token is not available."}function it(e){return String(e.deviceId||e.sessionId||e.deviceName||"").trim()}function ft(e){return String(e.deviceName||e.hostname||it(e)||"Remote device").trim()}function Xt(e){var t;return String(((t=e.status)==null?void 0:t.platform)||e.platform||"unknown").trim()}function Lc(e){return Cr.includes(e)?e:"status"}function jc(e){return xr.includes(e)?e:"connected"}function Nc(e){return wr.includes(e)?e:"all"}function Dc(e){switch(e){case"activity":return"Activity";case"platform":return"Platform";case"capability":return"Capability";default:return"Status"}}function Oc(e){switch(e){case"all":return"All";case"offline":return"Offline";default:return"Live"}}function _c(e){switch(e){case"control":return"Control";case"task":return"Task";case"ai":return"AI";default:return"Any"}}function Fc(e,t){switch(t){case"activity":return Bc(e);case"platform":return Xt(e).toLocaleLowerCase()||"unknown";case"capability":return Gc(e);default:return e.connected===!0?"online":"offline"}}function Bc(e){var o,n,r,s;const t=w((o=e.latestTask)==null?void 0:o.status).toLocaleLowerCase();return t==="running"||t==="queued"?`task-${t}`:((n=e.activeLiveStream)==null?void 0:n.active)===!0?"live":Number(((r=e.counters)==null?void 0:r.liveFramesReceived)||0)>0?"live-recent":Number(((s=e.counters)==null?void 0:s.thumbnailFramesReceived)||0)>0?"thumbnail":e.lastStatusAt||e.lastSeenAt?"heartbeat":"idle"}function Gc(e){return ce(e,"aiAssist")?"ai-assist":ce(e,"taskDispatch")?"task-dispatch":ce(e,"control")?"control":ce(e,"thumbnail")||ce(e,"screen")?"screen":"view-only"}function Wt(e){return e.latestLiveFrame||e.latestThumbnail}function Nn(e){return(e==null?void 0:e.dataUrl)||(e==null?void 0:e.frameUrl)||(e==null?void 0:e.framePath)||""}function Or(e){return e.live||e.thumbnail}function pt(e){const t=Number((e==null?void 0:e.frameSeq)||0);return Number.isFinite(t)&&t>0?t:0}function Dn(e,t,o){var n,r;return Math.max(e.get(o)||0,pt((n=t.get(o))==null?void 0:n.metadata),pt((r=Fr(o))==null?void 0:r.metadata))}function _r(e,t,o,n){e.has(t)&&e.delete(t);const r={metadata:{...o,deviceId:t},payload:n.slice(0),cachedAt:Date.now()};return e.set(t,r),Yt(e,fn),Uc(t,r),r}function Yt(e,t,o=Number.POSITIVE_INFINITY){const n=Date.now();for(const[r,s]of e)(!s||!s.payload||Number.isFinite(o)&&n-s.cachedAt>o)&&e.delete(r);for(;e.size>t;){const r=e.keys().next().value;if(!r)break;e.delete(r)}}function Uc(e,t){e&&(Rt.has(e)&&Rt.delete(e),Rt.set(e,{metadata:{...t.metadata,deviceId:e},payload:t.payload,cachedAt:t.cachedAt}),Yt(Rt,Ir,vr))}function Fr(e){return Yt(Rt,Ir,vr),Rt.get(e)}function Br(e,t){Yt(e,fn);const o=e.get(t);if(o)return{cached:o,scope:"local"};const n=Fr(t);return n?(e.set(t,n),Yt(e,fn),{cached:n,scope:"global"}):null}async function Mo(e,t,o,n){const r=w(t.metadata.deviceId).trim();if(!r||o.has(r))return!1;const s=pt(t.metadata),c=n.get(r)||0;if(s>0&&s<=c)return!1;o.add(r);try{const m=await On(e,t.metadata,t.payload);return m&&s>0&&n.set(r,s),m}catch{return!1}finally{o.delete(r)}}function Oo(e){const t=e.getBoundingClientRect(),o=Math.max(64,Math.round(t.width||120)),n=Math.max(42,Math.round(t.height||72)),r=Math.min(mc,Math.max(1,window.devicePixelRatio||1)),s=Math.round(o*r),c=Math.round(n*r),m=Math.abs(e.width-s),l=Math.abs(e.height-c);(e.width<=0||e.height<=0||m>wa||l>wa)&&(e.width=s,e.height=c);const k=e.getContext("2d",{alpha:!1});return k?(k.setTransform(r,0,0,r,0,0),{ctx:k,width:o,height:n}):null}function Ro(e,t,o){const n=Oo(e);if(!n)return;const{ctx:r,width:s,height:c}=n;Zt.set(e,{left:0,top:0,width:s,height:c});const m=t.connected===!0;r.fillStyle=m?"#ffffff":"#f8fafc",r.fillRect(0,0,s,c),r.strokeStyle=m?"#dbeafe":"#e2e8f0",r.lineWidth=1,r.strokeRect(.5,.5,s-1,c-1),r.fillStyle=m?"#bfdbfe":"#e2e8f0",r.fillRect(8,8,Math.max(12,s*.34),5),r.fillRect(8,18,Math.max(20,s*.52),5),r.fillStyle=o==="blocked"?"#94a3b8":"#cbd5e1",r.font="700 9px Inter, sans-serif",r.fillText(o==="bridge"?"waiting":o,8,c-8)}async function Gr(e,t,o){const n=t.startsWith("data:")?t:ns(t,o);if(!n)return!1;const r=new Image;r.decoding="async",r.loading="eager",r.src=n,await r.decode();const s=Oo(e);if(!s)return!1;const{ctx:c,width:m,height:l}=s;return c.fillStyle="#020617",c.fillRect(0,0,m,l),Zt.set(e,_n(c,r,m,l)),!0}async function On(e,t,o){const n=new Blob([o],{type:t.mimeType||"image/jpeg"});let r=null;try{r=await createImageBitmap(n);const s=Oo(e);if(!s)return!1;const{ctx:c,width:m,height:l}=s;return c.fillStyle="#020617",c.fillRect(0,0,m,l),Zt.set(e,_n(c,r,m,l)),!0}catch{return zc(e,t,n)}finally{r==null||r.close()}}async function zc(e,t,o){const n=URL.createObjectURL(o);try{const r=new Image;r.decoding="async",r.loading="eager",r.src=n,await r.decode();const s=Oo(e);if(!s)return!1;const{ctx:c,width:m,height:l}=s;return c.fillStyle="#020617",c.fillRect(0,0,m,l),Zt.set(e,_n(c,r,m,l)),!0}catch{return g.emit("remoteMonitor.node.frameDecodeFailed",{deviceId:w(t.deviceId),frameSeq:Number(t.frameSeq||0)||0,mimeType:t.mimeType||"",byteLength:Number(t.byteLength||o.size||0)||0}),!1}finally{URL.revokeObjectURL(n)}}async function Tn(e,t,o,n,r,s,c){const m=Nn(o),l={painted:!1,busy:!1,staleDropped:!1,frameSeq:0,previous:0};if(!e||!m)return l;if(r.has(t))return{...l,busy:!0};const b=Number((o==null?void 0:o.frameSeq)||0)||0,k=Dn(s,c,t);if(b>0&&b<=k||b<=0&&k>0)return{painted:!1,busy:!1,staleDropped:!0,frameSeq:b,previous:k};r.add(t);try{const x=await Gr(e,m,n);return x&&b>0&&s.set(t,b),{painted:x,busy:!1,staleDropped:!1,frameSeq:b,previous:k}}catch{return{painted:!1,busy:!1,staleDropped:!1,frameSeq:b,previous:k}}finally{r.delete(t)}}function _n(e,t,o,n){const r="width"in t?Number(t.width):o,s="height"in t?Number(t.height):n,c=Math.min(o/Math.max(1,r),n/Math.max(1,s)),m=r*c,l=s*c,b=(o-m)/2,k=(n-l)/2;return e.drawImage(t,b,k,m,l),{left:b,top:k,width:m,height:l}}function du({launchers:e,activeLauncher:t,template:o,selectedOptionId:n,values:r,validationMessage:s,canCreate:c,primaryLabel:m="Create board",onLauncherSelected:l,onOptionSelected:b,onInputChanged:k,onCreate:x,onClose:v}){const V=(o==null?void 0:o.inputs)??[];return a.jsx("div",{className:"template-launcher-backdrop","data-testid":"template-launcher-panel",onMouseDown:v,children:a.jsxs("section",{className:"template-launcher-panel floating-panel",onMouseDown:R=>R.stopPropagation(),children:[a.jsxs("header",{className:"template-launcher-head",children:[a.jsxs("div",{children:[a.jsx("span",{children:"Execution Canvas"}),a.jsx("strong",{children:t.label})]}),a.jsx("button",{type:"button",title:"Close template launcher",onClick:v,children:a.jsx(Po,{size:16})})]}),a.jsx("div",{className:"template-launcher-tabs","aria-label":"Template launchers",children:e.map(R=>a.jsxs("button",{type:"button",className:R.id===t.id?"is-active":"","data-testid":"template-launcher-tab","data-launcher-id":R.id,onClick:()=>l(R.id),children:[a.jsx(Ei,{size:14}),a.jsx("span",{children:R.label})]},R.id))}),a.jsx("p",{className:"template-launcher-description",children:t.description}),t.options.length>0&&a.jsxs("div",{className:"template-launcher-option-block",children:[a.jsx("div",{className:"template-launcher-prompt",children:t.prompt||"Choose the board to create."}),a.jsx("div",{className:"template-launcher-chips",children:t.options.map(R=>a.jsxs("button",{type:"button",className:n===R.id?"is-active":"","data-testid":"template-option","data-option-id":R.id,onClick:()=>b(R.id),children:[a.jsx("strong",{children:R.label}),a.jsx("span",{children:R.description})]},R.id))})]}),V.length>0&&a.jsx("div",{className:"template-launcher-form",children:V.map(R=>a.jsx($c,{input:R,value:r[R.key]??"",onChange:F=>k(R.key,F)},R.key))}),s&&a.jsx("div",{className:"template-launcher-validation",children:s}),a.jsxs("footer",{className:"template-launcher-footer",children:[a.jsx("button",{type:"button",className:"template-launcher-secondary",onClick:v,children:"Cancel"}),a.jsxs("button",{type:"button",className:"template-launcher-primary","data-testid":"template-create",disabled:!c,onClick:x,children:[a.jsx(Na,{size:15}),a.jsx("span",{children:m})]})]})]})})}function $c({input:e,value:t,onChange:o}){return a.jsxs("label",{className:"template-launcher-field",children:[a.jsxs("span",{children:[a.jsx("strong",{children:e.label}),e.description&&a.jsx("small",{children:e.description})]}),e.type==="textarea"?a.jsx("textarea",{placeholder:e.placeholder,value:t,onChange:n=>o(n.target.value)}):e.type==="select"?a.jsx("select",{value:t,onChange:n=>o(n.target.value),children:(e.options??[]).map(n=>a.jsx("option",{value:n.value,children:n.label},n.value))}):a.jsx("input",{type:"text",placeholder:e.placeholder,value:t,onChange:n=>o(n.target.value)})]})}function uu({node:e,onSave:t,onClose:o}){var b,k,x,v,V,R;const[n,r]=p.useState(((b=e.metadata)==null?void 0:b.DirectoryPath)??e.sourceFilePath??""),[s,c]=p.useState(((k=e.metadata)==null?void 0:k.Include)??""),[m,l]=p.useState(((x=e.metadata)==null?void 0:x.Exclude)??"");return p.useEffect(()=>{var F,J,Z;r(((F=e.metadata)==null?void 0:F.DirectoryPath)??e.sourceFilePath??""),c(((J=e.metadata)==null?void 0:J.Include)??""),l(((Z=e.metadata)==null?void 0:Z.Exclude)??"")},[e.id,(v=e.metadata)==null?void 0:v.DirectoryPath,(V=e.metadata)==null?void 0:V.Exclude,(R=e.metadata)==null?void 0:R.Include,e.sourceFilePath]),a.jsx("div",{className:"directory-settings-backdrop","data-testid":"directory-settings-dialog",onMouseDown:o,children:a.jsxs("section",{className:"directory-settings-dialog","aria-label":"Folder scan settings","data-disable-mindcanvas-hotkeys":"true",onMouseDown:F=>F.stopPropagation(),children:[a.jsxs("header",{className:"directory-settings-head",children:[a.jsxs("div",{children:[a.jsxs("span",{children:[a.jsx(Li,{size:15}),"Folder scan settings"]}),a.jsx("strong",{title:e.sourceFilePath||e.title,children:e.title})]}),a.jsx("button",{type:"button",title:"Close folder scan settings","aria-label":"Close folder scan settings","data-testid":"directory-settings-close",onClick:o,children:a.jsx(Po,{size:16})})]}),a.jsxs("div",{className:"directory-settings-body",children:[a.jsxs("label",{className:"directory-setting-row",children:[a.jsxs("span",{children:[a.jsx(ji,{size:14}),"LocalBridge path"]}),a.jsx("input",{value:n,placeholder:"E:\\\\Dev@Work\\\\Project or relative/path","data-testid":"directory-settings-path",onChange:F=>r(F.target.value)})]}),a.jsxs("label",{className:"directory-setting-row",children:[a.jsxs("span",{children:[a.jsx(Ni,{size:14}),"Extensions to include"]}),a.jsx("input",{value:s,placeholder:".cs, .js, .razor, .css","data-testid":"directory-settings-include",onChange:F=>c(F.target.value)})]}),a.jsxs("label",{className:"directory-setting-row",children:[a.jsxs("span",{children:[a.jsx(Di,{size:14}),"Paths/files to exclude"]}),a.jsx("input",{value:m,placeholder:"bin, obj, .git, node_modules","data-testid":"directory-settings-exclude",onChange:F=>l(F.target.value)})]})]}),a.jsxs("footer",{className:"directory-settings-footer",children:[a.jsx("button",{type:"button","data-testid":"directory-settings-cancel",onClick:o,children:"Cancel"}),a.jsxs("button",{type:"button",className:"is-primary","data-testid":"directory-settings-save",onClick:()=>t(e.id,{DirectoryPath:n.trim(),Include:s.trim(),Exclude:m.trim()}),children:[a.jsx(Ba,{size:15}),"Save"]})]})]})})}const an=[{id:"frame",label:"Frame Perf",icon:Oi},{id:"render",label:"Render Debug",icon:_i},{id:"prompt",label:"Prompt Debug",icon:Fi},{id:"points",label:"Points",icon:Bi},{id:"dev",label:"Dev",icon:Gi}],yo=[{key:"frameProbe",label:"Frame profiler",description:"Tracks local React frame budget and viewport pressure.",defaultValue:!0},{key:"motionGuard",label:"Motion guard",description:"Highlights pan and zoom paths that must stay patch-only.",defaultValue:!0},{key:"overlayAudit",label:"Overlay debug",description:"Checks floating panels, popovers, and result overlays.",defaultValue:!0},{key:"bridgeGate",label:"LocalBridge gate monitor",description:"Keeps hosted loopback access explicit and visible.",defaultValue:!0},{key:"storageTrace",label:"Storage trace",description:"Surfaces local save and restore evidence for this board.",defaultValue:!0}],Vc=[{route:"/code",label:"CodeGraph",description:"Repository graph, agent commands, and code notes."},{route:"/planmaster",label:"PlanMaster",description:"Goal planning, step states, and execution memory."},{route:"/youtube",label:"YouTube Capture",description:"Local YouTube search flow and MindCanvas handoff."},{route:"/company-core",label:"CompanyCore",description:"Company cockpit, approvals, artifacts, and publishing jobs."},{route:"/admin/dashboard",label:"Admin Dashboard",description:"Billing, entitlement, refund, and audit shell."},{route:"/tools",label:"Free Tools",description:"Markdown, note, and clipboard mini workflows."}];function qc(e,t,o){const n=(0-t.x)/t.scale,r=(0-t.y)/t.scale,s=(o.width-t.x)/t.scale,c=(o.height-t.y)/t.scale;return e.nodes.filter(m=>{const l=m.x+m.width,b=m.y+m.height;return l>=n&&m.x<=s&&b>=r&&m.y<=c}).length}function Wc(e,t){const o=e.trim().split(/\s+/).filter(Boolean).length,n=Math.max(1,Math.ceil(o/120)),r=t==="Deep"?3:t==="Fast"?1:2;return{words:o,estimatedTokens:Math.max(8,Math.ceil(e.length/4)),points:n*r}}function Kc(e,t,o){return[`Board: ${e.name}`,`Nodes: ${e.nodes.length}`,`Edges: ${e.edges.length}`,`Selected: ${t?`${t.title} (${t.kind})`:"none"}`,`Model: ${e.settings.model}`,`Effort: ${e.settings.effort}`,"",o].join(`
44
- `)}function pu({board:e,selectedNode:t,selectedCount:o,input:n,viewport:r,viewportSize:s,localBridgeState:c,syncStatus:m,syncMessage:l,buildPrompt:b,navigate:k,onClose:x}){const[v,V]=p.useState("frame"),[R,F]=p.useState(""),[J,Z]=p.useState("idle"),[E,ue]=p.useState(null),[B,pe]=p.useState(()=>Object.fromEntries(yo.map(S=>[S.key,S.defaultValue]))),Ce=p.useMemo(()=>qc(e,r,s),[e,r,s]),h=R||b(),ee=p.useMemo(()=>Wc(h,e.settings.effort),[e.settings.effort,h]),L=p.useMemo(()=>Sl(e),[e,e.settings.aiProvider,e.settings.effort,e.settings.imageRouterImageModel,e.settings.imageRouterVideoModel,e.settings.inputMode,e.settings.model]),Y=an.find(S=>S.id===v)??an[0],Oe=Y.icon;p.useEffect(()=>{if(v!=="points")return;const S=e.settings.inputMode==="Image"?e.settings.imageRouterImageModel:e.settings.inputMode==="Video"?e.settings.imageRouterVideoModel:e.settings.model;g.emit("promptDebug.points.quote",{mode:e.settings.inputMode,model:S??"",billingKind:L.billingKind,displayPoints:L.displayPoints,pricingSource:L.vendorPricingSource??"none",estimatedFromCatalog:L.isEstimatedFromCatalog})},[v,e.settings.imageRouterImageModel,e.settings.imageRouterVideoModel,e.settings.inputMode,e.settings.model,L.billingKind,L.displayPoints,L.isEstimatedFromCatalog,L.vendorPricingSource]);const W=S=>{V(S),g.emit("promptDebug.tab",{tab:S})},Pe=()=>{const S=b();F(S),ue(new Date().toLocaleTimeString()),Z("idle"),g.emit("promptDebug.build",{tab:v,selectedKind:(t==null?void 0:t.kind)??"none",chars:S.length})},_e=async()=>{const S=Kc(e,t,R||b());try{const Q=await An(S);Z("copied"),g.emit("promptDebug.copy",{ok:!0,tab:v,method:Q})}catch(Q){const te=document.querySelector('[data-testid="prompt-debug-preview"]');if(te){te.focus(),te.select(),V("prompt"),Z("selected"),g.emit("promptDebug.copy",{ok:!1,selected:!0,tab:v,message:Q instanceof Error?Q.message:String(Q)});return}Z("failed"),g.emit("promptDebug.copy",{ok:!1,tab:v,message:Q instanceof Error?Q.message:String(Q)})}},be=()=>{F(""),ue(null),Z("idle"),g.emit("promptDebug.clear",{tab:v})},A=S=>{pe(Object.fromEntries(yo.map(Q=>[Q.key,S]))),g.emit("promptDebug.renderToggle",{all:S})},xe=()=>{pe(Object.fromEntries(yo.map(S=>[S.key,S.defaultValue]))),g.emit("promptDebug.renderToggle",{reset:!0})},Fe=(S,Q)=>{pe(te=>({...te,[S]:Q})),g.emit("promptDebug.renderToggle",{key:S,value:Q})};return a.jsx("div",{className:"prompt-debug-backdrop","data-testid":"prompt-debug-dialog",onMouseDown:x,children:a.jsxs("section",{className:"prompt-debug-dialog","aria-label":"Prompt debugger","data-disable-mindcanvas-hotkeys":"true",onMouseDown:S=>S.stopPropagation(),children:[a.jsxs("header",{className:"prompt-debug-header",children:[a.jsxs("div",{children:[a.jsx(Ui,{size:16}),a.jsx("strong",{children:"Prompt Debugger"})]}),a.jsxs("div",{className:"prompt-debug-header__actions",children:[a.jsxs("button",{type:"button",onClick:Pe,"data-testid":"prompt-debug-build",children:[a.jsx(zi,{size:13}),"Build"]}),a.jsxs("button",{type:"button",onClick:_e,"data-testid":"prompt-debug-copy",children:[J==="copied"?a.jsx(Ba,{size:13}):a.jsx(Da,{size:13}),J==="copied"?"Copied":J==="selected"?"Selected":J==="failed"?"Copy failed":"Copy"]}),a.jsxs("button",{type:"button",onClick:be,children:[a.jsx($i,{size:13}),"Clear"]}),a.jsx("button",{type:"button",title:"Close debugger",onClick:x,children:a.jsx(Po,{size:15})})]})]}),a.jsxs("div",{className:"prompt-debug-content",children:[a.jsx("nav",{className:"prompt-debug-tabs","aria-label":"Prompt debugger sections",children:an.map(S=>{const Q=S.icon;return a.jsxs("button",{type:"button",className:v===S.id?"is-active":"","data-testid":`prompt-debug-tab-${S.id}`,onClick:()=>W(S.id),children:[a.jsx(Q,{size:14}),S.label]},S.id)})}),a.jsxs("main",{className:"prompt-debug-main",children:[a.jsxs("div",{className:"prompt-debug-section-title",children:[a.jsx(Oe,{size:15}),a.jsx("strong",{children:Y.label}),a.jsx("span",{children:E?`Built ${E}`:"Local React diagnostics"})]}),v==="frame"&&a.jsxs("div",{className:"prompt-debug-metric-grid",children:[a.jsx(qe,{label:"Nodes",value:e.nodes.length,detail:`${Ce} visible`}),a.jsx(qe,{label:"Edges",value:e.edges.length,detail:`${o} selected`}),a.jsx(qe,{label:"Zoom",value:`${Math.round(r.scale*100)}%`,detail:`${Math.round(r.x)}, ${Math.round(r.y)}`}),a.jsx(qe,{label:"Storage",value:m,detail:l||"Local browser state"}),a.jsx(qe,{label:"Bridge",value:c,detail:"Loopback stays gated on hosted Pages"}),a.jsx(qe,{label:"Selected",value:(t==null?void 0:t.kind)||"none",detail:(t==null?void 0:t.title)||"No selected node"})]}),v==="render"&&a.jsxs("div",{className:"prompt-debug-stack",children:[a.jsxs("div",{className:"prompt-debug-actions",children:[a.jsx("button",{type:"button",onClick:()=>A(!0),children:"Enable all"}),a.jsx("button",{type:"button",onClick:()=>A(!1),children:"Disable all"}),a.jsxs("button",{type:"button",onClick:xe,children:[a.jsx(vo,{size:13}),"Reset"]})]}),yo.map(S=>a.jsxs("label",{className:"prompt-debug-toggle",children:[a.jsxs("span",{children:[a.jsx("strong",{children:S.label}),a.jsx("small",{children:S.description})]}),a.jsx("input",{type:"checkbox",checked:B[S.key]??!1,onChange:Q=>Fe(S.key,Q.target.checked)})]},S.key))]}),v==="prompt"&&a.jsxs("div",{className:"prompt-debug-stack",children:[a.jsxs("div",{className:"prompt-debug-readout",children:[a.jsx("span",{children:"Selected node"}),a.jsx("strong",{children:t?`${t.title} / ${t.kind}`:"No selected node"})]}),a.jsx("textarea",{"data-testid":"prompt-debug-preview",value:R||h,onChange:S=>F(S.target.value),spellCheck:!1})]}),v==="points"&&a.jsxs("div",{className:"prompt-debug-stack",children:[a.jsxs("div",{className:"prompt-debug-metric-grid prompt-debug-metric-grid--small",children:[a.jsx(qe,{label:"Mode",value:e.settings.inputMode,detail:e.settings.aiProvider??"OpenAI Codex"}),a.jsx(qe,{label:"Words",value:ee.words,detail:"Prompt preview"}),a.jsx(qe,{label:"Tokens",value:ee.estimatedTokens,detail:"Local estimate"}),a.jsx(qe,{label:"Points",value:L.displayLabel,detail:L.basisLabel})]}),a.jsxs("div",{className:"prompt-debug-point-quote","data-testid":"prompt-debug-point-quote","data-billing-kind":L.billingKind,"data-pricing-source":L.vendorPricingSource??"none","data-estimated-from-catalog":L.isEstimatedFromCatalog?"true":"false",children:[a.jsx("span",{children:L.billingKind}),a.jsx("strong",{children:L.displayLabel}),a.jsx("small",{children:L.vendorCostUsdSnapshot===void 0?L.vendorPricingSource??"Local provider":`${L.vendorPricingSource??"catalog"} vendor snapshot $${L.vendorCostUsdSnapshot.toFixed(4)}`})]}),a.jsx("div",{className:"prompt-debug-note",children:"Point quote follows the original local PointQuoteService policy. It does not bill credits or call server-side accounting."})]}),v==="dev"&&a.jsx("div",{className:"prompt-debug-dev-grid",children:Vc.map(S=>a.jsxs("button",{type:"button",onClick:()=>{g.emit("promptDebug.devTool.open",{route:S.route}),k(S.route)},children:[a.jsx(Vi,{size:14}),a.jsxs("span",{children:[a.jsx("strong",{children:S.label}),a.jsx("small",{children:S.description})]})]},S.route))})]})]})]})})}function qe({label:e,value:t,detail:o}){return a.jsxs("article",{className:"prompt-debug-card",children:[a.jsx("span",{children:e}),a.jsx("strong",{children:t}),a.jsx("small",{children:o})]})}export{An as $,Wa as A,id as B,Gd as C,qa as D,Td as E,kd as F,Wd as G,Ns as H,Qd as I,ou as J,Lt as K,ls as L,us as M,Ud as N,Eo as O,wn as P,cn as Q,lu as R,dn as S,Ao as T,ln as U,Zd as V,Jd as W,jo as X,Os as Y,Ie as Z,eu as _,_d as a,Ds as a0,Yd as a1,Nd as a2,du as a3,As as a4,zd as a5,uu as a6,su as a7,pu as a8,Za as a9,ld as aA,cd as aB,dd as aC,ud as aD,pd as aE,ad as aF,rd as aG,nd as aH,od as aI,ed as aJ,td as aK,bd as aL,md as aM,hd as aN,gd as aO,fd as aP,Jc as aQ,Qc as aR,Zc as aS,iu as aa,Id as ab,Qa as ac,Ml as ad,wl as ae,Rl as af,tu as ag,Do as ah,vd as ai,ms as aj,ps as ak,Cn as al,vn as am,rt as an,Cd as ao,xd as ap,wd as aq,Sd as ar,Md as as,Rd as at,Pd as au,Ad as av,Ed as aw,Ld as ax,jd as ay,sd as az,Od as b,au as c,Bd as d,ru as e,cu as f,j as g,Hd as h,nu as i,Qi as j,Ls as k,$d as l,Lo as m,jt as n,Vd as o,tr as p,js as q,Dd as r,Pt as s,ns as t,Kd as u,Xd as v,Fd as w,qd as x,In as y,yd as z};
43
+ 基础风格:{{musicGenre}}`,"template.music-core.node.references.title":"参考","template.music-core.node.references.body":"列出参考曲和想借鉴的点。","template.music-core.node.vocals.title":"人声 / 乐器","template.music-core.node.vocals.body":"写下人声类型和核心乐器配置。","template.music-core.node.lyrics.title":"歌词","template.music-core.node.lyrics.body":"整理主题、重复钩子和禁用表达。","template.music-core.node.generationPrompt.title":"生成提示词","template.music-core.node.generationPrompt.body":"收集音色、结构和氛围指令。","template.music-core.node.versions.title":"版本比较","template.music-core.node.versions.body":"记录 mp3 结果和修改点。"}},Ie={studioNodeType:"studioNodeType",templateNodeId:"templateNodeId",templateRole:"templateRole",compileTarget:"compileTarget",inputKey:"inputKey",inputType:"inputType",inputDescription:"inputDescription",inputPlaceholder:"inputPlaceholder",inputDefaultValue:"inputDefaultValue",inputRequired:"inputRequired",inputOptions:"inputOptions"},js=[{studioNodeType:"template.note",label:"Template Note",shortLabel:"Note"},{studioNodeType:"template.input",label:"Template Input",shortLabel:"Input"},{studioNodeType:"template.prompt",label:"Template Prompt",shortLabel:"Prompt"},{studioNodeType:"template.output",label:"Template Output",shortLabel:"Output"},{studioNodeType:"template.knowledge",label:"Knowledge Reference",shortLabel:"Know"},{studioNodeType:"template.section",label:"Section",shortLabel:"Sect"},{studioNodeType:"template.checklist",label:"Checklist",shortLabel:"List"}],qd=["note","memo","markdown","aiPrompt","output","section","checklist","input"],q={contentType:"templateLauncher",semanticTypeKey:"semanticType",semanticTypeValue:"TemplateLauncher",launcherIdKey:"templateLauncherId",selectedOptionIdKey:"templateLauncherSelectedOptionId",cardVersionKey:"templateCardVersion",cardLockedKey:"templateCardLocked",controllerNodeIdKey:"sourceTemplateControllerNodeId",runIdKey:"sourceTemplateRunId",cardGeneratedKey:"sourceTemplateCardGenerated",localizationManagedKey:"templateLocalizationManaged",localizationLanguageKey:"templateLanguageCode",sourceInputValuesJsonKey:"sourceTemplateInputValuesJson",width:560,height:620,resultTopGap:90},ut=Ls,Ns=new Set(["en","ko","ja","zh"]);function yt(e){if(typeof e!="string")return"en";const t=e.trim().toLowerCase();return!t||t==="auto"?"en":Ns.has(t)?t:"en"}function le(e,t="",o){const n=yt(o),r=ba[n],s=ba.en,c=r[e];if(c!==void 0)return c;const m=s[e];return n!=="ko"&&m!==void 0?m:t}function Jt(e,t){const o=Ye(e.id);return{...e,label:le(`launcher.${o}.title`,e.label,t),description:le(`launcher.${o}.desc`,e.description,t),prompt:le(`launcher.${o}.prompt`,e.prompt,t),options:e.options.map(n=>Ks(e.id,n,t))}}function Ht(e,t){const o=Ye(e.id);return{...e,boardTitle:le(`template.${o}.boardTitle`,e.boardTitle,t),inputs:e.inputs.map(n=>Xs(e.id,n,t)),nodes:e.nodes.map(n=>Ys(e.id,n,t))}}function Wd(e){return ut.launchers.map(t=>Jt(t,e))}function Ds(e,t){const o=ut.launchers.find(n=>K(n.id,e));return o?Jt(o,t):null}function Lo(e,t){if(e.options.length!==0)return e.options.find(o=>K(o.id,t||""))??e.options[0]}function Os(e,t,o){const n=Lo(e,t),r=(n==null?void 0:n.templateId)||e.quickCreateTemplateId||"",s=ut.templates.find(c=>K(c.id,r));return s?Ht(s,o):null}function Hd(e){const t={};for(const o of(e==null?void 0:e.inputs)??[])t[o.key]=Pn(o);return t}function Kd(e,t){if(!e)return"Template is unavailable.";const o=e.inputs.find(n=>n.required&&!String(t[n.key]||"").trim());return o?`${o.label} is required.`:null}function _s(e,t,o,n){const r=yt(n.appLanguage),s=Jt(e,r),c=Lo(s,t),m=Os(s,c==null?void 0:c.id,r);return m?Fs(s,c,m,o,n):null}function Fs(e,t,o,n,r){const s=No(o,n),c=nr(e,t,s),m=new Date().toISOString(),l=ir("template-board"),b=At(o.boardTitle,c).trim()||e.label,k=o.nodes.map((x,v)=>Gs(x,e,t,o,c,l,v));return{launcher:e,option:t,template:o,board:{id:l,name:b,updatedAt:m,settings:r,source:{kind:"localStorage",loadedAt:m},nodes:k,edges:[]}}}function er(e,t,o={},n){const r=yt(n),s=Jt(e,r),c=Qs(r),m=nl(s,t),l={launcherId:s.id,title:s.label,description:s.description,prompt:s.prompt,iconClass:s.iconClass,selectedOptionId:m??void 0,options:[],inputValues:{},generateLabel:c.generateLabel,noInputsLabel:c.noInputsLabel,generatingMessage:c.generatingMessage,generatedMessageFormat:c.generatedMessageFormat,generationFailedMessage:c.generationFailedMessage,requiredMessageFormat:c.requiredMessageFormat,actionLabel:c.generateLabel};if(s.options.length===0){const k=s.quickCreateTemplateId?ut.templates.find(x=>K(x.id,e.quickCreateTemplateId)):null;if(k){const x=Ht(k,r);l.options.push({id:"",label:s.label,description:s.description,templateId:x.id,inputs:un(x.inputs)})}}else for(const k of s.options){const x=ut.templates.find(V=>K(V.id,k.templateId)),v=x?Ht(x,r):null;l.options.push({id:k.id,label:k.label,description:k.description,templateId:k.templateId,inputs:un((v==null?void 0:v.inputs)??[])})}const b=l.options.find(k=>K(k.id,l.selectedOptionId))??l.options[0];return l.selectedOptionId=b==null?void 0:b.id,l.inputValues=ar((b==null?void 0:b.inputs)??[],o),l}function Xd(e,t,o,n,r={},s){const c=yt(s),m=er(e,t,r,c),l=m.options.find(k=>K(k.id,m.selectedOptionId)),b={[q.semanticTypeKey]:q.semanticTypeValue,[q.launcherIdKey]:e.id,[q.selectedOptionIdKey]:m.selectedOptionId??"",[q.cardVersionKey]:"1.0",[q.cardLockedKey]:"True",[q.localizationLanguageKey]:c,IsNew:"true"};return{id:ir("template-card"),kind:"template-launcher",title:m.title,body:JSON.stringify(m),x:o,y:n,width:q.width,height:q.height,tags:["Template","Launcher",e.label,l==null?void 0:l.label].filter(k=>!!k),metadata:b,aiEnabled:!1}}function Mn(e){var t;return e?e.kind==="template-launcher"?!0:K((t=e.metadata)==null?void 0:t[q.semanticTypeKey],q.semanticTypeValue):!1}function tr(e){try{const t=JSON.parse(String(e||""));return!t||typeof t!="object"||!t.launcherId||!Array.isArray(t.options)?null:{launcherId:String(t.launcherId||""),title:String(t.title||""),description:String(t.description||""),prompt:String(t.prompt||""),iconClass:String(t.iconClass||""),selectedOptionId:t.selectedOptionId===void 0?void 0:String(t.selectedOptionId),options:t.options.map(o=>({id:String(o.id||""),label:String(o.label||""),description:String(o.description||""),templateId:String(o.templateId||""),inputs:un(o.inputs??[])})),inputValues:Object.fromEntries(Object.entries(t.inputValues??{}).map(([o,n])=>[o,String(n??"")])),generateLabel:String(t.generateLabel||t.actionLabel||"Generate"),noInputsLabel:String(t.noInputsLabel||"No inputs needed."),generatingMessage:String(t.generatingMessage||"Generating nodes..."),generatedMessageFormat:String(t.generatedMessageFormat||"Generated {0} nodes below."),generationFailedMessage:String(t.generationFailedMessage||"Template generation failed."),requiredMessageFormat:String(t.requiredMessageFormat||"{0} is required."),actionLabel:String(t.actionLabel||t.generateLabel||"Generate")}}catch{return null}}function Yd(e,t){const o=e.options.find(n=>K(n.id,t))??e.options[0];return{...e,selectedOptionId:o==null?void 0:o.id,inputValues:ar((o==null?void 0:o.inputs)??[],e.inputValues)}}function Qd(e,t,o){return{...e,inputValues:{...e.inputValues,[t]:o}}}function Jd(e){if(!e)return"Template card payload is unavailable.";const t=e.options.find(n=>K(n.id,e.selectedOptionId))??e.options[0];if(!t)return"Template card option is unavailable.";const o=t.inputs.find(n=>n.required&&!String(e.inputValues[n.key]||"").trim());return o?ol(e.requiredMessageFormat||"{0} is required.",o.label):null}function Zd(e,t,o,n,r=al()){var Z;if(!Mn(e))return null;const s=(Z=e.metadata)==null?void 0:Z[q.launcherIdKey],c=yt(n.appLanguage),m=s?Ds(s,c):null;if(!m)return null;const l=Lo(m,t),b=_s(m,(l==null?void 0:l.id)??null,o,n);if(!b)return null;const k=No(b.template,o),x=JSON.stringify(k),v=Math.min(...b.board.nodes.map(E=>E.x)),V=Math.min(...b.board.nodes.map(E=>E.y)),M=e.x,F=e.y+Math.max(e.height,q.height)+q.resultTopGap,J=b.board.nodes.map(E=>({...E,x:M+(E.x-v),y:F+(E.y-V),metadata:{...E.metadata??{},[q.controllerNodeIdKey]:e.id,[q.runIdKey]:r,[q.cardGeneratedKey]:"True",[q.localizationManagedKey]:"True",[q.localizationLanguageKey]:c,[q.sourceInputValuesJsonKey]:x}}));return{launcher:m,option:b.option,template:b.template,runId:r,nodes:J}}function eu(e,t){const o=yt(t),n=new Map(e.map(c=>[c.id,c]));let r=!1;const s=e.map(c=>{const m=Js(c,o);if(m)return r=!0,m;const l=Zs(c,n,o);return l?(r=!0,l):c});return{nodes:r?s:e,changed:r,language:o}}function tu(e){const t=String(e||"").trim()||"Template Studio Draft";return{templateId:jo(t),templateTitle:t,category:"custom",boardTitle:t,version:"0.1.0",tier:"draft",status:"draft"}}function ou(e,t){const o=[],n=Us(e),r=t.filter(k=>!!ve(k,Ie.studioNodeType)).sort((k,x)=>k.y-x.y||k.x-x.x||k.id.localeCompare(x.id)),s=r.filter(k=>K(ve(k,Ie.studioNodeType),"template.input")),c=r.filter(k=>!K(ve(k,Ie.studioNodeType),"template.input")),m=zs(s,o),l=$s(c,o);r.length===0&&o.push({code:"studio.nodes.empty",message:"Add at least one Template Studio node before compiling."});const b={id:n.templateId,version:n.version,tier:n.tier,status:n.status,boardTitle:n.boardTitle,inputs:m,nodes:l};return Vs(b,o),{template:b,manifestJson:JSON.stringify(b,null,2),issues:o}}function jo(e){return String(e||"").trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"template-studio-draft"}function Bs(e,t){switch(String(e||"").trim().toLowerCase()||or(t)){case"template.input":return"input";case"template.prompt":return"aiPrompt";case"template.output":return"output";case"template.knowledge":return"memo";case"template.section":return"section";case"template.checklist":return"checklist";default:return t?rr(t.kind):"note"}}function or(e){if(!e)return"template.note";switch(e.kind){case"ai-task":return"template.prompt";case"markdown":return"template.section";case"memo":return"template.knowledge";default:return"template.note"}}function nu(e){const t=js.find(o=>K(o.studioNodeType,e));return(t==null?void 0:t.shortLabel)??"Note"}function Gs(e,t,o,n,r,s,c){const m={};for(const[b,k]of Object.entries(e.metadata??{}))m[b]=At(k,r);m.IsNew="true",m.sourceLauncherId=t.id,m.sourceTemplateId=n.id,m.sourceTemplateVersion=n.version,m.sourceTemplateNodeId=e.id,m.templateRole=m.templateRole||e.id,m.templateLauncher=t.id,m.templateId=n.id,m.templateVersion=n.version,m.templateNodeId=e.id,o!=null&&o.id&&(m.sourceOptionId=o.id,m.templateOption=o.id);const l=rl(e.contentType);return{id:`${s}-${e.id||c}`,kind:l,title:At(e.title,r),body:At(e.body,r),x:Number(e.x)||0,y:Number(e.y)||0,width:Math.max(180,Number(e.width)||340),height:Math.max(120,Number(e.height)||220),tags:["Template",t.label,(o==null?void 0:o.label)||n.tier].filter(Boolean),metadata:m}}function No(e,t){const o={};for(const n of e.inputs){const r=String(t[n.key]??"").trim();o[n.key]=r||Pn(n)}return o}function nr(e,t,o){const n=(t==null?void 0:t.label)||e.label,r=(t==null?void 0:t.description)||e.description,s={launcherId:e.id,launcherLabel:e.label,launcherDescription:e.description,optionId:(t==null?void 0:t.id)||"",optionLabel:n,optionDescription:r,selectionLabel:n,timestampShort:il(new Date)};for(const[c,m]of Object.entries(o))s[c]=m;return s}function At(e,t){let o=e||"";for(const[n,r]of Object.entries(t))o=o.replace(new RegExp(`{{\\s*${sl(n)}\\s*}}`,"gi"),r);return o}function Pn(e){var t,o;return e.defaultValue?e.defaultValue:e.type==="select"&&((o=(t=e.options)==null?void 0:t[0])==null?void 0:o.value)||""}function Us(e){const t=String(e.templateTitle||"").trim()||"Template Studio Draft";return{templateId:jo(e.templateId||t),templateTitle:t,category:String(e.category||"").trim()||"custom",boardTitle:String(e.boardTitle||"").trim()||t,version:String(e.version||"").trim()||"0.1.0",tier:String(e.tier||"").trim()||"draft",status:String(e.status||"").trim()||"draft"}}function zs(e,t){const o=[],n=new Set;for(const r of e){const s=r.title.trim()||"Input",c=jo(ve(r,Ie.inputKey)||s),m=c.toLowerCase();if(n.has(m)){t.push({code:"studio.input.duplicate",message:`Template Studio input '${c}' is duplicated.`});continue}n.add(m),o.push({key:c,type:qs(ve(r,Ie.inputType)),label:s,description:ve(r,Ie.inputDescription)||r.body,placeholder:ve(r,Ie.inputPlaceholder),defaultValue:ve(r,Ie.inputDefaultValue),required:Ws(ve(r,Ie.inputRequired)),options:Hs(ve(r,Ie.inputOptions))})}return o}function $s(e,t){const o=[],n=new Set;for(const r of e){const s=ve(r,Ie.studioNodeType)||or(r);let c=jo(ve(r,Ie.templateNodeId)||r.title);const m=c.toLowerCase();if(n.has(m)){t.push({code:"studio.node.duplicate",message:`Template Studio node '${c}' is duplicated.`});continue}n.add(m);const l=ve(r,Ie.compileTarget)||Bs(s,r),b=ve(r,Ie.templateRole)||s.replace(/^template\./i,"");o.push({id:c,contentType:l,title:r.title.trim(),body:r.body,x:Math.round(r.x),y:Math.round(r.y),width:Math.max(180,Math.round(r.width||340)),height:Math.max(120,Math.round(r.height||220)),metadata:{templateRole:b,studioNodeType:s,compileTarget:l,studioSourceContentType:rr(r.kind)}})}return o}function Vs(e,t){const o=new Set;for(const r of e.inputs)r.key||t.push({code:"template.input.key",message:`Template '${e.id}' contains an input with no key.`}),r.label||t.push({code:"template.input.label",message:`Template '${e.id}' input '${r.key}' must define a label.`}),o.has(r.key.toLowerCase())&&t.push({code:"template.inputs.duplicate",message:`Template '${e.id}' contains duplicate input key '${r.key}'.`}),o.add(r.key.toLowerCase());const n=new Set;for(const r of e.nodes)r.id||t.push({code:"template.node.id",message:`Template '${e.id}' contains a node with no id.`}),n.has(r.id.toLowerCase())&&t.push({code:"template.nodes.duplicate",message:`Template '${e.id}' contains duplicate node id '${r.id}'.`}),n.add(r.id.toLowerCase())}function ve(e,t){var n;const o=(n=e.metadata)==null?void 0:n[t];return typeof o=="string"?o.trim():""}function qs(e){const t=e.trim().toLowerCase();return t==="textarea"||t==="select"?t:"text"}function Ws(e){return e.trim().toLowerCase()==="true"}function Hs(e){const t=[];for(const o of e.split(/\r?\n/)){const n=o.trim();if(!n)continue;const[r,s]=n.split("|",2).map(c=>c.trim());r&&t.push({value:r,label:s||r})}return t}function Ks(e,t,o){const n=Ye(e),r=Ye(t.id);return{...t,label:le(`launcher.${n}.option.${r}.title`,t.label,o),description:le(`launcher.${n}.option.${r}.desc`,t.description,o)}}function Xs(e,t,o){var s;const n=Ye(e),r=Ye(t.key);return{...t,label:le(`template.${n}.input.${r}.label`,t.label,o),description:le(`template.${n}.input.${r}.desc`,t.description,o),placeholder:le(`template.${n}.input.${r}.placeholder`,t.placeholder,o),options:(s=t.options)==null?void 0:s.map(c=>({...c,label:le(`template.${n}.input.${r}.option.${Ye(c.value)}`,c.label,o)}))}}function Ys(e,t,o){const n=Ye(e),r=Ye(t.id);return{...t,title:le(`template.${n}.node.${r}.title`,t.title,o),body:le(`template.${n}.node.${r}.body`,t.body,o),metadata:{...t.metadata??{}}}}function Qs(e){return{generateLabel:le("templateCard.generate","Generate",e),noInputsLabel:le("templateCard.noInputs","No inputs needed.",e),generatingMessage:le("templateCard.generating","Generating nodes...",e),generatedMessageFormat:le("templateCard.generated","Generated {0} nodes below.",e),generationFailedMessage:le("templateCard.failed","Template generation failed.",e),requiredMessageFormat:le("templateCard.required","{0} is required.",e)}}function Js(e,t){var m,l,b,k;if(!Mn(e))return null;const o=tr(e.body),n=((m=e.metadata)==null?void 0:m[q.launcherIdKey])||(o==null?void 0:o.launcherId),r=n?ut.launchers.find(x=>K(x.id,n)):null;if(!r)return null;const s=(o==null?void 0:o.selectedOptionId)||((l=e.metadata)==null?void 0:l[q.selectedOptionIdKey])||null,c=er(r,s,(o==null?void 0:o.inputValues)??{},t);return e.title===c.title&&e.body===JSON.stringify(c)&&((b=e.metadata)==null?void 0:b[q.localizationLanguageKey])===t?null:{...e,title:c.title,body:JSON.stringify(c),tags:["Template","Launcher",c.title,(k=c.options.find(x=>x.id===c.selectedOptionId))==null?void 0:k.label].filter(x=>!!x),metadata:{...e.metadata??{},[q.launcherIdKey]:r.id,[q.selectedOptionIdKey]:c.selectedOptionId??"",[q.localizationLanguageKey]:t}}}function Zs(e,t,o){if(Mn(e))return null;const n=ho(Be(e,"sourceTemplateId"),Be(e,"templateId")),r=ho(Be(e,"sourceTemplateNodeId"),Be(e,"templateNodeId")),s=ho(Be(e,"sourceLauncherId"),Be(e,"templateLauncher"));if(!n||!r||!s)return null;const c=ut.launchers.find(Z=>K(Z.id,s)),m=ut.templates.find(Z=>K(Z.id,n));if(!c||!m)return null;const l=ho(Be(e,"sourceOptionId"),Be(e,"templateOption")),b=el(e,t),k=No(Ht(m,o),b),x=en(c,m,r,l,k,"ko"),v=yt(Be(e,q.localizationLanguageKey)||"ko"),V=en(c,m,r,l,k,v),M=en(c,m,r,l,k,o);if(!x||!V||!M)return null;const F=e.title===x.title||e.title===V.title,J=e.body===x.body||e.body===V.body;return!F&&!J?null:{...e,title:F?M.title:e.title,body:J?M.body:e.body,tags:["Template",M.launcherLabel,M.optionLabel].filter(Boolean),metadata:{...e.metadata??{},[q.localizationManagedKey]:"True",[q.localizationLanguageKey]:o,[q.sourceInputValuesJsonKey]:JSON.stringify(k)}}}function en(e,t,o,n,r,s){const c=Jt(e,s),m=Ht(t,s),l=Lo(c,n),b=m.nodes.find(v=>K(v.id,o));if(!b)return null;const k=No(m,r),x=nr(c,l,k);return{title:At(b.title,x),body:At(b.body,x),launcherLabel:c.label,optionLabel:(l==null?void 0:l.label)||c.label}}function el(e,t){const o=tl(Be(e,q.sourceInputValuesJsonKey));if(Object.keys(o).length>0)return o;const n=Be(e,q.controllerNodeIdKey),r=n?t.get(n):null,s=tr(r==null?void 0:r.body);return(s==null?void 0:s.inputValues)??{}}function tl(e){if(!e)return{};try{const t=JSON.parse(e);return Object.fromEntries(Object.entries(t??{}).map(([o,n])=>[o,String(n??"")]))}catch{return{}}}function Be(e,t){var n;const o=(n=e.metadata)==null?void 0:n[t];return typeof o=="string"&&o.trim()?o.trim():null}function ho(...e){var t;return((t=e.find(o=>typeof o=="string"&&o.trim()))==null?void 0:t.trim())??null}function Ye(e){const t=String(e||"").trim();return t?t.replace(/:/g,"."):"unknown"}function ol(e,t){return e.includes("{0}")?e.replace("{0}",t):`${t} is required.`}function nl(e,t){var o,n,r;return String(t||"").trim()?((n=e.options.find(s=>K(s.id,t)))==null?void 0:n.id)??((r=e.options[0])==null?void 0:r.id):(o=e.options[0])==null?void 0:o.id}function un(e){return e.map(t=>{var o;return{...t,options:(o=t.options)==null?void 0:o.map(n=>({...n}))}})}function ar(e,t){const o={};for(const n of e)o[n.key]=String(t[n.key]??Pn(n));return o}function al(){const e=new Date,t=(o,n=2)=>`${o}`.padStart(n,"0");return[e.getFullYear(),t(e.getMonth()+1),t(e.getDate()),t(e.getHours()),t(e.getMinutes()),t(e.getSeconds()),t(e.getMilliseconds(),3)].join("")}function rr(e){return e==="ai-task"?"aiPrompt":e==="template-launcher"?q.contentType:e}function rl(e){return K(e,"directory")?"directory":K(e,"pdf")?"pdf":K(e,"file")?"file":K(e,"memo")?"memo":K(e,"markdown")?"markdown":K(e,"csv-table")?"csv-table":K(e,"text")?"text":K(e,"code")?"code":K(e,"mask")?"mask":K(e,"image")?"image":K(e,"embed")?"embed":K(e,"aiPrompt")?"ai-task":K(e,q.contentType)?"template-launcher":"note"}function il(e){const t=`${e.getMonth()+1}`.padStart(2,"0"),o=`${e.getDate()}`.padStart(2,"0"),n=`${e.getHours()}`.padStart(2,"0"),r=`${e.getMinutes()}`.padStart(2,"0");return`${t}.${o} ${n}:${r}`}function ir(e){return`${e}-${Math.random().toString(36).slice(2,9)}`}function K(e,t){return String(e||"").toLowerCase()===String(t||"").toLowerCase()}function sl(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function An(e){var r;let t=null;if(typeof navigator<"u"&&((r=navigator.clipboard)!=null&&r.writeText))try{return await navigator.clipboard.writeText(e),"clipboard"}catch(s){t=s}if(typeof document>"u"||!document.body||typeof document.execCommand!="function")throw t instanceof Error?t:new Error("clipboard-unavailable");const o=document.createElement("textarea"),n=document.activeElement instanceof HTMLElement?document.activeElement:null;o.value=e,o.setAttribute("readonly",""),o.style.position="fixed",o.style.left="-9999px",o.style.top="0",o.style.opacity="0",document.body.appendChild(o),o.focus(),o.select(),o.setSelectionRange(0,e.length);try{if(!document.execCommand("copy"))throw t instanceof Error?t:new Error("clipboard-unavailable");return"fallback"}finally{o.remove(),n==null||n.focus({preventScroll:!0})}}const sr="mindexec.app.language",xo="auto",Kt=[{code:xo,label:"Auto",nativeLabel:"Auto",englishName:"the user's input language",htmlLang:"auto",isAuto:!0,description:"Match the user's input language unless a prompt asks otherwise."},{code:"en",label:"English",nativeLabel:"English",englishName:"English",htmlLang:"en",isAuto:!1,description:"Prefer English for user-facing AI output."},{code:"ko",label:"Korean",nativeLabel:"한국어",englishName:"Korean",htmlLang:"ko",isAuto:!1,description:"Prefer Korean for user-facing AI output."},{code:"ja",label:"Japanese",nativeLabel:"日本語",englishName:"Japanese",htmlLang:"ja",isAuto:!1,description:"Prefer Japanese for user-facing AI output."},{code:"zh",label:"Chinese",nativeLabel:"中文",englishName:"Chinese",htmlLang:"zh",isAuto:!1,description:"Prefer Chinese for user-facing AI output."}];function jt(e){if(typeof e!="string")return xo;const t=e.trim().toLowerCase();return Kt.some(o=>o.code===t)?t:xo}function Do(e){const t=jt(e);return Kt.find(o=>o.code===t)??Kt[0]}function lr(){if(typeof window>"u")return null;try{const e=window.localStorage.getItem(sr);return e===null?null:jt(e)}catch{return null}}function au(e){return jt(lr()??e??xo)}function ru(e){const t=jt(e);if(typeof window>"u")return t;try{window.localStorage.setItem(sr,t)}catch{}return t}function iu(e){const t=lr()??jt(e.settings.appLanguage);return{...e,settings:{...e.settings,appLanguage:t}}}function su(e){const t=Do(e);return t.isAuto?"Language preference: match the user's input language unless the user explicitly asks for a different language.":`Language preference: respond in ${t.englishName} unless the user explicitly asks for a different language.`}function lu(e){return Do(e).englishName}function cu(e){const t=Do(e);return t.isAuto?"Language preference: if the generated asset includes visible text, captions, labels, or UI copy, match the user's input language unless the prompt explicitly asks for another language.":`Language preference: if the generated asset includes visible text, captions, labels, or UI copy, use ${t.englishName} unless the prompt explicitly asks for another language.`}const En=.001,ll=1,cl=5,dl=1.35,ul=1.3,pl=1.45,ml=.002,gl=.01,hl=.03,fl=.002,bl=.015,yl=.05,kl=5,Tl=20,Il=100,vl=2,ya=2500,Cl=800,xl=1200,wl=1800,Sl=2600,Rl={"deepseek/deepseek-v4-flash":{promptUsdPerToken:14e-8,completionUsdPerToken:28e-8,source:"openrouter"},"deepseek/deepseek-v4-pro":{promptUsdPerToken:435e-9,completionUsdPerToken:87e-8,source:"openrouter"},"deepseek/deepseek-chat-v3-0324":{promptUsdPerToken:14e-8,completionUsdPerToken:28e-8,source:"openrouter"},"gpt-image-2":{averageUsd:.02,source:"imagerouter"},"Tongyi-MAI/Z-Image-Turbo:free":{averageUsd:.02,source:"imagerouter"},"google/veo-2":{averageUsd:.25,maxUsd:.25,source:"imagerouter"},"runway/gen-3":{averageUsd:.2,maxUsd:.2,source:"imagerouter"}};function Ml(e){const t=Fl(e.reasoningEffort);return e.mode==="Text"?jl(e.provider,t,e.vendorPricing):e.mode==="Image"&&e.provider==="openai-codex"&&Gl(e.modelId)?st("Free",0,"Codex Responses image generation",void 0,"codex",!1):e.mode==="Image"?Dl(e.vendorPricing):e.mode==="Video"?Ol(e.vendorPricing):Et("Unavailable")}function Pl(e){const t=e.settings.inputMode==="Image"||e.settings.inputMode==="Video"?e.settings.inputMode:"Text",o=Ll(e.settings,t);return Ml({mode:t,provider:El(e.settings),modelId:o,reasoningEffort:e.settings.effort,vendorPricing:Al(o)})}function Al(e){const t=Ul(e);return Rl[t]??null}function El(e){switch(e.aiProvider??"OpenAI Codex"){case"Local Ollama":return"local-ollama";case"BYOK":return"byok";case"Managed Cloud":return"managed-cloud";case"Gemini CLI":return"google-gemini-cli";case"OpenAI Codex":default:return"openai-codex"}}function Ll(e,t){return t==="Image"?ln("Image",e).id:t==="Video"?ln("Video",e).id:e.model}function jl(e,t,o){switch(e){case"local-ollama":return st("Free",0,"Local execution",void 0,"ollama",!1);case"byok":return st("ServiceFeeOnly",vl,"BYOK platform fee",void 0,"byok",!1);case"openai-codex":return st("Free",0,"Codex CLI local execution",void 0,"codex",!1);case"google-gemini-cli":return st("Free",0,"Gemini CLI local execution",void 0,"gemini-cli",!1);case"managed-cloud":default:return Nl(t,o)}}function Nl(e,t){if(!bt(t==null?void 0:t.promptUsdPerToken)||!bt(t==null?void 0:t.completionUsdPerToken))return Et("Pricing unavailable");const o=_l(e),n=((t==null?void 0:t.requestUsd)??0)+t.promptUsdPerToken*ya+t.completionUsdPerToken*o,r=n*dl+ml+fl,s=Ln(Math.max(r/En,kl),ll);return st("FixedPoints",s,`Base run (${pn(ya)} in / ${pn(o)} out)`,n,t.source,!0)}function Dl(e){if(!e)return Et("Pricing unavailable");let t=e.averageUsd??e.maxUsd??e.minUsd;if(!bt(t))return Et("Pricing unavailable");bt(e.minUsd)&&(t=Math.max(t,e.minUsd*1.15));const o=t*ul+gl+bl,n=Ln(Math.max(o/En,Tl),cl);return st("FixedPoints",n,"Base image generation",t,e.source,!0)}function Ol(e){if(!e)return Et("Pricing unavailable");let t=0;if(bt(e.maxUsd)&&(t=Math.max(t,e.maxUsd)),bt(e.averageUsd)&&(t=Math.max(t,e.averageUsd*1.25)),bt(e.minUsd)&&(t=Math.max(t,e.minUsd)),t<=0)return Et("Pricing unavailable");const o=t*pl+hl+yl,n=Ln(Math.max(o/En,Il),10);return st("FixedPoints",n,"Base video generation",t,e.source,!0)}function _l(e){switch(e){case"low":return Cl;case"high":return wl;case"xhigh":return Sl;case"medium":default:return xl}}function Fl(e){switch(String(e??"").trim().toLowerCase()){case"fast":case"low":return"low";case"deep":case"xhigh":return"xhigh";case"high":return"high";case"normal":case"medium":default:return"medium"}}function Ln(e,t){return t<=1?Math.ceil(e):Math.ceil(e/t)*t}function st(e,t,o,n,r,s){return{billingKind:e,displayPoints:t,displayLabel:Bl(t),basisLabel:o,isEstimatedFromCatalog:s,vendorCostUsdSnapshot:n,vendorPricingSource:r}}function Et(e){return{billingKind:"Unavailable",displayPoints:0,displayLabel:e,basisLabel:"Pricing unavailable",isEstimatedFromCatalog:!1}}function Bl(e){return`${pn(e)}P`}function pn(e){return e.toLocaleString("en-US",{maximumFractionDigits:0})}function Gl(e){return String(e??"").trim().toLowerCase().startsWith("codex-image:")}function Ul(e){return String(e??"").trim()}function bt(e){return typeof e=="number"&&Number.isFinite(e)}const tn=[{id:"general",label:"General",icon:hi},{id:"language",label:"Language",icon:fi},{id:"connection",label:"Connection",icon:bi},{id:"media",label:"Media",icon:ja},{id:"agent",label:"Agent",icon:yi},{id:"system",label:"System",icon:ki},{id:"about",label:"About",icon:Ti}],zl=["Managed Cloud","BYOK","OpenAI Codex","Local Ollama"];function $l(e,t,o){return Number.isFinite(e)?Math.min(o,Math.max(t,Math.round(e))):t}function du({settings:e,onPatchSettings:t,onClose:o}){const[n,r]=p.useState("general"),[s,c]=p.useState("idle"),[m,l]=p.useState(null),b=tn.find(g=>g.id===n)??tn[0],k=gs(e),x=Lt(e.model),v=e.aiProvider??"OpenAI Codex",V=ql(x),M=Do(e.appLanguage),F=ka("Image",e),J=ka("Video",e),Z=Object.fromEntries(Kt.map(g=>[g.code,g.isAuto?g.label:`${g.nativeLabel} / ${g.label}`])),E=(g,ee)=>t(g,ee),ue=g=>{const ee=g.currentTarget;let L=0;if(g.key==="PageDown")L=Math.max(160,Math.floor(ee.clientHeight*.86));else if(g.key==="PageUp")L=-Math.max(160,Math.floor(ee.clientHeight*.86));else if(g.key==="ArrowDown")L=44;else if(g.key==="ArrowUp")L=-44;else if(g.key==="End"){g.preventDefault(),ee.scrollTo({top:ee.scrollHeight,behavior:"auto"});return}else if(g.key==="Home"){g.preventDefault(),ee.scrollTo({top:0,behavior:"auto"});return}else return;g.preventDefault(),ee.scrollBy({top:L,behavior:"auto"})},B=async()=>{try{const g=await An(V);c("copied"),h.emit("settings.providerCommand.copy",{provider:v,command:"dataset-generator",method:g,redacted:!0})}catch(g){if(Wl(m)){c("selected"),h.emit("settings.providerCommand.selectFallback",{provider:v,command:"dataset-generator",message:g instanceof Error?g.message:String(g),redacted:!0});return}c("failed"),h.emit("settings.providerCommand.copyFailed",{provider:v,command:"dataset-generator",message:g instanceof Error?g.message:String(g)})}},pe=(g,ee)=>{const L=wn(g,ee),Y=Eo(g).find(Pe=>Pe.id===L);if(!Y)return;const Oe=g==="Image"?e.imageRouterImageAspectPresetId:e.imageRouterVideoAspectPresetId,W=cn(g,Y,Oe);E(g==="Image"?{imageRouterImageModel:Y.id,imageRouterImageAspectPresetId:W.id}:{imageRouterVideoModel:Y.id,imageRouterVideoAspectPresetId:W.id},`media.${g.toLowerCase()}.model`),h.emit("media.model.select",{mode:g,model:Y.id,aspectPresetId:W.id,requestedSize:dn(W),source:"settings-dialog"})},Ce=(g,ee)=>{const L=g==="Image"?F.model:J.model,Y=cn(g,L,ee);E(g==="Image"?{imageRouterImageAspectPresetId:Y.id}:{imageRouterVideoAspectPresetId:Y.id},`media.${g.toLowerCase()}.aspect`),h.emit("media.aspect.select",{mode:g,model:L.id,aspectPresetId:Y.id,requestedSize:dn(Y),source:"settings-dialog"})};return a.jsx("div",{className:"ai-settings-backdrop","data-testid":"ai-settings-dialog","data-disable-mindcanvas-wheel":"true",onMouseDown:o,children:a.jsxs("section",{className:"ai-settings-dialog","aria-label":"AI settings","data-disable-mindcanvas-hotkeys":"true","data-ai-settings-dialog-surface":"true",onMouseDown:g=>g.stopPropagation(),children:[a.jsx("aside",{className:"ai-settings-tabs","aria-label":"Settings sections",children:tn.map(g=>{const ee=g.icon;return a.jsxs("button",{type:"button",className:n===g.id?"is-active":"","data-testid":`ai-settings-tab-${g.id}`,onClick:()=>r(g.id),children:[a.jsx(ee,{size:15}),a.jsx("span",{children:g.label})]},g.id)})}),a.jsxs("main",{className:"ai-settings-main",children:[a.jsxs("header",{className:"ai-settings-head",children:[a.jsx("strong",{children:b.label}),a.jsx("button",{type:"button",title:"Close settings",onClick:o,children:a.jsx(Po,{size:16})})]}),a.jsxs("div",{className:"ai-settings-body","data-testid":"ai-settings-body",tabIndex:0,onKeyDown:ue,children:[n==="general"&&a.jsxs("div",{className:"settings-grid",children:[a.jsx(xt,{label:"Grid snap",description:"Align new movement to the canvas grid.",checked:e.gridSnap??!0,onChange:g=>E({gridSnap:g},"general.gridSnap")}),a.jsx(De,{label:"Grid type",description:"Background grid rendering mode.",value:e.gridType??"dot",options:["dot","line","particles","spirit"],onChange:g=>E({gridType:g},"general.gridType")}),a.jsx(De,{label:"Cursor position",description:"Where new nodes are placed by default.",value:e.cursorMode??"center",options:["center","lastNode"],onChange:g=>E({cursorMode:g},"general.cursorMode")}),a.jsx(De,{label:"Cursor direction",description:"Direction for sequential node placement.",value:e.cursorDirection,options:["right","down"],onChange:g=>E({cursorDirection:g},"general.cursorDirection")}),a.jsx(De,{label:"Camera trace mode",description:"Whether the camera follows new work.",value:e.cameraTraceMode??"none",options:["none","cursor"],onChange:g=>E({cameraTraceMode:g},"general.cameraTraceMode")}),a.jsx(De,{label:"Image load size",description:"Image nodes use fixed or original sizing.",value:e.imageLoadSize??"default",options:["default","original"],onChange:g=>E({imageLoadSize:g},"general.imageLoadSize")}),a.jsx($t,{label:"AI node width",description:"Default width for new AI task nodes.",value:e.aiNodeDefaultWidth??340,min:220,max:1200,onChange:g=>E({aiNodeDefaultWidth:g},"general.aiNodeDefaultWidth")}),a.jsx($t,{label:"AI node height",description:"Default height for new AI task nodes.",value:e.aiNodeDefaultHeight??196,min:120,max:900,onChange:g=>E({aiNodeDefaultHeight:g},"general.aiNodeDefaultHeight")}),a.jsx(xt,{label:"Show full AI response",description:"Allow AI result nodes to expand for long output.",checked:e.showFullAiResponse??!1,onChange:g=>E({showFullAiResponse:g},"general.showFullAiResponse")}),a.jsx(xt,{label:"Minimap",description:"Display a small navigation minimap in the bottom-right of the canvas.",checked:e.minimapEnabled??!1,onChange:g=>E({minimapEnabled:g},"general.minimapEnabled")}),a.jsx(xt,{label:"Mouse wheel mode",description:"Swap wheel zoom and scroll behavior.",checked:e.wheelMode,onChange:g=>E({wheelMode:g},"general.wheelMode")})]}),n==="language"&&a.jsx("div",{className:"settings-grid settings-grid--compact",children:a.jsx(De,{label:"App Language",description:`Controls the language preference passed into AI runs. ${M.description}`,value:M.code,options:Kt.map(g=>g.code),optionLabels:Z,testId:"app-language-select",onChange:g=>E({appLanguage:jt(g)},"language.appLanguage")})}),n==="connection"&&a.jsxs("div",{className:"settings-stack",children:[a.jsx("section",{className:"settings-radio-group","aria-label":"AI Provider",children:zl.map(g=>a.jsxs("label",{className:v===g?"is-selected":"",children:[a.jsx("input",{type:"radio",name:"ai-provider",checked:v===g,onChange:()=>E({aiProvider:g},"connection.provider")}),a.jsxs("span",{children:[a.jsx("strong",{children:g}),a.jsx("small",{children:cr(g)})]})]},g))}),a.jsx(Hl,{provider:v,datasetGeneratorCommand:V,copyState:s,onCommandTextAreaRef:l,onCopyDatasetGeneratorCommand:B}),a.jsxs("div",{className:"settings-grid settings-grid--compact",children:[a.jsx(De,{label:"Text model",description:Vl(x),value:x,options:k.map(g=>g.id),optionLabels:Object.fromEntries(k.map(g=>[g.id,`${Qa(g.provider)} · ${g.label}`])),onChange:g=>E({model:g},"connection.model")}),a.jsx(De,{label:"Reasoning effort",description:"Mapped to LocalBridge Codex reasoning effort.",value:e.effort,options:["Fast","Normal","Deep"],onChange:g=>E({effort:g},"connection.effort")}),(e.aiProvider??"OpenAI Codex")==="Local Ollama"&&a.jsx(Kl,{label:"Ollama URL",description:"Local Ollama endpoint.",value:e.ollamaEndpoint??"http://localhost:11434",onChange:g=>E({ollamaEndpoint:g},"connection.ollamaEndpoint")}),a.jsx(xt,{label:"ImageRouter mode",description:"Key material remains outside this React board snapshot.",checked:e.imageRouterEnabled??!1,onChange:g=>E({imageRouterEnabled:g},"connection.imageRouterEnabled")}),a.jsx(xt,{label:"Parallel insight bundles",description:"Preserves the original CodeMaster insight bundle switch.",checked:e.codeMasterInsightBundlesEnabled??!0,onChange:g=>E({codeMasterInsightBundlesEnabled:g},"connection.codeMasterInsightBundlesEnabled")}),a.jsx($t,{label:"Bundle timeout",description:"Per insight bundle timeout in milliseconds.",value:e.codeMasterInsightBundleTimeoutMs??18e3,min:5e3,max:6e4,onChange:g=>E({codeMasterInsightBundleTimeoutMs:g},"connection.codeMasterInsightBundleTimeoutMs")}),a.jsx($t,{label:"Retry Count (Std)",description:"Retries for lite and standard CodeMaster insight bundle calls.",value:e.codeMasterInsightBundleRetryCount??2,min:1,max:4,step:1,testId:"codemaster-insight-retry-std",onChange:g=>E({codeMasterInsightBundleRetryCount:g},"connection.codeMasterInsightBundleRetryCount")}),a.jsx($t,{label:"Retry Count (Deep)",description:"Retries for deep CodeMaster insight bundle calls.",value:e.codeMasterInsightBundleRetryCountDeep??3,min:1,max:5,step:1,testId:"codemaster-insight-retry-deep",onChange:g=>E({codeMasterInsightBundleRetryCountDeep:g},"connection.codeMasterInsightBundleRetryCountDeep")})]}),a.jsxs("div",{className:"settings-note",children:[a.jsx(ma,{size:15}),a.jsx("span",{children:"API keys are intentionally not stored in this React board. Live provider adapters must supply and verify secrets separately."})]})]}),n==="media"&&a.jsxs("div",{className:"settings-stack","data-testid":"ai-settings-media-tab",children:[a.jsx(Ta,{mode:"Image",icon:a.jsx(ja,{size:17}),selection:F,onModelChange:g=>pe("Image",g),onAspectChange:g=>Ce("Image",g)}),a.jsx(Ta,{mode:"Video",icon:a.jsx(Ii,{size:17}),selection:J,onModelChange:g=>pe("Video",g),onAspectChange:g=>Ce("Video",g)}),a.jsxs("div",{className:"settings-note",children:[a.jsx(ma,{size:15}),a.jsx("span",{children:"These are adapter hints only. Selecting a media model does not store an API key, invoke ImageRouter, or claim live generation availability."})]})]}),n==="agent"&&a.jsx("div",{className:"settings-grid settings-grid--compact",children:a.jsx(De,{label:"Direct instruction queue",description:"How selected agents receive direct instructions.",value:e.directInstructionQueueMode??"Append",options:["Append","Next","ReplacePending"],onChange:g=>E({directInstructionQueueMode:g},"agent.directInstructionQueueMode")})}),n==="system"&&a.jsxs("div",{className:"settings-grid settings-grid--compact",children:[a.jsx(De,{label:"Execution mode",description:"Concept parses IR locally; PureLLM is direct chat adapter mode.",value:e.executionMode??"Concept",options:["Concept","PureLLM"],onChange:g=>E({executionMode:g},"system.executionMode")}),a.jsxs("div",{className:"settings-note",children:[a.jsx(vi,{size:15}),a.jsx("span",{children:"Changing this setting affects the next run only. It does not claim a live agent has executed."})]})]}),n==="about"&&a.jsxs("div",{className:"settings-about",children:[a.jsx(Ci,{size:34}),a.jsx("strong",{children:"MindExec React"}),a.jsx("span",{children:"Fast local-first MindCanvas shell, rebuilt without Blazor in the render loop."}),a.jsx("small",{children:"AI settings parity slice"})]})]}),a.jsx("footer",{className:"ai-settings-footer",children:a.jsx("button",{type:"button","data-testid":"ai-settings-done",onClick:o,children:"Save"})})]})]})})}function ka(e,t){const o=ln(e,t),n=e==="Image"?t.imageRouterImageAspectPresetId:t.imageRouterVideoAspectPresetId,r=cn(e,o,n);return{model:o,aspect:r,aspectOptions:Za(o,e),requestedSize:dn(r)}}function Vl(e){const t=us(e);return t?`${Qa(t.provider)} text model used by bottom input and AI Task runs.`:"Custom text model id preserved with this board."}function cr(e){switch(e){case"Managed Cloud":return"Reserved for the hosted paid adapter.";case"BYOK":return"Use a separately configured user key.";case"Local Ollama":return"Local LLM server endpoint.";case"Gemini CLI":return"Hidden Gemini CLI compatibility path.";case"OpenAI Codex":default:return"LocalBridge Codex execution path."}}function ql(e){return["dotnet run --project MindExecution.Tools -c Debug -- --count 50 --out finetune_dataset.jsonl","--baseUrl https://openrouter.ai/api/v1",`--model "${(e.trim()||"openai/gpt-4o-mini").replace(/"/g,'\\"')}"`,'--key "OPENROUTER_API_KEY"',"--httpReferer http://localhost",'--xTitle "MindExec DatasetGenerator"'].join(" ")}function Wl(e){return!e||e.value.length===0?!1:(e.focus({preventScroll:!0}),e.select(),e.setSelectionRange(0,e.value.length),!0)}function Hl({provider:e,datasetGeneratorCommand:t,copyState:o,onCommandTextAreaRef:n,onCopyDatasetGeneratorCommand:r}){const s=e==="BYOK"?"BYOK Settings":e==="Local Ollama"?"Ollama Settings":e==="Managed Cloud"?"Managed Cloud":e==="Gemini CLI"?"Gemini CLI":"OpenAI Codex";return a.jsxs("section",{className:"settings-provider-card","data-testid":"ai-settings-provider-guidance","data-provider":e,children:[a.jsx("header",{children:a.jsxs("div",{children:[a.jsx("strong",{"data-testid":"ai-settings-provider-title",children:s}),a.jsx("span",{children:cr(e)})]})}),e==="Managed Cloud"&&a.jsx("div",{className:"settings-provider-card__notice",children:"Managed Cloud is coming soon in this build. Switch to BYOK, OpenAI Codex, or Local Ollama for local execution."}),e==="Gemini CLI"&&a.jsx("div",{className:"settings-provider-card__notice","data-testid":"ai-settings-gemini-hidden-provider",children:"Gemini CLI is hidden in this company build. Switch to BYOK, OpenAI Codex, or Local Ollama to manage connection settings here."}),e==="BYOK"&&a.jsxs("div",{className:"settings-provider-card__section",children:[a.jsx("p",{children:"API key material stays outside this React board. Configure the BYOK adapter or environment before running live OpenRouter calls."}),a.jsxs("div",{className:"settings-provider-card__command-head",children:[a.jsx("strong",{children:"DatasetGenerator Export"}),a.jsx("button",{type:"button","data-testid":"ai-settings-provider-copy-command","data-provider-copy-state":o,onClick:()=>void r(),children:o==="copied"?"Copied":o==="selected"?"Selected":o==="failed"?"Copy failed":"Copy command"})]}),a.jsx("textarea",{readOnly:!0,ref:n,value:t,"data-testid":"ai-settings-provider-dataset-command",className:"settings-provider-card__command","aria-label":"Redacted DatasetGenerator command"}),a.jsx("div",{className:"settings-provider-card__note",children:"This command is redacted; no API key is stored in the board. Replace OPENROUTER_API_KEY only in a trusted shell."})]}),e==="OpenAI Codex"&&a.jsxs("div",{className:"settings-provider-card__section",children:[a.jsx("strong",{children:"Connection Requirements"}),a.jsxs("ol",{children:[a.jsxs("li",{children:["Install MindExec LocalBridge dependencies: ",a.jsx("code",{children:"npm install"})]}),a.jsxs("li",{children:["Sign in once: ",a.jsx("code",{children:"codex login"})]}),a.jsx("li",{children:"Runtime: Codex SDK first, Legacy Exec fallback when SDK is unavailable."})]})]}),e==="Local Ollama"&&a.jsxs("div",{className:"settings-provider-card__section",children:[a.jsx("p",{children:"Ollama model selection is handled from the bottom AI input bar. Keep the local endpoint editable below."}),a.jsxs("div",{className:"settings-provider-card__note",children:["Requires ",a.jsx("code",{children:'OLLAMA_ORIGINS="*"'})," when running Ollama for browser access."]})]}),a.jsxs("div",{className:"settings-provider-card__section settings-provider-card__section--image",children:[a.jsx("strong",{children:"Image Generation"}),a.jsx("p",{children:"Text AI provider and image generation provider are configured separately. ImageRouter API key is adapter-owned and used only for image mode."}),a.jsx("span",{children:"ImageRouter API key: not stored in this React board."})]})]})}function Ta({mode:e,icon:t,selection:o,onModelChange:n,onAspectChange:r}){const s=Eo(e),c=Object.fromEntries(s.map(l=>[l.id,`${l.provider} · ${l.label}`])),m=Object.fromEntries(o.aspectOptions.map(l=>[l.id,`${l.label} · ${l.resolvedSize??"auto"}`]));return a.jsxs("section",{className:"settings-media-section","data-testid":`ai-settings-media-${e.toLowerCase()}`,children:[a.jsxs("header",{children:[a.jsx("span",{className:"settings-media-section__icon",children:t}),a.jsxs("span",{children:[a.jsxs("strong",{children:[e," defaults"]}),a.jsxs("small",{children:[o.model.provider," · ",o.requestedSize]})]})]}),a.jsxs("div",{className:"settings-grid settings-grid--compact",children:[a.jsx(De,{label:`${e} model`,description:"Shared with the bottom input model selector.",value:o.model.id,options:s.map(l=>l.id),optionLabels:c,testId:`ai-settings-${e.toLowerCase()}-model`,onChange:n}),a.jsx(De,{label:`${e} aspect`,description:o.aspect.note,value:o.aspect.id,options:o.aspectOptions.map(l=>l.id),optionLabels:m,testId:`ai-settings-${e.toLowerCase()}-aspect`,swatchClassName:vs(o.aspect.id),onChange:r})]})]})}function xt({label:e,description:t,checked:o,onChange:n}){return a.jsxs("label",{className:"setting-row setting-row--toggle",children:[a.jsxs("span",{children:[a.jsx("strong",{children:e}),a.jsx("small",{children:t})]}),a.jsx("input",{type:"checkbox",checked:o,onChange:r=>n(r.target.checked)})]})}function De({label:e,description:t,value:o,options:n,optionLabels:r,testId:s,swatchClassName:c,onChange:m}){return a.jsxs("label",{className:"setting-row",children:[a.jsxs("span",{children:[a.jsx("strong",{children:e}),a.jsx("small",{children:t})]}),a.jsxs("span",{className:"setting-row__select-wrap",children:[c&&a.jsx("span",{className:`aspect-select__swatch ${c}`}),a.jsx("select",{value:o,"data-testid":s,onChange:l=>m(l.target.value),children:n.map(l=>a.jsx("option",{value:l,children:(r==null?void 0:r[l])??l},l))})]})]})}function $t({label:e,description:t,value:o,min:n,max:r,step:s=1,testId:c,onChange:m}){return a.jsxs("label",{className:"setting-row",children:[a.jsxs("span",{children:[a.jsx("strong",{children:e}),a.jsx("small",{children:t})]}),a.jsx("input",{type:"number",min:n,max:r,step:s,"data-testid":c,value:o,onChange:l=>m($l(l.target.valueAsNumber,n,r))})]})}function Kl({label:e,description:t,value:o,onChange:n}){return a.jsxs("label",{className:"setting-row",children:[a.jsxs("span",{children:[a.jsx("strong",{children:e}),a.jsx("small",{children:t})]}),a.jsx("input",{type:"text",value:o,onChange:r=>n(r.target.value.slice(0,160))})]})}const Xl=1e3,Ia=1536*1024,Yl=3*1024*1024*3/4,Ql=24,Jl=.65,Zl=16,ec=.92;function wo(e){if(e.byteLength<5)return null;try{const o=new DataView(e).getUint32(0,!1);if(o<2||o>e.byteLength-4)return null;const n=new TextDecoder().decode(new Uint8Array(e,4,o));return{metadata:tc(JSON.parse(n)),payload:e.slice(4+o)}}catch{return null}}function tc(e){const t=oc(e)?e:{};return{type:Ne(t.type)||"remote.frame.binary",kind:Ne(t.kind)||"live",deviceId:Ne(t.deviceId),frameSeq:fe(t.frameSeq),streamId:Ne(t.streamId),width:fe(t.width),height:fe(t.height),mimeType:Ne(t.mimeType)||"image/jpeg",mode:Ne(t.mode),fps:fe(t.fps),capturedAt:Ne(t.capturedAt),receivedAt:Ne(t.receivedAt),byteLength:fe(t.byteLength),transport:Ne(t.transport),contentHash:Ne(t.contentHash),captureMs:fe(t.captureMs),sameContentStreak:fe(t.sameContentStreak),droppedByAgent:fe(t.droppedByAgent),dirtyRectCount:nc(t.dirtyRectCount??t.dirtyRects??t.dirtyRegionCount),dirtyPixelRatio:ur(t.dirtyPixelRatio??t.dirtyRatio??t.dirtyAreaRatio??t.changedPixelRatio),codec:Ne(t.codec??t.encoder??t.encoding),deltaEncoded:pr(t.deltaEncoded??t.isDeltaEncoded??t.deltaFrame)}}function dr(e,t=0){const o=fe(e.captureMs),n=Math.max(fe(e.byteLength),fe(t)),r=fe(e.sameContentStreak),s=fe(e.droppedByAgent),c=fe(e.dirtyRectCount),m=ur(e.dirtyPixelRatio),l=Ne(e.codec),b=pr(e.deltaEncoded),k={captureMs:o,byteLength:n,sameContentStreak:r,droppedByAgent:s,dirtyRectCount:c,dirtyPixelRatio:m,codec:l,deltaEncoded:b};return n>=Yl?{level:"oversized-frame",overBudget:!0,reason:"RemoteFast frame is near the agent binary frame ceiling.",...k}:o>=Xl?{level:"slow-capture",overBudget:!0,reason:"RemoteFast reported a slow screen capture.",...k}:m>=ec&&n>=Ia?{level:"inefficient-full-frame",overBudget:!0,reason:"RemoteFast dirty-region metadata shows a near-full-frame update with a large payload.",...k}:m>=Jl&&c>=Zl?{level:"dirty-region-heavy",overBudget:!0,reason:"RemoteFast dirty-region metadata shows many changed regions in one frame.",...k}:n>=Ia?{level:"large-frame",overBudget:!0,reason:"RemoteFast frame payload is large enough to create decode or transport pressure.",...k}:r>=Ql?{level:"stable-duplicate",overBudget:!1,reason:"RemoteFast reports repeated identical content that may be eligible for future delta or skip optimization.",...k}:{level:"nominal",overBudget:!1,reason:"",...k}}function oc(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function Ne(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):""}function fe(e){const t=Number(e);return Number.isFinite(t)&&t>=0?t:0}function nc(e){return Array.isArray(e)?e.length:Math.round(fe(e))}function ur(e){const t=fe(e);return t<=1?t:t<=100?t/100:1}function pr(e){return typeof e=="boolean"?e:typeof e=="number"?e>0:typeof e=="string"?/^(1|true|yes|on|delta)$/i.test(e.trim()):!1}function mr(e){const t=Xe(e.deviceId,256),o=ac({...e.input,controlLeaseId:e.input.controlLeaseId||e.controlLeaseId});return!t||!o.type?null:{type:"input",requestId:Xe(e.requestId,160),deviceId:t,ack:rc(o.type,e.ack),input:o}}function ac(e={}){const t=Number(e.normalizedX),o=Number(e.normalizedY),n=Number(e.deltaX),r=Number(e.deltaY);return{type:Xe(e.type,48),normalizedX:Number.isFinite(t)?lt(t,0,1):void 0,normalizedY:Number.isFinite(o)?lt(o,0,1):void 0,button:Xe(e.button,24),deltaX:Number.isFinite(n)?lt(n,-4096,4096):0,deltaY:Number.isFinite(r)?lt(r,-4096,4096):0,key:Xe(e.key,80),code:Xe(e.code,80),text:sc(e.text,256),repeat:e.repeat===!0,controlLeaseId:Xe(e.controlLeaseId,128),issuedAt:Xe(e.issuedAt,80)}}function rc(e,t){return t===!0||!/^pointermove$/i.test(String(e||"").trim())}function gr(e){let t;try{const n=typeof e=="string"?JSON.parse(e||"{}"):e;if(!hr(n))return null;t=n}catch{return null}const o=wt(t.type||t.Type);return o==="RemoteInputSocketReady"?{type:o,ok:!0,requestId:"",deviceId:"",inputType:"",commandId:"",error:""}:o!=="RemoteInputResult"&&o!=="RemoteInputError"?null:{type:o,ok:t.ok===!0||t.Ok===!0,requestId:wt(t.requestId||t.RequestId),deviceId:wt(t.deviceId||t.DeviceId),inputType:wt(t.inputType||t.InputType),commandId:wt(t.commandId||t.CommandId),error:wt(t.error||t.Error)}}function ic(e,t,o,n=!1){if(!va(t))return null;const r=va(o)?o:{left:0,top:0,width:t.width,height:t.height};let s=Number(e.clientX)-t.left-r.left,c=Number(e.clientY)-t.top-r.top;return!Number.isFinite(s)||!Number.isFinite(c)||(s<0||c<0||s>r.width||c>r.height)&&!n?null:(s=lt(s,0,r.width),c=lt(c,0,r.height),{normalizedX:lt(s/r.width,0,1),normalizedY:lt(c/r.height,0,1)})}function lt(e,t,o){return Math.max(t,Math.min(o,e))}function va(e){if(!hr(e))return!1;const t=Number(e.width),o=Number(e.height);return Number.isFinite(Number(e.left))&&Number.isFinite(Number(e.top))&&Number.isFinite(t)&&Number.isFinite(o)&&t>0&&o>0}function Xe(e,t){return String(e??"").replace(/\0/g,"").trim().slice(0,t)}function sc(e,t){return Xe(e,t)}function wt(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):""}function hr(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function lc(e,t){const o=Math.max(1,Math.floor(t.visibleBudget)),n=t.searchText.trim(),r=n.length>0||t.visibilityFilter!=="connected"||t.capabilityFilter!=="all",s=cc(e,t.visibilityFilter,n,t.capabilityFilter),c=dc(s,t.groupMode),m=c.length,l=Math.max(1,Math.ceil(Math.max(0,m)/o)),b=Number.isFinite(t.pageIndex)?Math.floor(t.pageIndex):0,k=Math.max(0,Math.min(b,l-1)),x=k*o,v=c.slice(x,x+o),V=v.map(ct).filter(Boolean),M=v.filter(E=>E.connected===!0).map(ct).filter(Boolean),F=new Set(v.map(E=>mn(E,t.groupMode))).size,J=c.filter(E=>E.connected===!0&&Ge(E,"taskDispatch")).map(ct).filter(Boolean),Z=c.filter(E=>E.connected===!0&&Ge(E,"taskDispatch")&&Ge(E,"aiAssist")).map(ct).filter(Boolean);return{filterActive:r,filteredDevices:s,projectedDevices:c,visibleDevices:v,visibleDeviceIds:V,visibleConnectedDeviceIds:M,frameSubscriptionDeviceIdSignature:M.join(","),visibleGroupCount:F,projectedCount:m,filteredCount:s.length,pageCount:l,pageIndex:k,pageStart:x,placeholderSlots:Math.max(0,o-v.length),taskDispatchDeviceIds:J,aiTaskDeviceIds:Z}}function cc(e,t,o,n){const r=o.trim().toLocaleLowerCase();return e.filter(s=>uc(s,t)&&pc(s,n)&&mc(s,r))}function dc(e,t){return[...e].sort((o,n)=>{const r=mn(o,t),s=mn(n,t);if(r!==s)return r.localeCompare(s);const c=gn(o).toLocaleLowerCase(),m=gn(n).toLocaleLowerCase();return c!==m?c.localeCompare(m):ct(o).localeCompare(ct(n))})}function mn(e,t){switch(t){case"activity":return br(e);case"platform":return fr(e).toLocaleLowerCase()||"unknown";case"capability":return yr(e);default:return e.connected===!0?"online":"offline"}}function ct(e){return String(e.deviceId||e.sessionId||e.deviceName||"").trim()}function gn(e){return String(e.deviceName||e.hostname||ct(e)||"Remote device").trim()}function fr(e){var t;return String(((t=e.status)==null?void 0:t.platform)||e.platform||"unknown").trim()}function Ge(e,t){var n;const o=(n=e.capabilities)==null?void 0:n[t];return typeof o=="boolean"?o:typeof o=="number"?o!==0:typeof o=="string"?/^(1|true|yes|on)$/i.test(o):!1}function uc(e,t){return t==="all"?!0:t==="offline"?e.connected!==!0:e.connected===!0}function pc(e,t){switch(t){case"control":return Ge(e,"control");case"task":return Ge(e,"taskDispatch");case"ai":return Ge(e,"aiAssist");default:return!0}}function mc(e,t){var n;return t?[ct(e),gn(e),fr(e),hn(e.arch),hn((n=e.latestTask)==null?void 0:n.status),br(e),yr(e),e.connected===!0?"online live connected":"offline disconnected"].join(" ").toLocaleLowerCase().includes(t):!0}function br(e){var o,n,r,s;const t=hn((o=e.latestTask)==null?void 0:o.status).toLocaleLowerCase();return t==="running"||t==="queued"?`task-${t}`:((n=e.activeLiveStream)==null?void 0:n.active)===!0?"live":Number(((r=e.counters)==null?void 0:r.liveFramesReceived)||0)>0?"live-recent":Number(((s=e.counters)==null?void 0:s.thumbnailFramesReceived)||0)>0?"thumbnail":e.lastStatusAt||e.lastSeenAt?"heartbeat":"idle"}function yr(e){return Ge(e,"aiAssist")?"ai-assist":Ge(e,"taskDispatch")?"task-dispatch":Ge(e,"control")?"control":Ge(e,"thumbnail")||Ge(e,"screen")?"screen":"view-only"}function hn(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):""}const Me=30,gc=1200,hc=4200,Ca=12,kr=8e3,fc=1.5,Tr=42,xa="mindexec:remote-monitor-input-smoke",on="connected-screen-wall",fn=90,Ir=240,vr=1e4,Vt=6e4,fo=25e3,bc=250,Io=2e3,Rt=60,wa=2,yc=96,kc=58,qt=[1,1.5,2.25,3.375],Sa=1,Tc=5,Ic=72,vc=96,Ra="240px",bn="MindExec.RemoteFleet.AutoHost",yn="MindExec.RemoteFleet.AutoHostNodeId",Cr=["status","activity","platform","capability"],xr=["connected","all","offline"],wr=["all","control","task","ai"],Mt=new Map,Zt=new WeakMap;function Ma(e,t=0){if(typeof window>"u")return!0;const o=window.innerWidth||document.documentElement.clientWidth||0,n=window.innerHeight||document.documentElement.clientHeight||0;return o<=0||n<=0?!0:e.right>=-t&&e.bottom>=-t&&e.left<=o+t&&e.top<=n+t}function Sr(e,t,o){const[n,r]=p.useState(()=>typeof document>"u"?!0:document.visibilityState==="visible"),[s,c]=p.useState(!0),m=p.useRef(null);p.useEffect(()=>{if(typeof document>"u")return;const b=()=>r(document.visibilityState==="visible");return b(),document.addEventListener("visibilitychange",b),()=>document.removeEventListener("visibilitychange",b)},[]),p.useEffect(()=>{const b=e.current;if(!b||typeof IntersectionObserver>"u"){c(!0);return}const k=new IntersectionObserver(x=>{const v=x[0],V=!!(v!=null&&v.isIntersecting||((v==null?void 0:v.intersectionRatio)??0)>0),M=Ma(v?v.boundingClientRect:b.getBoundingClientRect(),240);c(V||M)},{root:null,rootMargin:Ra,threshold:0});return k.observe(b),()=>k.disconnect()},[e]);const l=n&&s;return p.useEffect(()=>{if(m.current===l)return;m.current=l;const b={nodeId:t,visible:l,pageVisible:n,viewportVisible:s,rootMargin:Ra};o==="monitor"?h.emit("remoteMonitor.node.transportVisibility",b):h.emit("remoteControl.node.transportVisibility",b)},[t,n,o,s,l]),l}function uu({node:e,onPatch:t,onCreateRemoteControl:o}){var Zn,ea,ta,oa,na,aa,ra,ia,sa,la,ca,da;const n=kn((Zn=e.metadata)==null?void 0:Zn.RemoteTotal,Me),r=kn((ea=e.metadata)==null?void 0:ea.RemoteConnected,0),s=p.useRef(null),c=p.useRef(null),m=Sr(s,e.id,"monitor"),[l,b]=p.useState(()=>({source:Pt()?"loading":"blocked",loading:!1,message:Pt()?"RemoteHub not checked yet.":"Hosted LocalBridge access is gated.",baseUrl:j(),devices:bo(n,r)})),k=p.useRef(new Map),x=p.useRef(new Set),v=p.useRef(new Map),V=p.useRef(new Map),M=p.useRef(new Map),F=p.useRef(null),J=p.useRef(0),Z=p.useRef(0),E=p.useRef(0),ue=p.useRef(!1),B=p.useRef(0),pe=p.useRef(0),Ce=p.useRef(!1),g=p.useRef(!1),ee=p.useRef(!1),L=p.useRef(""),Y=p.useRef(0),Oe=p.useRef(""),W=p.useRef(null),Pe=p.useRef(!1),_e=p.useRef(0),be=p.useRef(0),A=p.useRef(e.metadata??{}),[xe,Fe]=p.useState(""),[S,Q]=p.useState(!1),[te,ne]=p.useState("locked"),[Nt,ae]=p.useState("Remote input locked."),[_o,we]=p.useState(""),[Se,mt]=p.useState(""),[Dt,de]=p.useState(""),[Re,eo]=p.useState(""),[Je,to]=p.useState(""),[Fo,Ue]=p.useState(""),[kt,Ze]=p.useState(0),[He,Bo]=p.useState(Sa),[ze,oo]=p.useState("status"),[Ot,no]=p.useState(""),[Ae,ao]=p.useState("connected"),[Ee,ro]=p.useState("all"),[me,gt]=p.useState(()=>nn(e.id)),et=l.source==="bridge"?l.devices.length:l.devices.length||n,y=Ot.trim(),I=p.useMemo(()=>lc(l.devices,{groupMode:ze,visibilityFilter:Ae,searchText:y,capabilityFilter:Ee,pageIndex:kt,visibleBudget:Me}),[Ee,ze,kt,y,l.devices,Ae]),N=I.filterActive,U=I.filteredDevices,z=I.projectedDevices,O=I.projectedCount,P=I.pageCount,_=I.pageIndex,X=I.pageStart,ge=I.visibleDevices,tt=I.visibleDeviceIds,$e=I.visibleConnectedDeviceIds,ot=I.frameSubscriptionDeviceIdSignature,Fn=I.visibleGroupCount,Ur=I.placeholderSlots,Go=`${_+1}/${P}`,Bn=P<=1?100:Math.max(12,100/P),zr=P<=1?0:_/Math.max(1,P-1)*(100-Bn),_t=qt[He]??qt[Sa],Gn=Math.round(yc*_t),Un=Math.round(kc*_t),oe=p.useMemo(()=>ge.find(i=>it(i)===xe)||ge.find(i=>i.connected===!0)||ge[0],[xe,ge]),H=oe?it(oe):"",Ft=l.devices.filter(i=>i.connected===!0).length,Uo=l.devices.reduce((i,d)=>{var u;return i+Number(((u=d.counters)==null?void 0:u.tasksQueued)||0)},0),io=I.taskDispatchDeviceIds,so=I.aiTaskDeviceIds,zo=io.length,Bt=so.length,$o=l.source==="bridge"?(ta=l.hub)!=null&&ta.started?"Online":((oa=l.hub)==null?void 0:oa.enabled)===!1?"Off":"Ready":l.source==="blocked"?"Gated":l.source,lo=l.source==="bridge"?"Local":l.source==="blocked"?"Gated":"Preview",Vo=Ua((na=l.bridge)==null?void 0:na.status),qo=za((aa=l.bridge)==null?void 0:aa.status),zn=l.source==="bridge"&&!!qo,$n=oe?ce(oe,"control"):!1,Wo=oe?ce(oe,"taskDispatch"):!1,nt=p.useMemo(()=>oe?l.source!=="bridge"?"LocalBridge is not connected.":zn?oe.connected!==!0?"Selected device is offline.":$n?"":"RemoteAgent control capability is disabled.":"Remote input adapter is unavailable.":"No screen selected.",[zn,$n,oe,l.source]),Le=nt==="",Ho=S?Er(te):Le?"Locked":"Off",ie=l.source==="bridge"&&((ra=l.hub)==null?void 0:ra.hostTargetActive)===!0&&l.hub.hostTargetNodeId===e.id,re=p.useMemo(()=>wc(l.hub,ie),[ie,l.hub]),Gt=jc(l.agent,l.source),co=Nr(l.agent),Ko=Dr(l.agent),Ut=p.useMemo(()=>Ac(l.hub,e.id),[e.id,l.hub]),uo=Nc({source:l.source,hasAuth:!!l.auth,isHostActiveForNode:ie,request:Ut,busy:Se}),po=uo==="",mo=l.source==="bridge"&&!!l.auth&&co&&!Se,Vn=l.source==="bridge"&&!!H&&(oe==null?void 0:oe.connected)===!0&&Wo&&!!Re.trim()&&!Je,qn=l.source==="bridge"&&zo>0&&!!Re.trim()&&!Je,Wn=l.source==="bridge"&&Bt>0&&!!Re.trim()&&!Je,$r=Fo||Dt||_o||(l.source==="bridge"&&oe?`${ft(oe)}: ${Nt}`:l.message),Hn=p.useMemo(()=>Mc(l.latestTaskBatch,l.recentTaskBatches),[l.latestTaskBatch,l.recentTaskBatches]),ke=Pc(Hn),ht=l.source==="bridge"&&!!(Hn&&ke);p.useEffect(()=>{A.current=e.metadata??{}},[e.metadata]);const Kn=p.useCallback((i,d)=>{const u=A.current??{},f=Object.entries(d).filter(([C,R])=>u[C]!==R).map(([C])=>C);if(f.length===0)return;const T={...u,...d};A.current=T,t(e.id,{metadata:T}),h.emit("remoteMonitor.node.metadata.patch",{nodeId:e.id,reason:i,keys:f})},[e.id,t]);p.useEffect(()=>{l.loading||Kn("snapshot",xc({source:l.source,hub:l.hub,baseUrl:l.baseUrl,hubLabel:$o,routeLabel:lo,connected:Ft,total:et,taskCount:Uo,taskDispatchCount:zo,aiCount:Bt,pageLabel:Go,pageStart:X,pageIndex:_,pageCount:P,projectionMode:on,projectedCount:O,visibleBudget:Me,selectedDeviceId:H,inputLabel:Ho,devices:l.devices,latestTaskBatch:l.latestTaskBatch,recentTaskBatches:l.recentTaskBatches,taskFollowActive:ht,taskFollowKey:ke,isHostActiveForNode:ie,registryRouteInfo:re,hostTargetRenewMs:ie?fo:0,autoHostEnabled:me,agent:l.agent,agentStatusLabel:Gt,agentRunning:co,agentReady:Ko,message:l.message}))},[Bt,me,_,Ft,Ko,co,Gt,$o,Ho,ie,P,Go,X,Kn,O,re,lo,H,l.agent,l.baseUrl,l.devices,l.hub,l.latestTaskBatch,l.loading,l.message,l.recentTaskBatches,l.source,ht,ke,Uo,zo,et]),p.useEffect(()=>{kt!==_&&Ze(_)},[_,kt]),p.useEffect(()=>{const i=new Set(tt);for(const d of k.current.keys())i.has(d)||k.current.delete(d)},[tt]),p.useEffect(()=>{h.emit("remoteMonitor.node.frameSubscription",{nodeId:e.id,deviceCount:m?$e.length:0,visibleDeviceCount:$e.length,transportVisible:m,pageIndex:_,pageStart:X,visibleBudget:Me,transportKey:ot})},[_,e.id,X,m,$e.length,ot]),p.useEffect(()=>{if(l.source!=="bridge")return;const i=[re.status,re.reason,re.accountRouteReady?"ready":"local",re.migrationBlocked?"migration":"",ie?"hosting":"inactive"].join("|");Oe.current!==i&&(Oe.current=i,h.emit("remoteMonitor.node.registryRoute",{nodeId:e.id,status:re.status,reason:re.reason,accountRouteReady:re.accountRouteReady,migrationBlocked:re.migrationBlocked,hostTargetActive:ie}))},[ie,e.id,re,l.source]),p.useEffect(()=>{gt(nn(e.id))},[e.id]);const Tt=p.useCallback((i,d)=>{Ze(u=>{const f=Math.max(0,Math.min(P-1,u+i));return f!==u&&h.emit("remoteMonitor.node.page",{nodeId:e.id,from:u,to:f,pageCount:P,visibleBudget:Me,source:d}),f})},[e.id,P]),Xn=p.useCallback((i,d)=>{i.stopPropagation(),Tt(d,"button")},[Tt]),Yn=p.useCallback((i,d)=>{i.preventDefault(),i.stopPropagation(),Bo(u=>{const f=Math.max(0,Math.min(qt.length-1,u+d));return f!==u&&h.emit("remoteMonitor.node.tileScale",{nodeId:e.id,from:u,to:f,scale:qt[f],visibleBudget:Me}),f})},[e.id]);p.useEffect(()=>{var i;(i=c.current)==null||i.scrollTo({left:0,top:0,behavior:"auto"}),_e.current=0},[_,He,ot]);const at=p.useCallback(i=>{if(i instanceof HTMLElement){const d=i.closest('[data-testid="remote-monitor-node-wall"]');if(d instanceof HTMLDivElement)return d}return c.current},[]),Qn=p.useCallback(i=>i.scrollWidth>i.clientWidth+1||i.scrollHeight>i.clientHeight+1,[]),Xo=p.useCallback(i=>{if(i.button!==0&&i.button!==1)return;const d=i.target instanceof HTMLElement?i.target:null;if(d!=null&&d.closest('button,input,textarea,select,[contenteditable="true"],[contenteditable=""]'))return;const u=at(i.target);if(u){W.current={active:!0,pointerId:i.pointerId,startX:i.clientX,startY:i.clientY,lastX:i.clientX,lastY:i.clientY,scrollLeft:u.scrollLeft,scrollTop:u.scrollTop,didPan:!1,pageTriggered:!1},i.preventDefault(),i.stopPropagation();try{i.currentTarget.setPointerCapture(i.pointerId)}catch{}}},[at]),Yo=p.useCallback(i=>{const d=W.current;if(!(d!=null&&d.active)||d.pointerId!==i.pointerId)return;const u=at(i.target);if(!u)return;const f=i.clientX-d.startX,T=i.clientY-d.startY;if(!d.didPan&&Math.max(Math.abs(f),Math.abs(T))>=Tc&&(d.didPan=!0,Pe.current=!0),d.didPan){u.scrollLeft=d.scrollLeft-f,u.scrollTop=d.scrollTop-T;const C=Math.abs(T)>=Math.abs(f)?T:f;!d.pageTriggered&&P>1&&!Qn(u)&&Math.abs(C)>=Ic&&(d.pageTriggered=!0,Tt(C<0?1:-1,"drag"))}d.lastX=i.clientX,d.lastY=i.clientY,i.preventDefault(),i.stopPropagation()},[Qn,Tt,at,P]),It=p.useCallback(i=>{const d=W.current;if(!(!(d!=null&&d.active)||d.pointerId!==i.pointerId)){W.current=null;try{i.currentTarget.releasePointerCapture(i.pointerId)}catch{}if(d.didPan){const u=at(i.target);h.emit("remoteMonitor.node.wallPan",{nodeId:e.id,source:"drag",dx:Math.round(d.lastX-d.startX),dy:Math.round(d.lastY-d.startY),scrollLeft:Math.round((u==null?void 0:u.scrollLeft)??0),scrollTop:Math.round((u==null?void 0:u.scrollTop)??0),pageIndex:_,pageCount:P}),i.preventDefault(),i.stopPropagation()}}},[_,at,e.id,P]),Vr=p.useCallback(i=>{const d=i.target instanceof HTMLElement?i.target:null;if(d!=null&&d.closest('[data-input-active="true"]'))return;const u=at(i.target);if(!u)return;const f=u.scrollLeft,T=u.scrollTop;u.scrollLeft+=i.deltaX,u.scrollTop+=i.deltaY;const C=u.scrollLeft!==f||u.scrollTop!==T;!C&&P>1&&Math.abs(i.deltaY)>=Math.abs(i.deltaX)&&(_e.current+=i.deltaY,Math.abs(_e.current)>=vc&&(Tt(_e.current>0?1:-1,"wheel"),_e.current=0)),h.emit("remoteMonitor.node.wallPan",{nodeId:e.id,source:"wheel",dx:Math.round(i.deltaX),dy:Math.round(i.deltaY),moved:C,scrollLeft:Math.round(u.scrollLeft),scrollTop:Math.round(u.scrollTop),pageIndex:_,pageCount:P}),i.preventDefault(),i.stopPropagation()},[Tt,_,at,e.id,P]),qr=p.useCallback(i=>{i.stopPropagation();const d=Dc(i.target.value);oo(u=>u===d?u:(h.emit("remoteMonitor.node.groupMode",{nodeId:e.id,from:u,to:d,projectedCount:z.length,visibleBudget:Me}),d)),Ze(0)},[z.length,e.id]),Wr=p.useCallback(i=>{i.stopPropagation();const d=i.target.value.slice(0,64);no(u=>u===d?u:(h.emit("remoteMonitor.node.filter",{nodeId:e.id,reason:"search",searchText:d.trim(),visibilityFilter:Ae,capabilityFilter:Ee,projectedCount:z.length,visibleBudget:Me}),d)),Ze(0)},[Ee,z.length,e.id,Ae]),Hr=p.useCallback(i=>{i.stopPropagation();const d=Oc(i.target.value);ao(u=>u===d?u:(h.emit("remoteMonitor.node.filter",{nodeId:e.id,reason:"visibility",searchText:y,from:u,to:d,visibilityFilter:d,capabilityFilter:Ee,projectedCount:z.length,visibleBudget:Me}),d)),Ze(0)},[Ee,z.length,e.id,y]),Kr=p.useCallback(i=>{i.stopPropagation();const d=_c(i.target.value);ro(u=>u===d?u:(h.emit("remoteMonitor.node.filter",{nodeId:e.id,reason:"capability",searchText:y,visibilityFilter:Ae,from:u,to:d,capabilityFilter:d,projectedCount:z.length,visibleBudget:Me}),d)),Ze(0)},[z.length,e.id,y,Ae]),Xr=p.useCallback((i,d)=>{i.stopPropagation();const u=it(d);if(!u||!o)return;const f=Wt(d);o({sourceNodeId:e.id,deviceId:u,deviceName:ft(d),platform:Xt(d),connected:d.connected===!0,baseUrl:l.baseUrl,framePath:f==null?void 0:f.framePath,frameUrl:f==null?void 0:f.frameUrl,dataUrl:f==null?void 0:f.dataUrl,frameSeq:f==null?void 0:f.frameSeq}),h.emit("remoteMonitor.node.controlNode.create",{nodeId:e.id,deviceId:u,source:l.source})},[e.id,o,l.baseUrl,l.source]),se=p.useCallback(async(i="manual")=>{const d=++be.current,u=j();if(b(f=>({...f,loading:!0,baseUrl:u})),!Pt()){const f=bo(n,r);b({source:"blocked",loading:!1,message:"Hosted LocalBridge access is gated.",baseUrl:u,devices:f}),h.emit("remoteMonitor.node.preview",{nodeId:e.id,reason:"hosted-localbridge-gated",total:f.length});return}try{const f=await In(u);if(d!==be.current)return;if(f.state!=="connected"){const Te=bo(n,r);b({source:"unavailable",loading:!1,message:f.message||"LocalBridge is unavailable.",baseUrl:u,bridge:f,devices:Te}),h.emit("remoteMonitor.node.preview",{nodeId:e.id,reason:"localbridge-unavailable",total:Te.length});return}const T=Wa(f.status),C=os(T,u).catch(Te=>{h.emit("remoteMonitor.node.agent.status",{nodeId:e.id,reason:i,ok:!1,error:Te instanceof Error?Te.message:String(Te)})}),[R,$,G]=await Promise.all([Ha(T,u),Ka(T,u,{includeDataUrl:!1}),C]);if(d!==be.current)return;const he=Array.isArray($.devices)?$.devices:[];b({source:"bridge",loading:!1,message:R.started?"RemoteHub online.":R.enabled===!1?R.lastError||"RemoteHub adapter is not configured.":"RemoteHub available.",baseUrl:u,bridge:f,auth:T,hub:R,agent:G,latestTaskBatch:$.latestTaskBatch,recentTaskBatches:Array.isArray($.recentTaskBatches)?$.recentTaskBatches:[],devices:he}),h.emit("remoteMonitor.node.refresh",{nodeId:e.id,reason:i,total:$.total??he.length,connected:he.filter(Te=>Te.connected===!0).length,agentStatus:w(G==null?void 0:G.status),agentRunning:(G==null?void 0:G.running)===!0}),G&&h.emit("remoteMonitor.node.agent.status",{nodeId:e.id,reason:i,ok:!0,status:w(G.status),running:G.running===!0,ready:G.ready===!0})}catch(f){if(d!==be.current)return;const T=bo(n,r);b({source:"unavailable",loading:!1,message:f instanceof Error?f.message:String(f),baseUrl:u,devices:T}),h.emit("remoteMonitor.node.preview",{nodeId:e.id,reason:"remotehub-error",total:T.length})}},[r,n,e.id]);p.useEffect(()=>{se("mount")},[se]);const zt=p.useCallback((i,d,u)=>{const f=Br(M.current,i);if(!f)return!1;const{cached:T,scope:C}=f;return Ro(d,T,x.current,v.current).then(R=>{R&&h.emit("remoteMonitor.node.frameCache",{nodeId:e.id,deviceId:i,frameSeq:pt(T.metadata),scope:C,reason:u})}),!0},[e.id]),Yr=p.useCallback((i,d)=>{i&&(d?(k.current.set(i,d),zt(i,d,"canvas-attach")):k.current.delete(i))},[zt]);p.useEffect(()=>{for(const i of ge){const d=it(i),u=k.current.get(d);if(!u)continue;const f=Wt(i),T=Nn(f);l.source==="bridge"&&T?Tn(u,d,f,l.baseUrl,x.current,v.current,M.current).then(C=>{C.painted||C.busy||(C.staleDropped&&h.emit("remoteMonitor.node.frameStaleDropped",{nodeId:e.id,deviceId:d,frameSeq:C.frameSeq,previous:C.previous,source:"projection"}),!(l.source==="bridge"&&zt(d,u,"projection-rerender"))&&Mo(u,i,l.source))}):l.source==="bridge"&&zt(d,u,"projection-rerender")||Mo(u,i,l.source)}},[e.id,zt,l.baseUrl,l.source,ge]);const Qo=p.useCallback(async(i,d)=>{const u=w(i.deviceId).trim();if(!u)return;const f=w(i.streamId).trim(),T=Number(i.frameSeq||0)||0,C=Dn(v.current,M.current,u),R=V.current.get(u)||"",$=!!(f&&R&&f!==R);if($&&(v.current.delete(u),h.emit("remoteMonitor.node.frameStreamReset",{nodeId:e.id,deviceId:u,fromStreamId:R,toStreamId:f,previous:C,frameSeq:T})),!$&&T>0&&T<=C){h.emit("remoteMonitor.node.frameStaleDropped",{nodeId:e.id,deviceId:u,frameSeq:T,previous:C,source:"ws"});return}const G=dr(i,d.byteLength);G.level!=="nominal"&&h.emit("remoteMonitor.node.framePressure",{nodeId:e.id,deviceId:u,frameSeq:T,streamId:f,...G});const he=_r(M.current,u,i,d),Te=k.current.get(u);if(Te){if(x.current.has(u)){h.emit("remoteMonitor.node.frameCache",{nodeId:e.id,deviceId:u,frameSeq:T,scope:"local",reason:"decode-pending"});return}x.current.add(u);try{await On(Te,he.metadata,he.payload)&&(T>0&&v.current.set(u,T),f&&V.current.set(u,f),E.current+=1,E.current%12===1&&h.emit("remoteMonitor.node.framePainted",{nodeId:e.id,deviceId:u,frameSeq:T,streamId:i.streamId||"",painted:E.current,source:"ws"}))}catch{}finally{x.current.delete(u);const je=M.current.get(u),Ke=pt(je==null?void 0:je.metadata),ua=v.current.get(u)||0,pa=k.current.get(u);je&&pa&&(Ke<=0?ua<=0:Ke>ua)&&Ro(pa,je,x.current,v.current).then(gi=>{gi&&(E.current+=1,h.emit("remoteMonitor.node.frameCache",{nodeId:e.id,deviceId:u,frameSeq:Ke,scope:"local",reason:"latest-pending"}),h.emit("remoteMonitor.node.framePainted",{nodeId:e.id,deviceId:u,frameSeq:Ke,streamId:je.metadata.streamId||"",painted:E.current,source:"ws-cache"}))})}}},[e.id]);p.useEffect(()=>{if(l.source!=="bridge"||!m||!Vo)return;const i=Pa(ot);if(i.length===0)return;let d=!1,u=null,f=0;const T=()=>{var C,R;if(!d){ue.current=!1;try{u=new WebSocket(Ar(l.baseUrl,Vo,(R=(C=l.bridge)==null?void 0:C.status)==null?void 0:R.bridgeToken,i)),u.binaryType="arraybuffer"}catch($){h.emit("remoteMonitor.node.frameWs",{nodeId:e.id,ok:!1,error:$ instanceof Error?$.message:String($)});return}u.onopen=()=>{ue.current=!0,B.current=performance.now(),h.emit("remoteMonitor.node.frameWs",{nodeId:e.id,ok:!0,deviceCount:i.length,fps:Ca}),u==null||u.send(JSON.stringify({type:"subscribe",deviceIds:i,autoStartLive:!0,fps:Ca,maxWidth:640,maxHeight:360,quality:55,mode:"remote-fast"}))},u.onmessage=async $=>{if(!d){if(B.current=performance.now(),$.data instanceof ArrayBuffer){const G=wo($.data);G&&await Qo(G.metadata,G.payload);return}if($.data instanceof Blob){const G=wo(await $.data.arrayBuffer());G&&await Qo(G.metadata,G.payload)}}},u.onerror=()=>{h.emit("remoteMonitor.node.frameWs",{nodeId:e.id,ok:!1,reason:"socket-error"})},u.onclose=()=>{ue.current=!1,d||(f=window.setTimeout(T,1500))}}};return T(),()=>{d=!0,ue.current=!1,window.clearTimeout(f),u==null||u.close()}},[e.id,Qo,Vo,l.baseUrl,(sa=(ia=l.bridge)==null?void 0:ia.status)==null?void 0:sa.bridgeToken,l.source,m,ot]),p.useEffect(()=>{if(l.source!=="bridge"||!m)return;const i=Pa(ot);if(i.length===0)return;let d=!1,u=!1;const f=async()=>{var R;if(!(d||u)&&!(ue.current&&performance.now()-B.current<kr)){u=!0;try{const $=await Xa(i,l.auth,l.baseUrl);if(d||$.ok===!1)return;let G=0,he=0;for(const Te of $.frames||[]){const je=String(Te.deviceId||"").trim();if(!je)continue;const Ke=await Tn(k.current.get(je),je,Or(Te),l.baseUrl,x.current,v.current,M.current);Ke.painted&&(G+=1),Ke.staleDropped&&(he+=1,h.emit("remoteMonitor.node.frameStaleDropped",{nodeId:e.id,deviceId:je,frameSeq:Ke.frameSeq,previous:Ke.previous,source:"snapshot"}))}h.emit("remoteMonitor.node.frameSnapshot",{nodeId:e.id,deviceCount:i.length,frameCount:((R=$.frames)==null?void 0:R.length)||0,painted:G,staleDropped:he})}catch{}finally{u=!1}}},T=window.setTimeout(f,200),C=window.setInterval(f,hc);return()=>{d=!0,window.clearTimeout(T),window.clearInterval(C)}},[e.id,l.auth,l.baseUrl,l.source,m,ot]),p.useEffect(()=>{Q(!1),ne("locked"),ae("Remote input locked.")},[H,l.source]),p.useEffect(()=>{!S||Le||(Q(!1),ne("unavailable"),ae(nt||"Remote input unavailable."),h.emit("remoteMonitor.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"control-unavailable",deviceId:H}))},[Le,nt,S,e.id,H]),p.useEffect(()=>{var u,f,T;if(!S){(u=F.current)==null||u.close(),F.current=null,ne("locked");return}if(!Le||!H){ne("unavailable"),ae(nt||"Remote input unavailable.");return}let i=!1,d=null;ne("connecting"),ae("Connecting remote input adapter...");try{d=new WebSocket(Mr(l.baseUrl,qo,(T=(f=l.bridge)==null?void 0:f.status)==null?void 0:T.bridgeToken)),F.current=d}catch(C){const R=C instanceof Error?C.message:String(C);ne("error"),ae(R),h.emit("remoteMonitor.node.input.ws",{nodeId:e.id,ok:!1,deviceId:H,error:R});return}return d.onopen=()=>{i||(ne("ready"),ae("Remote input ready."),h.emit("remoteMonitor.node.input.ws",{nodeId:e.id,ok:!0,deviceId:H}))},d.onmessage=C=>{if(i)return;const R=gr(String(C.data||"{}"));if(R){if(R.type==="RemoteInputSocketReady"){ne("ready");return}h.emit("remoteMonitor.node.input.result",{nodeId:e.id,ok:R.ok,deviceId:R.deviceId||H,inputType:R.inputType,error:R.error}),!R.ok||R.error?ae(R.error||"Remote input failed."):/^pointermove$/i.test(R.inputType)||ae(`${R.inputType||"Input"} queued.`)}},d.onerror=()=>{i||(ne("error"),ae("Remote input socket error."),h.emit("remoteMonitor.node.input.ws",{nodeId:e.id,ok:!1,deviceId:H,reason:"socket-error"}))},d.onclose=()=>{i||(F.current=null,ne("error"),ae("Remote input socket closed."),h.emit("remoteMonitor.node.input.ws",{nodeId:e.id,ok:!1,deviceId:H,reason:"socket-closed"}))},()=>{i=!0,F.current===d&&(F.current=null),d==null||d.close()}},[Le,nt,S,e.id,qo,H,l.baseUrl,(ca=(la=l.bridge)==null?void 0:la.status)==null?void 0:ca.bridgeToken]),p.useEffect(()=>{if(!S)return;const i=d=>{d.key==="Escape"&&(d.preventDefault(),Q(!1),ae("Remote input locked."),h.emit("remoteMonitor.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"escape",deviceId:H}))};return window.addEventListener("keydown",i,!0),()=>window.removeEventListener("keydown",i,!0)},[S,e.id,H]);const Qr=p.useCallback(i=>{i.stopPropagation(),qa(!0),h.emit("remoteMonitor.node.hostedAccess.enabled",{nodeId:e.id}),se("hosted-access-enabled")},[e.id,se]),Jn=p.useCallback(i=>{i.stopPropagation(),se("manual")},[se]),Jr=p.useCallback(async i=>{var d,u,f;if(i.stopPropagation(),!po){de(uo||"RemoteAgent connect unavailable.");return}mt("connect"),de("Connecting RemoteAgent...");try{const T=await ns(Ut,l.auth,l.baseUrl);T.agent&&b(R=>R.source==="bridge"?{...R,agent:T.agent,message:R.message}:R);const C=T.ok===!0;de(C?T.alreadyRunning===!0?"RemoteAgent already running.":T.skipped===!0?T.reason||"RemoteAgent connect skipped.":"RemoteAgent connect requested.":T.error||"RemoteAgent connect failed."),h.emit("remoteMonitor.node.agent.connect",{nodeId:e.id,ok:C,alreadyRunning:T.alreadyRunning===!0,skipped:T.skipped===!0,reason:T.reason||"",status:w((d=T.agent)==null?void 0:d.status),managerCount:((u=Ut.managerCandidates)==null?void 0:u.length)??0,error:T.error||""}),C&&await se("agent-connect")}catch(T){const C=T instanceof Error?T.message:String(T);de(C),h.emit("remoteMonitor.node.agent.connect",{nodeId:e.id,ok:!1,managerCount:((f=Ut.managerCandidates)==null?void 0:f.length)??0,error:C})}finally{mt("")}},[po,e.id,se,uo,Ut,l.auth,l.baseUrl]),Zr=p.useCallback(async i=>{var d;if(i.stopPropagation(),!mo){de("RemoteAgent is not running.");return}mt("disconnect"),de("Stopping RemoteAgent...");try{const u=await as("react-remote-monitor-manual",l.auth,l.baseUrl);u.agent&&b(T=>T.source==="bridge"?{...T,agent:u.agent,message:T.message}:T);const f=u.ok===!0;de(f?"RemoteAgent stopped.":u.error||"RemoteAgent stop failed."),h.emit("remoteMonitor.node.agent.disconnect",{nodeId:e.id,ok:f,status:w((d=u.agent)==null?void 0:d.status),error:u.error||""}),f&&await se("agent-disconnect")}catch(u){const f=u instanceof Error?u.message:String(u);de(f),h.emit("remoteMonitor.node.agent.disconnect",{nodeId:e.id,ok:!1,error:f})}finally{mt("")}},[mo,e.id,se,l.auth,l.baseUrl]),ei=p.useCallback(async i=>{var u;i.stopPropagation();const d=jr(l.hub);try{const f=await An(d);we("Connect command copied."),h.emit("remoteMonitor.node.connectCommand.copy",{nodeId:e.id,ok:!0,method:f,source:l.source,hasPairPreview:!!((u=l.hub)!=null&&u.pairTokenPreview)})}catch(f){we(f instanceof Error?f.message:"Clipboard is unavailable."),h.emit("remoteMonitor.node.connectCommand.copy",{nodeId:e.id,ok:!1})}},[e.id,l.hub,l.source]),vt=p.useCallback(async(i,d)=>{if(l.source!=="bridge"||Ce.current)return!1;Ce.current=!0,we(i?"Requesting host target...":"Clearing host target...");try{const u=await ga(e.id,i,l.auth,l.baseUrl,{leaseMs:Vt});if(u.ok===!0){const f=i&&u.active===!0;Aa(e.id,f),gt(f)}return we(u.ok===!0?u.active?"This monitor node is the host target.":"Host target cleared.":u.error||"Host target update failed."),h.emit("remoteMonitor.node.hostTarget",{nodeId:e.id,reason:d,autoHost:me,ok:u.ok===!0,active:u.active===!0}),await se("host-target"),u.ok===!0&&(i?u.active===!0:u.active!==!0)}catch(u){return we(u instanceof Error?u.message:String(u)),h.emit("remoteMonitor.node.hostTarget",{nodeId:e.id,reason:d,autoHost:me,ok:!1}),!1}finally{Ce.current=!1}},[me,e.id,se,l.auth,l.baseUrl,l.source]),ti=p.useCallback(i=>{i.stopPropagation(),vt(!ie,"manual")},[ie,vt]),oi=p.useCallback(i=>{i.stopPropagation();const d=!me;Aa(e.id,d),gt(d),we(d?"Auto Host enabled for this monitor.":"Auto Host disabled."),h.emit("remoteMonitor.node.autoHost",{nodeId:e.id,enabled:d,source:l.source}),!d&&ie&&vt(!1,"auto-host-disabled")},[me,ie,e.id,vt,l.source]);p.useEffect(()=>{if(l.source!=="bridge"||!me||ie||ee.current)return;if(!nn(e.id)){gt(!1);return}let i=!1;return ee.current=!0,we("Restoring Auto Host..."),h.emit("remoteMonitor.node.autoHost.restore",{nodeId:e.id,requested:!0,source:l.source}),vt(!0,"auto-host-restore").then(d=>{i||(h.emit("remoteMonitor.node.autoHost.restore",{nodeId:e.id,ok:d,source:l.source}),d||we("Auto Host restore failed."))}).finally(()=>{ee.current=!1}),()=>{i=!0}},[me,ie,e.id,vt,l.source]),p.useEffect(()=>{if(l.source!=="bridge"||!ie)return;let i=!1;const d=async()=>{if(!(i||g.current)){g.current=!0;try{const f=await ga(e.id,!0,l.auth,l.baseUrl,{leaseMs:Vt});h.emit("remoteMonitor.node.hostTarget.renew",{nodeId:e.id,ok:f.ok===!0,active:f.active===!0,leaseMs:Vt}),!i&&(f.ok!==!0||f.active!==!0)&&(we(f.error||"Host target renewal lost ownership."),await se("host-target-renew"))}catch(f){h.emit("remoteMonitor.node.hostTarget.renew",{nodeId:e.id,ok:!1,active:!1,leaseMs:Vt,error:f instanceof Error?f.message:String(f)}),i||we(f instanceof Error?f.message:String(f))}finally{g.current=!1}}},u=window.setInterval(()=>{d()},fo);return h.emit("remoteMonitor.node.hostTarget.renew.timer",{nodeId:e.id,active:!0,intervalMs:fo,leaseMs:Vt}),()=>{i=!0,window.clearInterval(u),h.emit("remoteMonitor.node.hostTarget.renew.timer",{nodeId:e.id,active:!1})}},[ie,e.id,se,l.auth,l.baseUrl,l.source]),p.useEffect(()=>{if(l.source!=="bridge"||!ht||!ke){ht||(L.current="",Y.current=0);return}let i=!1,d=0;L.current!==ke&&(L.current=ke,Y.current=0);const u=f=>{window.clearTimeout(d),d=window.setTimeout(async()=>{if(i||L.current!==ke)return;const T=Y.current;if(T>=Rt){h.emit("remoteMonitor.node.task.follow",{nodeId:e.id,active:!1,batchKey:ke,tick:T,maxTicks:Rt,reason:"max-ticks"});return}const C=T+1;Y.current=C,h.emit("remoteMonitor.node.task.follow",{nodeId:e.id,active:!0,batchKey:ke,tick:C,maxTicks:Rt}),await se("task-follow"),!i&&L.current===ke&&Y.current<Rt&&u(Io)},Math.max(0,f))};return h.emit("remoteMonitor.node.task.follow",{nodeId:e.id,active:!0,batchKey:ke,intervalMs:Io,maxTicks:Rt,reason:"start"}),u(bc),()=>{i=!0,window.clearTimeout(d),h.emit("remoteMonitor.node.task.follow",{nodeId:e.id,active:!1,batchKey:ke,tick:Y.current,reason:"cleanup"})}},[e.id,se,l.source,ht,ke]);const ni=p.useCallback(i=>{if(i.stopPropagation(),S){Q(!1),ae("Remote input locked."),h.emit("remoteMonitor.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"manual",deviceId:H});return}if(!Le){ne("unavailable"),ae(nt||"Remote input unavailable."),h.emit("remoteMonitor.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"unavailable",deviceId:H});return}Q(!0),ae("Connecting remote input adapter..."),h.emit("remoteMonitor.node.input.lock",{nodeId:e.id,unlocked:!0,reason:"manual",deviceId:H})},[Le,nt,S,e.id,H]),Ve=p.useCallback(i=>{var $;const d=F.current;if(!S||!Le||!H||(d==null?void 0:d.readyState)!==WebSocket.OPEN){i.ack&&ae(S?"Remote input socket is not ready.":"Remote input locked.");return}const u=`remote-node-input-${Date.now()}-${++J.current}`,{ack:f,...T}=i,C=mr({requestId:u,deviceId:H,ack:f,controlLeaseId:($=l.hub)==null?void 0:$.hostTargetLeaseId,input:T});if(!C){f&&ae("Remote input payload is invalid.");return}const R=w(C.input.type);try{d.send(JSON.stringify(C));const G=++Z.current;(C.ack||G%24===1)&&h.emit("remoteMonitor.node.input.sent",{nodeId:e.id,deviceId:H,inputType:R,sampled:!C.ack,sent:G})}catch(G){const he=G instanceof Error?G.message:String(G);ne("error"),ae(he),h.emit("remoteMonitor.node.input.ws",{nodeId:e.id,ok:!1,deviceId:H,error:he})}},[Le,S,e.id,H,(da=l.hub)==null?void 0:da.hostTargetLeaseId]);p.useEffect(()=>{if(typeof document>"u")return;const i=d=>{const u=d.detail;if(!u||typeof u!="object")return;const f=w(u.nodeId);if(f&&f!==e.id)return;const T=w(u.deviceId);if(T&&T!==H)return;const C=u.input;!C||typeof C!="object"||Array.isArray(C)||Ve({...C,ack:u.ack!==!1})};return document.addEventListener(xa,i),()=>document.removeEventListener(xa,i)},[e.id,H,Ve]);const Ct=p.useCallback((i,d,u,f=!1)=>{const T=So(i,f);return T?(Ve({type:d,...T,button:Pr(i.button),ack:u}),!0):!1},[Ve]),ai=p.useCallback((i,d,u)=>{if(i.stopPropagation(),Fe(d),!u){Xo(i);return}if(Ct(i,"pointerDown",!0,!1)){i.preventDefault(),i.currentTarget.focus();try{i.currentTarget.setPointerCapture(i.pointerId)}catch{}}},[Ct,Xo]),ri=p.useCallback((i,d)=>{var C,R;if(!d){Yo(i);return}const u=performance.now();if(u-pe.current<Tr)return;pe.current=u;const f=((R=(C=i.currentTarget).hasPointerCapture)==null?void 0:R.call(C,i.pointerId))===!0;Ct(i,"pointerMove",!1,f)&&(i.preventDefault(),i.stopPropagation())},[Ct,Yo]),ii=p.useCallback((i,d)=>{if(!d){It(i);return}i.preventDefault(),i.stopPropagation();try{i.currentTarget.releasePointerCapture(i.pointerId)}catch{}Ct(i,"pointerUp",!0,!0)},[Ct,It]),si=p.useCallback((i,d)=>{d||It(i)},[It]),li=p.useCallback((i,d)=>{if(!d)return;const u=So(i,!1);u&&(Ve({type:"wheel",...u,deltaX:i.deltaX,deltaY:i.deltaY,ack:!0}),i.preventDefault(),i.stopPropagation())},[Ve]),ci=p.useCallback((i,d,u)=>{if(!u){(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),i.stopPropagation(),Fe(d));return}i.key!=="Escape"&&(i.preventDefault(),i.stopPropagation(),Ve({type:"keyDown",key:i.key,code:i.code,repeat:i.repeat,ack:!0}))},[Ve]),di=p.useCallback((i,d)=>{!d||i.key==="Escape"||(i.preventDefault(),i.stopPropagation(),Ve({type:"keyUp",key:i.key,code:i.code,repeat:!1,ack:!0}))},[Ve]),Jo=p.useCallback(async(i,d="selected")=>{var R;if(i.preventDefault(),i.stopPropagation(),l.source!=="bridge"){Ue("LocalBridge is not connected.");return}const u=Re.trim();if(!u){Ue("Remote task is empty.");return}if(d==="selected"&&(!H||!Wo||(oe==null?void 0:oe.connected)!==!0)){Ue("Selected device cannot accept remote tasks.");return}if(d==="all"&&io.length<=0){Ue("No task-capable connected devices are available.");return}if(d==="ai"&&so.length<=0){Ue("No AI assist devices are connected.");return}const f=d==="ai"?"ai-assist":"task-only",T=((R=u.split(/\r?\n/)[0])==null?void 0:R.slice(0,96))||"Remote task",C=d==="ai"?so:io;to(d),Ue(d==="selected"?"Queueing selected task...":"Queueing fleet task...");try{const $=d==="selected"?await Ya(H,{instruction:u,title:T,approvalLevel:f},l.auth,l.baseUrl):await rs({instruction:u,title:T,approvalLevel:f,deviceIds:C,allConnected:!1},l.auth,l.baseUrl),G=$.ok===!0,he=d==="selected"?G?1:0:Number("queued"in $?$.queued:0);Ue(G?`Queued ${he||1} remote task${(he||1)===1?"":"s"}.`:$.error||"Remote task queue failed."),h.emit("remoteMonitor.node.task.queue",{nodeId:e.id,mode:d,ok:G,queued:he,approvalLevel:f,deviceId:d==="selected"?H:"",targetCount:d==="selected"?1:C.length,batchId:"batchId"in $?$.batchId:"",error:$.error||""}),G&&(eo(""),await se("task-queued"))}catch($){const G=$ instanceof Error?$.message:String($);Ue(G),h.emit("remoteMonitor.node.task.queue",{nodeId:e.id,mode:d,ok:!1,approvalLevel:f,deviceId:d==="selected"?H:"",targetCount:d==="selected"?1:C.length,error:G})}finally{to("")}},[Bt,so,e.id,se,Wo,oe==null?void 0:oe.connected,H,l.auth,l.baseUrl,l.source,io,Re]),ui=a.jsxs("div",{className:"node-remote-monitor__head-actions",children:[a.jsx("i",{"aria-label":`Remote route ${lo}`}),a.jsxs("span",{className:"node-remote-monitor__head-status","data-testid":"remote-monitor-node-agent-status","data-agent-status":Gt,children:["AGENT ",a.jsx("strong",{children:Gt})]}),a.jsxs("span",{className:`node-remote-monitor__head-status node-remote-monitor__route-status is-${re.tone}`,"data-testid":"remote-monitor-node-registry-route","data-registry-route":re.status,"data-account-route-ready":re.accountRouteReady?"true":"false","data-registry-migration-blocked":re.migrationBlocked?"true":"false",title:re.title,children:["ROUTE ",a.jsx("strong",{children:re.value})]}),l.source==="bridge"?a.jsxs(a.Fragment,{children:[a.jsxs("button",{type:"button","data-testid":"remote-monitor-node-host",onClick:ti,children:[a.jsx(ko,{size:12}),ie?"Clear Host":"Set Host"]}),a.jsxs("button",{type:"button",className:me?"is-active":"","data-testid":"remote-monitor-node-auto-host","data-auto-host-active":me?"true":"false",onClick:oi,title:me?"Disable Auto Host restore for this monitor":"Remember this monitor as the Auto Host target",children:[a.jsx(ko,{size:12}),"Auto"]}),a.jsxs("button",{type:"button","data-testid":"remote-monitor-node-agent-connect",onClick:Jr,disabled:!po,title:po?"Connect managed RemoteAgent":uo,children:[a.jsx(xi,{size:12,className:Se==="connect"?"spin-icon":""}),"Start"]}),a.jsxs("button",{type:"button","data-testid":"remote-monitor-node-agent-disconnect",onClick:Zr,disabled:!mo,title:mo?"Stop managed RemoteAgent":"RemoteAgent is not running",children:[a.jsx(wi,{size:12,className:Se==="disconnect"?"spin-icon":""}),"Stop"]})]}):l.source==="blocked"?a.jsxs("button",{type:"button",onClick:Qr,children:[a.jsx(ko,{size:12}),"Enable"]}):a.jsxs("button",{type:"button",onClick:Jn,children:[a.jsx(vo,{size:12,className:l.loading?"spin-icon":""}),"Refresh"]})]}),pi=a.jsxs("form",{className:"node-remote-monitor__taskbar","data-testid":"remote-monitor-node-taskbar",onSubmit:i=>Jo(i,"selected"),children:[a.jsx("input",{"aria-label":"Remote task",value:Re,maxLength:1200,onChange:i=>eo(i.target.value),onPointerDown:i=>i.stopPropagation(),placeholder:oe?`Task for ${ft(oe)}`:"Remote task"}),a.jsxs("button",{type:"submit",disabled:!Vn,title:Vn?"Queue task for selected device":"Selected device cannot accept remote tasks",children:[a.jsx(rn,{size:12,className:Je==="selected"?"spin-icon":""}),"Selected"]}),a.jsxs("button",{type:"button",disabled:!qn,title:qn?"Queue task for connected devices":"No connected devices can accept tasks",onClick:i=>Jo(i,"all"),children:[a.jsx(rn,{size:12,className:Je==="all"?"spin-icon":""}),"All"]}),a.jsxs("button",{type:"button",disabled:!Wn,title:Wn?"Queue AI assist task for connected AI devices":"No AI assist device is connected",onClick:i=>Jo(i,"ai"),children:[a.jsx(Si,{size:12,className:Je==="ai"?"spin-icon":""}),"AI"]})]}),mi=a.jsxs("div",{className:"node-remote-monitor__footer",children:[a.jsxs("div",{className:"node-remote-monitor__footer-scale","data-testid":"remote-monitor-node-tile-scale","data-tile-scale-index":He,"data-tile-scale":_t,children:[a.jsx("button",{type:"button","aria-label":"Shrink remote monitor tiles","data-testid":"remote-monitor-node-tile-shrink",disabled:He<=0,onClick:i=>Yn(i,-1),children:a.jsx(Ri,{size:12})}),a.jsx("button",{type:"button","aria-label":"Grow remote monitor tiles","data-testid":"remote-monitor-node-tile-grow",disabled:He>=qt.length-1,onClick:i=>Yn(i,1),children:a.jsx(Na,{size:12})})]}),a.jsxs("label",{className:"node-remote-monitor__footer-group","data-testid":"remote-monitor-node-group","data-group-mode":ze,children:[a.jsx("span",{children:"GROUP"}),a.jsx("select",{"aria-label":"Remote monitor grouping","data-testid":"remote-monitor-node-group-mode",value:ze,onPointerDown:i=>i.stopPropagation(),onChange:qr,children:Cr.map(i=>a.jsx("option",{value:i,children:Fc(i)},i))})]}),a.jsxs("label",{className:"node-remote-monitor__footer-filter","data-testid":"remote-monitor-node-filter","data-filter-active":N?"true":"false",children:[a.jsx("span",{children:"FILTER"}),a.jsx("input",{"aria-label":"Remote monitor search","data-testid":"remote-monitor-node-filter-text",value:Ot,maxLength:64,onPointerDown:i=>i.stopPropagation(),onChange:Wr,placeholder:"Any"}),a.jsx("select",{"aria-label":"Remote monitor visibility filter","data-testid":"remote-monitor-node-visibility-filter",value:Ae,onPointerDown:i=>i.stopPropagation(),onChange:Hr,children:xr.map(i=>a.jsx("option",{value:i,children:Bc(i)},i))}),a.jsx("select",{"aria-label":"Remote monitor capability filter","data-testid":"remote-monitor-node-capability-filter",value:Ee,onPointerDown:i=>i.stopPropagation(),onChange:Kr,children:wr.map(i=>a.jsx("option",{value:i,children:Gc(i)},i))})]}),a.jsxs("div",{className:"node-remote-monitor__footer-status",children:[a.jsxs("span",{children:[a.jsx("i",{})," HUB ",a.jsx("strong",{children:$o})]}),a.jsxs("span",{children:["CONNECTED ",a.jsxs("strong",{children:[Ft,"/",et]})]}),a.jsxs("span",{children:["TASK ",a.jsx("strong",{children:Uo})]}),a.jsxs("span",{children:["AI ",a.jsx("strong",{children:Bt})]}),a.jsxs("span",{children:["INPUT ",a.jsx("strong",{children:Ho})]}),a.jsxs("span",{children:["PAGE ",a.jsx("strong",{children:Go})]}),a.jsxs("span",{children:[a.jsx("i",{})," ROUTE ",a.jsx("strong",{children:lo})]}),a.jsxs("button",{type:"button","data-testid":"remote-monitor-node-copy-connect",onClick:ei,children:[a.jsx(Da,{size:12}),"Connect"]}),a.jsxs("button",{type:"button","data-testid":"remote-monitor-node-refresh",onClick:Jn,children:[a.jsx(vo,{size:12,className:l.loading?"spin-icon":""}),"Refresh"]}),l.source==="bridge"&&a.jsxs("button",{type:"button","data-testid":"remote-monitor-node-input",onClick:ni,disabled:!Le&&!S,title:S||Le?Nt:nt,children:[S?a.jsx(Oa,{size:12}):a.jsx(_a,{size:12}),S?"Lock":"Unlock"]})]})]});return a.jsxs("div",{ref:s,className:"node-remote-monitor","data-testid":"remote-monitor-node","data-remote-source":l.source,"data-remote-canonical-total":et,"data-remote-connected":Ft,"data-remote-projection":on,"data-remote-projected-count":O,"data-remote-visible-budget":Me,"data-remote-page-index":_,"data-remote-page-count":P,"data-remote-page-start":X,"data-remote-host-active":ie?"true":"false","data-remote-registry-route":re.status,"data-remote-registry-ready":re.accountRouteReady?"true":"false","data-remote-registry-migration-blocked":re.migrationBlocked?"true":"false","data-remote-registry-reason":re.reason,"data-remote-host-renew-ms":ie?fo:0,"data-remote-auto-host":me?"true":"false","data-remote-agent-status":Gt,"data-remote-agent-running":co?"true":"false","data-remote-agent-ready":Ko?"true":"false","data-remote-task-follow-active":ht?"true":"false","data-remote-task-follow-key":ke,"data-remote-task-follow-refresh-ms":ht?Io:0,"data-remote-transport-visible":m?"true":"false","data-remote-frame-subscription-active":m&&$e.length>0?"true":"false","data-remote-tile-scale-index":He,"data-remote-tile-scale":_t,"data-remote-tile-min-width":Gn,"data-remote-tile-min-height":Un,"data-remote-group-mode":ze,"data-remote-visible-group-count":Fn,"data-remote-filter-text":y,"data-remote-filter-active":N?"true":"false","data-remote-visibility-filter":Ae,"data-remote-capability-filter":Ee,"data-remote-filtered-count":U.length,"data-disable-mindcanvas-wheel":"true",children:[a.jsxs("div",{className:"node-remote-monitor__surface",children:[a.jsx("div",{className:"node-remote-monitor__head",children:a.jsxs("div",{className:"node-remote-monitor__titlemark",children:[a.jsx("span",{children:a.jsx(Mi,{size:15})}),a.jsxs("div",{children:[a.jsx("small",{children:"REMOTE"}),a.jsx("strong",{children:"Multi Desktop Monitor"})]})]})}),a.jsxs("div",{className:"node-remote-monitor__wall-shell",children:[a.jsxs("div",{ref:c,className:"node-remote-monitor__wall","data-testid":"remote-monitor-node-wall","data-page-index":_,"data-page-count":P,"data-page-start":X,"data-visible-devices":ge.length,"data-visible-device-ids":tt.join(","),"data-visible-connected-devices":$e.length,"data-frame-subscription-device-ids":ot,"data-frame-subscription-active":m&&$e.length>0?"true":"false","data-transport-visible":m?"true":"false","data-canonical-device-count":et,"data-connected-device-count":Ft,"data-wall-projection":on,"data-projected-device-count":O,"data-visible-budget":Me,"data-tile-scale-index":He,"data-tile-scale":_t,"data-group-mode":ze,"data-visible-group-count":Fn,"data-filter-text":y,"data-filter-active":N?"true":"false","data-visibility-filter":Ae,"data-capability-filter":Ee,"data-filtered-device-count":U.length,style:{"--remote-node-tile-min-width":`${Gn}px`,"--remote-node-tile-min-height":`${Un}px`},onPointerDown:i=>Xo(i),onPointerMove:i=>Yo(i),onPointerUp:i=>It(i),onPointerCancel:i=>It(i),onWheel:Vr,children:[ge.map(i=>{const d=it(i),u=ft(i),f=Wt(i),T=d===H,C=S&&Le&&T;return a.jsxs("span",{className:`${i.connected===!0?"is-online":""} ${T?"is-selected":""} ${C?"is-input-active":""}`,"aria-label":`${u} remote desktop`,title:`${u} / ${Xt(i)}`,role:"button",tabIndex:C||T?0:-1,"data-device-id":d,"data-connected":i.connected===!0?"true":"false","data-frame-seq":(f==null?void 0:f.frameSeq)??0,"data-can-control":ce(i,"control")?"true":"false","data-can-dispatch-task":ce(i,"taskDispatch")?"true":"false","data-ai-assist":ce(i,"aiAssist")?"true":"false","data-input-active":C?"true":"false","data-group-mode":ze,"data-group-key":Uc(i,ze),onClick:R=>{if(R.stopPropagation(),Pe.current){Pe.current=!1,R.preventDefault();return}Fe(d)},onDoubleClick:R=>Xr(R,i),onPointerDown:R=>ai(R,d,C),onPointerMove:R=>ri(R,C),onPointerUp:R=>ii(R,C),onPointerCancel:R=>si(R,C),onWheel:R=>li(R,C),onKeyDown:R=>ci(R,d,C),onKeyUp:R=>di(R,C),children:[a.jsx("canvas",{ref:R=>Yr(d,R)}),C&&a.jsxs("em",{children:[a.jsx(Fa,{size:10}),"input"]}),a.jsx("small",{children:u})]},d)}),Array.from({length:Ur},(i,d)=>a.jsx("span",{"aria-label":`Remote desktop slot ${X+ge.length+d+1}`,"data-placeholder-slot":"true"},`empty-${_}-${d}`))]}),a.jsxs("div",{className:"node-remote-monitor__pager","aria-label":"Monitor page controls",children:[a.jsx("button",{type:"button","aria-label":"Previous monitor page",disabled:_<=0,onClick:i=>Xn(i,-1),children:a.jsx(Pi,{size:12})}),a.jsx("span",{className:"node-remote-monitor__pager-track",style:{"--remote-node-page-top":`${zr}%`,"--remote-node-page-height":`${Bn}%`},children:a.jsx("strong",{})}),a.jsx("button",{type:"button","aria-label":"Next monitor page",disabled:_>=P-1,onClick:i=>Xn(i,1),children:a.jsx(Ai,{size:12})})]})]})]}),a.jsxs("div",{className:"node-remote-monitor__external-rail","data-testid":"remote-monitor-node-external-rail",onPointerDown:i=>i.stopPropagation(),onClick:i=>i.stopPropagation(),children:[ui,pi,mi,a.jsx("p",{className:"node-remote-monitor__message",children:$r})]})]})}function pu({node:e,onPatch:t}){var oo,Ot,no,Ae,ao,Ee,ro,me,gt,et;const o=Rr(e),n=p.useRef(null),r=Sr(n,e.id,"control"),[s,c]=p.useState(()=>{var y;return{source:Pt()?"loading":"blocked",loading:!1,message:Pt()?"Remote device not checked yet.":"Hosted LocalBridge access is gated.",baseUrl:((y=e.metadata)==null?void 0:y.RemoteBaseUrl)||j(),device:St(e)}}),m=p.useRef(null),l=p.useRef(new Set),b=p.useRef(new Map),k=p.useRef(new Map),x=p.useRef(null),v=p.useRef(0),V=p.useRef(0),M=p.useRef(!1),F=p.useRef(0),J=p.useRef(0),Z=p.useRef(0),E=p.useRef(0),ue=p.useRef(e.metadata??{}),[B,pe]=p.useState(!1),[Ce,g]=p.useState("locked"),[ee,L]=p.useState("Remote input locked."),[Y,Oe]=p.useState(""),[W,Pe]=p.useState(!1),[_e,be]=p.useState(""),A=s.device,xe=A?ft(A):e.title||"Remote device",Fe=A?Xt(A):((oo=e.metadata)==null?void 0:oo.RemoteFleetDevicePlatform)||"unknown",S=Ua((Ot=s.bridge)==null?void 0:Ot.status),Q=za((no=s.bridge)==null?void 0:no.status),te=s.source==="bridge"&&!!o&&(A==null?void 0:A.connected)===!0&&!!Q&&ce(A,"control"),ne=A?ce(A,"taskDispatch"):!1,Nt=s.source==="bridge"&&!!o&&(A==null?void 0:A.connected)===!0&&ne&&!!Y.trim()&&!W,ae=B?Er(Ce):te?"Locked":"Off",_o=_e||ee||s.message;p.useEffect(()=>{ue.current=e.metadata??{}},[e.metadata]);const we=p.useCallback((y,I)=>{const N=ue.current??{},U=Object.entries(I).filter(([O,P])=>N[O]!==P).map(([O])=>O);if(U.length===0)return;const z={...N,...I};ue.current=z,t(e.id,{metadata:z}),h.emit("remoteControl.node.metadata.patch",{nodeId:e.id,reason:y,keys:U})},[e.id,t]),Se=p.useCallback(async(y="manual")=>{const I=++E.current,N=j();if(c(U=>({...U,loading:!0,baseUrl:N})),!o){c({source:"unavailable",loading:!1,message:"Remote control node has no device id.",baseUrl:N,device:St(e)});return}if(!Pt()){c({source:"blocked",loading:!1,message:"Hosted LocalBridge access is gated.",baseUrl:N,device:St(e)}),h.emit("remoteControl.node.preview",{nodeId:e.id,reason:"hosted-localbridge-gated",deviceId:o});return}try{const U=await In(N);if(I!==E.current)return;if(U.state!=="connected"){c({source:"unavailable",loading:!1,message:U.message||"LocalBridge is unavailable.",baseUrl:N,bridge:U,device:St(e)});return}const z=Wa(U.status),[O,P]=await Promise.all([Ha(z,N),Ka(z,N,{includeDataUrl:!1})]);if(I!==E.current)return;const _=(Array.isArray(P.devices)?P.devices:[]).find(ge=>it(ge)===o),X=_||St(e);c({source:_?"bridge":"unavailable",loading:!1,message:_?`${ft(X)} ${X.connected===!0?"online.":"offline."}`:"Selected remote device is not in the current RemoteHub inventory.",baseUrl:N,bridge:U,auth:z,hub:O,device:X}),h.emit("remoteControl.node.refresh",{nodeId:e.id,reason:y,deviceId:o,found:!!_,connected:X.connected===!0})}catch(U){if(I!==E.current)return;c({source:"unavailable",loading:!1,message:U instanceof Error?U.message:String(U),baseUrl:N,device:St(e)})}},[o,e]);p.useEffect(()=>{Se("mount")},[Se]),p.useEffect(()=>{var y,I,N;we("snapshot",{SemanticType:"RemoteFleetDevice",RemoteFleetSchemaVersion:"remote-fleet-device@1",RemoteFleetDeviceId:o,RemoteFleetDeviceName:xe,RemoteFleetDevicePlatform:Fe,RemoteFleetDeviceConnected:String((A==null?void 0:A.connected)===!0),RemoteFleetDeviceCanControl:String(te),RemoteFleetDeviceCanDispatchTask:String(ne),RemoteFleetDeviceTasksQueued:String(((y=A==null?void 0:A.counters)==null?void 0:y.tasksQueued)||0),RemoteFleetSourceMonitorNodeId:((I=e.metadata)==null?void 0:I.RemoteFleetSourceMonitorNodeId)||"",RemoteInput:ae,RemoteTask:ne?"available":"unavailable",RemoteHub:s.source==="bridge"?((N=s.hub)==null?void 0:N.started)===!0?"Online":"Ready":s.source==="blocked"?"Gated":s.source,RemoteRoute:s.source==="bridge"?"Local":s.source==="blocked"?"Gated":"Preview",RemoteBaseUrl:s.baseUrl,AdapterState:s.source==="bridge"?"localbridge-connected":s.source==="blocked"?"adapter-gated":s.source})},[te,ne,A==null?void 0:A.connected,(Ae=A==null?void 0:A.counters)==null?void 0:Ae.tasksQueued,o,xe,ae,e.metadata,we,Fe,s.baseUrl,(ao=s.hub)==null?void 0:ao.started,s.source]);const mt=p.useCallback((y,I)=>{if(!o)return!1;const N=Br(k.current,o);if(!N)return!1;const{cached:U,scope:z}=N;return Ro(y,U,l.current,b.current).then(O=>{O&&h.emit("remoteControl.node.frameCache",{nodeId:e.id,deviceId:o,frameSeq:pt(U.metadata),scope:z,reason:I})}),!0},[o,e.id]);p.useEffect(()=>{const y=m.current;if(!y||!A)return;const I=Wt(A),N=Nn(I);s.source==="bridge"&&N?Gr(y,N,s.baseUrl).catch(()=>Mo(y,A,s.source)):s.source==="bridge"&&mt(y,"projection-rerender")||Mo(y,A,s.source)},[A,mt,s.baseUrl,s.source]);const Dt=p.useCallback(async(y,I)=>{if(!o||w(y.deviceId).trim()!==o)return;const N=Number(y.frameSeq||0)||0,U=Dn(b.current,k.current,o);if(N>0&&N<=U){h.emit("remoteControl.node.frameStaleDropped",{nodeId:e.id,deviceId:o,frameSeq:N,previous:U,source:"ws"});return}const z=dr(y,I.byteLength);z.level!=="nominal"&&h.emit("remoteControl.node.framePressure",{nodeId:e.id,deviceId:o,frameSeq:N,...z});const O=_r(k.current,o,y,I),P=m.current;if(P){if(l.current.has(o)){h.emit("remoteControl.node.frameCache",{nodeId:e.id,deviceId:o,frameSeq:N,scope:"local",reason:"decode-pending"});return}l.current.add(o);try{await On(P,O.metadata,O.payload)&&(N>0&&b.current.set(o,N),J.current+=1,h.emit("remoteControl.node.framePainted",{nodeId:e.id,deviceId:o,frameSeq:N,painted:J.current,source:"ws"}))}catch{}finally{l.current.delete(o);const _=k.current.get(o),X=pt(_==null?void 0:_.metadata),ge=b.current.get(o)||0,tt=m.current;_&&tt&&(X<=0?ge<=0:X>ge)&&Ro(tt,_,l.current,b.current).then($e=>{$e&&(J.current+=1,h.emit("remoteControl.node.frameCache",{nodeId:e.id,deviceId:o,frameSeq:X,scope:"local",reason:"latest-pending"}),h.emit("remoteControl.node.framePainted",{nodeId:e.id,deviceId:o,frameSeq:X,painted:J.current,source:"ws-cache"}))})}}},[o,e.id]);p.useEffect(()=>{if(s.source!=="bridge"||!o||(A==null?void 0:A.connected)!==!0||!r)return;let y=!1,I=null,N=0;M.current=!1;const U=()=>{var z,O;if(!y){try{I=new WebSocket(Ar(s.baseUrl,S,(O=(z=s.bridge)==null?void 0:z.status)==null?void 0:O.bridgeToken,[o])),I.binaryType="arraybuffer"}catch(P){h.emit("remoteControl.node.frameWs",{nodeId:e.id,ok:!1,error:P instanceof Error?P.message:String(P)});return}I.onopen=()=>{M.current=!0,F.current=performance.now(),h.emit("remoteControl.node.frameWs",{nodeId:e.id,ok:!0,deviceId:o,fps:20}),I==null||I.send(JSON.stringify({type:"subscribe",deviceIds:[o],autoStartLive:!0,fps:20,maxWidth:960,maxHeight:540,quality:62,mode:"remote-fast-control"}))},I.onmessage=async P=>{if(!y){if(F.current=performance.now(),P.data instanceof ArrayBuffer){const _=wo(P.data);_&&await Dt(_.metadata,_.payload)}else if(P.data instanceof Blob){const _=wo(await P.data.arrayBuffer());_&&await Dt(_.metadata,_.payload)}}},I.onerror=()=>{M.current=!1,h.emit("remoteControl.node.frameWs",{nodeId:e.id,ok:!1,deviceId:o,reason:"socket-error"})},I.onclose=()=>{M.current=!1,y||(N=window.setTimeout(U,1500))}}};return U(),()=>{y=!0,M.current=!1,window.clearTimeout(N),I==null||I.close()}},[A==null?void 0:A.connected,o,e.id,Dt,S,s.baseUrl,(ro=(Ee=s.bridge)==null?void 0:Ee.status)==null?void 0:ro.bridgeToken,s.source,r]),p.useEffect(()=>{if(s.source!=="bridge"||!o||(A==null?void 0:A.connected)!==!0||!r)return;let y=!1,I=!1;const N=async()=>{var O;if(!(y||I)&&!(M.current&&performance.now()-F.current<kr)){I=!0;try{const P=await Xa([o],s.auth,s.baseUrl);if(y||P.ok===!1)return;const _=(O=P.frames)==null?void 0:O.find($e=>$e.deviceId===o),X=await Tn(m.current??void 0,o,_?Or(_):void 0,s.baseUrl,l.current,b.current,k.current),ge=X.painted?1:0,tt=X.staleDropped?1:0;X.staleDropped&&h.emit("remoteControl.node.frameStaleDropped",{nodeId:e.id,deviceId:o,frameSeq:X.frameSeq,previous:X.previous,source:"snapshot"}),h.emit("remoteControl.node.frameSnapshot",{nodeId:e.id,deviceId:o,frameCount:_?1:0,painted:ge,staleDropped:tt})}catch{}finally{I=!1}}},U=window.setTimeout(N,250),z=window.setInterval(N,2500);return()=>{y=!0,window.clearTimeout(U),window.clearInterval(z)}},[A==null?void 0:A.connected,o,e.id,s.auth,s.baseUrl,s.source,r]),p.useEffect(()=>{!B||te||(pe(!1),g("unavailable"),L("Remote input unavailable."),h.emit("remoteControl.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"control-unavailable",deviceId:o}))},[te,o,B,e.id]),p.useEffect(()=>{var N,U,z;if(!B){(N=x.current)==null||N.close(),x.current=null,g("locked");return}if(!te||!o){g("unavailable"),L("Remote input unavailable.");return}let y=!1,I=null;g("connecting"),L("Connecting remote input adapter...");try{I=new WebSocket(Mr(s.baseUrl,Q,(z=(U=s.bridge)==null?void 0:U.status)==null?void 0:z.bridgeToken)),x.current=I}catch(O){g("error");const P=O instanceof Error?O.message:String(O);L(P),h.emit("remoteControl.node.input.ws",{nodeId:e.id,ok:!1,deviceId:o,error:P});return}return I.onopen=()=>{y||(g("ready"),L("Remote input ready."),h.emit("remoteControl.node.input.ws",{nodeId:e.id,ok:!0,deviceId:o}))},I.onmessage=O=>{if(y)return;const P=gr(String(O.data||"{}"));if(P){if(P.type==="RemoteInputSocketReady"){g("ready");return}h.emit("remoteControl.node.input.result",{nodeId:e.id,ok:P.ok,deviceId:P.deviceId||o,inputType:P.inputType,error:P.error}),!P.ok||P.error?L(P.error||"Remote input failed."):/^pointermove$/i.test(P.inputType)||L(`${P.inputType||"Input"} queued.`)}},I.onerror=()=>{y||(g("error"),L("Remote input socket error."),h.emit("remoteControl.node.input.ws",{nodeId:e.id,ok:!1,deviceId:o,reason:"socket-error"}))},I.onclose=()=>{y||(x.current=null,g("error"),L("Remote input socket closed."),h.emit("remoteControl.node.input.ws",{nodeId:e.id,ok:!1,deviceId:o,reason:"socket-closed"}))},()=>{y=!0,x.current===I&&(x.current=null),I==null||I.close()}},[te,o,B,e.id,Q,s.baseUrl,(gt=(me=s.bridge)==null?void 0:me.status)==null?void 0:gt.bridgeToken]),p.useEffect(()=>{if(!B)return;const y=I=>{I.key==="Escape"&&(I.preventDefault(),pe(!1),L("Remote input locked."),h.emit("remoteControl.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"escape",deviceId:o}))};return window.addEventListener("keydown",y,!0),()=>window.removeEventListener("keydown",y,!0)},[o,B,e.id]);const de=p.useCallback(y=>{var _;const I=x.current;if(!B||!te||!o||(I==null?void 0:I.readyState)!==WebSocket.OPEN){y.ack&&L(B?"Remote input socket is not ready.":"Remote input locked.");return}const N=`remote-control-input-${Date.now()}-${++v.current}`,{ack:U,...z}=y,O=mr({requestId:N,deviceId:o,ack:U,controlLeaseId:(_=s.hub)==null?void 0:_.hostTargetLeaseId,input:z});if(!O){U&&L("Remote input payload is invalid.");return}const P=w(O.input.type);try{I.send(JSON.stringify(O));const X=++V.current;(O.ack||X%24===1)&&h.emit("remoteControl.node.input.sent",{nodeId:e.id,deviceId:o,inputType:P,sampled:!O.ack,sent:X})}catch(X){g("error"),L(X instanceof Error?X.message:String(X))}},[te,o,B,e.id,(et=s.hub)==null?void 0:et.hostTargetLeaseId]),Re=p.useCallback((y,I,N,U=!1)=>{const z=So(y,U);return z?(de({type:I,...z,button:Pr(y.button),ack:N}),!0):!1},[de]),eo=p.useCallback(y=>{if(!(!B||!Re(y,"pointerDown",!0,!1))){y.preventDefault(),y.stopPropagation(),y.currentTarget.focus();try{y.currentTarget.setPointerCapture(y.pointerId)}catch{}}},[Re,B]),Je=p.useCallback(y=>{var z,O;if(!B)return;const I=performance.now();if(I-Z.current<Tr)return;Z.current=I;const N=((O=(z=y.currentTarget).hasPointerCapture)==null?void 0:O.call(z,y.pointerId))===!0;Re(y,"pointerMove",!1,N)&&(y.preventDefault(),y.stopPropagation())},[Re,B]),to=p.useCallback(y=>{if(B){y.preventDefault(),y.stopPropagation();try{y.currentTarget.releasePointerCapture(y.pointerId)}catch{}Re(y,"pointerUp",!0,!0)}},[Re,B]),Fo=p.useCallback(y=>{if(!B)return;const I=So(y,!1);I&&(de({type:"wheel",...I,deltaX:y.deltaX,deltaY:y.deltaY,ack:!0}),y.preventDefault(),y.stopPropagation())},[B,de]),Ue=p.useCallback(y=>{!B||y.key==="Escape"||(y.preventDefault(),y.stopPropagation(),de({type:"keyDown",key:y.key,code:y.code,repeat:y.repeat,ack:!0}))},[B,de]),kt=p.useCallback(y=>{!B||y.key==="Escape"||(y.preventDefault(),y.stopPropagation(),de({type:"keyUp",key:y.key,code:y.code,repeat:!1,ack:!0}))},[B,de]),Ze=p.useCallback(y=>{y.stopPropagation(),qa(!0),Se("hosted-access-enabled")},[Se]),He=p.useCallback(y=>{if(y.stopPropagation(),B){pe(!1),L("Remote input locked."),h.emit("remoteControl.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"manual",deviceId:o});return}if(!te){g("unavailable"),L("Remote input unavailable."),h.emit("remoteControl.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"unavailable",deviceId:o});return}pe(!0),L("Connecting remote input adapter..."),h.emit("remoteControl.node.input.lock",{nodeId:e.id,unlocked:!0,reason:"manual",deviceId:o})},[te,o,B,e.id]),Bo=p.useCallback(y=>{y.stopPropagation(),Se("manual")},[Se]),ze=p.useCallback(async y=>{var z;if(y.preventDefault(),y.stopPropagation(),s.source!=="bridge"){be("LocalBridge is not connected.");return}const I=Y.trim();if(!I){be("Remote task is empty.");return}if(!o||(A==null?void 0:A.connected)!==!0||!ne){be("This device cannot accept remote tasks.");return}const N="task-only",U=((z=I.split(/\r?\n/)[0])==null?void 0:z.slice(0,96))||"Remote task";Pe(!0),be("Queueing device task...");try{const O=await Ya(o,{instruction:I,title:U,approvalLevel:N},s.auth,s.baseUrl),P=O.ok===!0;be(P?"Queued remote task.":O.error||"Remote task queue failed."),h.emit("remoteControl.node.task.queue",{nodeId:e.id,ok:P,deviceId:o,approvalLevel:N,queued:P?1:0,taskId:O.taskId||"",commandId:O.commandId||"",error:O.error||""}),P&&(Oe(""),await Se("task-queued"))}catch(O){const P=O instanceof Error?O.message:String(O);be(P),h.emit("remoteControl.node.task.queue",{nodeId:e.id,ok:!1,deviceId:o,approvalLevel:N,queued:0,error:P})}finally{Pe(!1)}},[ne,A==null?void 0:A.connected,o,e.id,Se,s.auth,s.baseUrl,s.source,Y]);return a.jsxs("div",{ref:n,className:"node-remote-control","data-testid":"remote-control-node","data-remote-source":s.source,"data-remote-transport-visible":r?"true":"false","data-remote-frame-subscription-active":r&&s.source==="bridge"&&(A==null?void 0:A.connected)===!0?"true":"false",onPointerDown:y=>y.stopPropagation(),children:[a.jsxs("div",{className:"node-remote-control__bar",children:[a.jsx("strong",{title:xe,children:xe}),a.jsx("span",{children:Fe}),a.jsx("button",{type:"button",title:"Refresh remote device",onClick:Bo,children:a.jsx(vo,{size:12,className:s.loading?"spin-icon":""})}),s.source==="blocked"?a.jsxs("button",{type:"button",onClick:Ze,children:[a.jsx(ko,{size:12}),"Enable"]}):a.jsxs("button",{type:"button",disabled:!te&&!B,onClick:He,children:[B?a.jsx(Oa,{size:12}):a.jsx(_a,{size:12}),B?"Lock":"Unlock"]})]}),a.jsxs("div",{className:`node-remote-control__screen ${B&&te?"is-input-active":""}`,tabIndex:B&&te?0:-1,onPointerDown:eo,onPointerMove:Je,onPointerUp:to,onWheel:Fo,onKeyDown:Ue,onKeyUp:kt,children:[a.jsx("canvas",{ref:m}),B&&te&&a.jsxs("em",{children:[a.jsx(Fa,{size:11}),"input"]})]}),a.jsxs("form",{className:"node-remote-control__taskbar","data-testid":"remote-control-node-taskbar",onSubmit:ze,children:[a.jsx("input",{"aria-label":"Remote control task",value:Y,maxLength:1200,onChange:y=>Oe(y.target.value),onPointerDown:y=>y.stopPropagation(),placeholder:ne?`Task for ${xe}`:"Task unavailable"}),a.jsxs("button",{type:"submit",disabled:!Nt,title:Nt?"Queue task for this device":"This device cannot accept remote tasks",children:[a.jsx(rn,{size:12,className:W?"spin-icon":""}),"Queue"]})]}),a.jsxs("div",{className:"node-remote-control__footer",children:[a.jsxs("span",{children:["DEVICE ",a.jsx("strong",{children:o||"missing"})]}),a.jsxs("span",{children:["STATE ",a.jsx("strong",{children:(A==null?void 0:A.connected)===!0?"online":"offline"})]}),a.jsxs("span",{children:["INPUT ",a.jsx("strong",{children:ae})]}),a.jsxs("span",{children:["TASK ",a.jsx("strong",{children:ne?"ready":"off"})]}),a.jsxs("span",{children:["ROUTE ",a.jsx("strong",{children:s.source==="bridge"?"Local":s.source==="blocked"?"Gated":"Preview"})]})]}),a.jsx("p",{className:"node-remote-control__message",children:_o})]})}function Rr(e){var t,o,n;return w(((t=e.metadata)==null?void 0:t.RemoteFleetDeviceId)||((o=e.metadata)==null?void 0:o.RemoteSelectedDeviceId)||((n=e.metadata)==null?void 0:n.DeviceId)).trim()}function St(e){var n,r,s,c,m,l,b,k,x,v,V,M,F;const t=new Date().toISOString();return{deviceId:Rr(e)||"remote-control-preview",deviceName:((n=e.metadata)==null?void 0:n.RemoteFleetDeviceName)||e.title||"Remote device",platform:((r=e.metadata)==null?void 0:r.RemoteFleetDevicePlatform)||"unknown",arch:((s=e.metadata)==null?void 0:s.RemoteFleetDeviceArch)||"",connected:/^(1|true|yes|online)$/i.test(((c=e.metadata)==null?void 0:c.RemoteFleetDeviceConnected)||""),lastSeenAt:t,capabilities:{control:/^(1|true|yes|on)$/i.test(((m=e.metadata)==null?void 0:m.RemoteFleetDeviceCanControl)||""),taskDispatch:/^(1|true|yes|on)$/i.test(((l=e.metadata)==null?void 0:l.RemoteFleetDeviceCanDispatchTask)||"")},latestLiveFrame:(b=e.metadata)!=null&&b.RemoteFleetLatestFramePath||(k=e.metadata)!=null&&k.RemoteFleetLatestFrameUrl||(x=e.metadata)!=null&&x.RemoteFleetLatestFrameDataUrl?{framePath:(v=e.metadata)==null?void 0:v.RemoteFleetLatestFramePath,frameUrl:(V=e.metadata)==null?void 0:V.RemoteFleetLatestFrameUrl,dataUrl:(M=e.metadata)==null?void 0:M.RemoteFleetLatestFrameDataUrl,frameSeq:kn((F=e.metadata)==null?void 0:F.RemoteFleetLatestFrameSeq,0)}:void 0}}function kn(e,t){const o=Number(e);return Number.isFinite(o)&&o>=0?o:t}function w(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):""}function ye(e,t){const o=Number(e);return Number.isFinite(o)?o:t}function ce(e,t){var n;const o=(n=e.capabilities)==null?void 0:n[t];return typeof o=="boolean"?o:typeof o=="number"?o!==0:typeof o=="string"?/^(1|true|yes|on)$/i.test(o):!1}function Mr(e,t,o){const n=e.replace(/^http:/i,"ws:").replace(/^https:/i,"wss:").replace(/\/+$/,""),r=t||"/api/remote/input/ws",s=new URLSearchParams;o&&s.set("token",o);const c=s.toString();return c?`${n}${r}?${c}`:`${n}${r}`}function Pr(e){return e===2?"right":e===1?"middle":"left"}function So(e,t=!1){const o=Cc(e.currentTarget);if(!o)return null;const n=o.getBoundingClientRect();if(n.width<=0||n.height<=0)return null;const r=Zt.get(o)??{left:0,top:0,width:n.width,height:n.height};return ic(e,n,r,t)}function Cc(e){return e instanceof HTMLCanvasElement?e:e.querySelector("canvas")}function Pa(e){return e.split(",").map(t=>t.trim()).filter(Boolean)}function Ar(e,t,o,n){const r=e.replace(/^http:/i,"ws:").replace(/^https:/i,"wss:").replace(/\/+$/,""),s=t||"/api/remote/frames/ws",c=new URLSearchParams;o&&c.set("token",o),n.length>0&&c.set("devices",n.join(","));const m=c.toString();return m?`${r}${s}?${m}`:`${r}${s}`}function Er(e){switch(e){case"ready":return"ready";case"connecting":return"connecting";case"unavailable":return"unavailable";case"error":return"error";default:return"locked"}}function bo(e,t){const o=new Date().toISOString(),n=Math.max(12,Math.min(gc,Math.floor(e||Me)));return Array.from({length:n},(r,s)=>({deviceId:`remote-node-preview-${s+1}`,deviceName:`Remote ${String(s+1).padStart(2,"0")}`,platform:s%4===0?"linux":"win32",arch:"x64",connected:s<t,lastSeenAt:o,capabilities:{control:!1}}))}function nn(e){if(typeof window>"u")return!1;try{const t=window.localStorage.getItem(bn);if(String(t||"").trim().toLowerCase()!=="true")return!1;const o=String(window.localStorage.getItem(yn)||"").trim(),n=String(e||"").trim();return!o||o===n}catch{return!1}}function Aa(e,t){if(!(typeof window>"u"))try{t?(window.localStorage.setItem(bn,"true"),window.localStorage.setItem(yn,String(e||"").trim())):(window.localStorage.removeItem(bn),window.localStorage.removeItem(yn))}catch{}}function xc({source:e,hub:t,baseUrl:o,hubLabel:n,routeLabel:r,connected:s,total:c,taskCount:m,taskDispatchCount:l,aiCount:b,pageLabel:k,pageStart:x,pageIndex:v,pageCount:V,projectionMode:M,projectedCount:F,visibleBudget:J,selectedDeviceId:Z,inputLabel:E,devices:ue,latestTaskBatch:B,recentTaskBatches:pe,taskFollowActive:Ce,taskFollowKey:g,isHostActiveForNode:ee,registryRouteInfo:L,hostTargetRenewMs:Y,autoHostEnabled:Oe,agent:W,agentStatusLabel:Pe,agentRunning:_e,agentReady:be,message:A}){const xe=jn(t),Fe=ee?"hosting":(t==null?void 0:t.hostTargetActive)===!0?"other-monitor":"inactive",S=Rc(ue);return{SemanticType:"RemoteFleetMonitor",RemoteFleetSchemaVersion:"remote-fleet@1",RemoteFleetViewMode:"all-devices",RemoteFleetLastRefreshAtUtc:new Date().toISOString(),RemoteFleetHubStatus:(t==null?void 0:t.started)===!0?"online":e==="blocked"?"gated":e==="bridge"?"ready":e,RemoteFleetHubEndpoint:xe,RemoteFleetManagerPackage:w(t==null?void 0:t.managerPackage)||"@mindexec/cli",RemoteFleetManagerVersion:w(t==null?void 0:t.managerVersion),RemoteFleetAgentPackage:w(t==null?void 0:t.agentPackage)||"@mindexec/remote",RemoteFleetPairTokenPreview:w(t==null?void 0:t.pairTokenPreview)||"<pair-token>",RemoteFleetConnectCommand:jr(t),RemoteFleetDeviceCount:String(c),RemoteFleetConnectedDeviceCount:String(s),RemoteFleetDevicesJson:JSON.stringify(S),RemoteFleetLatestTaskBatchJson:B?JSON.stringify(Ea(B)):"",RemoteFleetRecentTaskBatchesJson:JSON.stringify((pe??[]).slice(0,6).map(Ea)),RemoteFleetTaskFollowActive:String(Ce),RemoteFleetTaskFollowKey:g,RemoteFleetTaskFollowRefreshMs:String(Ce?Io:0),RemoteFleetTaskFollowMaxTicks:String(Rt),RemoteFleetProjectionMode:M,RemoteFleetProjectedDeviceCount:String(F),RemoteFleetCanvasPagination:`${M}:${v+1}/${V}`,RemoteFleetHostTargetState:Fe,RemoteFleetHostTargetNodeId:w(t==null?void 0:t.hostTargetNodeId),RemoteFleetHostTargetLeaseId:w(t==null?void 0:t.hostTargetLeaseId),RemoteFleetRegistryStatus:L.status,RemoteFleetRegistryReason:L.reason,RemoteFleetAccountRouteReady:String(L.accountRouteReady),RemoteFleetRegistryMigrationBlocked:String(L.migrationBlocked),RemoteFleetHostTargetRenewMs:String(Y),RemoteFleetAutoHost:String(Oe),RemoteFleetHostTargetEndpoint:w(t==null?void 0:t.hostTargetEndpoint)||xe,RemoteFleetHostTargetActivatedAtUtc:w(t==null?void 0:t.hostTargetActivatedAt),RemoteFleetHostTargetUpdatedAtUtc:w(t==null?void 0:t.hostTargetUpdatedAt),RemoteFleetHostTargetExpiresAtUtc:w(t==null?void 0:t.hostTargetExpiresAt),RemoteAgentStatus:Pe,RemoteAgentRunning:String(_e),RemoteAgentReady:String(be),RemoteAgentManager:w(W==null?void 0:W.manager),RemoteAgentLeaseId:w(W==null?void 0:W.leaseId),RemoteAgentNodeId:w(W==null?void 0:W.nodeId),RemoteAgentUpdatedAtUtc:w(W==null?void 0:W.updatedAt),RemoteAgentLastError:w((W==null?void 0:W.lastError)||(W==null?void 0:W.reconnectReason)),RemoteFleetLastError:e==="bridge"?w(t==null?void 0:t.lastError):A,RemoteHub:n,RemoteRoute:r,RemoteRegistryRoute:L.status,RemoteRegistryReason:L.reason,RemoteConnected:String(s),RemoteTotal:String(c),RemoteProjected:String(F),RemoteProjection:M,RemotePage:k,RemotePageStart:String(x),RemoteVisibleBudget:String(J),RemoteSelectedDeviceId:Z,RemoteInput:E,RemoteTasksQueued:String(m),RemoteTaskDevices:String(l),RemoteAiDevices:String(b),RemoteBaseUrl:o,AdapterState:e==="bridge"?"localbridge-connected":e==="blocked"?"adapter-gated":e}}function wc(e,t){const o=w(e==null?void 0:e.agentEndpointRouteReason).trim(),n=(e==null?void 0:e.agentEndpointAccountRouteReady)===!0,r=Lr(o);return(t?"account":(e==null?void 0:e.hostTargetActive)===!0?"other-monitor":"idle")==="other-monitor"?{status:"other-monitor",value:"Other",tone:"default",reason:o,accountRouteReady:n,migrationBlocked:r,title:o||"Another monitor currently owns the host route."}:t?n?{status:"account",value:"Account",tone:"online",reason:o||"ok",accountRouteReady:!0,migrationBlocked:!1,title:"Published to the account route registry for same-account agent pairing."}:Sc(o)?{status:"blocked",value:"Blocked",tone:"warn",reason:o,accountRouteReady:!1,migrationBlocked:r,title:r?"Account route registry needs the Supabase remote_host_targets migration.":o||"The local host is active, but account route publishing failed."}:{status:"local",value:"Local",tone:"warn",reason:o,accountRouteReady:!1,migrationBlocked:r,title:o||"The local host is active, but account route publishing is not available."}:{status:"idle",value:"Idle",tone:"default",reason:o,accountRouteReady:n,migrationBlocked:r,title:o||"No active host route."}}function Lr(e){return/registry-table-unavailable|PGRST20[25]|remote_host_targets|set_remote_host_target|clear_remote_host_target/i.test(String(e||""))}function Sc(e){return Lr(e)||/invalid-manager-endpoint|blocked|failed|error|unavailable|unauthori[sz]ed|forbidden/i.test(String(e||""))}function jn(e){const t=w(e==null?void 0:e.agentEndpoint).trim();if(t)return t;const o=w((e==null?void 0:e.agentHost)||(e==null?void 0:e.host)).trim()||"127.0.0.1",n=Number((e==null?void 0:e.port)||5197);return`${o}:${Number.isFinite(n)&&n>0?n:5197}`}function jr(e){const t=jn(e),o=w(e==null?void 0:e.pairTokenPreview).trim()||"<pair-token>";return`npx @mindexec/remote connect --manager ${t} --pair ${o}`}function Rc(e){return e.filter(t=>t.connected===!0).map(t=>{var r,s,c,m,l,b,k,x,v,V,M;const o=Wt(t),n=t.latestTask;return{deviceId:it(t),sessionId:w(t.sessionId),name:ft(t),hostname:w(t.hostname),platform:Xt(t),arch:w(t.arch),agentVersion:w(t.agentVersion),connected:t.connected===!0,lastSeenAt:w(t.lastSeenAt),lastStatusAt:w(t.lastStatusAt),computerAgentEnabled:ce(t,"taskDispatch"),controlEnabled:ce(t,"control"),thumbnailEnabled:ce(t,"thumbnail")||ce(t,"screen"),liveStreamEnabled:ce(t,"liveStream"),aiAssistEnabled:ce(t,"aiAssist"),aiModel:w((r=t.capabilities)==null?void 0:r.aiModel),aiProvider:w((s=t.capabilities)==null?void 0:s.aiProvider),thumbnailFrameUrl:w(((c=t.latestThumbnail)==null?void 0:c.frameUrl)||((m=t.latestThumbnail)==null?void 0:m.framePath)),liveFrameUrl:w(((l=t.latestLiveFrame)==null?void 0:l.frameUrl)||((b=t.latestLiveFrame)==null?void 0:b.framePath)),latestFrameSeq:pt(o),liveStreamActive:((k=t.activeLiveStream)==null?void 0:k.active)===!0,liveStreamId:w((x=t.activeLiveStream)==null?void 0:x.streamId),liveStreamFps:ye((v=t.activeLiveStream)==null?void 0:v.fps,0),latestTaskBatchId:w(n==null?void 0:n.batchId),latestTaskId:w(n==null?void 0:n.taskId),latestTaskStatus:w(n==null?void 0:n.status),latestTaskApprovalLevel:w(n==null?void 0:n.approvalLevel),latestTaskResultModel:w(n==null?void 0:n.resultModel),latestTaskResultResponseId:w(n==null?void 0:n.resultResponseId),latestTaskResultSummary:w(n==null?void 0:n.resultSummary),tasksQueued:ye((V=t.counters)==null?void 0:V.tasksQueued,0),taskResultsReceived:ye((M=t.counters)==null?void 0:M.taskResultsReceived,0)}})}function Ea(e){return{batchId:w(e.batchId),title:w(e.title),instructionPreview:w(e.instructionPreview),approvalLevel:w(e.approvalLevel),status:w(e.status),requestedAt:w(e.requestedAt),updatedAt:w(e.updatedAt),total:ye(e.total,0),queued:ye(e.queued,0),pending:ye(e.pending,0),completed:ye(e.completed,0),failed:ye(e.failed,0),timedOut:ye(e.timedOut,0)}}function Mc(e,t){return La(e)?e:(t??[]).find(La)}function Pc(e){if(!e)return"";const t=w(e.batchId).trim();return t||[w(e.title).trim(),w(e.requestedAt).trim(),w(e.updatedAt).trim(),String(ye(e.total,0)||"")].filter(Boolean).join(":")}function La(e){if(!e)return!1;const t=w(e.status).trim().toLocaleLowerCase(),o=ye(e.pending,0),n=ye(e.total,0),r=ye(e.completed,0),s=ye(e.failed,0),c=ye(e.timedOut,0);return["completed","completed-with-failures","failed","cancelled","canceled","done"].includes(t)?!1:o>0||["running","queued","pending","targeted","dispatching","in-progress"].includes(t)?!0:n>0&&r+s+c<n}function Ac(e,t){const o=Ec(e);return{manager:o[0]||"",managerCandidates:o,pairToken:w(e==null?void 0:e.pairToken).trim(),leaseId:w(e==null?void 0:e.hostTargetLeaseId).trim(),nodeId:t,engine:"auto",source:"react-remote-monitor"}}function Ec(e){const t=Array.isArray(e==null?void 0:e.agentEndpointCandidateDetails)?e.agentEndpointCandidateDetails:[],o=[e==null?void 0:e.hostTargetEndpoint,...Array.isArray(e==null?void 0:e.hostTargetEndpointCandidates)?e.hostTargetEndpointCandidates:[],e==null?void 0:e.agentEndpoint,...Array.isArray(e==null?void 0:e.agentEndpointCandidates)?e.agentEndpointCandidates:[],...t.map(s=>s.endpoint||s.address),jn(e)],n=new Set,r=[];for(const s of o){const c=Lc(s),m=c.toLowerCase();if(!(!c||n.has(m))&&(n.add(m),r.push(c),r.length>=12))break}return r}function Lc(e){const t=w(e).trim(),o=t.match(/^(\[[^\]]+\]|[^:\s]+):(\d{1,5})$/);if(!o)return"";const n=Number(o[2]);return!Number.isInteger(n)||n<=0||n>65535?"":t}function jc(e,t){if(t==="blocked")return"gated";if(t!=="bridge")return t;if(!e)return"unknown";const o=w(e.status).trim().toLowerCase();return Dr(e)?"ready":o||(Nr(e)?"running":"idle")}function Nr(e){const t=w(e==null?void 0:e.status).trim().toLowerCase();return(e==null?void 0:e.running)===!0||t==="running"||t==="starting"}function Dr(e){const t=w(e==null?void 0:e.status).trim().toLowerCase();return(e==null?void 0:e.ready)===!0||t==="ready"}function Nc({source:e,hasAuth:t,isHostActiveForNode:o,request:n,busy:r}){return r?"RemoteAgent action is already running.":e!=="bridge"?"LocalBridge is not connected.":t?o?"This monitor is already the active host target.":n.manager?n.pairToken?"":"RemoteAgent pair token is missing.":"RemoteAgent manager endpoint is missing.":"LocalBridge auth token is not available."}function it(e){return String(e.deviceId||e.sessionId||e.deviceName||"").trim()}function ft(e){return String(e.deviceName||e.hostname||it(e)||"Remote device").trim()}function Xt(e){var t;return String(((t=e.status)==null?void 0:t.platform)||e.platform||"unknown").trim()}function Dc(e){return Cr.includes(e)?e:"status"}function Oc(e){return xr.includes(e)?e:"connected"}function _c(e){return wr.includes(e)?e:"all"}function Fc(e){switch(e){case"activity":return"Activity";case"platform":return"Platform";case"capability":return"Capability";default:return"Status"}}function Bc(e){switch(e){case"all":return"All";case"offline":return"Offline";default:return"Live"}}function Gc(e){switch(e){case"control":return"Control";case"task":return"Task";case"ai":return"AI";default:return"Any"}}function Uc(e,t){switch(t){case"activity":return zc(e);case"platform":return Xt(e).toLocaleLowerCase()||"unknown";case"capability":return $c(e);default:return e.connected===!0?"online":"offline"}}function zc(e){var o,n,r,s;const t=w((o=e.latestTask)==null?void 0:o.status).toLocaleLowerCase();return t==="running"||t==="queued"?`task-${t}`:((n=e.activeLiveStream)==null?void 0:n.active)===!0?"live":Number(((r=e.counters)==null?void 0:r.liveFramesReceived)||0)>0?"live-recent":Number(((s=e.counters)==null?void 0:s.thumbnailFramesReceived)||0)>0?"thumbnail":e.lastStatusAt||e.lastSeenAt?"heartbeat":"idle"}function $c(e){return ce(e,"aiAssist")?"ai-assist":ce(e,"taskDispatch")?"task-dispatch":ce(e,"control")?"control":ce(e,"thumbnail")||ce(e,"screen")?"screen":"view-only"}function Wt(e){return e.latestLiveFrame||e.latestThumbnail}function Nn(e){return(e==null?void 0:e.dataUrl)||(e==null?void 0:e.frameUrl)||(e==null?void 0:e.framePath)||""}function Or(e){return e.live||e.thumbnail}function pt(e){const t=Number((e==null?void 0:e.frameSeq)||0);return Number.isFinite(t)&&t>0?t:0}function Dn(e,t,o){var n,r;return Math.max(e.get(o)||0,pt((n=t.get(o))==null?void 0:n.metadata),pt((r=Fr(o))==null?void 0:r.metadata))}function _r(e,t,o,n){e.has(t)&&e.delete(t);const r={metadata:{...o,deviceId:t},payload:n.slice(0),cachedAt:Date.now()};return e.set(t,r),Yt(e,fn),Vc(t,r),r}function Yt(e,t,o=Number.POSITIVE_INFINITY){const n=Date.now();for(const[r,s]of e)(!s||!s.payload||Number.isFinite(o)&&n-s.cachedAt>o)&&e.delete(r);for(;e.size>t;){const r=e.keys().next().value;if(!r)break;e.delete(r)}}function Vc(e,t){e&&(Mt.has(e)&&Mt.delete(e),Mt.set(e,{metadata:{...t.metadata,deviceId:e},payload:t.payload,cachedAt:t.cachedAt}),Yt(Mt,Ir,vr))}function Fr(e){return Yt(Mt,Ir,vr),Mt.get(e)}function Br(e,t){Yt(e,fn);const o=e.get(t);if(o)return{cached:o,scope:"local"};const n=Fr(t);return n?(e.set(t,n),Yt(e,fn),{cached:n,scope:"global"}):null}async function Ro(e,t,o,n){const r=w(t.metadata.deviceId).trim();if(!r||o.has(r))return!1;const s=pt(t.metadata),c=n.get(r)||0;if(s>0&&s<=c)return!1;o.add(r);try{const m=await On(e,t.metadata,t.payload);return m&&s>0&&n.set(r,s),m}catch{return!1}finally{o.delete(r)}}function Oo(e){const t=e.getBoundingClientRect(),o=Math.max(64,Math.round(t.width||120)),n=Math.max(42,Math.round(t.height||72)),r=Math.min(fc,Math.max(1,window.devicePixelRatio||1)),s=Math.round(o*r),c=Math.round(n*r),m=Math.abs(e.width-s),l=Math.abs(e.height-c);(e.width<=0||e.height<=0||m>wa||l>wa)&&(e.width=s,e.height=c);const k=e.getContext("2d",{alpha:!1});return k?(k.setTransform(r,0,0,r,0,0),{ctx:k,width:o,height:n}):null}function Mo(e,t,o){const n=Oo(e);if(!n)return;const{ctx:r,width:s,height:c}=n;Zt.set(e,{left:0,top:0,width:s,height:c});const m=t.connected===!0;r.fillStyle=m?"#ffffff":"#f8fafc",r.fillRect(0,0,s,c),r.strokeStyle=m?"#dbeafe":"#e2e8f0",r.lineWidth=1,r.strokeRect(.5,.5,s-1,c-1),r.fillStyle=m?"#bfdbfe":"#e2e8f0",r.fillRect(8,8,Math.max(12,s*.34),5),r.fillRect(8,18,Math.max(20,s*.52),5),r.fillStyle=o==="blocked"?"#94a3b8":"#cbd5e1",r.font="700 9px Inter, sans-serif",r.fillText(o==="bridge"?"waiting":o,8,c-8)}async function Gr(e,t,o){const n=t.startsWith("data:")?t:is(t,o);if(!n)return!1;const r=new Image;r.decoding="async",r.loading="eager",r.src=n,await r.decode();const s=Oo(e);if(!s)return!1;const{ctx:c,width:m,height:l}=s;return c.fillStyle="#020617",c.fillRect(0,0,m,l),Zt.set(e,_n(c,r,m,l)),!0}async function On(e,t,o){const n=new Blob([o],{type:t.mimeType||"image/jpeg"});let r=null;try{r=await createImageBitmap(n);const s=Oo(e);if(!s)return!1;const{ctx:c,width:m,height:l}=s;return c.fillStyle="#020617",c.fillRect(0,0,m,l),Zt.set(e,_n(c,r,m,l)),!0}catch{return qc(e,t,n)}finally{r==null||r.close()}}async function qc(e,t,o){const n=URL.createObjectURL(o);try{const r=new Image;r.decoding="async",r.loading="eager",r.src=n,await r.decode();const s=Oo(e);if(!s)return!1;const{ctx:c,width:m,height:l}=s;return c.fillStyle="#020617",c.fillRect(0,0,m,l),Zt.set(e,_n(c,r,m,l)),!0}catch{return h.emit("remoteMonitor.node.frameDecodeFailed",{deviceId:w(t.deviceId),frameSeq:Number(t.frameSeq||0)||0,mimeType:t.mimeType||"",byteLength:Number(t.byteLength||o.size||0)||0}),!1}finally{URL.revokeObjectURL(n)}}async function Tn(e,t,o,n,r,s,c){const m=Nn(o),l={painted:!1,busy:!1,staleDropped:!1,frameSeq:0,previous:0};if(!e||!m)return l;if(r.has(t))return{...l,busy:!0};const b=Number((o==null?void 0:o.frameSeq)||0)||0,k=Dn(s,c,t);if(b>0&&b<=k||b<=0&&k>0)return{painted:!1,busy:!1,staleDropped:!0,frameSeq:b,previous:k};r.add(t);try{const x=await Gr(e,m,n);return x&&b>0&&s.set(t,b),{painted:x,busy:!1,staleDropped:!1,frameSeq:b,previous:k}}catch{return{painted:!1,busy:!1,staleDropped:!1,frameSeq:b,previous:k}}finally{r.delete(t)}}function _n(e,t,o,n){const r="width"in t?Number(t.width):o,s="height"in t?Number(t.height):n,c=Math.min(o/Math.max(1,r),n/Math.max(1,s)),m=r*c,l=s*c,b=(o-m)/2,k=(n-l)/2;return e.drawImage(t,b,k,m,l),{left:b,top:k,width:m,height:l}}function mu({launchers:e,activeLauncher:t,template:o,selectedOptionId:n,values:r,validationMessage:s,canCreate:c,primaryLabel:m="Create board",onLauncherSelected:l,onOptionSelected:b,onInputChanged:k,onCreate:x,onClose:v}){const V=(o==null?void 0:o.inputs)??[];return a.jsx("div",{className:"template-launcher-backdrop","data-testid":"template-launcher-panel",onMouseDown:v,children:a.jsxs("section",{className:"template-launcher-panel floating-panel",onMouseDown:M=>M.stopPropagation(),children:[a.jsxs("header",{className:"template-launcher-head",children:[a.jsxs("div",{children:[a.jsx("span",{children:"Execution Canvas"}),a.jsx("strong",{children:t.label})]}),a.jsx("button",{type:"button",title:"Close template launcher",onClick:v,children:a.jsx(Po,{size:16})})]}),a.jsx("div",{className:"template-launcher-tabs","aria-label":"Template launchers",children:e.map(M=>a.jsxs("button",{type:"button",className:M.id===t.id?"is-active":"","data-testid":"template-launcher-tab","data-launcher-id":M.id,onClick:()=>l(M.id),children:[a.jsx(Ei,{size:14}),a.jsx("span",{children:M.label})]},M.id))}),a.jsx("p",{className:"template-launcher-description",children:t.description}),t.options.length>0&&a.jsxs("div",{className:"template-launcher-option-block",children:[a.jsx("div",{className:"template-launcher-prompt",children:t.prompt||"Choose the board to create."}),a.jsx("div",{className:"template-launcher-chips",children:t.options.map(M=>a.jsxs("button",{type:"button",className:n===M.id?"is-active":"","data-testid":"template-option","data-option-id":M.id,onClick:()=>b(M.id),children:[a.jsx("strong",{children:M.label}),a.jsx("span",{children:M.description})]},M.id))})]}),V.length>0&&a.jsx("div",{className:"template-launcher-form",children:V.map(M=>a.jsx(Wc,{input:M,value:r[M.key]??"",onChange:F=>k(M.key,F)},M.key))}),s&&a.jsx("div",{className:"template-launcher-validation",children:s}),a.jsxs("footer",{className:"template-launcher-footer",children:[a.jsx("button",{type:"button",className:"template-launcher-secondary",onClick:v,children:"Cancel"}),a.jsxs("button",{type:"button",className:"template-launcher-primary","data-testid":"template-create",disabled:!c,onClick:x,children:[a.jsx(Na,{size:15}),a.jsx("span",{children:m})]})]})]})})}function Wc({input:e,value:t,onChange:o}){return a.jsxs("label",{className:"template-launcher-field",children:[a.jsxs("span",{children:[a.jsx("strong",{children:e.label}),e.description&&a.jsx("small",{children:e.description})]}),e.type==="textarea"?a.jsx("textarea",{placeholder:e.placeholder,value:t,onChange:n=>o(n.target.value)}):e.type==="select"?a.jsx("select",{value:t,onChange:n=>o(n.target.value),children:(e.options??[]).map(n=>a.jsx("option",{value:n.value,children:n.label},n.value))}):a.jsx("input",{type:"text",placeholder:e.placeholder,value:t,onChange:n=>o(n.target.value)})]})}function gu({node:e,onSave:t,onClose:o}){var b,k,x,v,V,M;const[n,r]=p.useState(((b=e.metadata)==null?void 0:b.DirectoryPath)??e.sourceFilePath??""),[s,c]=p.useState(((k=e.metadata)==null?void 0:k.Include)??""),[m,l]=p.useState(((x=e.metadata)==null?void 0:x.Exclude)??"");return p.useEffect(()=>{var F,J,Z;r(((F=e.metadata)==null?void 0:F.DirectoryPath)??e.sourceFilePath??""),c(((J=e.metadata)==null?void 0:J.Include)??""),l(((Z=e.metadata)==null?void 0:Z.Exclude)??"")},[e.id,(v=e.metadata)==null?void 0:v.DirectoryPath,(V=e.metadata)==null?void 0:V.Exclude,(M=e.metadata)==null?void 0:M.Include,e.sourceFilePath]),a.jsx("div",{className:"directory-settings-backdrop","data-testid":"directory-settings-dialog",onMouseDown:o,children:a.jsxs("section",{className:"directory-settings-dialog","aria-label":"Folder scan settings","data-disable-mindcanvas-hotkeys":"true",onMouseDown:F=>F.stopPropagation(),children:[a.jsxs("header",{className:"directory-settings-head",children:[a.jsxs("div",{children:[a.jsxs("span",{children:[a.jsx(Li,{size:15}),"Folder scan settings"]}),a.jsx("strong",{title:e.sourceFilePath||e.title,children:e.title})]}),a.jsx("button",{type:"button",title:"Close folder scan settings","aria-label":"Close folder scan settings","data-testid":"directory-settings-close",onClick:o,children:a.jsx(Po,{size:16})})]}),a.jsxs("div",{className:"directory-settings-body",children:[a.jsxs("label",{className:"directory-setting-row",children:[a.jsxs("span",{children:[a.jsx(ji,{size:14}),"LocalBridge path"]}),a.jsx("input",{value:n,placeholder:"E:\\\\Dev@Work\\\\Project or relative/path","data-testid":"directory-settings-path",onChange:F=>r(F.target.value)})]}),a.jsxs("label",{className:"directory-setting-row",children:[a.jsxs("span",{children:[a.jsx(Ni,{size:14}),"Extensions to include"]}),a.jsx("input",{value:s,placeholder:".cs, .js, .razor, .css","data-testid":"directory-settings-include",onChange:F=>c(F.target.value)})]}),a.jsxs("label",{className:"directory-setting-row",children:[a.jsxs("span",{children:[a.jsx(Di,{size:14}),"Paths/files to exclude"]}),a.jsx("input",{value:m,placeholder:"bin, obj, .git, node_modules","data-testid":"directory-settings-exclude",onChange:F=>l(F.target.value)})]})]}),a.jsxs("footer",{className:"directory-settings-footer",children:[a.jsx("button",{type:"button","data-testid":"directory-settings-cancel",onClick:o,children:"Cancel"}),a.jsxs("button",{type:"button",className:"is-primary","data-testid":"directory-settings-save",onClick:()=>t(e.id,{DirectoryPath:n.trim(),Include:s.trim(),Exclude:m.trim()}),children:[a.jsx(Ba,{size:15}),"Save"]})]})]})})}const an=[{id:"frame",label:"Frame Perf",icon:Oi},{id:"render",label:"Render Debug",icon:_i},{id:"prompt",label:"Prompt Debug",icon:Fi},{id:"points",label:"Points",icon:Bi},{id:"dev",label:"Dev",icon:Gi}],yo=[{key:"frameProbe",label:"Frame profiler",description:"Tracks local React frame budget and viewport pressure.",defaultValue:!0},{key:"motionGuard",label:"Motion guard",description:"Highlights pan and zoom paths that must stay patch-only.",defaultValue:!0},{key:"overlayAudit",label:"Overlay debug",description:"Checks floating panels, popovers, and result overlays.",defaultValue:!0},{key:"bridgeGate",label:"LocalBridge gate monitor",description:"Keeps hosted loopback access explicit and visible.",defaultValue:!0},{key:"storageTrace",label:"Storage trace",description:"Surfaces local save and restore evidence for this board.",defaultValue:!0}],Hc=[{route:"/code",label:"CodeGraph",description:"Repository graph, agent commands, and code notes."},{route:"/planmaster",label:"PlanMaster",description:"Goal planning, step states, and execution memory."},{route:"/youtube",label:"YouTube Capture",description:"Local YouTube search flow and MindCanvas handoff."},{route:"/company-core",label:"CompanyCore",description:"Company cockpit, approvals, artifacts, and publishing jobs."},{route:"/admin/dashboard",label:"Admin Dashboard",description:"Billing, entitlement, refund, and audit shell."},{route:"/tools",label:"Free Tools",description:"Markdown, note, and clipboard mini workflows."}];function Kc(e,t,o){const n=(0-t.x)/t.scale,r=(0-t.y)/t.scale,s=(o.width-t.x)/t.scale,c=(o.height-t.y)/t.scale;return e.nodes.filter(m=>{const l=m.x+m.width,b=m.y+m.height;return l>=n&&m.x<=s&&b>=r&&m.y<=c}).length}function Xc(e,t){const o=e.trim().split(/\s+/).filter(Boolean).length,n=Math.max(1,Math.ceil(o/120)),r=t==="Deep"?3:t==="Fast"?1:2;return{words:o,estimatedTokens:Math.max(8,Math.ceil(e.length/4)),points:n*r}}function Yc(e,t,o){return[`Board: ${e.name}`,`Nodes: ${e.nodes.length}`,`Edges: ${e.edges.length}`,`Selected: ${t?`${t.title} (${t.kind})`:"none"}`,`Model: ${e.settings.model}`,`Effort: ${e.settings.effort}`,"",o].join(`
44
+ `)}function hu({board:e,selectedNode:t,selectedCount:o,input:n,viewport:r,viewportSize:s,localBridgeState:c,syncStatus:m,syncMessage:l,buildPrompt:b,navigate:k,onClose:x}){const[v,V]=p.useState("frame"),[M,F]=p.useState(""),[J,Z]=p.useState("idle"),[E,ue]=p.useState(null),[B,pe]=p.useState(()=>Object.fromEntries(yo.map(S=>[S.key,S.defaultValue]))),Ce=p.useMemo(()=>Kc(e,r,s),[e,r,s]),g=M||b(),ee=p.useMemo(()=>Xc(g,e.settings.effort),[e.settings.effort,g]),L=p.useMemo(()=>Pl(e),[e,e.settings.aiProvider,e.settings.effort,e.settings.imageRouterImageModel,e.settings.imageRouterVideoModel,e.settings.inputMode,e.settings.model]),Y=an.find(S=>S.id===v)??an[0],Oe=Y.icon;p.useEffect(()=>{if(v!=="points")return;const S=e.settings.inputMode==="Image"?e.settings.imageRouterImageModel:e.settings.inputMode==="Video"?e.settings.imageRouterVideoModel:e.settings.model;h.emit("promptDebug.points.quote",{mode:e.settings.inputMode,model:S??"",billingKind:L.billingKind,displayPoints:L.displayPoints,pricingSource:L.vendorPricingSource??"none",estimatedFromCatalog:L.isEstimatedFromCatalog})},[v,e.settings.imageRouterImageModel,e.settings.imageRouterVideoModel,e.settings.inputMode,e.settings.model,L.billingKind,L.displayPoints,L.isEstimatedFromCatalog,L.vendorPricingSource]);const W=S=>{V(S),h.emit("promptDebug.tab",{tab:S})},Pe=()=>{const S=b();F(S),ue(new Date().toLocaleTimeString()),Z("idle"),h.emit("promptDebug.build",{tab:v,selectedKind:(t==null?void 0:t.kind)??"none",chars:S.length})},_e=async()=>{const S=Yc(e,t,M||b());try{const Q=await An(S);Z("copied"),h.emit("promptDebug.copy",{ok:!0,tab:v,method:Q})}catch(Q){const te=document.querySelector('[data-testid="prompt-debug-preview"]');if(te){te.focus(),te.select(),V("prompt"),Z("selected"),h.emit("promptDebug.copy",{ok:!1,selected:!0,tab:v,message:Q instanceof Error?Q.message:String(Q)});return}Z("failed"),h.emit("promptDebug.copy",{ok:!1,tab:v,message:Q instanceof Error?Q.message:String(Q)})}},be=()=>{F(""),ue(null),Z("idle"),h.emit("promptDebug.clear",{tab:v})},A=S=>{pe(Object.fromEntries(yo.map(Q=>[Q.key,S]))),h.emit("promptDebug.renderToggle",{all:S})},xe=()=>{pe(Object.fromEntries(yo.map(S=>[S.key,S.defaultValue]))),h.emit("promptDebug.renderToggle",{reset:!0})},Fe=(S,Q)=>{pe(te=>({...te,[S]:Q})),h.emit("promptDebug.renderToggle",{key:S,value:Q})};return a.jsx("div",{className:"prompt-debug-backdrop","data-testid":"prompt-debug-dialog",onMouseDown:x,children:a.jsxs("section",{className:"prompt-debug-dialog","aria-label":"Prompt debugger","data-disable-mindcanvas-hotkeys":"true",onMouseDown:S=>S.stopPropagation(),children:[a.jsxs("header",{className:"prompt-debug-header",children:[a.jsxs("div",{children:[a.jsx(Ui,{size:16}),a.jsx("strong",{children:"Prompt Debugger"})]}),a.jsxs("div",{className:"prompt-debug-header__actions",children:[a.jsxs("button",{type:"button",onClick:Pe,"data-testid":"prompt-debug-build",children:[a.jsx(zi,{size:13}),"Build"]}),a.jsxs("button",{type:"button",onClick:_e,"data-testid":"prompt-debug-copy",children:[J==="copied"?a.jsx(Ba,{size:13}):a.jsx(Da,{size:13}),J==="copied"?"Copied":J==="selected"?"Selected":J==="failed"?"Copy failed":"Copy"]}),a.jsxs("button",{type:"button",onClick:be,children:[a.jsx($i,{size:13}),"Clear"]}),a.jsx("button",{type:"button",title:"Close debugger",onClick:x,children:a.jsx(Po,{size:15})})]})]}),a.jsxs("div",{className:"prompt-debug-content",children:[a.jsx("nav",{className:"prompt-debug-tabs","aria-label":"Prompt debugger sections",children:an.map(S=>{const Q=S.icon;return a.jsxs("button",{type:"button",className:v===S.id?"is-active":"","data-testid":`prompt-debug-tab-${S.id}`,onClick:()=>W(S.id),children:[a.jsx(Q,{size:14}),S.label]},S.id)})}),a.jsxs("main",{className:"prompt-debug-main",children:[a.jsxs("div",{className:"prompt-debug-section-title",children:[a.jsx(Oe,{size:15}),a.jsx("strong",{children:Y.label}),a.jsx("span",{children:E?`Built ${E}`:"Local React diagnostics"})]}),v==="frame"&&a.jsxs("div",{className:"prompt-debug-metric-grid",children:[a.jsx(qe,{label:"Nodes",value:e.nodes.length,detail:`${Ce} visible`}),a.jsx(qe,{label:"Edges",value:e.edges.length,detail:`${o} selected`}),a.jsx(qe,{label:"Zoom",value:`${Math.round(r.scale*100)}%`,detail:`${Math.round(r.x)}, ${Math.round(r.y)}`}),a.jsx(qe,{label:"Storage",value:m,detail:l||"Local browser state"}),a.jsx(qe,{label:"Bridge",value:c,detail:"Loopback stays gated on hosted Pages"}),a.jsx(qe,{label:"Selected",value:(t==null?void 0:t.kind)||"none",detail:(t==null?void 0:t.title)||"No selected node"})]}),v==="render"&&a.jsxs("div",{className:"prompt-debug-stack",children:[a.jsxs("div",{className:"prompt-debug-actions",children:[a.jsx("button",{type:"button",onClick:()=>A(!0),children:"Enable all"}),a.jsx("button",{type:"button",onClick:()=>A(!1),children:"Disable all"}),a.jsxs("button",{type:"button",onClick:xe,children:[a.jsx(vo,{size:13}),"Reset"]})]}),yo.map(S=>a.jsxs("label",{className:"prompt-debug-toggle",children:[a.jsxs("span",{children:[a.jsx("strong",{children:S.label}),a.jsx("small",{children:S.description})]}),a.jsx("input",{type:"checkbox",checked:B[S.key]??!1,onChange:Q=>Fe(S.key,Q.target.checked)})]},S.key))]}),v==="prompt"&&a.jsxs("div",{className:"prompt-debug-stack",children:[a.jsxs("div",{className:"prompt-debug-readout",children:[a.jsx("span",{children:"Selected node"}),a.jsx("strong",{children:t?`${t.title} / ${t.kind}`:"No selected node"})]}),a.jsx("textarea",{"data-testid":"prompt-debug-preview",value:M||g,onChange:S=>F(S.target.value),spellCheck:!1})]}),v==="points"&&a.jsxs("div",{className:"prompt-debug-stack",children:[a.jsxs("div",{className:"prompt-debug-metric-grid prompt-debug-metric-grid--small",children:[a.jsx(qe,{label:"Mode",value:e.settings.inputMode,detail:e.settings.aiProvider??"OpenAI Codex"}),a.jsx(qe,{label:"Words",value:ee.words,detail:"Prompt preview"}),a.jsx(qe,{label:"Tokens",value:ee.estimatedTokens,detail:"Local estimate"}),a.jsx(qe,{label:"Points",value:L.displayLabel,detail:L.basisLabel})]}),a.jsxs("div",{className:"prompt-debug-point-quote","data-testid":"prompt-debug-point-quote","data-billing-kind":L.billingKind,"data-pricing-source":L.vendorPricingSource??"none","data-estimated-from-catalog":L.isEstimatedFromCatalog?"true":"false",children:[a.jsx("span",{children:L.billingKind}),a.jsx("strong",{children:L.displayLabel}),a.jsx("small",{children:L.vendorCostUsdSnapshot===void 0?L.vendorPricingSource??"Local provider":`${L.vendorPricingSource??"catalog"} vendor snapshot $${L.vendorCostUsdSnapshot.toFixed(4)}`})]}),a.jsx("div",{className:"prompt-debug-note",children:"Point quote follows the original local PointQuoteService policy. It does not bill credits or call server-side accounting."})]}),v==="dev"&&a.jsx("div",{className:"prompt-debug-dev-grid",children:Hc.map(S=>a.jsxs("button",{type:"button",onClick:()=>{h.emit("promptDebug.devTool.open",{route:S.route}),k(S.route)},children:[a.jsx(Vi,{size:14}),a.jsxs("span",{children:[a.jsx("strong",{children:S.label}),a.jsx("small",{children:S.description})]})]},S.route))})]})]})]})})}function qe({label:e,value:t,detail:o}){return a.jsxs("article",{className:"prompt-debug-card",children:[a.jsx("span",{children:e}),a.jsx("strong",{children:t}),a.jsx("small",{children:o})]})}export{An as $,Wa as A,cd as B,$d as C,qa as D,Cd as E,vd as F,Xd as G,_s as H,eu as I,ru as J,Lt as K,us as L,gs as M,Vd as N,Eo as O,wn as P,cn as Q,uu as R,dn as S,Ao as T,ln as U,ou as V,tu as W,jo as X,Bs as Y,Ie as Z,nu as _,Gd as a,Fs as a0,Zd as a1,_d as a2,mu as a3,js as a4,qd as a5,gu as a6,du as a7,hu as a8,Za as a9,ud as aA,pd as aB,md as aC,gd as aD,hd as aE,sd as aF,ld as aG,id as aH,rd as aI,nd as aJ,ad as aK,Td as aL,fd as aM,bd as aN,yd as aO,kd as aP,td as aQ,ed as aR,od as aS,cu as aa,xd as ab,Qa as ac,Al as ad,Ml as ae,El as af,au as ag,Do as ah,wd as ai,fs as aj,hs as ak,Cn as al,vn as am,rt as an,Sd as ao,Rd as ap,Md as aq,Pd as ar,Ad as as,Ed as at,Ld as au,jd as av,Nd as aw,Dd as ax,Od as ay,dd as az,Bd as b,su as c,zd as d,lu as e,pu as f,j as g,Qd as h,iu as i,es as j,Ds as k,Wd as l,Lo as m,jt as n,Hd as o,tr as p,Os as q,Fd as r,Pt as s,is as t,Yd as u,Jd as v,Ud as w,Kd as x,In as y,Id as z};