mindexec-ai 0.2.385

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 (99) hide show
  1. package/README.md +354 -0
  2. package/codex-runtime.js +1339 -0
  3. package/launch-bridge.cjs +236 -0
  4. package/package.json +77 -0
  5. package/port-guard.cjs +232 -0
  6. package/remote-fast/osx-arm64/mindexec-remote-fast +0 -0
  7. package/remote-fast/osx-arm64/mindexec-remote-fast.deps.json +24 -0
  8. package/remote-fast/osx-arm64/mindexec-remote-fast.dll +0 -0
  9. package/remote-fast/osx-arm64/mindexec-remote-fast.runtimeconfig.json +13 -0
  10. package/remote-fast/osx-x64/mindexec-remote-fast +0 -0
  11. package/remote-fast/osx-x64/mindexec-remote-fast.deps.json +24 -0
  12. package/remote-fast/osx-x64/mindexec-remote-fast.dll +0 -0
  13. package/remote-fast/osx-x64/mindexec-remote-fast.runtimeconfig.json +13 -0
  14. package/remote-fast/win-x64/mindexec-remote-fast.deps.json +24 -0
  15. package/remote-fast/win-x64/mindexec-remote-fast.dll +0 -0
  16. package/remote-fast/win-x64/mindexec-remote-fast.exe +0 -0
  17. package/remote-fast/win-x64/mindexec-remote-fast.runtimeconfig.json +20 -0
  18. package/remote-hub.js +3106 -0
  19. package/scripts/auth-session-smoke.mjs +262 -0
  20. package/scripts/remote-agent-managed-smoke.mjs +291 -0
  21. package/scripts/remote-agent-package-smoke.mjs +64 -0
  22. package/scripts/remote-agent-ws-smoke.mjs +202 -0
  23. package/scripts/remote-fast-live-rate-smoke.mjs +355 -0
  24. package/scripts/remote-fast-mdm-browser-smoke.mjs +476 -0
  25. package/scripts/remote-fleet-render-smoke.mjs +1491 -0
  26. package/scripts/remote-frame-ws-smoke.mjs +234 -0
  27. package/scripts/remote-http-smoke.mjs +592 -0
  28. package/scripts/remote-hub-identity-smoke.mjs +146 -0
  29. package/scripts/remote-hub-scale-smoke.mjs +124 -0
  30. package/scripts/remote-hub-smoke.mjs +631 -0
  31. package/scripts/remote-input-ws-smoke.mjs +263 -0
  32. package/scripts/remote-registry-follower-smoke.mjs +752 -0
  33. package/scripts/setup-tree-sitter-grammars.mjs +80 -0
  34. package/server.js +15709 -0
  35. package/start-bridge.bat +32 -0
  36. package/start-bridge.sh +81 -0
  37. package/tree-sitter-grammars/README.md +18 -0
  38. package/tree-sitter-grammars/tree-sitter-c_sharp.wasm +0 -0
  39. package/tree-sitter-grammars/tree-sitter-go.wasm +0 -0
  40. package/tree-sitter-grammars/tree-sitter-java.wasm +0 -0
  41. package/tree-sitter-grammars/tree-sitter-javascript.wasm +0 -0
  42. package/tree-sitter-grammars/tree-sitter-python.wasm +0 -0
  43. package/tree-sitter-grammars/tree-sitter-rust.wasm +0 -0
  44. package/tree-sitter-grammars/tree-sitter-tsx.wasm +0 -0
  45. package/tree-sitter-grammars/tree-sitter-typescript.wasm +0 -0
  46. package/wwwroot/_headers +73 -0
  47. package/wwwroot/_redirects +1 -0
  48. package/wwwroot/appsettings.json +83 -0
  49. package/wwwroot/assets/AdminDashboardPage-B2vz2Px9.css +1 -0
  50. package/wwwroot/assets/AdminDashboardPage-DnuCHywn.js +1 -0
  51. package/wwwroot/assets/AppSidebar-DU2OgSiv.js +2 -0
  52. package/wwwroot/assets/AuthPages-BrH6kRcv.css +1 -0
  53. package/wwwroot/assets/AuthPages-Dgezl7Vj.js +1 -0
  54. package/wwwroot/assets/CodePage-7kgZlB3O.js +87 -0
  55. package/wwwroot/assets/CodePage-Bncc352E.css +1 -0
  56. package/wwwroot/assets/CompanyCorePage-ChBnq1ve.css +1 -0
  57. package/wwwroot/assets/CompanyCorePage-CzIZIIU_.js +13 -0
  58. package/wwwroot/assets/ExecutionModePage-B-etp_mc.js +18 -0
  59. package/wwwroot/assets/ExecutionModePage-TLuld9l3.css +1 -0
  60. package/wwwroot/assets/LaunchLeadCapture-Bx9LM0IX.js +1 -0
  61. package/wwwroot/assets/LaunchLeadCapture-CiRI1shz.css +1 -0
  62. package/wwwroot/assets/MarketingHome-BsyerRpe.js +1 -0
  63. package/wwwroot/assets/MarketingHome-DPzaYzA_.css +1 -0
  64. package/wwwroot/assets/MindCanvas-DtqOZnoW.css +1 -0
  65. package/wwwroot/assets/MindCanvas-zEDXzaxW.js +49 -0
  66. package/wwwroot/assets/PlanMasterPage-CJ36rep-.css +1 -0
  67. package/wwwroot/assets/PlanMasterPage-NZ_mPvaE.js +4 -0
  68. package/wwwroot/assets/PricingPage-Cg_0i_ZR.css +1 -0
  69. package/wwwroot/assets/PricingPage-Ylrn8l2g.js +1 -0
  70. package/wwwroot/assets/ToolPages-3M2KqA9k.js +28 -0
  71. package/wwwroot/assets/ToolPages-DIB187pZ.css +1 -0
  72. package/wwwroot/assets/YouTubeSearchPage-COv1oAA7.js +4 -0
  73. package/wwwroot/assets/YouTubeSearchPage-IPPa_BIH.css +1 -0
  74. package/wwwroot/assets/app-runtime-xD2Z3NdN.js +1 -0
  75. package/wwwroot/assets/canvas-runtime-BbicBcOj.js +44 -0
  76. package/wwwroot/assets/code-agent-runtime-B5PPZd1t.js +74 -0
  77. package/wwwroot/assets/executionModeSettings-NJqurj-o.js +1 -0
  78. package/wwwroot/assets/index-CQMKCp-t.js +2 -0
  79. package/wwwroot/assets/index-yNpEK-gp.css +1 -0
  80. package/wwwroot/assets/marketingTools-DN_rnHeB.js +4 -0
  81. package/wwwroot/assets/mindCanvasSearchWorker-BzPMsHOB.js +1 -0
  82. package/wwwroot/assets/mindexecution-mindcanvas.png +0 -0
  83. package/wwwroot/assets/mindexecution-prod-home-current.png +0 -0
  84. package/wwwroot/assets/mindexecution-prod-pricing-current.png +0 -0
  85. package/wwwroot/assets/pricingCheckoutShell-O-DnwmbU.js +1 -0
  86. package/wwwroot/assets/productionAdapterConfig-C5jfk6oG.js +1 -0
  87. package/wwwroot/assets/runtimeSettingsPersistenceProjection-BoNWmYjU.js +1 -0
  88. package/wwwroot/assets/storage-TM3YrWaj.js +1 -0
  89. package/wwwroot/assets/supabaseAuthAdapter-DA43DeSY.js +44 -0
  90. package/wwwroot/assets/toolHandoff-D5e5f7t5.js +4 -0
  91. package/wwwroot/assets/vendor-icons-DE3gIReG.js +681 -0
  92. package/wwwroot/assets/vendor-msgpack-BE8aAsr3.js +1 -0
  93. package/wwwroot/assets/vendor-react-BXzpOyCS.js +40 -0
  94. package/wwwroot/favicon.svg +7 -0
  95. package/wwwroot/index.html +22 -0
  96. package/wwwroot/manifest.webmanifest +19 -0
  97. package/wwwroot/robots.txt +4 -0
  98. package/wwwroot/service-worker.js +7 -0
  99. package/wwwroot/sitemap.xml +39 -0
@@ -0,0 +1,44 @@
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 Ci,L as Ti,P as vi,I as _a,U as xi,a as wi,b as Si,X as Eo,K as fa,V as Ri,C as Mi,B as Ai,c as Co,d as Pi,e as Ei,R as xo,f as ln,g as Li,M as Ni,h as Fa,i as Ba,j as Ga,k as Ua,l as ji,m as za,n as Di,o as Oi,F as _i,p as Fi,H as Bi,q as Gi,r as Ui,s as $a,t as zi,G as $i,u as Vi,v as qi,w as Ki,x as Wi,y as Hi,T as Yi,z as Xi}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"}),Va=Object.freeze({frames:"/api/remote/frames/ws",input:"/api/remote/input/ws"});function Qi(e){return Qe.deviceTasksTemplate.replace("{deviceId}",encodeURIComponent(e))}function qa(e){return Wa(e==null?void 0:e.remoteFrameWsPath,Va.frames)}function Ka(e){return Wa(e==null?void 0:e.remoteInputWsPath,Va.input)}function Wa(e,t){return typeof e=="string"?e.trim():t}const Ji="pages";function Zi(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 es(e,t="0"){return`${Zi(e)}/api/status?mindexecOrigin=${Ji}&cb=${encodeURIComponent(t)}`}const tn={},ts="http://127.0.0.1:5147",Ha="MindExec.AllowHostedLocalBridge",os=new Set(["4173","5173"]);function Zt(e){return e.replace(/\/+$/,"")}function ns(){return((tn==null?void 0:tn.VITE_LOCAL_BRIDGE_URL)||"").trim()}function as(){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&&!os.has(o)?n:""}function N(){return Zt(ns()||as()||ts)}function rs(){const e=window.location.hostname.toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"}function is(){try{return window.localStorage.getItem(Ha)==="true"}catch{return!1}}function Ya(e){try{e&&window.localStorage.setItem(Ha,"true")}catch{}}function Et(){return rs()||is()}function Xa(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}}function ss(e){try{const o=new URL(e,window.location.href).hostname.toLowerCase();if(o==="localhost"||o==="::1"||o==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(o))return"loopback"}catch{return}}function vn(e,t){const o=ss(e);return o?{...t,targetAddressSpace:o}:t}async function D(e,t,o={}){const n=new AbortController,r=window.setTimeout(()=>n.abort(),o.timeoutMs??4200),i=new Headers;i.set("Accept","application/json"),o.noCacheHeaders!==!1&&(i.set("Cache-Control","no-store"),i.set("Pragma","no-cache")),o.body!==void 0&&i.set("Content-Type","application/json"),o.auth&&i.set(o.auth.header,o.auth.token);try{const c=/^https?:\/\//i.test(t)?t:`${Zt(e)}${t}`,m=await fetch(c,vn(c,{method:o.method||(o.body===void 0?"GET":"POST"),headers:i,body:o.body===void 0?void 0:JSON.stringify(o.body),cache:"no-store",signal:n.signal})),l=await m.text(),y=l?JSON.parse(l):null;if(!m.ok){const f=(y==null?void 0:y.error)||(y==null?void 0:y.message)||`LocalBridge request failed: ${m.status}`;throw new Error(f)}return y}finally{window.clearTimeout(r)}}function ls(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 xn(e=N()){var t;try{const o=await D(e,es(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=ls(o);return h.emit("localBridge.status",{baseUrl:e,connected:!1,message:n}),{state:"unavailable",baseUrl:e,message:n}}}async function ld(e,t=N()){return D(t,"/api/auth/session",{auth:e,timeoutMs:6500})}async function cd(e,t,o=N()){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 dd(e,t=N()){return h.emit("localBridge.authSession.clear.request",{baseUrl:t}),D(t,"/api/auth/session",{method:"DELETE",auth:e,timeoutMs:6500})}async function ud(e,t,o=N()){return D(o,"/project/open",{method:"POST",body:{path:e},auth:t,timeoutMs:15e3})}async function pd(e=N(),t=18,o=1200){var r,i;let n={state:"idle",baseUrl:e};for(let c=0;c<t;c+=1){if(n=await xn(e),n.state==="connected"&&((i=(r=n.status)==null?void 0:r.project)!=null&&i.isOpen))return n;await new Promise(m=>{window.setTimeout(m,o)})}return n}async function md(e,t=N()){return D(t,"/project/symbols",{auth:e,timeoutMs:12e3})}async function gd(e,t=N()){return D(t,"/project/graph",{auth:e,timeoutMs:12e3})}async function hd(e="standard",t,o=N()){const n=`?level=${encodeURIComponent(e)}`;return D(o,`/project/ai-context${n}`,{auth:t,timeoutMs:14e3})}async function fd(e,t=N()){return h.emit("localBridge.codex.capabilities.request",{baseUrl:t}),D(t,"/api/codex/capabilities",{auth:e,timeoutMs:12e3})}async function bd(e,t=N()){return h.emit("localBridge.modelCatalog.request",{baseUrl:t}),D(t,"/api/model-catalog",{auth:e,timeoutMs:16e3})}async function yd(e,t=5,o,n=N()){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 kd(e,t=6e3,o,n=N()){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 Id(e,t,o=N()){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 Cd(e,t=4e3,o,n=N()){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 Td(e,t="hero",o=3e3,n,r=N()){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 vd(e,t,o=N()){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 xd(e,t,o=N()){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 wd(e,t=N()){return h.emit("localBridge.concept.status.request",{baseUrl:t}),D(t,"/api/concept/status",{method:"GET",auth:e,timeoutMs:12e3})}async function Sd(e,t,o=N()){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 Rd(e,t=N()){return h.emit("localBridge.concept.embed.readiness.request",{baseUrl:t}),D(t,"/api/concept/embed/readiness",{method:"GET",auth:e,timeoutMs:12e3})}async function Md(e,t=N()){return D(t,"/project/close",{method:"POST",auth:e,timeoutMs:12e3})}async function Ad(e=N()){return D(e,"/api/workspace",{timeoutMs:4200})}async function Pd(e,t,o=N()){return D(o,"/api/workspace/browse",{method:"POST",body:{initialPath:e||""},auth:t,timeoutMs:12e4})}async function Ed(e,t,o=N()){return D(o,"/api/workspace/set",{method:"POST",body:{path:e},auth:t,timeoutMs:3e4})}async function Ld(e,t,o=N()){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 Nd(e=N()){return D(e,"/project/change-feed",{timeoutMs:4200})}async function Qa(e,t=N()){return D(t,Qe.status,{auth:e,timeoutMs:4200})}async function cs(e,t=N()){return D(t,Qe.agentStatus,{auth:e,timeoutMs:4200})}async function Ja(e,t=N(),o={}){const n=o.includeDataUrl?"?includeDataUrl=true":"";return D(t,`${Qe.devices}${n}`,{auth:e,timeoutMs:6500})}async function Za(e,t,o=N()){return D(o,Qe.frames,{method:"POST",body:{deviceIds:e,includeThumbnail:!0,includeLive:!0},auth:t,timeoutMs:6500})}async function ba(e,t,o,n=N(),r={}){return D(n,Qe.hostTarget,{method:"POST",body:{nodeId:e,enabled:t,leaseMs:r.leaseMs??6e4},auth:o,timeoutMs:6500})}async function ds(e,t,o=N()){return D(o,Qe.agentConnect,{method:"POST",body:e,auth:t,timeoutMs:3e4})}async function us(e="react-remote-monitor",t,o=N()){return D(o,Qe.agentDisconnect,{method:"POST",body:{reason:e},auth:t,timeoutMs:12e3})}async function er(e,t,o,n=N()){return D(n,Qi(e),{method:"POST",body:t,auth:o,timeoutMs:12e3})}async function ps(e,t,o=N()){return D(o,Qe.taskBatch,{method:"POST",body:e,auth:t,timeoutMs:16e3})}async function jd(e,t=N()){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 Ke(e){return`/api/company-core${e.startsWith("/")?e:`/${e}`}`}async function Dd(e,t=N()){return h.emit("companyCore.bridge.request",{method:"GET",path:"/health"}),D(t,Ke("/health"),{auth:e,timeoutMs:6500})}async function Od(e,t=N()){return h.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies"}),D(t,Ke("/api/companies"),{auth:e,timeoutMs:12e3})}async function _d(e=20,t,o=N()){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,Ke(`/api/company-runs?limit=${n}`),{auth:t,timeoutMs:12e3})}async function Fd(e,t,o=N()){const n=encodeURIComponent(e);return h.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies/:id/snapshot"}),D(o,Ke(`/api/companies/${n}/snapshot`),{auth:t,timeoutMs:12e3})}async function Bd(e,t,o=N()){const n=encodeURIComponent(e);return h.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies/:id/approvals"}),D(o,Ke(`/api/companies/${n}/approvals?pendingOnly=false`),{auth:t,timeoutMs:12e3})}async function Gd(e,t,o=N()){const n=encodeURIComponent(e);return h.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies/:id/artifacts"}),D(o,Ke(`/api/companies/${n}/artifacts`),{auth:t,timeoutMs:12e3})}async function Ud(e,t,o=N()){const n=encodeURIComponent(e);return h.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies/:id/publishing-jobs"}),D(o,Ke(`/api/companies/${n}/publishing-jobs?limit=100`),{auth:t,timeoutMs:12e3})}async function zd(e,t,o=N()){const n=encodeURIComponent(e);return h.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies/:id/growth"}),D(o,Ke(`/api/companies/${n}/growth?limit=100`),{auth:t,timeoutMs:12e3})}async function $d(e,t,o=N()){const n=encodeURIComponent(e);return h.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies/:id/revenue"}),D(o,Ke(`/api/companies/${n}/revenue?limit=100`),{auth:t,timeoutMs:12e3})}async function Vd(e,t,o=N()){const n=encodeURIComponent(e);return h.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies/:id/reflections"}),D(o,Ke(`/api/companies/${n}/reflections?limit=50`),{auth:t,timeoutMs:12e3})}async function qd(e,t,o=N()){return D(o,"/api/codex/thread/run",{method:"POST",body:e,auth:t,timeoutMs:18e4})}async function Kd(e,t=N()){return D(t,"/api/file/read",{method:"POST",body:{path:e},timeoutMs:3e4})}async function Wd(e,t=N()){const o=new AbortController,n=window.setTimeout(()=>o.abort(),3e4);try{const r=`${Zt(t)}/api/file/read-raw?path=${encodeURIComponent(e)}`,i=await fetch(r,vn(r,{method:"GET",headers:{Accept:"application/octet-stream","Cache-Control":"no-store",Pragma:"no-cache"},cache:"no-store",signal:o.signal}));if(!i.ok)throw new Error(`LocalBridge raw file read failed: ${i.status}`);return new Uint8Array(await i.arrayBuffer())}finally{window.clearTimeout(n)}}async function Hd(e,t,o,n=N()){return D(n,"/api/file/write",{method:"POST",body:{path:e,content:t,encoding:"utf8"},auth:o,timeoutMs:3e4})}async function Yd(e,t,o,n=N()){const r=new AbortController,i=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=`${Zt(n)}/api/file/write-raw?path=${encodeURIComponent(e)}`,y=await fetch(l,vn(l,{method:"PUT",headers:c,body:m,cache:"no-store",signal:r.signal})),f=await y.json().catch(()=>null);if(!y.ok){const v=(f==null?void 0:f.error)||(f==null?void 0:f.message)||`LocalBridge raw file write failed: ${y.status}`;throw new Error(v)}return f}finally{window.clearTimeout(i)}}async function Xd(e,t,o=N()){return D(o,"/api/file/delete",{method:"POST",body:{path:e},auth:t,timeoutMs:3e4})}function ms(e,t=N()){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`${Zt(t)}/${n}`}const it="gpt-5.5",gs="gemini-3-flash-preview",hs="llama3",Lo=[{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:hs,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:gs,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"}],fs=new Map([["",it],["openai: gpt-4.1 mini",it],["gpt-4.1 mini",it],["gpt-5.3-codex",it],["gpt-5.2",it],["gpt-5.2-codex",it]]);function Dt(e){const t=String(e??"").trim().replace(/^["']|["']$/g,""),o=t.toLowerCase();return fs.get(o)??t}function bs(e){const t=Dt(e);return t.includes("/")||t.includes(":")}function tr(e,t=Lo){const o=Dt(e);return t.find(n=>n.id===o)??null}function or(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 fo(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 i=o.get(n.option.provider)??Number.MAX_SAFE_INTEGER,c=o.get(r.option.provider)??Number.MAX_SAFE_INTEGER;return i-c||n.index-r.index}).map(({option:n})=>n)}function ys(e,t=Lo){switch(e){case"Local Ollama":return fo(t,["ollama","openrouter"]);case"OpenAI Codex":return fo(t,["codex","openrouter"]);case"Gemini CLI":return fo(t,["gemini-cli"]);case"Managed Cloud":case"BYOK":default:return fo(t,["openrouter"])}}function Qd(...e){const t=new Map;for(const o of e)for(const n of o??[]){const r=Dt(n.id);if(!r)continue;const i=t.get(r);t.set(r,i?{...i,...n,id:r}:{...n,id:r})}return Array.from(t.values())}function ks(e){return e.startsWith("gemini-")?"gemini-cli":e.startsWith("llama")?"ollama":bs(e)?"openrouter":"codex"}function Is(e,t=Lo){const o=e.aiProvider??"OpenAI Codex",n=ys(o,t),r=Dt(e.model);return r&&!n.some(i=>i.id===r)?[{id:r,label:`${r} (custom)`,provider:ks(r)},...n]:n}const wn="gpt-image-2",Sn="google/veo-2",Cs="1:1",Ts="16:9",wo="codex-image:",cn="codex:",vs=["1024x1024","1536x1024","1024x1536"],xs=[{id:"low",label:"Low"},{id:"medium",label:"Mid"},{id:"high",label:"High"}],ws=Lo.filter(e=>e.provider==="codex").flatMap(e=>xs.map(t=>({id:To(e.id,t.id),label:`Codex Image ${t.label} (${e.label})`,provider:"OpenAI Codex",mode:"Image",supportedSizes:vs}))),Ss=[{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"]},...ws],Rs=[{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"]}],nr=[{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}],Rn={id:"auto",label:"Auto",resolvedSize:null,note:"Adapter decides the final render size."},ya=.16;function No(e,t){return(t==null?void 0:t[e])??(e==="Image"?Ss:Rs)}function Jd(e,...t){const o=new Map;for(const n of t)for(const r of n??[]){if(r.mode!==e)continue;const i=Mn(e,r.id);if(!i)continue;const c=o.get(i);o.set(i,c?{...c,...r,id:i,mode:e}:{...r,id:i,mode:e})}return Array.from(o.values())}function Mn(e,t){const o=An(t),n=e==="Image"?wn:Sn;if(!o)return n;if(e==="Image"){const r=As(o);if(r)return r;if(Es(o))return Ns(o)}else{const r=Ps(o);if(r)return r}return Pn(e,o)??o}function dn(e,t,o){const n=e==="Image"?t.imageRouterImageModel:t.imageRouterVideoModel,r=Mn(e,n),i=e==="Image"?wn:Sn,c=No(e,o),m=c.find(l=>l.id===r)??c.find(l=>l.id===i);return m||{id:r??i,label:r??i,provider:"Saved",mode:e,supportedSizes:e==="Image"?["custom"]:[]}}function ar(e,t){if(e.supportedSizes.map(r=>r.toLowerCase()).includes("custom"))return ka(t);const n=e.supportedSizes.map(r=>js(r)).filter(r=>!!r);return n.length>0?n:t==="Image"?ka(t):[Rn]}function un(e,t,o){const n=ar(t,e),r=e==="Image"?Cs:Ts;return n.find(i=>i.id===o)??n.find(i=>i.id===r)??n[0]??Rn}function Ms(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 pn(e){return e.resolvedSize??"auto"}function ka(e){const t=e==="Image"?"Image":"Video";return[Rn,...nr.map(o=>({id:o.id,label:o.label,resolvedSize:o.size,width:o.width,height:o.height,note:`${t} adapter hint: ${o.size}.`}))]}function An(e){return String(e??"").trim().replace(/^["']|["']$/g,"").trim()}function ut(e){return e.trim().toLowerCase().replace(/\s+/g," ")}function As(e){const t=ut(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)?wn:["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":Pn("Image",e)}function Ps(e){const t=ut(e);return["google/veo-2","google veo 2","google/veo2","google veo2","veo-2","veo2"].includes(t)?Sn:Pn("Video",e)}function Pn(e,t){const o=ut(t),n=No(e).find(r=>ut(r.id)===o||ut(r.label)===o);return(n==null?void 0:n.id)??null}function Es(e){const t=ut(e);return t.startsWith(wo)||t.startsWith(cn)||t.startsWith("codex image")}function Ls(e){const t=ut(An(e));return t==="low"?"low":t==="mid"||t==="medium"?"medium":t==="high"?"high":"medium"}function To(e,t){const o=Dt(e)||it;return`${wo}${o}:${Ls(t)}`}function Ns(e,t=it){const o=An(e),n=ut(o);let r="";if(n.startsWith(wo)?r=o.slice(wo.length).trim():n.startsWith(cn)?r=o.slice(cn.length).trim():n.startsWith("codex image")&&(r=o.replace(/^codex\s+image\s*/i,"").trim()),!r)return To(t,"medium");const i=r.lastIndexOf(":");return i>0&&i<r.length-1?To(r.slice(0,i),r.slice(i+1)):To(t,r)}function js(e){const t=Ds(e);if(!t)return null;const o=t.width/t.height,n=nr.map(i=>({definition:i,delta:Math.abs(i.ratio-o)})).sort((i,c)=>i.delta-c.delta)[0];return{id:n&&n.delta<=ya?n.definition.id:`${t.width}:${t.height}`,label:n&&n.delta<=ya?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 Ds(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 Os=[{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"}]}],_s=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}]}]'),Fs={launchers:Os,templates:_s},Ia={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
+
3
+ 1. Three first customer groups
4
+ 2. Urgent problems for each group
5
+ 3. Why this should be solved now`,"template.business-core.node.problem.title":"Problem Definition","template.business-core.node.problem.body":`This board goal is {{businessGoal}}.
6
+ Write problems that can become money, such as cost, time, or risk, not just inconvenience.`,"template.business-core.node.revenue.title":"Revenue Model Candidates","template.business-core.node.revenue.body":"Compare subscription, one-time purchase, credits, and service-bundled models.","template.business-core.node.mvp.title":"MVP Features","template.business-core.node.mvp.body":"Limit the MVP to three or fewer features that solve the core problem.","template.business-core.node.pricing.title":"Pricing Policy","template.business-core.node.pricing.body":"Write free trial, base plan, and upsell points together.","template.business-core.node.first100.title":"First 100 Users Strategy","template.business-core.node.first100.body":"Pick the fastest channel among direct sales, communities, content, and partnerships.","template.business-core.node.plan7.title":"7-Day Execution Plan","template.business-core.node.plan7.body":"Write only the work needed for the next seven days and turn it into an executable schedule.","template.build-core.boardTitle":"Service Build - {{productName}}","template.build-core.input.productName.label":"What are you building?","template.build-core.input.productName.desc":"Write the product name that should appear in the board and nodes.","template.build-core.input.productName.placeholder":"Example: MeetingPilot","template.build-core.input.productGoal.label":"What is the core value of this MVP?","template.build-core.input.productGoal.desc":"Write why users should use this product in one or two sentences.","template.build-core.input.productGoal.placeholder":"Example: Organize action items within 5 minutes after a meeting.","template.build-core.input.stackOpinion.label":"Default build flow","template.build-core.input.stackOpinion.desc":"Choose the implementation flow for the first version.","template.build-core.input.stackOpinion.option.supabase-cloudflare":"Supabase + Cloudflare","template.build-core.input.stackOpinion.option.webapp-default":"Standard web app MVP","template.build-core.input.stackOpinion.option.ai-tooling":"AI-tool centered","template.build-core.node.overview.title":"Service Overview","template.build-core.node.overview.body":`{{productName}}
7
+
8
+ {{productGoal}}`,"template.build-core.node.prd.title":"PRD","template.build-core.node.prd.body":`Product: {{productName}}
9
+ Summarize the problem, user flow, required features, and excluded features on one page.`,"template.build-core.node.prompt.title":"Development Prompt","template.build-core.node.prompt.body":`Draft the implementation prompt you will pass to external dev tools or Codex.
10
+ Default flow: {{stackOpinion}}`,"template.build-core.node.db.title":"DB Design","template.build-core.node.db.body":"Define only the core tables, relationships, and minimum required columns first.","template.build-core.node.auth.title":"Auth / Permissions","template.build-core.node.auth.body":"Write login, role, onboarding, and access-control scenarios.","template.build-core.node.payment.title":"Payment Flow","template.build-core.node.payment.body":"Connect pricing plans, payment success/failure, refunds, and usage limits.","template.build-core.node.deploy.title":"Deployment Checklist","template.build-core.node.deploy.body":"Check environment variables, domain, monitoring, and error tracking readiness.","template.build-core.node.ops.title":"Ops / Customer Support","template.build-core.node.ops.body":"Organize inquiries, refunds, bug reports, and admin dashboard items.","template.build-core.node.qa.title":"Pre-Launch QA","template.build-core.node.qa.body":"Final-check payment, login, onboarding, mobile screens, and recovery scenarios.","template.launch-core.boardTitle":"Marketing Launch - {{productName}}","template.launch-core.input.productName.label":"What are you promoting?","template.launch-core.input.productName.desc":"Write the product or campaign name.","template.launch-core.input.productName.placeholder":"Example: MeetingPilot","template.launch-core.input.targetAudience.label":"Who is the main target?","template.launch-core.input.targetAudience.desc":"Write the representative user group for the message.","template.launch-core.input.targetAudience.placeholder":"Example: startup team leads, solo founders","template.launch-core.input.launchGoal.label":"Goal of this launch","template.launch-core.input.launchGoal.desc":"Choose the board's top priority.","template.launch-core.input.launchGoal.option.signups":"Signup conversion","template.launch-core.input.launchGoal.option.waitlist":"Build a waitlist","template.launch-core.input.launchGoal.option.sales":"Create first payments","template.launch-core.node.positioning.title":"Positioning","template.launch-core.node.positioning.body":`{{productName}}
11
+ Main target: {{targetAudience}}
12
+ Launch goal: {{launchGoal}}`,"template.launch-core.node.landing.title":"Landing Page Copy","template.launch-core.node.landing.body":"Draft the headline, subcopy, CTA, and trust elements quickly.","template.launch-core.node.channelCopy.title":"Channel Copy","template.launch-core.node.channelCopy.body":"Write different copy for Product Hunt, X, LinkedIn, and communities.","template.launch-core.node.community.title":"Community Post","template.launch-core.node.community.body":"Turn it into a problem-solving experience share, not a promotion.","template.launch-core.node.demoChecklist.title":"Demo Video Checklist","template.launch-core.node.demoChecklist.body":"Organize scenes in the order of problem, solution demo, and CTA.","template.launch-core.node.assets.title":"Screenshot Assets","template.launch-core.node.assets.body":"Collect representative screens, comparison scenes, testimonials, and proof images.","template.launch-core.node.schedule.title":"Distribution Schedule","template.launch-core.node.schedule.body":"Write the channels and times to publish today, tomorrow, and within a week.","template.launch-core.node.metrics.title":"Performance Log","template.launch-core.node.metrics.body":"Track visits, signups, payments, and messages that performed well in one place.","template.content-core.boardTitle":"Content Production - {{contentTheme}}","template.content-core.input.contentTheme.label":"What content are we making?","template.content-core.input.contentTheme.desc":"Write the core topic of the video or post.","template.content-core.input.contentTheme.placeholder":"Example: Intro video for an AI meeting summary tool","template.content-core.input.contentChannel.label":"Main channel","template.content-core.input.contentChannel.desc":"Choose the channel to target in the first draft.","template.content-core.input.contentChannel.option.youtube":"YouTube","template.content-core.input.contentChannel.option.shorts":"Shorts / Reels","template.content-core.input.contentChannel.option.blog":"Blog / Article","template.content-core.node.contentPlan.title":"Content Plan","template.content-core.node.contentPlan.body":`{{contentTheme}}
13
+ Main channel: {{contentChannel}}`,"template.content-core.node.script.title":"Script","template.content-core.node.script.body":"Write the opening hook, key points, and CTA.","template.content-core.node.scenes.title":"Scene Structure","template.content-core.node.scenes.body":"Split each scene's message and required visual assets.","template.content-core.node.imagePrompts.title":"Image Prompts","template.content-core.node.imagePrompts.body":"Write image prompts for thumbnails and cutscenes.","template.content-core.node.videoPrompts.title":"Video Prompts","template.content-core.node.videoPrompts.body":"Define camera movement, mood, and duration.","template.content-core.node.distribution.title":"Distribution Check","template.content-core.node.distribution.body":"Check title, description, thumbnail, and upload schedule.","template.learn-core.boardTitle":"Launch-Focused Learning - {{learningGoal}}","template.learn-core.input.learningGoal.label":"What outcome are you learning toward?","template.learn-core.input.learningGoal.desc":"Write the thing you want to build, not just grammar or theory.","template.learn-core.input.learningGoal.placeholder":"Example: launch my first SaaS MVP","template.learn-core.node.goal.title":"Learning Goal","template.learn-core.node.goal.body":"{{learningGoal}}","template.learn-core.node.basics.title":"Core Concepts","template.learn-core.node.basics.body":"Write the concepts and syntax you are missing, then prioritize them.","template.learn-core.node.smallFeature.title":"Build a Small Feature","template.learn-core.node.smallFeature.body":"Break work into feature units small enough to finish.","template.learn-core.node.api.title":"API Usage","template.learn-core.node.api.body":"Organize the APIs to connect and the test scenarios.","template.learn-core.node.dbAuth.title":"DB / Auth","template.learn-core.node.dbAuth.body":"Design the storage structure and login flow simply.","template.learn-core.node.ship.title":"Ship","template.learn-core.node.ship.body":"Write only the minimum checklist needed to deploy.","template.book-core.boardTitle":"Book / Ebook - {{bookTopic}}","template.book-core.input.bookTopic.label":"What book are you making?","template.book-core.input.bookTopic.desc":"Write the topic or draft title.","template.book-core.input.bookTopic.placeholder":"Example: AI execution guide for solo founders","template.book-core.input.readerType.label":"Who is this book for?","template.book-core.input.readerType.desc":"Write the representative reader in one line.","template.book-core.input.readerType.placeholder":"Example: solo founders building their first product","template.book-core.node.bookConcept.title":"Book Concept","template.book-core.node.bookConcept.body":`{{bookTopic}}
14
+ Representative reader: {{readerType}}`,"template.book-core.node.toc.title":"Table of Contents","template.book-core.node.toc.body":"Organize the major chapters and subsection flow first.","template.book-core.node.chapters.title":"Chapter Drafts","template.book-core.node.chapters.body":"Memo the key message and examples by chapter.","template.book-core.node.cover.title":"Illustration / Cover","template.book-core.node.cover.body":"List the visual assets you need.","template.book-core.node.edit.title":"Proofread / Edit","template.book-core.node.edit.body":"Write checkpoints for tone, repetition, flow, and CTA.","template.book-core.node.export.title":"Export","template.book-core.node.export.body":"Finish PDF, EPUB, and distribution channel tasks.","template.music-core.boardTitle":"Music Production - {{trackMood}}","template.music-core.input.trackMood.label":"What mood should the track have?","template.music-core.input.trackMood.desc":"Briefly write the emotion or use case.","template.music-core.input.trackMood.placeholder":"Example: lo-fi focus track for night work","template.music-core.input.musicGenre.label":"Base genre","template.music-core.input.musicGenre.desc":"Choose the closest starting genre.","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":"Music Concept","template.music-core.node.musicConcept.body":`{{trackMood}}
15
+ Base genre: {{musicGenre}}`,"template.music-core.node.references.title":"References","template.music-core.node.references.body":"List reference tracks and what to borrow from each.","template.music-core.node.vocals.title":"Vocals / Instruments","template.music-core.node.vocals.body":"Write the vocal type and core instrument setup.","template.music-core.node.lyrics.title":"Lyrics","template.music-core.node.lyrics.body":"Organize the theme, repeated hook, and banned expressions.","template.music-core.node.generationPrompt.title":"Generation Prompt","template.music-core.node.generationPrompt.body":"Collect audio, structure, and mood instructions.","template.music-core.node.versions.title":"Version Comparison","template.music-core.node.versions.body":"Record mp3 results and revision points."},ko:{"launcher.blank.title":"새 Mind Canvas","launcher.blank.desc":"빈 실행 캔버스를 새로 만듭니다.","launcher.blank.prompt":"생성할 보드를 선택하세요.","launcher.business.title":"비즈니스","launcher.business.desc":"아이디어를 수익 모델, MVP, 실행 계획으로 바꿉니다.","launcher.business.prompt":"어떤 비즈니스 구조로 시작할까요?","launcher.business.option.saas.title":"SaaS","launcher.business.option.saas.desc":"구독형 SaaS 비즈니스","launcher.business.option.mobile.title":"모바일 앱","launcher.business.option.mobile.desc":"모바일 중심 실행 보드","launcher.business.option.automation.title":"AI 자동화","launcher.business.option.automation.desc":"자동화 서비스 구조","launcher.business.option.education.title":"교육 상품","launcher.business.option.education.desc":"코스 또는 강의 사업","launcher.business.option.unknown.title":"아직 모름","launcher.business.option.unknown.desc":"아이디어 탐색 중심","launcher.build.title":"빌드","launcher.build.desc":"PRD, 데이터, 결제, 배포까지 서비스 개발 흐름을 정리합니다.","launcher.build.prompt":"어떤 방식으로 제품을 만들고 싶나요?","launcher.build.option.webapp.title":"웹앱","launcher.build.option.webapp.desc":"웹앱 MVP 빌드","launcher.build.option.saas_mvp.title":"SaaS MVP","launcher.build.option.saas_mvp.desc":"구독형 SaaS 출시","launcher.build.option.aitool.title":"AI 도구","launcher.build.option.aitool.desc":"AI 기반 서비스 구현","launcher.build.option.internal.title":"내부 도구","launcher.build.option.internal.desc":"팀 또는 개인 생산성 도구","launcher.launch.title":"런칭","launcher.launch.desc":"랜딩 카피, 채널 게시물, 일정까지 묶은 런칭 보드를 만듭니다.","launcher.launch.prompt":"어떤 런칭 흐름을 준비할까요?","launcher.launch.option.product_hunt.title":"Product Hunt","launcher.launch.option.product_hunt.desc":"런칭 페이지 준비","launcher.launch.option.social.title":"X / LinkedIn","launcher.launch.option.social.desc":"소셜 런칭 준비","launcher.launch.option.community.title":"커뮤니티","launcher.launch.option.community.desc":"커뮤니티 배포 준비","launcher.launch.option.demo.title":"데모 영상","launcher.launch.option.demo.desc":"데모 자산 준비","launcher.more.title":"더보기","launcher.more.desc":"콘텐츠, 학습, 책, 음악 같은 추가 실행 보드를 엽니다.","launcher.more.prompt":"다음으로 확장할 실행 보드를 골라보세요.","launcher.more.option.content.title":"콘텐츠","launcher.more.option.content.desc":"영상 또는 콘텐츠 제작 시작","launcher.more.option.learn.title":"학습","launcher.more.option.learn.desc":"출시형 학습 보드","launcher.more.option.book.title":"책","launcher.more.option.book.desc":"전자책 또는 스토리 시작","launcher.more.option.music.title":"음악","launcher.more.option.music.desc":"오디오 제작 스튜디오","templateCard.eyebrow":"템플릿","templateCard.generate":"생성","templateCard.noInputs":"필요한 입력이 없습니다.","templateCard.generating":"노드를 생성하는 중...","templateCard.generated":"아래에 노드 {0}개를 생성했습니다.","templateCard.failed":"템플릿 생성에 실패했습니다.","templateCard.required":"{0} 항목을 입력하세요."},ja:{"launcher.blank.title":"新しいMind Canvas","launcher.blank.desc":"空の実行キャンバスを作成します。","launcher.blank.prompt":"作成するボードを選んでください。","launcher.business.title":"ビジネス","launcher.business.desc":"アイデアを収益モデル、MVP、実行計画に変換します。","launcher.business.prompt":"どのビジネス構造から始めますか?","launcher.business.option.saas.title":"SaaS","launcher.business.option.saas.desc":"サブスクリプション型SaaSビジネス","launcher.business.option.mobile.title":"モバイルアプリ","launcher.business.option.mobile.desc":"モバイル中心の実行ボード","launcher.business.option.automation.title":"AI自動化","launcher.business.option.automation.desc":"自動化サービス構造","launcher.business.option.education.title":"教育商品","launcher.business.option.education.desc":"コースまたは講座ビジネス","launcher.business.option.unknown.title":"まだ未定","launcher.business.option.unknown.desc":"可能性のあるアイデアを探索","launcher.build.title":"ビルド","launcher.build.desc":"PRD、データ、課金、デプロイまでサービス構築を整理します。","launcher.build.prompt":"どのようなプロダクトを作りますか?","launcher.build.option.webapp.title":"Webアプリ","launcher.build.option.webapp.desc":"Web MVPを構築","launcher.build.option.saas_mvp.title":"SaaS MVP","launcher.build.option.saas_mvp.desc":"サブスクリプションSaaSを立ち上げ","launcher.build.option.aitool.title":"AIツール","launcher.build.option.aitool.desc":"AI活用サービスを実装","launcher.build.option.internal.title":"内部ツール","launcher.build.option.internal.desc":"チームまたは個人の生産性ツール","launcher.launch.title":"ローンチ","launcher.launch.desc":"ランディングコピー、投稿、素材、スケジュールを準備します。","launcher.launch.prompt":"どのローンチフローを準備しますか?","launcher.launch.option.product_hunt.title":"Product Hunt","launcher.launch.option.product_hunt.desc":"ローンチページを準備","launcher.launch.option.social.title":"X / LinkedIn","launcher.launch.option.social.desc":"ソーシャル投稿を計画","launcher.launch.option.community.title":"コミュニティ","launcher.launch.option.community.desc":"コミュニティ配信を計画","launcher.launch.option.demo.title":"デモ動画","launcher.launch.option.demo.desc":"デモ素材を準備","launcher.more.title":"その他","launcher.more.desc":"コンテンツ、学習、本、音楽の実行ボードを開きます。","launcher.more.prompt":"次の実行ボードを選んでください。","launcher.more.option.content.title":"コンテンツ","launcher.more.option.content.desc":"動画またはコンテンツ制作を開始","launcher.more.option.learn.title":"学習","launcher.more.option.learn.desc":"ローンチ重視の学習ボードを作成","launcher.more.option.book.title":"本","launcher.more.option.book.desc":"電子書籍または物語ボードを開始","launcher.more.option.music.title":"音楽","launcher.more.option.music.desc":"音声制作スタジオを開始","templateCard.eyebrow":"テンプレート","templateCard.generate":"生成","templateCard.noInputs":"入力は不要です。","templateCard.generating":"ノードを生成中...","templateCard.generated":"下に{0}個のノードを生成しました。","templateCard.failed":"テンプレート生成に失敗しました。","templateCard.required":"{0}を入力してください。","template.blank-core.boardTitle":"キャンバス {{timestampShort}}","template.business-core.boardTitle":"ビジネス設計 - {{optionLabel}}","template.business-core.input.businessIdea.label":"どんなビジネスを作りたいですか?","template.business-core.input.businessIdea.desc":"解決したい問題とアイデアを1〜2文で書いてください。","template.business-core.input.businessIdea.placeholder":"例: 会議メモを要約し、次の作業を自動で割り当てるSaaS","template.business-core.input.targetUser.label":"主な顧客は誰ですか?","template.business-core.input.targetUser.desc":"最初に支払う可能性が高いユーザー層を書いてください。","template.business-core.input.targetUser.placeholder":"例: スタートアップのチームリード、フリーランス運営者","template.business-core.input.businessGoal.label":"このボードの目標","template.business-core.input.businessGoal.desc":"まず解決したい目標を選んでください。","template.business-core.input.businessGoal.option.validate":"アイデア検証","template.business-core.input.businessGoal.option.mvp":"MVP設計","template.business-core.input.businessGoal.option.monetize":"収益化設計","template.business-core.node.idea.title":"事業アイデア","template.business-core.node.idea.body":"{{businessIdea}}","template.business-core.node.target.title":"ターゲット顧客","template.business-core.node.target.body":`最初の顧客候補: {{targetUser}}
16
+
17
+ 1. 最初の顧客層を3つ
18
+ 2. 各顧客の切実な問題
19
+ 3. なぜ今解決すべきか`,"template.business-core.node.problem.title":"問題定義","template.business-core.node.problem.body":`今回の目標は{{businessGoal}}です。
20
+ 単なる不便ではなく、コスト、時間、リスクのようにお金につながる問題を書いてください。`,"template.business-core.node.revenue.title":"収益モデル候補","template.business-core.node.revenue.body":"サブスク、買い切り、クレジット、サービス同梱モデルを比較してください。","template.business-core.node.mvp.title":"MVP機能","template.business-core.node.mvp.body":"中核問題を解決する機能だけを3つ以下に絞ってください。","template.business-core.node.pricing.title":"価格設計","template.business-core.node.pricing.body":"無料トライアル、基本プラン、アップセルポイントを一緒に書いてください。","template.business-core.node.first100.title":"最初の100人戦略","template.business-core.node.first100.body":"直接販売、コミュニティ、コンテンツ、提携の中で最速のチャネルを選んでください。","template.business-core.node.plan7.title":"7日実行計画","template.business-core.node.plan7.body":"今日から7日間に必要な作業だけを実行できる日程にしてください。","template.build-core.boardTitle":"サービス開発 - {{productName}}","template.build-core.input.productName.label":"何を作っていますか?","template.build-core.input.productName.desc":"ボードとノードに表示する製品名を書いてください。","template.build-core.input.productName.placeholder":"例: MeetingPilot","template.build-core.input.productGoal.label":"このMVPの中核価値は何ですか?","template.build-core.input.productGoal.desc":"ユーザーがこの製品を使う理由を1〜2文で書いてください。","template.build-core.input.productGoal.placeholder":"例: 会議後5分以内に実行項目を整理する。","template.build-core.input.stackOpinion.label":"基本ビルド方針","template.build-core.input.stackOpinion.desc":"初版で進める実装フローを選んでください。","template.build-core.input.stackOpinion.option.supabase-cloudflare":"Supabase + Cloudflare","template.build-core.input.stackOpinion.option.webapp-default":"標準WebアプリMVP","template.build-core.input.stackOpinion.option.ai-tooling":"AIツール中心","template.build-core.node.overview.title":"サービス概要","template.build-core.node.overview.body":`{{productName}}
21
+
22
+ {{productGoal}}`,"template.build-core.node.prd.title":"PRD","template.build-core.node.prd.body":`製品: {{productName}}
23
+ 問題、ユーザーフロー、必須機能、除外機能を1ページにまとめてください。`,"template.build-core.node.prompt.title":"開発プロンプト","template.build-core.node.prompt.body":`外部開発ツールやCodexに渡す実装プロンプトの下書きを作ってください。
24
+ 基本方針: {{stackOpinion}}`,"template.build-core.node.db.title":"DB設計","template.build-core.node.db.body":"中核テーブル、関係、最小必須カラムだけを先に定義してください。","template.build-core.node.auth.title":"Auth / 権限","template.build-core.node.auth.body":"ログイン、役割、オンボーディング、アクセス制御のシナリオを書いてください。","template.build-core.node.payment.title":"決済フロー","template.build-core.node.payment.body":"料金プラン、決済成功/失敗、返金、利用制限までつなげてください。","template.build-core.node.deploy.title":"デプロイチェックリスト","template.build-core.node.deploy.body":"環境変数、ドメイン、監視、エラー追跡の準備状態を確認してください。","template.build-core.node.ops.title":"運用 / 顧客対応","template.build-core.node.ops.body":"問い合わせ、返金、バグ報告、管理画面項目を整理してください。","template.build-core.node.qa.title":"ローンチ前QA","template.build-core.node.qa.body":"決済、ログイン、オンボーディング、モバイル画面、復旧シナリオを最終点検してください。","template.launch-core.boardTitle":"マーケティングローンチ - {{productName}}","template.launch-core.input.productName.label":"何を宣伝しますか?","template.launch-core.input.productName.desc":"製品名またはキャンペーン名を書いてください。","template.launch-core.input.productName.placeholder":"例: MeetingPilot","template.launch-core.input.targetAudience.label":"主なターゲットは誰ですか?","template.launch-core.input.targetAudience.desc":"メッセージを合わせる代表ユーザー層を書いてください。","template.launch-core.input.targetAudience.placeholder":"例: スタートアップのチームリード、ソロ創業者","template.launch-core.input.launchGoal.label":"このローンチの目標","template.launch-core.input.launchGoal.desc":"ボードで最優先に助けたい目標を選んでください。","template.launch-core.input.launchGoal.option.signups":"登録転換","template.launch-core.input.launchGoal.option.waitlist":"待機リスト獲得","template.launch-core.input.launchGoal.option.sales":"最初の支払いを作る","template.launch-core.node.positioning.title":"ポジショニング","template.launch-core.node.positioning.body":`{{productName}}
25
+ 主なターゲット: {{targetAudience}}
26
+ 今回の目標: {{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":"今日、明日、1週間以内に配信するチャネルと時間を書いてください。","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}}
27
+ 主なチャネル: {{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":"代表的な読者層を1行で書いてください。","template.book-core.input.readerType.placeholder":"例: 最初の製品を作るソロ創業者","template.book-core.node.bookConcept.title":"本のコンセプト","template.book-core.node.bookConcept.body":`{{bookTopic}}
28
+ 代表読者: {{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":"例: 夜作業用のローファイ集中トラック","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}}
29
+ 基本ジャンル: {{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結果と修正ポイントを記録してください。"},zh:{"launcher.blank.title":"新 Mind Canvas","launcher.blank.desc":"创建一个干净的执行画布。","launcher.blank.prompt":"选择要创建的看板。","launcher.business.title":"业务","launcher.business.desc":"把想法转成收入模型、MVP 和执行计划。","launcher.business.prompt":"从哪种业务结构开始?","launcher.business.option.saas.title":"SaaS","launcher.business.option.saas.desc":"订阅式 SaaS 业务","launcher.business.option.mobile.title":"移动应用","launcher.business.option.mobile.desc":"移动优先的执行看板","launcher.business.option.automation.title":"AI 自动化","launcher.business.option.automation.desc":"自动化服务结构","launcher.business.option.education.title":"教育产品","launcher.business.option.education.desc":"课程或讲座业务","launcher.business.option.unknown.title":"尚不确定","launcher.business.option.unknown.desc":"探索可能的想法","launcher.build.title":"构建","launcher.build.desc":"整理从 PRD、数据、计费到部署的服务构建流程。","launcher.build.prompt":"要构建哪类产品?","launcher.build.option.webapp.title":"Web 应用","launcher.build.option.webapp.desc":"构建 Web MVP","launcher.build.option.saas_mvp.title":"SaaS MVP","launcher.build.option.saas_mvp.desc":"发布订阅式 SaaS","launcher.build.option.aitool.title":"AI 工具","launcher.build.option.aitool.desc":"实现 AI 驱动服务","launcher.build.option.internal.title":"内部工具","launcher.build.option.internal.desc":"团队或个人生产力工具","launcher.launch.title":"发布","launcher.launch.desc":"规划落地页文案、渠道内容、素材和发布日程。","launcher.launch.prompt":"要准备哪种发布流程?","launcher.launch.option.product_hunt.title":"Product Hunt","launcher.launch.option.product_hunt.desc":"准备发布页面","launcher.launch.option.social.title":"X / LinkedIn","launcher.launch.option.social.desc":"规划社交发布内容","launcher.launch.option.community.title":"社区","launcher.launch.option.community.desc":"规划社区分发","launcher.launch.option.demo.title":"演示视频","launcher.launch.option.demo.desc":"准备演示素材","launcher.more.title":"更多","launcher.more.desc":"打开内容、学习、书籍和音乐执行看板。","launcher.more.prompt":"选择下一个执行看板。","launcher.more.option.content.title":"内容","launcher.more.option.content.desc":"开始视频或内容制作","launcher.more.option.learn.title":"学习","launcher.more.option.learn.desc":"创建面向发布的学习看板","launcher.more.option.book.title":"书籍","launcher.more.option.book.desc":"开始电子书或故事看板","launcher.more.option.music.title":"音乐","launcher.more.option.music.desc":"开始音频制作工作室","templateCard.eyebrow":"模板","templateCard.generate":"生成","templateCard.noInputs":"无需输入。","templateCard.generating":"正在生成节点...","templateCard.generated":"已在下方生成 {0} 个节点。","templateCard.failed":"模板生成失败。","templateCard.required":"请填写 {0}。","template.blank-core.boardTitle":"画布 {{timestampShort}}","template.business-core.boardTitle":"业务设计 - {{optionLabel}}","template.business-core.input.businessIdea.label":"你想做什么业务?","template.business-core.input.businessIdea.desc":"用一两句话写下要解决的问题和想法。","template.business-core.input.businessIdea.placeholder":"例如:自动总结会议并分配后续任务的 SaaS","template.business-core.input.targetUser.label":"主要客户是谁?","template.business-core.input.targetUser.desc":"写下最可能首先付费的用户群。","template.business-core.input.targetUser.placeholder":"例如:创业团队负责人、自由职业运营者","template.business-core.input.businessGoal.label":"本看板目标","template.business-core.input.businessGoal.desc":"选择现在最想先解决的目标。","template.business-core.input.businessGoal.option.validate":"验证想法","template.business-core.input.businessGoal.option.mvp":"设计 MVP","template.business-core.input.businessGoal.option.monetize":"设计变现","template.business-core.node.idea.title":"业务想法","template.business-core.node.idea.body":"{{businessIdea}}","template.business-core.node.target.title":"目标客户","template.business-core.node.target.body":`首批客户候选:{{targetUser}}
30
+
31
+ 1. 三类首批客户
32
+ 2. 每类客户的紧急问题
33
+ 3. 为什么现在必须解决`,"template.business-core.node.problem.title":"问题定义","template.business-core.node.problem.body":`本次目标是 {{businessGoal}}。
34
+ 请写能带来收入的问题,例如成本、时间或风险,而不只是一般不便。`,"template.business-core.node.revenue.title":"收入模型候选","template.business-core.node.revenue.body":"比较订阅、一次性购买、积分和服务捆绑模型。","template.business-core.node.mvp.title":"MVP 功能","template.business-core.node.mvp.body":"只保留能解决核心问题的三个以内功能。","template.business-core.node.pricing.title":"定价策略","template.business-core.node.pricing.body":"一起写下免费试用、基础套餐和追加销售点。","template.business-core.node.first100.title":"首批 100 人策略","template.business-core.node.first100.body":"从直销、社区、内容和合作中选择最快渠道。","template.business-core.node.plan7.title":"7 天执行计划","template.business-core.node.plan7.body":"只写从今天起 7 天内需要做的事,并整理成可执行日程。","template.build-core.boardTitle":"服务开发 - {{productName}}","template.build-core.input.productName.label":"你正在做什么?","template.build-core.input.productName.desc":"写下会显示在看板和节点上的产品名。","template.build-core.input.productName.placeholder":"例如:MeetingPilot","template.build-core.input.productGoal.label":"这个 MVP 的核心价值是什么?","template.build-core.input.productGoal.desc":"用一两句话写出用户为什么要使用它。","template.build-core.input.productGoal.placeholder":"例如:会议后 5 分钟内整理行动项。","template.build-core.input.stackOpinion.label":"默认开发流程","template.build-core.input.stackOpinion.desc":"选择第一版要采用的实现流程。","template.build-core.input.stackOpinion.option.supabase-cloudflare":"Supabase + Cloudflare","template.build-core.input.stackOpinion.option.webapp-default":"标准 Web App MVP","template.build-core.input.stackOpinion.option.ai-tooling":"AI 工具优先","template.build-core.node.overview.title":"服务概要","template.build-core.node.overview.body":`{{productName}}
35
+
36
+ {{productGoal}}`,"template.build-core.node.prd.title":"PRD","template.build-core.node.prd.body":`产品:{{productName}}
37
+ 把问题、用户流程、必需功能和排除功能整理成一页。`,"template.build-core.node.prompt.title":"开发提示词","template.build-core.node.prompt.body":`起草要交给外部开发工具或 Codex 的实现提示词。
38
+ 默认流程:{{stackOpinion}}`,"template.build-core.node.db.title":"DB 设计","template.build-core.node.db.body":"先定义核心表、关系和最少必需字段。","template.build-core.node.auth.title":"Auth / 权限","template.build-core.node.auth.body":"写下登录、角色、引导和访问控制场景。","template.build-core.node.payment.title":"支付流程","template.build-core.node.payment.body":"连接套餐、支付成功/失败、退款和用量限制。","template.build-core.node.deploy.title":"部署检查清单","template.build-core.node.deploy.body":"确认环境变量、域名、监控和错误追踪准备情况。","template.build-core.node.ops.title":"运营 / 客服","template.build-core.node.ops.body":"整理咨询、退款、Bug 报告和管理后台项目。","template.build-core.node.qa.title":"上线前 QA","template.build-core.node.qa.body":"最终检查支付、登录、引导、移动端页面和错误恢复场景。","template.launch-core.boardTitle":"营销发布 - {{productName}}","template.launch-core.input.productName.label":"你要推广什么?","template.launch-core.input.productName.desc":"写下产品名或活动名。","template.launch-core.input.productName.placeholder":"例如:MeetingPilot","template.launch-core.input.targetAudience.label":"主要目标是谁?","template.launch-core.input.targetAudience.desc":"写下消息要面向的代表用户群。","template.launch-core.input.targetAudience.placeholder":"例如:创业团队负责人、独立创始人","template.launch-core.input.launchGoal.label":"本次发布目标","template.launch-core.input.launchGoal.desc":"选择看板最优先支持的目标。","template.launch-core.input.launchGoal.option.signups":"注册转化","template.launch-core.input.launchGoal.option.waitlist":"建立等待名单","template.launch-core.input.launchGoal.option.sales":"获得首批付款","template.launch-core.node.positioning.title":"定位","template.launch-core.node.positioning.body":`{{productName}}
39
+ 主要目标:{{targetAudience}}
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
+ 主要渠道:{{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
+ 代表读者:{{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 结果和修改点。"}},Te={studioNodeType:"studioNodeType",templateNodeId:"templateNodeId",templateRole:"templateRole",compileTarget:"compileTarget",inputKey:"inputKey",inputType:"inputType",inputDescription:"inputDescription",inputPlaceholder:"inputPlaceholder",inputDefaultValue:"inputDefaultValue",inputRequired:"inputRequired",inputOptions:"inputOptions"},Bs=[{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"],K={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},pt=Fs,Gs=new Set(["en","ko","ja","zh"]);function kt(e){if(typeof e!="string")return"en";const t=e.trim().toLowerCase();return!t||t==="auto"?"en":Gs.has(t)?t:"en"}function le(e,t="",o){const n=kt(o),r=Ia[n],i=Ia.en,c=r[e];if(c!==void 0)return c;const m=i[e];return n!=="ko"&&m!==void 0?m:t}function eo(e,t){const o=Xe(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=>el(e.id,n,t))}}function Yt(e,t){const o=Xe(e.id);return{...e,boardTitle:le(`template.${o}.boardTitle`,e.boardTitle,t),inputs:e.inputs.map(n=>tl(e.id,n,t)),nodes:e.nodes.map(n=>ol(e.id,n,t))}}function eu(e){return pt.launchers.map(t=>eo(t,e))}function Us(e,t){const o=pt.launchers.find(n=>Y(n.id,e));return o?eo(o,t):null}function jo(e,t){if(e.options.length!==0)return e.options.find(o=>Y(o.id,t||""))??e.options[0]}function zs(e,t,o){const n=jo(e,t),r=(n==null?void 0:n.templateId)||e.quickCreateTemplateId||"",i=pt.templates.find(c=>Y(c.id,r));return i?Yt(i,o):null}function tu(e){const t={};for(const o of(e==null?void 0:e.inputs)??[])t[o.key]=Ln(o);return t}function ou(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=kt(n.appLanguage),i=eo(e,r),c=jo(i,t),m=zs(i,c==null?void 0:c.id,r);return m?Vs(i,c,m,o,n):null}function Vs(e,t,o,n,r){const i=Oo(o,n),c=lr(e,t,i),m=new Date().toISOString(),l=ur("template-board"),y=Lt(o.boardTitle,c).trim()||e.label,f=o.nodes.map((v,x)=>Ks(v,e,t,o,c,l,x));return{launcher:e,option:t,template:o,board:{id:l,name:y,updatedAt:m,settings:r,source:{kind:"localStorage",loadedAt:m},nodes:f,edges:[]}}}function rr(e,t,o={},n){const r=kt(n),i=eo(e,r),c=nl(r),m=cl(i,t),l={launcherId:i.id,title:i.label,description:i.description,prompt:i.prompt,iconClass:i.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(i.options.length===0){const f=i.quickCreateTemplateId?pt.templates.find(v=>Y(v.id,e.quickCreateTemplateId)):null;if(f){const v=Yt(f,r);l.options.push({id:"",label:i.label,description:i.description,templateId:v.id,inputs:mn(v.inputs)})}}else for(const f of i.options){const v=pt.templates.find(G=>Y(G.id,f.templateId)),x=v?Yt(v,r):null;l.options.push({id:f.id,label:f.label,description:f.description,templateId:f.templateId,inputs:mn((x==null?void 0:x.inputs)??[])})}const y=l.options.find(f=>Y(f.id,l.selectedOptionId))??l.options[0];return l.selectedOptionId=y==null?void 0:y.id,l.inputValues=cr((y==null?void 0:y.inputs)??[],o),l}function nu(e,t,o,n,r={},i){const c=kt(i),m=rr(e,t,r,c),l=m.options.find(f=>Y(f.id,m.selectedOptionId)),y={[K.semanticTypeKey]:K.semanticTypeValue,[K.launcherIdKey]:e.id,[K.selectedOptionIdKey]:m.selectedOptionId??"",[K.cardVersionKey]:"1.0",[K.cardLockedKey]:"True",[K.localizationLanguageKey]:c,IsNew:"true"};return{id:ur("template-card"),kind:"template-launcher",title:m.title,body:JSON.stringify(m),x:o,y:n,width:K.width,height:K.height,tags:["Template","Launcher",e.label,l==null?void 0:l.label].filter(f=>!!f),metadata:y,aiEnabled:!1}}function En(e){var t;return e?e.kind==="template-launcher"?!0:Y((t=e.metadata)==null?void 0:t[K.semanticTypeKey],K.semanticTypeValue):!1}function ir(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:mn(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 au(e,t){const o=e.options.find(n=>Y(n.id,t))??e.options[0];return{...e,selectedOptionId:o==null?void 0:o.id,inputValues:cr((o==null?void 0:o.inputs)??[],e.inputValues)}}function ru(e,t,o){return{...e,inputValues:{...e.inputValues,[t]:o}}}function iu(e){if(!e)return"Template card payload is unavailable.";const t=e.options.find(n=>Y(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?ll(e.requiredMessageFormat||"{0} is required.",o.label):null}function su(e,t,o,n,r=dl()){var Q;if(!En(e))return null;const i=(Q=e.metadata)==null?void 0:Q[K.launcherIdKey],c=kt(n.appLanguage),m=i?Us(i,c):null;if(!m)return null;const l=jo(m,t),y=$s(m,(l==null?void 0:l.id)??null,o,n);if(!y)return null;const f=Oo(y.template,o),v=JSON.stringify(f),x=Math.min(...y.board.nodes.map(V=>V.x)),G=Math.min(...y.board.nodes.map(V=>V.y)),M=e.x,O=e.y+Math.max(e.height,K.height)+K.resultTopGap,I=y.board.nodes.map(V=>({...V,x:M+(V.x-x),y:O+(V.y-G),metadata:{...V.metadata??{},[K.controllerNodeIdKey]:e.id,[K.runIdKey]:r,[K.cardGeneratedKey]:"True",[K.localizationManagedKey]:"True",[K.localizationLanguageKey]:c,[K.sourceInputValuesJsonKey]:v}}));return{launcher:m,option:y.option,template:y.template,runId:r,nodes:I}}function lu(e,t){const o=kt(t),n=new Map(e.map(c=>[c.id,c]));let r=!1;const i=e.map(c=>{const m=al(c,o);if(m)return r=!0,m;const l=rl(c,n,o);return l?(r=!0,l):c});return{nodes:r?i:e,changed:r,language:o}}function cu(e){const t=String(e||"").trim()||"Template Studio Draft";return{templateId:Do(t),templateTitle:t,category:"custom",boardTitle:t,version:"0.1.0",tier:"draft",status:"draft"}}function du(e,t){const o=[],n=Ws(e),r=t.filter(f=>!!ve(f,Te.studioNodeType)).sort((f,v)=>f.y-v.y||f.x-v.x||f.id.localeCompare(v.id)),i=r.filter(f=>Y(ve(f,Te.studioNodeType),"template.input")),c=r.filter(f=>!Y(ve(f,Te.studioNodeType),"template.input")),m=Hs(i,o),l=Ys(c,o);r.length===0&&o.push({code:"studio.nodes.empty",message:"Add at least one Template Studio node before compiling."});const y={id:n.templateId,version:n.version,tier:n.tier,status:n.status,boardTitle:n.boardTitle,inputs:m,nodes:l};return Xs(y,o),{template:y,manifestJson:JSON.stringify(y,null,2),issues:o}}function Do(e){return String(e||"").trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"template-studio-draft"}function qs(e,t){switch(String(e||"").trim().toLowerCase()||sr(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?dr(t.kind):"note"}}function sr(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 uu(e){const t=Bs.find(o=>Y(o.studioNodeType,e));return(t==null?void 0:t.shortLabel)??"Note"}function Ks(e,t,o,n,r,i,c){const m={};for(const[y,f]of Object.entries(e.metadata??{}))m[y]=Lt(f,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=ul(e.contentType);return{id:`${i}-${e.id||c}`,kind:l,title:Lt(e.title,r),body:Lt(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 Oo(e,t){const o={};for(const n of e.inputs){const r=String(t[n.key]??"").trim();o[n.key]=r||Ln(n)}return o}function lr(e,t,o){const n=(t==null?void 0:t.label)||e.label,r=(t==null?void 0:t.description)||e.description,i={launcherId:e.id,launcherLabel:e.label,launcherDescription:e.description,optionId:(t==null?void 0:t.id)||"",optionLabel:n,optionDescription:r,selectionLabel:n,timestampShort:pl(new Date)};for(const[c,m]of Object.entries(o))i[c]=m;return i}function Lt(e,t){let o=e||"";for(const[n,r]of Object.entries(t))o=o.replace(new RegExp(`{{\\s*${ml(n)}\\s*}}`,"gi"),r);return o}function Ln(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 Ws(e){const t=String(e.templateTitle||"").trim()||"Template Studio Draft";return{templateId:Do(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 Hs(e,t){const o=[],n=new Set;for(const r of e){const i=r.title.trim()||"Input",c=Do(ve(r,Te.inputKey)||i),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,Te.inputType)),label:i,description:ve(r,Te.inputDescription)||r.body,placeholder:ve(r,Te.inputPlaceholder),defaultValue:ve(r,Te.inputDefaultValue),required:Js(ve(r,Te.inputRequired)),options:Zs(ve(r,Te.inputOptions))})}return o}function Ys(e,t){const o=[],n=new Set;for(const r of e){const i=ve(r,Te.studioNodeType)||sr(r);let c=Do(ve(r,Te.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,Te.compileTarget)||qs(i,r),y=ve(r,Te.templateRole)||i.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:y,studioNodeType:i,compileTarget:l,studioSourceContentType:dr(r.kind)}})}return o}function Xs(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 Js(e){return e.trim().toLowerCase()==="true"}function Zs(e){const t=[];for(const o of e.split(/\r?\n/)){const n=o.trim();if(!n)continue;const[r,i]=n.split("|",2).map(c=>c.trim());r&&t.push({value:r,label:i||r})}return t}function el(e,t,o){const n=Xe(e),r=Xe(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 tl(e,t,o){var i;const n=Xe(e),r=Xe(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:(i=t.options)==null?void 0:i.map(c=>({...c,label:le(`template.${n}.input.${r}.option.${Xe(c.value)}`,c.label,o)}))}}function ol(e,t,o){const n=Xe(e),r=Xe(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 nl(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 al(e,t){var m,l,y,f;if(!En(e))return null;const o=ir(e.body),n=((m=e.metadata)==null?void 0:m[K.launcherIdKey])||(o==null?void 0:o.launcherId),r=n?pt.launchers.find(v=>Y(v.id,n)):null;if(!r)return null;const i=(o==null?void 0:o.selectedOptionId)||((l=e.metadata)==null?void 0:l[K.selectedOptionIdKey])||null,c=rr(r,i,(o==null?void 0:o.inputValues)??{},t);return e.title===c.title&&e.body===JSON.stringify(c)&&((y=e.metadata)==null?void 0:y[K.localizationLanguageKey])===t?null:{...e,title:c.title,body:JSON.stringify(c),tags:["Template","Launcher",c.title,(f=c.options.find(v=>v.id===c.selectedOptionId))==null?void 0:f.label].filter(v=>!!v),metadata:{...e.metadata??{},[K.launcherIdKey]:r.id,[K.selectedOptionIdKey]:c.selectedOptionId??"",[K.localizationLanguageKey]:t}}}function rl(e,t,o){if(En(e))return null;const n=bo(Be(e,"sourceTemplateId"),Be(e,"templateId")),r=bo(Be(e,"sourceTemplateNodeId"),Be(e,"templateNodeId")),i=bo(Be(e,"sourceLauncherId"),Be(e,"templateLauncher"));if(!n||!r||!i)return null;const c=pt.launchers.find(Q=>Y(Q.id,i)),m=pt.templates.find(Q=>Y(Q.id,n));if(!c||!m)return null;const l=bo(Be(e,"sourceOptionId"),Be(e,"templateOption")),y=il(e,t),f=Oo(Yt(m,o),y),v=on(c,m,r,l,f,"ko"),x=kt(Be(e,K.localizationLanguageKey)||"ko"),G=on(c,m,r,l,f,x),M=on(c,m,r,l,f,o);if(!v||!G||!M)return null;const O=e.title===v.title||e.title===G.title,I=e.body===v.body||e.body===G.body;return!O&&!I?null:{...e,title:O?M.title:e.title,body:I?M.body:e.body,tags:["Template",M.launcherLabel,M.optionLabel].filter(Boolean),metadata:{...e.metadata??{},[K.localizationManagedKey]:"True",[K.localizationLanguageKey]:o,[K.sourceInputValuesJsonKey]:JSON.stringify(f)}}}function on(e,t,o,n,r,i){const c=eo(e,i),m=Yt(t,i),l=jo(c,n),y=m.nodes.find(x=>Y(x.id,o));if(!y)return null;const f=Oo(m,r),v=lr(c,l,f);return{title:Lt(y.title,v),body:Lt(y.body,v),launcherLabel:c.label,optionLabel:(l==null?void 0:l.label)||c.label}}function il(e,t){const o=sl(Be(e,K.sourceInputValuesJsonKey));if(Object.keys(o).length>0)return o;const n=Be(e,K.controllerNodeIdKey),r=n?t.get(n):null,i=ir(r==null?void 0:r.body);return(i==null?void 0:i.inputValues)??{}}function sl(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 bo(...e){var t;return((t=e.find(o=>typeof o=="string"&&o.trim()))==null?void 0:t.trim())??null}function Xe(e){const t=String(e||"").trim();return t?t.replace(/:/g,"."):"unknown"}function ll(e,t){return e.includes("{0}")?e.replace("{0}",t):`${t} is required.`}function cl(e,t){var o,n,r;return String(t||"").trim()?((n=e.options.find(i=>Y(i.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 mn(e){return e.map(t=>{var o;return{...t,options:(o=t.options)==null?void 0:o.map(n=>({...n}))}})}function cr(e,t){const o={};for(const n of e)o[n.key]=String(t[n.key]??Ln(n));return o}function dl(){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 dr(e){return e==="ai-task"?"aiPrompt":e==="template-launcher"?K.contentType:e}function ul(e){return Y(e,"directory")?"directory":Y(e,"pdf")?"pdf":Y(e,"file")?"file":Y(e,"memo")?"memo":Y(e,"markdown")?"markdown":Y(e,"csv-table")?"csv-table":Y(e,"text")?"text":Y(e,"code")?"code":Y(e,"mask")?"mask":Y(e,"image")?"image":Y(e,"embed")?"embed":Y(e,"aiPrompt")?"ai-task":Y(e,K.contentType)?"template-launcher":"note"}function pl(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 ur(e){return`${e}-${Math.random().toString(36).slice(2,9)}`}function Y(e,t){return String(e||"").toLowerCase()===String(t||"").toLowerCase()}function ml(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function Nn(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(i){t=i}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 pr="mindexec.app.language",So="auto",Xt=[{code:So,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."}],gl={"AI settings":"AI 설정","AI Settings":"AI 설정","Settings sections":"설정 섹션","Close settings":"설정 닫기",General:"일반",Language:"언어",Connection:"연결",Media:"미디어",Agent:"에이전트",System:"시스템",About:"정보",Save:"저장","Grid snap":"그리드 스냅","Align new movement to the canvas grid.":"노드 이동과 배치를 캔버스 그리드에 맞춥니다.","Grid type":"그리드 유형","Background grid rendering mode.":"배경 그리드 표시 방식을 선택합니다.","Cursor position":"커서 위치","Where new nodes are placed by default.":"새 노드가 기본으로 만들어질 위치입니다.","Cursor direction":"커서 방향","Direction for sequential node placement.":"연속으로 노드를 만들 때 배치되는 방향입니다.","Camera trace mode":"카메라 추적 모드","Whether the camera follows new work.":"새 작업을 만들 때 카메라가 따라갈지 정합니다.","Image load size":"이미지 로드 크기","Image nodes use fixed or original sizing.":"이미지 노드를 기본 크기 또는 원본 크기로 불러옵니다.","AI node width":"AI 노드 너비","Default width for new AI task nodes.":"새 AI 작업 노드의 기본 너비입니다.","AI node height":"AI 노드 높이","Default height for new AI task nodes.":"새 AI 작업 노드의 기본 높이입니다.","Show full AI response":"AI 응답 전체 표시","Allow AI result nodes to expand for long output.":"긴 AI 결과를 노드에서 더 크게 펼칠 수 있게 합니다.",Minimap:"미니맵","Display a small navigation minimap in the bottom-right of the canvas.":"캔버스 오른쪽 아래에 작은 이동용 미니맵을 표시합니다.","Mouse wheel mode":"마우스 휠 모드","Swap wheel zoom and scroll behavior.":"휠 줌과 스크롤 동작을 서로 바꿉니다.","App Language":"앱 언어","Controls the language preference passed into AI runs.":"AI 실행에 전달할 언어 기본값을 정합니다.","AI Provider":"AI 공급자","Text model":"텍스트 모델","Text model used by bottom input and AI Task runs.":"하단 입력창과 AI 작업 실행에서 사용하는 텍스트 모델입니다.","Custom text model id preserved with this board.":"사용자 지정 텍스트 모델 ID를 이 보드에 유지합니다.","Reasoning effort":"추론 강도","Mapped to LocalBridge Codex reasoning effort.":"LocalBridge Codex의 추론 강도에 매핑됩니다.","Ollama URL":"Ollama URL","Local Ollama endpoint.":"로컬 Ollama 엔드포인트입니다.","ImageRouter mode":"ImageRouter 모드","Key material remains outside this React board snapshot.":"키 정보는 React 보드 스냅샷에 저장하지 않습니다.","Parallel insight bundles":"병렬 인사이트 번들","Preserves the original CodeMaster insight bundle switch.":"원본 CodeMaster 인사이트 번들 스위치를 유지합니다.","Bundle timeout":"번들 제한 시간","Per insight bundle timeout in milliseconds.":"인사이트 번들별 제한 시간입니다. 단위는 밀리초입니다.","Retry Count (Std)":"재시도 횟수(표준)","Retries for lite and standard CodeMaster insight bundle calls.":"라이트/표준 CodeMaster 인사이트 번들 호출 재시도 횟수입니다.","Retry Count (Deep)":"재시도 횟수(심층)","Retries for deep CodeMaster insight bundle calls.":"심층 CodeMaster 인사이트 번들 호출 재시도 횟수입니다.","API keys are intentionally not stored in this React board. Live provider adapters must supply and verify secrets separately.":"API 키는 의도적으로 React 보드에 저장하지 않습니다. 실제 provider adapter가 별도로 비밀값을 제공하고 검증해야 합니다.","These are adapter hints only. Selecting a media model does not store an API key, invoke ImageRouter, or claim live generation availability.":"이 값들은 adapter 힌트일 뿐입니다. 미디어 모델을 선택해도 API 키 저장, ImageRouter 호출, 실제 생성 가능 상태 선언을 하지 않습니다.","Direct instruction queue":"직접 지시 큐","How selected agents receive direct instructions.":"선택된 에이전트가 직접 지시를 받는 방식입니다.","Execution mode":"실행 모드","Concept parses IR locally; PureLLM is direct chat adapter mode.":"Concept는 IR을 로컬에서 파싱하고, PureLLM은 직접 채팅 adapter 모드입니다.","Changing this setting affects the next run only. It does not claim a live agent has executed.":"이 설정은 다음 실행부터 적용됩니다. 실제 에이전트가 실행됐다고 표시하지 않습니다.","Fast local-first MindCanvas shell, rebuilt without Blazor in the render loop.":"Blazor 렌더 루프 없이 다시 만든 빠른 로컬 우선 MindCanvas 셸입니다.","AI settings parity slice":"AI 설정 포팅 구간","Managed Cloud":"관리형 클라우드",BYOK:"BYOK","OpenAI Codex":"OpenAI Codex","Local Ollama":"로컬 Ollama","Gemini CLI":"Gemini CLI","Reserved for the hosted paid adapter.":"호스팅 유료 adapter용으로 예약된 경로입니다.","Use a separately configured user key.":"별도로 설정한 사용자 키를 사용합니다.","Local LLM server endpoint.":"로컬 LLM 서버 엔드포인트입니다.","Hidden Gemini CLI compatibility path.":"숨겨진 Gemini CLI 호환 경로입니다.","LocalBridge Codex execution path.":"LocalBridge Codex 실행 경로입니다.","BYOK Settings":"BYOK 설정","Ollama Settings":"Ollama 설정","DatasetGenerator Export":"DatasetGenerator 내보내기","Managed Cloud is coming soon in this build. Switch to BYOK, OpenAI Codex, or Local Ollama for local execution.":"관리형 클라우드는 이 빌드에서 준비 중입니다. 로컬 실행은 BYOK, OpenAI Codex, 로컬 Ollama를 사용하세요.","Gemini CLI is hidden in this company build. Switch to BYOK, OpenAI Codex, or Local Ollama to manage connection settings here.":"Gemini CLI는 이 회사 빌드에서 숨겨져 있습니다. 연결 설정은 BYOK, OpenAI Codex, 로컬 Ollama에서 관리하세요.","API key material stays outside this React board. Configure the BYOK adapter or environment before running live OpenRouter calls.":"API 키 정보는 React 보드 밖에 둡니다. 실제 OpenRouter 호출 전 BYOK adapter나 환경 변수를 설정하세요.","Redacted DatasetGenerator command":"마스킹된 DatasetGenerator 명령","This command is redacted; no API key is stored in the board. Replace OPENROUTER_API_KEY only in a trusted shell.":"이 명령은 키가 마스킹되어 있습니다. API 키는 보드에 저장하지 않으며, 신뢰할 수 있는 셸에서만 OPENROUTER_API_KEY를 교체하세요.","Install MindExec LocalBridge dependencies":"MindExec LocalBridge 의존성 설치","Sign in once":"한 번 로그인","Runtime: Codex SDK first, Legacy Exec fallback when SDK is unavailable.":"런타임은 Codex SDK를 먼저 사용하고, SDK를 쓸 수 없으면 Legacy Exec으로 fallback합니다.","Ollama model selection is handled from the bottom AI input bar. Keep the local endpoint editable below.":"Ollama 모델 선택은 하단 AI 입력창에서 처리합니다. 아래 로컬 엔드포인트는 계속 수정할 수 있습니다.",Requires:"필요:","when running Ollama for browser access.":"브라우저에서 Ollama에 접근하려면 필요합니다.","Text AI provider and image generation provider are configured separately. ImageRouter API key is adapter-owned and used only for image mode.":"텍스트 AI 공급자와 이미지 생성 공급자는 별도로 설정합니다. ImageRouter API 키는 adapter가 소유하고 이미지 모드에서만 사용합니다.","ImageRouter API key: not stored in this React board.":"ImageRouter API 키: 이 React 보드에 저장하지 않음.",Copied:"복사됨",Selected:"선택됨","Copy failed":"복사 실패","Copy command":"명령 복사","Connection Requirements":"연결 요구사항","Image Generation":"이미지 생성","Image defaults":"이미지 기본값","Video defaults":"비디오 기본값","Image model":"이미지 모델","Video model":"비디오 모델","Image aspect":"이미지 비율","Video aspect":"비디오 비율","Shared with the bottom input model selector.":"하단 입력창 모델 선택과 공유됩니다.",Text:"텍스트",Image:"이미지",Video:"비디오",Fast:"빠름",Normal:"보통",Deep:"깊게",Append:"뒤에 추가",Next:"다음 실행",ReplacePending:"대기 항목 교체",Concept:"Concept",PureLLM:"PureLLM",dot:"점",line:"선",particles:"입자",spirit:"스피릿",center:"중앙",lastNode:"마지막 노드",right:"오른쪽",down:"아래",none:"없음",cursor:"커서",default:"기본",original:"원본",Auto:"자동",English:"영어",Korean:"한국어",Japanese:"일본어",Chinese:"중국어","Match the user's input language unless a prompt asks otherwise.":"프롬프트가 별도 언어를 요구하지 않으면 사용자 입력 언어에 맞춥니다.","Prefer English for user-facing AI output.":"사용자에게 보이는 AI 출력은 영어를 우선합니다.","Prefer Korean for user-facing AI output.":"사용자에게 보이는 AI 출력은 한국어를 우선합니다.","Prefer Japanese for user-facing AI output.":"사용자에게 보이는 AI 출력은 일본어를 우선합니다.","Prefer Chinese for user-facing AI output.":"사용자에게 보이는 AI 출력은 중국어를 우선합니다.","Add note":"노트 추가","Add memo":"메모 추가","Add markdown":"Markdown 추가","Add CSV table":"CSV 테이블 추가","Add code":"코드 추가","Add AI Task":"AI 작업 추가","Add Code Note":"코드 노트 추가","Add Agent Command":"에이전트 명령 추가","Add image generation spec":"이미지 생성 스펙 추가","Add video generation spec":"비디오 생성 스펙 추가","Add image":"이미지 추가","Add image mask":"이미지 마스크 추가","Add video":"비디오 추가","Add embed":"임베드 추가","Add remote monitor":"원격 모니터 추가","Add PDF":"PDF 추가","Add file reference":"파일 참조 추가","Add directory reference":"폴더 참조 추가",Templates:"템플릿","Template Studio":"템플릿 스튜디오","Import board JSON":"보드 JSON 가져오기",Tools:"도구","Run all graphs":"전체 그래프 실행","Run selected graph":"선택 그래프 실행","Pause running AI tasks":"실행 중인 AI 작업 일시정지","Stop active AI tasks":"활성 AI 작업 중지","Generating flow":"플로우 생성 중","Generate flow":"플로우 생성",Undo:"실행 취소",Redo:"다시 실행","Search text":"텍스트 검색","Search text ...":"텍스트 검색 ...","Previous search result":"이전 검색 결과","Next search result":"다음 검색 결과","No matches":"일치 항목 없음",Focus:"이동",Close:"닫기","MindCanvas all tools":"MindCanvas 전체 도구","MindCanvas curated tools":"MindCanvas 주요 도구","Multi selection actions":"다중 선택 작업","Copy selected nodes":"선택 노드 복사","Duplicate selected nodes":"선택 노드 복제","Bring selected nodes to front":"선택 노드 앞으로 가져오기","Send selected nodes to back":"선택 노드 뒤로 보내기","Fit selected text heights":"선택 텍스트 높이 맞추기","Arrange selected nodes as grid":"선택 노드 그리드 정렬","Arrange selected nodes as strip":"선택 노드 가로 정렬","Tidy selected nodes":"선택 노드 정돈","Stack selected image nodes":"선택 이미지 노드 스택","Delete selected nodes":"선택 노드 삭제","Clear selection":"선택 해제","Close tab":"탭 닫기","New board":"새 보드","Copy result":"결과 복사","Archive result as a Markdown node":"결과를 Markdown 노드로 보관","Stage a follow-up AI Task from this result":"이 결과로 후속 AI 작업 만들기",Copy:"복사",Archive:"보관","Follow-up":"후속 작업","Run selected AI Task...":"선택한 AI 작업 실행...","Talk with AI...":"AI와 대화...",Submit:"전송","Image aspect ratio":"이미지 비율","Video aspect ratio":"비디오 비율","Canvas grid controls":"캔버스 그리드 컨트롤","Toggle grid snap":"그리드 스냅 전환","Camera bookmarks":"카메라 북마크","Go to home view":"홈 보기로 이동","Save current camera to the next empty slot":"현재 카메라를 다음 빈 슬롯에 저장","Go to camera slot N":"카메라 슬롯 N으로 이동","Empty camera slot N":"빈 카메라 슬롯 N","Toggle mouse wheel mode":"마우스 휠 모드 전환","Toggle cursor direction":"커서 방향 전환","Reset fixture":"샘플 보드 초기화","Exit read mode":"읽기 모드 종료",Fullscreen:"전체 화면","Canvas minimap":"캔버스 미니맵","Navigate canvas minimap":"캔버스 미니맵 이동","Disable AI reference":"AI 참조 끄기","Enable AI reference":"AI 참조 켜기","Change memo color":"메모 색상 변경","Enable word wrap":"자동 줄바꿈 켜기","Disable word wrap":"자동 줄바꿈 끄기","Copy image to clipboard":"이미지를 클립보드에 복사","Copy content":"내용 복사","Duplicate node":"노드 복제","Fit text height":"텍스트 높이 맞추기","Expand node":"노드 펼치기","Collapse node":"노드 접기","Run node":"노드 실행","Open Company graph":"Company 그래프 열기","Run this note as Company":"이 노트를 Company로 실행","Delete node":"노드 삭제","Context input":"컨텍스트 입력",Context:"컨텍스트",Result:"결과","Drag to connect this result to an input pin. Click to view the result.":"이 결과를 입력 핀에 연결하려면 드래그하세요. 클릭하면 결과를 봅니다.","Use this node as AI Task context":"이 노드를 AI 작업 컨텍스트로 사용","Image edit mask reference":"이미지 편집 마스크 참조","Image stack variants":"이미지 스택 변형","Open embed":"임베드 열기",Open:"열기","Copy URL":"URL 복사","Play video":"비디오 재생",Play:"재생","Pause video":"비디오 일시정지",Pause:"일시정지","Preview PDF":"PDF 미리보기",Preview:"미리보기","Open in new tab":"새 탭에서 열기","Scan folder":"폴더 스캔",Scan:"스캔","Folder scan settings":"폴더 스캔 설정",Settings:"설정",Plan:"계획",Execute:"실행",Approve:"승인",Review:"검토","Out of sync":"동기화 안 됨","Update Company goal from this note":"이 노트에서 Company 목표 업데이트","Refresh Company status":"Company 상태 새로고침","Company is archived":"Company가 보관됨","Resume Company":"Company 재개","Pause Company":"Company 일시정지","Archive Company":"Company 보관","Remove Company from this note":"이 노트에서 Company 제거","Resize node":"노드 크기 조절","Node title":"노드 제목","Node body":"노드 본문","Embed URL or description":"임베드 URL 또는 설명","Video prompt or source":"비디오 프롬프트 또는 소스","CSV source":"CSV 소스","Markdown preview":"Markdown 미리보기","Markdown source":"Markdown 소스","CSV table preview":"CSV 테이블 미리보기"},Ca={top:"위",right:"오른쪽",bottom:"아래",left:"왼쪽"};function It(e){if(typeof e!="string")return So;const t=e.trim().toLowerCase();return Xt.some(o=>o.code===t)?t:So}function _o(e){const t=It(e);return Xt.find(o=>o.code===t)??Xt[0]}function mr(e){return It(e)==="ko"}function Nt(e,t){if(!mr(e))return t;const o=gl[t];if(o)return o;const n=t.match(/^Use (.+) grid$/);if(n)return`${Nt(e,n[1])} 그리드 사용`;const r=t.match(/^Go to camera slot (.+)\. Shift-click to save\.$/);if(r)return`카메라 슬롯 ${r[1]}로 이동합니다. Shift-클릭하면 저장합니다.`;const i=t.match(/^Slot (.+) empty\. Click for Home, shift-click to save\.$/);if(i)return`슬롯 ${i[1]}이 비어 있습니다. 클릭하면 홈으로 이동하고, Shift-클릭하면 저장합니다.`;const c=t.match(/^Go to camera slot (.+)$/);if(c)return`카메라 슬롯 ${c[1]}로 이동`;const m=t.match(/^Empty camera slot (.+)$/);if(m)return`빈 카메라 슬롯 ${m[1]}`;const l=t.match(/^Cursor direction (.+)$/);if(l)return`커서 방향 ${Nt(e,l[1])}`;const y=t.match(/^Drag from (.+) to connect$/);if(y)return`${Ca[y[1]]??y[1]} 핸들에서 드래그해 연결`;const f=t.match(/^Drag (.+) connector$/);if(f)return`${Ca[f[1]]??f[1]} 연결 핸들 드래그`;const v=t.match(/^Variant (\d+)$/);if(v)return`변형 ${v[1]}`;const x=t.match(/^Show image variant (\d+)$/);if(x)return`이미지 변형 ${x[1]} 보기`;const G=t.match(/^(.+) memo color$/);return G?`${G[1]} 메모 색상`:t}function hl(e,t){return mr(e)?t.code==="auto"?"자동":`${t.nativeLabel} / ${Nt(e,t.label)}`:t.isAuto?t.label:`${t.nativeLabel} / ${t.label}`}function gr(){if(typeof window>"u")return null;try{const e=window.localStorage.getItem(pr);return e===null?null:It(e)}catch{return null}}function pu(e){return It(gr()??e??So)}function mu(e){const t=It(e);if(typeof window>"u")return t;try{window.localStorage.setItem(pr,t)}catch{}return t}function gu(e){const t=gr()??It(e.settings.appLanguage);return{...e,settings:{...e.settings,appLanguage:t}}}function hu(e){const t=_o(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 fu(e){return _o(e).englishName}function bu(e){const t=_o(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 jn=.001,fl=1,bl=5,yl=1.35,kl=1.3,Il=1.45,Cl=.002,Tl=.01,vl=.03,xl=.002,wl=.015,Sl=.05,Rl=5,Ml=20,Al=100,Pl=2,Ta=2500,El=800,Ll=1200,Nl=1800,jl=2600,Dl={"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 Ol(e){const t=Kl(e.reasoningEffort);return e.mode==="Text"?Ul(e.provider,t,e.vendorPricing):e.mode==="Image"&&e.provider==="openai-codex"&&Hl(e.modelId)?lt("Free",0,"Codex Responses image generation",void 0,"codex",!1):e.mode==="Image"?$l(e.vendorPricing):e.mode==="Video"?Vl(e.vendorPricing):jt("Unavailable")}function _l(e){const t=e.settings.inputMode==="Image"||e.settings.inputMode==="Video"?e.settings.inputMode:"Text",o=Gl(e.settings,t);return Ol({mode:t,provider:Bl(e.settings),modelId:o,reasoningEffort:e.settings.effort,vendorPricing:Fl(o)})}function Fl(e){const t=Yl(e);return Dl[t]??null}function Bl(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 Gl(e,t){return t==="Image"?dn("Image",e).id:t==="Video"?dn("Video",e).id:e.model}function Ul(e,t,o){switch(e){case"local-ollama":return lt("Free",0,"Local execution",void 0,"ollama",!1);case"byok":return lt("ServiceFeeOnly",Pl,"BYOK platform fee",void 0,"byok",!1);case"openai-codex":return lt("Free",0,"Codex CLI local execution",void 0,"codex",!1);case"google-gemini-cli":return lt("Free",0,"Gemini CLI local execution",void 0,"gemini-cli",!1);case"managed-cloud":default:return zl(t,o)}}function zl(e,t){if(!yt(t==null?void 0:t.promptUsdPerToken)||!yt(t==null?void 0:t.completionUsdPerToken))return jt("Pricing unavailable");const o=ql(e),n=((t==null?void 0:t.requestUsd)??0)+t.promptUsdPerToken*Ta+t.completionUsdPerToken*o,r=n*yl+Cl+xl,i=Dn(Math.max(r/jn,Rl),fl);return lt("FixedPoints",i,`Base run (${gn(Ta)} in / ${gn(o)} out)`,n,t.source,!0)}function $l(e){if(!e)return jt("Pricing unavailable");let t=e.averageUsd??e.maxUsd??e.minUsd;if(!yt(t))return jt("Pricing unavailable");yt(e.minUsd)&&(t=Math.max(t,e.minUsd*1.15));const o=t*kl+Tl+wl,n=Dn(Math.max(o/jn,Ml),bl);return lt("FixedPoints",n,"Base image generation",t,e.source,!0)}function Vl(e){if(!e)return jt("Pricing unavailable");let t=0;if(yt(e.maxUsd)&&(t=Math.max(t,e.maxUsd)),yt(e.averageUsd)&&(t=Math.max(t,e.averageUsd*1.25)),yt(e.minUsd)&&(t=Math.max(t,e.minUsd)),t<=0)return jt("Pricing unavailable");const o=t*Il+vl+Sl,n=Dn(Math.max(o/jn,Al),10);return lt("FixedPoints",n,"Base video generation",t,e.source,!0)}function ql(e){switch(e){case"low":return El;case"high":return Nl;case"xhigh":return jl;case"medium":default:return Ll}}function Kl(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 Dn(e,t){return t<=1?Math.ceil(e):Math.ceil(e/t)*t}function lt(e,t,o,n,r,i){return{billingKind:e,displayPoints:t,displayLabel:Wl(t),basisLabel:o,isEstimatedFromCatalog:i,vendorCostUsdSnapshot:n,vendorPricingSource:r}}function jt(e){return{billingKind:"Unavailable",displayPoints:0,displayLabel:e,basisLabel:"Pricing unavailable",isEstimatedFromCatalog:!1}}function Wl(e){return`${gn(e)}P`}function gn(e){return e.toLocaleString("en-US",{maximumFractionDigits:0})}function Hl(e){return String(e??"").trim().toLowerCase().startsWith("codex-image:")}function Yl(e){return String(e??"").trim()}function yt(e){return typeof e=="number"&&Number.isFinite(e)}const nn=[{id:"general",label:"General",icon:Ci},{id:"language",label:"Language",icon:Ti},{id:"connection",label:"Connection",icon:vi},{id:"media",label:"Media",icon:_a},{id:"agent",label:"Agent",icon:xi},{id:"system",label:"System",icon:wi},{id:"about",label:"About",icon:Si}],Xl=["Managed Cloud","BYOK","OpenAI Codex","Local Ollama"];function Ql(e,t,o){return Number.isFinite(e)?Math.min(o,Math.max(t,Math.round(e))):t}function yu({settings:e,onPatchSettings:t,onClose:o}){const[n,r]=p.useState("general"),[i,c]=p.useState("idle"),[m,l]=p.useState(null),y=nn.find(g=>g.id===n)??nn[0],f=Is(e),v=Dt(e.model),x=e.aiProvider??"OpenAI Codex",G=Zl(v),M=_o(e.appLanguage),O=e.appLanguage,I=g=>Nt(O,g),Q=va("Image",e),V=va("Video",e),pe=Object.fromEntries(Xt.map(g=>[g.code,hl(O,g)])),P=(g,H)=>t(g,H),ye=g=>{const H=g.currentTarget;let re=0;if(g.key==="PageDown")re=Math.max(160,Math.floor(H.clientHeight*.86));else if(g.key==="PageUp")re=-Math.max(160,Math.floor(H.clientHeight*.86));else if(g.key==="ArrowDown")re=44;else if(g.key==="ArrowUp")re=-44;else if(g.key==="End"){g.preventDefault(),H.scrollTo({top:H.scrollHeight,behavior:"auto"});return}else if(g.key==="Home"){g.preventDefault(),H.scrollTo({top:0,behavior:"auto"});return}else return;g.preventDefault(),H.scrollBy({top:re,behavior:"auto"})},Pe=async()=>{try{const g=await Nn(G);c("copied"),h.emit("settings.providerCommand.copy",{provider:x,command:"dataset-generator",method:g,redacted:!0})}catch(g){if(ec(m)){c("selected"),h.emit("settings.providerCommand.selectFallback",{provider:x,command:"dataset-generator",message:g instanceof Error?g.message:String(g),redacted:!0});return}c("failed"),h.emit("settings.providerCommand.copyFailed",{provider:x,command:"dataset-generator",message:g instanceof Error?g.message:String(g)})}},Z=(g,H)=>{const re=Mn(g,H),U=No(g).find(de=>de.id===re);if(!U)return;const Ee=g==="Image"?e.imageRouterImageAspectPresetId:e.imageRouterVideoAspectPresetId,me=un(g,U,Ee);P(g==="Image"?{imageRouterImageModel:U.id,imageRouterImageAspectPresetId:me.id}:{imageRouterVideoModel:U.id,imageRouterVideoAspectPresetId:me.id},`media.${g.toLowerCase()}.model`),h.emit("media.model.select",{mode:g,model:U.id,aspectPresetId:me.id,requestedSize:pn(me),source:"settings-dialog"})},xe=(g,H)=>{const re=g==="Image"?Q.model:V.model,U=un(g,re,H);P(g==="Image"?{imageRouterImageAspectPresetId:U.id}:{imageRouterVideoAspectPresetId:U.id},`media.${g.toLowerCase()}.aspect`),h.emit("media.aspect.select",{mode:g,model:re.id,aspectPresetId:U.id,requestedSize:pn(U),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":I("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":I("Settings sections"),children:nn.map(g=>{const H=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(H,{size:15}),a.jsx("span",{children:I(g.label)})]},g.id)})}),a.jsxs("main",{className:"ai-settings-main",children:[a.jsxs("header",{className:"ai-settings-head",children:[a.jsx("strong",{children:I(y.label)}),a.jsx("button",{type:"button",title:I("Close settings"),onClick:o,children:a.jsx(Eo,{size:16})})]}),a.jsxs("div",{className:"ai-settings-body","data-testid":"ai-settings-body",tabIndex:0,onKeyDown:ye,children:[n==="general"&&a.jsxs("div",{className:"settings-grid",children:[a.jsx(St,{label:I("Grid snap"),description:I("Align new movement to the canvas grid."),checked:e.gridSnap??!0,onChange:g=>P({gridSnap:g},"general.gridSnap")}),a.jsx(_e,{label:I("Grid type"),description:I("Background grid rendering mode."),value:e.gridType??"dot",options:["dot","line","particles","spirit"],optionLabels:rt(I,["dot","line","particles","spirit"]),onChange:g=>P({gridType:g},"general.gridType")}),a.jsx(_e,{label:I("Cursor position"),description:I("Where new nodes are placed by default."),value:e.cursorMode??"center",options:["center","lastNode"],optionLabels:rt(I,["center","lastNode"]),onChange:g=>P({cursorMode:g},"general.cursorMode")}),a.jsx(_e,{label:I("Cursor direction"),description:I("Direction for sequential node placement."),value:e.cursorDirection,options:["right","down"],optionLabels:rt(I,["right","down"]),onChange:g=>P({cursorDirection:g},"general.cursorDirection")}),a.jsx(_e,{label:I("Camera trace mode"),description:I("Whether the camera follows new work."),value:e.cameraTraceMode??"none",options:["none","cursor"],optionLabels:rt(I,["none","cursor"]),onChange:g=>P({cameraTraceMode:g},"general.cameraTraceMode")}),a.jsx(_e,{label:I("Image load size"),description:I("Image nodes use fixed or original sizing."),value:e.imageLoadSize??"default",options:["default","original"],optionLabels:rt(I,["default","original"]),onChange:g=>P({imageLoadSize:g},"general.imageLoadSize")}),a.jsx(qt,{label:I("AI node width"),description:I("Default width for new AI task nodes."),value:e.aiNodeDefaultWidth??340,min:220,max:1200,onChange:g=>P({aiNodeDefaultWidth:g},"general.aiNodeDefaultWidth")}),a.jsx(qt,{label:I("AI node height"),description:I("Default height for new AI task nodes."),value:e.aiNodeDefaultHeight??196,min:120,max:900,onChange:g=>P({aiNodeDefaultHeight:g},"general.aiNodeDefaultHeight")}),a.jsx(St,{label:I("Show full AI response"),description:I("Allow AI result nodes to expand for long output."),checked:e.showFullAiResponse??!1,onChange:g=>P({showFullAiResponse:g},"general.showFullAiResponse")}),a.jsx(St,{label:I("Minimap"),description:I("Display a small navigation minimap in the bottom-right of the canvas."),checked:e.minimapEnabled??!1,onChange:g=>P({minimapEnabled:g},"general.minimapEnabled")}),a.jsx(St,{label:I("Mouse wheel mode"),description:I("Swap wheel zoom and scroll behavior."),checked:e.wheelMode,onChange:g=>P({wheelMode:g},"general.wheelMode")})]}),n==="language"&&a.jsx("div",{className:"settings-grid settings-grid--compact",children:a.jsx(_e,{label:I("App Language"),description:`${I("Controls the language preference passed into AI runs.")} ${I(M.description)}`,value:M.code,options:Xt.map(g=>g.code),optionLabels:pe,testId:"app-language-select",onChange:g=>P({appLanguage:It(g)},"language.appLanguage")})}),n==="connection"&&a.jsxs("div",{className:"settings-stack",children:[a.jsx("section",{className:"settings-radio-group","aria-label":I("AI Provider"),children:Xl.map(g=>a.jsxs("label",{className:x===g?"is-selected":"",children:[a.jsx("input",{type:"radio",name:"ai-provider",checked:x===g,onChange:()=>P({aiProvider:g},"connection.provider")}),a.jsxs("span",{children:[a.jsx("strong",{children:I(g)}),a.jsx("small",{children:I(hr(g))})]})]},g))}),a.jsx(tc,{provider:x,language:O,datasetGeneratorCommand:G,copyState:i,onCommandTextAreaRef:l,onCopyDatasetGeneratorCommand:Pe}),a.jsxs("div",{className:"settings-grid settings-grid--compact",children:[a.jsx(_e,{label:I("Text model"),description:tr(v)?I("Text model used by bottom input and AI Task runs."):I(Jl(v)),value:v,options:f.map(g=>g.id),optionLabels:Object.fromEntries(f.map(g=>[g.id,`${or(g.provider)} · ${g.label}`])),onChange:g=>P({model:g},"connection.model")}),a.jsx(_e,{label:I("Reasoning effort"),description:I("Mapped to LocalBridge Codex reasoning effort."),value:e.effort,options:["Fast","Normal","Deep"],optionLabels:rt(I,["Fast","Normal","Deep"]),onChange:g=>P({effort:g},"connection.effort")}),(e.aiProvider??"OpenAI Codex")==="Local Ollama"&&a.jsx(oc,{label:I("Ollama URL"),description:I("Local Ollama endpoint."),value:e.ollamaEndpoint??"http://localhost:11434",onChange:g=>P({ollamaEndpoint:g},"connection.ollamaEndpoint")}),a.jsx(St,{label:I("ImageRouter mode"),description:I("Key material remains outside this React board snapshot."),checked:e.imageRouterEnabled??!1,onChange:g=>P({imageRouterEnabled:g},"connection.imageRouterEnabled")}),a.jsx(St,{label:I("Parallel insight bundles"),description:I("Preserves the original CodeMaster insight bundle switch."),checked:e.codeMasterInsightBundlesEnabled??!0,onChange:g=>P({codeMasterInsightBundlesEnabled:g},"connection.codeMasterInsightBundlesEnabled")}),a.jsx(qt,{label:I("Bundle timeout"),description:I("Per insight bundle timeout in milliseconds."),value:e.codeMasterInsightBundleTimeoutMs??18e3,min:5e3,max:6e4,onChange:g=>P({codeMasterInsightBundleTimeoutMs:g},"connection.codeMasterInsightBundleTimeoutMs")}),a.jsx(qt,{label:I("Retry Count (Std)"),description:I("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=>P({codeMasterInsightBundleRetryCount:g},"connection.codeMasterInsightBundleRetryCount")}),a.jsx(qt,{label:I("Retry Count (Deep)"),description:I("Retries for deep CodeMaster insight bundle calls."),value:e.codeMasterInsightBundleRetryCountDeep??3,min:1,max:5,step:1,testId:"codemaster-insight-retry-deep",onChange:g=>P({codeMasterInsightBundleRetryCountDeep:g},"connection.codeMasterInsightBundleRetryCountDeep")})]}),a.jsxs("div",{className:"settings-note",children:[a.jsx(fa,{size:15}),a.jsx("span",{children:I("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(xa,{mode:"Image",language:O,icon:a.jsx(_a,{size:17}),selection:Q,onModelChange:g=>Z("Image",g),onAspectChange:g=>xe("Image",g)}),a.jsx(xa,{mode:"Video",language:O,icon:a.jsx(Ri,{size:17}),selection:V,onModelChange:g=>Z("Video",g),onAspectChange:g=>xe("Video",g)}),a.jsxs("div",{className:"settings-note",children:[a.jsx(fa,{size:15}),a.jsx("span",{children:I("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(_e,{label:I("Direct instruction queue"),description:I("How selected agents receive direct instructions."),value:e.directInstructionQueueMode??"Append",options:["Append","Next","ReplacePending"],optionLabels:rt(I,["Append","Next","ReplacePending"]),onChange:g=>P({directInstructionQueueMode:g},"agent.directInstructionQueueMode")})}),n==="system"&&a.jsxs("div",{className:"settings-grid settings-grid--compact",children:[a.jsx(_e,{label:I("Execution mode"),description:I("Concept parses IR locally; PureLLM is direct chat adapter mode."),value:e.executionMode??"Concept",options:["Concept","PureLLM"],optionLabels:rt(I,["Concept","PureLLM"]),onChange:g=>P({executionMode:g},"system.executionMode")}),a.jsxs("div",{className:"settings-note",children:[a.jsx(Mi,{size:15}),a.jsx("span",{children:I("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(Ai,{size:34}),a.jsx("strong",{children:"MindExec React"}),a.jsx("span",{children:I("Fast local-first MindCanvas shell, rebuilt without Blazor in the render loop.")}),a.jsx("small",{children:I("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:I("Save")})})]})]})})}function va(e,t){const o=dn(e,t),n=e==="Image"?t.imageRouterImageAspectPresetId:t.imageRouterVideoAspectPresetId,r=un(e,o,n);return{model:o,aspect:r,aspectOptions:ar(o,e),requestedSize:pn(r)}}function Jl(e){const t=tr(e);return t?`${or(t.provider)} text model used by bottom input and AI Task runs.`:"Custom text model id preserved with this board."}function rt(e,t){return Object.fromEntries(t.map(o=>[o,e(o)]))}function hr(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 ec(e){return!e||e.value.length===0?!1:(e.focus({preventScroll:!0}),e.select(),e.setSelectionRange(0,e.value.length),!0)}function tc({provider:e,language:t,datasetGeneratorCommand:o,copyState:n,onCommandTextAreaRef:r,onCopyDatasetGeneratorCommand:i}){const c=l=>Nt(t,l),m=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:c(m)}),a.jsx("span",{children:c(hr(e))})]})}),e==="Managed Cloud"&&a.jsx("div",{className:"settings-provider-card__notice",children:c("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:c("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:c("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:c("DatasetGenerator Export")}),a.jsx("button",{type:"button","data-testid":"ai-settings-provider-copy-command","data-provider-copy-state":n,onClick:()=>void i(),children:c(n==="copied"?"Copied":n==="selected"?"Selected":n==="failed"?"Copy failed":"Copy command")})]}),a.jsx("textarea",{readOnly:!0,ref:r,value:o,"data-testid":"ai-settings-provider-dataset-command",className:"settings-provider-card__command","aria-label":c("Redacted DatasetGenerator command")}),a.jsx("div",{className:"settings-provider-card__note",children:c("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:c("Connection Requirements")}),a.jsxs("ol",{children:[a.jsxs("li",{children:[c("Install MindExec LocalBridge dependencies"),": ",a.jsx("code",{children:"npm install"})]}),a.jsxs("li",{children:[c("Sign in once"),": ",a.jsx("code",{children:"codex login"})]}),a.jsx("li",{children:c("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:c("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:[c("Requires")," ",a.jsx("code",{children:'OLLAMA_ORIGINS="*"'})," ",c("when running Ollama for browser access.")]})]}),a.jsxs("div",{className:"settings-provider-card__section settings-provider-card__section--image",children:[a.jsx("strong",{children:c("Image Generation")}),a.jsx("p",{children:c("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:c("ImageRouter API key: not stored in this React board.")})]})]})}function xa({mode:e,language:t,icon:o,selection:n,onModelChange:r,onAspectChange:i}){const c=f=>Nt(t,f),m=No(e),l=Object.fromEntries(m.map(f=>[f.id,f.label])),y=Object.fromEntries(n.aspectOptions.map(f=>[f.id,`${f.label} · ${f.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:o}),a.jsxs("span",{children:[a.jsx("strong",{children:c(`${e} defaults`)}),a.jsx("small",{children:n.requestedSize})]})]}),a.jsxs("div",{className:"settings-grid settings-grid--compact",children:[a.jsx(_e,{label:c(`${e} model`),description:c("Shared with the bottom input model selector."),value:n.model.id,options:m.map(f=>f.id),optionLabels:l,testId:`ai-settings-${e.toLowerCase()}-model`,onChange:r}),a.jsx(_e,{label:c(`${e} aspect`),description:n.aspect.note,value:n.aspect.id,options:n.aspectOptions.map(f=>f.id),optionLabels:y,testId:`ai-settings-${e.toLowerCase()}-aspect`,swatchClassName:Ms(n.aspect.id),onChange:i})]})]})}function St({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 _e({label:e,description:t,value:o,options:n,optionLabels:r,testId:i,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":i,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 qt({label:e,description:t,value:o,min:n,max:r,step:i=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:i,"data-testid":c,value:o,onChange:l=>m(Ql(l.target.valueAsNumber,n,r))})]})}function oc({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 nc=1e3,wa=1536*1024,ac=3*1024*1024*3/4,rc=24,ic=.65,sc=16,lc=.92;function Ro(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:cc(JSON.parse(n)),payload:e.slice(4+o)}}catch{return null}}function cc(e){const t=dc(e)?e:{};return{type:Oe(t.type)||"remote.frame.binary",kind:Oe(t.kind)||"live",deviceId:Oe(t.deviceId),frameSeq:be(t.frameSeq),streamId:Oe(t.streamId),width:be(t.width),height:be(t.height),mimeType:Oe(t.mimeType)||"image/jpeg",mode:Oe(t.mode),fps:be(t.fps),capturedAt:Oe(t.capturedAt),receivedAt:Oe(t.receivedAt),byteLength:be(t.byteLength),transport:Oe(t.transport),contentHash:Oe(t.contentHash),captureMs:be(t.captureMs),sameContentStreak:be(t.sameContentStreak),droppedByAgent:be(t.droppedByAgent),dirtyRectCount:uc(t.dirtyRectCount??t.dirtyRects??t.dirtyRegionCount),dirtyPixelRatio:br(t.dirtyPixelRatio??t.dirtyRatio??t.dirtyAreaRatio??t.changedPixelRatio),codec:Oe(t.codec??t.encoder??t.encoding),deltaEncoded:yr(t.deltaEncoded??t.isDeltaEncoded??t.deltaFrame)}}function fr(e,t=0){const o=be(e.captureMs),n=Math.max(be(e.byteLength),be(t)),r=be(e.sameContentStreak),i=be(e.droppedByAgent),c=be(e.dirtyRectCount),m=br(e.dirtyPixelRatio),l=Oe(e.codec),y=yr(e.deltaEncoded),f={captureMs:o,byteLength:n,sameContentStreak:r,droppedByAgent:i,dirtyRectCount:c,dirtyPixelRatio:m,codec:l,deltaEncoded:y};return n>=ac?{level:"oversized-frame",overBudget:!0,reason:"RemoteFast frame is near the agent binary frame ceiling.",...f}:o>=nc?{level:"slow-capture",overBudget:!0,reason:"RemoteFast reported a slow screen capture.",...f}:m>=lc&&n>=wa?{level:"inefficient-full-frame",overBudget:!0,reason:"RemoteFast dirty-region metadata shows a near-full-frame update with a large payload.",...f}:m>=ic&&c>=sc?{level:"dirty-region-heavy",overBudget:!0,reason:"RemoteFast dirty-region metadata shows many changed regions in one frame.",...f}:n>=wa?{level:"large-frame",overBudget:!0,reason:"RemoteFast frame payload is large enough to create decode or transport pressure.",...f}:r>=rc?{level:"stable-duplicate",overBudget:!1,reason:"RemoteFast reports repeated identical content that may be eligible for future delta or skip optimization.",...f}:{level:"nominal",overBudget:!1,reason:"",...f}}function dc(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function Oe(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):""}function be(e){const t=Number(e);return Number.isFinite(t)&&t>=0?t:0}function uc(e){return Array.isArray(e)?e.length:Math.round(be(e))}function br(e){const t=be(e);return t<=1?t:t<=100?t/100:1}function yr(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 kr(e){const t=Ye(e.deviceId,256),o=pc({...e.input,controlLeaseId:e.input.controlLeaseId||e.controlLeaseId});return!t||!o.type?null:{type:"input",requestId:Ye(e.requestId,160),deviceId:t,ack:mc(o.type,e.ack),input:o}}function pc(e={}){const t=Number(e.normalizedX),o=Number(e.normalizedY),n=Number(e.deltaX),r=Number(e.deltaY);return{type:Ye(e.type,48),normalizedX:Number.isFinite(t)?ct(t,0,1):void 0,normalizedY:Number.isFinite(o)?ct(o,0,1):void 0,button:Ye(e.button,24),deltaX:Number.isFinite(n)?ct(n,-4096,4096):0,deltaY:Number.isFinite(r)?ct(r,-4096,4096):0,key:Ye(e.key,80),code:Ye(e.code,80),text:hc(e.text,256),repeat:e.repeat===!0,controlLeaseId:Ye(e.controlLeaseId,128),issuedAt:Ye(e.issuedAt,80)}}function mc(e,t){return t===!0||!/^pointermove$/i.test(String(e||"").trim())}function Ir(e){let t;try{const n=typeof e=="string"?JSON.parse(e||"{}"):e;if(!Cr(n))return null;t=n}catch{return null}const o=Rt(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:Rt(t.requestId||t.RequestId),deviceId:Rt(t.deviceId||t.DeviceId),inputType:Rt(t.inputType||t.InputType),commandId:Rt(t.commandId||t.CommandId),error:Rt(t.error||t.Error)}}function gc(e,t,o,n=!1){if(!Sa(t))return null;const r=Sa(o)?o:{left:0,top:0,width:t.width,height:t.height};let i=Number(e.clientX)-t.left-r.left,c=Number(e.clientY)-t.top-r.top;return!Number.isFinite(i)||!Number.isFinite(c)||(i<0||c<0||i>r.width||c>r.height)&&!n?null:(i=ct(i,0,r.width),c=ct(c,0,r.height),{normalizedX:ct(i/r.width,0,1),normalizedY:ct(c/r.height,0,1)})}function ct(e,t,o){return Math.max(t,Math.min(o,e))}function Sa(e){if(!Cr(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 Ye(e,t){return String(e??"").replace(/\0/g,"").trim().slice(0,t)}function hc(e,t){return Ye(e,t)}function Rt(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):""}function Cr(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function fc(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",i=bc(e,t.visibilityFilter,n,t.capabilityFilter),c=yc(i,t.groupMode),m=c.length,l=Math.max(1,Math.ceil(Math.max(0,m)/o)),y=Number.isFinite(t.pageIndex)?Math.floor(t.pageIndex):0,f=Math.max(0,Math.min(y,l-1)),v=f*o,x=c.slice(v,v+o),G=x.map(dt).filter(Boolean),M=x.filter(V=>V.connected===!0).map(dt).filter(Boolean),O=new Set(x.map(V=>hn(V,t.groupMode))).size,I=c.filter(V=>V.connected===!0&&Ge(V,"taskDispatch")).map(dt).filter(Boolean),Q=c.filter(V=>V.connected===!0&&Ge(V,"taskDispatch")&&Ge(V,"aiAssist")).map(dt).filter(Boolean);return{filterActive:r,filteredDevices:i,projectedDevices:c,visibleDevices:x,visibleDeviceIds:G,visibleConnectedDeviceIds:M,frameSubscriptionDeviceIdSignature:M.join(","),visibleGroupCount:O,projectedCount:m,filteredCount:i.length,pageCount:l,pageIndex:f,pageStart:v,placeholderSlots:Math.max(0,o-x.length),taskDispatchDeviceIds:I,aiTaskDeviceIds:Q}}function bc(e,t,o,n){const r=o.trim().toLocaleLowerCase();return e.filter(i=>kc(i,t)&&Ic(i,n)&&Cc(i,r))}function yc(e,t){return[...e].sort((o,n)=>{const r=hn(o,t),i=hn(n,t);if(r!==i)return r.localeCompare(i);const c=fn(o).toLocaleLowerCase(),m=fn(n).toLocaleLowerCase();return c!==m?c.localeCompare(m):dt(o).localeCompare(dt(n))})}function hn(e,t){switch(t){case"activity":return vr(e);case"platform":return Tr(e).toLocaleLowerCase()||"unknown";case"capability":return xr(e);default:return e.connected===!0?"online":"offline"}}function dt(e){return String(e.deviceId||e.sessionId||e.deviceName||"").trim()}function fn(e){return String(e.deviceName||e.hostname||dt(e)||"Remote device").trim()}function Tr(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 kc(e,t){return t==="all"?!0:t==="offline"?e.connected!==!0:e.connected===!0}function Ic(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 Cc(e,t){var n;return t?[dt(e),fn(e),Tr(e),bn(e.arch),bn((n=e.latestTask)==null?void 0:n.status),vr(e),xr(e),e.connected===!0?"online live connected":"offline disconnected"].join(" ").toLocaleLowerCase().includes(t):!0}function vr(e){var o,n,r,i;const t=bn((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(((i=e.counters)==null?void 0:i.thumbnailFramesReceived)||0)>0?"thumbnail":e.lastStatusAt||e.lastSeenAt?"heartbeat":"idle"}function xr(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 bn(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):""}const Ae=30,Tc=1200,vc=4200,Ra=12,wr=8e3,xc=1.5,Sr=42,Ma="mindexec:remote-monitor-input-smoke",an="connected-screen-wall",yn=90,Rr=240,Mr=1e4,Kt=6e4,yo=25e3,wc=250,vo=2e3,At=60,Aa=2,Sc=96,Rc=58,Wt=[1,1.5,2.25,3.375],Pa=1,Mc=5,Ac=72,Pc=96,Ea="240px",kn="MindExec.RemoteFleet.AutoHost",In="MindExec.RemoteFleet.AutoHostNodeId",Ar=["status","activity","platform","capability"],Pr=["connected","all","offline"],Er=["all","control","task","ai"],Pt=new Map,to=new WeakMap;function La(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 Lr(e,t,o){const[n,r]=p.useState(()=>typeof document>"u"?!0:document.visibilityState==="visible"),[i,c]=p.useState(!0),m=p.useRef(null);p.useEffect(()=>{if(typeof document>"u")return;const y=()=>r(document.visibilityState==="visible");return y(),document.addEventListener("visibilitychange",y),()=>document.removeEventListener("visibilitychange",y)},[]),p.useEffect(()=>{const y=e.current;if(!y||typeof IntersectionObserver>"u"){c(!0);return}const f=new IntersectionObserver(v=>{const x=v[0],G=!!(x!=null&&x.isIntersecting||((x==null?void 0:x.intersectionRatio)??0)>0),M=La(x?x.boundingClientRect:y.getBoundingClientRect(),240);c(G||M)},{root:null,rootMargin:Ea,threshold:0});return f.observe(y),()=>f.disconnect()},[e]);const l=n&&i;return p.useEffect(()=>{if(m.current===l)return;m.current=l;const y={nodeId:t,visible:l,pageVisible:n,viewportVisible:i,rootMargin:Ea};o==="monitor"?h.emit("remoteMonitor.node.transportVisibility",y):h.emit("remoteControl.node.transportVisibility",y)},[t,n,o,i,l]),l}function ku({node:e,onPatch:t,onCreateRemoteControl:o}){var oa,na,aa,ra,ia,sa,la,ca,da,ua,pa,ma;const n=Cn((oa=e.metadata)==null?void 0:oa.RemoteTotal,Ae),r=Cn((na=e.metadata)==null?void 0:na.RemoteConnected,0),i=p.useRef(null),c=p.useRef(null),m=Lr(i,e.id,"monitor"),[l,y]=p.useState(()=>({source:Et()?"loading":"blocked",loading:!1,message:Et()?"RemoteHub not checked yet.":"Hosted LocalBridge access is gated.",baseUrl:N(),devices:ko(n,r)})),f=p.useRef(new Map),v=p.useRef(new Set),x=p.useRef(new Map),G=p.useRef(new Map),M=p.useRef(new Map),O=p.useRef(null),I=p.useRef(0),Q=p.useRef(0),V=p.useRef(0),pe=p.useRef(!1),P=p.useRef(0),ye=p.useRef(0),Pe=p.useRef(!1),Z=p.useRef(!1),xe=p.useRef(!1),g=p.useRef(""),H=p.useRef(0),re=p.useRef(""),U=p.useRef(null),Ee=p.useRef(!1),me=p.useRef(0),de=p.useRef(0),L=p.useRef(e.metadata??{}),[we,Fe]=p.useState(""),[R,J]=p.useState(!1),[ee,oe]=p.useState("locked"),[Ot,ne]=p.useState("Remote input locked."),[Bo,Se]=p.useState(""),[Re,gt]=p.useState(""),[_t,ue]=p.useState(""),[Me,oo]=p.useState(""),[Je,no]=p.useState(""),[Go,Ue]=p.useState(""),[Ct,Ze]=p.useState(0),[We,Uo]=p.useState(Pa),[ze,ao]=p.useState("status"),[Ft,ro]=p.useState(""),[Le,io]=p.useState("connected"),[Ne,so]=p.useState("all"),[ge,ht]=p.useState(()=>rn(e.id)),et=l.source==="bridge"?l.devices.length:l.devices.length||n,k=Ft.trim(),T=p.useMemo(()=>fc(l.devices,{groupMode:ze,visibilityFilter:Le,searchText:k,capabilityFilter:Ne,pageIndex:Ct,visibleBudget:Ae}),[Ne,ze,Ct,k,l.devices,Le]),j=T.filterActive,z=T.filteredDevices,$=T.projectedDevices,_=T.projectedCount,E=T.pageCount,F=T.pageIndex,X=T.pageStart,he=T.visibleDevices,tt=T.visibleDeviceIds,$e=T.visibleConnectedDeviceIds,ot=T.frameSubscriptionDeviceIdSignature,Un=T.visibleGroupCount,Wr=T.placeholderSlots,zo=`${F+1}/${E}`,zn=E<=1?100:Math.max(12,100/E),Hr=E<=1?0:F/Math.max(1,E-1)*(100-zn),Bt=Wt[We]??Wt[Pa],$n=Math.round(Sc*Bt),Vn=Math.round(Rc*Bt),te=p.useMemo(()=>he.find(s=>st(s)===we)||he.find(s=>s.connected===!0)||he[0],[we,he]),W=te?st(te):"",Gt=l.devices.filter(s=>s.connected===!0).length,$o=l.devices.reduce((s,d)=>{var u;return s+Number(((u=d.counters)==null?void 0:u.tasksQueued)||0)},0),lo=T.taskDispatchDeviceIds,co=T.aiTaskDeviceIds,Vo=lo.length,Ut=co.length,qo=l.source==="bridge"?(aa=l.hub)!=null&&aa.started?"Online":((ra=l.hub)==null?void 0:ra.enabled)===!1?"Off":"Ready":l.source==="blocked"?"Gated":l.source,uo=l.source==="bridge"?"Local":l.source==="blocked"?"Gated":"Preview",Ko=qa((ia=l.bridge)==null?void 0:ia.status),Wo=Ka((sa=l.bridge)==null?void 0:sa.status),qn=l.source==="bridge"&&!!Wo,Kn=te?ce(te,"control"):!1,Ho=te?ce(te,"taskDispatch"):!1,nt=p.useMemo(()=>te?l.source!=="bridge"?"LocalBridge is not connected.":qn?te.connected!==!0?"Selected device is offline.":Kn?"":"RemoteAgent control capability is disabled.":"Remote input adapter is unavailable.":"No screen selected.",[qn,Kn,te,l.source]),je=nt==="",Yo=R?_r(ee):je?"Locked":"Off",ie=l.source==="bridge"&&((la=l.hub)==null?void 0:la.hostTargetActive)===!0&&l.hub.hostTargetNodeId===e.id,ae=p.useMemo(()=>Nc(l.hub,ie),[ie,l.hub]),zt=Uc(l.agent,l.source),po=Gr(l.agent),Xo=Ur(l.agent),$t=p.useMemo(()=>Fc(l.hub,e.id),[e.id,l.hub]),mo=zc({source:l.source,hasAuth:!!l.auth,isHostActiveForNode:ie,request:$t,busy:Re}),go=mo==="",ho=l.source==="bridge"&&!!l.auth&&po&&!Re,Wn=l.source==="bridge"&&!!W&&(te==null?void 0:te.connected)===!0&&Ho&&!!Me.trim()&&!Je,Hn=l.source==="bridge"&&Vo>0&&!!Me.trim()&&!Je,Yn=l.source==="bridge"&&Ut>0&&!!Me.trim()&&!Je,Yr=Go||_t||Bo||(l.source==="bridge"&&te?`${bt(te)}: ${Ot}`:l.message),Xn=p.useMemo(()=>Oc(l.latestTaskBatch,l.recentTaskBatches),[l.latestTaskBatch,l.recentTaskBatches]),Ie=_c(Xn),ft=l.source==="bridge"&&!!(Xn&&Ie);p.useEffect(()=>{L.current=e.metadata??{}},[e.metadata]);const Qn=p.useCallback((s,d)=>{const u=L.current??{},b=Object.entries(d).filter(([w,A])=>u[w]!==A).map(([w])=>w);if(b.length===0)return;const C={...u,...d};L.current=C,t(e.id,{metadata:C}),h.emit("remoteMonitor.node.metadata.patch",{nodeId:e.id,reason:s,keys:b})},[e.id,t]);p.useEffect(()=>{l.loading||Qn("snapshot",Lc({source:l.source,hub:l.hub,baseUrl:l.baseUrl,hubLabel:qo,routeLabel:uo,connected:Gt,total:et,taskCount:$o,taskDispatchCount:Vo,aiCount:Ut,pageLabel:zo,pageStart:X,pageIndex:F,pageCount:E,projectionMode:an,projectedCount:_,visibleBudget:Ae,selectedDeviceId:W,inputLabel:Yo,devices:l.devices,latestTaskBatch:l.latestTaskBatch,recentTaskBatches:l.recentTaskBatches,taskFollowActive:ft,taskFollowKey:Ie,isHostActiveForNode:ie,registryRouteInfo:ae,hostTargetRenewMs:ie?yo:0,autoHostEnabled:ge,agent:l.agent,agentStatusLabel:zt,agentRunning:po,agentReady:Xo,message:l.message}))},[Ut,ge,F,Gt,Xo,po,zt,qo,Yo,ie,E,zo,X,Qn,_,ae,uo,W,l.agent,l.baseUrl,l.devices,l.hub,l.latestTaskBatch,l.loading,l.message,l.recentTaskBatches,l.source,ft,Ie,$o,Vo,et]),p.useEffect(()=>{Ct!==F&&Ze(F)},[F,Ct]),p.useEffect(()=>{const s=new Set(tt);for(const d of f.current.keys())s.has(d)||f.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:F,pageStart:X,visibleBudget:Ae,transportKey:ot})},[F,e.id,X,m,$e.length,ot]),p.useEffect(()=>{if(l.source!=="bridge")return;const s=[ae.status,ae.reason,ae.accountRouteReady?"ready":"local",ae.migrationBlocked?"migration":"",ie?"hosting":"inactive"].join("|");re.current!==s&&(re.current=s,h.emit("remoteMonitor.node.registryRoute",{nodeId:e.id,status:ae.status,reason:ae.reason,accountRouteReady:ae.accountRouteReady,migrationBlocked:ae.migrationBlocked,hostTargetActive:ie}))},[ie,e.id,ae,l.source]),p.useEffect(()=>{ht(rn(e.id))},[e.id]);const Tt=p.useCallback((s,d)=>{Ze(u=>{const b=Math.max(0,Math.min(E-1,u+s));return b!==u&&h.emit("remoteMonitor.node.page",{nodeId:e.id,from:u,to:b,pageCount:E,visibleBudget:Ae,source:d}),b})},[e.id,E]),Jn=p.useCallback((s,d)=>{s.stopPropagation(),Tt(d,"button")},[Tt]),Zn=p.useCallback((s,d)=>{s.preventDefault(),s.stopPropagation(),Uo(u=>{const b=Math.max(0,Math.min(Wt.length-1,u+d));return b!==u&&h.emit("remoteMonitor.node.tileScale",{nodeId:e.id,from:u,to:b,scale:Wt[b],visibleBudget:Ae}),b})},[e.id]);p.useEffect(()=>{var s;(s=c.current)==null||s.scrollTo({left:0,top:0,behavior:"auto"}),me.current=0},[F,We,ot]);const at=p.useCallback(s=>{if(s instanceof HTMLElement){const d=s.closest('[data-testid="remote-monitor-node-wall"]');if(d instanceof HTMLDivElement)return d}return c.current},[]),ea=p.useCallback(s=>s.scrollWidth>s.clientWidth+1||s.scrollHeight>s.clientHeight+1,[]),Qo=p.useCallback(s=>{if(s.button!==0&&s.button!==1)return;const d=s.target instanceof HTMLElement?s.target:null;if(d!=null&&d.closest('button,input,textarea,select,[contenteditable="true"],[contenteditable=""]'))return;const u=at(s.target);if(u){U.current={active:!0,pointerId:s.pointerId,startX:s.clientX,startY:s.clientY,lastX:s.clientX,lastY:s.clientY,scrollLeft:u.scrollLeft,scrollTop:u.scrollTop,didPan:!1,pageTriggered:!1},s.preventDefault(),s.stopPropagation();try{s.currentTarget.setPointerCapture(s.pointerId)}catch{}}},[at]),Jo=p.useCallback(s=>{const d=U.current;if(!(d!=null&&d.active)||d.pointerId!==s.pointerId)return;const u=at(s.target);if(!u)return;const b=s.clientX-d.startX,C=s.clientY-d.startY;if(!d.didPan&&Math.max(Math.abs(b),Math.abs(C))>=Mc&&(d.didPan=!0,Ee.current=!0),d.didPan){u.scrollLeft=d.scrollLeft-b,u.scrollTop=d.scrollTop-C;const w=Math.abs(C)>=Math.abs(b)?C:b;!d.pageTriggered&&E>1&&!ea(u)&&Math.abs(w)>=Ac&&(d.pageTriggered=!0,Tt(w<0?1:-1,"drag"))}d.lastX=s.clientX,d.lastY=s.clientY,s.preventDefault(),s.stopPropagation()},[ea,Tt,at,E]),vt=p.useCallback(s=>{const d=U.current;if(!(!(d!=null&&d.active)||d.pointerId!==s.pointerId)){U.current=null;try{s.currentTarget.releasePointerCapture(s.pointerId)}catch{}if(d.didPan){const u=at(s.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:F,pageCount:E}),s.preventDefault(),s.stopPropagation()}}},[F,at,e.id,E]),Xr=p.useCallback(s=>{const d=s.target instanceof HTMLElement?s.target:null;if(d!=null&&d.closest('[data-input-active="true"]'))return;const u=at(s.target);if(!u)return;const b=u.scrollLeft,C=u.scrollTop;u.scrollLeft+=s.deltaX,u.scrollTop+=s.deltaY;const w=u.scrollLeft!==b||u.scrollTop!==C;!w&&E>1&&Math.abs(s.deltaY)>=Math.abs(s.deltaX)&&(me.current+=s.deltaY,Math.abs(me.current)>=Pc&&(Tt(me.current>0?1:-1,"wheel"),me.current=0)),h.emit("remoteMonitor.node.wallPan",{nodeId:e.id,source:"wheel",dx:Math.round(s.deltaX),dy:Math.round(s.deltaY),moved:w,scrollLeft:Math.round(u.scrollLeft),scrollTop:Math.round(u.scrollTop),pageIndex:F,pageCount:E}),s.preventDefault(),s.stopPropagation()},[Tt,F,at,e.id,E]),Qr=p.useCallback(s=>{s.stopPropagation();const d=$c(s.target.value);ao(u=>u===d?u:(h.emit("remoteMonitor.node.groupMode",{nodeId:e.id,from:u,to:d,projectedCount:$.length,visibleBudget:Ae}),d)),Ze(0)},[$.length,e.id]),Jr=p.useCallback(s=>{s.stopPropagation();const d=s.target.value.slice(0,64);ro(u=>u===d?u:(h.emit("remoteMonitor.node.filter",{nodeId:e.id,reason:"search",searchText:d.trim(),visibilityFilter:Le,capabilityFilter:Ne,projectedCount:$.length,visibleBudget:Ae}),d)),Ze(0)},[Ne,$.length,e.id,Le]),Zr=p.useCallback(s=>{s.stopPropagation();const d=Vc(s.target.value);io(u=>u===d?u:(h.emit("remoteMonitor.node.filter",{nodeId:e.id,reason:"visibility",searchText:k,from:u,to:d,visibilityFilter:d,capabilityFilter:Ne,projectedCount:$.length,visibleBudget:Ae}),d)),Ze(0)},[Ne,$.length,e.id,k]),ei=p.useCallback(s=>{s.stopPropagation();const d=qc(s.target.value);so(u=>u===d?u:(h.emit("remoteMonitor.node.filter",{nodeId:e.id,reason:"capability",searchText:k,visibilityFilter:Le,from:u,to:d,capabilityFilter:d,projectedCount:$.length,visibleBudget:Ae}),d)),Ze(0)},[$.length,e.id,k,Le]),ti=p.useCallback((s,d)=>{s.stopPropagation();const u=st(d);if(!u||!o)return;const b=Ht(d);o({sourceNodeId:e.id,deviceId:u,deviceName:bt(d),platform:Qt(d),connected:d.connected===!0,baseUrl:l.baseUrl,framePath:b==null?void 0:b.framePath,frameUrl:b==null?void 0:b.frameUrl,dataUrl:b==null?void 0:b.dataUrl,frameSeq:b==null?void 0:b.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(s="manual")=>{const d=++de.current,u=N();if(y(b=>({...b,loading:!0,baseUrl:u})),!Et()){const b=ko(n,r);y({source:"blocked",loading:!1,message:"Hosted LocalBridge access is gated.",baseUrl:u,devices:b}),h.emit("remoteMonitor.node.preview",{nodeId:e.id,reason:"hosted-localbridge-gated",total:b.length});return}try{const b=await xn(u);if(d!==de.current)return;if(b.state!=="connected"){const Ce=ko(n,r);y({source:"unavailable",loading:!1,message:b.message||"LocalBridge is unavailable.",baseUrl:u,bridge:b,devices:Ce}),h.emit("remoteMonitor.node.preview",{nodeId:e.id,reason:"localbridge-unavailable",total:Ce.length});return}const C=Xa(b.status),w=cs(C,u).catch(Ce=>{h.emit("remoteMonitor.node.agent.status",{nodeId:e.id,reason:s,ok:!1,error:Ce instanceof Error?Ce.message:String(Ce)})}),[A,q,B]=await Promise.all([Qa(C,u),Ja(C,u,{includeDataUrl:!1}),w]);if(d!==de.current)return;const fe=Array.isArray(q.devices)?q.devices:[];y({source:"bridge",loading:!1,message:A.started?"RemoteHub online.":A.enabled===!1?A.lastError||"RemoteHub adapter is not configured.":"RemoteHub available.",baseUrl:u,bridge:b,auth:C,hub:A,agent:B,latestTaskBatch:q.latestTaskBatch,recentTaskBatches:Array.isArray(q.recentTaskBatches)?q.recentTaskBatches:[],devices:fe}),h.emit("remoteMonitor.node.refresh",{nodeId:e.id,reason:s,total:q.total??fe.length,connected:fe.filter(Ce=>Ce.connected===!0).length,agentStatus:S(B==null?void 0:B.status),agentRunning:(B==null?void 0:B.running)===!0}),B&&h.emit("remoteMonitor.node.agent.status",{nodeId:e.id,reason:s,ok:!0,status:S(B.status),running:B.running===!0,ready:B.ready===!0})}catch(b){if(d!==de.current)return;const C=ko(n,r);y({source:"unavailable",loading:!1,message:b instanceof Error?b.message:String(b),baseUrl:u,devices:C}),h.emit("remoteMonitor.node.preview",{nodeId:e.id,reason:"remotehub-error",total:C.length})}},[r,n,e.id]);p.useEffect(()=>{se("mount")},[se]);const Vt=p.useCallback((s,d,u)=>{const b=qr(M.current,s);if(!b)return!1;const{cached:C,scope:w}=b;return Ao(d,C,v.current,x.current).then(A=>{A&&h.emit("remoteMonitor.node.frameCache",{nodeId:e.id,deviceId:s,frameSeq:mt(C.metadata),scope:w,reason:u})}),!0},[e.id]),oi=p.useCallback((s,d)=>{s&&(d?(f.current.set(s,d),Vt(s,d,"canvas-attach")):f.current.delete(s))},[Vt]);p.useEffect(()=>{for(const s of he){const d=st(s),u=f.current.get(d);if(!u)continue;const b=Ht(s),C=_n(b);l.source==="bridge"&&C?Tn(u,d,b,l.baseUrl,v.current,x.current,M.current).then(w=>{w.painted||w.busy||(w.staleDropped&&h.emit("remoteMonitor.node.frameStaleDropped",{nodeId:e.id,deviceId:d,frameSeq:w.frameSeq,previous:w.previous,source:"projection"}),!(l.source==="bridge"&&Vt(d,u,"projection-rerender"))&&Po(u,s,l.source))}):l.source==="bridge"&&Vt(d,u,"projection-rerender")||Po(u,s,l.source)}},[e.id,Vt,l.baseUrl,l.source,he]);const Zo=p.useCallback(async(s,d)=>{const u=S(s.deviceId).trim();if(!u)return;const b=S(s.streamId).trim(),C=Number(s.frameSeq||0)||0,w=Fn(x.current,M.current,u),A=G.current.get(u)||"",q=!!(b&&A&&b!==A);if(q&&(x.current.delete(u),h.emit("remoteMonitor.node.frameStreamReset",{nodeId:e.id,deviceId:u,fromStreamId:A,toStreamId:b,previous:w,frameSeq:C})),!q&&C>0&&C<=w){h.emit("remoteMonitor.node.frameStaleDropped",{nodeId:e.id,deviceId:u,frameSeq:C,previous:w,source:"ws"});return}const B=fr(s,d.byteLength);B.level!=="nominal"&&h.emit("remoteMonitor.node.framePressure",{nodeId:e.id,deviceId:u,frameSeq:C,streamId:b,...B});const fe=$r(M.current,u,s,d),Ce=f.current.get(u);if(Ce){if(v.current.has(u)){h.emit("remoteMonitor.node.frameCache",{nodeId:e.id,deviceId:u,frameSeq:C,scope:"local",reason:"decode-pending"});return}v.current.add(u);try{await Bn(Ce,fe.metadata,fe.payload)&&(C>0&&x.current.set(u,C),b&&G.current.set(u,b),V.current+=1,V.current%12===1&&h.emit("remoteMonitor.node.framePainted",{nodeId:e.id,deviceId:u,frameSeq:C,streamId:s.streamId||"",painted:V.current,source:"ws"}))}catch{}finally{v.current.delete(u);const De=M.current.get(u),He=mt(De==null?void 0:De.metadata),ga=x.current.get(u)||0,ha=f.current.get(u);De&&ha&&(He<=0?ga<=0:He>ga)&&Ao(ha,De,v.current,x.current).then(Ii=>{Ii&&(V.current+=1,h.emit("remoteMonitor.node.frameCache",{nodeId:e.id,deviceId:u,frameSeq:He,scope:"local",reason:"latest-pending"}),h.emit("remoteMonitor.node.framePainted",{nodeId:e.id,deviceId:u,frameSeq:He,streamId:De.metadata.streamId||"",painted:V.current,source:"ws-cache"}))})}}},[e.id]);p.useEffect(()=>{if(l.source!=="bridge"||!m||!Ko)return;const s=Na(ot);if(s.length===0)return;let d=!1,u=null,b=0;const C=()=>{var w,A;if(!d){pe.current=!1;try{u=new WebSocket(Or(l.baseUrl,Ko,(A=(w=l.bridge)==null?void 0:w.status)==null?void 0:A.bridgeToken,s)),u.binaryType="arraybuffer"}catch(q){h.emit("remoteMonitor.node.frameWs",{nodeId:e.id,ok:!1,error:q instanceof Error?q.message:String(q)});return}u.onopen=()=>{pe.current=!0,P.current=performance.now(),h.emit("remoteMonitor.node.frameWs",{nodeId:e.id,ok:!0,deviceCount:s.length,fps:Ra}),u==null||u.send(JSON.stringify({type:"subscribe",deviceIds:s,autoStartLive:!0,fps:Ra,maxWidth:640,maxHeight:360,quality:55,mode:"remote-fast"}))},u.onmessage=async q=>{if(!d){if(P.current=performance.now(),q.data instanceof ArrayBuffer){const B=Ro(q.data);B&&await Zo(B.metadata,B.payload);return}if(q.data instanceof Blob){const B=Ro(await q.data.arrayBuffer());B&&await Zo(B.metadata,B.payload)}}},u.onerror=()=>{h.emit("remoteMonitor.node.frameWs",{nodeId:e.id,ok:!1,reason:"socket-error"})},u.onclose=()=>{pe.current=!1,d||(b=window.setTimeout(C,1500))}}};return C(),()=>{d=!0,pe.current=!1,window.clearTimeout(b),u==null||u.close()}},[e.id,Zo,Ko,l.baseUrl,(da=(ca=l.bridge)==null?void 0:ca.status)==null?void 0:da.bridgeToken,l.source,m,ot]),p.useEffect(()=>{if(l.source!=="bridge"||!m)return;const s=Na(ot);if(s.length===0)return;let d=!1,u=!1;const b=async()=>{var A;if(!(d||u)&&!(pe.current&&performance.now()-P.current<wr)){u=!0;try{const q=await Za(s,l.auth,l.baseUrl);if(d||q.ok===!1)return;let B=0,fe=0;for(const Ce of q.frames||[]){const De=String(Ce.deviceId||"").trim();if(!De)continue;const He=await Tn(f.current.get(De),De,zr(Ce),l.baseUrl,v.current,x.current,M.current);He.painted&&(B+=1),He.staleDropped&&(fe+=1,h.emit("remoteMonitor.node.frameStaleDropped",{nodeId:e.id,deviceId:De,frameSeq:He.frameSeq,previous:He.previous,source:"snapshot"}))}h.emit("remoteMonitor.node.frameSnapshot",{nodeId:e.id,deviceCount:s.length,frameCount:((A=q.frames)==null?void 0:A.length)||0,painted:B,staleDropped:fe})}catch{}finally{u=!1}}},C=window.setTimeout(b,200),w=window.setInterval(b,vc);return()=>{d=!0,window.clearTimeout(C),window.clearInterval(w)}},[e.id,l.auth,l.baseUrl,l.source,m,ot]),p.useEffect(()=>{J(!1),oe("locked"),ne("Remote input locked.")},[W,l.source]),p.useEffect(()=>{!R||je||(J(!1),oe("unavailable"),ne(nt||"Remote input unavailable."),h.emit("remoteMonitor.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"control-unavailable",deviceId:W}))},[je,nt,R,e.id,W]),p.useEffect(()=>{var u,b,C;if(!R){(u=O.current)==null||u.close(),O.current=null,oe("locked");return}if(!je||!W){oe("unavailable"),ne(nt||"Remote input unavailable.");return}let s=!1,d=null;oe("connecting"),ne("Connecting remote input adapter...");try{d=new WebSocket(jr(l.baseUrl,Wo,(C=(b=l.bridge)==null?void 0:b.status)==null?void 0:C.bridgeToken)),O.current=d}catch(w){const A=w instanceof Error?w.message:String(w);oe("error"),ne(A),h.emit("remoteMonitor.node.input.ws",{nodeId:e.id,ok:!1,deviceId:W,error:A});return}return d.onopen=()=>{s||(oe("ready"),ne("Remote input ready."),h.emit("remoteMonitor.node.input.ws",{nodeId:e.id,ok:!0,deviceId:W}))},d.onmessage=w=>{if(s)return;const A=Ir(String(w.data||"{}"));if(A){if(A.type==="RemoteInputSocketReady"){oe("ready");return}h.emit("remoteMonitor.node.input.result",{nodeId:e.id,ok:A.ok,deviceId:A.deviceId||W,inputType:A.inputType,error:A.error}),!A.ok||A.error?ne(A.error||"Remote input failed."):/^pointermove$/i.test(A.inputType)||ne(`${A.inputType||"Input"} queued.`)}},d.onerror=()=>{s||(oe("error"),ne("Remote input socket error."),h.emit("remoteMonitor.node.input.ws",{nodeId:e.id,ok:!1,deviceId:W,reason:"socket-error"}))},d.onclose=()=>{s||(O.current=null,oe("error"),ne("Remote input socket closed."),h.emit("remoteMonitor.node.input.ws",{nodeId:e.id,ok:!1,deviceId:W,reason:"socket-closed"}))},()=>{s=!0,O.current===d&&(O.current=null),d==null||d.close()}},[je,nt,R,e.id,Wo,W,l.baseUrl,(pa=(ua=l.bridge)==null?void 0:ua.status)==null?void 0:pa.bridgeToken]),p.useEffect(()=>{if(!R)return;const s=d=>{d.key==="Escape"&&(d.preventDefault(),J(!1),ne("Remote input locked."),h.emit("remoteMonitor.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"escape",deviceId:W}))};return window.addEventListener("keydown",s,!0),()=>window.removeEventListener("keydown",s,!0)},[R,e.id,W]);const ni=p.useCallback(s=>{s.stopPropagation(),Ya(!0),h.emit("remoteMonitor.node.hostedAccess.enabled",{nodeId:e.id}),se("hosted-access-enabled")},[e.id,se]),ta=p.useCallback(s=>{s.stopPropagation(),se("manual")},[se]),ai=p.useCallback(async s=>{var d,u,b;if(s.stopPropagation(),!go){ue(mo||"RemoteAgent connect unavailable.");return}gt("connect"),ue("Connecting RemoteAgent...");try{const C=await ds($t,l.auth,l.baseUrl);C.agent&&y(A=>A.source==="bridge"?{...A,agent:C.agent,message:A.message}:A);const w=C.ok===!0;ue(w?C.alreadyRunning===!0?"RemoteAgent already running.":C.skipped===!0?C.reason||"RemoteAgent connect skipped.":"RemoteAgent connect requested.":C.error||"RemoteAgent connect failed."),h.emit("remoteMonitor.node.agent.connect",{nodeId:e.id,ok:w,alreadyRunning:C.alreadyRunning===!0,skipped:C.skipped===!0,reason:C.reason||"",status:S((d=C.agent)==null?void 0:d.status),managerCount:((u=$t.managerCandidates)==null?void 0:u.length)??0,error:C.error||""}),w&&await se("agent-connect")}catch(C){const w=C instanceof Error?C.message:String(C);ue(w),h.emit("remoteMonitor.node.agent.connect",{nodeId:e.id,ok:!1,managerCount:((b=$t.managerCandidates)==null?void 0:b.length)??0,error:w})}finally{gt("")}},[go,e.id,se,mo,$t,l.auth,l.baseUrl]),ri=p.useCallback(async s=>{var d;if(s.stopPropagation(),!ho){ue("RemoteAgent is not running.");return}gt("disconnect"),ue("Stopping RemoteAgent...");try{const u=await us("react-remote-monitor-manual",l.auth,l.baseUrl);u.agent&&y(C=>C.source==="bridge"?{...C,agent:u.agent,message:C.message}:C);const b=u.ok===!0;ue(b?"RemoteAgent stopped.":u.error||"RemoteAgent stop failed."),h.emit("remoteMonitor.node.agent.disconnect",{nodeId:e.id,ok:b,status:S((d=u.agent)==null?void 0:d.status),error:u.error||""}),b&&await se("agent-disconnect")}catch(u){const b=u instanceof Error?u.message:String(u);ue(b),h.emit("remoteMonitor.node.agent.disconnect",{nodeId:e.id,ok:!1,error:b})}finally{gt("")}},[ho,e.id,se,l.auth,l.baseUrl]),ii=p.useCallback(async s=>{var u;s.stopPropagation();const d=Br(l.hub);try{const b=await Nn(d);Se("Connect command copied."),h.emit("remoteMonitor.node.connectCommand.copy",{nodeId:e.id,ok:!0,method:b,source:l.source,hasPairPreview:!!((u=l.hub)!=null&&u.pairTokenPreview)})}catch(b){Se(b instanceof Error?b.message:"Clipboard is unavailable."),h.emit("remoteMonitor.node.connectCommand.copy",{nodeId:e.id,ok:!1})}},[e.id,l.hub,l.source]),xt=p.useCallback(async(s,d)=>{if(l.source!=="bridge"||Pe.current)return!1;Pe.current=!0,Se(s?"Requesting host target...":"Clearing host target...");try{const u=await ba(e.id,s,l.auth,l.baseUrl,{leaseMs:Kt});if(u.ok===!0){const b=s&&u.active===!0;ja(e.id,b),ht(b)}return Se(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:ge,ok:u.ok===!0,active:u.active===!0}),await se("host-target"),u.ok===!0&&(s?u.active===!0:u.active!==!0)}catch(u){return Se(u instanceof Error?u.message:String(u)),h.emit("remoteMonitor.node.hostTarget",{nodeId:e.id,reason:d,autoHost:ge,ok:!1}),!1}finally{Pe.current=!1}},[ge,e.id,se,l.auth,l.baseUrl,l.source]),si=p.useCallback(s=>{s.stopPropagation(),xt(!ie,"manual")},[ie,xt]),li=p.useCallback(s=>{s.stopPropagation();const d=!ge;ja(e.id,d),ht(d),Se(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&&xt(!1,"auto-host-disabled")},[ge,ie,e.id,xt,l.source]);p.useEffect(()=>{if(l.source!=="bridge"||!ge||ie||xe.current)return;if(!rn(e.id)){ht(!1);return}let s=!1;return xe.current=!0,Se("Restoring Auto Host..."),h.emit("remoteMonitor.node.autoHost.restore",{nodeId:e.id,requested:!0,source:l.source}),xt(!0,"auto-host-restore").then(d=>{s||(h.emit("remoteMonitor.node.autoHost.restore",{nodeId:e.id,ok:d,source:l.source}),d||Se("Auto Host restore failed."))}).finally(()=>{xe.current=!1}),()=>{s=!0}},[ge,ie,e.id,xt,l.source]),p.useEffect(()=>{if(l.source!=="bridge"||!ie)return;let s=!1;const d=async()=>{if(!(s||Z.current)){Z.current=!0;try{const b=await ba(e.id,!0,l.auth,l.baseUrl,{leaseMs:Kt});h.emit("remoteMonitor.node.hostTarget.renew",{nodeId:e.id,ok:b.ok===!0,active:b.active===!0,leaseMs:Kt}),!s&&(b.ok!==!0||b.active!==!0)&&(Se(b.error||"Host target renewal lost ownership."),await se("host-target-renew"))}catch(b){h.emit("remoteMonitor.node.hostTarget.renew",{nodeId:e.id,ok:!1,active:!1,leaseMs:Kt,error:b instanceof Error?b.message:String(b)}),s||Se(b instanceof Error?b.message:String(b))}finally{Z.current=!1}}},u=window.setInterval(()=>{d()},yo);return h.emit("remoteMonitor.node.hostTarget.renew.timer",{nodeId:e.id,active:!0,intervalMs:yo,leaseMs:Kt}),()=>{s=!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"||!ft||!Ie){ft||(g.current="",H.current=0);return}let s=!1,d=0;g.current!==Ie&&(g.current=Ie,H.current=0);const u=b=>{window.clearTimeout(d),d=window.setTimeout(async()=>{if(s||g.current!==Ie)return;const C=H.current;if(C>=At){h.emit("remoteMonitor.node.task.follow",{nodeId:e.id,active:!1,batchKey:Ie,tick:C,maxTicks:At,reason:"max-ticks"});return}const w=C+1;H.current=w,h.emit("remoteMonitor.node.task.follow",{nodeId:e.id,active:!0,batchKey:Ie,tick:w,maxTicks:At}),await se("task-follow"),!s&&g.current===Ie&&H.current<At&&u(vo)},Math.max(0,b))};return h.emit("remoteMonitor.node.task.follow",{nodeId:e.id,active:!0,batchKey:Ie,intervalMs:vo,maxTicks:At,reason:"start"}),u(wc),()=>{s=!0,window.clearTimeout(d),h.emit("remoteMonitor.node.task.follow",{nodeId:e.id,active:!1,batchKey:Ie,tick:H.current,reason:"cleanup"})}},[e.id,se,l.source,ft,Ie]);const ci=p.useCallback(s=>{if(s.stopPropagation(),R){J(!1),ne("Remote input locked."),h.emit("remoteMonitor.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"manual",deviceId:W});return}if(!je){oe("unavailable"),ne(nt||"Remote input unavailable."),h.emit("remoteMonitor.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"unavailable",deviceId:W});return}J(!0),ne("Connecting remote input adapter..."),h.emit("remoteMonitor.node.input.lock",{nodeId:e.id,unlocked:!0,reason:"manual",deviceId:W})},[je,nt,R,e.id,W]),Ve=p.useCallback(s=>{var q;const d=O.current;if(!R||!je||!W||(d==null?void 0:d.readyState)!==WebSocket.OPEN){s.ack&&ne(R?"Remote input socket is not ready.":"Remote input locked.");return}const u=`remote-node-input-${Date.now()}-${++I.current}`,{ack:b,...C}=s,w=kr({requestId:u,deviceId:W,ack:b,controlLeaseId:(q=l.hub)==null?void 0:q.hostTargetLeaseId,input:C});if(!w){b&&ne("Remote input payload is invalid.");return}const A=S(w.input.type);try{d.send(JSON.stringify(w));const B=++Q.current;(w.ack||B%24===1)&&h.emit("remoteMonitor.node.input.sent",{nodeId:e.id,deviceId:W,inputType:A,sampled:!w.ack,sent:B})}catch(B){const fe=B instanceof Error?B.message:String(B);oe("error"),ne(fe),h.emit("remoteMonitor.node.input.ws",{nodeId:e.id,ok:!1,deviceId:W,error:fe})}},[je,R,e.id,W,(ma=l.hub)==null?void 0:ma.hostTargetLeaseId]);p.useEffect(()=>{if(typeof document>"u")return;const s=d=>{const u=d.detail;if(!u||typeof u!="object")return;const b=S(u.nodeId);if(b&&b!==e.id)return;const C=S(u.deviceId);if(C&&C!==W)return;const w=u.input;!w||typeof w!="object"||Array.isArray(w)||Ve({...w,ack:u.ack!==!1})};return document.addEventListener(Ma,s),()=>document.removeEventListener(Ma,s)},[e.id,W,Ve]);const wt=p.useCallback((s,d,u,b=!1)=>{const C=Mo(s,b);return C?(Ve({type:d,...C,button:Dr(s.button),ack:u}),!0):!1},[Ve]),di=p.useCallback((s,d,u)=>{if(s.stopPropagation(),Fe(d),!u){Qo(s);return}if(wt(s,"pointerDown",!0,!1)){s.preventDefault(),s.currentTarget.focus();try{s.currentTarget.setPointerCapture(s.pointerId)}catch{}}},[wt,Qo]),ui=p.useCallback((s,d)=>{var w,A;if(!d){Jo(s);return}const u=performance.now();if(u-ye.current<Sr)return;ye.current=u;const b=((A=(w=s.currentTarget).hasPointerCapture)==null?void 0:A.call(w,s.pointerId))===!0;wt(s,"pointerMove",!1,b)&&(s.preventDefault(),s.stopPropagation())},[wt,Jo]),pi=p.useCallback((s,d)=>{if(!d){vt(s);return}s.preventDefault(),s.stopPropagation();try{s.currentTarget.releasePointerCapture(s.pointerId)}catch{}wt(s,"pointerUp",!0,!0)},[wt,vt]),mi=p.useCallback((s,d)=>{d||vt(s)},[vt]),gi=p.useCallback((s,d)=>{if(!d)return;const u=Mo(s,!1);u&&(Ve({type:"wheel",...u,deltaX:s.deltaX,deltaY:s.deltaY,ack:!0}),s.preventDefault(),s.stopPropagation())},[Ve]),hi=p.useCallback((s,d,u)=>{if(!u){(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),s.stopPropagation(),Fe(d));return}s.key!=="Escape"&&(s.preventDefault(),s.stopPropagation(),Ve({type:"keyDown",key:s.key,code:s.code,repeat:s.repeat,ack:!0}))},[Ve]),fi=p.useCallback((s,d)=>{!d||s.key==="Escape"||(s.preventDefault(),s.stopPropagation(),Ve({type:"keyUp",key:s.key,code:s.code,repeat:!1,ack:!0}))},[Ve]),en=p.useCallback(async(s,d="selected")=>{var A;if(s.preventDefault(),s.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"&&(!W||!Ho||(te==null?void 0:te.connected)!==!0)){Ue("Selected device cannot accept remote tasks.");return}if(d==="all"&&lo.length<=0){Ue("No task-capable connected devices are available.");return}if(d==="ai"&&co.length<=0){Ue("No AI assist devices are connected.");return}const b=d==="ai"?"ai-assist":"task-only",C=((A=u.split(/\r?\n/)[0])==null?void 0:A.slice(0,96))||"Remote task",w=d==="ai"?co:lo;no(d),Ue(d==="selected"?"Queueing selected task...":"Queueing fleet task...");try{const q=d==="selected"?await er(W,{instruction:u,title:C,approvalLevel:b},l.auth,l.baseUrl):await ps({instruction:u,title:C,approvalLevel:b,deviceIds:w,allConnected:!1},l.auth,l.baseUrl),B=q.ok===!0,fe=d==="selected"?B?1:0:Number("queued"in q?q.queued:0);Ue(B?`Queued ${fe||1} remote task${(fe||1)===1?"":"s"}.`:q.error||"Remote task queue failed."),h.emit("remoteMonitor.node.task.queue",{nodeId:e.id,mode:d,ok:B,queued:fe,approvalLevel:b,deviceId:d==="selected"?W:"",targetCount:d==="selected"?1:w.length,batchId:"batchId"in q?q.batchId:"",error:q.error||""}),B&&(oo(""),await se("task-queued"))}catch(q){const B=q instanceof Error?q.message:String(q);Ue(B),h.emit("remoteMonitor.node.task.queue",{nodeId:e.id,mode:d,ok:!1,approvalLevel:b,deviceId:d==="selected"?W:"",targetCount:d==="selected"?1:w.length,error:B})}finally{no("")}},[Ut,co,e.id,se,Ho,te==null?void 0:te.connected,W,l.auth,l.baseUrl,l.source,lo,Me]),bi=a.jsxs("div",{className:"node-remote-monitor__head-actions",children:[a.jsx("i",{"aria-label":`Remote route ${uo}`}),a.jsxs("span",{className:"node-remote-monitor__head-status","data-testid":"remote-monitor-node-agent-status","data-agent-status":zt,children:["AGENT ",a.jsx("strong",{children:zt})]}),a.jsxs("span",{className:`node-remote-monitor__head-status node-remote-monitor__route-status is-${ae.tone}`,"data-testid":"remote-monitor-node-registry-route","data-registry-route":ae.status,"data-account-route-ready":ae.accountRouteReady?"true":"false","data-registry-migration-blocked":ae.migrationBlocked?"true":"false",title:ae.title,children:["ROUTE ",a.jsx("strong",{children:ae.value})]}),l.source==="bridge"?a.jsxs(a.Fragment,{children:[a.jsxs("button",{type:"button","data-testid":"remote-monitor-node-host",onClick:si,children:[a.jsx(Co,{size:12}),ie?"Clear Host":"Set Host"]}),a.jsxs("button",{type:"button",className:ge?"is-active":"","data-testid":"remote-monitor-node-auto-host","data-auto-host-active":ge?"true":"false",onClick:li,title:ge?"Disable Auto Host restore for this monitor":"Remember this monitor as the Auto Host target",children:[a.jsx(Co,{size:12}),"Auto"]}),a.jsxs("button",{type:"button","data-testid":"remote-monitor-node-agent-connect",onClick:ai,disabled:!go,title:go?"Connect managed RemoteAgent":mo,children:[a.jsx(Pi,{size:12,className:Re==="connect"?"spin-icon":""}),"Start"]}),a.jsxs("button",{type:"button","data-testid":"remote-monitor-node-agent-disconnect",onClick:ri,disabled:!ho,title:ho?"Stop managed RemoteAgent":"RemoteAgent is not running",children:[a.jsx(Ei,{size:12,className:Re==="disconnect"?"spin-icon":""}),"Stop"]})]}):l.source==="blocked"?a.jsxs("button",{type:"button",onClick:ni,children:[a.jsx(Co,{size:12}),"Enable"]}):a.jsxs("button",{type:"button",onClick:ta,children:[a.jsx(xo,{size:12,className:l.loading?"spin-icon":""}),"Refresh"]})]}),yi=a.jsxs("form",{className:"node-remote-monitor__taskbar","data-testid":"remote-monitor-node-taskbar",onSubmit:s=>en(s,"selected"),children:[a.jsx("input",{"aria-label":"Remote task",value:Me,maxLength:1200,onChange:s=>oo(s.target.value),onPointerDown:s=>s.stopPropagation(),placeholder:te?`Task for ${bt(te)}`:"Remote task"}),a.jsxs("button",{type:"submit",disabled:!Wn,title:Wn?"Queue task for selected device":"Selected device cannot accept remote tasks",children:[a.jsx(ln,{size:12,className:Je==="selected"?"spin-icon":""}),"Selected"]}),a.jsxs("button",{type:"button",disabled:!Hn,title:Hn?"Queue task for connected devices":"No connected devices can accept tasks",onClick:s=>en(s,"all"),children:[a.jsx(ln,{size:12,className:Je==="all"?"spin-icon":""}),"All"]}),a.jsxs("button",{type:"button",disabled:!Yn,title:Yn?"Queue AI assist task for connected AI devices":"No AI assist device is connected",onClick:s=>en(s,"ai"),children:[a.jsx(Li,{size:12,className:Je==="ai"?"spin-icon":""}),"AI"]})]}),ki=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":We,"data-tile-scale":Bt,children:[a.jsx("button",{type:"button","aria-label":"Shrink remote monitor tiles","data-testid":"remote-monitor-node-tile-shrink",disabled:We<=0,onClick:s=>Zn(s,-1),children:a.jsx(Ni,{size:12})}),a.jsx("button",{type:"button","aria-label":"Grow remote monitor tiles","data-testid":"remote-monitor-node-tile-grow",disabled:We>=Wt.length-1,onClick:s=>Zn(s,1),children:a.jsx(Fa,{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:s=>s.stopPropagation(),onChange:Qr,children:Ar.map(s=>a.jsx("option",{value:s,children:Kc(s)},s))})]}),a.jsxs("label",{className:"node-remote-monitor__footer-filter","data-testid":"remote-monitor-node-filter","data-filter-active":j?"true":"false",children:[a.jsx("span",{children:"FILTER"}),a.jsx("input",{"aria-label":"Remote monitor search","data-testid":"remote-monitor-node-filter-text",value:Ft,maxLength:64,onPointerDown:s=>s.stopPropagation(),onChange:Jr,placeholder:"Any"}),a.jsx("select",{"aria-label":"Remote monitor visibility filter","data-testid":"remote-monitor-node-visibility-filter",value:Le,onPointerDown:s=>s.stopPropagation(),onChange:Zr,children:Pr.map(s=>a.jsx("option",{value:s,children:Wc(s)},s))}),a.jsx("select",{"aria-label":"Remote monitor capability filter","data-testid":"remote-monitor-node-capability-filter",value:Ne,onPointerDown:s=>s.stopPropagation(),onChange:ei,children:Er.map(s=>a.jsx("option",{value:s,children:Hc(s)},s))})]}),a.jsxs("div",{className:"node-remote-monitor__footer-status",children:[a.jsxs("span",{children:[a.jsx("i",{})," HUB ",a.jsx("strong",{children:qo})]}),a.jsxs("span",{children:["CONNECTED ",a.jsxs("strong",{children:[Gt,"/",et]})]}),a.jsxs("span",{children:["TASK ",a.jsx("strong",{children:$o})]}),a.jsxs("span",{children:["AI ",a.jsx("strong",{children:Ut})]}),a.jsxs("span",{children:["INPUT ",a.jsx("strong",{children:Yo})]}),a.jsxs("span",{children:["PAGE ",a.jsx("strong",{children:zo})]}),a.jsxs("span",{children:[a.jsx("i",{})," ROUTE ",a.jsx("strong",{children:uo})]}),a.jsxs("button",{type:"button","data-testid":"remote-monitor-node-copy-connect",onClick:ii,children:[a.jsx(Ba,{size:12}),"Connect"]}),a.jsxs("button",{type:"button","data-testid":"remote-monitor-node-refresh",onClick:ta,children:[a.jsx(xo,{size:12,className:l.loading?"spin-icon":""}),"Refresh"]}),l.source==="bridge"&&a.jsxs("button",{type:"button","data-testid":"remote-monitor-node-input",onClick:ci,disabled:!je&&!R,title:R||je?Ot:nt,children:[R?a.jsx(Ga,{size:12}):a.jsx(Ua,{size:12}),R?"Lock":"Unlock"]})]})]});return a.jsxs("div",{ref:i,className:"node-remote-monitor","data-testid":"remote-monitor-node","data-remote-source":l.source,"data-remote-canonical-total":et,"data-remote-connected":Gt,"data-remote-projection":an,"data-remote-projected-count":_,"data-remote-visible-budget":Ae,"data-remote-page-index":F,"data-remote-page-count":E,"data-remote-page-start":X,"data-remote-host-active":ie?"true":"false","data-remote-registry-route":ae.status,"data-remote-registry-ready":ae.accountRouteReady?"true":"false","data-remote-registry-migration-blocked":ae.migrationBlocked?"true":"false","data-remote-registry-reason":ae.reason,"data-remote-host-renew-ms":ie?yo:0,"data-remote-auto-host":ge?"true":"false","data-remote-agent-status":zt,"data-remote-agent-running":po?"true":"false","data-remote-agent-ready":Xo?"true":"false","data-remote-task-follow-active":ft?"true":"false","data-remote-task-follow-key":Ie,"data-remote-task-follow-refresh-ms":ft?vo:0,"data-remote-transport-visible":m?"true":"false","data-remote-frame-subscription-active":m&&$e.length>0?"true":"false","data-remote-tile-scale-index":We,"data-remote-tile-scale":Bt,"data-remote-tile-min-width":$n,"data-remote-tile-min-height":Vn,"data-remote-group-mode":ze,"data-remote-visible-group-count":Un,"data-remote-filter-text":k,"data-remote-filter-active":j?"true":"false","data-remote-visibility-filter":Le,"data-remote-capability-filter":Ne,"data-remote-filtered-count":z.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(ji,{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":F,"data-page-count":E,"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":Gt,"data-wall-projection":an,"data-projected-device-count":_,"data-visible-budget":Ae,"data-tile-scale-index":We,"data-tile-scale":Bt,"data-group-mode":ze,"data-visible-group-count":Un,"data-filter-text":k,"data-filter-active":j?"true":"false","data-visibility-filter":Le,"data-capability-filter":Ne,"data-filtered-device-count":z.length,style:{"--remote-node-tile-min-width":`${$n}px`,"--remote-node-tile-min-height":`${Vn}px`},onPointerDown:s=>Qo(s),onPointerMove:s=>Jo(s),onPointerUp:s=>vt(s),onPointerCancel:s=>vt(s),onWheel:Xr,children:[he.map(s=>{const d=st(s),u=bt(s),b=Ht(s),C=d===W,w=R&&je&&C;return a.jsxs("span",{className:`${s.connected===!0?"is-online":""} ${C?"is-selected":""} ${w?"is-input-active":""}`,"aria-label":`${u} remote desktop`,title:`${u} / ${Qt(s)}`,role:"button",tabIndex:w||C?0:-1,"data-device-id":d,"data-connected":s.connected===!0?"true":"false","data-frame-seq":(b==null?void 0:b.frameSeq)??0,"data-can-control":ce(s,"control")?"true":"false","data-can-dispatch-task":ce(s,"taskDispatch")?"true":"false","data-ai-assist":ce(s,"aiAssist")?"true":"false","data-input-active":w?"true":"false","data-group-mode":ze,"data-group-key":Yc(s,ze),onClick:A=>{if(A.stopPropagation(),Ee.current){Ee.current=!1,A.preventDefault();return}Fe(d)},onDoubleClick:A=>ti(A,s),onPointerDown:A=>di(A,d,w),onPointerMove:A=>ui(A,w),onPointerUp:A=>pi(A,w),onPointerCancel:A=>mi(A,w),onWheel:A=>gi(A,w),onKeyDown:A=>hi(A,d,w),onKeyUp:A=>fi(A,w),children:[a.jsx("canvas",{ref:A=>oi(d,A)}),w&&a.jsxs("em",{children:[a.jsx(za,{size:10}),"input"]}),a.jsx("small",{children:u})]},d)}),Array.from({length:Wr},(s,d)=>a.jsx("span",{"aria-label":`Remote desktop slot ${X+he.length+d+1}`,"data-placeholder-slot":"true"},`empty-${F}-${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:F<=0,onClick:s=>Jn(s,-1),children:a.jsx(Di,{size:12})}),a.jsx("span",{className:"node-remote-monitor__pager-track",style:{"--remote-node-page-top":`${Hr}%`,"--remote-node-page-height":`${zn}%`},children:a.jsx("strong",{})}),a.jsx("button",{type:"button","aria-label":"Next monitor page",disabled:F>=E-1,onClick:s=>Jn(s,1),children:a.jsx(Oi,{size:12})})]})]})]}),a.jsxs("div",{className:"node-remote-monitor__external-rail","data-testid":"remote-monitor-node-external-rail",onPointerDown:s=>s.stopPropagation(),onClick:s=>s.stopPropagation(),children:[bi,yi,ki,a.jsx("p",{className:"node-remote-monitor__message",children:Yr})]})]})}function Iu({node:e,onPatch:t}){var ao,Ft,ro,Le,io,Ne,so,ge,ht,et;const o=Nr(e),n=p.useRef(null),r=Lr(n,e.id,"control"),[i,c]=p.useState(()=>{var k;return{source:Et()?"loading":"blocked",loading:!1,message:Et()?"Remote device not checked yet.":"Hosted LocalBridge access is gated.",baseUrl:((k=e.metadata)==null?void 0:k.RemoteBaseUrl)||N(),device:Mt(e)}}),m=p.useRef(null),l=p.useRef(new Set),y=p.useRef(new Map),f=p.useRef(new Map),v=p.useRef(null),x=p.useRef(0),G=p.useRef(0),M=p.useRef(!1),O=p.useRef(0),I=p.useRef(0),Q=p.useRef(0),V=p.useRef(0),pe=p.useRef(e.metadata??{}),[P,ye]=p.useState(!1),[Pe,Z]=p.useState("locked"),[xe,g]=p.useState("Remote input locked."),[H,re]=p.useState(""),[U,Ee]=p.useState(!1),[me,de]=p.useState(""),L=i.device,we=L?bt(L):e.title||"Remote device",Fe=L?Qt(L):((ao=e.metadata)==null?void 0:ao.RemoteFleetDevicePlatform)||"unknown",R=qa((Ft=i.bridge)==null?void 0:Ft.status),J=Ka((ro=i.bridge)==null?void 0:ro.status),ee=i.source==="bridge"&&!!o&&(L==null?void 0:L.connected)===!0&&!!J&&ce(L,"control"),oe=L?ce(L,"taskDispatch"):!1,Ot=i.source==="bridge"&&!!o&&(L==null?void 0:L.connected)===!0&&oe&&!!H.trim()&&!U,ne=P?_r(Pe):ee?"Locked":"Off",Bo=me||xe||i.message;p.useEffect(()=>{pe.current=e.metadata??{}},[e.metadata]);const Se=p.useCallback((k,T)=>{const j=pe.current??{},z=Object.entries(T).filter(([_,E])=>j[_]!==E).map(([_])=>_);if(z.length===0)return;const $={...j,...T};pe.current=$,t(e.id,{metadata:$}),h.emit("remoteControl.node.metadata.patch",{nodeId:e.id,reason:k,keys:z})},[e.id,t]),Re=p.useCallback(async(k="manual")=>{const T=++V.current,j=N();if(c(z=>({...z,loading:!0,baseUrl:j})),!o){c({source:"unavailable",loading:!1,message:"Remote control node has no device id.",baseUrl:j,device:Mt(e)});return}if(!Et()){c({source:"blocked",loading:!1,message:"Hosted LocalBridge access is gated.",baseUrl:j,device:Mt(e)}),h.emit("remoteControl.node.preview",{nodeId:e.id,reason:"hosted-localbridge-gated",deviceId:o});return}try{const z=await xn(j);if(T!==V.current)return;if(z.state!=="connected"){c({source:"unavailable",loading:!1,message:z.message||"LocalBridge is unavailable.",baseUrl:j,bridge:z,device:Mt(e)});return}const $=Xa(z.status),[_,E]=await Promise.all([Qa($,j),Ja($,j,{includeDataUrl:!1})]);if(T!==V.current)return;const F=(Array.isArray(E.devices)?E.devices:[]).find(he=>st(he)===o),X=F||Mt(e);c({source:F?"bridge":"unavailable",loading:!1,message:F?`${bt(X)} ${X.connected===!0?"online.":"offline."}`:"Selected remote device is not in the current RemoteHub inventory.",baseUrl:j,bridge:z,auth:$,hub:_,device:X}),h.emit("remoteControl.node.refresh",{nodeId:e.id,reason:k,deviceId:o,found:!!F,connected:X.connected===!0})}catch(z){if(T!==V.current)return;c({source:"unavailable",loading:!1,message:z instanceof Error?z.message:String(z),baseUrl:j,device:Mt(e)})}},[o,e]);p.useEffect(()=>{Re("mount")},[Re]),p.useEffect(()=>{var k,T,j;Se("snapshot",{SemanticType:"RemoteFleetDevice",RemoteFleetSchemaVersion:"remote-fleet-device@1",RemoteFleetDeviceId:o,RemoteFleetDeviceName:we,RemoteFleetDevicePlatform:Fe,RemoteFleetDeviceConnected:String((L==null?void 0:L.connected)===!0),RemoteFleetDeviceCanControl:String(ee),RemoteFleetDeviceCanDispatchTask:String(oe),RemoteFleetDeviceTasksQueued:String(((k=L==null?void 0:L.counters)==null?void 0:k.tasksQueued)||0),RemoteFleetSourceMonitorNodeId:((T=e.metadata)==null?void 0:T.RemoteFleetSourceMonitorNodeId)||"",RemoteInput:ne,RemoteTask:oe?"available":"unavailable",RemoteHub:i.source==="bridge"?((j=i.hub)==null?void 0:j.started)===!0?"Online":"Ready":i.source==="blocked"?"Gated":i.source,RemoteRoute:i.source==="bridge"?"Local":i.source==="blocked"?"Gated":"Preview",RemoteBaseUrl:i.baseUrl,AdapterState:i.source==="bridge"?"localbridge-connected":i.source==="blocked"?"adapter-gated":i.source})},[ee,oe,L==null?void 0:L.connected,(Le=L==null?void 0:L.counters)==null?void 0:Le.tasksQueued,o,we,ne,e.metadata,Se,Fe,i.baseUrl,(io=i.hub)==null?void 0:io.started,i.source]);const gt=p.useCallback((k,T)=>{if(!o)return!1;const j=qr(f.current,o);if(!j)return!1;const{cached:z,scope:$}=j;return Ao(k,z,l.current,y.current).then(_=>{_&&h.emit("remoteControl.node.frameCache",{nodeId:e.id,deviceId:o,frameSeq:mt(z.metadata),scope:$,reason:T})}),!0},[o,e.id]);p.useEffect(()=>{const k=m.current;if(!k||!L)return;const T=Ht(L),j=_n(T);i.source==="bridge"&&j?Kr(k,j,i.baseUrl).catch(()=>Po(k,L,i.source)):i.source==="bridge"&&gt(k,"projection-rerender")||Po(k,L,i.source)},[L,gt,i.baseUrl,i.source]);const _t=p.useCallback(async(k,T)=>{if(!o||S(k.deviceId).trim()!==o)return;const j=Number(k.frameSeq||0)||0,z=Fn(y.current,f.current,o);if(j>0&&j<=z){h.emit("remoteControl.node.frameStaleDropped",{nodeId:e.id,deviceId:o,frameSeq:j,previous:z,source:"ws"});return}const $=fr(k,T.byteLength);$.level!=="nominal"&&h.emit("remoteControl.node.framePressure",{nodeId:e.id,deviceId:o,frameSeq:j,...$});const _=$r(f.current,o,k,T),E=m.current;if(E){if(l.current.has(o)){h.emit("remoteControl.node.frameCache",{nodeId:e.id,deviceId:o,frameSeq:j,scope:"local",reason:"decode-pending"});return}l.current.add(o);try{await Bn(E,_.metadata,_.payload)&&(j>0&&y.current.set(o,j),I.current+=1,h.emit("remoteControl.node.framePainted",{nodeId:e.id,deviceId:o,frameSeq:j,painted:I.current,source:"ws"}))}catch{}finally{l.current.delete(o);const F=f.current.get(o),X=mt(F==null?void 0:F.metadata),he=y.current.get(o)||0,tt=m.current;F&&tt&&(X<=0?he<=0:X>he)&&Ao(tt,F,l.current,y.current).then($e=>{$e&&(I.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:I.current,source:"ws-cache"}))})}}},[o,e.id]);p.useEffect(()=>{if(i.source!=="bridge"||!o||(L==null?void 0:L.connected)!==!0||!r)return;let k=!1,T=null,j=0;M.current=!1;const z=()=>{var $,_;if(!k){try{T=new WebSocket(Or(i.baseUrl,R,(_=($=i.bridge)==null?void 0:$.status)==null?void 0:_.bridgeToken,[o])),T.binaryType="arraybuffer"}catch(E){h.emit("remoteControl.node.frameWs",{nodeId:e.id,ok:!1,error:E instanceof Error?E.message:String(E)});return}T.onopen=()=>{M.current=!0,O.current=performance.now(),h.emit("remoteControl.node.frameWs",{nodeId:e.id,ok:!0,deviceId:o,fps:20}),T==null||T.send(JSON.stringify({type:"subscribe",deviceIds:[o],autoStartLive:!0,fps:20,maxWidth:960,maxHeight:540,quality:62,mode:"remote-fast-control"}))},T.onmessage=async E=>{if(!k){if(O.current=performance.now(),E.data instanceof ArrayBuffer){const F=Ro(E.data);F&&await _t(F.metadata,F.payload)}else if(E.data instanceof Blob){const F=Ro(await E.data.arrayBuffer());F&&await _t(F.metadata,F.payload)}}},T.onerror=()=>{M.current=!1,h.emit("remoteControl.node.frameWs",{nodeId:e.id,ok:!1,deviceId:o,reason:"socket-error"})},T.onclose=()=>{M.current=!1,k||(j=window.setTimeout(z,1500))}}};return z(),()=>{k=!0,M.current=!1,window.clearTimeout(j),T==null||T.close()}},[L==null?void 0:L.connected,o,e.id,_t,R,i.baseUrl,(so=(Ne=i.bridge)==null?void 0:Ne.status)==null?void 0:so.bridgeToken,i.source,r]),p.useEffect(()=>{if(i.source!=="bridge"||!o||(L==null?void 0:L.connected)!==!0||!r)return;let k=!1,T=!1;const j=async()=>{var _;if(!(k||T)&&!(M.current&&performance.now()-O.current<wr)){T=!0;try{const E=await Za([o],i.auth,i.baseUrl);if(k||E.ok===!1)return;const F=(_=E.frames)==null?void 0:_.find($e=>$e.deviceId===o),X=await Tn(m.current??void 0,o,F?zr(F):void 0,i.baseUrl,l.current,y.current,f.current),he=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:F?1:0,painted:he,staleDropped:tt})}catch{}finally{T=!1}}},z=window.setTimeout(j,250),$=window.setInterval(j,2500);return()=>{k=!0,window.clearTimeout(z),window.clearInterval($)}},[L==null?void 0:L.connected,o,e.id,i.auth,i.baseUrl,i.source,r]),p.useEffect(()=>{!P||ee||(ye(!1),Z("unavailable"),g("Remote input unavailable."),h.emit("remoteControl.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"control-unavailable",deviceId:o}))},[ee,o,P,e.id]),p.useEffect(()=>{var j,z,$;if(!P){(j=v.current)==null||j.close(),v.current=null,Z("locked");return}if(!ee||!o){Z("unavailable"),g("Remote input unavailable.");return}let k=!1,T=null;Z("connecting"),g("Connecting remote input adapter...");try{T=new WebSocket(jr(i.baseUrl,J,($=(z=i.bridge)==null?void 0:z.status)==null?void 0:$.bridgeToken)),v.current=T}catch(_){Z("error");const E=_ instanceof Error?_.message:String(_);g(E),h.emit("remoteControl.node.input.ws",{nodeId:e.id,ok:!1,deviceId:o,error:E});return}return T.onopen=()=>{k||(Z("ready"),g("Remote input ready."),h.emit("remoteControl.node.input.ws",{nodeId:e.id,ok:!0,deviceId:o}))},T.onmessage=_=>{if(k)return;const E=Ir(String(_.data||"{}"));if(E){if(E.type==="RemoteInputSocketReady"){Z("ready");return}h.emit("remoteControl.node.input.result",{nodeId:e.id,ok:E.ok,deviceId:E.deviceId||o,inputType:E.inputType,error:E.error}),!E.ok||E.error?g(E.error||"Remote input failed."):/^pointermove$/i.test(E.inputType)||g(`${E.inputType||"Input"} queued.`)}},T.onerror=()=>{k||(Z("error"),g("Remote input socket error."),h.emit("remoteControl.node.input.ws",{nodeId:e.id,ok:!1,deviceId:o,reason:"socket-error"}))},T.onclose=()=>{k||(v.current=null,Z("error"),g("Remote input socket closed."),h.emit("remoteControl.node.input.ws",{nodeId:e.id,ok:!1,deviceId:o,reason:"socket-closed"}))},()=>{k=!0,v.current===T&&(v.current=null),T==null||T.close()}},[ee,o,P,e.id,J,i.baseUrl,(ht=(ge=i.bridge)==null?void 0:ge.status)==null?void 0:ht.bridgeToken]),p.useEffect(()=>{if(!P)return;const k=T=>{T.key==="Escape"&&(T.preventDefault(),ye(!1),g("Remote input locked."),h.emit("remoteControl.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"escape",deviceId:o}))};return window.addEventListener("keydown",k,!0),()=>window.removeEventListener("keydown",k,!0)},[o,P,e.id]);const ue=p.useCallback(k=>{var F;const T=v.current;if(!P||!ee||!o||(T==null?void 0:T.readyState)!==WebSocket.OPEN){k.ack&&g(P?"Remote input socket is not ready.":"Remote input locked.");return}const j=`remote-control-input-${Date.now()}-${++x.current}`,{ack:z,...$}=k,_=kr({requestId:j,deviceId:o,ack:z,controlLeaseId:(F=i.hub)==null?void 0:F.hostTargetLeaseId,input:$});if(!_){z&&g("Remote input payload is invalid.");return}const E=S(_.input.type);try{T.send(JSON.stringify(_));const X=++G.current;(_.ack||X%24===1)&&h.emit("remoteControl.node.input.sent",{nodeId:e.id,deviceId:o,inputType:E,sampled:!_.ack,sent:X})}catch(X){Z("error"),g(X instanceof Error?X.message:String(X))}},[ee,o,P,e.id,(et=i.hub)==null?void 0:et.hostTargetLeaseId]),Me=p.useCallback((k,T,j,z=!1)=>{const $=Mo(k,z);return $?(ue({type:T,...$,button:Dr(k.button),ack:j}),!0):!1},[ue]),oo=p.useCallback(k=>{if(!(!P||!Me(k,"pointerDown",!0,!1))){k.preventDefault(),k.stopPropagation(),k.currentTarget.focus();try{k.currentTarget.setPointerCapture(k.pointerId)}catch{}}},[Me,P]),Je=p.useCallback(k=>{var $,_;if(!P)return;const T=performance.now();if(T-Q.current<Sr)return;Q.current=T;const j=((_=($=k.currentTarget).hasPointerCapture)==null?void 0:_.call($,k.pointerId))===!0;Me(k,"pointerMove",!1,j)&&(k.preventDefault(),k.stopPropagation())},[Me,P]),no=p.useCallback(k=>{if(P){k.preventDefault(),k.stopPropagation();try{k.currentTarget.releasePointerCapture(k.pointerId)}catch{}Me(k,"pointerUp",!0,!0)}},[Me,P]),Go=p.useCallback(k=>{if(!P)return;const T=Mo(k,!1);T&&(ue({type:"wheel",...T,deltaX:k.deltaX,deltaY:k.deltaY,ack:!0}),k.preventDefault(),k.stopPropagation())},[P,ue]),Ue=p.useCallback(k=>{!P||k.key==="Escape"||(k.preventDefault(),k.stopPropagation(),ue({type:"keyDown",key:k.key,code:k.code,repeat:k.repeat,ack:!0}))},[P,ue]),Ct=p.useCallback(k=>{!P||k.key==="Escape"||(k.preventDefault(),k.stopPropagation(),ue({type:"keyUp",key:k.key,code:k.code,repeat:!1,ack:!0}))},[P,ue]),Ze=p.useCallback(k=>{k.stopPropagation(),Ya(!0),Re("hosted-access-enabled")},[Re]),We=p.useCallback(k=>{if(k.stopPropagation(),P){ye(!1),g("Remote input locked."),h.emit("remoteControl.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"manual",deviceId:o});return}if(!ee){Z("unavailable"),g("Remote input unavailable."),h.emit("remoteControl.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"unavailable",deviceId:o});return}ye(!0),g("Connecting remote input adapter..."),h.emit("remoteControl.node.input.lock",{nodeId:e.id,unlocked:!0,reason:"manual",deviceId:o})},[ee,o,P,e.id]),Uo=p.useCallback(k=>{k.stopPropagation(),Re("manual")},[Re]),ze=p.useCallback(async k=>{var $;if(k.preventDefault(),k.stopPropagation(),i.source!=="bridge"){de("LocalBridge is not connected.");return}const T=H.trim();if(!T){de("Remote task is empty.");return}if(!o||(L==null?void 0:L.connected)!==!0||!oe){de("This device cannot accept remote tasks.");return}const j="task-only",z=(($=T.split(/\r?\n/)[0])==null?void 0:$.slice(0,96))||"Remote task";Ee(!0),de("Queueing device task...");try{const _=await er(o,{instruction:T,title:z,approvalLevel:j},i.auth,i.baseUrl),E=_.ok===!0;de(E?"Queued remote task.":_.error||"Remote task queue failed."),h.emit("remoteControl.node.task.queue",{nodeId:e.id,ok:E,deviceId:o,approvalLevel:j,queued:E?1:0,taskId:_.taskId||"",commandId:_.commandId||"",error:_.error||""}),E&&(re(""),await Re("task-queued"))}catch(_){const E=_ instanceof Error?_.message:String(_);de(E),h.emit("remoteControl.node.task.queue",{nodeId:e.id,ok:!1,deviceId:o,approvalLevel:j,queued:0,error:E})}finally{Ee(!1)}},[oe,L==null?void 0:L.connected,o,e.id,Re,i.auth,i.baseUrl,i.source,H]);return a.jsxs("div",{ref:n,className:"node-remote-control","data-testid":"remote-control-node","data-remote-source":i.source,"data-remote-transport-visible":r?"true":"false","data-remote-frame-subscription-active":r&&i.source==="bridge"&&(L==null?void 0:L.connected)===!0?"true":"false",onPointerDown:k=>k.stopPropagation(),children:[a.jsxs("div",{className:"node-remote-control__bar",children:[a.jsx("strong",{title:we,children:we}),a.jsx("span",{children:Fe}),a.jsx("button",{type:"button",title:"Refresh remote device",onClick:Uo,children:a.jsx(xo,{size:12,className:i.loading?"spin-icon":""})}),i.source==="blocked"?a.jsxs("button",{type:"button",onClick:Ze,children:[a.jsx(Co,{size:12}),"Enable"]}):a.jsxs("button",{type:"button",disabled:!ee&&!P,onClick:We,children:[P?a.jsx(Ga,{size:12}):a.jsx(Ua,{size:12}),P?"Lock":"Unlock"]})]}),a.jsxs("div",{className:`node-remote-control__screen ${P&&ee?"is-input-active":""}`,tabIndex:P&&ee?0:-1,onPointerDown:oo,onPointerMove:Je,onPointerUp:no,onWheel:Go,onKeyDown:Ue,onKeyUp:Ct,children:[a.jsx("canvas",{ref:m}),P&&ee&&a.jsxs("em",{children:[a.jsx(za,{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:H,maxLength:1200,onChange:k=>re(k.target.value),onPointerDown:k=>k.stopPropagation(),placeholder:oe?`Task for ${we}`:"Task unavailable"}),a.jsxs("button",{type:"submit",disabled:!Ot,title:Ot?"Queue task for this device":"This device cannot accept remote tasks",children:[a.jsx(ln,{size:12,className:U?"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:(L==null?void 0:L.connected)===!0?"online":"offline"})]}),a.jsxs("span",{children:["INPUT ",a.jsx("strong",{children:ne})]}),a.jsxs("span",{children:["TASK ",a.jsx("strong",{children:oe?"ready":"off"})]}),a.jsxs("span",{children:["ROUTE ",a.jsx("strong",{children:i.source==="bridge"?"Local":i.source==="blocked"?"Gated":"Preview"})]})]}),a.jsx("p",{className:"node-remote-control__message",children:Bo})]})}function Nr(e){var t,o,n;return S(((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 Mt(e){var n,r,i,c,m,l,y,f,v,x,G,M,O;const t=new Date().toISOString();return{deviceId:Nr(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:((i=e.metadata)==null?void 0:i.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:(y=e.metadata)!=null&&y.RemoteFleetLatestFramePath||(f=e.metadata)!=null&&f.RemoteFleetLatestFrameUrl||(v=e.metadata)!=null&&v.RemoteFleetLatestFrameDataUrl?{framePath:(x=e.metadata)==null?void 0:x.RemoteFleetLatestFramePath,frameUrl:(G=e.metadata)==null?void 0:G.RemoteFleetLatestFrameUrl,dataUrl:(M=e.metadata)==null?void 0:M.RemoteFleetLatestFrameDataUrl,frameSeq:Cn((O=e.metadata)==null?void 0:O.RemoteFleetLatestFrameSeq,0)}:void 0}}function Cn(e,t){const o=Number(e);return Number.isFinite(o)&&o>=0?o:t}function S(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):""}function ke(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 jr(e,t,o){const n=e.replace(/^http:/i,"ws:").replace(/^https:/i,"wss:").replace(/\/+$/,""),r=t||"/api/remote/input/ws",i=new URLSearchParams;o&&i.set("token",o);const c=i.toString();return c?`${n}${r}?${c}`:`${n}${r}`}function Dr(e){return e===2?"right":e===1?"middle":"left"}function Mo(e,t=!1){const o=Ec(e.currentTarget);if(!o)return null;const n=o.getBoundingClientRect();if(n.width<=0||n.height<=0)return null;const r=to.get(o)??{left:0,top:0,width:n.width,height:n.height};return gc(e,n,r,t)}function Ec(e){return e instanceof HTMLCanvasElement?e:e.querySelector("canvas")}function Na(e){return e.split(",").map(t=>t.trim()).filter(Boolean)}function Or(e,t,o,n){const r=e.replace(/^http:/i,"ws:").replace(/^https:/i,"wss:").replace(/\/+$/,""),i=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}${i}?${m}`:`${r}${i}`}function _r(e){switch(e){case"ready":return"ready";case"connecting":return"connecting";case"unavailable":return"unavailable";case"error":return"error";default:return"locked"}}function ko(e,t){const o=new Date().toISOString(),n=Math.max(12,Math.min(Tc,Math.floor(e||Ae)));return Array.from({length:n},(r,i)=>({deviceId:`remote-node-preview-${i+1}`,deviceName:`Remote ${String(i+1).padStart(2,"0")}`,platform:i%4===0?"linux":"win32",arch:"x64",connected:i<t,lastSeenAt:o,capabilities:{control:!1}}))}function rn(e){if(typeof window>"u")return!1;try{const t=window.localStorage.getItem(kn);if(String(t||"").trim().toLowerCase()!=="true")return!1;const o=String(window.localStorage.getItem(In)||"").trim(),n=String(e||"").trim();return!o||o===n}catch{return!1}}function ja(e,t){if(!(typeof window>"u"))try{t?(window.localStorage.setItem(kn,"true"),window.localStorage.setItem(In,String(e||"").trim())):(window.localStorage.removeItem(kn),window.localStorage.removeItem(In))}catch{}}function Lc({source:e,hub:t,baseUrl:o,hubLabel:n,routeLabel:r,connected:i,total:c,taskCount:m,taskDispatchCount:l,aiCount:y,pageLabel:f,pageStart:v,pageIndex:x,pageCount:G,projectionMode:M,projectedCount:O,visibleBudget:I,selectedDeviceId:Q,inputLabel:V,devices:pe,latestTaskBatch:P,recentTaskBatches:ye,taskFollowActive:Pe,taskFollowKey:Z,isHostActiveForNode:xe,registryRouteInfo:g,hostTargetRenewMs:H,autoHostEnabled:re,agent:U,agentStatusLabel:Ee,agentRunning:me,agentReady:de,message:L}){const we=On(t),Fe=xe?"hosting":(t==null?void 0:t.hostTargetActive)===!0?"other-monitor":"inactive",R=Dc(pe);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:we,RemoteFleetManagerPackage:S(t==null?void 0:t.managerPackage)||"mindexec-ai",RemoteFleetManagerVersion:S(t==null?void 0:t.managerVersion),RemoteFleetAgentPackage:S(t==null?void 0:t.agentPackage)||"@mindexec/remote",RemoteFleetPairTokenPreview:S(t==null?void 0:t.pairTokenPreview)||"<pair-token>",RemoteFleetConnectCommand:Br(t),RemoteFleetDeviceCount:String(c),RemoteFleetConnectedDeviceCount:String(i),RemoteFleetDevicesJson:JSON.stringify(R),RemoteFleetLatestTaskBatchJson:P?JSON.stringify(Da(P)):"",RemoteFleetRecentTaskBatchesJson:JSON.stringify((ye??[]).slice(0,6).map(Da)),RemoteFleetTaskFollowActive:String(Pe),RemoteFleetTaskFollowKey:Z,RemoteFleetTaskFollowRefreshMs:String(Pe?vo:0),RemoteFleetTaskFollowMaxTicks:String(At),RemoteFleetProjectionMode:M,RemoteFleetProjectedDeviceCount:String(O),RemoteFleetCanvasPagination:`${M}:${x+1}/${G}`,RemoteFleetHostTargetState:Fe,RemoteFleetHostTargetNodeId:S(t==null?void 0:t.hostTargetNodeId),RemoteFleetHostTargetLeaseId:S(t==null?void 0:t.hostTargetLeaseId),RemoteFleetRegistryStatus:g.status,RemoteFleetRegistryReason:g.reason,RemoteFleetAccountRouteReady:String(g.accountRouteReady),RemoteFleetRegistryMigrationBlocked:String(g.migrationBlocked),RemoteFleetHostTargetRenewMs:String(H),RemoteFleetAutoHost:String(re),RemoteFleetHostTargetEndpoint:S(t==null?void 0:t.hostTargetEndpoint)||we,RemoteFleetHostTargetActivatedAtUtc:S(t==null?void 0:t.hostTargetActivatedAt),RemoteFleetHostTargetUpdatedAtUtc:S(t==null?void 0:t.hostTargetUpdatedAt),RemoteFleetHostTargetExpiresAtUtc:S(t==null?void 0:t.hostTargetExpiresAt),RemoteAgentStatus:Ee,RemoteAgentRunning:String(me),RemoteAgentReady:String(de),RemoteAgentManager:S(U==null?void 0:U.manager),RemoteAgentLeaseId:S(U==null?void 0:U.leaseId),RemoteAgentNodeId:S(U==null?void 0:U.nodeId),RemoteAgentUpdatedAtUtc:S(U==null?void 0:U.updatedAt),RemoteAgentLastError:S((U==null?void 0:U.lastError)||(U==null?void 0:U.reconnectReason)),RemoteFleetLastError:e==="bridge"?S(t==null?void 0:t.lastError):L,RemoteHub:n,RemoteRoute:r,RemoteRegistryRoute:g.status,RemoteRegistryReason:g.reason,RemoteConnected:String(i),RemoteTotal:String(c),RemoteProjected:String(O),RemoteProjection:M,RemotePage:f,RemotePageStart:String(v),RemoteVisibleBudget:String(I),RemoteSelectedDeviceId:Q,RemoteInput:V,RemoteTasksQueued:String(m),RemoteTaskDevices:String(l),RemoteAiDevices:String(y),RemoteBaseUrl:o,AdapterState:e==="bridge"?"localbridge-connected":e==="blocked"?"adapter-gated":e}}function Nc(e,t){const o=S(e==null?void 0:e.agentEndpointRouteReason).trim(),n=(e==null?void 0:e.agentEndpointAccountRouteReady)===!0,r=Fr(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."}:jc(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 Fr(e){return/registry-table-unavailable|PGRST20[25]|remote_host_targets|set_remote_host_target|clear_remote_host_target/i.test(String(e||""))}function jc(e){return Fr(e)||/invalid-manager-endpoint|blocked|failed|error|unavailable|unauthori[sz]ed|forbidden/i.test(String(e||""))}function On(e){const t=S(e==null?void 0:e.agentEndpoint).trim();if(t)return t;const o=S((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 Br(e){const t=On(e),o=S(e==null?void 0:e.pairTokenPreview).trim()||"<pair-token>";return`npx @mindexec/remote connect --manager ${t} --pair ${o}`}function Dc(e){return e.filter(t=>t.connected===!0).map(t=>{var r,i,c,m,l,y,f,v,x,G,M;const o=Ht(t),n=t.latestTask;return{deviceId:st(t),sessionId:S(t.sessionId),name:bt(t),hostname:S(t.hostname),platform:Qt(t),arch:S(t.arch),agentVersion:S(t.agentVersion),connected:t.connected===!0,lastSeenAt:S(t.lastSeenAt),lastStatusAt:S(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:S((r=t.capabilities)==null?void 0:r.aiModel),aiProvider:S((i=t.capabilities)==null?void 0:i.aiProvider),thumbnailFrameUrl:S(((c=t.latestThumbnail)==null?void 0:c.frameUrl)||((m=t.latestThumbnail)==null?void 0:m.framePath)),liveFrameUrl:S(((l=t.latestLiveFrame)==null?void 0:l.frameUrl)||((y=t.latestLiveFrame)==null?void 0:y.framePath)),latestFrameSeq:mt(o),liveStreamActive:((f=t.activeLiveStream)==null?void 0:f.active)===!0,liveStreamId:S((v=t.activeLiveStream)==null?void 0:v.streamId),liveStreamFps:ke((x=t.activeLiveStream)==null?void 0:x.fps,0),latestTaskBatchId:S(n==null?void 0:n.batchId),latestTaskId:S(n==null?void 0:n.taskId),latestTaskStatus:S(n==null?void 0:n.status),latestTaskApprovalLevel:S(n==null?void 0:n.approvalLevel),latestTaskResultModel:S(n==null?void 0:n.resultModel),latestTaskResultResponseId:S(n==null?void 0:n.resultResponseId),latestTaskResultSummary:S(n==null?void 0:n.resultSummary),tasksQueued:ke((G=t.counters)==null?void 0:G.tasksQueued,0),taskResultsReceived:ke((M=t.counters)==null?void 0:M.taskResultsReceived,0)}})}function Da(e){return{batchId:S(e.batchId),title:S(e.title),instructionPreview:S(e.instructionPreview),approvalLevel:S(e.approvalLevel),status:S(e.status),requestedAt:S(e.requestedAt),updatedAt:S(e.updatedAt),total:ke(e.total,0),queued:ke(e.queued,0),pending:ke(e.pending,0),completed:ke(e.completed,0),failed:ke(e.failed,0),timedOut:ke(e.timedOut,0)}}function Oc(e,t){return Oa(e)?e:(t??[]).find(Oa)}function _c(e){if(!e)return"";const t=S(e.batchId).trim();return t||[S(e.title).trim(),S(e.requestedAt).trim(),S(e.updatedAt).trim(),String(ke(e.total,0)||"")].filter(Boolean).join(":")}function Oa(e){if(!e)return!1;const t=S(e.status).trim().toLocaleLowerCase(),o=ke(e.pending,0),n=ke(e.total,0),r=ke(e.completed,0),i=ke(e.failed,0),c=ke(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+i+c<n}function Fc(e,t){const o=Bc(e);return{manager:o[0]||"",managerCandidates:o,pairToken:S(e==null?void 0:e.pairToken).trim(),leaseId:S(e==null?void 0:e.hostTargetLeaseId).trim(),nodeId:t,engine:"auto",source:"react-remote-monitor"}}function Bc(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(i=>i.endpoint||i.address),On(e)],n=new Set,r=[];for(const i of o){const c=Gc(i),m=c.toLowerCase();if(!(!c||n.has(m))&&(n.add(m),r.push(c),r.length>=12))break}return r}function Gc(e){const t=S(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 Uc(e,t){if(t==="blocked")return"gated";if(t!=="bridge")return t;if(!e)return"unknown";const o=S(e.status).trim().toLowerCase();return Ur(e)?"ready":o||(Gr(e)?"running":"idle")}function Gr(e){const t=S(e==null?void 0:e.status).trim().toLowerCase();return(e==null?void 0:e.running)===!0||t==="running"||t==="starting"}function Ur(e){const t=S(e==null?void 0:e.status).trim().toLowerCase();return(e==null?void 0:e.ready)===!0||t==="ready"}function zc({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 st(e){return String(e.deviceId||e.sessionId||e.deviceName||"").trim()}function bt(e){return String(e.deviceName||e.hostname||st(e)||"Remote device").trim()}function Qt(e){var t;return String(((t=e.status)==null?void 0:t.platform)||e.platform||"unknown").trim()}function $c(e){return Ar.includes(e)?e:"status"}function Vc(e){return Pr.includes(e)?e:"connected"}function qc(e){return Er.includes(e)?e:"all"}function Kc(e){switch(e){case"activity":return"Activity";case"platform":return"Platform";case"capability":return"Capability";default:return"Status"}}function Wc(e){switch(e){case"all":return"All";case"offline":return"Offline";default:return"Live"}}function Hc(e){switch(e){case"control":return"Control";case"task":return"Task";case"ai":return"AI";default:return"Any"}}function Yc(e,t){switch(t){case"activity":return Xc(e);case"platform":return Qt(e).toLocaleLowerCase()||"unknown";case"capability":return Qc(e);default:return e.connected===!0?"online":"offline"}}function Xc(e){var o,n,r,i;const t=S((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(((i=e.counters)==null?void 0:i.thumbnailFramesReceived)||0)>0?"thumbnail":e.lastStatusAt||e.lastSeenAt?"heartbeat":"idle"}function Qc(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 Ht(e){return e.latestLiveFrame||e.latestThumbnail}function _n(e){return(e==null?void 0:e.dataUrl)||(e==null?void 0:e.frameUrl)||(e==null?void 0:e.framePath)||""}function zr(e){return e.live||e.thumbnail}function mt(e){const t=Number((e==null?void 0:e.frameSeq)||0);return Number.isFinite(t)&&t>0?t:0}function Fn(e,t,o){var n,r;return Math.max(e.get(o)||0,mt((n=t.get(o))==null?void 0:n.metadata),mt((r=Vr(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),Jt(e,yn),Jc(t,r),r}function Jt(e,t,o=Number.POSITIVE_INFINITY){const n=Date.now();for(const[r,i]of e)(!i||!i.payload||Number.isFinite(o)&&n-i.cachedAt>o)&&e.delete(r);for(;e.size>t;){const r=e.keys().next().value;if(!r)break;e.delete(r)}}function Jc(e,t){e&&(Pt.has(e)&&Pt.delete(e),Pt.set(e,{metadata:{...t.metadata,deviceId:e},payload:t.payload,cachedAt:t.cachedAt}),Jt(Pt,Rr,Mr))}function Vr(e){return Jt(Pt,Rr,Mr),Pt.get(e)}function qr(e,t){Jt(e,yn);const o=e.get(t);if(o)return{cached:o,scope:"local"};const n=Vr(t);return n?(e.set(t,n),Jt(e,yn),{cached:n,scope:"global"}):null}async function Ao(e,t,o,n){const r=S(t.metadata.deviceId).trim();if(!r||o.has(r))return!1;const i=mt(t.metadata),c=n.get(r)||0;if(i>0&&i<=c)return!1;o.add(r);try{const m=await Bn(e,t.metadata,t.payload);return m&&i>0&&n.set(r,i),m}catch{return!1}finally{o.delete(r)}}function Fo(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(xc,Math.max(1,window.devicePixelRatio||1)),i=Math.round(o*r),c=Math.round(n*r),m=Math.abs(e.width-i),l=Math.abs(e.height-c);(e.width<=0||e.height<=0||m>Aa||l>Aa)&&(e.width=i,e.height=c);const f=e.getContext("2d",{alpha:!1});return f?(f.setTransform(r,0,0,r,0,0),{ctx:f,width:o,height:n}):null}function Po(e,t,o){const n=Fo(e);if(!n)return;const{ctx:r,width:i,height:c}=n;to.set(e,{left:0,top:0,width:i,height:c});const m=t.connected===!0;r.fillStyle=m?"#ffffff":"#f8fafc",r.fillRect(0,0,i,c),r.strokeStyle=m?"#dbeafe":"#e2e8f0",r.lineWidth=1,r.strokeRect(.5,.5,i-1,c-1),r.fillStyle=m?"#bfdbfe":"#e2e8f0",r.fillRect(8,8,Math.max(12,i*.34),5),r.fillRect(8,18,Math.max(20,i*.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 Kr(e,t,o){const n=t.startsWith("data:")?t:ms(t,o);if(!n)return!1;const r=new Image;r.decoding="async",r.loading="eager",r.src=n,await r.decode();const i=Fo(e);if(!i)return!1;const{ctx:c,width:m,height:l}=i;return c.fillStyle="#020617",c.fillRect(0,0,m,l),to.set(e,Gn(c,r,m,l)),!0}async function Bn(e,t,o){const n=new Blob([o],{type:t.mimeType||"image/jpeg"});let r=null;try{r=await createImageBitmap(n);const i=Fo(e);if(!i)return!1;const{ctx:c,width:m,height:l}=i;return c.fillStyle="#020617",c.fillRect(0,0,m,l),to.set(e,Gn(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 i=Fo(e);if(!i)return!1;const{ctx:c,width:m,height:l}=i;return c.fillStyle="#020617",c.fillRect(0,0,m,l),to.set(e,Gn(c,r,m,l)),!0}catch{return h.emit("remoteMonitor.node.frameDecodeFailed",{deviceId:S(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,i,c){const m=_n(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 y=Number((o==null?void 0:o.frameSeq)||0)||0,f=Fn(i,c,t);if(y>0&&y<=f||y<=0&&f>0)return{painted:!1,busy:!1,staleDropped:!0,frameSeq:y,previous:f};r.add(t);try{const v=await Kr(e,m,n);return v&&y>0&&i.set(t,y),{painted:v,busy:!1,staleDropped:!1,frameSeq:y,previous:f}}catch{return{painted:!1,busy:!1,staleDropped:!1,frameSeq:y,previous:f}}finally{r.delete(t)}}function Gn(e,t,o,n){const r="width"in t?Number(t.width):o,i="height"in t?Number(t.height):n,c=Math.min(o/Math.max(1,r),n/Math.max(1,i)),m=r*c,l=i*c,y=(o-m)/2,f=(n-l)/2;return e.drawImage(t,y,f,m,l),{left:y,top:f,width:m,height:l}}function Cu({launchers:e,activeLauncher:t,template:o,selectedOptionId:n,values:r,validationMessage:i,canCreate:c,primaryLabel:m="Create board",onLauncherSelected:l,onOptionSelected:y,onInputChanged:f,onCreate:v,onClose:x}){const G=(o==null?void 0:o.inputs)??[];return a.jsx("div",{className:"template-launcher-backdrop","data-testid":"template-launcher-panel",onMouseDown:x,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:x,children:a.jsx(Eo,{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(_i,{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:()=>y(M.id),children:[a.jsx("strong",{children:M.label}),a.jsx("span",{children:M.description})]},M.id))})]}),G.length>0&&a.jsx("div",{className:"template-launcher-form",children:G.map(M=>a.jsx(ed,{input:M,value:r[M.key]??"",onChange:O=>f(M.key,O)},M.key))}),i&&a.jsx("div",{className:"template-launcher-validation",children:i}),a.jsxs("footer",{className:"template-launcher-footer",children:[a.jsx("button",{type:"button",className:"template-launcher-secondary",onClick:x,children:"Cancel"}),a.jsxs("button",{type:"button",className:"template-launcher-primary","data-testid":"template-create",disabled:!c,onClick:v,children:[a.jsx(Fa,{size:15}),a.jsx("span",{children:m})]})]})]})})}function ed({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 Tu({node:e,onSave:t,onClose:o}){var y,f,v,x,G,M;const[n,r]=p.useState(((y=e.metadata)==null?void 0:y.DirectoryPath)??e.sourceFilePath??""),[i,c]=p.useState(((f=e.metadata)==null?void 0:f.Include)??""),[m,l]=p.useState(((v=e.metadata)==null?void 0:v.Exclude)??"");return p.useEffect(()=>{var O,I,Q;r(((O=e.metadata)==null?void 0:O.DirectoryPath)??e.sourceFilePath??""),c(((I=e.metadata)==null?void 0:I.Include)??""),l(((Q=e.metadata)==null?void 0:Q.Exclude)??"")},[e.id,(x=e.metadata)==null?void 0:x.DirectoryPath,(G=e.metadata)==null?void 0:G.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:O=>O.stopPropagation(),children:[a.jsxs("header",{className:"directory-settings-head",children:[a.jsxs("div",{children:[a.jsxs("span",{children:[a.jsx(Fi,{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(Eo,{size:16})})]}),a.jsxs("div",{className:"directory-settings-body",children:[a.jsxs("label",{className:"directory-setting-row",children:[a.jsxs("span",{children:[a.jsx(Bi,{size:14}),"LocalBridge path"]}),a.jsx("input",{value:n,placeholder:"E:\\\\Dev@Work\\\\Project or relative/path","data-testid":"directory-settings-path",onChange:O=>r(O.target.value)})]}),a.jsxs("label",{className:"directory-setting-row",children:[a.jsxs("span",{children:[a.jsx(Gi,{size:14}),"Extensions to include"]}),a.jsx("input",{value:i,placeholder:".cs, .js, .razor, .css","data-testid":"directory-settings-include",onChange:O=>c(O.target.value)})]}),a.jsxs("label",{className:"directory-setting-row",children:[a.jsxs("span",{children:[a.jsx(Ui,{size:14}),"Paths/files to exclude"]}),a.jsx("input",{value:m,placeholder:"bin, obj, .git, node_modules","data-testid":"directory-settings-exclude",onChange:O=>l(O.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:i.trim(),Exclude:m.trim()}),children:[a.jsx($a,{size:15}),"Save"]})]})]})})}const sn=[{id:"frame",label:"Frame Perf",icon:zi},{id:"render",label:"Render Debug",icon:$i},{id:"prompt",label:"Prompt Debug",icon:Vi},{id:"points",label:"Points",icon:qi},{id:"dev",label:"Dev",icon:Ki}],Io=[{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}],td=[{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 od(e,t,o){const n=(0-t.x)/t.scale,r=(0-t.y)/t.scale,i=(o.width-t.x)/t.scale,c=(o.height-t.y)/t.scale;return e.nodes.filter(m=>{const l=m.x+m.width,y=m.y+m.height;return l>=n&&m.x<=i&&y>=r&&m.y<=c}).length}function nd(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 ad(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 vu({board:e,selectedNode:t,selectedCount:o,input:n,viewport:r,viewportSize:i,localBridgeState:c,syncStatus:m,syncMessage:l,buildPrompt:y,navigate:f,onClose:v}){const[x,G]=p.useState("frame"),[M,O]=p.useState(""),[I,Q]=p.useState("idle"),[V,pe]=p.useState(null),[P,ye]=p.useState(()=>Object.fromEntries(Io.map(R=>[R.key,R.defaultValue]))),Pe=p.useMemo(()=>od(e,r,i),[e,r,i]),Z=M||y(),xe=p.useMemo(()=>nd(Z,e.settings.effort),[e.settings.effort,Z]),g=p.useMemo(()=>_l(e),[e,e.settings.aiProvider,e.settings.effort,e.settings.imageRouterImageModel,e.settings.imageRouterVideoModel,e.settings.inputMode,e.settings.model]),H=sn.find(R=>R.id===x)??sn[0],re=H.icon;p.useEffect(()=>{if(x!=="points")return;const R=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:R??"",billingKind:g.billingKind,displayPoints:g.displayPoints,pricingSource:g.vendorPricingSource??"none",estimatedFromCatalog:g.isEstimatedFromCatalog})},[x,e.settings.imageRouterImageModel,e.settings.imageRouterVideoModel,e.settings.inputMode,e.settings.model,g.billingKind,g.displayPoints,g.isEstimatedFromCatalog,g.vendorPricingSource]);const U=R=>{G(R),h.emit("promptDebug.tab",{tab:R})},Ee=()=>{const R=y();O(R),pe(new Date().toLocaleTimeString()),Q("idle"),h.emit("promptDebug.build",{tab:x,selectedKind:(t==null?void 0:t.kind)??"none",chars:R.length})},me=async()=>{const R=ad(e,t,M||y());try{const J=await Nn(R);Q("copied"),h.emit("promptDebug.copy",{ok:!0,tab:x,method:J})}catch(J){const ee=document.querySelector('[data-testid="prompt-debug-preview"]');if(ee){ee.focus(),ee.select(),G("prompt"),Q("selected"),h.emit("promptDebug.copy",{ok:!1,selected:!0,tab:x,message:J instanceof Error?J.message:String(J)});return}Q("failed"),h.emit("promptDebug.copy",{ok:!1,tab:x,message:J instanceof Error?J.message:String(J)})}},de=()=>{O(""),pe(null),Q("idle"),h.emit("promptDebug.clear",{tab:x})},L=R=>{ye(Object.fromEntries(Io.map(J=>[J.key,R]))),h.emit("promptDebug.renderToggle",{all:R})},we=()=>{ye(Object.fromEntries(Io.map(R=>[R.key,R.defaultValue]))),h.emit("promptDebug.renderToggle",{reset:!0})},Fe=(R,J)=>{ye(ee=>({...ee,[R]:J})),h.emit("promptDebug.renderToggle",{key:R,value:J})};return a.jsx("div",{className:"prompt-debug-backdrop","data-testid":"prompt-debug-dialog",onMouseDown:v,children:a.jsxs("section",{className:"prompt-debug-dialog","aria-label":"Prompt debugger","data-disable-mindcanvas-hotkeys":"true",onMouseDown:R=>R.stopPropagation(),children:[a.jsxs("header",{className:"prompt-debug-header",children:[a.jsxs("div",{children:[a.jsx(Wi,{size:16}),a.jsx("strong",{children:"Prompt Debugger"})]}),a.jsxs("div",{className:"prompt-debug-header__actions",children:[a.jsxs("button",{type:"button",onClick:Ee,"data-testid":"prompt-debug-build",children:[a.jsx(Hi,{size:13}),"Build"]}),a.jsxs("button",{type:"button",onClick:me,"data-testid":"prompt-debug-copy",children:[I==="copied"?a.jsx($a,{size:13}):a.jsx(Ba,{size:13}),I==="copied"?"Copied":I==="selected"?"Selected":I==="failed"?"Copy failed":"Copy"]}),a.jsxs("button",{type:"button",onClick:de,children:[a.jsx(Yi,{size:13}),"Clear"]}),a.jsx("button",{type:"button",title:"Close debugger",onClick:v,children:a.jsx(Eo,{size:15})})]})]}),a.jsxs("div",{className:"prompt-debug-content",children:[a.jsx("nav",{className:"prompt-debug-tabs","aria-label":"Prompt debugger sections",children:sn.map(R=>{const J=R.icon;return a.jsxs("button",{type:"button",className:x===R.id?"is-active":"","data-testid":`prompt-debug-tab-${R.id}`,onClick:()=>U(R.id),children:[a.jsx(J,{size:14}),R.label]},R.id)})}),a.jsxs("main",{className:"prompt-debug-main",children:[a.jsxs("div",{className:"prompt-debug-section-title",children:[a.jsx(re,{size:15}),a.jsx("strong",{children:H.label}),a.jsx("span",{children:V?`Built ${V}`:"Local React diagnostics"})]}),x==="frame"&&a.jsxs("div",{className:"prompt-debug-metric-grid",children:[a.jsx(qe,{label:"Nodes",value:e.nodes.length,detail:`${Pe} 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"})]}),x==="render"&&a.jsxs("div",{className:"prompt-debug-stack",children:[a.jsxs("div",{className:"prompt-debug-actions",children:[a.jsx("button",{type:"button",onClick:()=>L(!0),children:"Enable all"}),a.jsx("button",{type:"button",onClick:()=>L(!1),children:"Disable all"}),a.jsxs("button",{type:"button",onClick:we,children:[a.jsx(xo,{size:13}),"Reset"]})]}),Io.map(R=>a.jsxs("label",{className:"prompt-debug-toggle",children:[a.jsxs("span",{children:[a.jsx("strong",{children:R.label}),a.jsx("small",{children:R.description})]}),a.jsx("input",{type:"checkbox",checked:P[R.key]??!1,onChange:J=>Fe(R.key,J.target.checked)})]},R.key))]}),x==="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||Z,onChange:R=>O(R.target.value),spellCheck:!1})]}),x==="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:xe.words,detail:"Prompt preview"}),a.jsx(qe,{label:"Tokens",value:xe.estimatedTokens,detail:"Local estimate"}),a.jsx(qe,{label:"Points",value:g.displayLabel,detail:g.basisLabel})]}),a.jsxs("div",{className:"prompt-debug-point-quote","data-testid":"prompt-debug-point-quote","data-billing-kind":g.billingKind,"data-pricing-source":g.vendorPricingSource??"none","data-estimated-from-catalog":g.isEstimatedFromCatalog?"true":"false",children:[a.jsx("span",{children:g.billingKind}),a.jsx("strong",{children:g.displayLabel}),a.jsx("small",{children:g.vendorCostUsdSnapshot===void 0?g.vendorPricingSource??"Local provider":`${g.vendorPricingSource??"catalog"} vendor snapshot $${g.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."})]}),x==="dev"&&a.jsx("div",{className:"prompt-debug-dev-grid",children:td.map(R=>a.jsxs("button",{type:"button",onClick:()=>{h.emit("promptDebug.devTool.open",{route:R.route}),f(R.route)},children:[a.jsx(Xi,{size:14}),a.jsxs("span",{children:[a.jsx("strong",{children:R.label}),a.jsx("small",{children:R.description})]})]},R.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{uu as $,Ad as A,Xa as B,bd as C,Qd as D,Ya as E,Ed as F,Pd as G,nu as H,$s as I,lu as J,mu as K,Dt as L,tr as M,Is as N,Jd as O,No as P,Mn as Q,ku as R,un as S,Lo as T,pn as U,dn as V,du as W,cu as X,Do as Y,qs as Z,Te as _,Hd as a,Nn as a0,Vs as a1,su as a2,qd as a3,Cu as a4,Bs as a5,Zd as a6,Tu as a7,yu as a8,vu as a9,yd as aA,kd as aB,Id as aC,Cd as aD,Td as aE,vd as aF,hd as aG,fd as aH,gd as aI,md as aJ,ud as aK,pd as aL,Md as aM,xd as aN,wd as aO,Sd as aP,Rd as aQ,cd as aR,ld as aS,dd as aT,ar as aa,bu as ab,Ld as ac,or as ad,Fl as ae,Ol as af,Bl as ag,pu as ah,_o as ai,Nd as aj,Ts as ak,Cs as al,Sn as am,wn as an,it as ao,jd as ap,Dd as aq,Od as ar,_d as as,Fd as at,Bd as au,Gd as av,Ud as aw,zd as ax,$d as ay,Vd as az,Wd as b,hu as c,Xd as d,fu as e,Iu as f,N as g,ru as h,gu as i,is as j,eu as k,Nt as l,Us as m,It as n,jo as o,ir as p,tu as q,Kd as r,Et as s,ms as t,au as u,iu as v,Yd as w,zs as x,ou as y,xn as z};