@mindexec/cli 0.2.355 → 0.2.357
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/wwwroot/appsettings.json +83 -0
- package/wwwroot/assets/AdminDashboardPage-DsHcDAoZ.js +1 -0
- package/wwwroot/assets/AppSidebar-BDh-q5Ak.js +1 -0
- package/wwwroot/assets/AuthPages-rcSXkqjo.js +1 -0
- package/wwwroot/assets/{CodePage-zMi_UJaE.js → CodePage-BM1f1VnB.js} +1 -1
- package/wwwroot/assets/{CompanyCorePage-V37js22g.js → CompanyCorePage-BcgESM4i.js} +1 -1
- package/wwwroot/assets/{ExecutionModePage-WoYwTq2j.js → ExecutionModePage-D3oo7YEk.js} +1 -1
- package/wwwroot/assets/{LaunchLeadCapture-C3SfsELA.js → LaunchLeadCapture-DhMxzfOQ.js} +1 -1
- package/wwwroot/assets/{MarketingHome-Cg_3ZuaT.js → MarketingHome-Di28dHQZ.js} +1 -1
- package/wwwroot/assets/{MindCanvas-C5eyrO5Z.js → MindCanvas-Do3lqP59.js} +18 -18
- package/wwwroot/assets/{PlanMasterPage-BNRDnDs3.js → PlanMasterPage-Dc9jGdQ6.js} +1 -1
- package/wwwroot/assets/PricingPage-BYhQK7kr.js +1 -0
- package/wwwroot/assets/{ToolPages-2-8bifXT.js → ToolPages-_JsgqKvE.js} +1 -1
- package/wwwroot/assets/{YouTubeSearchPage-DM1skiy0.js → YouTubeSearchPage-DSjCA5Xo.js} +1 -1
- package/wwwroot/assets/{canvas-runtime-DyQNXrXQ.js → canvas-runtime-hH7qY6Be.js} +2 -2
- package/wwwroot/assets/index-OcBiE4Nr.js +2 -0
- package/wwwroot/assets/{storage-BF01PMeG.js → storage-CWUvUZC-.js} +1 -1
- package/wwwroot/assets/{vendor-icons-Ckw7YAP6.js → vendor-icons-D0xKCnZS.js} +23 -18
- package/wwwroot/index.html +1 -1
- package/wwwroot/assets/AdminDashboardPage-pAvr0347.js +0 -1
- package/wwwroot/assets/AppSidebar-CBDe_h8f.js +0 -1
- package/wwwroot/assets/AuthPages-CmvRijfd.js +0 -1
- package/wwwroot/assets/PricingPage-CXC2_PAJ.js +0 -1
- package/wwwroot/assets/index-BZ5SDUW0.js +0 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{r as p,j as a}from"./vendor-react-BXzpOyCS.js";import{R as g}from"./app-runtime-xD2Z3NdN.js";import{S as gi,L as fi,P as bi,I as La,U as yi,a as ki,b as Ti,X as Po,K as pa,V as Ii,C as vi,B as Ci,c as ko,d as xi,e as wi,R as vo,f as nn,g as Si,M as Ri,h as ja,i as Na,j as Da,k as Oa,l as Mi,m as _a,n as Pi,o as Ai,F as Ei,p as Li,H as ji,q as Ni,r as Di,s as Fa,t as Oi,G as _i,u as Fi,v as Bi,w as Gi,x as Ui,y as zi,T as $i,z as Vi}from"./vendor-icons-Ckw7YAP6.js";const rt="gpt-5.5",qi="gemini-3-flash-preview",Wi="llama3",kn=[{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:Wi,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:qi,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"}],Hi=new Map([["",rt],["openai: gpt-4.1 mini",rt],["gpt-4.1 mini",rt],["gpt-5.3-codex",rt],["gpt-5.2",rt],["gpt-5.2-codex",rt]]);function Yt(e){const t=String(e??"").trim().replace(/^["']|["']$/g,""),o=t.toLowerCase();return Hi.get(o)??t}function Ki(e){const t=Yt(e);return t.includes("/")||t.includes(":")}function Xi(e){const t=Yt(e);return kn.find(o=>o.id===t)??null}function Ba(e){switch(e){case"codex":return"Codex";case"ollama":return"Ollama";case"gemini-cli":return"Gemini CLI";case"openrouter":return"OpenRouter";default:return e}}function ho(e,t){const o=new Map(t.map((n,r)=>[n,r]));return e.map((n,r)=>({option:n,index:r})).filter(({option:n})=>o.has(n.provider)).sort((n,r)=>{const s=o.get(n.option.provider)??Number.MAX_SAFE_INTEGER,c=o.get(r.option.provider)??Number.MAX_SAFE_INTEGER;return s-c||n.index-r.index}).map(({option:n})=>n)}function Yi(e,t=kn){switch(e){case"Local Ollama":return ho(t,["ollama","openrouter"]);case"OpenAI Codex":return ho(t,["codex","openrouter"]);case"Gemini CLI":return ho(t,["gemini-cli"]);case"Managed Cloud":case"BYOK":default:return ho(t,["openrouter"])}}function Qi(e){return e.startsWith("gemini-")?"gemini-cli":e.startsWith("llama")?"ollama":Ki(e)?"openrouter":"codex"}function Ji(e){const t=e.aiProvider??"OpenAI Codex",o=Yi(t),n=Yt(e.model);return n&&!o.some(r=>r.id===n)?[{id:n,label:`${n} (custom)`,provider:Qi(n)},...o]:o}const Tn="gpt-image-2",In="google/veo-2",Zi="1:1",es="16:9",Co="codex-image:",an="codex:",ts=["1024x1024","1536x1024","1024x1536"],os=[{id:"low",label:"Low"},{id:"medium",label:"Mid"},{id:"high",label:"High"}],ns=kn.filter(e=>e.provider==="codex").flatMap(e=>os.map(t=>({id:To(e.id,t.id),label:`Codex Image ${t.label} (${e.label})`,provider:"OpenAI Codex",mode:"Image",supportedSizes:ts}))),as=[{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"]},...ns],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"]}],Ga=[{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}],vn={id:"auto",label:"Auto",resolvedSize:null,note:"Adapter decides the final render size."},ma=.16;function Ao(e){return e==="Image"?as:rs}function Ua(e,t){const o=Cn(t),n=e==="Image"?Tn:In;if(!o)return n;if(e==="Image"){const r=ss(o);if(r)return r;if(cs(o))return us(o)}else{const r=ls(o);if(r)return r}return xn(e,o)??o}function rn(e,t){const o=e==="Image"?t.imageRouterImageModel:t.imageRouterVideoModel,n=Ua(e,o),r=e==="Image"?Tn:In,s=Ao(e),c=s.find(m=>m.id===n)??s.find(m=>m.id===r);return c||{id:n??r,label:n??r,provider:"Saved",mode:e,supportedSizes:e==="Image"?["custom"]:[]}}function za(e,t){if(e.supportedSizes.map(r=>r.toLowerCase()).includes("custom"))return ha(t);const n=e.supportedSizes.map(r=>ps(r)).filter(r=>!!r);return n.length>0?n:t==="Image"?ha(t):[vn]}function sn(e,t,o){const n=za(t,e),r=e==="Image"?Zi:es;return n.find(s=>s.id===o)??n.find(s=>s.id===r)??n[0]??vn}function is(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 ln(e){return e.resolvedSize??"auto"}function ha(e){const t=e==="Image"?"Image":"Video";return[vn,...Ga.map(o=>({id:o.id,label:o.label,resolvedSize:o.size,width:o.width,height:o.height,note:`${t} adapter hint: ${o.size}.`}))]}function Cn(e){return String(e??"").trim().replace(/^["']|["']$/g,"").trim()}function dt(e){return e.trim().toLowerCase().replace(/\s+/g," ")}function ss(e){const t=dt(e);return["gpt-image-2","gpt image 2","gpt-image2","openai/gpt-image-2","openai:gpt-image-2","openai gpt-image-2","openai gpt image 2"].includes(t)?Tn:["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":xn("Image",e)}function ls(e){const t=dt(e);return["google/veo-2","google veo 2","google/veo2","google veo2","veo-2","veo2"].includes(t)?In:xn("Video",e)}function xn(e,t){const o=dt(t),n=Ao(e).find(r=>dt(r.id)===o||dt(r.label)===o);return(n==null?void 0:n.id)??null}function cs(e){const t=dt(e);return t.startsWith(Co)||t.startsWith(an)||t.startsWith("codex image")}function ds(e){const t=dt(Cn(e));return t==="low"?"low":t==="mid"||t==="medium"?"medium":t==="high"?"high":"medium"}function To(e,t){const o=Yt(e)||rt;return`${Co}${o}:${ds(t)}`}function us(e,t=rt){const o=Cn(e),n=dt(o);let r="";if(n.startsWith(Co)?r=o.slice(Co.length).trim():n.startsWith(an)?r=o.slice(an.length).trim():n.startsWith("codex image")&&(r=o.replace(/^codex\s+image\s*/i,"").trim()),!r)return To(t,"medium");const s=r.lastIndexOf(":");return s>0&&s<r.length-1?To(r.slice(0,s),r.slice(s+1)):To(t,r)}function ps(e){const t=ms(e);if(!t)return null;const o=t.width/t.height,n=Ga.map(s=>({definition:s,delta:Math.abs(s.ratio-o)})).sort((s,c)=>s.delta-c.delta)[0];return{id:n&&n.delta<=ma?n.definition.id:`${t.width}:${t.height}`,label:n&&n.delta<=ma?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 ms(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 hs=[{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"}]}],gs=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:hs,templates:gs},ga={en:{"launcher.blank.title":"New Mind Canvas","launcher.blank.desc":"Create a clean execution canvas.","launcher.blank.prompt":"Choose the board you want to create.","launcher.business.title":"Business","launcher.business.desc":"Turn an idea into a revenue model, MVP, and execution plan.","launcher.business.prompt":"What business structure should we start with?","launcher.business.option.saas.title":"SaaS","launcher.business.option.saas.desc":"Subscription SaaS business","launcher.business.option.mobile.title":"Mobile App","launcher.business.option.mobile.desc":"Mobile-first execution board","launcher.business.option.automation.title":"AI Automation","launcher.business.option.automation.desc":"Automation service structure","launcher.business.option.education.title":"Education Product","launcher.business.option.education.desc":"Course or lecture business","launcher.business.option.unknown.title":"Not sure yet","launcher.business.option.unknown.desc":"Explore possible ideas","launcher.build.title":"Build","launcher.build.desc":"Organize a service build from PRD, data, billing, and deployment.","launcher.build.prompt":"What kind of product should we build?","launcher.build.option.webapp.title":"Web App","launcher.build.option.webapp.desc":"Build a web MVP","launcher.build.option.saas_mvp.title":"SaaS MVP","launcher.build.option.saas_mvp.desc":"Launch a subscription SaaS","launcher.build.option.aitool.title":"AI Tool","launcher.build.option.aitool.desc":"Implement an AI-powered service","launcher.build.option.internal.title":"Internal Tool","launcher.build.option.internal.desc":"Team or personal productivity tool","launcher.launch.title":"Launch","launcher.launch.desc":"Plan landing copy, channel posts, assets, and launch schedule.","launcher.launch.prompt":"What launch flow should we prepare?","launcher.launch.option.product_hunt.title":"Product Hunt","launcher.launch.option.product_hunt.desc":"Prepare a launch page","launcher.launch.option.social.title":"X / LinkedIn","launcher.launch.option.social.desc":"Plan social launch posts","launcher.launch.option.community.title":"Community","launcher.launch.option.community.desc":"Plan community distribution","launcher.launch.option.demo.title":"Demo Video","launcher.launch.option.demo.desc":"Prepare a demo asset","launcher.more.title":"More","launcher.more.desc":"Open more execution boards for content, learning, books, and music.","launcher.more.prompt":"Choose the next execution board.","launcher.more.option.content.title":"Content","launcher.more.option.content.desc":"Start video or content production","launcher.more.option.learn.title":"Learn","launcher.more.option.learn.desc":"Create a launch-focused learning board","launcher.more.option.book.title":"Book","launcher.more.option.book.desc":"Start an ebook or story board","launcher.more.option.music.title":"Music","launcher.more.option.music.desc":"Start an audio production studio","templateCard.eyebrow":"Template","templateCard.generate":"Generate","templateCard.noInputs":"No inputs needed.","templateCard.generating":"Generating nodes...","templateCard.generated":"Generated {0} nodes below.","templateCard.failed":"Template generation failed.","templateCard.required":"{0} is required.","template.blank-core.boardTitle":"Canvas {{timestampShort}}","template.business-core.boardTitle":"Business Design - {{optionLabel}}","template.business-core.input.businessIdea.label":"What business do you want to build?","template.business-core.input.businessIdea.desc":"Write the problem and idea you want to solve in one or two sentences.","template.business-core.input.businessIdea.placeholder":"Example: A SaaS that summarizes meetings and assigns follow-up work automatically","template.business-core.input.targetUser.label":"Who is the primary customer?","template.business-core.input.targetUser.desc":"Write the user group most likely to pay first.","template.business-core.input.targetUser.placeholder":"Example: startup team leads, freelance operators","template.business-core.input.businessGoal.label":"Goal for this board","template.business-core.input.businessGoal.desc":"Choose what you want to solve first.","template.business-core.input.businessGoal.option.validate":"Validate the idea","template.business-core.input.businessGoal.option.mvp":"Design the MVP","template.business-core.input.businessGoal.option.monetize":"Design monetization","template.business-core.node.idea.title":"Business Idea","template.business-core.node.idea.body":"{{businessIdea}}","template.business-core.node.target.title":"Target Customers","template.business-core.node.target.body":`First customer candidates: {{targetUser}}
|
|
1
|
+
import{r as p,j as a}from"./vendor-react-BXzpOyCS.js";import{R as g}from"./app-runtime-xD2Z3NdN.js";import{S as gi,L as fi,P as bi,I as La,U as yi,a as ki,b as Ti,X as Po,K as pa,V as Ii,C as vi,B as Ci,c as ko,d as xi,e as wi,R as vo,f as nn,g as Si,M as Ri,h as ja,i as Na,j as Da,k as Oa,l as Mi,m as _a,n as Pi,o as Ai,F as Ei,p as Li,H as ji,q as Ni,r as Di,s as Fa,t as Oi,G as _i,u as Fi,v as Bi,w as Gi,x as Ui,y as zi,T as $i,z as Vi}from"./vendor-icons-D0xKCnZS.js";const rt="gpt-5.5",qi="gemini-3-flash-preview",Wi="llama3",kn=[{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:Wi,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:qi,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"}],Hi=new Map([["",rt],["openai: gpt-4.1 mini",rt],["gpt-4.1 mini",rt],["gpt-5.3-codex",rt],["gpt-5.2",rt],["gpt-5.2-codex",rt]]);function Yt(e){const t=String(e??"").trim().replace(/^["']|["']$/g,""),o=t.toLowerCase();return Hi.get(o)??t}function Ki(e){const t=Yt(e);return t.includes("/")||t.includes(":")}function Xi(e){const t=Yt(e);return kn.find(o=>o.id===t)??null}function Ba(e){switch(e){case"codex":return"Codex";case"ollama":return"Ollama";case"gemini-cli":return"Gemini CLI";case"openrouter":return"OpenRouter";default:return e}}function ho(e,t){const o=new Map(t.map((n,r)=>[n,r]));return e.map((n,r)=>({option:n,index:r})).filter(({option:n})=>o.has(n.provider)).sort((n,r)=>{const s=o.get(n.option.provider)??Number.MAX_SAFE_INTEGER,c=o.get(r.option.provider)??Number.MAX_SAFE_INTEGER;return s-c||n.index-r.index}).map(({option:n})=>n)}function Yi(e,t=kn){switch(e){case"Local Ollama":return ho(t,["ollama","openrouter"]);case"OpenAI Codex":return ho(t,["codex","openrouter"]);case"Gemini CLI":return ho(t,["gemini-cli"]);case"Managed Cloud":case"BYOK":default:return ho(t,["openrouter"])}}function Qi(e){return e.startsWith("gemini-")?"gemini-cli":e.startsWith("llama")?"ollama":Ki(e)?"openrouter":"codex"}function Ji(e){const t=e.aiProvider??"OpenAI Codex",o=Yi(t),n=Yt(e.model);return n&&!o.some(r=>r.id===n)?[{id:n,label:`${n} (custom)`,provider:Qi(n)},...o]:o}const Tn="gpt-image-2",In="google/veo-2",Zi="1:1",es="16:9",Co="codex-image:",an="codex:",ts=["1024x1024","1536x1024","1024x1536"],os=[{id:"low",label:"Low"},{id:"medium",label:"Mid"},{id:"high",label:"High"}],ns=kn.filter(e=>e.provider==="codex").flatMap(e=>os.map(t=>({id:To(e.id,t.id),label:`Codex Image ${t.label} (${e.label})`,provider:"OpenAI Codex",mode:"Image",supportedSizes:ts}))),as=[{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"]},...ns],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"]}],Ga=[{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}],vn={id:"auto",label:"Auto",resolvedSize:null,note:"Adapter decides the final render size."},ma=.16;function Ao(e){return e==="Image"?as:rs}function Ua(e,t){const o=Cn(t),n=e==="Image"?Tn:In;if(!o)return n;if(e==="Image"){const r=ss(o);if(r)return r;if(cs(o))return us(o)}else{const r=ls(o);if(r)return r}return xn(e,o)??o}function rn(e,t){const o=e==="Image"?t.imageRouterImageModel:t.imageRouterVideoModel,n=Ua(e,o),r=e==="Image"?Tn:In,s=Ao(e),c=s.find(m=>m.id===n)??s.find(m=>m.id===r);return c||{id:n??r,label:n??r,provider:"Saved",mode:e,supportedSizes:e==="Image"?["custom"]:[]}}function za(e,t){if(e.supportedSizes.map(r=>r.toLowerCase()).includes("custom"))return ha(t);const n=e.supportedSizes.map(r=>ps(r)).filter(r=>!!r);return n.length>0?n:t==="Image"?ha(t):[vn]}function sn(e,t,o){const n=za(t,e),r=e==="Image"?Zi:es;return n.find(s=>s.id===o)??n.find(s=>s.id===r)??n[0]??vn}function is(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 ln(e){return e.resolvedSize??"auto"}function ha(e){const t=e==="Image"?"Image":"Video";return[vn,...Ga.map(o=>({id:o.id,label:o.label,resolvedSize:o.size,width:o.width,height:o.height,note:`${t} adapter hint: ${o.size}.`}))]}function Cn(e){return String(e??"").trim().replace(/^["']|["']$/g,"").trim()}function dt(e){return e.trim().toLowerCase().replace(/\s+/g," ")}function ss(e){const t=dt(e);return["gpt-image-2","gpt image 2","gpt-image2","openai/gpt-image-2","openai:gpt-image-2","openai gpt-image-2","openai gpt image 2"].includes(t)?Tn:["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":xn("Image",e)}function ls(e){const t=dt(e);return["google/veo-2","google veo 2","google/veo2","google veo2","veo-2","veo2"].includes(t)?In:xn("Video",e)}function xn(e,t){const o=dt(t),n=Ao(e).find(r=>dt(r.id)===o||dt(r.label)===o);return(n==null?void 0:n.id)??null}function cs(e){const t=dt(e);return t.startsWith(Co)||t.startsWith(an)||t.startsWith("codex image")}function ds(e){const t=dt(Cn(e));return t==="low"?"low":t==="mid"||t==="medium"?"medium":t==="high"?"high":"medium"}function To(e,t){const o=Yt(e)||rt;return`${Co}${o}:${ds(t)}`}function us(e,t=rt){const o=Cn(e),n=dt(o);let r="";if(n.startsWith(Co)?r=o.slice(Co.length).trim():n.startsWith(an)?r=o.slice(an.length).trim():n.startsWith("codex image")&&(r=o.replace(/^codex\s+image\s*/i,"").trim()),!r)return To(t,"medium");const s=r.lastIndexOf(":");return s>0&&s<r.length-1?To(r.slice(0,s),r.slice(s+1)):To(t,r)}function ps(e){const t=ms(e);if(!t)return null;const o=t.width/t.height,n=Ga.map(s=>({definition:s,delta:Math.abs(s.ratio-o)})).sort((s,c)=>s.delta-c.delta)[0];return{id:n&&n.delta<=ma?n.definition.id:`${t.width}:${t.height}`,label:n&&n.delta<=ma?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 ms(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 hs=[{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"}]}],gs=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:hs,templates:gs},ga={en:{"launcher.blank.title":"New Mind Canvas","launcher.blank.desc":"Create a clean execution canvas.","launcher.blank.prompt":"Choose the board you want to create.","launcher.business.title":"Business","launcher.business.desc":"Turn an idea into a revenue model, MVP, and execution plan.","launcher.business.prompt":"What business structure should we start with?","launcher.business.option.saas.title":"SaaS","launcher.business.option.saas.desc":"Subscription SaaS business","launcher.business.option.mobile.title":"Mobile App","launcher.business.option.mobile.desc":"Mobile-first execution board","launcher.business.option.automation.title":"AI Automation","launcher.business.option.automation.desc":"Automation service structure","launcher.business.option.education.title":"Education Product","launcher.business.option.education.desc":"Course or lecture business","launcher.business.option.unknown.title":"Not sure yet","launcher.business.option.unknown.desc":"Explore possible ideas","launcher.build.title":"Build","launcher.build.desc":"Organize a service build from PRD, data, billing, and deployment.","launcher.build.prompt":"What kind of product should we build?","launcher.build.option.webapp.title":"Web App","launcher.build.option.webapp.desc":"Build a web MVP","launcher.build.option.saas_mvp.title":"SaaS MVP","launcher.build.option.saas_mvp.desc":"Launch a subscription SaaS","launcher.build.option.aitool.title":"AI Tool","launcher.build.option.aitool.desc":"Implement an AI-powered service","launcher.build.option.internal.title":"Internal Tool","launcher.build.option.internal.desc":"Team or personal productivity tool","launcher.launch.title":"Launch","launcher.launch.desc":"Plan landing copy, channel posts, assets, and launch schedule.","launcher.launch.prompt":"What launch flow should we prepare?","launcher.launch.option.product_hunt.title":"Product Hunt","launcher.launch.option.product_hunt.desc":"Prepare a launch page","launcher.launch.option.social.title":"X / LinkedIn","launcher.launch.option.social.desc":"Plan social launch posts","launcher.launch.option.community.title":"Community","launcher.launch.option.community.desc":"Plan community distribution","launcher.launch.option.demo.title":"Demo Video","launcher.launch.option.demo.desc":"Prepare a demo asset","launcher.more.title":"More","launcher.more.desc":"Open more execution boards for content, learning, books, and music.","launcher.more.prompt":"Choose the next execution board.","launcher.more.option.content.title":"Content","launcher.more.option.content.desc":"Start video or content production","launcher.more.option.learn.title":"Learn","launcher.more.option.learn.desc":"Create a launch-focused learning board","launcher.more.option.book.title":"Book","launcher.more.option.book.desc":"Start an ebook or story board","launcher.more.option.music.title":"Music","launcher.more.option.music.desc":"Start an audio production studio","templateCard.eyebrow":"Template","templateCard.generate":"Generate","templateCard.noInputs":"No inputs needed.","templateCard.generating":"Generating nodes...","templateCard.generated":"Generated {0} nodes below.","templateCard.failed":"Template generation failed.","templateCard.required":"{0} is required.","template.blank-core.boardTitle":"Canvas {{timestampShort}}","template.business-core.boardTitle":"Business Design - {{optionLabel}}","template.business-core.input.businessIdea.label":"What business do you want to build?","template.business-core.input.businessIdea.desc":"Write the problem and idea you want to solve in one or two sentences.","template.business-core.input.businessIdea.placeholder":"Example: A SaaS that summarizes meetings and assigns follow-up work automatically","template.business-core.input.targetUser.label":"Who is the primary customer?","template.business-core.input.targetUser.desc":"Write the user group most likely to pay first.","template.business-core.input.targetUser.placeholder":"Example: startup team leads, freelance operators","template.business-core.input.businessGoal.label":"Goal for this board","template.business-core.input.businessGoal.desc":"Choose what you want to solve first.","template.business-core.input.businessGoal.option.validate":"Validate the idea","template.business-core.input.businessGoal.option.mvp":"Design the MVP","template.business-core.input.businessGoal.option.monetize":"Design monetization","template.business-core.node.idea.title":"Business Idea","template.business-core.node.idea.body":"{{businessIdea}}","template.business-core.node.target.title":"Target Customers","template.business-core.node.target.body":`First customer candidates: {{targetUser}}
|
|
2
2
|
|
|
3
3
|
1. Three first customer groups
|
|
4
4
|
2. Urgent problems for each group
|
|
@@ -40,5 +40,5 @@ Base genre: {{musicGenre}}`,"template.music-core.node.references.title":"Referen
|
|
|
40
40
|
本次目标:{{launchGoal}}`,"template.launch-core.node.landing.title":"落地页文案","template.launch-core.node.landing.body":"快速起草标题、副文案、CTA 和信任元素。","template.launch-core.node.channelCopy.title":"渠道文案","template.launch-core.node.channelCopy.body":"分别为 Product Hunt、X、LinkedIn 和社区写不同文案。","template.launch-core.node.community.title":"社区帖子","template.launch-core.node.community.body":"改写成问题解决经验分享,而不是广告。","template.launch-core.node.demoChecklist.title":"演示视频检查清单","template.launch-core.node.demoChecklist.body":"按问题、解决方案演示和 CTA 顺序整理所需场景。","template.launch-core.node.assets.title":"截图素材","template.launch-core.node.assets.body":"收集代表页面、对比场景、评价和证明图片。","template.launch-core.node.schedule.title":"发布日程","template.launch-core.node.schedule.body":"写下今天、明天和一周内要发布的渠道与时间。","template.launch-core.node.metrics.title":"成果记录","template.launch-core.node.metrics.body":"集中记录访问、注册、支付和表现好的消息。","template.content-core.boardTitle":"内容制作 - {{contentTheme}}","template.content-core.input.contentTheme.label":"要制作什么内容?","template.content-core.input.contentTheme.desc":"写下视频或帖子的核心主题。","template.content-core.input.contentTheme.placeholder":"例如:AI 会议总结工具介绍视频","template.content-core.input.contentChannel.label":"主要渠道","template.content-core.input.contentChannel.desc":"选择第一版内容要面向的渠道。","template.content-core.input.contentChannel.option.youtube":"YouTube","template.content-core.input.contentChannel.option.shorts":"Shorts / Reels","template.content-core.input.contentChannel.option.blog":"博客 / 文章","template.content-core.node.contentPlan.title":"内容计划","template.content-core.node.contentPlan.body":`{{contentTheme}}
|
|
41
41
|
主要渠道:{{contentChannel}}`,"template.content-core.node.script.title":"脚本","template.content-core.node.script.body":"写下开场钩子、核心要点和 CTA。","template.content-core.node.scenes.title":"场景结构","template.content-core.node.scenes.body":"拆分每个场景的信息和所需视觉素材。","template.content-core.node.imagePrompts.title":"图片提示词","template.content-core.node.imagePrompts.body":"为缩略图和转场画面编写图片提示词。","template.content-core.node.videoPrompts.title":"视频提示词","template.content-core.node.videoPrompts.body":"定义镜头运动、氛围和时长。","template.content-core.node.distribution.title":"发布检查","template.content-core.node.distribution.body":"检查标题、说明、缩略图和上传日程。","template.learn-core.boardTitle":"面向发布的学习 - {{learningGoal}}","template.learn-core.input.learningGoal.label":"你为了什么成果而学习?","template.learn-core.input.learningGoal.desc":"写下想做出的东西,而不只是语法或理论。","template.learn-core.input.learningGoal.placeholder":"例如:发布我的第一个 SaaS MVP","template.learn-core.node.goal.title":"学习目标","template.learn-core.node.goal.body":"{{learningGoal}}","template.learn-core.node.basics.title":"核心概念","template.learn-core.node.basics.body":"写下目前缺少的语法和概念,并排序优先级。","template.learn-core.node.smallFeature.title":"做一个小功能","template.learn-core.node.smallFeature.body":"拆成足够小、能完成的功能单位。","template.learn-core.node.api.title":"API 使用","template.learn-core.node.api.body":"整理要连接的 API 和测试场景。","template.learn-core.node.dbAuth.title":"DB / Auth","template.learn-core.node.dbAuth.body":"简单设计存储结构和登录流程。","template.learn-core.node.ship.title":"部署","template.learn-core.node.ship.body":"只写部署所需的最小检查清单。","template.book-core.boardTitle":"书籍 / 电子书 - {{bookTopic}}","template.book-core.input.bookTopic.label":"要做什么书?","template.book-core.input.bookTopic.desc":"写下主题或暂定书名。","template.book-core.input.bookTopic.placeholder":"例如:面向独立创始人的 AI 执行指南","template.book-core.input.readerType.label":"这本书写给谁?","template.book-core.input.readerType.desc":"用一行写下代表读者。","template.book-core.input.readerType.placeholder":"例如:正在做第一个产品的独立创始人","template.book-core.node.bookConcept.title":"书籍概念","template.book-core.node.bookConcept.body":`{{bookTopic}}
|
|
42
42
|
代表读者:{{readerType}}`,"template.book-core.node.toc.title":"目录","template.book-core.node.toc.body":"先整理大章和小节流程。","template.book-core.node.chapters.title":"章节草稿","template.book-core.node.chapters.body":"按章节记录核心信息和案例。","template.book-core.node.cover.title":"插图 / 封面","template.book-core.node.cover.body":"整理需要的视觉素材清单。","template.book-core.node.edit.title":"校对 / 编辑","template.book-core.node.edit.body":"写下语气、重复、流程和 CTA 检查点。","template.book-core.node.export.title":"Export","template.book-core.node.export.body":"完成 PDF、EPUB 和发布渠道的收尾工作。","template.music-core.boardTitle":"音乐制作 - {{trackMood}}","template.music-core.input.trackMood.label":"想做什么氛围的曲子?","template.music-core.input.trackMood.desc":"简短写下情绪或使用场景。","template.music-core.input.trackMood.placeholder":"例如:夜间工作用的 lo-fi 专注曲","template.music-core.input.musicGenre.label":"基础风格","template.music-core.input.musicGenre.desc":"选择最接近的起始风格。","template.music-core.input.musicGenre.option.lofi":"Lo-fi","template.music-core.input.musicGenre.option.ambient":"Ambient","template.music-core.input.musicGenre.option.pop":"Pop","template.music-core.input.musicGenre.option.cinematic":"Cinematic","template.music-core.node.musicConcept.title":"音乐概念","template.music-core.node.musicConcept.body":`{{trackMood}}
|
|
43
|
-
基础风格:{{musicGenre}}`,"template.music-core.node.references.title":"参考","template.music-core.node.references.body":"列出参考曲和想借鉴的点。","template.music-core.node.vocals.title":"人声 / 乐器","template.music-core.node.vocals.body":"写下人声类型和核心乐器配置。","template.music-core.node.lyrics.title":"歌词","template.music-core.node.lyrics.body":"整理主题、重复钩子和禁用表达。","template.music-core.node.generationPrompt.title":"生成提示词","template.music-core.node.generationPrompt.body":"收集音色、结构和氛围指令。","template.music-core.node.versions.title":"版本比较","template.music-core.node.versions.body":"记录 mp3 结果和修改点。"}},Ie={studioNodeType:"studioNodeType",templateNodeId:"templateNodeId",templateRole:"templateRole",compileTarget:"compileTarget",inputKey:"inputKey",inputType:"inputType",inputDescription:"inputDescription",inputPlaceholder:"inputPlaceholder",inputDefaultValue:"inputDefaultValue",inputRequired:"inputRequired",inputOptions:"inputOptions"},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"}],Qc=["note","memo","markdown","aiPrompt","output","section","checklist","input"],q={contentType:"templateLauncher",semanticTypeKey:"semanticType",semanticTypeValue:"TemplateLauncher",launcherIdKey:"templateLauncherId",selectedOptionIdKey:"templateLauncherSelectedOptionId",cardVersionKey:"templateCardVersion",cardLockedKey:"templateCardLocked",controllerNodeIdKey:"sourceTemplateControllerNodeId",runIdKey:"sourceTemplateRunId",cardGeneratedKey:"sourceTemplateCardGenerated",localizationManagedKey:"templateLocalizationManaged",localizationLanguageKey:"templateLanguageCode",sourceInputValuesJsonKey:"sourceTemplateInputValuesJson",width:560,height:620,resultTopGap:90},ut=fs,ys=new Set(["en","ko","ja","zh"]);function yt(e){if(typeof e!="string")return"en";const t=e.trim().toLowerCase();return!t||t==="auto"?"en":ys.has(t)?t:"en"}function le(e,t="",o){const n=yt(o),r=ga[n],s=ga.en,c=r[e];if(c!==void 0)return c;const m=s[e];return n!=="ko"&&m!==void 0?m:t}function Qt(e,t){const o=Ye(e.id);return{...e,label:le(`launcher.${o}.title`,e.label,t),description:le(`launcher.${o}.desc`,e.description,t),prompt:le(`launcher.${o}.prompt`,e.prompt,t),options:e.options.map(n=>Ls(e.id,n,t))}}function Wt(e,t){const o=Ye(e.id);return{...e,boardTitle:le(`template.${o}.boardTitle`,e.boardTitle,t),inputs:e.inputs.map(n=>js(e.id,n,t)),nodes:e.nodes.map(n=>Ns(e.id,n,t))}}function Jc(e){return ut.launchers.map(t=>Qt(t,e))}function ks(e,t){const o=ut.launchers.find(n=>K(n.id,e));return o?Qt(o,t):null}function Eo(e,t){if(e.options.length!==0)return e.options.find(o=>K(o.id,t||""))??e.options[0]}function Ts(e,t,o){const n=Eo(e,t),r=(n==null?void 0:n.templateId)||e.quickCreateTemplateId||"",s=ut.templates.find(c=>K(c.id,r));return s?Wt(s,o):null}function Zc(e){const t={};for(const o of(e==null?void 0:e.inputs)??[])t[o.key]=Sn(o);return t}function ed(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 Is(e,t,o,n){const r=yt(n.appLanguage),s=Qt(e,r),c=Eo(s,t),m=Ts(s,c==null?void 0:c.id,r);return m?vs(s,c,m,o,n):null}function vs(e,t,o,n,r){const s=jo(o,n),c=Wa(e,t,s),m=new Date().toISOString(),l=Xa("template-board"),b=Pt(o.boardTitle,c).trim()||e.label,k=o.nodes.map((x,v)=>xs(x,e,t,o,c,l,v));return{launcher:e,option:t,template:o,board:{id:l,name:b,updatedAt:m,settings:r,source:{kind:"localStorage",loadedAt:m},nodes:k,edges:[]}}}function $a(e,t,o={},n){const r=yt(n),s=Qt(e,r),c=Ds(r),m=Us(s,t),l={launcherId:s.id,title:s.label,description:s.description,prompt:s.prompt,iconClass:s.iconClass,selectedOptionId:m??void 0,options:[],inputValues:{},generateLabel:c.generateLabel,noInputsLabel:c.noInputsLabel,generatingMessage:c.generatingMessage,generatedMessageFormat:c.generatedMessageFormat,generationFailedMessage:c.generationFailedMessage,requiredMessageFormat:c.requiredMessageFormat,actionLabel:c.generateLabel};if(s.options.length===0){const k=s.quickCreateTemplateId?ut.templates.find(x=>K(x.id,e.quickCreateTemplateId)):null;if(k){const x=Wt(k,r);l.options.push({id:"",label:s.label,description:s.description,templateId:x.id,inputs:cn(x.inputs)})}}else for(const k of s.options){const x=ut.templates.find(V=>K(V.id,k.templateId)),v=x?Wt(x,r):null;l.options.push({id:k.id,label:k.label,description:k.description,templateId:k.templateId,inputs:cn((v==null?void 0:v.inputs)??[])})}const b=l.options.find(k=>K(k.id,l.selectedOptionId))??l.options[0];return l.selectedOptionId=b==null?void 0:b.id,l.inputValues=Ha((b==null?void 0:b.inputs)??[],o),l}function td(e,t,o,n,r={},s){const c=yt(s),m=$a(e,t,r,c),l=m.options.find(k=>K(k.id,m.selectedOptionId)),b={[q.semanticTypeKey]:q.semanticTypeValue,[q.launcherIdKey]:e.id,[q.selectedOptionIdKey]:m.selectedOptionId??"",[q.cardVersionKey]:"1.0",[q.cardLockedKey]:"True",[q.localizationLanguageKey]:c,IsNew:"true"};return{id:Xa("template-card"),kind:"template-launcher",title:m.title,body:JSON.stringify(m),x:o,y:n,width:q.width,height:q.height,tags:["Template","Launcher",e.label,l==null?void 0:l.label].filter(k=>!!k),metadata:b,aiEnabled:!1}}function wn(e){var t;return e?e.kind==="template-launcher"?!0:K((t=e.metadata)==null?void 0:t[q.semanticTypeKey],q.semanticTypeValue):!1}function Va(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:cn(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 od(e,t){const o=e.options.find(n=>K(n.id,t))??e.options[0];return{...e,selectedOptionId:o==null?void 0:o.id,inputValues:Ha((o==null?void 0:o.inputs)??[],e.inputValues)}}function nd(e,t,o){return{...e,inputValues:{...e.inputValues,[t]:o}}}function ad(e){if(!e)return"Template card payload is unavailable.";const t=e.options.find(n=>K(n.id,e.selectedOptionId))??e.options[0];if(!t)return"Template card option is unavailable.";const o=t.inputs.find(n=>n.required&&!String(e.inputValues[n.key]||"").trim());return o?Gs(e.requiredMessageFormat||"{0} is required.",o.label):null}function rd(e,t,o,n,r=zs()){var Z;if(!wn(e))return null;const s=(Z=e.metadata)==null?void 0:Z[q.launcherIdKey],c=yt(n.appLanguage),m=s?ks(s,c):null;if(!m)return null;const l=Eo(m,t),b=Is(m,(l==null?void 0:l.id)??null,o,n);if(!b)return null;const k=jo(b.template,o),x=JSON.stringify(k),v=Math.min(...b.board.nodes.map(E=>E.x)),V=Math.min(...b.board.nodes.map(E=>E.y)),M=e.x,F=e.y+Math.max(e.height,q.height)+q.resultTopGap,J=b.board.nodes.map(E=>({...E,x:M+(E.x-v),y:F+(E.y-V),metadata:{...E.metadata??{},[q.controllerNodeIdKey]:e.id,[q.runIdKey]:r,[q.cardGeneratedKey]:"True",[q.localizationManagedKey]:"True",[q.localizationLanguageKey]:c,[q.sourceInputValuesJsonKey]:x}}));return{launcher:m,option:b.option,template:b.template,runId:r,nodes:J}}function id(e,t){const o=yt(t),n=new Map(e.map(c=>[c.id,c]));let r=!1;const s=e.map(c=>{const m=Os(c,o);if(m)return r=!0,m;const l=_s(c,n,o);return l?(r=!0,l):c});return{nodes:r?s:e,changed:r,language:o}}function sd(e){const t=String(e||"").trim()||"Template Studio Draft";return{templateId:Lo(t),templateTitle:t,category:"custom",boardTitle:t,version:"0.1.0",tier:"draft",status:"draft"}}function ld(e,t){const o=[],n=ws(e),r=t.filter(k=>!!ve(k,Ie.studioNodeType)).sort((k,x)=>k.y-x.y||k.x-x.x||k.id.localeCompare(x.id)),s=r.filter(k=>K(ve(k,Ie.studioNodeType),"template.input")),c=r.filter(k=>!K(ve(k,Ie.studioNodeType),"template.input")),m=Ss(s,o),l=Rs(c,o);r.length===0&&o.push({code:"studio.nodes.empty",message:"Add at least one Template Studio node before compiling."});const b={id:n.templateId,version:n.version,tier:n.tier,status:n.status,boardTitle:n.boardTitle,inputs:m,nodes:l};return Ms(b,o),{template:b,manifestJson:JSON.stringify(b,null,2),issues:o}}function Lo(e){return String(e||"").trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"template-studio-draft"}function Cs(e,t){switch(String(e||"").trim().toLowerCase()||qa(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?Ka(t.kind):"note"}}function qa(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 cd(e){const t=bs.find(o=>K(o.studioNodeType,e));return(t==null?void 0:t.shortLabel)??"Note"}function xs(e,t,o,n,r,s,c){const m={};for(const[b,k]of Object.entries(e.metadata??{}))m[b]=Pt(k,r);m.IsNew="true",m.sourceLauncherId=t.id,m.sourceTemplateId=n.id,m.sourceTemplateVersion=n.version,m.sourceTemplateNodeId=e.id,m.templateRole=m.templateRole||e.id,m.templateLauncher=t.id,m.templateId=n.id,m.templateVersion=n.version,m.templateNodeId=e.id,o!=null&&o.id&&(m.sourceOptionId=o.id,m.templateOption=o.id);const l=$s(e.contentType);return{id:`${s}-${e.id||c}`,kind:l,title:Pt(e.title,r),body:Pt(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 jo(e,t){const o={};for(const n of e.inputs){const r=String(t[n.key]??"").trim();o[n.key]=r||Sn(n)}return o}function Wa(e,t,o){const n=(t==null?void 0:t.label)||e.label,r=(t==null?void 0:t.description)||e.description,s={launcherId:e.id,launcherLabel:e.label,launcherDescription:e.description,optionId:(t==null?void 0:t.id)||"",optionLabel:n,optionDescription:r,selectionLabel:n,timestampShort:Vs(new Date)};for(const[c,m]of Object.entries(o))s[c]=m;return s}function Pt(e,t){let o=e||"";for(const[n,r]of Object.entries(t))o=o.replace(new RegExp(`{{\\s*${qs(n)}\\s*}}`,"gi"),r);return o}function Sn(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:Lo(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 Ss(e,t){const o=[],n=new Set;for(const r of e){const s=r.title.trim()||"Input",c=Lo(ve(r,Ie.inputKey)||s),m=c.toLowerCase();if(n.has(m)){t.push({code:"studio.input.duplicate",message:`Template Studio input '${c}' is duplicated.`});continue}n.add(m),o.push({key:c,type:Ps(ve(r,Ie.inputType)),label:s,description:ve(r,Ie.inputDescription)||r.body,placeholder:ve(r,Ie.inputPlaceholder),defaultValue:ve(r,Ie.inputDefaultValue),required:As(ve(r,Ie.inputRequired)),options:Es(ve(r,Ie.inputOptions))})}return o}function Rs(e,t){const o=[],n=new Set;for(const r of e){const s=ve(r,Ie.studioNodeType)||qa(r);let c=Lo(ve(r,Ie.templateNodeId)||r.title);const m=c.toLowerCase();if(n.has(m)){t.push({code:"studio.node.duplicate",message:`Template Studio node '${c}' is duplicated.`});continue}n.add(m);const l=ve(r,Ie.compileTarget)||Cs(s,r),b=ve(r,Ie.templateRole)||s.replace(/^template\./i,"");o.push({id:c,contentType:l,title:r.title.trim(),body:r.body,x:Math.round(r.x),y:Math.round(r.y),width:Math.max(180,Math.round(r.width||340)),height:Math.max(120,Math.round(r.height||220)),metadata:{templateRole:b,studioNodeType:s,compileTarget:l,studioSourceContentType:Ka(r.kind)}})}return o}function Ms(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 Ps(e){const t=e.trim().toLowerCase();return t==="textarea"||t==="select"?t:"text"}function As(e){return e.trim().toLowerCase()==="true"}function Es(e){const t=[];for(const o of e.split(/\r?\n/)){const n=o.trim();if(!n)continue;const[r,s]=n.split("|",2).map(c=>c.trim());r&&t.push({value:r,label:s||r})}return t}function Ls(e,t,o){const n=Ye(e),r=Ye(t.id);return{...t,label:le(`launcher.${n}.option.${r}.title`,t.label,o),description:le(`launcher.${n}.option.${r}.desc`,t.description,o)}}function js(e,t,o){var s;const n=Ye(e),r=Ye(t.key);return{...t,label:le(`template.${n}.input.${r}.label`,t.label,o),description:le(`template.${n}.input.${r}.desc`,t.description,o),placeholder:le(`template.${n}.input.${r}.placeholder`,t.placeholder,o),options:(s=t.options)==null?void 0:s.map(c=>({...c,label:le(`template.${n}.input.${r}.option.${Ye(c.value)}`,c.label,o)}))}}function Ns(e,t,o){const n=Ye(e),r=Ye(t.id);return{...t,title:le(`template.${n}.node.${r}.title`,t.title,o),body:le(`template.${n}.node.${r}.body`,t.body,o),metadata:{...t.metadata??{}}}}function Ds(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 Os(e,t){var m,l,b,k;if(!wn(e))return null;const o=Va(e.body),n=((m=e.metadata)==null?void 0:m[q.launcherIdKey])||(o==null?void 0:o.launcherId),r=n?ut.launchers.find(x=>K(x.id,n)):null;if(!r)return null;const s=(o==null?void 0:o.selectedOptionId)||((l=e.metadata)==null?void 0:l[q.selectedOptionIdKey])||null,c=$a(r,s,(o==null?void 0:o.inputValues)??{},t);return e.title===c.title&&e.body===JSON.stringify(c)&&((b=e.metadata)==null?void 0:b[q.localizationLanguageKey])===t?null:{...e,title:c.title,body:JSON.stringify(c),tags:["Template","Launcher",c.title,(k=c.options.find(x=>x.id===c.selectedOptionId))==null?void 0:k.label].filter(x=>!!x),metadata:{...e.metadata??{},[q.launcherIdKey]:r.id,[q.selectedOptionIdKey]:c.selectedOptionId??"",[q.localizationLanguageKey]:t}}}function _s(e,t,o){if(wn(e))return null;const n=go(Be(e,"sourceTemplateId"),Be(e,"templateId")),r=go(Be(e,"sourceTemplateNodeId"),Be(e,"templateNodeId")),s=go(Be(e,"sourceLauncherId"),Be(e,"templateLauncher"));if(!n||!r||!s)return null;const c=ut.launchers.find(Z=>K(Z.id,s)),m=ut.templates.find(Z=>K(Z.id,n));if(!c||!m)return null;const l=go(Be(e,"sourceOptionId"),Be(e,"templateOption")),b=Fs(e,t),k=jo(Wt(m,o),b),x=Qo(c,m,r,l,k,"ko"),v=yt(Be(e,q.localizationLanguageKey)||"ko"),V=Qo(c,m,r,l,k,v),M=Qo(c,m,r,l,k,o);if(!x||!V||!M)return null;const F=e.title===x.title||e.title===V.title,J=e.body===x.body||e.body===V.body;return!F&&!J?null:{...e,title:F?M.title:e.title,body:J?M.body:e.body,tags:["Template",M.launcherLabel,M.optionLabel].filter(Boolean),metadata:{...e.metadata??{},[q.localizationManagedKey]:"True",[q.localizationLanguageKey]:o,[q.sourceInputValuesJsonKey]:JSON.stringify(k)}}}function Qo(e,t,o,n,r,s){const c=Qt(e,s),m=Wt(t,s),l=Eo(c,n),b=m.nodes.find(v=>K(v.id,o));if(!b)return null;const k=jo(m,r),x=Wa(c,l,k);return{title:Pt(b.title,x),body:Pt(b.body,x),launcherLabel:c.label,optionLabel:(l==null?void 0:l.label)||c.label}}function Fs(e,t){const o=Bs(Be(e,q.sourceInputValuesJsonKey));if(Object.keys(o).length>0)return o;const n=Be(e,q.controllerNodeIdKey),r=n?t.get(n):null,s=Va(r==null?void 0:r.body);return(s==null?void 0:s.inputValues)??{}}function Bs(e){if(!e)return{};try{const t=JSON.parse(e);return Object.fromEntries(Object.entries(t??{}).map(([o,n])=>[o,String(n??"")]))}catch{return{}}}function Be(e,t){var n;const o=(n=e.metadata)==null?void 0:n[t];return typeof o=="string"&&o.trim()?o.trim():null}function go(...e){var t;return((t=e.find(o=>typeof o=="string"&&o.trim()))==null?void 0:t.trim())??null}function Ye(e){const t=String(e||"").trim();return t?t.replace(/:/g,"."):"unknown"}function Gs(e,t){return e.includes("{0}")?e.replace("{0}",t):`${t} is required.`}function Us(e,t){var o,n,r;return String(t||"").trim()?((n=e.options.find(s=>K(s.id,t)))==null?void 0:n.id)??((r=e.options[0])==null?void 0:r.id):(o=e.options[0])==null?void 0:o.id}function cn(e){return e.map(t=>{var o;return{...t,options:(o=t.options)==null?void 0:o.map(n=>({...n}))}})}function Ha(e,t){const o={};for(const n of e)o[n.key]=String(t[n.key]??Sn(n));return o}function zs(){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 Ka(e){return e==="ai-task"?"aiPrompt":e==="template-launcher"?q.contentType:e}function $s(e){return K(e,"directory")?"directory":K(e,"pdf")?"pdf":K(e,"file")?"file":K(e,"memo")?"memo":K(e,"markdown")?"markdown":K(e,"csv-table")?"csv-table":K(e,"text")?"text":K(e,"code")?"code":K(e,"mask")?"mask":K(e,"image")?"image":K(e,"embed")?"embed":K(e,"aiPrompt")?"ai-task":K(e,q.contentType)?"template-launcher":"note"}function Vs(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 Xa(e){return`${e}-${Math.random().toString(36).slice(2,9)}`}function K(e,t){return String(e||"").toLowerCase()===String(t||"").toLowerCase()}function qs(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}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"}),Ya=Object.freeze({frames:"/api/remote/frames/ws",input:"/api/remote/input/ws"});function Ws(e){return Qe.deviceTasksTemplate.replace("{deviceId}",encodeURIComponent(e))}function Qa(e){return Za(e==null?void 0:e.remoteFrameWsPath,Ya.frames)}function Ja(e){return Za(e==null?void 0:e.remoteInputWsPath,Ya.input)}function Za(e,t){return typeof e=="string"?e.trim():t}const Jo={},Hs="http://127.0.0.1:5147",er="MindExec.AllowHostedLocalBridge",Ks=new Set(["4173","5173"]);function Jt(e){return e.replace(/\/+$/,"")}function Xs(){return((Jo==null?void 0:Jo.VITE_LOCAL_BRIDGE_URL)||"").trim()}function Ys(){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&&!Ks.has(o)?n:""}function j(){return Jt(Xs()||Ys()||Hs)}function Qs(){const e=window.location.hostname.toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"}function Js(){try{return window.localStorage.getItem(er)==="true"}catch{return!1}}function tr(e){try{e&&window.localStorage.setItem(er,"true")}catch{}}function At(){return Qs()||Js()}function or(e){const t=String((e==null?void 0:e.bridgeToken)||"").trim();if(t)return{header:(e==null?void 0:e.bridgeTokenHeader)||"X-Bridge-Token",token:t}}async function _(e,t,o={}){const n=new AbortController,r=window.setTimeout(()=>n.abort(),o.timeoutMs??4200),s=new Headers;s.set("Accept","application/json"),s.set("Cache-Control","no-store"),s.set("Pragma","no-cache"),o.body!==void 0&&s.set("Content-Type","application/json"),o.auth&&s.set(o.auth.header,o.auth.token);try{const c=await fetch(`${Jt(e)}${t}`,{method:o.method||(o.body===void 0?"GET":"POST"),headers:s,body:o.body===void 0?void 0:JSON.stringify(o.body),cache:"no-store",signal:n.signal}),m=await c.text(),l=m?JSON.parse(m):null;if(!c.ok){const b=(l==null?void 0:l.error)||(l==null?void 0:l.message)||`LocalBridge request failed: ${c.status}`;throw new Error(b)}return l}finally{window.clearTimeout(r)}}function Zs(e){return e instanceof DOMException&&e.name==="AbortError"?"LocalBridge probe timed out.":e instanceof SyntaxError?"LocalBridge returned a non-JSON response.":e instanceof Error?e.message||"LocalBridge is unavailable.":String(e||"LocalBridge is unavailable.")}async function Rn(e=j()){var t;try{const o=await _(e,"/api/status?refresh=1",{timeoutMs:4200});return g.emit("localBridge.status",{baseUrl:e,connected:!0,projectOpen:((t=o.project)==null?void 0:t.isOpen)===!0}),{state:"connected",baseUrl:e,status:o}}catch(o){const n=Zs(o);return g.emit("localBridge.status",{baseUrl:e,connected:!1,message:n}),{state:"unavailable",baseUrl:e,message:n}}}async function dd(e,t,o=j()){return _(o,"/project/open",{method:"POST",body:{path:e},auth:t,timeoutMs:15e3})}async function ud(e=j(),t=18,o=1200){var r,s;let n={state:"idle",baseUrl:e};for(let c=0;c<t;c+=1){if(n=await Rn(e),n.state==="connected"&&((s=(r=n.status)==null?void 0:r.project)!=null&&s.isOpen))return n;await new Promise(m=>{window.setTimeout(m,o)})}return n}async function pd(e,t=j()){return _(t,"/project/symbols",{auth:e,timeoutMs:12e3})}async function md(e,t=j()){return _(t,"/project/graph",{auth:e,timeoutMs:12e3})}async function hd(e="standard",t,o=j()){const n=`?level=${encodeURIComponent(e)}`;return _(o,`/project/ai-context${n}`,{auth:t,timeoutMs:14e3})}async function gd(e,t=j()){return g.emit("localBridge.codex.capabilities.request",{baseUrl:t}),_(t,"/api/codex/capabilities",{auth:e,timeoutMs:12e3})}async function fd(e,t=5,o,n=j()){return g.emit("localBridge.web.search.request",{baseUrl:n,maxResults:t}),_(n,"/api/web/search",{method:"POST",body:{query:e,maxResults:t},auth:o,timeoutMs:24e3})}async function bd(e,t=6e3,o,n=j()){return g.emit("localBridge.web.fetch.request",{baseUrl:n,maxChars:t}),_(n,"/api/web/fetch",{method:"POST",body:{url:e,maxChars:t},auth:o,timeoutMs:24e3})}async function yd(e,t,o=j()){return g.emit("localBridge.browser.open.request",{baseUrl:o}),_(o,"/api/browser/open",{method:"POST",body:{url:e},auth:t,timeoutMs:24e3})}async function kd(e,t=4e3,o,n=j()){return g.emit("localBridge.browser.snapshot.request",{baseUrl:n,maxChars:t}),_(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=j()){return g.emit("localBridge.browser.extract.request",{baseUrl:r,scope:t,maxChars:o}),_(r,"/api/browser/extract",{method:"POST",body:{sessionId:e,scope:t,maxChars:o},auth:n,timeoutMs:18e3})}async function Id(e,t,o=j()){return g.emit("localBridge.evidence.save.request",{baseUrl:o,kind:e.kind||"evidence"}),_(o,"/api/evidence/save",{method:"POST",body:e,auth:t,timeoutMs:18e3})}async function vd(e,t,o=j()){var n;return g.emit("localBridge.concept.defineComposite.request",{baseUrl:o,hasSignature:!!((n=e.signature)!=null&&n.trim())}),_(o,"/api/concept/define-composite",{method:"POST",body:e,auth:t,timeoutMs:18e3})}async function Cd(e,t=j()){return g.emit("localBridge.concept.status.request",{baseUrl:t}),_(t,"/api/concept/status",{method:"GET",auth:e,timeoutMs:12e3})}async function xd(e,t,o=j()){return g.emit("localBridge.concept.row.request",{baseUrl:o,id:e}),_(o,`/api/concept/row?id=${encodeURIComponent(e)}`,{method:"GET",auth:t,timeoutMs:12e3})}async function wd(e,t=j()){return g.emit("localBridge.concept.embed.readiness.request",{baseUrl:t}),_(t,"/api/concept/embed/readiness",{method:"GET",auth:e,timeoutMs:12e3})}async function Sd(e,t=j()){return _(t,"/project/close",{method:"POST",auth:e,timeoutMs:12e3})}async function Rd(e=j()){return _(e,"/api/workspace",{timeoutMs:4200})}async function Md(e,t,o=j()){return _(o,"/api/workspace/browse",{method:"POST",body:{initialPath:e||""},auth:t,timeoutMs:12e4})}async function Pd(e,t,o=j()){return _(o,"/api/workspace/set",{method:"POST",body:{path:e},auth:t,timeoutMs:3e4})}async function Ad(e,t,o=j()){return g.emit("localBridge.dir.list.request",{baseUrl:o}),_(o,"/api/dir/list",{method:"POST",body:{path:e},auth:t,timeoutMs:12e3})}async function Ed(e=j()){return _(e,"/project/change-feed",{timeoutMs:4200})}async function nr(e,t=j()){return _(t,Qe.status,{auth:e,timeoutMs:4200})}async function el(e,t=j()){return _(t,Qe.agentStatus,{auth:e,timeoutMs:4200})}async function ar(e,t=j(),o={}){const n=o.includeDataUrl?"?includeDataUrl=true":"";return _(t,`${Qe.devices}${n}`,{auth:e,timeoutMs:6500})}async function rr(e,t,o=j()){return _(o,Qe.frames,{method:"POST",body:{deviceIds:e,includeThumbnail:!0,includeLive:!0},auth:t,timeoutMs:6500})}async function fa(e,t,o,n=j(),r={}){return _(n,Qe.hostTarget,{method:"POST",body:{nodeId:e,enabled:t,leaseMs:r.leaseMs??6e4},auth:o,timeoutMs:6500})}async function tl(e,t,o=j()){return _(o,Qe.agentConnect,{method:"POST",body:e,auth:t,timeoutMs:3e4})}async function ol(e="react-remote-monitor",t,o=j()){return _(o,Qe.agentDisconnect,{method:"POST",body:{reason:e},auth:t,timeoutMs:12e3})}async function ir(e,t,o,n=j()){return _(n,Ws(e),{method:"POST",body:t,auth:o,timeoutMs:12e3})}async function nl(e,t,o=j()){return _(o,Qe.taskBatch,{method:"POST",body:e,auth:t,timeoutMs:16e3})}async function Ld(e,t=j()){const o=new URLSearchParams;return o.set("q",e.q),o.set("order",e.order||"relevance"),o.set("publishedWithin",e.publishedWithin||"any"),o.set("videoDuration",e.videoDuration||"any"),o.set("eventType",e.eventType||"any"),o.set("safeSearch",e.safeSearch||"moderate"),e.relevanceLanguage&&o.set("relevanceLanguage",e.relevanceLanguage),e.regionCode&&o.set("regionCode",e.regionCode),e.maxResults&&o.set("maxResults",String(e.maxResults)),e.pageToken&&o.set("pageToken",e.pageToken),_(t,`/api/youtube/search?${o.toString()}`,{timeoutMs:16e3})}function We(e){return`/api/company-core${e.startsWith("/")?e:`/${e}`}`}async function jd(e,t=j()){return g.emit("companyCore.bridge.request",{method:"GET",path:"/health"}),_(t,We("/health"),{auth:e,timeoutMs:6500})}async function Nd(e,t=j()){return g.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies"}),_(t,We("/api/companies"),{auth:e,timeoutMs:12e3})}async function Dd(e=20,t,o=j()){const n=Math.max(1,Math.min(100,Math.round(e)));return g.emit("companyCore.bridge.request",{method:"GET",path:"/api/company-runs",limit:n}),_(o,We(`/api/company-runs?limit=${n}`),{auth:t,timeoutMs:12e3})}async function Od(e,t,o=j()){const n=encodeURIComponent(e);return g.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies/:id/snapshot"}),_(o,We(`/api/companies/${n}/snapshot`),{auth:t,timeoutMs:12e3})}async function _d(e,t,o=j()){const n=encodeURIComponent(e);return g.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies/:id/approvals"}),_(o,We(`/api/companies/${n}/approvals?pendingOnly=false`),{auth:t,timeoutMs:12e3})}async function Fd(e,t,o=j()){const n=encodeURIComponent(e);return g.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies/:id/artifacts"}),_(o,We(`/api/companies/${n}/artifacts`),{auth:t,timeoutMs:12e3})}async function Bd(e,t,o=j()){const n=encodeURIComponent(e);return g.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies/:id/publishing-jobs"}),_(o,We(`/api/companies/${n}/publishing-jobs?limit=100`),{auth:t,timeoutMs:12e3})}async function Gd(e,t,o=j()){const n=encodeURIComponent(e);return g.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies/:id/growth"}),_(o,We(`/api/companies/${n}/growth?limit=100`),{auth:t,timeoutMs:12e3})}async function Ud(e,t,o=j()){const n=encodeURIComponent(e);return g.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies/:id/revenue"}),_(o,We(`/api/companies/${n}/revenue?limit=100`),{auth:t,timeoutMs:12e3})}async function zd(e,t,o=j()){const n=encodeURIComponent(e);return g.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies/:id/reflections"}),_(o,We(`/api/companies/${n}/reflections?limit=50`),{auth:t,timeoutMs:12e3})}async function $d(e,t,o=j()){return _(o,"/api/codex/thread/run",{method:"POST",body:e,auth:t,timeoutMs:18e4})}async function Vd(e,t=j()){return _(t,"/api/file/read",{method:"POST",body:{path:e},timeoutMs:3e4})}async function qd(e,t=j()){const o=new AbortController,n=window.setTimeout(()=>o.abort(),3e4);try{const r=await fetch(`${Jt(t)}/api/file/read-raw?path=${encodeURIComponent(e)}`,{method:"GET",headers:{Accept:"application/octet-stream","Cache-Control":"no-store",Pragma:"no-cache"},cache:"no-store",signal:o.signal});if(!r.ok)throw new Error(`LocalBridge raw file read failed: ${r.status}`);return new Uint8Array(await r.arrayBuffer())}finally{window.clearTimeout(n)}}async function Wd(e,t,o,n=j()){return _(n,"/api/file/write",{method:"POST",body:{path:e,content:t,encoding:"utf8"},auth:o,timeoutMs:3e4})}async function Hd(e,t,o,n=j()){const r=new AbortController,s=window.setTimeout(()=>r.abort(),3e4),c=new Headers;c.set("Accept","application/json"),c.set("Content-Type","application/octet-stream"),c.set("Cache-Control","no-store"),c.set("Pragma","no-cache"),c.set(o.header,o.token);try{const m=new ArrayBuffer(t.byteLength);new Uint8Array(m).set(t);const l=await fetch(`${Jt(n)}/api/file/write-raw?path=${encodeURIComponent(e)}`,{method:"PUT",headers:c,body:m,cache:"no-store",signal:r.signal}),b=await l.json().catch(()=>null);if(!l.ok){const k=(b==null?void 0:b.error)||(b==null?void 0:b.message)||`LocalBridge raw file write failed: ${l.status}`;throw new Error(k)}return b}finally{window.clearTimeout(s)}}async function Kd(e,t,o=j()){return _(o,"/api/file/delete",{method:"POST",body:{path:e},auth:t,timeoutMs:3e4})}function al(e,t=j()){const o=String(e||"").trim();if(!o)return;if(/^https?:\/\//i.test(o)||o.startsWith("data:"))return o;const n=o.replace(/\\/g,"/").replace(/^\/+/,"");return`${Jt(t)}/${n}`}async function Mn(e){var r;let t=null;if(typeof navigator<"u"&&((r=navigator.clipboard)!=null&&r.writeText))try{return await navigator.clipboard.writeText(e),"clipboard"}catch(s){t=s}if(typeof document>"u"||!document.body||typeof document.execCommand!="function")throw t instanceof Error?t:new Error("clipboard-unavailable");const o=document.createElement("textarea"),n=document.activeElement instanceof HTMLElement?document.activeElement:null;o.value=e,o.setAttribute("readonly",""),o.style.position="fixed",o.style.left="-9999px",o.style.top="0",o.style.opacity="0",document.body.appendChild(o),o.focus(),o.select(),o.setSelectionRange(0,e.length);try{if(!document.execCommand("copy"))throw t instanceof Error?t:new Error("clipboard-unavailable");return"fallback"}finally{o.remove(),n==null||n.focus({preventScroll:!0})}}const sr="mindexec.app.language",xo="auto",Ht=[{code:xo,label:"Auto",nativeLabel:"Auto",englishName:"the user's input language",htmlLang:"auto",isAuto:!0,description:"Match the user's input language unless a prompt asks otherwise."},{code:"en",label:"English",nativeLabel:"English",englishName:"English",htmlLang:"en",isAuto:!1,description:"Prefer English for user-facing AI output."},{code:"ko",label:"Korean",nativeLabel:"한국어",englishName:"Korean",htmlLang:"ko",isAuto:!1,description:"Prefer Korean for user-facing AI output."},{code:"ja",label:"Japanese",nativeLabel:"日本語",englishName:"Japanese",htmlLang:"ja",isAuto:!1,description:"Prefer Japanese for user-facing AI output."},{code:"zh",label:"Chinese",nativeLabel:"中文",englishName:"Chinese",htmlLang:"zh",isAuto:!1,description:"Prefer Chinese for user-facing AI output."}];function Lt(e){if(typeof e!="string")return xo;const t=e.trim().toLowerCase();return Ht.some(o=>o.code===t)?t:xo}function Pn(e){const t=Lt(e);return Ht.find(o=>o.code===t)??Ht[0]}function lr(){if(typeof window>"u")return null;try{const e=window.localStorage.getItem(sr);return e===null?null:Lt(e)}catch{return null}}function Xd(e){return Lt(lr()??e??xo)}function Yd(e){const t=Lt(e);if(typeof window>"u")return t;try{window.localStorage.setItem(sr,t)}catch{}return t}function Qd(e){const t=lr()??Lt(e.settings.appLanguage);return{...e,settings:{...e.settings,appLanguage:t}}}function Jd(e){const t=Pn(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 Zd(e){const t=Pn(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 Zo=[{id:"general",label:"General",icon:gi},{id:"language",label:"Language",icon:fi},{id:"connection",label:"Connection",icon:bi},{id:"media",label:"Media",icon:La},{id:"agent",label:"Agent",icon:yi},{id:"system",label:"System",icon:ki},{id:"about",label:"About",icon:Ti}],rl=["Managed Cloud","BYOK","OpenAI Codex","Local Ollama"];function il(e,t,o){return Number.isFinite(e)?Math.min(o,Math.max(t,Math.round(e))):t}function eu({settings:e,onPatchSettings:t,onClose:o}){const[n,r]=p.useState("general"),[s,c]=p.useState("idle"),[m,l]=p.useState(null),b=Zo.find(h=>h.id===n)??Zo[0],k=Ji(e),x=Yt(e.model),v=e.aiProvider??"OpenAI Codex",V=ll(x),M=Pn(e.appLanguage),F=ba("Image",e),J=ba("Video",e),Z=Object.fromEntries(Ht.map(h=>[h.code,h.isAuto?h.label:`${h.nativeLabel} / ${h.label}`])),E=(h,ee)=>t(h,ee),ue=h=>{const ee=h.currentTarget;let L=0;if(h.key==="PageDown")L=Math.max(160,Math.floor(ee.clientHeight*.86));else if(h.key==="PageUp")L=-Math.max(160,Math.floor(ee.clientHeight*.86));else if(h.key==="ArrowDown")L=44;else if(h.key==="ArrowUp")L=-44;else if(h.key==="End"){h.preventDefault(),ee.scrollTo({top:ee.scrollHeight,behavior:"auto"});return}else if(h.key==="Home"){h.preventDefault(),ee.scrollTo({top:0,behavior:"auto"});return}else return;h.preventDefault(),ee.scrollBy({top:L,behavior:"auto"})},B=async()=>{try{const h=await Mn(V);c("copied"),g.emit("settings.providerCommand.copy",{provider:v,command:"dataset-generator",method:h,redacted:!0})}catch(h){if(cl(m)){c("selected"),g.emit("settings.providerCommand.selectFallback",{provider:v,command:"dataset-generator",message:h instanceof Error?h.message:String(h),redacted:!0});return}c("failed"),g.emit("settings.providerCommand.copyFailed",{provider:v,command:"dataset-generator",message:h instanceof Error?h.message:String(h)})}},pe=(h,ee)=>{const L=Ua(h,ee),Y=Ao(h).find(Pe=>Pe.id===L);if(!Y)return;const Oe=h==="Image"?e.imageRouterImageAspectPresetId:e.imageRouterVideoAspectPresetId,W=sn(h,Y,Oe);E(h==="Image"?{imageRouterImageModel:Y.id,imageRouterImageAspectPresetId:W.id}:{imageRouterVideoModel:Y.id,imageRouterVideoAspectPresetId:W.id},`media.${h.toLowerCase()}.model`),g.emit("media.model.select",{mode:h,model:Y.id,aspectPresetId:W.id,requestedSize:ln(W),source:"settings-dialog"})},Ce=(h,ee)=>{const L=h==="Image"?F.model:J.model,Y=sn(h,L,ee);E(h==="Image"?{imageRouterImageAspectPresetId:Y.id}:{imageRouterVideoAspectPresetId:Y.id},`media.${h.toLowerCase()}.aspect`),g.emit("media.aspect.select",{mode:h,model:L.id,aspectPresetId:Y.id,requestedSize:ln(Y),source:"settings-dialog"})};return a.jsx("div",{className:"ai-settings-backdrop","data-testid":"ai-settings-dialog","data-disable-mindcanvas-wheel":"true",onMouseDown:o,children:a.jsxs("section",{className:"ai-settings-dialog","aria-label":"AI settings","data-disable-mindcanvas-hotkeys":"true","data-ai-settings-dialog-surface":"true",onMouseDown:h=>h.stopPropagation(),children:[a.jsx("aside",{className:"ai-settings-tabs","aria-label":"Settings sections",children:Zo.map(h=>{const ee=h.icon;return a.jsxs("button",{type:"button",className:n===h.id?"is-active":"","data-testid":`ai-settings-tab-${h.id}`,onClick:()=>r(h.id),children:[a.jsx(ee,{size:15}),a.jsx("span",{children:h.label})]},h.id)})}),a.jsxs("main",{className:"ai-settings-main",children:[a.jsxs("header",{className:"ai-settings-head",children:[a.jsx("strong",{children:b.label}),a.jsx("button",{type:"button",title:"Close settings",onClick:o,children:a.jsx(Po,{size:16})})]}),a.jsxs("div",{className:"ai-settings-body","data-testid":"ai-settings-body",tabIndex:0,onKeyDown:ue,children:[n==="general"&&a.jsxs("div",{className:"settings-grid",children:[a.jsx(xt,{label:"Grid snap",description:"Align new movement to the canvas grid.",checked:e.gridSnap??!0,onChange:h=>E({gridSnap:h},"general.gridSnap")}),a.jsx(De,{label:"Grid type",description:"Background grid rendering mode.",value:e.gridType??"dot",options:["dot","line","particles","spirit"],onChange:h=>E({gridType:h},"general.gridType")}),a.jsx(De,{label:"Cursor position",description:"Where new nodes are placed by default.",value:e.cursorMode??"center",options:["center","lastNode"],onChange:h=>E({cursorMode:h},"general.cursorMode")}),a.jsx(De,{label:"Cursor direction",description:"Direction for sequential node placement.",value:e.cursorDirection,options:["right","down"],onChange:h=>E({cursorDirection:h},"general.cursorDirection")}),a.jsx(De,{label:"Camera trace mode",description:"Whether the camera follows new work.",value:e.cameraTraceMode??"none",options:["none","cursor"],onChange:h=>E({cameraTraceMode:h},"general.cameraTraceMode")}),a.jsx(De,{label:"Image load size",description:"Image nodes use fixed or original sizing.",value:e.imageLoadSize??"default",options:["default","original"],onChange:h=>E({imageLoadSize:h},"general.imageLoadSize")}),a.jsx(zt,{label:"AI node width",description:"Default width for new AI task nodes.",value:e.aiNodeDefaultWidth??340,min:220,max:1200,onChange:h=>E({aiNodeDefaultWidth:h},"general.aiNodeDefaultWidth")}),a.jsx(zt,{label:"AI node height",description:"Default height for new AI task nodes.",value:e.aiNodeDefaultHeight??196,min:120,max:900,onChange:h=>E({aiNodeDefaultHeight:h},"general.aiNodeDefaultHeight")}),a.jsx(xt,{label:"Show full AI response",description:"Allow AI result nodes to expand for long output.",checked:e.showFullAiResponse??!1,onChange:h=>E({showFullAiResponse:h},"general.showFullAiResponse")}),a.jsx(xt,{label:"Minimap",description:"Display a small navigation minimap in the bottom-right of the canvas.",checked:e.minimapEnabled??!1,onChange:h=>E({minimapEnabled:h},"general.minimapEnabled")}),a.jsx(xt,{label:"Mouse wheel mode",description:"Swap wheel zoom and scroll behavior.",checked:e.wheelMode,onChange:h=>E({wheelMode:h},"general.wheelMode")})]}),n==="language"&&a.jsx("div",{className:"settings-grid settings-grid--compact",children:a.jsx(De,{label:"App Language",description:`Controls the language preference passed into AI runs. ${M.description}`,value:M.code,options:Ht.map(h=>h.code),optionLabels:Z,testId:"app-language-select",onChange:h=>E({appLanguage:Lt(h)},"language.appLanguage")})}),n==="connection"&&a.jsxs("div",{className:"settings-stack",children:[a.jsx("section",{className:"settings-radio-group","aria-label":"AI Provider",children:rl.map(h=>a.jsxs("label",{className:v===h?"is-selected":"",children:[a.jsx("input",{type:"radio",name:"ai-provider",checked:v===h,onChange:()=>E({aiProvider:h},"connection.provider")}),a.jsxs("span",{children:[a.jsx("strong",{children:h}),a.jsx("small",{children:cr(h)})]})]},h))}),a.jsx(dl,{provider:v,datasetGeneratorCommand:V,copyState:s,onCommandTextAreaRef:l,onCopyDatasetGeneratorCommand:B}),a.jsxs("div",{className:"settings-grid settings-grid--compact",children:[a.jsx(De,{label:"Text model",description:sl(x),value:x,options:k.map(h=>h.id),optionLabels:Object.fromEntries(k.map(h=>[h.id,`${Ba(h.provider)} · ${h.label}`])),onChange:h=>E({model:h},"connection.model")}),a.jsx(De,{label:"Reasoning effort",description:"Mapped to LocalBridge Codex reasoning effort.",value:e.effort,options:["Fast","Normal","Deep"],onChange:h=>E({effort:h},"connection.effort")}),(e.aiProvider??"OpenAI Codex")==="Local Ollama"&&a.jsx(ul,{label:"Ollama URL",description:"Local Ollama endpoint.",value:e.ollamaEndpoint??"http://localhost:11434",onChange:h=>E({ollamaEndpoint:h},"connection.ollamaEndpoint")}),a.jsx(xt,{label:"ImageRouter mode",description:"Key material remains outside this React board snapshot.",checked:e.imageRouterEnabled??!1,onChange:h=>E({imageRouterEnabled:h},"connection.imageRouterEnabled")}),a.jsx(xt,{label:"Parallel insight bundles",description:"Preserves the original CodeMaster insight bundle switch.",checked:e.codeMasterInsightBundlesEnabled??!0,onChange:h=>E({codeMasterInsightBundlesEnabled:h},"connection.codeMasterInsightBundlesEnabled")}),a.jsx(zt,{label:"Bundle timeout",description:"Per insight bundle timeout in milliseconds.",value:e.codeMasterInsightBundleTimeoutMs??18e3,min:5e3,max:6e4,onChange:h=>E({codeMasterInsightBundleTimeoutMs:h},"connection.codeMasterInsightBundleTimeoutMs")}),a.jsx(zt,{label:"Retry Count (Std)",description:"Retries for lite and standard CodeMaster insight bundle calls.",value:e.codeMasterInsightBundleRetryCount??2,min:1,max:4,step:1,testId:"codemaster-insight-retry-std",onChange:h=>E({codeMasterInsightBundleRetryCount:h},"connection.codeMasterInsightBundleRetryCount")}),a.jsx(zt,{label:"Retry Count (Deep)",description:"Retries for deep CodeMaster insight bundle calls.",value:e.codeMasterInsightBundleRetryCountDeep??3,min:1,max:5,step:1,testId:"codemaster-insight-retry-deep",onChange:h=>E({codeMasterInsightBundleRetryCountDeep:h},"connection.codeMasterInsightBundleRetryCountDeep")})]}),a.jsxs("div",{className:"settings-note",children:[a.jsx(pa,{size:15}),a.jsx("span",{children:"API keys are intentionally not stored in this React board. Live provider adapters must supply and verify secrets separately."})]})]}),n==="media"&&a.jsxs("div",{className:"settings-stack","data-testid":"ai-settings-media-tab",children:[a.jsx(ya,{mode:"Image",icon:a.jsx(La,{size:17}),selection:F,onModelChange:h=>pe("Image",h),onAspectChange:h=>Ce("Image",h)}),a.jsx(ya,{mode:"Video",icon:a.jsx(Ii,{size:17}),selection:J,onModelChange:h=>pe("Video",h),onAspectChange:h=>Ce("Video",h)}),a.jsxs("div",{className:"settings-note",children:[a.jsx(pa,{size:15}),a.jsx("span",{children:"These are adapter hints only. Selecting a media model does not store an API key, invoke ImageRouter, or claim live generation availability."})]})]}),n==="agent"&&a.jsx("div",{className:"settings-grid settings-grid--compact",children:a.jsx(De,{label:"Direct instruction queue",description:"How selected agents receive direct instructions.",value:e.directInstructionQueueMode??"Append",options:["Append","Next","ReplacePending"],onChange:h=>E({directInstructionQueueMode:h},"agent.directInstructionQueueMode")})}),n==="system"&&a.jsxs("div",{className:"settings-grid settings-grid--compact",children:[a.jsx(De,{label:"Execution mode",description:"Concept parses IR locally; PureLLM is direct chat adapter mode.",value:e.executionMode??"Concept",options:["Concept","PureLLM"],onChange:h=>E({executionMode:h},"system.executionMode")}),a.jsxs("div",{className:"settings-note",children:[a.jsx(vi,{size:15}),a.jsx("span",{children:"Changing this setting affects the next run only. It does not claim a live agent has executed."})]})]}),n==="about"&&a.jsxs("div",{className:"settings-about",children:[a.jsx(Ci,{size:34}),a.jsx("strong",{children:"MindExec React"}),a.jsx("span",{children:"Fast local-first MindCanvas shell, rebuilt without Blazor in the render loop."}),a.jsx("small",{children:"AI settings parity slice"})]})]}),a.jsx("footer",{className:"ai-settings-footer",children:a.jsx("button",{type:"button","data-testid":"ai-settings-done",onClick:o,children:"Save"})})]})]})})}function ba(e,t){const o=rn(e,t),n=e==="Image"?t.imageRouterImageAspectPresetId:t.imageRouterVideoAspectPresetId,r=sn(e,o,n);return{model:o,aspect:r,aspectOptions:za(o,e),requestedSize:ln(r)}}function sl(e){const t=Xi(e);return t?`${Ba(t.provider)} text model used by bottom input and AI Task runs.`:"Custom text model id preserved with this board."}function cr(e){switch(e){case"Managed Cloud":return"Reserved for the hosted paid adapter.";case"BYOK":return"Use a separately configured user key.";case"Local Ollama":return"Local LLM server endpoint.";case"Gemini CLI":return"Hidden Gemini CLI compatibility path.";case"OpenAI Codex":default:return"LocalBridge Codex execution path."}}function ll(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 cl(e){return!e||e.value.length===0?!1:(e.focus({preventScroll:!0}),e.select(),e.setSelectionRange(0,e.value.length),!0)}function dl({provider:e,datasetGeneratorCommand:t,copyState:o,onCommandTextAreaRef:n,onCopyDatasetGeneratorCommand:r}){const s=e==="BYOK"?"BYOK Settings":e==="Local Ollama"?"Ollama Settings":e==="Managed Cloud"?"Managed Cloud":e==="Gemini CLI"?"Gemini CLI":"OpenAI Codex";return a.jsxs("section",{className:"settings-provider-card","data-testid":"ai-settings-provider-guidance","data-provider":e,children:[a.jsx("header",{children:a.jsxs("div",{children:[a.jsx("strong",{"data-testid":"ai-settings-provider-title",children:s}),a.jsx("span",{children:cr(e)})]})}),e==="Managed Cloud"&&a.jsx("div",{className:"settings-provider-card__notice",children:"Managed Cloud is coming soon in this build. Switch to BYOK, OpenAI Codex, or Local Ollama for local execution."}),e==="Gemini CLI"&&a.jsx("div",{className:"settings-provider-card__notice","data-testid":"ai-settings-gemini-hidden-provider",children:"Gemini CLI is hidden in this company build. Switch to BYOK, OpenAI Codex, or Local Ollama to manage connection settings here."}),e==="BYOK"&&a.jsxs("div",{className:"settings-provider-card__section",children:[a.jsx("p",{children:"API key material stays outside this React board. Configure the BYOK adapter or environment before running live OpenRouter calls."}),a.jsxs("div",{className:"settings-provider-card__command-head",children:[a.jsx("strong",{children:"DatasetGenerator Export"}),a.jsx("button",{type:"button","data-testid":"ai-settings-provider-copy-command","data-provider-copy-state":o,onClick:()=>void r(),children:o==="copied"?"Copied":o==="selected"?"Selected":o==="failed"?"Copy failed":"Copy command"})]}),a.jsx("textarea",{readOnly:!0,ref:n,value:t,"data-testid":"ai-settings-provider-dataset-command",className:"settings-provider-card__command","aria-label":"Redacted DatasetGenerator command"}),a.jsx("div",{className:"settings-provider-card__note",children:"This command is redacted; no API key is stored in the board. Replace OPENROUTER_API_KEY only in a trusted shell."})]}),e==="OpenAI Codex"&&a.jsxs("div",{className:"settings-provider-card__section",children:[a.jsx("strong",{children:"Connection Requirements"}),a.jsxs("ol",{children:[a.jsxs("li",{children:["Install MindExec LocalBridge dependencies: ",a.jsx("code",{children:"npm install"})]}),a.jsxs("li",{children:["Sign in once: ",a.jsx("code",{children:"codex login"})]}),a.jsx("li",{children:"Runtime: Codex SDK first, Legacy Exec fallback when SDK is unavailable."})]})]}),e==="Local Ollama"&&a.jsxs("div",{className:"settings-provider-card__section",children:[a.jsx("p",{children:"Ollama model selection is handled from the bottom AI input bar. Keep the local endpoint editable below."}),a.jsxs("div",{className:"settings-provider-card__note",children:["Requires ",a.jsx("code",{children:'OLLAMA_ORIGINS="*"'})," when running Ollama for browser access."]})]}),a.jsxs("div",{className:"settings-provider-card__section settings-provider-card__section--image",children:[a.jsx("strong",{children:"Image Generation"}),a.jsx("p",{children:"Text AI provider and image generation provider are configured separately. ImageRouter API key is adapter-owned and used only for image mode."}),a.jsx("span",{children:"ImageRouter API key: not stored in this React board."})]})]})}function ya({mode:e,icon:t,selection:o,onModelChange:n,onAspectChange:r}){const s=Ao(e),c=Object.fromEntries(s.map(l=>[l.id,`${l.provider} · ${l.label}`])),m=Object.fromEntries(o.aspectOptions.map(l=>[l.id,`${l.label} · ${l.resolvedSize??"auto"}`]));return a.jsxs("section",{className:"settings-media-section","data-testid":`ai-settings-media-${e.toLowerCase()}`,children:[a.jsxs("header",{children:[a.jsx("span",{className:"settings-media-section__icon",children:t}),a.jsxs("span",{children:[a.jsxs("strong",{children:[e," defaults"]}),a.jsxs("small",{children:[o.model.provider," · ",o.requestedSize]})]})]}),a.jsxs("div",{className:"settings-grid settings-grid--compact",children:[a.jsx(De,{label:`${e} model`,description:"Shared with the bottom input model selector.",value:o.model.id,options:s.map(l=>l.id),optionLabels:c,testId:`ai-settings-${e.toLowerCase()}-model`,onChange:n}),a.jsx(De,{label:`${e} aspect`,description:o.aspect.note,value:o.aspect.id,options:o.aspectOptions.map(l=>l.id),optionLabels:m,testId:`ai-settings-${e.toLowerCase()}-aspect`,swatchClassName:is(o.aspect.id),onChange:r})]})]})}function xt({label:e,description:t,checked:o,onChange:n}){return a.jsxs("label",{className:"setting-row setting-row--toggle",children:[a.jsxs("span",{children:[a.jsx("strong",{children:e}),a.jsx("small",{children:t})]}),a.jsx("input",{type:"checkbox",checked:o,onChange:r=>n(r.target.checked)})]})}function De({label:e,description:t,value:o,options:n,optionLabels:r,testId:s,swatchClassName:c,onChange:m}){return a.jsxs("label",{className:"setting-row",children:[a.jsxs("span",{children:[a.jsx("strong",{children:e}),a.jsx("small",{children:t})]}),a.jsxs("span",{className:"setting-row__select-wrap",children:[c&&a.jsx("span",{className:`aspect-select__swatch ${c}`}),a.jsx("select",{value:o,"data-testid":s,onChange:l=>m(l.target.value),children:n.map(l=>a.jsx("option",{value:l,children:(r==null?void 0:r[l])??l},l))})]})]})}function zt({label:e,description:t,value:o,min:n,max:r,step:s=1,testId:c,onChange:m}){return a.jsxs("label",{className:"setting-row",children:[a.jsxs("span",{children:[a.jsx("strong",{children:e}),a.jsx("small",{children:t})]}),a.jsx("input",{type:"number",min:n,max:r,step:s,"data-testid":c,value:o,onChange:l=>m(il(l.target.valueAsNumber,n,r))})]})}function ul({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 pl=1e3,ka=1536*1024,ml=3*1024*1024*3/4,hl=24,gl=.65,fl=16,bl=.92;function wo(e){if(e.byteLength<5)return null;try{const o=new DataView(e).getUint32(0,!1);if(o<2||o>e.byteLength-4)return null;const n=new TextDecoder().decode(new Uint8Array(e,4,o));return{metadata:yl(JSON.parse(n)),payload:e.slice(4+o)}}catch{return null}}function yl(e){const t=kl(e)?e:{};return{type:Ne(t.type)||"remote.frame.binary",kind:Ne(t.kind)||"live",deviceId:Ne(t.deviceId),frameSeq:fe(t.frameSeq),streamId:Ne(t.streamId),width:fe(t.width),height:fe(t.height),mimeType:Ne(t.mimeType)||"image/jpeg",mode:Ne(t.mode),fps:fe(t.fps),capturedAt:Ne(t.capturedAt),receivedAt:Ne(t.receivedAt),byteLength:fe(t.byteLength),transport:Ne(t.transport),contentHash:Ne(t.contentHash),captureMs:fe(t.captureMs),sameContentStreak:fe(t.sameContentStreak),droppedByAgent:fe(t.droppedByAgent),dirtyRectCount:Tl(t.dirtyRectCount??t.dirtyRects??t.dirtyRegionCount),dirtyPixelRatio:ur(t.dirtyPixelRatio??t.dirtyRatio??t.dirtyAreaRatio??t.changedPixelRatio),codec:Ne(t.codec??t.encoder??t.encoding),deltaEncoded:pr(t.deltaEncoded??t.isDeltaEncoded??t.deltaFrame)}}function dr(e,t=0){const o=fe(e.captureMs),n=Math.max(fe(e.byteLength),fe(t)),r=fe(e.sameContentStreak),s=fe(e.droppedByAgent),c=fe(e.dirtyRectCount),m=ur(e.dirtyPixelRatio),l=Ne(e.codec),b=pr(e.deltaEncoded),k={captureMs:o,byteLength:n,sameContentStreak:r,droppedByAgent:s,dirtyRectCount:c,dirtyPixelRatio:m,codec:l,deltaEncoded:b};return n>=ml?{level:"oversized-frame",overBudget:!0,reason:"RemoteFast frame is near the agent binary frame ceiling.",...k}:o>=pl?{level:"slow-capture",overBudget:!0,reason:"RemoteFast reported a slow screen capture.",...k}:m>=bl&&n>=ka?{level:"inefficient-full-frame",overBudget:!0,reason:"RemoteFast dirty-region metadata shows a near-full-frame update with a large payload.",...k}:m>=gl&&c>=fl?{level:"dirty-region-heavy",overBudget:!0,reason:"RemoteFast dirty-region metadata shows many changed regions in one frame.",...k}:n>=ka?{level:"large-frame",overBudget:!0,reason:"RemoteFast frame payload is large enough to create decode or transport pressure.",...k}:r>=hl?{level:"stable-duplicate",overBudget:!1,reason:"RemoteFast reports repeated identical content that may be eligible for future delta or skip optimization.",...k}:{level:"nominal",overBudget:!1,reason:"",...k}}function kl(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function Ne(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):""}function fe(e){const t=Number(e);return Number.isFinite(t)&&t>=0?t:0}function Tl(e){return Array.isArray(e)?e.length:Math.round(fe(e))}function ur(e){const t=fe(e);return t<=1?t:t<=100?t/100:1}function pr(e){return typeof e=="boolean"?e:typeof e=="number"?e>0:typeof e=="string"?/^(1|true|yes|on|delta)$/i.test(e.trim()):!1}function mr(e){const t=Xe(e.deviceId,256),o=Il({...e.input,controlLeaseId:e.input.controlLeaseId||e.controlLeaseId});return!t||!o.type?null:{type:"input",requestId:Xe(e.requestId,160),deviceId:t,ack:vl(o.type,e.ack),input:o}}function Il(e={}){const t=Number(e.normalizedX),o=Number(e.normalizedY),n=Number(e.deltaX),r=Number(e.deltaY);return{type:Xe(e.type,48),normalizedX:Number.isFinite(t)?st(t,0,1):void 0,normalizedY:Number.isFinite(o)?st(o,0,1):void 0,button:Xe(e.button,24),deltaX:Number.isFinite(n)?st(n,-4096,4096):0,deltaY:Number.isFinite(r)?st(r,-4096,4096):0,key:Xe(e.key,80),code:Xe(e.code,80),text:xl(e.text,256),repeat:e.repeat===!0,controlLeaseId:Xe(e.controlLeaseId,128),issuedAt:Xe(e.issuedAt,80)}}function vl(e,t){return t===!0||!/^pointermove$/i.test(String(e||"").trim())}function hr(e){let t;try{const n=typeof e=="string"?JSON.parse(e||"{}"):e;if(!gr(n))return null;t=n}catch{return null}const o=wt(t.type||t.Type);return o==="RemoteInputSocketReady"?{type:o,ok:!0,requestId:"",deviceId:"",inputType:"",commandId:"",error:""}:o!=="RemoteInputResult"&&o!=="RemoteInputError"?null:{type:o,ok:t.ok===!0||t.Ok===!0,requestId:wt(t.requestId||t.RequestId),deviceId:wt(t.deviceId||t.DeviceId),inputType:wt(t.inputType||t.InputType),commandId:wt(t.commandId||t.CommandId),error:wt(t.error||t.Error)}}function Cl(e,t,o,n=!1){if(!Ta(t))return null;const r=Ta(o)?o:{left:0,top:0,width:t.width,height:t.height};let s=Number(e.clientX)-t.left-r.left,c=Number(e.clientY)-t.top-r.top;return!Number.isFinite(s)||!Number.isFinite(c)||(s<0||c<0||s>r.width||c>r.height)&&!n?null:(s=st(s,0,r.width),c=st(c,0,r.height),{normalizedX:st(s/r.width,0,1),normalizedY:st(c/r.height,0,1)})}function st(e,t,o){return Math.max(t,Math.min(o,e))}function Ta(e){if(!gr(e))return!1;const t=Number(e.width),o=Number(e.height);return Number.isFinite(Number(e.left))&&Number.isFinite(Number(e.top))&&Number.isFinite(t)&&Number.isFinite(o)&&t>0&&o>0}function Xe(e,t){return String(e??"").replace(/\0/g,"").trim().slice(0,t)}function xl(e,t){return Xe(e,t)}function wt(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):""}function gr(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function wl(e,t){const o=Math.max(1,Math.floor(t.visibleBudget)),n=t.searchText.trim(),r=n.length>0||t.visibilityFilter!=="connected"||t.capabilityFilter!=="all",s=Sl(e,t.visibilityFilter,n,t.capabilityFilter),c=Rl(s,t.groupMode),m=c.length,l=Math.max(1,Math.ceil(Math.max(0,m)/o)),b=Number.isFinite(t.pageIndex)?Math.floor(t.pageIndex):0,k=Math.max(0,Math.min(b,l-1)),x=k*o,v=c.slice(x,x+o),V=v.map(lt).filter(Boolean),M=v.filter(E=>E.connected===!0).map(lt).filter(Boolean),F=new Set(v.map(E=>dn(E,t.groupMode))).size,J=c.filter(E=>E.connected===!0&&Ge(E,"taskDispatch")).map(lt).filter(Boolean),Z=c.filter(E=>E.connected===!0&&Ge(E,"taskDispatch")&&Ge(E,"aiAssist")).map(lt).filter(Boolean);return{filterActive:r,filteredDevices:s,projectedDevices:c,visibleDevices:v,visibleDeviceIds:V,visibleConnectedDeviceIds:M,frameSubscriptionDeviceIdSignature:M.join(","),visibleGroupCount:F,projectedCount:m,filteredCount:s.length,pageCount:l,pageIndex:k,pageStart:x,placeholderSlots:Math.max(0,o-v.length),taskDispatchDeviceIds:J,aiTaskDeviceIds:Z}}function Sl(e,t,o,n){const r=o.trim().toLocaleLowerCase();return e.filter(s=>Ml(s,t)&&Pl(s,n)&&Al(s,r))}function Rl(e,t){return[...e].sort((o,n)=>{const r=dn(o,t),s=dn(n,t);if(r!==s)return r.localeCompare(s);const c=un(o).toLocaleLowerCase(),m=un(n).toLocaleLowerCase();return c!==m?c.localeCompare(m):lt(o).localeCompare(lt(n))})}function dn(e,t){switch(t){case"activity":return br(e);case"platform":return fr(e).toLocaleLowerCase()||"unknown";case"capability":return yr(e);default:return e.connected===!0?"online":"offline"}}function lt(e){return String(e.deviceId||e.sessionId||e.deviceName||"").trim()}function un(e){return String(e.deviceName||e.hostname||lt(e)||"Remote device").trim()}function fr(e){var t;return String(((t=e.status)==null?void 0:t.platform)||e.platform||"unknown").trim()}function Ge(e,t){var n;const o=(n=e.capabilities)==null?void 0:n[t];return typeof o=="boolean"?o:typeof o=="number"?o!==0:typeof o=="string"?/^(1|true|yes|on)$/i.test(o):!1}function Ml(e,t){return t==="all"?!0:t==="offline"?e.connected!==!0:e.connected===!0}function Pl(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 Al(e,t){var n;return t?[lt(e),un(e),fr(e),pn(e.arch),pn((n=e.latestTask)==null?void 0:n.status),br(e),yr(e),e.connected===!0?"online live connected":"offline disconnected"].join(" ").toLocaleLowerCase().includes(t):!0}function br(e){var o,n,r,s;const t=pn((o=e.latestTask)==null?void 0:o.status).toLocaleLowerCase();return t==="running"||t==="queued"?`task-${t}`:((n=e.activeLiveStream)==null?void 0:n.active)===!0?"live":Number(((r=e.counters)==null?void 0:r.liveFramesReceived)||0)>0?"live-recent":Number(((s=e.counters)==null?void 0:s.thumbnailFramesReceived)||0)>0?"thumbnail":e.lastStatusAt||e.lastSeenAt?"heartbeat":"idle"}function yr(e){return Ge(e,"aiAssist")?"ai-assist":Ge(e,"taskDispatch")?"task-dispatch":Ge(e,"control")?"control":Ge(e,"thumbnail")||Ge(e,"screen")?"screen":"view-only"}function pn(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):""}const Me=30,El=1200,Ll=4200,Ia=12,kr=8e3,jl=1.5,Tr=42,va="mindexec:remote-monitor-input-smoke",en="connected-screen-wall",mn=90,Ir=240,vr=1e4,$t=6e4,fo=25e3,Nl=250,Io=2e3,Rt=60,Ca=2,Dl=96,Ol=58,Vt=[1,1.5,2.25,3.375],xa=1,_l=5,Fl=72,Bl=96,wa="240px",hn="MindExec.RemoteFleet.AutoHost",gn="MindExec.RemoteFleet.AutoHostNodeId",Cr=["status","activity","platform","capability"],xr=["connected","all","offline"],wr=["all","control","task","ai"],Mt=new Map,Zt=new WeakMap;function Sa(e,t=0){if(typeof window>"u")return!0;const o=window.innerWidth||document.documentElement.clientWidth||0,n=window.innerHeight||document.documentElement.clientHeight||0;return o<=0||n<=0?!0:e.right>=-t&&e.bottom>=-t&&e.left<=o+t&&e.top<=n+t}function Sr(e,t,o){const[n,r]=p.useState(()=>typeof document>"u"?!0:document.visibilityState==="visible"),[s,c]=p.useState(!0),m=p.useRef(null);p.useEffect(()=>{if(typeof document>"u")return;const b=()=>r(document.visibilityState==="visible");return b(),document.addEventListener("visibilitychange",b),()=>document.removeEventListener("visibilitychange",b)},[]),p.useEffect(()=>{const b=e.current;if(!b||typeof IntersectionObserver>"u"){c(!0);return}const k=new IntersectionObserver(x=>{const v=x[0],V=!!(v!=null&&v.isIntersecting||((v==null?void 0:v.intersectionRatio)??0)>0),M=Sa(v?v.boundingClientRect:b.getBoundingClientRect(),240);c(V||M)},{root:null,rootMargin:wa,threshold:0});return k.observe(b),()=>k.disconnect()},[e]);const l=n&&s;return p.useEffect(()=>{if(m.current===l)return;m.current=l;const b={nodeId:t,visible:l,pageVisible:n,viewportVisible:s,rootMargin:wa};o==="monitor"?g.emit("remoteMonitor.node.transportVisibility",b):g.emit("remoteControl.node.transportVisibility",b)},[t,n,o,s,l]),l}function tu({node:e,onPatch:t,onCreateRemoteControl:o}){var Jn,Zn,ea,ta,oa,na,aa,ra,ia,sa,la,ca;const n=fn((Jn=e.metadata)==null?void 0:Jn.RemoteTotal,Me),r=fn((Zn=e.metadata)==null?void 0:Zn.RemoteConnected,0),s=p.useRef(null),c=p.useRef(null),m=Sr(s,e.id,"monitor"),[l,b]=p.useState(()=>({source:At()?"loading":"blocked",loading:!1,message:At()?"RemoteHub not checked yet.":"Hosted LocalBridge access is gated.",baseUrl:j(),devices:bo(n,r)})),k=p.useRef(new Map),x=p.useRef(new Set),v=p.useRef(new Map),V=p.useRef(new Map),M=p.useRef(new Map),F=p.useRef(null),J=p.useRef(0),Z=p.useRef(0),E=p.useRef(0),ue=p.useRef(!1),B=p.useRef(0),pe=p.useRef(0),Ce=p.useRef(!1),h=p.useRef(!1),ee=p.useRef(!1),L=p.useRef(""),Y=p.useRef(0),Oe=p.useRef(""),W=p.useRef(null),Pe=p.useRef(!1),_e=p.useRef(0),be=p.useRef(0),A=p.useRef(e.metadata??{}),[xe,Fe]=p.useState(""),[S,Q]=p.useState(!1),[te,ne]=p.useState("locked"),[jt,ae]=p.useState("Remote input locked."),[Do,we]=p.useState(""),[Se,mt]=p.useState(""),[Nt,de]=p.useState(""),[Re,eo]=p.useState(""),[Je,to]=p.useState(""),[Oo,Ue]=p.useState(""),[kt,Ze]=p.useState(0),[He,_o]=p.useState(xa),[ze,oo]=p.useState("status"),[Dt,no]=p.useState(""),[Ae,ao]=p.useState("connected"),[Ee,ro]=p.useState("all"),[me,ht]=p.useState(()=>tn(e.id)),et=l.source==="bridge"?l.devices.length:l.devices.length||n,y=Dt.trim(),I=p.useMemo(()=>wl(l.devices,{groupMode:ze,visibilityFilter:Ae,searchText:y,capabilityFilter:Ee,pageIndex:kt,visibleBudget:Me}),[Ee,ze,kt,y,l.devices,Ae]),N=I.filterActive,U=I.filteredDevices,z=I.projectedDevices,D=I.projectedCount,P=I.pageCount,O=I.pageIndex,X=I.pageStart,he=I.visibleDevices,tt=I.visibleDeviceIds,$e=I.visibleConnectedDeviceIds,ot=I.frameSubscriptionDeviceIdSignature,_n=I.visibleGroupCount,Ur=I.placeholderSlots,Fo=`${O+1}/${P}`,Fn=P<=1?100:Math.max(12,100/P),zr=P<=1?0:O/Math.max(1,P-1)*(100-Fn),Ot=Vt[He]??Vt[xa],Bn=Math.round(Dl*Ot),Gn=Math.round(Ol*Ot),oe=p.useMemo(()=>he.find(i=>it(i)===xe)||he.find(i=>i.connected===!0)||he[0],[xe,he]),H=oe?it(oe):"",_t=l.devices.filter(i=>i.connected===!0).length,Bo=l.devices.reduce((i,d)=>{var u;return i+Number(((u=d.counters)==null?void 0:u.tasksQueued)||0)},0),io=I.taskDispatchDeviceIds,so=I.aiTaskDeviceIds,Go=io.length,Ft=so.length,Uo=l.source==="bridge"?(ea=l.hub)!=null&&ea.started?"Online":((ta=l.hub)==null?void 0:ta.enabled)===!1?"Off":"Ready":l.source==="blocked"?"Gated":l.source,lo=l.source==="bridge"?"Local":l.source==="blocked"?"Gated":"Preview",zo=Qa((oa=l.bridge)==null?void 0:oa.status),$o=Ja((na=l.bridge)==null?void 0:na.status),Un=l.source==="bridge"&&!!$o,zn=oe?ce(oe,"control"):!1,Vo=oe?ce(oe,"taskDispatch"):!1,nt=p.useMemo(()=>oe?l.source!=="bridge"?"LocalBridge is not connected.":Un?oe.connected!==!0?"Selected device is offline.":zn?"":"RemoteAgent control capability is disabled.":"Remote input adapter is unavailable.":"No screen selected.",[Un,zn,oe,l.source]),Le=nt==="",qo=S?Er(te):Le?"Locked":"Off",ie=l.source==="bridge"&&((aa=l.hub)==null?void 0:aa.hostTargetActive)===!0&&l.hub.hostTargetNodeId===e.id,re=p.useMemo(()=>zl(l.hub,ie),[ie,l.hub]),Bt=Yl(l.agent,l.source),co=Nr(l.agent),Wo=Dr(l.agent),Gt=p.useMemo(()=>Hl(l.hub,e.id),[e.id,l.hub]),uo=Ql({source:l.source,hasAuth:!!l.auth,isHostActiveForNode:ie,request:Gt,busy:Se}),po=uo==="",mo=l.source==="bridge"&&!!l.auth&&co&&!Se,$n=l.source==="bridge"&&!!H&&(oe==null?void 0:oe.connected)===!0&&Vo&&!!Re.trim()&&!Je,Vn=l.source==="bridge"&&Go>0&&!!Re.trim()&&!Je,qn=l.source==="bridge"&&Ft>0&&!!Re.trim()&&!Je,$r=Oo||Nt||Do||(l.source==="bridge"&&oe?`${ft(oe)}: ${jt}`:l.message),Wn=p.useMemo(()=>ql(l.latestTaskBatch,l.recentTaskBatches),[l.latestTaskBatch,l.recentTaskBatches]),ke=Wl(Wn),gt=l.source==="bridge"&&!!(Wn&&ke);p.useEffect(()=>{A.current=e.metadata??{}},[e.metadata]);const Hn=p.useCallback((i,d)=>{const u=A.current??{},f=Object.entries(d).filter(([C,R])=>u[C]!==R).map(([C])=>C);if(f.length===0)return;const T={...u,...d};A.current=T,t(e.id,{metadata:T}),g.emit("remoteMonitor.node.metadata.patch",{nodeId:e.id,reason:i,keys:f})},[e.id,t]);p.useEffect(()=>{l.loading||Hn("snapshot",Ul({source:l.source,hub:l.hub,baseUrl:l.baseUrl,hubLabel:Uo,routeLabel:lo,connected:_t,total:et,taskCount:Bo,taskDispatchCount:Go,aiCount:Ft,pageLabel:Fo,pageStart:X,pageIndex:O,pageCount:P,projectionMode:en,projectedCount:D,visibleBudget:Me,selectedDeviceId:H,inputLabel:qo,devices:l.devices,latestTaskBatch:l.latestTaskBatch,recentTaskBatches:l.recentTaskBatches,taskFollowActive:gt,taskFollowKey:ke,isHostActiveForNode:ie,registryRouteInfo:re,hostTargetRenewMs:ie?fo:0,autoHostEnabled:me,agent:l.agent,agentStatusLabel:Bt,agentRunning:co,agentReady:Wo,message:l.message}))},[Ft,me,O,_t,Wo,co,Bt,Uo,qo,ie,P,Fo,X,Hn,D,re,lo,H,l.agent,l.baseUrl,l.devices,l.hub,l.latestTaskBatch,l.loading,l.message,l.recentTaskBatches,l.source,gt,ke,Bo,Go,et]),p.useEffect(()=>{kt!==O&&Ze(O)},[O,kt]),p.useEffect(()=>{const i=new Set(tt);for(const d of k.current.keys())i.has(d)||k.current.delete(d)},[tt]),p.useEffect(()=>{g.emit("remoteMonitor.node.frameSubscription",{nodeId:e.id,deviceCount:m?$e.length:0,visibleDeviceCount:$e.length,transportVisible:m,pageIndex:O,pageStart:X,visibleBudget:Me,transportKey:ot})},[O,e.id,X,m,$e.length,ot]),p.useEffect(()=>{if(l.source!=="bridge")return;const i=[re.status,re.reason,re.accountRouteReady?"ready":"local",re.migrationBlocked?"migration":"",ie?"hosting":"inactive"].join("|");Oe.current!==i&&(Oe.current=i,g.emit("remoteMonitor.node.registryRoute",{nodeId:e.id,status:re.status,reason:re.reason,accountRouteReady:re.accountRouteReady,migrationBlocked:re.migrationBlocked,hostTargetActive:ie}))},[ie,e.id,re,l.source]),p.useEffect(()=>{ht(tn(e.id))},[e.id]);const Tt=p.useCallback((i,d)=>{Ze(u=>{const f=Math.max(0,Math.min(P-1,u+i));return f!==u&&g.emit("remoteMonitor.node.page",{nodeId:e.id,from:u,to:f,pageCount:P,visibleBudget:Me,source:d}),f})},[e.id,P]),Kn=p.useCallback((i,d)=>{i.stopPropagation(),Tt(d,"button")},[Tt]),Xn=p.useCallback((i,d)=>{i.preventDefault(),i.stopPropagation(),_o(u=>{const f=Math.max(0,Math.min(Vt.length-1,u+d));return f!==u&&g.emit("remoteMonitor.node.tileScale",{nodeId:e.id,from:u,to:f,scale:Vt[f],visibleBudget:Me}),f})},[e.id]);p.useEffect(()=>{var i;(i=c.current)==null||i.scrollTo({left:0,top:0,behavior:"auto"}),_e.current=0},[O,He,ot]);const at=p.useCallback(i=>{if(i instanceof HTMLElement){const d=i.closest('[data-testid="remote-monitor-node-wall"]');if(d instanceof HTMLDivElement)return d}return c.current},[]),Yn=p.useCallback(i=>i.scrollWidth>i.clientWidth+1||i.scrollHeight>i.clientHeight+1,[]),Ho=p.useCallback(i=>{if(i.button!==0&&i.button!==1)return;const d=i.target instanceof HTMLElement?i.target:null;if(d!=null&&d.closest('button,input,textarea,select,[contenteditable="true"],[contenteditable=""]'))return;const u=at(i.target);if(u){W.current={active:!0,pointerId:i.pointerId,startX:i.clientX,startY:i.clientY,lastX:i.clientX,lastY:i.clientY,scrollLeft:u.scrollLeft,scrollTop:u.scrollTop,didPan:!1,pageTriggered:!1},i.preventDefault(),i.stopPropagation();try{i.currentTarget.setPointerCapture(i.pointerId)}catch{}}},[at]),Ko=p.useCallback(i=>{const d=W.current;if(!(d!=null&&d.active)||d.pointerId!==i.pointerId)return;const u=at(i.target);if(!u)return;const f=i.clientX-d.startX,T=i.clientY-d.startY;if(!d.didPan&&Math.max(Math.abs(f),Math.abs(T))>=_l&&(d.didPan=!0,Pe.current=!0),d.didPan){u.scrollLeft=d.scrollLeft-f,u.scrollTop=d.scrollTop-T;const C=Math.abs(T)>=Math.abs(f)?T:f;!d.pageTriggered&&P>1&&!Yn(u)&&Math.abs(C)>=Fl&&(d.pageTriggered=!0,Tt(C<0?1:-1,"drag"))}d.lastX=i.clientX,d.lastY=i.clientY,i.preventDefault(),i.stopPropagation()},[Yn,Tt,at,P]),It=p.useCallback(i=>{const d=W.current;if(!(!(d!=null&&d.active)||d.pointerId!==i.pointerId)){W.current=null;try{i.currentTarget.releasePointerCapture(i.pointerId)}catch{}if(d.didPan){const u=at(i.target);g.emit("remoteMonitor.node.wallPan",{nodeId:e.id,source:"drag",dx:Math.round(d.lastX-d.startX),dy:Math.round(d.lastY-d.startY),scrollLeft:Math.round((u==null?void 0:u.scrollLeft)??0),scrollTop:Math.round((u==null?void 0:u.scrollTop)??0),pageIndex:O,pageCount:P}),i.preventDefault(),i.stopPropagation()}}},[O,at,e.id,P]),Vr=p.useCallback(i=>{const d=i.target instanceof HTMLElement?i.target:null;if(d!=null&&d.closest('[data-input-active="true"]'))return;const u=at(i.target);if(!u)return;const f=u.scrollLeft,T=u.scrollTop;u.scrollLeft+=i.deltaX,u.scrollTop+=i.deltaY;const C=u.scrollLeft!==f||u.scrollTop!==T;!C&&P>1&&Math.abs(i.deltaY)>=Math.abs(i.deltaX)&&(_e.current+=i.deltaY,Math.abs(_e.current)>=Bl&&(Tt(_e.current>0?1:-1,"wheel"),_e.current=0)),g.emit("remoteMonitor.node.wallPan",{nodeId:e.id,source:"wheel",dx:Math.round(i.deltaX),dy:Math.round(i.deltaY),moved:C,scrollLeft:Math.round(u.scrollLeft),scrollTop:Math.round(u.scrollTop),pageIndex:O,pageCount:P}),i.preventDefault(),i.stopPropagation()},[Tt,O,at,e.id,P]),qr=p.useCallback(i=>{i.stopPropagation();const d=Jl(i.target.value);oo(u=>u===d?u:(g.emit("remoteMonitor.node.groupMode",{nodeId:e.id,from:u,to:d,projectedCount:z.length,visibleBudget:Me}),d)),Ze(0)},[z.length,e.id]),Wr=p.useCallback(i=>{i.stopPropagation();const d=i.target.value.slice(0,64);no(u=>u===d?u:(g.emit("remoteMonitor.node.filter",{nodeId:e.id,reason:"search",searchText:d.trim(),visibilityFilter:Ae,capabilityFilter:Ee,projectedCount:z.length,visibleBudget:Me}),d)),Ze(0)},[Ee,z.length,e.id,Ae]),Hr=p.useCallback(i=>{i.stopPropagation();const d=Zl(i.target.value);ao(u=>u===d?u:(g.emit("remoteMonitor.node.filter",{nodeId:e.id,reason:"visibility",searchText:y,from:u,to:d,visibilityFilter:d,capabilityFilter:Ee,projectedCount:z.length,visibleBudget:Me}),d)),Ze(0)},[Ee,z.length,e.id,y]),Kr=p.useCallback(i=>{i.stopPropagation();const d=ec(i.target.value);ro(u=>u===d?u:(g.emit("remoteMonitor.node.filter",{nodeId:e.id,reason:"capability",searchText:y,visibilityFilter:Ae,from:u,to:d,capabilityFilter:d,projectedCount:z.length,visibleBudget:Me}),d)),Ze(0)},[z.length,e.id,y,Ae]),Xr=p.useCallback((i,d)=>{i.stopPropagation();const u=it(d);if(!u||!o)return;const f=qt(d);o({sourceNodeId:e.id,deviceId:u,deviceName:ft(d),platform:Kt(d),connected:d.connected===!0,baseUrl:l.baseUrl,framePath:f==null?void 0:f.framePath,frameUrl:f==null?void 0:f.frameUrl,dataUrl:f==null?void 0:f.dataUrl,frameSeq:f==null?void 0:f.frameSeq}),g.emit("remoteMonitor.node.controlNode.create",{nodeId:e.id,deviceId:u,source:l.source})},[e.id,o,l.baseUrl,l.source]),se=p.useCallback(async(i="manual")=>{const d=++be.current,u=j();if(b(f=>({...f,loading:!0,baseUrl:u})),!At()){const f=bo(n,r);b({source:"blocked",loading:!1,message:"Hosted LocalBridge access is gated.",baseUrl:u,devices:f}),g.emit("remoteMonitor.node.preview",{nodeId:e.id,reason:"hosted-localbridge-gated",total:f.length});return}try{const f=await Rn(u);if(d!==be.current)return;if(f.state!=="connected"){const Te=bo(n,r);b({source:"unavailable",loading:!1,message:f.message||"LocalBridge is unavailable.",baseUrl:u,bridge:f,devices:Te}),g.emit("remoteMonitor.node.preview",{nodeId:e.id,reason:"localbridge-unavailable",total:Te.length});return}const T=or(f.status),C=el(T,u).catch(Te=>{g.emit("remoteMonitor.node.agent.status",{nodeId:e.id,reason:i,ok:!1,error:Te instanceof Error?Te.message:String(Te)})}),[R,$,G]=await Promise.all([nr(T,u),ar(T,u,{includeDataUrl:!1}),C]);if(d!==be.current)return;const ge=Array.isArray($.devices)?$.devices:[];b({source:"bridge",loading:!1,message:R.started?"RemoteHub online.":R.enabled===!1?R.lastError||"RemoteHub adapter is not configured.":"RemoteHub available.",baseUrl:u,bridge:f,auth:T,hub:R,agent:G,latestTaskBatch:$.latestTaskBatch,recentTaskBatches:Array.isArray($.recentTaskBatches)?$.recentTaskBatches:[],devices:ge}),g.emit("remoteMonitor.node.refresh",{nodeId:e.id,reason:i,total:$.total??ge.length,connected:ge.filter(Te=>Te.connected===!0).length,agentStatus:w(G==null?void 0:G.status),agentRunning:(G==null?void 0:G.running)===!0}),G&&g.emit("remoteMonitor.node.agent.status",{nodeId:e.id,reason:i,ok:!0,status:w(G.status),running:G.running===!0,ready:G.ready===!0})}catch(f){if(d!==be.current)return;const T=bo(n,r);b({source:"unavailable",loading:!1,message:f instanceof Error?f.message:String(f),baseUrl:u,devices:T}),g.emit("remoteMonitor.node.preview",{nodeId:e.id,reason:"remotehub-error",total:T.length})}},[r,n,e.id]);p.useEffect(()=>{se("mount")},[se]);const Ut=p.useCallback((i,d,u)=>{const f=Br(M.current,i);if(!f)return!1;const{cached:T,scope:C}=f;return Ro(d,T,x.current,v.current).then(R=>{R&&g.emit("remoteMonitor.node.frameCache",{nodeId:e.id,deviceId:i,frameSeq:pt(T.metadata),scope:C,reason:u})}),!0},[e.id]),Yr=p.useCallback((i,d)=>{i&&(d?(k.current.set(i,d),Ut(i,d,"canvas-attach")):k.current.delete(i))},[Ut]);p.useEffect(()=>{for(const i of he){const d=it(i),u=k.current.get(d);if(!u)continue;const f=qt(i),T=En(f);l.source==="bridge"&&T?bn(u,d,f,l.baseUrl,x.current,v.current,M.current).then(C=>{C.painted||C.busy||(C.staleDropped&&g.emit("remoteMonitor.node.frameStaleDropped",{nodeId:e.id,deviceId:d,frameSeq:C.frameSeq,previous:C.previous,source:"projection"}),!(l.source==="bridge"&&Ut(d,u,"projection-rerender"))&&Mo(u,i,l.source))}):l.source==="bridge"&&Ut(d,u,"projection-rerender")||Mo(u,i,l.source)}},[e.id,Ut,l.baseUrl,l.source,he]);const Xo=p.useCallback(async(i,d)=>{const u=w(i.deviceId).trim();if(!u)return;const f=w(i.streamId).trim(),T=Number(i.frameSeq||0)||0,C=Ln(v.current,M.current,u),R=V.current.get(u)||"",$=!!(f&&R&&f!==R);if($&&(v.current.delete(u),g.emit("remoteMonitor.node.frameStreamReset",{nodeId:e.id,deviceId:u,fromStreamId:R,toStreamId:f,previous:C,frameSeq:T})),!$&&T>0&&T<=C){g.emit("remoteMonitor.node.frameStaleDropped",{nodeId:e.id,deviceId:u,frameSeq:T,previous:C,source:"ws"});return}const G=dr(i,d.byteLength);G.level!=="nominal"&&g.emit("remoteMonitor.node.framePressure",{nodeId:e.id,deviceId:u,frameSeq:T,streamId:f,...G});const ge=_r(M.current,u,i,d),Te=k.current.get(u);if(Te){if(x.current.has(u)){g.emit("remoteMonitor.node.frameCache",{nodeId:e.id,deviceId:u,frameSeq:T,scope:"local",reason:"decode-pending"});return}x.current.add(u);try{await jn(Te,ge.metadata,ge.payload)&&(T>0&&v.current.set(u,T),f&&V.current.set(u,f),E.current+=1,E.current%12===1&&g.emit("remoteMonitor.node.framePainted",{nodeId:e.id,deviceId:u,frameSeq:T,streamId:i.streamId||"",painted:E.current,source:"ws"}))}catch{}finally{x.current.delete(u);const je=M.current.get(u),Ke=pt(je==null?void 0:je.metadata),da=v.current.get(u)||0,ua=k.current.get(u);je&&ua&&(Ke<=0?da<=0:Ke>da)&&Ro(ua,je,x.current,v.current).then(hi=>{hi&&(E.current+=1,g.emit("remoteMonitor.node.frameCache",{nodeId:e.id,deviceId:u,frameSeq:Ke,scope:"local",reason:"latest-pending"}),g.emit("remoteMonitor.node.framePainted",{nodeId:e.id,deviceId:u,frameSeq:Ke,streamId:je.metadata.streamId||"",painted:E.current,source:"ws-cache"}))})}}},[e.id]);p.useEffect(()=>{if(l.source!=="bridge"||!m||!zo)return;const i=Ra(ot);if(i.length===0)return;let d=!1,u=null,f=0;const T=()=>{var C,R;if(!d){ue.current=!1;try{u=new WebSocket(Ar(l.baseUrl,zo,(R=(C=l.bridge)==null?void 0:C.status)==null?void 0:R.bridgeToken,i)),u.binaryType="arraybuffer"}catch($){g.emit("remoteMonitor.node.frameWs",{nodeId:e.id,ok:!1,error:$ instanceof Error?$.message:String($)});return}u.onopen=()=>{ue.current=!0,B.current=performance.now(),g.emit("remoteMonitor.node.frameWs",{nodeId:e.id,ok:!0,deviceCount:i.length,fps:Ia}),u==null||u.send(JSON.stringify({type:"subscribe",deviceIds:i,autoStartLive:!0,fps:Ia,maxWidth:640,maxHeight:360,quality:55,mode:"remote-fast"}))},u.onmessage=async $=>{if(!d){if(B.current=performance.now(),$.data instanceof ArrayBuffer){const G=wo($.data);G&&await Xo(G.metadata,G.payload);return}if($.data instanceof Blob){const G=wo(await $.data.arrayBuffer());G&&await Xo(G.metadata,G.payload)}}},u.onerror=()=>{g.emit("remoteMonitor.node.frameWs",{nodeId:e.id,ok:!1,reason:"socket-error"})},u.onclose=()=>{ue.current=!1,d||(f=window.setTimeout(T,1500))}}};return T(),()=>{d=!0,ue.current=!1,window.clearTimeout(f),u==null||u.close()}},[e.id,Xo,zo,l.baseUrl,(ia=(ra=l.bridge)==null?void 0:ra.status)==null?void 0:ia.bridgeToken,l.source,m,ot]),p.useEffect(()=>{if(l.source!=="bridge"||!m)return;const i=Ra(ot);if(i.length===0)return;let d=!1,u=!1;const f=async()=>{var R;if(!(d||u)&&!(ue.current&&performance.now()-B.current<kr)){u=!0;try{const $=await rr(i,l.auth,l.baseUrl);if(d||$.ok===!1)return;let G=0,ge=0;for(const Te of $.frames||[]){const je=String(Te.deviceId||"").trim();if(!je)continue;const Ke=await bn(k.current.get(je),je,Or(Te),l.baseUrl,x.current,v.current,M.current);Ke.painted&&(G+=1),Ke.staleDropped&&(ge+=1,g.emit("remoteMonitor.node.frameStaleDropped",{nodeId:e.id,deviceId:je,frameSeq:Ke.frameSeq,previous:Ke.previous,source:"snapshot"}))}g.emit("remoteMonitor.node.frameSnapshot",{nodeId:e.id,deviceCount:i.length,frameCount:((R=$.frames)==null?void 0:R.length)||0,painted:G,staleDropped:ge})}catch{}finally{u=!1}}},T=window.setTimeout(f,200),C=window.setInterval(f,Ll);return()=>{d=!0,window.clearTimeout(T),window.clearInterval(C)}},[e.id,l.auth,l.baseUrl,l.source,m,ot]),p.useEffect(()=>{Q(!1),ne("locked"),ae("Remote input locked.")},[H,l.source]),p.useEffect(()=>{!S||Le||(Q(!1),ne("unavailable"),ae(nt||"Remote input unavailable."),g.emit("remoteMonitor.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"control-unavailable",deviceId:H}))},[Le,nt,S,e.id,H]),p.useEffect(()=>{var u,f,T;if(!S){(u=F.current)==null||u.close(),F.current=null,ne("locked");return}if(!Le||!H){ne("unavailable"),ae(nt||"Remote input unavailable.");return}let i=!1,d=null;ne("connecting"),ae("Connecting remote input adapter...");try{d=new WebSocket(Mr(l.baseUrl,$o,(T=(f=l.bridge)==null?void 0:f.status)==null?void 0:T.bridgeToken)),F.current=d}catch(C){const R=C instanceof Error?C.message:String(C);ne("error"),ae(R),g.emit("remoteMonitor.node.input.ws",{nodeId:e.id,ok:!1,deviceId:H,error:R});return}return d.onopen=()=>{i||(ne("ready"),ae("Remote input ready."),g.emit("remoteMonitor.node.input.ws",{nodeId:e.id,ok:!0,deviceId:H}))},d.onmessage=C=>{if(i)return;const R=hr(String(C.data||"{}"));if(R){if(R.type==="RemoteInputSocketReady"){ne("ready");return}g.emit("remoteMonitor.node.input.result",{nodeId:e.id,ok:R.ok,deviceId:R.deviceId||H,inputType:R.inputType,error:R.error}),!R.ok||R.error?ae(R.error||"Remote input failed."):/^pointermove$/i.test(R.inputType)||ae(`${R.inputType||"Input"} queued.`)}},d.onerror=()=>{i||(ne("error"),ae("Remote input socket error."),g.emit("remoteMonitor.node.input.ws",{nodeId:e.id,ok:!1,deviceId:H,reason:"socket-error"}))},d.onclose=()=>{i||(F.current=null,ne("error"),ae("Remote input socket closed."),g.emit("remoteMonitor.node.input.ws",{nodeId:e.id,ok:!1,deviceId:H,reason:"socket-closed"}))},()=>{i=!0,F.current===d&&(F.current=null),d==null||d.close()}},[Le,nt,S,e.id,$o,H,l.baseUrl,(la=(sa=l.bridge)==null?void 0:sa.status)==null?void 0:la.bridgeToken]),p.useEffect(()=>{if(!S)return;const i=d=>{d.key==="Escape"&&(d.preventDefault(),Q(!1),ae("Remote input locked."),g.emit("remoteMonitor.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"escape",deviceId:H}))};return window.addEventListener("keydown",i,!0),()=>window.removeEventListener("keydown",i,!0)},[S,e.id,H]);const Qr=p.useCallback(i=>{i.stopPropagation(),tr(!0),g.emit("remoteMonitor.node.hostedAccess.enabled",{nodeId:e.id}),se("hosted-access-enabled")},[e.id,se]),Qn=p.useCallback(i=>{i.stopPropagation(),se("manual")},[se]),Jr=p.useCallback(async i=>{var d,u,f;if(i.stopPropagation(),!po){de(uo||"RemoteAgent connect unavailable.");return}mt("connect"),de("Connecting RemoteAgent...");try{const T=await tl(Gt,l.auth,l.baseUrl);T.agent&&b(R=>R.source==="bridge"?{...R,agent:T.agent,message:R.message}:R);const C=T.ok===!0;de(C?T.alreadyRunning===!0?"RemoteAgent already running.":T.skipped===!0?T.reason||"RemoteAgent connect skipped.":"RemoteAgent connect requested.":T.error||"RemoteAgent connect failed."),g.emit("remoteMonitor.node.agent.connect",{nodeId:e.id,ok:C,alreadyRunning:T.alreadyRunning===!0,skipped:T.skipped===!0,reason:T.reason||"",status:w((d=T.agent)==null?void 0:d.status),managerCount:((u=Gt.managerCandidates)==null?void 0:u.length)??0,error:T.error||""}),C&&await se("agent-connect")}catch(T){const C=T instanceof Error?T.message:String(T);de(C),g.emit("remoteMonitor.node.agent.connect",{nodeId:e.id,ok:!1,managerCount:((f=Gt.managerCandidates)==null?void 0:f.length)??0,error:C})}finally{mt("")}},[po,e.id,se,uo,Gt,l.auth,l.baseUrl]),Zr=p.useCallback(async i=>{var d;if(i.stopPropagation(),!mo){de("RemoteAgent is not running.");return}mt("disconnect"),de("Stopping RemoteAgent...");try{const u=await ol("react-remote-monitor-manual",l.auth,l.baseUrl);u.agent&&b(T=>T.source==="bridge"?{...T,agent:u.agent,message:T.message}:T);const f=u.ok===!0;de(f?"RemoteAgent stopped.":u.error||"RemoteAgent stop failed."),g.emit("remoteMonitor.node.agent.disconnect",{nodeId:e.id,ok:f,status:w((d=u.agent)==null?void 0:d.status),error:u.error||""}),f&&await se("agent-disconnect")}catch(u){const f=u instanceof Error?u.message:String(u);de(f),g.emit("remoteMonitor.node.agent.disconnect",{nodeId:e.id,ok:!1,error:f})}finally{mt("")}},[mo,e.id,se,l.auth,l.baseUrl]),ei=p.useCallback(async i=>{var u;i.stopPropagation();const d=jr(l.hub);try{const f=await Mn(d);we("Connect command copied."),g.emit("remoteMonitor.node.connectCommand.copy",{nodeId:e.id,ok:!0,method:f,source:l.source,hasPairPreview:!!((u=l.hub)!=null&&u.pairTokenPreview)})}catch(f){we(f instanceof Error?f.message:"Clipboard is unavailable."),g.emit("remoteMonitor.node.connectCommand.copy",{nodeId:e.id,ok:!1})}},[e.id,l.hub,l.source]),vt=p.useCallback(async(i,d)=>{if(l.source!=="bridge"||Ce.current)return!1;Ce.current=!0,we(i?"Requesting host target...":"Clearing host target...");try{const u=await fa(e.id,i,l.auth,l.baseUrl,{leaseMs:$t});if(u.ok===!0){const f=i&&u.active===!0;Ma(e.id,f),ht(f)}return we(u.ok===!0?u.active?"This monitor node is the host target.":"Host target cleared.":u.error||"Host target update failed."),g.emit("remoteMonitor.node.hostTarget",{nodeId:e.id,reason:d,autoHost:me,ok:u.ok===!0,active:u.active===!0}),await se("host-target"),u.ok===!0&&(i?u.active===!0:u.active!==!0)}catch(u){return we(u instanceof Error?u.message:String(u)),g.emit("remoteMonitor.node.hostTarget",{nodeId:e.id,reason:d,autoHost:me,ok:!1}),!1}finally{Ce.current=!1}},[me,e.id,se,l.auth,l.baseUrl,l.source]),ti=p.useCallback(i=>{i.stopPropagation(),vt(!ie,"manual")},[ie,vt]),oi=p.useCallback(i=>{i.stopPropagation();const d=!me;Ma(e.id,d),ht(d),we(d?"Auto Host enabled for this monitor.":"Auto Host disabled."),g.emit("remoteMonitor.node.autoHost",{nodeId:e.id,enabled:d,source:l.source}),!d&&ie&&vt(!1,"auto-host-disabled")},[me,ie,e.id,vt,l.source]);p.useEffect(()=>{if(l.source!=="bridge"||!me||ie||ee.current)return;if(!tn(e.id)){ht(!1);return}let i=!1;return ee.current=!0,we("Restoring Auto Host..."),g.emit("remoteMonitor.node.autoHost.restore",{nodeId:e.id,requested:!0,source:l.source}),vt(!0,"auto-host-restore").then(d=>{i||(g.emit("remoteMonitor.node.autoHost.restore",{nodeId:e.id,ok:d,source:l.source}),d||we("Auto Host restore failed."))}).finally(()=>{ee.current=!1}),()=>{i=!0}},[me,ie,e.id,vt,l.source]),p.useEffect(()=>{if(l.source!=="bridge"||!ie)return;let i=!1;const d=async()=>{if(!(i||h.current)){h.current=!0;try{const f=await fa(e.id,!0,l.auth,l.baseUrl,{leaseMs:$t});g.emit("remoteMonitor.node.hostTarget.renew",{nodeId:e.id,ok:f.ok===!0,active:f.active===!0,leaseMs:$t}),!i&&(f.ok!==!0||f.active!==!0)&&(we(f.error||"Host target renewal lost ownership."),await se("host-target-renew"))}catch(f){g.emit("remoteMonitor.node.hostTarget.renew",{nodeId:e.id,ok:!1,active:!1,leaseMs:$t,error:f instanceof Error?f.message:String(f)}),i||we(f instanceof Error?f.message:String(f))}finally{h.current=!1}}},u=window.setInterval(()=>{d()},fo);return g.emit("remoteMonitor.node.hostTarget.renew.timer",{nodeId:e.id,active:!0,intervalMs:fo,leaseMs:$t}),()=>{i=!0,window.clearInterval(u),g.emit("remoteMonitor.node.hostTarget.renew.timer",{nodeId:e.id,active:!1})}},[ie,e.id,se,l.auth,l.baseUrl,l.source]),p.useEffect(()=>{if(l.source!=="bridge"||!gt||!ke){gt||(L.current="",Y.current=0);return}let i=!1,d=0;L.current!==ke&&(L.current=ke,Y.current=0);const u=f=>{window.clearTimeout(d),d=window.setTimeout(async()=>{if(i||L.current!==ke)return;const T=Y.current;if(T>=Rt){g.emit("remoteMonitor.node.task.follow",{nodeId:e.id,active:!1,batchKey:ke,tick:T,maxTicks:Rt,reason:"max-ticks"});return}const C=T+1;Y.current=C,g.emit("remoteMonitor.node.task.follow",{nodeId:e.id,active:!0,batchKey:ke,tick:C,maxTicks:Rt}),await se("task-follow"),!i&&L.current===ke&&Y.current<Rt&&u(Io)},Math.max(0,f))};return g.emit("remoteMonitor.node.task.follow",{nodeId:e.id,active:!0,batchKey:ke,intervalMs:Io,maxTicks:Rt,reason:"start"}),u(Nl),()=>{i=!0,window.clearTimeout(d),g.emit("remoteMonitor.node.task.follow",{nodeId:e.id,active:!1,batchKey:ke,tick:Y.current,reason:"cleanup"})}},[e.id,se,l.source,gt,ke]);const ni=p.useCallback(i=>{if(i.stopPropagation(),S){Q(!1),ae("Remote input locked."),g.emit("remoteMonitor.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"manual",deviceId:H});return}if(!Le){ne("unavailable"),ae(nt||"Remote input unavailable."),g.emit("remoteMonitor.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"unavailable",deviceId:H});return}Q(!0),ae("Connecting remote input adapter..."),g.emit("remoteMonitor.node.input.lock",{nodeId:e.id,unlocked:!0,reason:"manual",deviceId:H})},[Le,nt,S,e.id,H]),Ve=p.useCallback(i=>{var $;const d=F.current;if(!S||!Le||!H||(d==null?void 0:d.readyState)!==WebSocket.OPEN){i.ack&&ae(S?"Remote input socket is not ready.":"Remote input locked.");return}const u=`remote-node-input-${Date.now()}-${++J.current}`,{ack:f,...T}=i,C=mr({requestId:u,deviceId:H,ack:f,controlLeaseId:($=l.hub)==null?void 0:$.hostTargetLeaseId,input:T});if(!C){f&&ae("Remote input payload is invalid.");return}const R=w(C.input.type);try{d.send(JSON.stringify(C));const G=++Z.current;(C.ack||G%24===1)&&g.emit("remoteMonitor.node.input.sent",{nodeId:e.id,deviceId:H,inputType:R,sampled:!C.ack,sent:G})}catch(G){const ge=G instanceof Error?G.message:String(G);ne("error"),ae(ge),g.emit("remoteMonitor.node.input.ws",{nodeId:e.id,ok:!1,deviceId:H,error:ge})}},[Le,S,e.id,H,(ca=l.hub)==null?void 0:ca.hostTargetLeaseId]);p.useEffect(()=>{if(typeof document>"u")return;const i=d=>{const u=d.detail;if(!u||typeof u!="object")return;const f=w(u.nodeId);if(f&&f!==e.id)return;const T=w(u.deviceId);if(T&&T!==H)return;const C=u.input;!C||typeof C!="object"||Array.isArray(C)||Ve({...C,ack:u.ack!==!1})};return document.addEventListener(va,i),()=>document.removeEventListener(va,i)},[e.id,H,Ve]);const Ct=p.useCallback((i,d,u,f=!1)=>{const T=So(i,f);return T?(Ve({type:d,...T,button:Pr(i.button),ack:u}),!0):!1},[Ve]),ai=p.useCallback((i,d,u)=>{if(i.stopPropagation(),Fe(d),!u){Ho(i);return}if(Ct(i,"pointerDown",!0,!1)){i.preventDefault(),i.currentTarget.focus();try{i.currentTarget.setPointerCapture(i.pointerId)}catch{}}},[Ct,Ho]),ri=p.useCallback((i,d)=>{var C,R;if(!d){Ko(i);return}const u=performance.now();if(u-pe.current<Tr)return;pe.current=u;const f=((R=(C=i.currentTarget).hasPointerCapture)==null?void 0:R.call(C,i.pointerId))===!0;Ct(i,"pointerMove",!1,f)&&(i.preventDefault(),i.stopPropagation())},[Ct,Ko]),ii=p.useCallback((i,d)=>{if(!d){It(i);return}i.preventDefault(),i.stopPropagation();try{i.currentTarget.releasePointerCapture(i.pointerId)}catch{}Ct(i,"pointerUp",!0,!0)},[Ct,It]),si=p.useCallback((i,d)=>{d||It(i)},[It]),li=p.useCallback((i,d)=>{if(!d)return;const u=So(i,!1);u&&(Ve({type:"wheel",...u,deltaX:i.deltaX,deltaY:i.deltaY,ack:!0}),i.preventDefault(),i.stopPropagation())},[Ve]),ci=p.useCallback((i,d,u)=>{if(!u){(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),i.stopPropagation(),Fe(d));return}i.key!=="Escape"&&(i.preventDefault(),i.stopPropagation(),Ve({type:"keyDown",key:i.key,code:i.code,repeat:i.repeat,ack:!0}))},[Ve]),di=p.useCallback((i,d)=>{!d||i.key==="Escape"||(i.preventDefault(),i.stopPropagation(),Ve({type:"keyUp",key:i.key,code:i.code,repeat:!1,ack:!0}))},[Ve]),Yo=p.useCallback(async(i,d="selected")=>{var R;if(i.preventDefault(),i.stopPropagation(),l.source!=="bridge"){Ue("LocalBridge is not connected.");return}const u=Re.trim();if(!u){Ue("Remote task is empty.");return}if(d==="selected"&&(!H||!Vo||(oe==null?void 0:oe.connected)!==!0)){Ue("Selected device cannot accept remote tasks.");return}if(d==="all"&&io.length<=0){Ue("No task-capable connected devices are available.");return}if(d==="ai"&&so.length<=0){Ue("No AI assist devices are connected.");return}const f=d==="ai"?"ai-assist":"task-only",T=((R=u.split(/\r?\n/)[0])==null?void 0:R.slice(0,96))||"Remote task",C=d==="ai"?so:io;to(d),Ue(d==="selected"?"Queueing selected task...":"Queueing fleet task...");try{const $=d==="selected"?await ir(H,{instruction:u,title:T,approvalLevel:f},l.auth,l.baseUrl):await nl({instruction:u,title:T,approvalLevel:f,deviceIds:C,allConnected:!1},l.auth,l.baseUrl),G=$.ok===!0,ge=d==="selected"?G?1:0:Number("queued"in $?$.queued:0);Ue(G?`Queued ${ge||1} remote task${(ge||1)===1?"":"s"}.`:$.error||"Remote task queue failed."),g.emit("remoteMonitor.node.task.queue",{nodeId:e.id,mode:d,ok:G,queued:ge,approvalLevel:f,deviceId:d==="selected"?H:"",targetCount:d==="selected"?1:C.length,batchId:"batchId"in $?$.batchId:"",error:$.error||""}),G&&(eo(""),await se("task-queued"))}catch($){const G=$ instanceof Error?$.message:String($);Ue(G),g.emit("remoteMonitor.node.task.queue",{nodeId:e.id,mode:d,ok:!1,approvalLevel:f,deviceId:d==="selected"?H:"",targetCount:d==="selected"?1:C.length,error:G})}finally{to("")}},[Ft,so,e.id,se,Vo,oe==null?void 0:oe.connected,H,l.auth,l.baseUrl,l.source,io,Re]),ui=a.jsxs("div",{className:"node-remote-monitor__head-actions",children:[a.jsx("i",{"aria-label":`Remote route ${lo}`}),a.jsxs("span",{className:"node-remote-monitor__head-status","data-testid":"remote-monitor-node-agent-status","data-agent-status":Bt,children:["AGENT ",a.jsx("strong",{children:Bt})]}),a.jsxs("span",{className:`node-remote-monitor__head-status node-remote-monitor__route-status is-${re.tone}`,"data-testid":"remote-monitor-node-registry-route","data-registry-route":re.status,"data-account-route-ready":re.accountRouteReady?"true":"false","data-registry-migration-blocked":re.migrationBlocked?"true":"false",title:re.title,children:["ROUTE ",a.jsx("strong",{children:re.value})]}),l.source==="bridge"?a.jsxs(a.Fragment,{children:[a.jsxs("button",{type:"button","data-testid":"remote-monitor-node-host",onClick:ti,children:[a.jsx(ko,{size:12}),ie?"Clear Host":"Set Host"]}),a.jsxs("button",{type:"button",className:me?"is-active":"","data-testid":"remote-monitor-node-auto-host","data-auto-host-active":me?"true":"false",onClick:oi,title:me?"Disable Auto Host restore for this monitor":"Remember this monitor as the Auto Host target",children:[a.jsx(ko,{size:12}),"Auto"]}),a.jsxs("button",{type:"button","data-testid":"remote-monitor-node-agent-connect",onClick:Jr,disabled:!po,title:po?"Connect managed RemoteAgent":uo,children:[a.jsx(xi,{size:12,className:Se==="connect"?"spin-icon":""}),"Start"]}),a.jsxs("button",{type:"button","data-testid":"remote-monitor-node-agent-disconnect",onClick:Zr,disabled:!mo,title:mo?"Stop managed RemoteAgent":"RemoteAgent is not running",children:[a.jsx(wi,{size:12,className:Se==="disconnect"?"spin-icon":""}),"Stop"]})]}):l.source==="blocked"?a.jsxs("button",{type:"button",onClick:Qr,children:[a.jsx(ko,{size:12}),"Enable"]}):a.jsxs("button",{type:"button",onClick:Qn,children:[a.jsx(vo,{size:12,className:l.loading?"spin-icon":""}),"Refresh"]})]}),pi=a.jsxs("form",{className:"node-remote-monitor__taskbar","data-testid":"remote-monitor-node-taskbar",onSubmit:i=>Yo(i,"selected"),children:[a.jsx("input",{"aria-label":"Remote task",value:Re,maxLength:1200,onChange:i=>eo(i.target.value),onPointerDown:i=>i.stopPropagation(),placeholder:oe?`Task for ${ft(oe)}`:"Remote task"}),a.jsxs("button",{type:"submit",disabled:!$n,title:$n?"Queue task for selected device":"Selected device cannot accept remote tasks",children:[a.jsx(nn,{size:12,className:Je==="selected"?"spin-icon":""}),"Selected"]}),a.jsxs("button",{type:"button",disabled:!Vn,title:Vn?"Queue task for connected devices":"No connected devices can accept tasks",onClick:i=>Yo(i,"all"),children:[a.jsx(nn,{size:12,className:Je==="all"?"spin-icon":""}),"All"]}),a.jsxs("button",{type:"button",disabled:!qn,title:qn?"Queue AI assist task for connected AI devices":"No AI assist device is connected",onClick:i=>Yo(i,"ai"),children:[a.jsx(Si,{size:12,className:Je==="ai"?"spin-icon":""}),"AI"]})]}),mi=a.jsxs("div",{className:"node-remote-monitor__footer",children:[a.jsxs("div",{className:"node-remote-monitor__footer-scale","data-testid":"remote-monitor-node-tile-scale","data-tile-scale-index":He,"data-tile-scale":Ot,children:[a.jsx("button",{type:"button","aria-label":"Shrink remote monitor tiles","data-testid":"remote-monitor-node-tile-shrink",disabled:He<=0,onClick:i=>Xn(i,-1),children:a.jsx(Ri,{size:12})}),a.jsx("button",{type:"button","aria-label":"Grow remote monitor tiles","data-testid":"remote-monitor-node-tile-grow",disabled:He>=Vt.length-1,onClick:i=>Xn(i,1),children:a.jsx(ja,{size:12})})]}),a.jsxs("label",{className:"node-remote-monitor__footer-group","data-testid":"remote-monitor-node-group","data-group-mode":ze,children:[a.jsx("span",{children:"GROUP"}),a.jsx("select",{"aria-label":"Remote monitor grouping","data-testid":"remote-monitor-node-group-mode",value:ze,onPointerDown:i=>i.stopPropagation(),onChange:qr,children:Cr.map(i=>a.jsx("option",{value:i,children:tc(i)},i))})]}),a.jsxs("label",{className:"node-remote-monitor__footer-filter","data-testid":"remote-monitor-node-filter","data-filter-active":N?"true":"false",children:[a.jsx("span",{children:"FILTER"}),a.jsx("input",{"aria-label":"Remote monitor search","data-testid":"remote-monitor-node-filter-text",value:Dt,maxLength:64,onPointerDown:i=>i.stopPropagation(),onChange:Wr,placeholder:"Any"}),a.jsx("select",{"aria-label":"Remote monitor visibility filter","data-testid":"remote-monitor-node-visibility-filter",value:Ae,onPointerDown:i=>i.stopPropagation(),onChange:Hr,children:xr.map(i=>a.jsx("option",{value:i,children:oc(i)},i))}),a.jsx("select",{"aria-label":"Remote monitor capability filter","data-testid":"remote-monitor-node-capability-filter",value:Ee,onPointerDown:i=>i.stopPropagation(),onChange:Kr,children:wr.map(i=>a.jsx("option",{value:i,children:nc(i)},i))})]}),a.jsxs("div",{className:"node-remote-monitor__footer-status",children:[a.jsxs("span",{children:[a.jsx("i",{})," HUB ",a.jsx("strong",{children:Uo})]}),a.jsxs("span",{children:["CONNECTED ",a.jsxs("strong",{children:[_t,"/",et]})]}),a.jsxs("span",{children:["TASK ",a.jsx("strong",{children:Bo})]}),a.jsxs("span",{children:["AI ",a.jsx("strong",{children:Ft})]}),a.jsxs("span",{children:["INPUT ",a.jsx("strong",{children:qo})]}),a.jsxs("span",{children:["PAGE ",a.jsx("strong",{children:Fo})]}),a.jsxs("span",{children:[a.jsx("i",{})," ROUTE ",a.jsx("strong",{children:lo})]}),a.jsxs("button",{type:"button","data-testid":"remote-monitor-node-copy-connect",onClick:ei,children:[a.jsx(Na,{size:12}),"Connect"]}),a.jsxs("button",{type:"button","data-testid":"remote-monitor-node-refresh",onClick:Qn,children:[a.jsx(vo,{size:12,className:l.loading?"spin-icon":""}),"Refresh"]}),l.source==="bridge"&&a.jsxs("button",{type:"button","data-testid":"remote-monitor-node-input",onClick:ni,disabled:!Le&&!S,title:S||Le?jt:nt,children:[S?a.jsx(Da,{size:12}):a.jsx(Oa,{size:12}),S?"Lock":"Unlock"]})]})]});return a.jsxs("div",{ref:s,className:"node-remote-monitor","data-testid":"remote-monitor-node","data-remote-source":l.source,"data-remote-canonical-total":et,"data-remote-connected":_t,"data-remote-projection":en,"data-remote-projected-count":D,"data-remote-visible-budget":Me,"data-remote-page-index":O,"data-remote-page-count":P,"data-remote-page-start":X,"data-remote-host-active":ie?"true":"false","data-remote-registry-route":re.status,"data-remote-registry-ready":re.accountRouteReady?"true":"false","data-remote-registry-migration-blocked":re.migrationBlocked?"true":"false","data-remote-registry-reason":re.reason,"data-remote-host-renew-ms":ie?fo:0,"data-remote-auto-host":me?"true":"false","data-remote-agent-status":Bt,"data-remote-agent-running":co?"true":"false","data-remote-agent-ready":Wo?"true":"false","data-remote-task-follow-active":gt?"true":"false","data-remote-task-follow-key":ke,"data-remote-task-follow-refresh-ms":gt?Io:0,"data-remote-transport-visible":m?"true":"false","data-remote-frame-subscription-active":m&&$e.length>0?"true":"false","data-remote-tile-scale-index":He,"data-remote-tile-scale":Ot,"data-remote-tile-min-width":Bn,"data-remote-tile-min-height":Gn,"data-remote-group-mode":ze,"data-remote-visible-group-count":_n,"data-remote-filter-text":y,"data-remote-filter-active":N?"true":"false","data-remote-visibility-filter":Ae,"data-remote-capability-filter":Ee,"data-remote-filtered-count":U.length,"data-disable-mindcanvas-wheel":"true",onPointerDown:i=>i.stopPropagation(),children:[a.jsxs("div",{className:"node-remote-monitor__surface",children:[a.jsx("div",{className:"node-remote-monitor__head",children:a.jsxs("div",{className:"node-remote-monitor__titlemark",children:[a.jsx("span",{children:a.jsx(Mi,{size:15})}),a.jsxs("div",{children:[a.jsx("small",{children:"REMOTE"}),a.jsx("strong",{children:"Multi Desktop Monitor"})]})]})}),a.jsxs("div",{className:"node-remote-monitor__wall-shell",children:[a.jsxs("div",{ref:c,className:"node-remote-monitor__wall","data-testid":"remote-monitor-node-wall","data-page-index":O,"data-page-count":P,"data-page-start":X,"data-visible-devices":he.length,"data-visible-device-ids":tt.join(","),"data-visible-connected-devices":$e.length,"data-frame-subscription-device-ids":ot,"data-frame-subscription-active":m&&$e.length>0?"true":"false","data-transport-visible":m?"true":"false","data-canonical-device-count":et,"data-connected-device-count":_t,"data-wall-projection":en,"data-projected-device-count":D,"data-visible-budget":Me,"data-tile-scale-index":He,"data-tile-scale":Ot,"data-group-mode":ze,"data-visible-group-count":_n,"data-filter-text":y,"data-filter-active":N?"true":"false","data-visibility-filter":Ae,"data-capability-filter":Ee,"data-filtered-device-count":U.length,style:{"--remote-node-tile-min-width":`${Bn}px`,"--remote-node-tile-min-height":`${Gn}px`},onPointerDown:i=>Ho(i),onPointerMove:i=>Ko(i),onPointerUp:i=>It(i),onPointerCancel:i=>It(i),onWheel:Vr,children:[he.map(i=>{const d=it(i),u=ft(i),f=qt(i),T=d===H,C=S&&Le&&T;return a.jsxs("span",{className:`${i.connected===!0?"is-online":""} ${T?"is-selected":""} ${C?"is-input-active":""}`,"aria-label":`${u} remote desktop`,title:`${u} / ${Kt(i)}`,role:"button",tabIndex:C||T?0:-1,"data-device-id":d,"data-connected":i.connected===!0?"true":"false","data-frame-seq":(f==null?void 0:f.frameSeq)??0,"data-can-control":ce(i,"control")?"true":"false","data-can-dispatch-task":ce(i,"taskDispatch")?"true":"false","data-ai-assist":ce(i,"aiAssist")?"true":"false","data-input-active":C?"true":"false","data-group-mode":ze,"data-group-key":ac(i,ze),onClick:R=>{if(R.stopPropagation(),Pe.current){Pe.current=!1,R.preventDefault();return}Fe(d)},onDoubleClick:R=>Xr(R,i),onPointerDown:R=>ai(R,d,C),onPointerMove:R=>ri(R,C),onPointerUp:R=>ii(R,C),onPointerCancel:R=>si(R,C),onWheel:R=>li(R,C),onKeyDown:R=>ci(R,d,C),onKeyUp:R=>di(R,C),children:[a.jsx("canvas",{ref:R=>Yr(d,R)}),C&&a.jsxs("em",{children:[a.jsx(_a,{size:10}),"input"]}),a.jsx("small",{children:u})]},d)}),Array.from({length:Ur},(i,d)=>a.jsx("span",{"aria-label":`Remote desktop slot ${X+he.length+d+1}`,"data-placeholder-slot":"true"},`empty-${O}-${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:O<=0,onClick:i=>Kn(i,-1),children:a.jsx(Pi,{size:12})}),a.jsx("span",{className:"node-remote-monitor__pager-track",style:{"--remote-node-page-top":`${zr}%`,"--remote-node-page-height":`${Fn}%`},children:a.jsx("strong",{})}),a.jsx("button",{type:"button","aria-label":"Next monitor page",disabled:O>=P-1,onClick:i=>Kn(i,1),children:a.jsx(Ai,{size:12})})]})]})]}),a.jsxs("div",{className:"node-remote-monitor__external-rail","data-testid":"remote-monitor-node-external-rail",onPointerDown:i=>i.stopPropagation(),onClick:i=>i.stopPropagation(),children:[ui,pi,mi,a.jsx("p",{className:"node-remote-monitor__message",children:$r})]})]})}function ou({node:e,onPatch:t}){var oo,Dt,no,Ae,ao,Ee,ro,me,ht,et;const o=Rr(e),n=p.useRef(null),r=Sr(n,e.id,"control"),[s,c]=p.useState(()=>{var y;return{source:At()?"loading":"blocked",loading:!1,message:At()?"Remote device not checked yet.":"Hosted LocalBridge access is gated.",baseUrl:((y=e.metadata)==null?void 0:y.RemoteBaseUrl)||j(),device:St(e)}}),m=p.useRef(null),l=p.useRef(new Set),b=p.useRef(new Map),k=p.useRef(new Map),x=p.useRef(null),v=p.useRef(0),V=p.useRef(0),M=p.useRef(!1),F=p.useRef(0),J=p.useRef(0),Z=p.useRef(0),E=p.useRef(0),ue=p.useRef(e.metadata??{}),[B,pe]=p.useState(!1),[Ce,h]=p.useState("locked"),[ee,L]=p.useState("Remote input locked."),[Y,Oe]=p.useState(""),[W,Pe]=p.useState(!1),[_e,be]=p.useState(""),A=s.device,xe=A?ft(A):e.title||"Remote device",Fe=A?Kt(A):((oo=e.metadata)==null?void 0:oo.RemoteFleetDevicePlatform)||"unknown",S=Qa((Dt=s.bridge)==null?void 0:Dt.status),Q=Ja((no=s.bridge)==null?void 0:no.status),te=s.source==="bridge"&&!!o&&(A==null?void 0:A.connected)===!0&&!!Q&&ce(A,"control"),ne=A?ce(A,"taskDispatch"):!1,jt=s.source==="bridge"&&!!o&&(A==null?void 0:A.connected)===!0&&ne&&!!Y.trim()&&!W,ae=B?Er(Ce):te?"Locked":"Off",Do=_e||ee||s.message;p.useEffect(()=>{ue.current=e.metadata??{}},[e.metadata]);const we=p.useCallback((y,I)=>{const N=ue.current??{},U=Object.entries(I).filter(([D,P])=>N[D]!==P).map(([D])=>D);if(U.length===0)return;const z={...N,...I};ue.current=z,t(e.id,{metadata:z}),g.emit("remoteControl.node.metadata.patch",{nodeId:e.id,reason:y,keys:U})},[e.id,t]),Se=p.useCallback(async(y="manual")=>{const I=++E.current,N=j();if(c(U=>({...U,loading:!0,baseUrl:N})),!o){c({source:"unavailable",loading:!1,message:"Remote control node has no device id.",baseUrl:N,device:St(e)});return}if(!At()){c({source:"blocked",loading:!1,message:"Hosted LocalBridge access is gated.",baseUrl:N,device:St(e)}),g.emit("remoteControl.node.preview",{nodeId:e.id,reason:"hosted-localbridge-gated",deviceId:o});return}try{const U=await Rn(N);if(I!==E.current)return;if(U.state!=="connected"){c({source:"unavailable",loading:!1,message:U.message||"LocalBridge is unavailable.",baseUrl:N,bridge:U,device:St(e)});return}const z=or(U.status),[D,P]=await Promise.all([nr(z,N),ar(z,N,{includeDataUrl:!1})]);if(I!==E.current)return;const O=(Array.isArray(P.devices)?P.devices:[]).find(he=>it(he)===o),X=O||St(e);c({source:O?"bridge":"unavailable",loading:!1,message:O?`${ft(X)} ${X.connected===!0?"online.":"offline."}`:"Selected remote device is not in the current RemoteHub inventory.",baseUrl:N,bridge:U,auth:z,hub:D,device:X}),g.emit("remoteControl.node.refresh",{nodeId:e.id,reason:y,deviceId:o,found:!!O,connected:X.connected===!0})}catch(U){if(I!==E.current)return;c({source:"unavailable",loading:!1,message:U instanceof Error?U.message:String(U),baseUrl:N,device:St(e)})}},[o,e]);p.useEffect(()=>{Se("mount")},[Se]),p.useEffect(()=>{var y,I,N;we("snapshot",{SemanticType:"RemoteFleetDevice",RemoteFleetSchemaVersion:"remote-fleet-device@1",RemoteFleetDeviceId:o,RemoteFleetDeviceName:xe,RemoteFleetDevicePlatform:Fe,RemoteFleetDeviceConnected:String((A==null?void 0:A.connected)===!0),RemoteFleetDeviceCanControl:String(te),RemoteFleetDeviceCanDispatchTask:String(ne),RemoteFleetDeviceTasksQueued:String(((y=A==null?void 0:A.counters)==null?void 0:y.tasksQueued)||0),RemoteFleetSourceMonitorNodeId:((I=e.metadata)==null?void 0:I.RemoteFleetSourceMonitorNodeId)||"",RemoteInput:ae,RemoteTask:ne?"available":"unavailable",RemoteHub:s.source==="bridge"?((N=s.hub)==null?void 0:N.started)===!0?"Online":"Ready":s.source==="blocked"?"Gated":s.source,RemoteRoute:s.source==="bridge"?"Local":s.source==="blocked"?"Gated":"Preview",RemoteBaseUrl:s.baseUrl,AdapterState:s.source==="bridge"?"localbridge-connected":s.source==="blocked"?"adapter-gated":s.source})},[te,ne,A==null?void 0:A.connected,(Ae=A==null?void 0:A.counters)==null?void 0:Ae.tasksQueued,o,xe,ae,e.metadata,we,Fe,s.baseUrl,(ao=s.hub)==null?void 0:ao.started,s.source]);const mt=p.useCallback((y,I)=>{if(!o)return!1;const N=Br(k.current,o);if(!N)return!1;const{cached:U,scope:z}=N;return Ro(y,U,l.current,b.current).then(D=>{D&&g.emit("remoteControl.node.frameCache",{nodeId:e.id,deviceId:o,frameSeq:pt(U.metadata),scope:z,reason:I})}),!0},[o,e.id]);p.useEffect(()=>{const y=m.current;if(!y||!A)return;const I=qt(A),N=En(I);s.source==="bridge"&&N?Gr(y,N,s.baseUrl).catch(()=>Mo(y,A,s.source)):s.source==="bridge"&&mt(y,"projection-rerender")||Mo(y,A,s.source)},[A,mt,s.baseUrl,s.source]);const Nt=p.useCallback(async(y,I)=>{if(!o||w(y.deviceId).trim()!==o)return;const N=Number(y.frameSeq||0)||0,U=Ln(b.current,k.current,o);if(N>0&&N<=U){g.emit("remoteControl.node.frameStaleDropped",{nodeId:e.id,deviceId:o,frameSeq:N,previous:U,source:"ws"});return}const z=dr(y,I.byteLength);z.level!=="nominal"&&g.emit("remoteControl.node.framePressure",{nodeId:e.id,deviceId:o,frameSeq:N,...z});const D=_r(k.current,o,y,I),P=m.current;if(P){if(l.current.has(o)){g.emit("remoteControl.node.frameCache",{nodeId:e.id,deviceId:o,frameSeq:N,scope:"local",reason:"decode-pending"});return}l.current.add(o);try{await jn(P,D.metadata,D.payload)&&(N>0&&b.current.set(o,N),J.current+=1,g.emit("remoteControl.node.framePainted",{nodeId:e.id,deviceId:o,frameSeq:N,painted:J.current,source:"ws"}))}catch{}finally{l.current.delete(o);const O=k.current.get(o),X=pt(O==null?void 0:O.metadata),he=b.current.get(o)||0,tt=m.current;O&&tt&&(X<=0?he<=0:X>he)&&Ro(tt,O,l.current,b.current).then($e=>{$e&&(J.current+=1,g.emit("remoteControl.node.frameCache",{nodeId:e.id,deviceId:o,frameSeq:X,scope:"local",reason:"latest-pending"}),g.emit("remoteControl.node.framePainted",{nodeId:e.id,deviceId:o,frameSeq:X,painted:J.current,source:"ws-cache"}))})}}},[o,e.id]);p.useEffect(()=>{if(s.source!=="bridge"||!o||(A==null?void 0:A.connected)!==!0||!r)return;let y=!1,I=null,N=0;M.current=!1;const U=()=>{var z,D;if(!y){try{I=new WebSocket(Ar(s.baseUrl,S,(D=(z=s.bridge)==null?void 0:z.status)==null?void 0:D.bridgeToken,[o])),I.binaryType="arraybuffer"}catch(P){g.emit("remoteControl.node.frameWs",{nodeId:e.id,ok:!1,error:P instanceof Error?P.message:String(P)});return}I.onopen=()=>{M.current=!0,F.current=performance.now(),g.emit("remoteControl.node.frameWs",{nodeId:e.id,ok:!0,deviceId:o,fps:20}),I==null||I.send(JSON.stringify({type:"subscribe",deviceIds:[o],autoStartLive:!0,fps:20,maxWidth:960,maxHeight:540,quality:62,mode:"remote-fast-control"}))},I.onmessage=async P=>{if(!y){if(F.current=performance.now(),P.data instanceof ArrayBuffer){const O=wo(P.data);O&&await Nt(O.metadata,O.payload)}else if(P.data instanceof Blob){const O=wo(await P.data.arrayBuffer());O&&await Nt(O.metadata,O.payload)}}},I.onerror=()=>{M.current=!1,g.emit("remoteControl.node.frameWs",{nodeId:e.id,ok:!1,deviceId:o,reason:"socket-error"})},I.onclose=()=>{M.current=!1,y||(N=window.setTimeout(U,1500))}}};return U(),()=>{y=!0,M.current=!1,window.clearTimeout(N),I==null||I.close()}},[A==null?void 0:A.connected,o,e.id,Nt,S,s.baseUrl,(ro=(Ee=s.bridge)==null?void 0:Ee.status)==null?void 0:ro.bridgeToken,s.source,r]),p.useEffect(()=>{if(s.source!=="bridge"||!o||(A==null?void 0:A.connected)!==!0||!r)return;let y=!1,I=!1;const N=async()=>{var D;if(!(y||I)&&!(M.current&&performance.now()-F.current<kr)){I=!0;try{const P=await rr([o],s.auth,s.baseUrl);if(y||P.ok===!1)return;const O=(D=P.frames)==null?void 0:D.find($e=>$e.deviceId===o),X=await bn(m.current??void 0,o,O?Or(O):void 0,s.baseUrl,l.current,b.current,k.current),he=X.painted?1:0,tt=X.staleDropped?1:0;X.staleDropped&&g.emit("remoteControl.node.frameStaleDropped",{nodeId:e.id,deviceId:o,frameSeq:X.frameSeq,previous:X.previous,source:"snapshot"}),g.emit("remoteControl.node.frameSnapshot",{nodeId:e.id,deviceId:o,frameCount:O?1:0,painted:he,staleDropped:tt})}catch{}finally{I=!1}}},U=window.setTimeout(N,250),z=window.setInterval(N,2500);return()=>{y=!0,window.clearTimeout(U),window.clearInterval(z)}},[A==null?void 0:A.connected,o,e.id,s.auth,s.baseUrl,s.source,r]),p.useEffect(()=>{!B||te||(pe(!1),h("unavailable"),L("Remote input unavailable."),g.emit("remoteControl.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"control-unavailable",deviceId:o}))},[te,o,B,e.id]),p.useEffect(()=>{var N,U,z;if(!B){(N=x.current)==null||N.close(),x.current=null,h("locked");return}if(!te||!o){h("unavailable"),L("Remote input unavailable.");return}let y=!1,I=null;h("connecting"),L("Connecting remote input adapter...");try{I=new WebSocket(Mr(s.baseUrl,Q,(z=(U=s.bridge)==null?void 0:U.status)==null?void 0:z.bridgeToken)),x.current=I}catch(D){h("error");const P=D instanceof Error?D.message:String(D);L(P),g.emit("remoteControl.node.input.ws",{nodeId:e.id,ok:!1,deviceId:o,error:P});return}return I.onopen=()=>{y||(h("ready"),L("Remote input ready."),g.emit("remoteControl.node.input.ws",{nodeId:e.id,ok:!0,deviceId:o}))},I.onmessage=D=>{if(y)return;const P=hr(String(D.data||"{}"));if(P){if(P.type==="RemoteInputSocketReady"){h("ready");return}g.emit("remoteControl.node.input.result",{nodeId:e.id,ok:P.ok,deviceId:P.deviceId||o,inputType:P.inputType,error:P.error}),!P.ok||P.error?L(P.error||"Remote input failed."):/^pointermove$/i.test(P.inputType)||L(`${P.inputType||"Input"} queued.`)}},I.onerror=()=>{y||(h("error"),L("Remote input socket error."),g.emit("remoteControl.node.input.ws",{nodeId:e.id,ok:!1,deviceId:o,reason:"socket-error"}))},I.onclose=()=>{y||(x.current=null,h("error"),L("Remote input socket closed."),g.emit("remoteControl.node.input.ws",{nodeId:e.id,ok:!1,deviceId:o,reason:"socket-closed"}))},()=>{y=!0,x.current===I&&(x.current=null),I==null||I.close()}},[te,o,B,e.id,Q,s.baseUrl,(ht=(me=s.bridge)==null?void 0:me.status)==null?void 0:ht.bridgeToken]),p.useEffect(()=>{if(!B)return;const y=I=>{I.key==="Escape"&&(I.preventDefault(),pe(!1),L("Remote input locked."),g.emit("remoteControl.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"escape",deviceId:o}))};return window.addEventListener("keydown",y,!0),()=>window.removeEventListener("keydown",y,!0)},[o,B,e.id]);const de=p.useCallback(y=>{var O;const I=x.current;if(!B||!te||!o||(I==null?void 0:I.readyState)!==WebSocket.OPEN){y.ack&&L(B?"Remote input socket is not ready.":"Remote input locked.");return}const N=`remote-control-input-${Date.now()}-${++v.current}`,{ack:U,...z}=y,D=mr({requestId:N,deviceId:o,ack:U,controlLeaseId:(O=s.hub)==null?void 0:O.hostTargetLeaseId,input:z});if(!D){U&&L("Remote input payload is invalid.");return}const P=w(D.input.type);try{I.send(JSON.stringify(D));const X=++V.current;(D.ack||X%24===1)&&g.emit("remoteControl.node.input.sent",{nodeId:e.id,deviceId:o,inputType:P,sampled:!D.ack,sent:X})}catch(X){h("error"),L(X instanceof Error?X.message:String(X))}},[te,o,B,e.id,(et=s.hub)==null?void 0:et.hostTargetLeaseId]),Re=p.useCallback((y,I,N,U=!1)=>{const z=So(y,U);return z?(de({type:I,...z,button:Pr(y.button),ack:N}),!0):!1},[de]),eo=p.useCallback(y=>{if(!(!B||!Re(y,"pointerDown",!0,!1))){y.preventDefault(),y.stopPropagation(),y.currentTarget.focus();try{y.currentTarget.setPointerCapture(y.pointerId)}catch{}}},[Re,B]),Je=p.useCallback(y=>{var z,D;if(!B)return;const I=performance.now();if(I-Z.current<Tr)return;Z.current=I;const N=((D=(z=y.currentTarget).hasPointerCapture)==null?void 0:D.call(z,y.pointerId))===!0;Re(y,"pointerMove",!1,N)&&(y.preventDefault(),y.stopPropagation())},[Re,B]),to=p.useCallback(y=>{if(B){y.preventDefault(),y.stopPropagation();try{y.currentTarget.releasePointerCapture(y.pointerId)}catch{}Re(y,"pointerUp",!0,!0)}},[Re,B]),Oo=p.useCallback(y=>{if(!B)return;const I=So(y,!1);I&&(de({type:"wheel",...I,deltaX:y.deltaX,deltaY:y.deltaY,ack:!0}),y.preventDefault(),y.stopPropagation())},[B,de]),Ue=p.useCallback(y=>{!B||y.key==="Escape"||(y.preventDefault(),y.stopPropagation(),de({type:"keyDown",key:y.key,code:y.code,repeat:y.repeat,ack:!0}))},[B,de]),kt=p.useCallback(y=>{!B||y.key==="Escape"||(y.preventDefault(),y.stopPropagation(),de({type:"keyUp",key:y.key,code:y.code,repeat:!1,ack:!0}))},[B,de]),Ze=p.useCallback(y=>{y.stopPropagation(),tr(!0),Se("hosted-access-enabled")},[Se]),He=p.useCallback(y=>{if(y.stopPropagation(),B){pe(!1),L("Remote input locked."),g.emit("remoteControl.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"manual",deviceId:o});return}if(!te){h("unavailable"),L("Remote input unavailable."),g.emit("remoteControl.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"unavailable",deviceId:o});return}pe(!0),L("Connecting remote input adapter..."),g.emit("remoteControl.node.input.lock",{nodeId:e.id,unlocked:!0,reason:"manual",deviceId:o})},[te,o,B,e.id]),_o=p.useCallback(y=>{y.stopPropagation(),Se("manual")},[Se]),ze=p.useCallback(async y=>{var z;if(y.preventDefault(),y.stopPropagation(),s.source!=="bridge"){be("LocalBridge is not connected.");return}const I=Y.trim();if(!I){be("Remote task is empty.");return}if(!o||(A==null?void 0:A.connected)!==!0||!ne){be("This device cannot accept remote tasks.");return}const N="task-only",U=((z=I.split(/\r?\n/)[0])==null?void 0:z.slice(0,96))||"Remote task";Pe(!0),be("Queueing device task...");try{const D=await ir(o,{instruction:I,title:U,approvalLevel:N},s.auth,s.baseUrl),P=D.ok===!0;be(P?"Queued remote task.":D.error||"Remote task queue failed."),g.emit("remoteControl.node.task.queue",{nodeId:e.id,ok:P,deviceId:o,approvalLevel:N,queued:P?1:0,taskId:D.taskId||"",commandId:D.commandId||"",error:D.error||""}),P&&(Oe(""),await Se("task-queued"))}catch(D){const P=D instanceof Error?D.message:String(D);be(P),g.emit("remoteControl.node.task.queue",{nodeId:e.id,ok:!1,deviceId:o,approvalLevel:N,queued:0,error:P})}finally{Pe(!1)}},[ne,A==null?void 0:A.connected,o,e.id,Se,s.auth,s.baseUrl,s.source,Y]);return a.jsxs("div",{ref:n,className:"node-remote-control","data-testid":"remote-control-node","data-remote-source":s.source,"data-remote-transport-visible":r?"true":"false","data-remote-frame-subscription-active":r&&s.source==="bridge"&&(A==null?void 0:A.connected)===!0?"true":"false",onPointerDown:y=>y.stopPropagation(),children:[a.jsxs("div",{className:"node-remote-control__bar",children:[a.jsx("strong",{title:xe,children:xe}),a.jsx("span",{children:Fe}),a.jsx("button",{type:"button",title:"Refresh remote device",onClick:_o,children:a.jsx(vo,{size:12,className:s.loading?"spin-icon":""})}),s.source==="blocked"?a.jsxs("button",{type:"button",onClick:Ze,children:[a.jsx(ko,{size:12}),"Enable"]}):a.jsxs("button",{type:"button",disabled:!te&&!B,onClick:He,children:[B?a.jsx(Da,{size:12}):a.jsx(Oa,{size:12}),B?"Lock":"Unlock"]})]}),a.jsxs("div",{className:`node-remote-control__screen ${B&&te?"is-input-active":""}`,tabIndex:B&&te?0:-1,onPointerDown:eo,onPointerMove:Je,onPointerUp:to,onWheel:Oo,onKeyDown:Ue,onKeyUp:kt,children:[a.jsx("canvas",{ref:m}),B&&te&&a.jsxs("em",{children:[a.jsx(_a,{size:11}),"input"]})]}),a.jsxs("form",{className:"node-remote-control__taskbar","data-testid":"remote-control-node-taskbar",onSubmit:ze,children:[a.jsx("input",{"aria-label":"Remote control task",value:Y,maxLength:1200,onChange:y=>Oe(y.target.value),onPointerDown:y=>y.stopPropagation(),placeholder:ne?`Task for ${xe}`:"Task unavailable"}),a.jsxs("button",{type:"submit",disabled:!jt,title:jt?"Queue task for this device":"This device cannot accept remote tasks",children:[a.jsx(nn,{size:12,className:W?"spin-icon":""}),"Queue"]})]}),a.jsxs("div",{className:"node-remote-control__footer",children:[a.jsxs("span",{children:["DEVICE ",a.jsx("strong",{children:o||"missing"})]}),a.jsxs("span",{children:["STATE ",a.jsx("strong",{children:(A==null?void 0:A.connected)===!0?"online":"offline"})]}),a.jsxs("span",{children:["INPUT ",a.jsx("strong",{children:ae})]}),a.jsxs("span",{children:["TASK ",a.jsx("strong",{children:ne?"ready":"off"})]}),a.jsxs("span",{children:["ROUTE ",a.jsx("strong",{children:s.source==="bridge"?"Local":s.source==="blocked"?"Gated":"Preview"})]})]}),a.jsx("p",{className:"node-remote-control__message",children:Do})]})}function Rr(e){var t,o,n;return w(((t=e.metadata)==null?void 0:t.RemoteFleetDeviceId)||((o=e.metadata)==null?void 0:o.RemoteSelectedDeviceId)||((n=e.metadata)==null?void 0:n.DeviceId)).trim()}function St(e){var n,r,s,c,m,l,b,k,x,v,V,M,F;const t=new Date().toISOString();return{deviceId:Rr(e)||"remote-control-preview",deviceName:((n=e.metadata)==null?void 0:n.RemoteFleetDeviceName)||e.title||"Remote device",platform:((r=e.metadata)==null?void 0:r.RemoteFleetDevicePlatform)||"unknown",arch:((s=e.metadata)==null?void 0:s.RemoteFleetDeviceArch)||"",connected:/^(1|true|yes|online)$/i.test(((c=e.metadata)==null?void 0:c.RemoteFleetDeviceConnected)||""),lastSeenAt:t,capabilities:{control:/^(1|true|yes|on)$/i.test(((m=e.metadata)==null?void 0:m.RemoteFleetDeviceCanControl)||""),taskDispatch:/^(1|true|yes|on)$/i.test(((l=e.metadata)==null?void 0:l.RemoteFleetDeviceCanDispatchTask)||"")},latestLiveFrame:(b=e.metadata)!=null&&b.RemoteFleetLatestFramePath||(k=e.metadata)!=null&&k.RemoteFleetLatestFrameUrl||(x=e.metadata)!=null&&x.RemoteFleetLatestFrameDataUrl?{framePath:(v=e.metadata)==null?void 0:v.RemoteFleetLatestFramePath,frameUrl:(V=e.metadata)==null?void 0:V.RemoteFleetLatestFrameUrl,dataUrl:(M=e.metadata)==null?void 0:M.RemoteFleetLatestFrameDataUrl,frameSeq:fn((F=e.metadata)==null?void 0:F.RemoteFleetLatestFrameSeq,0)}:void 0}}function fn(e,t){const o=Number(e);return Number.isFinite(o)&&o>=0?o:t}function w(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):""}function ye(e,t){const o=Number(e);return Number.isFinite(o)?o:t}function ce(e,t){var n;const o=(n=e.capabilities)==null?void 0:n[t];return typeof o=="boolean"?o:typeof o=="number"?o!==0:typeof o=="string"?/^(1|true|yes|on)$/i.test(o):!1}function Mr(e,t,o){const n=e.replace(/^http:/i,"ws:").replace(/^https:/i,"wss:").replace(/\/+$/,""),r=t||"/api/remote/input/ws",s=new URLSearchParams;o&&s.set("token",o);const c=s.toString();return c?`${n}${r}?${c}`:`${n}${r}`}function Pr(e){return e===2?"right":e===1?"middle":"left"}function So(e,t=!1){const o=Gl(e.currentTarget);if(!o)return null;const n=o.getBoundingClientRect();if(n.width<=0||n.height<=0)return null;const r=Zt.get(o)??{left:0,top:0,width:n.width,height:n.height};return Cl(e,n,r,t)}function Gl(e){return e instanceof HTMLCanvasElement?e:e.querySelector("canvas")}function Ra(e){return e.split(",").map(t=>t.trim()).filter(Boolean)}function Ar(e,t,o,n){const r=e.replace(/^http:/i,"ws:").replace(/^https:/i,"wss:").replace(/\/+$/,""),s=t||"/api/remote/frames/ws",c=new URLSearchParams;o&&c.set("token",o),n.length>0&&c.set("devices",n.join(","));const m=c.toString();return m?`${r}${s}?${m}`:`${r}${s}`}function Er(e){switch(e){case"ready":return"ready";case"connecting":return"connecting";case"unavailable":return"unavailable";case"error":return"error";default:return"locked"}}function bo(e,t){const o=new Date().toISOString(),n=Math.max(12,Math.min(El,Math.floor(e||Me)));return Array.from({length:n},(r,s)=>({deviceId:`remote-node-preview-${s+1}`,deviceName:`Remote ${String(s+1).padStart(2,"0")}`,platform:s%4===0?"linux":"win32",arch:"x64",connected:s<t,lastSeenAt:o,capabilities:{control:!1}}))}function tn(e){if(typeof window>"u")return!1;try{const t=window.localStorage.getItem(hn);if(String(t||"").trim().toLowerCase()!=="true")return!1;const o=String(window.localStorage.getItem(gn)||"").trim(),n=String(e||"").trim();return!o||o===n}catch{return!1}}function Ma(e,t){if(!(typeof window>"u"))try{t?(window.localStorage.setItem(hn,"true"),window.localStorage.setItem(gn,String(e||"").trim())):(window.localStorage.removeItem(hn),window.localStorage.removeItem(gn))}catch{}}function Ul({source:e,hub:t,baseUrl:o,hubLabel:n,routeLabel:r,connected:s,total:c,taskCount:m,taskDispatchCount:l,aiCount:b,pageLabel:k,pageStart:x,pageIndex:v,pageCount:V,projectionMode:M,projectedCount:F,visibleBudget:J,selectedDeviceId:Z,inputLabel:E,devices:ue,latestTaskBatch:B,recentTaskBatches:pe,taskFollowActive:Ce,taskFollowKey:h,isHostActiveForNode:ee,registryRouteInfo:L,hostTargetRenewMs:Y,autoHostEnabled:Oe,agent:W,agentStatusLabel:Pe,agentRunning:_e,agentReady:be,message:A}){const xe=An(t),Fe=ee?"hosting":(t==null?void 0:t.hostTargetActive)===!0?"other-monitor":"inactive",S=Vl(ue);return{SemanticType:"RemoteFleetMonitor",RemoteFleetSchemaVersion:"remote-fleet@1",RemoteFleetViewMode:"all-devices",RemoteFleetLastRefreshAtUtc:new Date().toISOString(),RemoteFleetHubStatus:(t==null?void 0:t.started)===!0?"online":e==="blocked"?"gated":e==="bridge"?"ready":e,RemoteFleetHubEndpoint:xe,RemoteFleetManagerPackage:w(t==null?void 0:t.managerPackage)||"@mindexec/cli",RemoteFleetManagerVersion:w(t==null?void 0:t.managerVersion),RemoteFleetAgentPackage:w(t==null?void 0:t.agentPackage)||"@mindexec/remote",RemoteFleetPairTokenPreview:w(t==null?void 0:t.pairTokenPreview)||"<pair-token>",RemoteFleetConnectCommand:jr(t),RemoteFleetDeviceCount:String(c),RemoteFleetConnectedDeviceCount:String(s),RemoteFleetDevicesJson:JSON.stringify(S),RemoteFleetLatestTaskBatchJson:B?JSON.stringify(Pa(B)):"",RemoteFleetRecentTaskBatchesJson:JSON.stringify((pe??[]).slice(0,6).map(Pa)),RemoteFleetTaskFollowActive:String(Ce),RemoteFleetTaskFollowKey:h,RemoteFleetTaskFollowRefreshMs:String(Ce?Io:0),RemoteFleetTaskFollowMaxTicks:String(Rt),RemoteFleetProjectionMode:M,RemoteFleetProjectedDeviceCount:String(F),RemoteFleetCanvasPagination:`${M}:${v+1}/${V}`,RemoteFleetHostTargetState:Fe,RemoteFleetHostTargetNodeId:w(t==null?void 0:t.hostTargetNodeId),RemoteFleetHostTargetLeaseId:w(t==null?void 0:t.hostTargetLeaseId),RemoteFleetRegistryStatus:L.status,RemoteFleetRegistryReason:L.reason,RemoteFleetAccountRouteReady:String(L.accountRouteReady),RemoteFleetRegistryMigrationBlocked:String(L.migrationBlocked),RemoteFleetHostTargetRenewMs:String(Y),RemoteFleetAutoHost:String(Oe),RemoteFleetHostTargetEndpoint:w(t==null?void 0:t.hostTargetEndpoint)||xe,RemoteFleetHostTargetActivatedAtUtc:w(t==null?void 0:t.hostTargetActivatedAt),RemoteFleetHostTargetUpdatedAtUtc:w(t==null?void 0:t.hostTargetUpdatedAt),RemoteFleetHostTargetExpiresAtUtc:w(t==null?void 0:t.hostTargetExpiresAt),RemoteAgentStatus:Pe,RemoteAgentRunning:String(_e),RemoteAgentReady:String(be),RemoteAgentManager:w(W==null?void 0:W.manager),RemoteAgentLeaseId:w(W==null?void 0:W.leaseId),RemoteAgentNodeId:w(W==null?void 0:W.nodeId),RemoteAgentUpdatedAtUtc:w(W==null?void 0:W.updatedAt),RemoteAgentLastError:w((W==null?void 0:W.lastError)||(W==null?void 0:W.reconnectReason)),RemoteFleetLastError:e==="bridge"?w(t==null?void 0:t.lastError):A,RemoteHub:n,RemoteRoute:r,RemoteRegistryRoute:L.status,RemoteRegistryReason:L.reason,RemoteConnected:String(s),RemoteTotal:String(c),RemoteProjected:String(F),RemoteProjection:M,RemotePage:k,RemotePageStart:String(x),RemoteVisibleBudget:String(J),RemoteSelectedDeviceId:Z,RemoteInput:E,RemoteTasksQueued:String(m),RemoteTaskDevices:String(l),RemoteAiDevices:String(b),RemoteBaseUrl:o,AdapterState:e==="bridge"?"localbridge-connected":e==="blocked"?"adapter-gated":e}}function zl(e,t){const o=w(e==null?void 0:e.agentEndpointRouteReason).trim(),n=(e==null?void 0:e.agentEndpointAccountRouteReady)===!0,r=Lr(o);return(t?"account":(e==null?void 0:e.hostTargetActive)===!0?"other-monitor":"idle")==="other-monitor"?{status:"other-monitor",value:"Other",tone:"default",reason:o,accountRouteReady:n,migrationBlocked:r,title:o||"Another monitor currently owns the host route."}:t?n?{status:"account",value:"Account",tone:"online",reason:o||"ok",accountRouteReady:!0,migrationBlocked:!1,title:"Published to the account route registry for same-account agent pairing."}:$l(o)?{status:"blocked",value:"Blocked",tone:"warn",reason:o,accountRouteReady:!1,migrationBlocked:r,title:r?"Account route registry needs the Supabase remote_host_targets migration.":o||"The local host is active, but account route publishing failed."}:{status:"local",value:"Local",tone:"warn",reason:o,accountRouteReady:!1,migrationBlocked:r,title:o||"The local host is active, but account route publishing is not available."}:{status:"idle",value:"Idle",tone:"default",reason:o,accountRouteReady:n,migrationBlocked:r,title:o||"No active host route."}}function Lr(e){return/registry-table-unavailable|PGRST20[25]|remote_host_targets|set_remote_host_target|clear_remote_host_target/i.test(String(e||""))}function $l(e){return Lr(e)||/invalid-manager-endpoint|blocked|failed|error|unavailable|unauthori[sz]ed|forbidden/i.test(String(e||""))}function An(e){const t=w(e==null?void 0:e.agentEndpoint).trim();if(t)return t;const o=w((e==null?void 0:e.agentHost)||(e==null?void 0:e.host)).trim()||"127.0.0.1",n=Number((e==null?void 0:e.port)||5197);return`${o}:${Number.isFinite(n)&&n>0?n:5197}`}function jr(e){const t=An(e),o=w(e==null?void 0:e.pairTokenPreview).trim()||"<pair-token>";return`npx @mindexec/remote connect --manager ${t} --pair ${o}`}function Vl(e){return e.filter(t=>t.connected===!0).map(t=>{var r,s,c,m,l,b,k,x,v,V,M;const o=qt(t),n=t.latestTask;return{deviceId:it(t),sessionId:w(t.sessionId),name:ft(t),hostname:w(t.hostname),platform:Kt(t),arch:w(t.arch),agentVersion:w(t.agentVersion),connected:t.connected===!0,lastSeenAt:w(t.lastSeenAt),lastStatusAt:w(t.lastStatusAt),computerAgentEnabled:ce(t,"taskDispatch"),controlEnabled:ce(t,"control"),thumbnailEnabled:ce(t,"thumbnail")||ce(t,"screen"),liveStreamEnabled:ce(t,"liveStream"),aiAssistEnabled:ce(t,"aiAssist"),aiModel:w((r=t.capabilities)==null?void 0:r.aiModel),aiProvider:w((s=t.capabilities)==null?void 0:s.aiProvider),thumbnailFrameUrl:w(((c=t.latestThumbnail)==null?void 0:c.frameUrl)||((m=t.latestThumbnail)==null?void 0:m.framePath)),liveFrameUrl:w(((l=t.latestLiveFrame)==null?void 0:l.frameUrl)||((b=t.latestLiveFrame)==null?void 0:b.framePath)),latestFrameSeq:pt(o),liveStreamActive:((k=t.activeLiveStream)==null?void 0:k.active)===!0,liveStreamId:w((x=t.activeLiveStream)==null?void 0:x.streamId),liveStreamFps:ye((v=t.activeLiveStream)==null?void 0:v.fps,0),latestTaskBatchId:w(n==null?void 0:n.batchId),latestTaskId:w(n==null?void 0:n.taskId),latestTaskStatus:w(n==null?void 0:n.status),latestTaskApprovalLevel:w(n==null?void 0:n.approvalLevel),latestTaskResultModel:w(n==null?void 0:n.resultModel),latestTaskResultResponseId:w(n==null?void 0:n.resultResponseId),latestTaskResultSummary:w(n==null?void 0:n.resultSummary),tasksQueued:ye((V=t.counters)==null?void 0:V.tasksQueued,0),taskResultsReceived:ye((M=t.counters)==null?void 0:M.taskResultsReceived,0)}})}function Pa(e){return{batchId:w(e.batchId),title:w(e.title),instructionPreview:w(e.instructionPreview),approvalLevel:w(e.approvalLevel),status:w(e.status),requestedAt:w(e.requestedAt),updatedAt:w(e.updatedAt),total:ye(e.total,0),queued:ye(e.queued,0),pending:ye(e.pending,0),completed:ye(e.completed,0),failed:ye(e.failed,0),timedOut:ye(e.timedOut,0)}}function ql(e,t){return Aa(e)?e:(t??[]).find(Aa)}function Wl(e){if(!e)return"";const t=w(e.batchId).trim();return t||[w(e.title).trim(),w(e.requestedAt).trim(),w(e.updatedAt).trim(),String(ye(e.total,0)||"")].filter(Boolean).join(":")}function Aa(e){if(!e)return!1;const t=w(e.status).trim().toLocaleLowerCase(),o=ye(e.pending,0),n=ye(e.total,0),r=ye(e.completed,0),s=ye(e.failed,0),c=ye(e.timedOut,0);return["completed","completed-with-failures","failed","cancelled","canceled","done"].includes(t)?!1:o>0||["running","queued","pending","targeted","dispatching","in-progress"].includes(t)?!0:n>0&&r+s+c<n}function Hl(e,t){const o=Kl(e);return{manager:o[0]||"",managerCandidates:o,pairToken:w(e==null?void 0:e.pairToken).trim(),leaseId:w(e==null?void 0:e.hostTargetLeaseId).trim(),nodeId:t,engine:"auto",source:"react-remote-monitor"}}function Kl(e){const t=Array.isArray(e==null?void 0:e.agentEndpointCandidateDetails)?e.agentEndpointCandidateDetails:[],o=[e==null?void 0:e.hostTargetEndpoint,...Array.isArray(e==null?void 0:e.hostTargetEndpointCandidates)?e.hostTargetEndpointCandidates:[],e==null?void 0:e.agentEndpoint,...Array.isArray(e==null?void 0:e.agentEndpointCandidates)?e.agentEndpointCandidates:[],...t.map(s=>s.endpoint||s.address),An(e)],n=new Set,r=[];for(const s of o){const c=Xl(s),m=c.toLowerCase();if(!(!c||n.has(m))&&(n.add(m),r.push(c),r.length>=12))break}return r}function Xl(e){const t=w(e).trim(),o=t.match(/^(\[[^\]]+\]|[^:\s]+):(\d{1,5})$/);if(!o)return"";const n=Number(o[2]);return!Number.isInteger(n)||n<=0||n>65535?"":t}function Yl(e,t){if(t==="blocked")return"gated";if(t!=="bridge")return t;if(!e)return"unknown";const o=w(e.status).trim().toLowerCase();return Dr(e)?"ready":o||(Nr(e)?"running":"idle")}function Nr(e){const t=w(e==null?void 0:e.status).trim().toLowerCase();return(e==null?void 0:e.running)===!0||t==="running"||t==="starting"}function Dr(e){const t=w(e==null?void 0:e.status).trim().toLowerCase();return(e==null?void 0:e.ready)===!0||t==="ready"}function Ql({source:e,hasAuth:t,isHostActiveForNode:o,request:n,busy:r}){return r?"RemoteAgent action is already running.":e!=="bridge"?"LocalBridge is not connected.":t?o?"This monitor is already the active host target.":n.manager?n.pairToken?"":"RemoteAgent pair token is missing.":"RemoteAgent manager endpoint is missing.":"LocalBridge auth token is not available."}function it(e){return String(e.deviceId||e.sessionId||e.deviceName||"").trim()}function ft(e){return String(e.deviceName||e.hostname||it(e)||"Remote device").trim()}function Kt(e){var t;return String(((t=e.status)==null?void 0:t.platform)||e.platform||"unknown").trim()}function Jl(e){return Cr.includes(e)?e:"status"}function Zl(e){return xr.includes(e)?e:"connected"}function ec(e){return wr.includes(e)?e:"all"}function tc(e){switch(e){case"activity":return"Activity";case"platform":return"Platform";case"capability":return"Capability";default:return"Status"}}function oc(e){switch(e){case"all":return"All";case"offline":return"Offline";default:return"Live"}}function nc(e){switch(e){case"control":return"Control";case"task":return"Task";case"ai":return"AI";default:return"Any"}}function ac(e,t){switch(t){case"activity":return rc(e);case"platform":return Kt(e).toLocaleLowerCase()||"unknown";case"capability":return ic(e);default:return e.connected===!0?"online":"offline"}}function rc(e){var o,n,r,s;const t=w((o=e.latestTask)==null?void 0:o.status).toLocaleLowerCase();return t==="running"||t==="queued"?`task-${t}`:((n=e.activeLiveStream)==null?void 0:n.active)===!0?"live":Number(((r=e.counters)==null?void 0:r.liveFramesReceived)||0)>0?"live-recent":Number(((s=e.counters)==null?void 0:s.thumbnailFramesReceived)||0)>0?"thumbnail":e.lastStatusAt||e.lastSeenAt?"heartbeat":"idle"}function ic(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 qt(e){return e.latestLiveFrame||e.latestThumbnail}function En(e){return(e==null?void 0:e.dataUrl)||(e==null?void 0:e.frameUrl)||(e==null?void 0:e.framePath)||""}function Or(e){return e.live||e.thumbnail}function pt(e){const t=Number((e==null?void 0:e.frameSeq)||0);return Number.isFinite(t)&&t>0?t:0}function Ln(e,t,o){var n,r;return Math.max(e.get(o)||0,pt((n=t.get(o))==null?void 0:n.metadata),pt((r=Fr(o))==null?void 0:r.metadata))}function _r(e,t,o,n){e.has(t)&&e.delete(t);const r={metadata:{...o,deviceId:t},payload:n.slice(0),cachedAt:Date.now()};return e.set(t,r),Xt(e,mn),sc(t,r),r}function Xt(e,t,o=Number.POSITIVE_INFINITY){const n=Date.now();for(const[r,s]of e)(!s||!s.payload||Number.isFinite(o)&&n-s.cachedAt>o)&&e.delete(r);for(;e.size>t;){const r=e.keys().next().value;if(!r)break;e.delete(r)}}function sc(e,t){e&&(Mt.has(e)&&Mt.delete(e),Mt.set(e,{metadata:{...t.metadata,deviceId:e},payload:t.payload,cachedAt:t.cachedAt}),Xt(Mt,Ir,vr))}function Fr(e){return Xt(Mt,Ir,vr),Mt.get(e)}function Br(e,t){Xt(e,mn);const o=e.get(t);if(o)return{cached:o,scope:"local"};const n=Fr(t);return n?(e.set(t,n),Xt(e,mn),{cached:n,scope:"global"}):null}async function Ro(e,t,o,n){const r=w(t.metadata.deviceId).trim();if(!r||o.has(r))return!1;const s=pt(t.metadata),c=n.get(r)||0;if(s>0&&s<=c)return!1;o.add(r);try{const m=await jn(e,t.metadata,t.payload);return m&&s>0&&n.set(r,s),m}catch{return!1}finally{o.delete(r)}}function No(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(jl,Math.max(1,window.devicePixelRatio||1)),s=Math.round(o*r),c=Math.round(n*r),m=Math.abs(e.width-s),l=Math.abs(e.height-c);(e.width<=0||e.height<=0||m>Ca||l>Ca)&&(e.width=s,e.height=c);const k=e.getContext("2d",{alpha:!1});return k?(k.setTransform(r,0,0,r,0,0),{ctx:k,width:o,height:n}):null}function Mo(e,t,o){const n=No(e);if(!n)return;const{ctx:r,width:s,height:c}=n;Zt.set(e,{left:0,top:0,width:s,height:c});const m=t.connected===!0;r.fillStyle=m?"#ffffff":"#f8fafc",r.fillRect(0,0,s,c),r.strokeStyle=m?"#dbeafe":"#e2e8f0",r.lineWidth=1,r.strokeRect(.5,.5,s-1,c-1),r.fillStyle=m?"#bfdbfe":"#e2e8f0",r.fillRect(8,8,Math.max(12,s*.34),5),r.fillRect(8,18,Math.max(20,s*.52),5),r.fillStyle=o==="blocked"?"#94a3b8":"#cbd5e1",r.font="700 9px Inter, sans-serif",r.fillText(o==="bridge"?"waiting":o,8,c-8)}async function Gr(e,t,o){const n=t.startsWith("data:")?t:al(t,o);if(!n)return!1;const r=new Image;r.decoding="async",r.loading="eager",r.src=n,await r.decode();const s=No(e);if(!s)return!1;const{ctx:c,width:m,height:l}=s;return c.fillStyle="#020617",c.fillRect(0,0,m,l),Zt.set(e,Nn(c,r,m,l)),!0}async function jn(e,t,o){const n=new Blob([o],{type:t.mimeType||"image/jpeg"});let r=null;try{r=await createImageBitmap(n);const s=No(e);if(!s)return!1;const{ctx:c,width:m,height:l}=s;return c.fillStyle="#020617",c.fillRect(0,0,m,l),Zt.set(e,Nn(c,r,m,l)),!0}catch{return lc(e,t,n)}finally{r==null||r.close()}}async function lc(e,t,o){const n=URL.createObjectURL(o);try{const r=new Image;r.decoding="async",r.loading="eager",r.src=n,await r.decode();const s=No(e);if(!s)return!1;const{ctx:c,width:m,height:l}=s;return c.fillStyle="#020617",c.fillRect(0,0,m,l),Zt.set(e,Nn(c,r,m,l)),!0}catch{return g.emit("remoteMonitor.node.frameDecodeFailed",{deviceId:w(t.deviceId),frameSeq:Number(t.frameSeq||0)||0,mimeType:t.mimeType||"",byteLength:Number(t.byteLength||o.size||0)||0}),!1}finally{URL.revokeObjectURL(n)}}async function bn(e,t,o,n,r,s,c){const m=En(o),l={painted:!1,busy:!1,staleDropped:!1,frameSeq:0,previous:0};if(!e||!m)return l;if(r.has(t))return{...l,busy:!0};const b=Number((o==null?void 0:o.frameSeq)||0)||0,k=Ln(s,c,t);if(b>0&&b<=k||b<=0&&k>0)return{painted:!1,busy:!1,staleDropped:!0,frameSeq:b,previous:k};r.add(t);try{const x=await Gr(e,m,n);return x&&b>0&&s.set(t,b),{painted:x,busy:!1,staleDropped:!1,frameSeq:b,previous:k}}catch{return{painted:!1,busy:!1,staleDropped:!1,frameSeq:b,previous:k}}finally{r.delete(t)}}function Nn(e,t,o,n){const r="width"in t?Number(t.width):o,s="height"in t?Number(t.height):n,c=Math.min(o/Math.max(1,r),n/Math.max(1,s)),m=r*c,l=s*c,b=(o-m)/2,k=(n-l)/2;return e.drawImage(t,b,k,m,l),{left:b,top:k,width:m,height:l}}function nu({launchers:e,activeLauncher:t,template:o,selectedOptionId:n,values:r,validationMessage:s,canCreate:c,primaryLabel:m="Create board",onLauncherSelected:l,onOptionSelected:b,onInputChanged:k,onCreate:x,onClose:v}){const V=(o==null?void 0:o.inputs)??[];return a.jsx("div",{className:"template-launcher-backdrop","data-testid":"template-launcher-panel",onMouseDown:v,children:a.jsxs("section",{className:"template-launcher-panel floating-panel",onMouseDown:M=>M.stopPropagation(),children:[a.jsxs("header",{className:"template-launcher-head",children:[a.jsxs("div",{children:[a.jsx("span",{children:"Execution Canvas"}),a.jsx("strong",{children:t.label})]}),a.jsx("button",{type:"button",title:"Close template launcher",onClick:v,children:a.jsx(Po,{size:16})})]}),a.jsx("div",{className:"template-launcher-tabs","aria-label":"Template launchers",children:e.map(M=>a.jsxs("button",{type:"button",className:M.id===t.id?"is-active":"","data-testid":"template-launcher-tab","data-launcher-id":M.id,onClick:()=>l(M.id),children:[a.jsx(Ei,{size:14}),a.jsx("span",{children:M.label})]},M.id))}),a.jsx("p",{className:"template-launcher-description",children:t.description}),t.options.length>0&&a.jsxs("div",{className:"template-launcher-option-block",children:[a.jsx("div",{className:"template-launcher-prompt",children:t.prompt||"Choose the board to create."}),a.jsx("div",{className:"template-launcher-chips",children:t.options.map(M=>a.jsxs("button",{type:"button",className:n===M.id?"is-active":"","data-testid":"template-option","data-option-id":M.id,onClick:()=>b(M.id),children:[a.jsx("strong",{children:M.label}),a.jsx("span",{children:M.description})]},M.id))})]}),V.length>0&&a.jsx("div",{className:"template-launcher-form",children:V.map(M=>a.jsx(cc,{input:M,value:r[M.key]??"",onChange:F=>k(M.key,F)},M.key))}),s&&a.jsx("div",{className:"template-launcher-validation",children:s}),a.jsxs("footer",{className:"template-launcher-footer",children:[a.jsx("button",{type:"button",className:"template-launcher-secondary",onClick:v,children:"Cancel"}),a.jsxs("button",{type:"button",className:"template-launcher-primary","data-testid":"template-create",disabled:!c,onClick:x,children:[a.jsx(ja,{size:15}),a.jsx("span",{children:m})]})]})]})})}function cc({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 au({node:e,onSave:t,onClose:o}){var b,k,x,v,V,M;const[n,r]=p.useState(((b=e.metadata)==null?void 0:b.DirectoryPath)??e.sourceFilePath??""),[s,c]=p.useState(((k=e.metadata)==null?void 0:k.Include)??""),[m,l]=p.useState(((x=e.metadata)==null?void 0:x.Exclude)??"");return p.useEffect(()=>{var F,J,Z;r(((F=e.metadata)==null?void 0:F.DirectoryPath)??e.sourceFilePath??""),c(((J=e.metadata)==null?void 0:J.Include)??""),l(((Z=e.metadata)==null?void 0:Z.Exclude)??"")},[e.id,(v=e.metadata)==null?void 0:v.DirectoryPath,(V=e.metadata)==null?void 0:V.Exclude,(M=e.metadata)==null?void 0:M.Include,e.sourceFilePath]),a.jsx("div",{className:"directory-settings-backdrop","data-testid":"directory-settings-dialog",onMouseDown:o,children:a.jsxs("section",{className:"directory-settings-dialog","aria-label":"Folder scan settings","data-disable-mindcanvas-hotkeys":"true",onMouseDown:F=>F.stopPropagation(),children:[a.jsxs("header",{className:"directory-settings-head",children:[a.jsxs("div",{children:[a.jsxs("span",{children:[a.jsx(Li,{size:15}),"Folder scan settings"]}),a.jsx("strong",{title:e.sourceFilePath||e.title,children:e.title})]}),a.jsx("button",{type:"button",title:"Close folder scan settings","aria-label":"Close folder scan settings","data-testid":"directory-settings-close",onClick:o,children:a.jsx(Po,{size:16})})]}),a.jsxs("div",{className:"directory-settings-body",children:[a.jsxs("label",{className:"directory-setting-row",children:[a.jsxs("span",{children:[a.jsx(ji,{size:14}),"LocalBridge path"]}),a.jsx("input",{value:n,placeholder:"E:\\\\Dev@Work\\\\Project or relative/path","data-testid":"directory-settings-path",onChange:F=>r(F.target.value)})]}),a.jsxs("label",{className:"directory-setting-row",children:[a.jsxs("span",{children:[a.jsx(Ni,{size:14}),"Extensions to include"]}),a.jsx("input",{value:s,placeholder:".cs, .js, .razor, .css","data-testid":"directory-settings-include",onChange:F=>c(F.target.value)})]}),a.jsxs("label",{className:"directory-setting-row",children:[a.jsxs("span",{children:[a.jsx(Di,{size:14}),"Paths/files to exclude"]}),a.jsx("input",{value:m,placeholder:"bin, obj, .git, node_modules","data-testid":"directory-settings-exclude",onChange:F=>l(F.target.value)})]})]}),a.jsxs("footer",{className:"directory-settings-footer",children:[a.jsx("button",{type:"button","data-testid":"directory-settings-cancel",onClick:o,children:"Cancel"}),a.jsxs("button",{type:"button",className:"is-primary","data-testid":"directory-settings-save",onClick:()=>t(e.id,{DirectoryPath:n.trim(),Include:s.trim(),Exclude:m.trim()}),children:[a.jsx(Fa,{size:15}),"Save"]})]})]})})}const Dn=.001,dc=1,uc=5,pc=1.35,mc=1.3,hc=1.45,gc=.002,fc=.01,bc=.03,yc=.002,kc=.015,Tc=.05,Ic=5,vc=20,Cc=100,xc=2,Ea=2500,wc=800,Sc=1200,Rc=1800,Mc=2600,Pc={"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 Ac(e){const t=Gc(e.reasoningEffort);return e.mode==="Text"?Dc(e.provider,t,e.vendorPricing):e.mode==="Image"&&e.provider==="openai-codex"&&zc(e.modelId)?ct("Free",0,"Codex Responses image generation",void 0,"codex",!1):e.mode==="Image"?_c(e.vendorPricing):e.mode==="Video"?Fc(e.vendorPricing):Et("Unavailable")}function Ec(e){const t=e.settings.inputMode==="Image"||e.settings.inputMode==="Video"?e.settings.inputMode:"Text",o=Nc(e.settings,t);return Ac({mode:t,provider:jc(e.settings),modelId:o,reasoningEffort:e.settings.effort,vendorPricing:Lc(o)})}function Lc(e){const t=$c(e);return Pc[t]??null}function jc(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 Nc(e,t){return t==="Image"?rn("Image",e).id:t==="Video"?rn("Video",e).id:e.model}function Dc(e,t,o){switch(e){case"local-ollama":return ct("Free",0,"Local execution",void 0,"ollama",!1);case"byok":return ct("ServiceFeeOnly",xc,"BYOK platform fee",void 0,"byok",!1);case"openai-codex":return ct("Free",0,"Codex CLI local execution",void 0,"codex",!1);case"google-gemini-cli":return ct("Free",0,"Gemini CLI local execution",void 0,"gemini-cli",!1);case"managed-cloud":default:return Oc(t,o)}}function Oc(e,t){if(!bt(t==null?void 0:t.promptUsdPerToken)||!bt(t==null?void 0:t.completionUsdPerToken))return Et("Pricing unavailable");const o=Bc(e),n=((t==null?void 0:t.requestUsd)??0)+t.promptUsdPerToken*Ea+t.completionUsdPerToken*o,r=n*pc+gc+yc,s=On(Math.max(r/Dn,Ic),dc);return ct("FixedPoints",s,`Base run (${yn(Ea)} in / ${yn(o)} out)`,n,t.source,!0)}function _c(e){if(!e)return Et("Pricing unavailable");let t=e.averageUsd??e.maxUsd??e.minUsd;if(!bt(t))return Et("Pricing unavailable");bt(e.minUsd)&&(t=Math.max(t,e.minUsd*1.15));const o=t*mc+fc+kc,n=On(Math.max(o/Dn,vc),uc);return ct("FixedPoints",n,"Base image generation",t,e.source,!0)}function Fc(e){if(!e)return Et("Pricing unavailable");let t=0;if(bt(e.maxUsd)&&(t=Math.max(t,e.maxUsd)),bt(e.averageUsd)&&(t=Math.max(t,e.averageUsd*1.25)),bt(e.minUsd)&&(t=Math.max(t,e.minUsd)),t<=0)return Et("Pricing unavailable");const o=t*hc+bc+Tc,n=On(Math.max(o/Dn,Cc),10);return ct("FixedPoints",n,"Base video generation",t,e.source,!0)}function Bc(e){switch(e){case"low":return wc;case"high":return Rc;case"xhigh":return Mc;case"medium":default:return Sc}}function Gc(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 On(e,t){return t<=1?Math.ceil(e):Math.ceil(e/t)*t}function ct(e,t,o,n,r,s){return{billingKind:e,displayPoints:t,displayLabel:Uc(t),basisLabel:o,isEstimatedFromCatalog:s,vendorCostUsdSnapshot:n,vendorPricingSource:r}}function Et(e){return{billingKind:"Unavailable",displayPoints:0,displayLabel:e,basisLabel:"Pricing unavailable",isEstimatedFromCatalog:!1}}function Uc(e){return`${yn(e)}P`}function yn(e){return e.toLocaleString("en-US",{maximumFractionDigits:0})}function zc(e){return String(e??"").trim().toLowerCase().startsWith("codex-image:")}function $c(e){return String(e??"").trim()}function bt(e){return typeof e=="number"&&Number.isFinite(e)}const on=[{id:"frame",label:"Frame Perf",icon:Oi},{id:"render",label:"Render Debug",icon:_i},{id:"prompt",label:"Prompt Debug",icon:Fi},{id:"points",label:"Points",icon:Bi},{id:"dev",label:"Dev",icon:Gi}],yo=[{key:"frameProbe",label:"Frame profiler",description:"Tracks local React frame budget and viewport pressure.",defaultValue:!0},{key:"motionGuard",label:"Motion guard",description:"Highlights pan and zoom paths that must stay patch-only.",defaultValue:!0},{key:"overlayAudit",label:"Overlay debug",description:"Checks floating panels, popovers, and result overlays.",defaultValue:!0},{key:"bridgeGate",label:"LocalBridge gate monitor",description:"Keeps hosted loopback access explicit and visible.",defaultValue:!0},{key:"storageTrace",label:"Storage trace",description:"Surfaces local save and restore evidence for this board.",defaultValue:!0}],Vc=[{route:"/code",label:"CodeGraph",description:"Repository graph, agent commands, and code notes."},{route:"/planmaster",label:"PlanMaster",description:"Goal planning, step states, and execution memory."},{route:"/youtube",label:"YouTube Capture",description:"Local YouTube search flow and MindCanvas handoff."},{route:"/company-core",label:"CompanyCore",description:"Company cockpit, approvals, artifacts, and publishing jobs."},{route:"/admin/dashboard",label:"Admin Dashboard",description:"Billing, entitlement, refund, and audit shell."},{route:"/tools",label:"Free Tools",description:"Markdown, note, and clipboard mini workflows."}];function qc(e,t,o){const n=(0-t.x)/t.scale,r=(0-t.y)/t.scale,s=(o.width-t.x)/t.scale,c=(o.height-t.y)/t.scale;return e.nodes.filter(m=>{const l=m.x+m.width,b=m.y+m.height;return l>=n&&m.x<=s&&b>=r&&m.y<=c}).length}function Wc(e,t){const o=e.trim().split(/\s+/).filter(Boolean).length,n=Math.max(1,Math.ceil(o/120)),r=t==="Deep"?3:t==="Fast"?1:2;return{words:o,estimatedTokens:Math.max(8,Math.ceil(e.length/4)),points:n*r}}function Hc(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(`
|
|
43
|
+
基础风格:{{musicGenre}}`,"template.music-core.node.references.title":"参考","template.music-core.node.references.body":"列出参考曲和想借鉴的点。","template.music-core.node.vocals.title":"人声 / 乐器","template.music-core.node.vocals.body":"写下人声类型和核心乐器配置。","template.music-core.node.lyrics.title":"歌词","template.music-core.node.lyrics.body":"整理主题、重复钩子和禁用表达。","template.music-core.node.generationPrompt.title":"生成提示词","template.music-core.node.generationPrompt.body":"收集音色、结构和氛围指令。","template.music-core.node.versions.title":"版本比较","template.music-core.node.versions.body":"记录 mp3 结果和修改点。"}},Ie={studioNodeType:"studioNodeType",templateNodeId:"templateNodeId",templateRole:"templateRole",compileTarget:"compileTarget",inputKey:"inputKey",inputType:"inputType",inputDescription:"inputDescription",inputPlaceholder:"inputPlaceholder",inputDefaultValue:"inputDefaultValue",inputRequired:"inputRequired",inputOptions:"inputOptions"},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"}],Qc=["note","memo","markdown","aiPrompt","output","section","checklist","input"],q={contentType:"templateLauncher",semanticTypeKey:"semanticType",semanticTypeValue:"TemplateLauncher",launcherIdKey:"templateLauncherId",selectedOptionIdKey:"templateLauncherSelectedOptionId",cardVersionKey:"templateCardVersion",cardLockedKey:"templateCardLocked",controllerNodeIdKey:"sourceTemplateControllerNodeId",runIdKey:"sourceTemplateRunId",cardGeneratedKey:"sourceTemplateCardGenerated",localizationManagedKey:"templateLocalizationManaged",localizationLanguageKey:"templateLanguageCode",sourceInputValuesJsonKey:"sourceTemplateInputValuesJson",width:560,height:620,resultTopGap:90},ut=fs,ys=new Set(["en","ko","ja","zh"]);function yt(e){if(typeof e!="string")return"en";const t=e.trim().toLowerCase();return!t||t==="auto"?"en":ys.has(t)?t:"en"}function le(e,t="",o){const n=yt(o),r=ga[n],s=ga.en,c=r[e];if(c!==void 0)return c;const m=s[e];return n!=="ko"&&m!==void 0?m:t}function Qt(e,t){const o=Ye(e.id);return{...e,label:le(`launcher.${o}.title`,e.label,t),description:le(`launcher.${o}.desc`,e.description,t),prompt:le(`launcher.${o}.prompt`,e.prompt,t),options:e.options.map(n=>Ls(e.id,n,t))}}function Wt(e,t){const o=Ye(e.id);return{...e,boardTitle:le(`template.${o}.boardTitle`,e.boardTitle,t),inputs:e.inputs.map(n=>js(e.id,n,t)),nodes:e.nodes.map(n=>Ns(e.id,n,t))}}function Jc(e){return ut.launchers.map(t=>Qt(t,e))}function ks(e,t){const o=ut.launchers.find(n=>K(n.id,e));return o?Qt(o,t):null}function Eo(e,t){if(e.options.length!==0)return e.options.find(o=>K(o.id,t||""))??e.options[0]}function Ts(e,t,o){const n=Eo(e,t),r=(n==null?void 0:n.templateId)||e.quickCreateTemplateId||"",s=ut.templates.find(c=>K(c.id,r));return s?Wt(s,o):null}function Zc(e){const t={};for(const o of(e==null?void 0:e.inputs)??[])t[o.key]=Sn(o);return t}function ed(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 Is(e,t,o,n){const r=yt(n.appLanguage),s=Qt(e,r),c=Eo(s,t),m=Ts(s,c==null?void 0:c.id,r);return m?vs(s,c,m,o,n):null}function vs(e,t,o,n,r){const s=jo(o,n),c=Wa(e,t,s),m=new Date().toISOString(),l=Xa("template-board"),b=Pt(o.boardTitle,c).trim()||e.label,k=o.nodes.map((x,v)=>xs(x,e,t,o,c,l,v));return{launcher:e,option:t,template:o,board:{id:l,name:b,updatedAt:m,settings:r,source:{kind:"localStorage",loadedAt:m},nodes:k,edges:[]}}}function $a(e,t,o={},n){const r=yt(n),s=Qt(e,r),c=Ds(r),m=Us(s,t),l={launcherId:s.id,title:s.label,description:s.description,prompt:s.prompt,iconClass:s.iconClass,selectedOptionId:m??void 0,options:[],inputValues:{},generateLabel:c.generateLabel,noInputsLabel:c.noInputsLabel,generatingMessage:c.generatingMessage,generatedMessageFormat:c.generatedMessageFormat,generationFailedMessage:c.generationFailedMessage,requiredMessageFormat:c.requiredMessageFormat,actionLabel:c.generateLabel};if(s.options.length===0){const k=s.quickCreateTemplateId?ut.templates.find(x=>K(x.id,e.quickCreateTemplateId)):null;if(k){const x=Wt(k,r);l.options.push({id:"",label:s.label,description:s.description,templateId:x.id,inputs:cn(x.inputs)})}}else for(const k of s.options){const x=ut.templates.find(V=>K(V.id,k.templateId)),v=x?Wt(x,r):null;l.options.push({id:k.id,label:k.label,description:k.description,templateId:k.templateId,inputs:cn((v==null?void 0:v.inputs)??[])})}const b=l.options.find(k=>K(k.id,l.selectedOptionId))??l.options[0];return l.selectedOptionId=b==null?void 0:b.id,l.inputValues=Ha((b==null?void 0:b.inputs)??[],o),l}function td(e,t,o,n,r={},s){const c=yt(s),m=$a(e,t,r,c),l=m.options.find(k=>K(k.id,m.selectedOptionId)),b={[q.semanticTypeKey]:q.semanticTypeValue,[q.launcherIdKey]:e.id,[q.selectedOptionIdKey]:m.selectedOptionId??"",[q.cardVersionKey]:"1.0",[q.cardLockedKey]:"True",[q.localizationLanguageKey]:c,IsNew:"true"};return{id:Xa("template-card"),kind:"template-launcher",title:m.title,body:JSON.stringify(m),x:o,y:n,width:q.width,height:q.height,tags:["Template","Launcher",e.label,l==null?void 0:l.label].filter(k=>!!k),metadata:b,aiEnabled:!1}}function wn(e){var t;return e?e.kind==="template-launcher"?!0:K((t=e.metadata)==null?void 0:t[q.semanticTypeKey],q.semanticTypeValue):!1}function Va(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:cn(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 od(e,t){const o=e.options.find(n=>K(n.id,t))??e.options[0];return{...e,selectedOptionId:o==null?void 0:o.id,inputValues:Ha((o==null?void 0:o.inputs)??[],e.inputValues)}}function nd(e,t,o){return{...e,inputValues:{...e.inputValues,[t]:o}}}function ad(e){if(!e)return"Template card payload is unavailable.";const t=e.options.find(n=>K(n.id,e.selectedOptionId))??e.options[0];if(!t)return"Template card option is unavailable.";const o=t.inputs.find(n=>n.required&&!String(e.inputValues[n.key]||"").trim());return o?Gs(e.requiredMessageFormat||"{0} is required.",o.label):null}function rd(e,t,o,n,r=zs()){var Z;if(!wn(e))return null;const s=(Z=e.metadata)==null?void 0:Z[q.launcherIdKey],c=yt(n.appLanguage),m=s?ks(s,c):null;if(!m)return null;const l=Eo(m,t),b=Is(m,(l==null?void 0:l.id)??null,o,n);if(!b)return null;const k=jo(b.template,o),x=JSON.stringify(k),v=Math.min(...b.board.nodes.map(E=>E.x)),V=Math.min(...b.board.nodes.map(E=>E.y)),M=e.x,F=e.y+Math.max(e.height,q.height)+q.resultTopGap,J=b.board.nodes.map(E=>({...E,x:M+(E.x-v),y:F+(E.y-V),metadata:{...E.metadata??{},[q.controllerNodeIdKey]:e.id,[q.runIdKey]:r,[q.cardGeneratedKey]:"True",[q.localizationManagedKey]:"True",[q.localizationLanguageKey]:c,[q.sourceInputValuesJsonKey]:x}}));return{launcher:m,option:b.option,template:b.template,runId:r,nodes:J}}function id(e,t){const o=yt(t),n=new Map(e.map(c=>[c.id,c]));let r=!1;const s=e.map(c=>{const m=Os(c,o);if(m)return r=!0,m;const l=_s(c,n,o);return l?(r=!0,l):c});return{nodes:r?s:e,changed:r,language:o}}function sd(e){const t=String(e||"").trim()||"Template Studio Draft";return{templateId:Lo(t),templateTitle:t,category:"custom",boardTitle:t,version:"0.1.0",tier:"draft",status:"draft"}}function ld(e,t){const o=[],n=ws(e),r=t.filter(k=>!!ve(k,Ie.studioNodeType)).sort((k,x)=>k.y-x.y||k.x-x.x||k.id.localeCompare(x.id)),s=r.filter(k=>K(ve(k,Ie.studioNodeType),"template.input")),c=r.filter(k=>!K(ve(k,Ie.studioNodeType),"template.input")),m=Ss(s,o),l=Rs(c,o);r.length===0&&o.push({code:"studio.nodes.empty",message:"Add at least one Template Studio node before compiling."});const b={id:n.templateId,version:n.version,tier:n.tier,status:n.status,boardTitle:n.boardTitle,inputs:m,nodes:l};return Ms(b,o),{template:b,manifestJson:JSON.stringify(b,null,2),issues:o}}function Lo(e){return String(e||"").trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"template-studio-draft"}function Cs(e,t){switch(String(e||"").trim().toLowerCase()||qa(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?Ka(t.kind):"note"}}function qa(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 cd(e){const t=bs.find(o=>K(o.studioNodeType,e));return(t==null?void 0:t.shortLabel)??"Note"}function xs(e,t,o,n,r,s,c){const m={};for(const[b,k]of Object.entries(e.metadata??{}))m[b]=Pt(k,r);m.IsNew="true",m.sourceLauncherId=t.id,m.sourceTemplateId=n.id,m.sourceTemplateVersion=n.version,m.sourceTemplateNodeId=e.id,m.templateRole=m.templateRole||e.id,m.templateLauncher=t.id,m.templateId=n.id,m.templateVersion=n.version,m.templateNodeId=e.id,o!=null&&o.id&&(m.sourceOptionId=o.id,m.templateOption=o.id);const l=$s(e.contentType);return{id:`${s}-${e.id||c}`,kind:l,title:Pt(e.title,r),body:Pt(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 jo(e,t){const o={};for(const n of e.inputs){const r=String(t[n.key]??"").trim();o[n.key]=r||Sn(n)}return o}function Wa(e,t,o){const n=(t==null?void 0:t.label)||e.label,r=(t==null?void 0:t.description)||e.description,s={launcherId:e.id,launcherLabel:e.label,launcherDescription:e.description,optionId:(t==null?void 0:t.id)||"",optionLabel:n,optionDescription:r,selectionLabel:n,timestampShort:Vs(new Date)};for(const[c,m]of Object.entries(o))s[c]=m;return s}function Pt(e,t){let o=e||"";for(const[n,r]of Object.entries(t))o=o.replace(new RegExp(`{{\\s*${qs(n)}\\s*}}`,"gi"),r);return o}function Sn(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:Lo(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 Ss(e,t){const o=[],n=new Set;for(const r of e){const s=r.title.trim()||"Input",c=Lo(ve(r,Ie.inputKey)||s),m=c.toLowerCase();if(n.has(m)){t.push({code:"studio.input.duplicate",message:`Template Studio input '${c}' is duplicated.`});continue}n.add(m),o.push({key:c,type:Ps(ve(r,Ie.inputType)),label:s,description:ve(r,Ie.inputDescription)||r.body,placeholder:ve(r,Ie.inputPlaceholder),defaultValue:ve(r,Ie.inputDefaultValue),required:As(ve(r,Ie.inputRequired)),options:Es(ve(r,Ie.inputOptions))})}return o}function Rs(e,t){const o=[],n=new Set;for(const r of e){const s=ve(r,Ie.studioNodeType)||qa(r);let c=Lo(ve(r,Ie.templateNodeId)||r.title);const m=c.toLowerCase();if(n.has(m)){t.push({code:"studio.node.duplicate",message:`Template Studio node '${c}' is duplicated.`});continue}n.add(m);const l=ve(r,Ie.compileTarget)||Cs(s,r),b=ve(r,Ie.templateRole)||s.replace(/^template\./i,"");o.push({id:c,contentType:l,title:r.title.trim(),body:r.body,x:Math.round(r.x),y:Math.round(r.y),width:Math.max(180,Math.round(r.width||340)),height:Math.max(120,Math.round(r.height||220)),metadata:{templateRole:b,studioNodeType:s,compileTarget:l,studioSourceContentType:Ka(r.kind)}})}return o}function Ms(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 Ps(e){const t=e.trim().toLowerCase();return t==="textarea"||t==="select"?t:"text"}function As(e){return e.trim().toLowerCase()==="true"}function Es(e){const t=[];for(const o of e.split(/\r?\n/)){const n=o.trim();if(!n)continue;const[r,s]=n.split("|",2).map(c=>c.trim());r&&t.push({value:r,label:s||r})}return t}function Ls(e,t,o){const n=Ye(e),r=Ye(t.id);return{...t,label:le(`launcher.${n}.option.${r}.title`,t.label,o),description:le(`launcher.${n}.option.${r}.desc`,t.description,o)}}function js(e,t,o){var s;const n=Ye(e),r=Ye(t.key);return{...t,label:le(`template.${n}.input.${r}.label`,t.label,o),description:le(`template.${n}.input.${r}.desc`,t.description,o),placeholder:le(`template.${n}.input.${r}.placeholder`,t.placeholder,o),options:(s=t.options)==null?void 0:s.map(c=>({...c,label:le(`template.${n}.input.${r}.option.${Ye(c.value)}`,c.label,o)}))}}function Ns(e,t,o){const n=Ye(e),r=Ye(t.id);return{...t,title:le(`template.${n}.node.${r}.title`,t.title,o),body:le(`template.${n}.node.${r}.body`,t.body,o),metadata:{...t.metadata??{}}}}function Ds(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 Os(e,t){var m,l,b,k;if(!wn(e))return null;const o=Va(e.body),n=((m=e.metadata)==null?void 0:m[q.launcherIdKey])||(o==null?void 0:o.launcherId),r=n?ut.launchers.find(x=>K(x.id,n)):null;if(!r)return null;const s=(o==null?void 0:o.selectedOptionId)||((l=e.metadata)==null?void 0:l[q.selectedOptionIdKey])||null,c=$a(r,s,(o==null?void 0:o.inputValues)??{},t);return e.title===c.title&&e.body===JSON.stringify(c)&&((b=e.metadata)==null?void 0:b[q.localizationLanguageKey])===t?null:{...e,title:c.title,body:JSON.stringify(c),tags:["Template","Launcher",c.title,(k=c.options.find(x=>x.id===c.selectedOptionId))==null?void 0:k.label].filter(x=>!!x),metadata:{...e.metadata??{},[q.launcherIdKey]:r.id,[q.selectedOptionIdKey]:c.selectedOptionId??"",[q.localizationLanguageKey]:t}}}function _s(e,t,o){if(wn(e))return null;const n=go(Be(e,"sourceTemplateId"),Be(e,"templateId")),r=go(Be(e,"sourceTemplateNodeId"),Be(e,"templateNodeId")),s=go(Be(e,"sourceLauncherId"),Be(e,"templateLauncher"));if(!n||!r||!s)return null;const c=ut.launchers.find(Z=>K(Z.id,s)),m=ut.templates.find(Z=>K(Z.id,n));if(!c||!m)return null;const l=go(Be(e,"sourceOptionId"),Be(e,"templateOption")),b=Fs(e,t),k=jo(Wt(m,o),b),x=Qo(c,m,r,l,k,"ko"),v=yt(Be(e,q.localizationLanguageKey)||"ko"),V=Qo(c,m,r,l,k,v),M=Qo(c,m,r,l,k,o);if(!x||!V||!M)return null;const F=e.title===x.title||e.title===V.title,J=e.body===x.body||e.body===V.body;return!F&&!J?null:{...e,title:F?M.title:e.title,body:J?M.body:e.body,tags:["Template",M.launcherLabel,M.optionLabel].filter(Boolean),metadata:{...e.metadata??{},[q.localizationManagedKey]:"True",[q.localizationLanguageKey]:o,[q.sourceInputValuesJsonKey]:JSON.stringify(k)}}}function Qo(e,t,o,n,r,s){const c=Qt(e,s),m=Wt(t,s),l=Eo(c,n),b=m.nodes.find(v=>K(v.id,o));if(!b)return null;const k=jo(m,r),x=Wa(c,l,k);return{title:Pt(b.title,x),body:Pt(b.body,x),launcherLabel:c.label,optionLabel:(l==null?void 0:l.label)||c.label}}function Fs(e,t){const o=Bs(Be(e,q.sourceInputValuesJsonKey));if(Object.keys(o).length>0)return o;const n=Be(e,q.controllerNodeIdKey),r=n?t.get(n):null,s=Va(r==null?void 0:r.body);return(s==null?void 0:s.inputValues)??{}}function Bs(e){if(!e)return{};try{const t=JSON.parse(e);return Object.fromEntries(Object.entries(t??{}).map(([o,n])=>[o,String(n??"")]))}catch{return{}}}function Be(e,t){var n;const o=(n=e.metadata)==null?void 0:n[t];return typeof o=="string"&&o.trim()?o.trim():null}function go(...e){var t;return((t=e.find(o=>typeof o=="string"&&o.trim()))==null?void 0:t.trim())??null}function Ye(e){const t=String(e||"").trim();return t?t.replace(/:/g,"."):"unknown"}function Gs(e,t){return e.includes("{0}")?e.replace("{0}",t):`${t} is required.`}function Us(e,t){var o,n,r;return String(t||"").trim()?((n=e.options.find(s=>K(s.id,t)))==null?void 0:n.id)??((r=e.options[0])==null?void 0:r.id):(o=e.options[0])==null?void 0:o.id}function cn(e){return e.map(t=>{var o;return{...t,options:(o=t.options)==null?void 0:o.map(n=>({...n}))}})}function Ha(e,t){const o={};for(const n of e)o[n.key]=String(t[n.key]??Sn(n));return o}function zs(){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 Ka(e){return e==="ai-task"?"aiPrompt":e==="template-launcher"?q.contentType:e}function $s(e){return K(e,"directory")?"directory":K(e,"pdf")?"pdf":K(e,"file")?"file":K(e,"memo")?"memo":K(e,"markdown")?"markdown":K(e,"csv-table")?"csv-table":K(e,"text")?"text":K(e,"code")?"code":K(e,"mask")?"mask":K(e,"image")?"image":K(e,"embed")?"embed":K(e,"aiPrompt")?"ai-task":K(e,q.contentType)?"template-launcher":"note"}function Vs(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 Xa(e){return`${e}-${Math.random().toString(36).slice(2,9)}`}function K(e,t){return String(e||"").toLowerCase()===String(t||"").toLowerCase()}function qs(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}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"}),Ya=Object.freeze({frames:"/api/remote/frames/ws",input:"/api/remote/input/ws"});function Ws(e){return Qe.deviceTasksTemplate.replace("{deviceId}",encodeURIComponent(e))}function Qa(e){return Za(e==null?void 0:e.remoteFrameWsPath,Ya.frames)}function Ja(e){return Za(e==null?void 0:e.remoteInputWsPath,Ya.input)}function Za(e,t){return typeof e=="string"?e.trim():t}const Jo={},Hs="http://127.0.0.1:5147",er="MindExec.AllowHostedLocalBridge",Ks=new Set(["4173","5173"]);function Jt(e){return e.replace(/\/+$/,"")}function Xs(){return((Jo==null?void 0:Jo.VITE_LOCAL_BRIDGE_URL)||"").trim()}function Ys(){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&&!Ks.has(o)?n:""}function j(){return Jt(Xs()||Ys()||Hs)}function Qs(){const e=window.location.hostname.toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"}function Js(){try{return window.localStorage.getItem(er)==="true"}catch{return!1}}function tr(e){try{e&&window.localStorage.setItem(er,"true")}catch{}}function At(){return Qs()||Js()}function or(e){const t=String((e==null?void 0:e.bridgeToken)||"").trim();if(t)return{header:(e==null?void 0:e.bridgeTokenHeader)||"X-Bridge-Token",token:t}}async function _(e,t,o={}){const n=new AbortController,r=window.setTimeout(()=>n.abort(),o.timeoutMs??4200),s=new Headers;s.set("Accept","application/json"),s.set("Cache-Control","no-store"),s.set("Pragma","no-cache"),o.body!==void 0&&s.set("Content-Type","application/json"),o.auth&&s.set(o.auth.header,o.auth.token);try{const c=await fetch(`${Jt(e)}${t}`,{method:o.method||(o.body===void 0?"GET":"POST"),headers:s,body:o.body===void 0?void 0:JSON.stringify(o.body),cache:"no-store",signal:n.signal}),m=await c.text(),l=m?JSON.parse(m):null;if(!c.ok){const b=(l==null?void 0:l.error)||(l==null?void 0:l.message)||`LocalBridge request failed: ${c.status}`;throw new Error(b)}return l}finally{window.clearTimeout(r)}}function Zs(e){return e instanceof DOMException&&e.name==="AbortError"?"LocalBridge probe timed out.":e instanceof SyntaxError?"LocalBridge returned a non-JSON response.":e instanceof Error?e.message||"LocalBridge is unavailable.":String(e||"LocalBridge is unavailable.")}async function Rn(e=j()){var t;try{const o=await _(e,"/api/status?refresh=1",{timeoutMs:4200});return g.emit("localBridge.status",{baseUrl:e,connected:!0,projectOpen:((t=o.project)==null?void 0:t.isOpen)===!0}),{state:"connected",baseUrl:e,status:o}}catch(o){const n=Zs(o);return g.emit("localBridge.status",{baseUrl:e,connected:!1,message:n}),{state:"unavailable",baseUrl:e,message:n}}}async function dd(e,t,o=j()){return _(o,"/project/open",{method:"POST",body:{path:e},auth:t,timeoutMs:15e3})}async function ud(e=j(),t=18,o=1200){var r,s;let n={state:"idle",baseUrl:e};for(let c=0;c<t;c+=1){if(n=await Rn(e),n.state==="connected"&&((s=(r=n.status)==null?void 0:r.project)!=null&&s.isOpen))return n;await new Promise(m=>{window.setTimeout(m,o)})}return n}async function pd(e,t=j()){return _(t,"/project/symbols",{auth:e,timeoutMs:12e3})}async function md(e,t=j()){return _(t,"/project/graph",{auth:e,timeoutMs:12e3})}async function hd(e="standard",t,o=j()){const n=`?level=${encodeURIComponent(e)}`;return _(o,`/project/ai-context${n}`,{auth:t,timeoutMs:14e3})}async function gd(e,t=j()){return g.emit("localBridge.codex.capabilities.request",{baseUrl:t}),_(t,"/api/codex/capabilities",{auth:e,timeoutMs:12e3})}async function fd(e,t=5,o,n=j()){return g.emit("localBridge.web.search.request",{baseUrl:n,maxResults:t}),_(n,"/api/web/search",{method:"POST",body:{query:e,maxResults:t},auth:o,timeoutMs:24e3})}async function bd(e,t=6e3,o,n=j()){return g.emit("localBridge.web.fetch.request",{baseUrl:n,maxChars:t}),_(n,"/api/web/fetch",{method:"POST",body:{url:e,maxChars:t},auth:o,timeoutMs:24e3})}async function yd(e,t,o=j()){return g.emit("localBridge.browser.open.request",{baseUrl:o}),_(o,"/api/browser/open",{method:"POST",body:{url:e},auth:t,timeoutMs:24e3})}async function kd(e,t=4e3,o,n=j()){return g.emit("localBridge.browser.snapshot.request",{baseUrl:n,maxChars:t}),_(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=j()){return g.emit("localBridge.browser.extract.request",{baseUrl:r,scope:t,maxChars:o}),_(r,"/api/browser/extract",{method:"POST",body:{sessionId:e,scope:t,maxChars:o},auth:n,timeoutMs:18e3})}async function Id(e,t,o=j()){return g.emit("localBridge.evidence.save.request",{baseUrl:o,kind:e.kind||"evidence"}),_(o,"/api/evidence/save",{method:"POST",body:e,auth:t,timeoutMs:18e3})}async function vd(e,t,o=j()){var n;return g.emit("localBridge.concept.defineComposite.request",{baseUrl:o,hasSignature:!!((n=e.signature)!=null&&n.trim())}),_(o,"/api/concept/define-composite",{method:"POST",body:e,auth:t,timeoutMs:18e3})}async function Cd(e,t=j()){return g.emit("localBridge.concept.status.request",{baseUrl:t}),_(t,"/api/concept/status",{method:"GET",auth:e,timeoutMs:12e3})}async function xd(e,t,o=j()){return g.emit("localBridge.concept.row.request",{baseUrl:o,id:e}),_(o,`/api/concept/row?id=${encodeURIComponent(e)}`,{method:"GET",auth:t,timeoutMs:12e3})}async function wd(e,t=j()){return g.emit("localBridge.concept.embed.readiness.request",{baseUrl:t}),_(t,"/api/concept/embed/readiness",{method:"GET",auth:e,timeoutMs:12e3})}async function Sd(e,t=j()){return _(t,"/project/close",{method:"POST",auth:e,timeoutMs:12e3})}async function Rd(e=j()){return _(e,"/api/workspace",{timeoutMs:4200})}async function Md(e,t,o=j()){return _(o,"/api/workspace/browse",{method:"POST",body:{initialPath:e||""},auth:t,timeoutMs:12e4})}async function Pd(e,t,o=j()){return _(o,"/api/workspace/set",{method:"POST",body:{path:e},auth:t,timeoutMs:3e4})}async function Ad(e,t,o=j()){return g.emit("localBridge.dir.list.request",{baseUrl:o}),_(o,"/api/dir/list",{method:"POST",body:{path:e},auth:t,timeoutMs:12e3})}async function Ed(e=j()){return _(e,"/project/change-feed",{timeoutMs:4200})}async function nr(e,t=j()){return _(t,Qe.status,{auth:e,timeoutMs:4200})}async function el(e,t=j()){return _(t,Qe.agentStatus,{auth:e,timeoutMs:4200})}async function ar(e,t=j(),o={}){const n=o.includeDataUrl?"?includeDataUrl=true":"";return _(t,`${Qe.devices}${n}`,{auth:e,timeoutMs:6500})}async function rr(e,t,o=j()){return _(o,Qe.frames,{method:"POST",body:{deviceIds:e,includeThumbnail:!0,includeLive:!0},auth:t,timeoutMs:6500})}async function fa(e,t,o,n=j(),r={}){return _(n,Qe.hostTarget,{method:"POST",body:{nodeId:e,enabled:t,leaseMs:r.leaseMs??6e4},auth:o,timeoutMs:6500})}async function tl(e,t,o=j()){return _(o,Qe.agentConnect,{method:"POST",body:e,auth:t,timeoutMs:3e4})}async function ol(e="react-remote-monitor",t,o=j()){return _(o,Qe.agentDisconnect,{method:"POST",body:{reason:e},auth:t,timeoutMs:12e3})}async function ir(e,t,o,n=j()){return _(n,Ws(e),{method:"POST",body:t,auth:o,timeoutMs:12e3})}async function nl(e,t,o=j()){return _(o,Qe.taskBatch,{method:"POST",body:e,auth:t,timeoutMs:16e3})}async function Ld(e,t=j()){const o=new URLSearchParams;return o.set("q",e.q),o.set("order",e.order||"relevance"),o.set("publishedWithin",e.publishedWithin||"any"),o.set("videoDuration",e.videoDuration||"any"),o.set("eventType",e.eventType||"any"),o.set("safeSearch",e.safeSearch||"moderate"),e.relevanceLanguage&&o.set("relevanceLanguage",e.relevanceLanguage),e.regionCode&&o.set("regionCode",e.regionCode),e.maxResults&&o.set("maxResults",String(e.maxResults)),e.pageToken&&o.set("pageToken",e.pageToken),_(t,`/api/youtube/search?${o.toString()}`,{timeoutMs:16e3})}function We(e){return`/api/company-core${e.startsWith("/")?e:`/${e}`}`}async function jd(e,t=j()){return g.emit("companyCore.bridge.request",{method:"GET",path:"/health"}),_(t,We("/health"),{auth:e,timeoutMs:6500})}async function Nd(e,t=j()){return g.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies"}),_(t,We("/api/companies"),{auth:e,timeoutMs:12e3})}async function Dd(e=20,t,o=j()){const n=Math.max(1,Math.min(100,Math.round(e)));return g.emit("companyCore.bridge.request",{method:"GET",path:"/api/company-runs",limit:n}),_(o,We(`/api/company-runs?limit=${n}`),{auth:t,timeoutMs:12e3})}async function Od(e,t,o=j()){const n=encodeURIComponent(e);return g.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies/:id/snapshot"}),_(o,We(`/api/companies/${n}/snapshot`),{auth:t,timeoutMs:12e3})}async function _d(e,t,o=j()){const n=encodeURIComponent(e);return g.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies/:id/approvals"}),_(o,We(`/api/companies/${n}/approvals?pendingOnly=false`),{auth:t,timeoutMs:12e3})}async function Fd(e,t,o=j()){const n=encodeURIComponent(e);return g.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies/:id/artifacts"}),_(o,We(`/api/companies/${n}/artifacts`),{auth:t,timeoutMs:12e3})}async function Bd(e,t,o=j()){const n=encodeURIComponent(e);return g.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies/:id/publishing-jobs"}),_(o,We(`/api/companies/${n}/publishing-jobs?limit=100`),{auth:t,timeoutMs:12e3})}async function Gd(e,t,o=j()){const n=encodeURIComponent(e);return g.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies/:id/growth"}),_(o,We(`/api/companies/${n}/growth?limit=100`),{auth:t,timeoutMs:12e3})}async function Ud(e,t,o=j()){const n=encodeURIComponent(e);return g.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies/:id/revenue"}),_(o,We(`/api/companies/${n}/revenue?limit=100`),{auth:t,timeoutMs:12e3})}async function zd(e,t,o=j()){const n=encodeURIComponent(e);return g.emit("companyCore.bridge.request",{method:"GET",path:"/api/companies/:id/reflections"}),_(o,We(`/api/companies/${n}/reflections?limit=50`),{auth:t,timeoutMs:12e3})}async function $d(e,t,o=j()){return _(o,"/api/codex/thread/run",{method:"POST",body:e,auth:t,timeoutMs:18e4})}async function Vd(e,t=j()){return _(t,"/api/file/read",{method:"POST",body:{path:e},timeoutMs:3e4})}async function qd(e,t=j()){const o=new AbortController,n=window.setTimeout(()=>o.abort(),3e4);try{const r=await fetch(`${Jt(t)}/api/file/read-raw?path=${encodeURIComponent(e)}`,{method:"GET",headers:{Accept:"application/octet-stream","Cache-Control":"no-store",Pragma:"no-cache"},cache:"no-store",signal:o.signal});if(!r.ok)throw new Error(`LocalBridge raw file read failed: ${r.status}`);return new Uint8Array(await r.arrayBuffer())}finally{window.clearTimeout(n)}}async function Wd(e,t,o,n=j()){return _(n,"/api/file/write",{method:"POST",body:{path:e,content:t,encoding:"utf8"},auth:o,timeoutMs:3e4})}async function Hd(e,t,o,n=j()){const r=new AbortController,s=window.setTimeout(()=>r.abort(),3e4),c=new Headers;c.set("Accept","application/json"),c.set("Content-Type","application/octet-stream"),c.set("Cache-Control","no-store"),c.set("Pragma","no-cache"),c.set(o.header,o.token);try{const m=new ArrayBuffer(t.byteLength);new Uint8Array(m).set(t);const l=await fetch(`${Jt(n)}/api/file/write-raw?path=${encodeURIComponent(e)}`,{method:"PUT",headers:c,body:m,cache:"no-store",signal:r.signal}),b=await l.json().catch(()=>null);if(!l.ok){const k=(b==null?void 0:b.error)||(b==null?void 0:b.message)||`LocalBridge raw file write failed: ${l.status}`;throw new Error(k)}return b}finally{window.clearTimeout(s)}}async function Kd(e,t,o=j()){return _(o,"/api/file/delete",{method:"POST",body:{path:e},auth:t,timeoutMs:3e4})}function al(e,t=j()){const o=String(e||"").trim();if(!o)return;if(/^https?:\/\//i.test(o)||o.startsWith("data:"))return o;const n=o.replace(/\\/g,"/").replace(/^\/+/,"");return`${Jt(t)}/${n}`}async function Mn(e){var r;let t=null;if(typeof navigator<"u"&&((r=navigator.clipboard)!=null&&r.writeText))try{return await navigator.clipboard.writeText(e),"clipboard"}catch(s){t=s}if(typeof document>"u"||!document.body||typeof document.execCommand!="function")throw t instanceof Error?t:new Error("clipboard-unavailable");const o=document.createElement("textarea"),n=document.activeElement instanceof HTMLElement?document.activeElement:null;o.value=e,o.setAttribute("readonly",""),o.style.position="fixed",o.style.left="-9999px",o.style.top="0",o.style.opacity="0",document.body.appendChild(o),o.focus(),o.select(),o.setSelectionRange(0,e.length);try{if(!document.execCommand("copy"))throw t instanceof Error?t:new Error("clipboard-unavailable");return"fallback"}finally{o.remove(),n==null||n.focus({preventScroll:!0})}}const sr="mindexec.app.language",xo="auto",Ht=[{code:xo,label:"Auto",nativeLabel:"Auto",englishName:"the user's input language",htmlLang:"auto",isAuto:!0,description:"Match the user's input language unless a prompt asks otherwise."},{code:"en",label:"English",nativeLabel:"English",englishName:"English",htmlLang:"en",isAuto:!1,description:"Prefer English for user-facing AI output."},{code:"ko",label:"Korean",nativeLabel:"한국어",englishName:"Korean",htmlLang:"ko",isAuto:!1,description:"Prefer Korean for user-facing AI output."},{code:"ja",label:"Japanese",nativeLabel:"日本語",englishName:"Japanese",htmlLang:"ja",isAuto:!1,description:"Prefer Japanese for user-facing AI output."},{code:"zh",label:"Chinese",nativeLabel:"中文",englishName:"Chinese",htmlLang:"zh",isAuto:!1,description:"Prefer Chinese for user-facing AI output."}];function Lt(e){if(typeof e!="string")return xo;const t=e.trim().toLowerCase();return Ht.some(o=>o.code===t)?t:xo}function Pn(e){const t=Lt(e);return Ht.find(o=>o.code===t)??Ht[0]}function lr(){if(typeof window>"u")return null;try{const e=window.localStorage.getItem(sr);return e===null?null:Lt(e)}catch{return null}}function Xd(e){return Lt(lr()??e??xo)}function Yd(e){const t=Lt(e);if(typeof window>"u")return t;try{window.localStorage.setItem(sr,t)}catch{}return t}function Qd(e){const t=lr()??Lt(e.settings.appLanguage);return{...e,settings:{...e.settings,appLanguage:t}}}function Jd(e){const t=Pn(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 Zd(e){const t=Pn(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 Zo=[{id:"general",label:"General",icon:gi},{id:"language",label:"Language",icon:fi},{id:"connection",label:"Connection",icon:bi},{id:"media",label:"Media",icon:La},{id:"agent",label:"Agent",icon:yi},{id:"system",label:"System",icon:ki},{id:"about",label:"About",icon:Ti}],rl=["Managed Cloud","BYOK","OpenAI Codex","Local Ollama"];function il(e,t,o){return Number.isFinite(e)?Math.min(o,Math.max(t,Math.round(e))):t}function eu({settings:e,onPatchSettings:t,onClose:o}){const[n,r]=p.useState("general"),[s,c]=p.useState("idle"),[m,l]=p.useState(null),b=Zo.find(h=>h.id===n)??Zo[0],k=Ji(e),x=Yt(e.model),v=e.aiProvider??"OpenAI Codex",V=ll(x),M=Pn(e.appLanguage),F=ba("Image",e),J=ba("Video",e),Z=Object.fromEntries(Ht.map(h=>[h.code,h.isAuto?h.label:`${h.nativeLabel} / ${h.label}`])),E=(h,ee)=>t(h,ee),ue=h=>{const ee=h.currentTarget;let L=0;if(h.key==="PageDown")L=Math.max(160,Math.floor(ee.clientHeight*.86));else if(h.key==="PageUp")L=-Math.max(160,Math.floor(ee.clientHeight*.86));else if(h.key==="ArrowDown")L=44;else if(h.key==="ArrowUp")L=-44;else if(h.key==="End"){h.preventDefault(),ee.scrollTo({top:ee.scrollHeight,behavior:"auto"});return}else if(h.key==="Home"){h.preventDefault(),ee.scrollTo({top:0,behavior:"auto"});return}else return;h.preventDefault(),ee.scrollBy({top:L,behavior:"auto"})},B=async()=>{try{const h=await Mn(V);c("copied"),g.emit("settings.providerCommand.copy",{provider:v,command:"dataset-generator",method:h,redacted:!0})}catch(h){if(cl(m)){c("selected"),g.emit("settings.providerCommand.selectFallback",{provider:v,command:"dataset-generator",message:h instanceof Error?h.message:String(h),redacted:!0});return}c("failed"),g.emit("settings.providerCommand.copyFailed",{provider:v,command:"dataset-generator",message:h instanceof Error?h.message:String(h)})}},pe=(h,ee)=>{const L=Ua(h,ee),Y=Ao(h).find(Pe=>Pe.id===L);if(!Y)return;const Oe=h==="Image"?e.imageRouterImageAspectPresetId:e.imageRouterVideoAspectPresetId,W=sn(h,Y,Oe);E(h==="Image"?{imageRouterImageModel:Y.id,imageRouterImageAspectPresetId:W.id}:{imageRouterVideoModel:Y.id,imageRouterVideoAspectPresetId:W.id},`media.${h.toLowerCase()}.model`),g.emit("media.model.select",{mode:h,model:Y.id,aspectPresetId:W.id,requestedSize:ln(W),source:"settings-dialog"})},Ce=(h,ee)=>{const L=h==="Image"?F.model:J.model,Y=sn(h,L,ee);E(h==="Image"?{imageRouterImageAspectPresetId:Y.id}:{imageRouterVideoAspectPresetId:Y.id},`media.${h.toLowerCase()}.aspect`),g.emit("media.aspect.select",{mode:h,model:L.id,aspectPresetId:Y.id,requestedSize:ln(Y),source:"settings-dialog"})};return a.jsx("div",{className:"ai-settings-backdrop","data-testid":"ai-settings-dialog","data-disable-mindcanvas-wheel":"true",onMouseDown:o,children:a.jsxs("section",{className:"ai-settings-dialog","aria-label":"AI settings","data-disable-mindcanvas-hotkeys":"true","data-ai-settings-dialog-surface":"true",onMouseDown:h=>h.stopPropagation(),children:[a.jsx("aside",{className:"ai-settings-tabs","aria-label":"Settings sections",children:Zo.map(h=>{const ee=h.icon;return a.jsxs("button",{type:"button",className:n===h.id?"is-active":"","data-testid":`ai-settings-tab-${h.id}`,onClick:()=>r(h.id),children:[a.jsx(ee,{size:15}),a.jsx("span",{children:h.label})]},h.id)})}),a.jsxs("main",{className:"ai-settings-main",children:[a.jsxs("header",{className:"ai-settings-head",children:[a.jsx("strong",{children:b.label}),a.jsx("button",{type:"button",title:"Close settings",onClick:o,children:a.jsx(Po,{size:16})})]}),a.jsxs("div",{className:"ai-settings-body","data-testid":"ai-settings-body",tabIndex:0,onKeyDown:ue,children:[n==="general"&&a.jsxs("div",{className:"settings-grid",children:[a.jsx(xt,{label:"Grid snap",description:"Align new movement to the canvas grid.",checked:e.gridSnap??!0,onChange:h=>E({gridSnap:h},"general.gridSnap")}),a.jsx(De,{label:"Grid type",description:"Background grid rendering mode.",value:e.gridType??"dot",options:["dot","line","particles","spirit"],onChange:h=>E({gridType:h},"general.gridType")}),a.jsx(De,{label:"Cursor position",description:"Where new nodes are placed by default.",value:e.cursorMode??"center",options:["center","lastNode"],onChange:h=>E({cursorMode:h},"general.cursorMode")}),a.jsx(De,{label:"Cursor direction",description:"Direction for sequential node placement.",value:e.cursorDirection,options:["right","down"],onChange:h=>E({cursorDirection:h},"general.cursorDirection")}),a.jsx(De,{label:"Camera trace mode",description:"Whether the camera follows new work.",value:e.cameraTraceMode??"none",options:["none","cursor"],onChange:h=>E({cameraTraceMode:h},"general.cameraTraceMode")}),a.jsx(De,{label:"Image load size",description:"Image nodes use fixed or original sizing.",value:e.imageLoadSize??"default",options:["default","original"],onChange:h=>E({imageLoadSize:h},"general.imageLoadSize")}),a.jsx(zt,{label:"AI node width",description:"Default width for new AI task nodes.",value:e.aiNodeDefaultWidth??340,min:220,max:1200,onChange:h=>E({aiNodeDefaultWidth:h},"general.aiNodeDefaultWidth")}),a.jsx(zt,{label:"AI node height",description:"Default height for new AI task nodes.",value:e.aiNodeDefaultHeight??196,min:120,max:900,onChange:h=>E({aiNodeDefaultHeight:h},"general.aiNodeDefaultHeight")}),a.jsx(xt,{label:"Show full AI response",description:"Allow AI result nodes to expand for long output.",checked:e.showFullAiResponse??!1,onChange:h=>E({showFullAiResponse:h},"general.showFullAiResponse")}),a.jsx(xt,{label:"Minimap",description:"Display a small navigation minimap in the bottom-right of the canvas.",checked:e.minimapEnabled??!1,onChange:h=>E({minimapEnabled:h},"general.minimapEnabled")}),a.jsx(xt,{label:"Mouse wheel mode",description:"Swap wheel zoom and scroll behavior.",checked:e.wheelMode,onChange:h=>E({wheelMode:h},"general.wheelMode")})]}),n==="language"&&a.jsx("div",{className:"settings-grid settings-grid--compact",children:a.jsx(De,{label:"App Language",description:`Controls the language preference passed into AI runs. ${M.description}`,value:M.code,options:Ht.map(h=>h.code),optionLabels:Z,testId:"app-language-select",onChange:h=>E({appLanguage:Lt(h)},"language.appLanguage")})}),n==="connection"&&a.jsxs("div",{className:"settings-stack",children:[a.jsx("section",{className:"settings-radio-group","aria-label":"AI Provider",children:rl.map(h=>a.jsxs("label",{className:v===h?"is-selected":"",children:[a.jsx("input",{type:"radio",name:"ai-provider",checked:v===h,onChange:()=>E({aiProvider:h},"connection.provider")}),a.jsxs("span",{children:[a.jsx("strong",{children:h}),a.jsx("small",{children:cr(h)})]})]},h))}),a.jsx(dl,{provider:v,datasetGeneratorCommand:V,copyState:s,onCommandTextAreaRef:l,onCopyDatasetGeneratorCommand:B}),a.jsxs("div",{className:"settings-grid settings-grid--compact",children:[a.jsx(De,{label:"Text model",description:sl(x),value:x,options:k.map(h=>h.id),optionLabels:Object.fromEntries(k.map(h=>[h.id,`${Ba(h.provider)} · ${h.label}`])),onChange:h=>E({model:h},"connection.model")}),a.jsx(De,{label:"Reasoning effort",description:"Mapped to LocalBridge Codex reasoning effort.",value:e.effort,options:["Fast","Normal","Deep"],onChange:h=>E({effort:h},"connection.effort")}),(e.aiProvider??"OpenAI Codex")==="Local Ollama"&&a.jsx(ul,{label:"Ollama URL",description:"Local Ollama endpoint.",value:e.ollamaEndpoint??"http://localhost:11434",onChange:h=>E({ollamaEndpoint:h},"connection.ollamaEndpoint")}),a.jsx(xt,{label:"ImageRouter mode",description:"Key material remains outside this React board snapshot.",checked:e.imageRouterEnabled??!1,onChange:h=>E({imageRouterEnabled:h},"connection.imageRouterEnabled")}),a.jsx(xt,{label:"Parallel insight bundles",description:"Preserves the original CodeMaster insight bundle switch.",checked:e.codeMasterInsightBundlesEnabled??!0,onChange:h=>E({codeMasterInsightBundlesEnabled:h},"connection.codeMasterInsightBundlesEnabled")}),a.jsx(zt,{label:"Bundle timeout",description:"Per insight bundle timeout in milliseconds.",value:e.codeMasterInsightBundleTimeoutMs??18e3,min:5e3,max:6e4,onChange:h=>E({codeMasterInsightBundleTimeoutMs:h},"connection.codeMasterInsightBundleTimeoutMs")}),a.jsx(zt,{label:"Retry Count (Std)",description:"Retries for lite and standard CodeMaster insight bundle calls.",value:e.codeMasterInsightBundleRetryCount??2,min:1,max:4,step:1,testId:"codemaster-insight-retry-std",onChange:h=>E({codeMasterInsightBundleRetryCount:h},"connection.codeMasterInsightBundleRetryCount")}),a.jsx(zt,{label:"Retry Count (Deep)",description:"Retries for deep CodeMaster insight bundle calls.",value:e.codeMasterInsightBundleRetryCountDeep??3,min:1,max:5,step:1,testId:"codemaster-insight-retry-deep",onChange:h=>E({codeMasterInsightBundleRetryCountDeep:h},"connection.codeMasterInsightBundleRetryCountDeep")})]}),a.jsxs("div",{className:"settings-note",children:[a.jsx(pa,{size:15}),a.jsx("span",{children:"API keys are intentionally not stored in this React board. Live provider adapters must supply and verify secrets separately."})]})]}),n==="media"&&a.jsxs("div",{className:"settings-stack","data-testid":"ai-settings-media-tab",children:[a.jsx(ya,{mode:"Image",icon:a.jsx(La,{size:17}),selection:F,onModelChange:h=>pe("Image",h),onAspectChange:h=>Ce("Image",h)}),a.jsx(ya,{mode:"Video",icon:a.jsx(Ii,{size:17}),selection:J,onModelChange:h=>pe("Video",h),onAspectChange:h=>Ce("Video",h)}),a.jsxs("div",{className:"settings-note",children:[a.jsx(pa,{size:15}),a.jsx("span",{children:"These are adapter hints only. Selecting a media model does not store an API key, invoke ImageRouter, or claim live generation availability."})]})]}),n==="agent"&&a.jsx("div",{className:"settings-grid settings-grid--compact",children:a.jsx(De,{label:"Direct instruction queue",description:"How selected agents receive direct instructions.",value:e.directInstructionQueueMode??"Append",options:["Append","Next","ReplacePending"],onChange:h=>E({directInstructionQueueMode:h},"agent.directInstructionQueueMode")})}),n==="system"&&a.jsxs("div",{className:"settings-grid settings-grid--compact",children:[a.jsx(De,{label:"Execution mode",description:"Concept parses IR locally; PureLLM is direct chat adapter mode.",value:e.executionMode??"Concept",options:["Concept","PureLLM"],onChange:h=>E({executionMode:h},"system.executionMode")}),a.jsxs("div",{className:"settings-note",children:[a.jsx(vi,{size:15}),a.jsx("span",{children:"Changing this setting affects the next run only. It does not claim a live agent has executed."})]})]}),n==="about"&&a.jsxs("div",{className:"settings-about",children:[a.jsx(Ci,{size:34}),a.jsx("strong",{children:"MindExec React"}),a.jsx("span",{children:"Fast local-first MindCanvas shell, rebuilt without Blazor in the render loop."}),a.jsx("small",{children:"AI settings parity slice"})]})]}),a.jsx("footer",{className:"ai-settings-footer",children:a.jsx("button",{type:"button","data-testid":"ai-settings-done",onClick:o,children:"Save"})})]})]})})}function ba(e,t){const o=rn(e,t),n=e==="Image"?t.imageRouterImageAspectPresetId:t.imageRouterVideoAspectPresetId,r=sn(e,o,n);return{model:o,aspect:r,aspectOptions:za(o,e),requestedSize:ln(r)}}function sl(e){const t=Xi(e);return t?`${Ba(t.provider)} text model used by bottom input and AI Task runs.`:"Custom text model id preserved with this board."}function cr(e){switch(e){case"Managed Cloud":return"Reserved for the hosted paid adapter.";case"BYOK":return"Use a separately configured user key.";case"Local Ollama":return"Local LLM server endpoint.";case"Gemini CLI":return"Hidden Gemini CLI compatibility path.";case"OpenAI Codex":default:return"LocalBridge Codex execution path."}}function ll(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 cl(e){return!e||e.value.length===0?!1:(e.focus({preventScroll:!0}),e.select(),e.setSelectionRange(0,e.value.length),!0)}function dl({provider:e,datasetGeneratorCommand:t,copyState:o,onCommandTextAreaRef:n,onCopyDatasetGeneratorCommand:r}){const s=e==="BYOK"?"BYOK Settings":e==="Local Ollama"?"Ollama Settings":e==="Managed Cloud"?"Managed Cloud":e==="Gemini CLI"?"Gemini CLI":"OpenAI Codex";return a.jsxs("section",{className:"settings-provider-card","data-testid":"ai-settings-provider-guidance","data-provider":e,children:[a.jsx("header",{children:a.jsxs("div",{children:[a.jsx("strong",{"data-testid":"ai-settings-provider-title",children:s}),a.jsx("span",{children:cr(e)})]})}),e==="Managed Cloud"&&a.jsx("div",{className:"settings-provider-card__notice",children:"Managed Cloud is coming soon in this build. Switch to BYOK, OpenAI Codex, or Local Ollama for local execution."}),e==="Gemini CLI"&&a.jsx("div",{className:"settings-provider-card__notice","data-testid":"ai-settings-gemini-hidden-provider",children:"Gemini CLI is hidden in this company build. Switch to BYOK, OpenAI Codex, or Local Ollama to manage connection settings here."}),e==="BYOK"&&a.jsxs("div",{className:"settings-provider-card__section",children:[a.jsx("p",{children:"API key material stays outside this React board. Configure the BYOK adapter or environment before running live OpenRouter calls."}),a.jsxs("div",{className:"settings-provider-card__command-head",children:[a.jsx("strong",{children:"DatasetGenerator Export"}),a.jsx("button",{type:"button","data-testid":"ai-settings-provider-copy-command","data-provider-copy-state":o,onClick:()=>void r(),children:o==="copied"?"Copied":o==="selected"?"Selected":o==="failed"?"Copy failed":"Copy command"})]}),a.jsx("textarea",{readOnly:!0,ref:n,value:t,"data-testid":"ai-settings-provider-dataset-command",className:"settings-provider-card__command","aria-label":"Redacted DatasetGenerator command"}),a.jsx("div",{className:"settings-provider-card__note",children:"This command is redacted; no API key is stored in the board. Replace OPENROUTER_API_KEY only in a trusted shell."})]}),e==="OpenAI Codex"&&a.jsxs("div",{className:"settings-provider-card__section",children:[a.jsx("strong",{children:"Connection Requirements"}),a.jsxs("ol",{children:[a.jsxs("li",{children:["Install MindExec LocalBridge dependencies: ",a.jsx("code",{children:"npm install"})]}),a.jsxs("li",{children:["Sign in once: ",a.jsx("code",{children:"codex login"})]}),a.jsx("li",{children:"Runtime: Codex SDK first, Legacy Exec fallback when SDK is unavailable."})]})]}),e==="Local Ollama"&&a.jsxs("div",{className:"settings-provider-card__section",children:[a.jsx("p",{children:"Ollama model selection is handled from the bottom AI input bar. Keep the local endpoint editable below."}),a.jsxs("div",{className:"settings-provider-card__note",children:["Requires ",a.jsx("code",{children:'OLLAMA_ORIGINS="*"'})," when running Ollama for browser access."]})]}),a.jsxs("div",{className:"settings-provider-card__section settings-provider-card__section--image",children:[a.jsx("strong",{children:"Image Generation"}),a.jsx("p",{children:"Text AI provider and image generation provider are configured separately. ImageRouter API key is adapter-owned and used only for image mode."}),a.jsx("span",{children:"ImageRouter API key: not stored in this React board."})]})]})}function ya({mode:e,icon:t,selection:o,onModelChange:n,onAspectChange:r}){const s=Ao(e),c=Object.fromEntries(s.map(l=>[l.id,`${l.provider} · ${l.label}`])),m=Object.fromEntries(o.aspectOptions.map(l=>[l.id,`${l.label} · ${l.resolvedSize??"auto"}`]));return a.jsxs("section",{className:"settings-media-section","data-testid":`ai-settings-media-${e.toLowerCase()}`,children:[a.jsxs("header",{children:[a.jsx("span",{className:"settings-media-section__icon",children:t}),a.jsxs("span",{children:[a.jsxs("strong",{children:[e," defaults"]}),a.jsxs("small",{children:[o.model.provider," · ",o.requestedSize]})]})]}),a.jsxs("div",{className:"settings-grid settings-grid--compact",children:[a.jsx(De,{label:`${e} model`,description:"Shared with the bottom input model selector.",value:o.model.id,options:s.map(l=>l.id),optionLabels:c,testId:`ai-settings-${e.toLowerCase()}-model`,onChange:n}),a.jsx(De,{label:`${e} aspect`,description:o.aspect.note,value:o.aspect.id,options:o.aspectOptions.map(l=>l.id),optionLabels:m,testId:`ai-settings-${e.toLowerCase()}-aspect`,swatchClassName:is(o.aspect.id),onChange:r})]})]})}function xt({label:e,description:t,checked:o,onChange:n}){return a.jsxs("label",{className:"setting-row setting-row--toggle",children:[a.jsxs("span",{children:[a.jsx("strong",{children:e}),a.jsx("small",{children:t})]}),a.jsx("input",{type:"checkbox",checked:o,onChange:r=>n(r.target.checked)})]})}function De({label:e,description:t,value:o,options:n,optionLabels:r,testId:s,swatchClassName:c,onChange:m}){return a.jsxs("label",{className:"setting-row",children:[a.jsxs("span",{children:[a.jsx("strong",{children:e}),a.jsx("small",{children:t})]}),a.jsxs("span",{className:"setting-row__select-wrap",children:[c&&a.jsx("span",{className:`aspect-select__swatch ${c}`}),a.jsx("select",{value:o,"data-testid":s,onChange:l=>m(l.target.value),children:n.map(l=>a.jsx("option",{value:l,children:(r==null?void 0:r[l])??l},l))})]})]})}function zt({label:e,description:t,value:o,min:n,max:r,step:s=1,testId:c,onChange:m}){return a.jsxs("label",{className:"setting-row",children:[a.jsxs("span",{children:[a.jsx("strong",{children:e}),a.jsx("small",{children:t})]}),a.jsx("input",{type:"number",min:n,max:r,step:s,"data-testid":c,value:o,onChange:l=>m(il(l.target.valueAsNumber,n,r))})]})}function ul({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 pl=1e3,ka=1536*1024,ml=3*1024*1024*3/4,hl=24,gl=.65,fl=16,bl=.92;function wo(e){if(e.byteLength<5)return null;try{const o=new DataView(e).getUint32(0,!1);if(o<2||o>e.byteLength-4)return null;const n=new TextDecoder().decode(new Uint8Array(e,4,o));return{metadata:yl(JSON.parse(n)),payload:e.slice(4+o)}}catch{return null}}function yl(e){const t=kl(e)?e:{};return{type:Ne(t.type)||"remote.frame.binary",kind:Ne(t.kind)||"live",deviceId:Ne(t.deviceId),frameSeq:fe(t.frameSeq),streamId:Ne(t.streamId),width:fe(t.width),height:fe(t.height),mimeType:Ne(t.mimeType)||"image/jpeg",mode:Ne(t.mode),fps:fe(t.fps),capturedAt:Ne(t.capturedAt),receivedAt:Ne(t.receivedAt),byteLength:fe(t.byteLength),transport:Ne(t.transport),contentHash:Ne(t.contentHash),captureMs:fe(t.captureMs),sameContentStreak:fe(t.sameContentStreak),droppedByAgent:fe(t.droppedByAgent),dirtyRectCount:Tl(t.dirtyRectCount??t.dirtyRects??t.dirtyRegionCount),dirtyPixelRatio:ur(t.dirtyPixelRatio??t.dirtyRatio??t.dirtyAreaRatio??t.changedPixelRatio),codec:Ne(t.codec??t.encoder??t.encoding),deltaEncoded:pr(t.deltaEncoded??t.isDeltaEncoded??t.deltaFrame)}}function dr(e,t=0){const o=fe(e.captureMs),n=Math.max(fe(e.byteLength),fe(t)),r=fe(e.sameContentStreak),s=fe(e.droppedByAgent),c=fe(e.dirtyRectCount),m=ur(e.dirtyPixelRatio),l=Ne(e.codec),b=pr(e.deltaEncoded),k={captureMs:o,byteLength:n,sameContentStreak:r,droppedByAgent:s,dirtyRectCount:c,dirtyPixelRatio:m,codec:l,deltaEncoded:b};return n>=ml?{level:"oversized-frame",overBudget:!0,reason:"RemoteFast frame is near the agent binary frame ceiling.",...k}:o>=pl?{level:"slow-capture",overBudget:!0,reason:"RemoteFast reported a slow screen capture.",...k}:m>=bl&&n>=ka?{level:"inefficient-full-frame",overBudget:!0,reason:"RemoteFast dirty-region metadata shows a near-full-frame update with a large payload.",...k}:m>=gl&&c>=fl?{level:"dirty-region-heavy",overBudget:!0,reason:"RemoteFast dirty-region metadata shows many changed regions in one frame.",...k}:n>=ka?{level:"large-frame",overBudget:!0,reason:"RemoteFast frame payload is large enough to create decode or transport pressure.",...k}:r>=hl?{level:"stable-duplicate",overBudget:!1,reason:"RemoteFast reports repeated identical content that may be eligible for future delta or skip optimization.",...k}:{level:"nominal",overBudget:!1,reason:"",...k}}function kl(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function Ne(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):""}function fe(e){const t=Number(e);return Number.isFinite(t)&&t>=0?t:0}function Tl(e){return Array.isArray(e)?e.length:Math.round(fe(e))}function ur(e){const t=fe(e);return t<=1?t:t<=100?t/100:1}function pr(e){return typeof e=="boolean"?e:typeof e=="number"?e>0:typeof e=="string"?/^(1|true|yes|on|delta)$/i.test(e.trim()):!1}function mr(e){const t=Xe(e.deviceId,256),o=Il({...e.input,controlLeaseId:e.input.controlLeaseId||e.controlLeaseId});return!t||!o.type?null:{type:"input",requestId:Xe(e.requestId,160),deviceId:t,ack:vl(o.type,e.ack),input:o}}function Il(e={}){const t=Number(e.normalizedX),o=Number(e.normalizedY),n=Number(e.deltaX),r=Number(e.deltaY);return{type:Xe(e.type,48),normalizedX:Number.isFinite(t)?st(t,0,1):void 0,normalizedY:Number.isFinite(o)?st(o,0,1):void 0,button:Xe(e.button,24),deltaX:Number.isFinite(n)?st(n,-4096,4096):0,deltaY:Number.isFinite(r)?st(r,-4096,4096):0,key:Xe(e.key,80),code:Xe(e.code,80),text:xl(e.text,256),repeat:e.repeat===!0,controlLeaseId:Xe(e.controlLeaseId,128),issuedAt:Xe(e.issuedAt,80)}}function vl(e,t){return t===!0||!/^pointermove$/i.test(String(e||"").trim())}function hr(e){let t;try{const n=typeof e=="string"?JSON.parse(e||"{}"):e;if(!gr(n))return null;t=n}catch{return null}const o=wt(t.type||t.Type);return o==="RemoteInputSocketReady"?{type:o,ok:!0,requestId:"",deviceId:"",inputType:"",commandId:"",error:""}:o!=="RemoteInputResult"&&o!=="RemoteInputError"?null:{type:o,ok:t.ok===!0||t.Ok===!0,requestId:wt(t.requestId||t.RequestId),deviceId:wt(t.deviceId||t.DeviceId),inputType:wt(t.inputType||t.InputType),commandId:wt(t.commandId||t.CommandId),error:wt(t.error||t.Error)}}function Cl(e,t,o,n=!1){if(!Ta(t))return null;const r=Ta(o)?o:{left:0,top:0,width:t.width,height:t.height};let s=Number(e.clientX)-t.left-r.left,c=Number(e.clientY)-t.top-r.top;return!Number.isFinite(s)||!Number.isFinite(c)||(s<0||c<0||s>r.width||c>r.height)&&!n?null:(s=st(s,0,r.width),c=st(c,0,r.height),{normalizedX:st(s/r.width,0,1),normalizedY:st(c/r.height,0,1)})}function st(e,t,o){return Math.max(t,Math.min(o,e))}function Ta(e){if(!gr(e))return!1;const t=Number(e.width),o=Number(e.height);return Number.isFinite(Number(e.left))&&Number.isFinite(Number(e.top))&&Number.isFinite(t)&&Number.isFinite(o)&&t>0&&o>0}function Xe(e,t){return String(e??"").replace(/\0/g,"").trim().slice(0,t)}function xl(e,t){return Xe(e,t)}function wt(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):""}function gr(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function wl(e,t){const o=Math.max(1,Math.floor(t.visibleBudget)),n=t.searchText.trim(),r=n.length>0||t.visibilityFilter!=="connected"||t.capabilityFilter!=="all",s=Sl(e,t.visibilityFilter,n,t.capabilityFilter),c=Rl(s,t.groupMode),m=c.length,l=Math.max(1,Math.ceil(Math.max(0,m)/o)),b=Number.isFinite(t.pageIndex)?Math.floor(t.pageIndex):0,k=Math.max(0,Math.min(b,l-1)),x=k*o,v=c.slice(x,x+o),V=v.map(lt).filter(Boolean),M=v.filter(E=>E.connected===!0).map(lt).filter(Boolean),F=new Set(v.map(E=>dn(E,t.groupMode))).size,J=c.filter(E=>E.connected===!0&&Ge(E,"taskDispatch")).map(lt).filter(Boolean),Z=c.filter(E=>E.connected===!0&&Ge(E,"taskDispatch")&&Ge(E,"aiAssist")).map(lt).filter(Boolean);return{filterActive:r,filteredDevices:s,projectedDevices:c,visibleDevices:v,visibleDeviceIds:V,visibleConnectedDeviceIds:M,frameSubscriptionDeviceIdSignature:M.join(","),visibleGroupCount:F,projectedCount:m,filteredCount:s.length,pageCount:l,pageIndex:k,pageStart:x,placeholderSlots:Math.max(0,o-v.length),taskDispatchDeviceIds:J,aiTaskDeviceIds:Z}}function Sl(e,t,o,n){const r=o.trim().toLocaleLowerCase();return e.filter(s=>Ml(s,t)&&Pl(s,n)&&Al(s,r))}function Rl(e,t){return[...e].sort((o,n)=>{const r=dn(o,t),s=dn(n,t);if(r!==s)return r.localeCompare(s);const c=un(o).toLocaleLowerCase(),m=un(n).toLocaleLowerCase();return c!==m?c.localeCompare(m):lt(o).localeCompare(lt(n))})}function dn(e,t){switch(t){case"activity":return br(e);case"platform":return fr(e).toLocaleLowerCase()||"unknown";case"capability":return yr(e);default:return e.connected===!0?"online":"offline"}}function lt(e){return String(e.deviceId||e.sessionId||e.deviceName||"").trim()}function un(e){return String(e.deviceName||e.hostname||lt(e)||"Remote device").trim()}function fr(e){var t;return String(((t=e.status)==null?void 0:t.platform)||e.platform||"unknown").trim()}function Ge(e,t){var n;const o=(n=e.capabilities)==null?void 0:n[t];return typeof o=="boolean"?o:typeof o=="number"?o!==0:typeof o=="string"?/^(1|true|yes|on)$/i.test(o):!1}function Ml(e,t){return t==="all"?!0:t==="offline"?e.connected!==!0:e.connected===!0}function Pl(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 Al(e,t){var n;return t?[lt(e),un(e),fr(e),pn(e.arch),pn((n=e.latestTask)==null?void 0:n.status),br(e),yr(e),e.connected===!0?"online live connected":"offline disconnected"].join(" ").toLocaleLowerCase().includes(t):!0}function br(e){var o,n,r,s;const t=pn((o=e.latestTask)==null?void 0:o.status).toLocaleLowerCase();return t==="running"||t==="queued"?`task-${t}`:((n=e.activeLiveStream)==null?void 0:n.active)===!0?"live":Number(((r=e.counters)==null?void 0:r.liveFramesReceived)||0)>0?"live-recent":Number(((s=e.counters)==null?void 0:s.thumbnailFramesReceived)||0)>0?"thumbnail":e.lastStatusAt||e.lastSeenAt?"heartbeat":"idle"}function yr(e){return Ge(e,"aiAssist")?"ai-assist":Ge(e,"taskDispatch")?"task-dispatch":Ge(e,"control")?"control":Ge(e,"thumbnail")||Ge(e,"screen")?"screen":"view-only"}function pn(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):""}const Me=30,El=1200,Ll=4200,Ia=12,kr=8e3,jl=1.5,Tr=42,va="mindexec:remote-monitor-input-smoke",en="connected-screen-wall",mn=90,Ir=240,vr=1e4,$t=6e4,fo=25e3,Nl=250,Io=2e3,Rt=60,Ca=2,Dl=96,Ol=58,Vt=[1,1.5,2.25,3.375],xa=1,_l=5,Fl=72,Bl=96,wa="240px",hn="MindExec.RemoteFleet.AutoHost",gn="MindExec.RemoteFleet.AutoHostNodeId",Cr=["status","activity","platform","capability"],xr=["connected","all","offline"],wr=["all","control","task","ai"],Mt=new Map,Zt=new WeakMap;function Sa(e,t=0){if(typeof window>"u")return!0;const o=window.innerWidth||document.documentElement.clientWidth||0,n=window.innerHeight||document.documentElement.clientHeight||0;return o<=0||n<=0?!0:e.right>=-t&&e.bottom>=-t&&e.left<=o+t&&e.top<=n+t}function Sr(e,t,o){const[n,r]=p.useState(()=>typeof document>"u"?!0:document.visibilityState==="visible"),[s,c]=p.useState(!0),m=p.useRef(null);p.useEffect(()=>{if(typeof document>"u")return;const b=()=>r(document.visibilityState==="visible");return b(),document.addEventListener("visibilitychange",b),()=>document.removeEventListener("visibilitychange",b)},[]),p.useEffect(()=>{const b=e.current;if(!b||typeof IntersectionObserver>"u"){c(!0);return}const k=new IntersectionObserver(x=>{const v=x[0],V=!!(v!=null&&v.isIntersecting||((v==null?void 0:v.intersectionRatio)??0)>0),M=Sa(v?v.boundingClientRect:b.getBoundingClientRect(),240);c(V||M)},{root:null,rootMargin:wa,threshold:0});return k.observe(b),()=>k.disconnect()},[e]);const l=n&&s;return p.useEffect(()=>{if(m.current===l)return;m.current=l;const b={nodeId:t,visible:l,pageVisible:n,viewportVisible:s,rootMargin:wa};o==="monitor"?g.emit("remoteMonitor.node.transportVisibility",b):g.emit("remoteControl.node.transportVisibility",b)},[t,n,o,s,l]),l}function tu({node:e,onPatch:t,onCreateRemoteControl:o}){var Jn,Zn,ea,ta,oa,na,aa,ra,ia,sa,la,ca;const n=fn((Jn=e.metadata)==null?void 0:Jn.RemoteTotal,Me),r=fn((Zn=e.metadata)==null?void 0:Zn.RemoteConnected,0),s=p.useRef(null),c=p.useRef(null),m=Sr(s,e.id,"monitor"),[l,b]=p.useState(()=>({source:At()?"loading":"blocked",loading:!1,message:At()?"RemoteHub not checked yet.":"Hosted LocalBridge access is gated.",baseUrl:j(),devices:bo(n,r)})),k=p.useRef(new Map),x=p.useRef(new Set),v=p.useRef(new Map),V=p.useRef(new Map),M=p.useRef(new Map),F=p.useRef(null),J=p.useRef(0),Z=p.useRef(0),E=p.useRef(0),ue=p.useRef(!1),B=p.useRef(0),pe=p.useRef(0),Ce=p.useRef(!1),h=p.useRef(!1),ee=p.useRef(!1),L=p.useRef(""),Y=p.useRef(0),Oe=p.useRef(""),W=p.useRef(null),Pe=p.useRef(!1),_e=p.useRef(0),be=p.useRef(0),A=p.useRef(e.metadata??{}),[xe,Fe]=p.useState(""),[S,Q]=p.useState(!1),[te,ne]=p.useState("locked"),[jt,ae]=p.useState("Remote input locked."),[Do,we]=p.useState(""),[Se,mt]=p.useState(""),[Nt,de]=p.useState(""),[Re,eo]=p.useState(""),[Je,to]=p.useState(""),[Oo,Ue]=p.useState(""),[kt,Ze]=p.useState(0),[He,_o]=p.useState(xa),[ze,oo]=p.useState("status"),[Dt,no]=p.useState(""),[Ae,ao]=p.useState("connected"),[Ee,ro]=p.useState("all"),[me,ht]=p.useState(()=>tn(e.id)),et=l.source==="bridge"?l.devices.length:l.devices.length||n,y=Dt.trim(),I=p.useMemo(()=>wl(l.devices,{groupMode:ze,visibilityFilter:Ae,searchText:y,capabilityFilter:Ee,pageIndex:kt,visibleBudget:Me}),[Ee,ze,kt,y,l.devices,Ae]),N=I.filterActive,U=I.filteredDevices,z=I.projectedDevices,D=I.projectedCount,P=I.pageCount,O=I.pageIndex,X=I.pageStart,he=I.visibleDevices,tt=I.visibleDeviceIds,$e=I.visibleConnectedDeviceIds,ot=I.frameSubscriptionDeviceIdSignature,_n=I.visibleGroupCount,Ur=I.placeholderSlots,Fo=`${O+1}/${P}`,Fn=P<=1?100:Math.max(12,100/P),zr=P<=1?0:O/Math.max(1,P-1)*(100-Fn),Ot=Vt[He]??Vt[xa],Bn=Math.round(Dl*Ot),Gn=Math.round(Ol*Ot),oe=p.useMemo(()=>he.find(i=>it(i)===xe)||he.find(i=>i.connected===!0)||he[0],[xe,he]),H=oe?it(oe):"",_t=l.devices.filter(i=>i.connected===!0).length,Bo=l.devices.reduce((i,d)=>{var u;return i+Number(((u=d.counters)==null?void 0:u.tasksQueued)||0)},0),io=I.taskDispatchDeviceIds,so=I.aiTaskDeviceIds,Go=io.length,Ft=so.length,Uo=l.source==="bridge"?(ea=l.hub)!=null&&ea.started?"Online":((ta=l.hub)==null?void 0:ta.enabled)===!1?"Off":"Ready":l.source==="blocked"?"Gated":l.source,lo=l.source==="bridge"?"Local":l.source==="blocked"?"Gated":"Preview",zo=Qa((oa=l.bridge)==null?void 0:oa.status),$o=Ja((na=l.bridge)==null?void 0:na.status),Un=l.source==="bridge"&&!!$o,zn=oe?ce(oe,"control"):!1,Vo=oe?ce(oe,"taskDispatch"):!1,nt=p.useMemo(()=>oe?l.source!=="bridge"?"LocalBridge is not connected.":Un?oe.connected!==!0?"Selected device is offline.":zn?"":"RemoteAgent control capability is disabled.":"Remote input adapter is unavailable.":"No screen selected.",[Un,zn,oe,l.source]),Le=nt==="",qo=S?Er(te):Le?"Locked":"Off",ie=l.source==="bridge"&&((aa=l.hub)==null?void 0:aa.hostTargetActive)===!0&&l.hub.hostTargetNodeId===e.id,re=p.useMemo(()=>zl(l.hub,ie),[ie,l.hub]),Bt=Yl(l.agent,l.source),co=Nr(l.agent),Wo=Dr(l.agent),Gt=p.useMemo(()=>Hl(l.hub,e.id),[e.id,l.hub]),uo=Ql({source:l.source,hasAuth:!!l.auth,isHostActiveForNode:ie,request:Gt,busy:Se}),po=uo==="",mo=l.source==="bridge"&&!!l.auth&&co&&!Se,$n=l.source==="bridge"&&!!H&&(oe==null?void 0:oe.connected)===!0&&Vo&&!!Re.trim()&&!Je,Vn=l.source==="bridge"&&Go>0&&!!Re.trim()&&!Je,qn=l.source==="bridge"&&Ft>0&&!!Re.trim()&&!Je,$r=Oo||Nt||Do||(l.source==="bridge"&&oe?`${ft(oe)}: ${jt}`:l.message),Wn=p.useMemo(()=>ql(l.latestTaskBatch,l.recentTaskBatches),[l.latestTaskBatch,l.recentTaskBatches]),ke=Wl(Wn),gt=l.source==="bridge"&&!!(Wn&&ke);p.useEffect(()=>{A.current=e.metadata??{}},[e.metadata]);const Hn=p.useCallback((i,d)=>{const u=A.current??{},f=Object.entries(d).filter(([C,R])=>u[C]!==R).map(([C])=>C);if(f.length===0)return;const T={...u,...d};A.current=T,t(e.id,{metadata:T}),g.emit("remoteMonitor.node.metadata.patch",{nodeId:e.id,reason:i,keys:f})},[e.id,t]);p.useEffect(()=>{l.loading||Hn("snapshot",Ul({source:l.source,hub:l.hub,baseUrl:l.baseUrl,hubLabel:Uo,routeLabel:lo,connected:_t,total:et,taskCount:Bo,taskDispatchCount:Go,aiCount:Ft,pageLabel:Fo,pageStart:X,pageIndex:O,pageCount:P,projectionMode:en,projectedCount:D,visibleBudget:Me,selectedDeviceId:H,inputLabel:qo,devices:l.devices,latestTaskBatch:l.latestTaskBatch,recentTaskBatches:l.recentTaskBatches,taskFollowActive:gt,taskFollowKey:ke,isHostActiveForNode:ie,registryRouteInfo:re,hostTargetRenewMs:ie?fo:0,autoHostEnabled:me,agent:l.agent,agentStatusLabel:Bt,agentRunning:co,agentReady:Wo,message:l.message}))},[Ft,me,O,_t,Wo,co,Bt,Uo,qo,ie,P,Fo,X,Hn,D,re,lo,H,l.agent,l.baseUrl,l.devices,l.hub,l.latestTaskBatch,l.loading,l.message,l.recentTaskBatches,l.source,gt,ke,Bo,Go,et]),p.useEffect(()=>{kt!==O&&Ze(O)},[O,kt]),p.useEffect(()=>{const i=new Set(tt);for(const d of k.current.keys())i.has(d)||k.current.delete(d)},[tt]),p.useEffect(()=>{g.emit("remoteMonitor.node.frameSubscription",{nodeId:e.id,deviceCount:m?$e.length:0,visibleDeviceCount:$e.length,transportVisible:m,pageIndex:O,pageStart:X,visibleBudget:Me,transportKey:ot})},[O,e.id,X,m,$e.length,ot]),p.useEffect(()=>{if(l.source!=="bridge")return;const i=[re.status,re.reason,re.accountRouteReady?"ready":"local",re.migrationBlocked?"migration":"",ie?"hosting":"inactive"].join("|");Oe.current!==i&&(Oe.current=i,g.emit("remoteMonitor.node.registryRoute",{nodeId:e.id,status:re.status,reason:re.reason,accountRouteReady:re.accountRouteReady,migrationBlocked:re.migrationBlocked,hostTargetActive:ie}))},[ie,e.id,re,l.source]),p.useEffect(()=>{ht(tn(e.id))},[e.id]);const Tt=p.useCallback((i,d)=>{Ze(u=>{const f=Math.max(0,Math.min(P-1,u+i));return f!==u&&g.emit("remoteMonitor.node.page",{nodeId:e.id,from:u,to:f,pageCount:P,visibleBudget:Me,source:d}),f})},[e.id,P]),Kn=p.useCallback((i,d)=>{i.stopPropagation(),Tt(d,"button")},[Tt]),Xn=p.useCallback((i,d)=>{i.preventDefault(),i.stopPropagation(),_o(u=>{const f=Math.max(0,Math.min(Vt.length-1,u+d));return f!==u&&g.emit("remoteMonitor.node.tileScale",{nodeId:e.id,from:u,to:f,scale:Vt[f],visibleBudget:Me}),f})},[e.id]);p.useEffect(()=>{var i;(i=c.current)==null||i.scrollTo({left:0,top:0,behavior:"auto"}),_e.current=0},[O,He,ot]);const at=p.useCallback(i=>{if(i instanceof HTMLElement){const d=i.closest('[data-testid="remote-monitor-node-wall"]');if(d instanceof HTMLDivElement)return d}return c.current},[]),Yn=p.useCallback(i=>i.scrollWidth>i.clientWidth+1||i.scrollHeight>i.clientHeight+1,[]),Ho=p.useCallback(i=>{if(i.button!==0&&i.button!==1)return;const d=i.target instanceof HTMLElement?i.target:null;if(d!=null&&d.closest('button,input,textarea,select,[contenteditable="true"],[contenteditable=""]'))return;const u=at(i.target);if(u){W.current={active:!0,pointerId:i.pointerId,startX:i.clientX,startY:i.clientY,lastX:i.clientX,lastY:i.clientY,scrollLeft:u.scrollLeft,scrollTop:u.scrollTop,didPan:!1,pageTriggered:!1},i.preventDefault(),i.stopPropagation();try{i.currentTarget.setPointerCapture(i.pointerId)}catch{}}},[at]),Ko=p.useCallback(i=>{const d=W.current;if(!(d!=null&&d.active)||d.pointerId!==i.pointerId)return;const u=at(i.target);if(!u)return;const f=i.clientX-d.startX,T=i.clientY-d.startY;if(!d.didPan&&Math.max(Math.abs(f),Math.abs(T))>=_l&&(d.didPan=!0,Pe.current=!0),d.didPan){u.scrollLeft=d.scrollLeft-f,u.scrollTop=d.scrollTop-T;const C=Math.abs(T)>=Math.abs(f)?T:f;!d.pageTriggered&&P>1&&!Yn(u)&&Math.abs(C)>=Fl&&(d.pageTriggered=!0,Tt(C<0?1:-1,"drag"))}d.lastX=i.clientX,d.lastY=i.clientY,i.preventDefault(),i.stopPropagation()},[Yn,Tt,at,P]),It=p.useCallback(i=>{const d=W.current;if(!(!(d!=null&&d.active)||d.pointerId!==i.pointerId)){W.current=null;try{i.currentTarget.releasePointerCapture(i.pointerId)}catch{}if(d.didPan){const u=at(i.target);g.emit("remoteMonitor.node.wallPan",{nodeId:e.id,source:"drag",dx:Math.round(d.lastX-d.startX),dy:Math.round(d.lastY-d.startY),scrollLeft:Math.round((u==null?void 0:u.scrollLeft)??0),scrollTop:Math.round((u==null?void 0:u.scrollTop)??0),pageIndex:O,pageCount:P}),i.preventDefault(),i.stopPropagation()}}},[O,at,e.id,P]),Vr=p.useCallback(i=>{const d=i.target instanceof HTMLElement?i.target:null;if(d!=null&&d.closest('[data-input-active="true"]'))return;const u=at(i.target);if(!u)return;const f=u.scrollLeft,T=u.scrollTop;u.scrollLeft+=i.deltaX,u.scrollTop+=i.deltaY;const C=u.scrollLeft!==f||u.scrollTop!==T;!C&&P>1&&Math.abs(i.deltaY)>=Math.abs(i.deltaX)&&(_e.current+=i.deltaY,Math.abs(_e.current)>=Bl&&(Tt(_e.current>0?1:-1,"wheel"),_e.current=0)),g.emit("remoteMonitor.node.wallPan",{nodeId:e.id,source:"wheel",dx:Math.round(i.deltaX),dy:Math.round(i.deltaY),moved:C,scrollLeft:Math.round(u.scrollLeft),scrollTop:Math.round(u.scrollTop),pageIndex:O,pageCount:P}),i.preventDefault(),i.stopPropagation()},[Tt,O,at,e.id,P]),qr=p.useCallback(i=>{i.stopPropagation();const d=Jl(i.target.value);oo(u=>u===d?u:(g.emit("remoteMonitor.node.groupMode",{nodeId:e.id,from:u,to:d,projectedCount:z.length,visibleBudget:Me}),d)),Ze(0)},[z.length,e.id]),Wr=p.useCallback(i=>{i.stopPropagation();const d=i.target.value.slice(0,64);no(u=>u===d?u:(g.emit("remoteMonitor.node.filter",{nodeId:e.id,reason:"search",searchText:d.trim(),visibilityFilter:Ae,capabilityFilter:Ee,projectedCount:z.length,visibleBudget:Me}),d)),Ze(0)},[Ee,z.length,e.id,Ae]),Hr=p.useCallback(i=>{i.stopPropagation();const d=Zl(i.target.value);ao(u=>u===d?u:(g.emit("remoteMonitor.node.filter",{nodeId:e.id,reason:"visibility",searchText:y,from:u,to:d,visibilityFilter:d,capabilityFilter:Ee,projectedCount:z.length,visibleBudget:Me}),d)),Ze(0)},[Ee,z.length,e.id,y]),Kr=p.useCallback(i=>{i.stopPropagation();const d=ec(i.target.value);ro(u=>u===d?u:(g.emit("remoteMonitor.node.filter",{nodeId:e.id,reason:"capability",searchText:y,visibilityFilter:Ae,from:u,to:d,capabilityFilter:d,projectedCount:z.length,visibleBudget:Me}),d)),Ze(0)},[z.length,e.id,y,Ae]),Xr=p.useCallback((i,d)=>{i.stopPropagation();const u=it(d);if(!u||!o)return;const f=qt(d);o({sourceNodeId:e.id,deviceId:u,deviceName:ft(d),platform:Kt(d),connected:d.connected===!0,baseUrl:l.baseUrl,framePath:f==null?void 0:f.framePath,frameUrl:f==null?void 0:f.frameUrl,dataUrl:f==null?void 0:f.dataUrl,frameSeq:f==null?void 0:f.frameSeq}),g.emit("remoteMonitor.node.controlNode.create",{nodeId:e.id,deviceId:u,source:l.source})},[e.id,o,l.baseUrl,l.source]),se=p.useCallback(async(i="manual")=>{const d=++be.current,u=j();if(b(f=>({...f,loading:!0,baseUrl:u})),!At()){const f=bo(n,r);b({source:"blocked",loading:!1,message:"Hosted LocalBridge access is gated.",baseUrl:u,devices:f}),g.emit("remoteMonitor.node.preview",{nodeId:e.id,reason:"hosted-localbridge-gated",total:f.length});return}try{const f=await Rn(u);if(d!==be.current)return;if(f.state!=="connected"){const Te=bo(n,r);b({source:"unavailable",loading:!1,message:f.message||"LocalBridge is unavailable.",baseUrl:u,bridge:f,devices:Te}),g.emit("remoteMonitor.node.preview",{nodeId:e.id,reason:"localbridge-unavailable",total:Te.length});return}const T=or(f.status),C=el(T,u).catch(Te=>{g.emit("remoteMonitor.node.agent.status",{nodeId:e.id,reason:i,ok:!1,error:Te instanceof Error?Te.message:String(Te)})}),[R,$,G]=await Promise.all([nr(T,u),ar(T,u,{includeDataUrl:!1}),C]);if(d!==be.current)return;const ge=Array.isArray($.devices)?$.devices:[];b({source:"bridge",loading:!1,message:R.started?"RemoteHub online.":R.enabled===!1?R.lastError||"RemoteHub adapter is not configured.":"RemoteHub available.",baseUrl:u,bridge:f,auth:T,hub:R,agent:G,latestTaskBatch:$.latestTaskBatch,recentTaskBatches:Array.isArray($.recentTaskBatches)?$.recentTaskBatches:[],devices:ge}),g.emit("remoteMonitor.node.refresh",{nodeId:e.id,reason:i,total:$.total??ge.length,connected:ge.filter(Te=>Te.connected===!0).length,agentStatus:w(G==null?void 0:G.status),agentRunning:(G==null?void 0:G.running)===!0}),G&&g.emit("remoteMonitor.node.agent.status",{nodeId:e.id,reason:i,ok:!0,status:w(G.status),running:G.running===!0,ready:G.ready===!0})}catch(f){if(d!==be.current)return;const T=bo(n,r);b({source:"unavailable",loading:!1,message:f instanceof Error?f.message:String(f),baseUrl:u,devices:T}),g.emit("remoteMonitor.node.preview",{nodeId:e.id,reason:"remotehub-error",total:T.length})}},[r,n,e.id]);p.useEffect(()=>{se("mount")},[se]);const Ut=p.useCallback((i,d,u)=>{const f=Br(M.current,i);if(!f)return!1;const{cached:T,scope:C}=f;return Ro(d,T,x.current,v.current).then(R=>{R&&g.emit("remoteMonitor.node.frameCache",{nodeId:e.id,deviceId:i,frameSeq:pt(T.metadata),scope:C,reason:u})}),!0},[e.id]),Yr=p.useCallback((i,d)=>{i&&(d?(k.current.set(i,d),Ut(i,d,"canvas-attach")):k.current.delete(i))},[Ut]);p.useEffect(()=>{for(const i of he){const d=it(i),u=k.current.get(d);if(!u)continue;const f=qt(i),T=En(f);l.source==="bridge"&&T?bn(u,d,f,l.baseUrl,x.current,v.current,M.current).then(C=>{C.painted||C.busy||(C.staleDropped&&g.emit("remoteMonitor.node.frameStaleDropped",{nodeId:e.id,deviceId:d,frameSeq:C.frameSeq,previous:C.previous,source:"projection"}),!(l.source==="bridge"&&Ut(d,u,"projection-rerender"))&&Mo(u,i,l.source))}):l.source==="bridge"&&Ut(d,u,"projection-rerender")||Mo(u,i,l.source)}},[e.id,Ut,l.baseUrl,l.source,he]);const Xo=p.useCallback(async(i,d)=>{const u=w(i.deviceId).trim();if(!u)return;const f=w(i.streamId).trim(),T=Number(i.frameSeq||0)||0,C=Ln(v.current,M.current,u),R=V.current.get(u)||"",$=!!(f&&R&&f!==R);if($&&(v.current.delete(u),g.emit("remoteMonitor.node.frameStreamReset",{nodeId:e.id,deviceId:u,fromStreamId:R,toStreamId:f,previous:C,frameSeq:T})),!$&&T>0&&T<=C){g.emit("remoteMonitor.node.frameStaleDropped",{nodeId:e.id,deviceId:u,frameSeq:T,previous:C,source:"ws"});return}const G=dr(i,d.byteLength);G.level!=="nominal"&&g.emit("remoteMonitor.node.framePressure",{nodeId:e.id,deviceId:u,frameSeq:T,streamId:f,...G});const ge=_r(M.current,u,i,d),Te=k.current.get(u);if(Te){if(x.current.has(u)){g.emit("remoteMonitor.node.frameCache",{nodeId:e.id,deviceId:u,frameSeq:T,scope:"local",reason:"decode-pending"});return}x.current.add(u);try{await jn(Te,ge.metadata,ge.payload)&&(T>0&&v.current.set(u,T),f&&V.current.set(u,f),E.current+=1,E.current%12===1&&g.emit("remoteMonitor.node.framePainted",{nodeId:e.id,deviceId:u,frameSeq:T,streamId:i.streamId||"",painted:E.current,source:"ws"}))}catch{}finally{x.current.delete(u);const je=M.current.get(u),Ke=pt(je==null?void 0:je.metadata),da=v.current.get(u)||0,ua=k.current.get(u);je&&ua&&(Ke<=0?da<=0:Ke>da)&&Ro(ua,je,x.current,v.current).then(hi=>{hi&&(E.current+=1,g.emit("remoteMonitor.node.frameCache",{nodeId:e.id,deviceId:u,frameSeq:Ke,scope:"local",reason:"latest-pending"}),g.emit("remoteMonitor.node.framePainted",{nodeId:e.id,deviceId:u,frameSeq:Ke,streamId:je.metadata.streamId||"",painted:E.current,source:"ws-cache"}))})}}},[e.id]);p.useEffect(()=>{if(l.source!=="bridge"||!m||!zo)return;const i=Ra(ot);if(i.length===0)return;let d=!1,u=null,f=0;const T=()=>{var C,R;if(!d){ue.current=!1;try{u=new WebSocket(Ar(l.baseUrl,zo,(R=(C=l.bridge)==null?void 0:C.status)==null?void 0:R.bridgeToken,i)),u.binaryType="arraybuffer"}catch($){g.emit("remoteMonitor.node.frameWs",{nodeId:e.id,ok:!1,error:$ instanceof Error?$.message:String($)});return}u.onopen=()=>{ue.current=!0,B.current=performance.now(),g.emit("remoteMonitor.node.frameWs",{nodeId:e.id,ok:!0,deviceCount:i.length,fps:Ia}),u==null||u.send(JSON.stringify({type:"subscribe",deviceIds:i,autoStartLive:!0,fps:Ia,maxWidth:640,maxHeight:360,quality:55,mode:"remote-fast"}))},u.onmessage=async $=>{if(!d){if(B.current=performance.now(),$.data instanceof ArrayBuffer){const G=wo($.data);G&&await Xo(G.metadata,G.payload);return}if($.data instanceof Blob){const G=wo(await $.data.arrayBuffer());G&&await Xo(G.metadata,G.payload)}}},u.onerror=()=>{g.emit("remoteMonitor.node.frameWs",{nodeId:e.id,ok:!1,reason:"socket-error"})},u.onclose=()=>{ue.current=!1,d||(f=window.setTimeout(T,1500))}}};return T(),()=>{d=!0,ue.current=!1,window.clearTimeout(f),u==null||u.close()}},[e.id,Xo,zo,l.baseUrl,(ia=(ra=l.bridge)==null?void 0:ra.status)==null?void 0:ia.bridgeToken,l.source,m,ot]),p.useEffect(()=>{if(l.source!=="bridge"||!m)return;const i=Ra(ot);if(i.length===0)return;let d=!1,u=!1;const f=async()=>{var R;if(!(d||u)&&!(ue.current&&performance.now()-B.current<kr)){u=!0;try{const $=await rr(i,l.auth,l.baseUrl);if(d||$.ok===!1)return;let G=0,ge=0;for(const Te of $.frames||[]){const je=String(Te.deviceId||"").trim();if(!je)continue;const Ke=await bn(k.current.get(je),je,Or(Te),l.baseUrl,x.current,v.current,M.current);Ke.painted&&(G+=1),Ke.staleDropped&&(ge+=1,g.emit("remoteMonitor.node.frameStaleDropped",{nodeId:e.id,deviceId:je,frameSeq:Ke.frameSeq,previous:Ke.previous,source:"snapshot"}))}g.emit("remoteMonitor.node.frameSnapshot",{nodeId:e.id,deviceCount:i.length,frameCount:((R=$.frames)==null?void 0:R.length)||0,painted:G,staleDropped:ge})}catch{}finally{u=!1}}},T=window.setTimeout(f,200),C=window.setInterval(f,Ll);return()=>{d=!0,window.clearTimeout(T),window.clearInterval(C)}},[e.id,l.auth,l.baseUrl,l.source,m,ot]),p.useEffect(()=>{Q(!1),ne("locked"),ae("Remote input locked.")},[H,l.source]),p.useEffect(()=>{!S||Le||(Q(!1),ne("unavailable"),ae(nt||"Remote input unavailable."),g.emit("remoteMonitor.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"control-unavailable",deviceId:H}))},[Le,nt,S,e.id,H]),p.useEffect(()=>{var u,f,T;if(!S){(u=F.current)==null||u.close(),F.current=null,ne("locked");return}if(!Le||!H){ne("unavailable"),ae(nt||"Remote input unavailable.");return}let i=!1,d=null;ne("connecting"),ae("Connecting remote input adapter...");try{d=new WebSocket(Mr(l.baseUrl,$o,(T=(f=l.bridge)==null?void 0:f.status)==null?void 0:T.bridgeToken)),F.current=d}catch(C){const R=C instanceof Error?C.message:String(C);ne("error"),ae(R),g.emit("remoteMonitor.node.input.ws",{nodeId:e.id,ok:!1,deviceId:H,error:R});return}return d.onopen=()=>{i||(ne("ready"),ae("Remote input ready."),g.emit("remoteMonitor.node.input.ws",{nodeId:e.id,ok:!0,deviceId:H}))},d.onmessage=C=>{if(i)return;const R=hr(String(C.data||"{}"));if(R){if(R.type==="RemoteInputSocketReady"){ne("ready");return}g.emit("remoteMonitor.node.input.result",{nodeId:e.id,ok:R.ok,deviceId:R.deviceId||H,inputType:R.inputType,error:R.error}),!R.ok||R.error?ae(R.error||"Remote input failed."):/^pointermove$/i.test(R.inputType)||ae(`${R.inputType||"Input"} queued.`)}},d.onerror=()=>{i||(ne("error"),ae("Remote input socket error."),g.emit("remoteMonitor.node.input.ws",{nodeId:e.id,ok:!1,deviceId:H,reason:"socket-error"}))},d.onclose=()=>{i||(F.current=null,ne("error"),ae("Remote input socket closed."),g.emit("remoteMonitor.node.input.ws",{nodeId:e.id,ok:!1,deviceId:H,reason:"socket-closed"}))},()=>{i=!0,F.current===d&&(F.current=null),d==null||d.close()}},[Le,nt,S,e.id,$o,H,l.baseUrl,(la=(sa=l.bridge)==null?void 0:sa.status)==null?void 0:la.bridgeToken]),p.useEffect(()=>{if(!S)return;const i=d=>{d.key==="Escape"&&(d.preventDefault(),Q(!1),ae("Remote input locked."),g.emit("remoteMonitor.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"escape",deviceId:H}))};return window.addEventListener("keydown",i,!0),()=>window.removeEventListener("keydown",i,!0)},[S,e.id,H]);const Qr=p.useCallback(i=>{i.stopPropagation(),tr(!0),g.emit("remoteMonitor.node.hostedAccess.enabled",{nodeId:e.id}),se("hosted-access-enabled")},[e.id,se]),Qn=p.useCallback(i=>{i.stopPropagation(),se("manual")},[se]),Jr=p.useCallback(async i=>{var d,u,f;if(i.stopPropagation(),!po){de(uo||"RemoteAgent connect unavailable.");return}mt("connect"),de("Connecting RemoteAgent...");try{const T=await tl(Gt,l.auth,l.baseUrl);T.agent&&b(R=>R.source==="bridge"?{...R,agent:T.agent,message:R.message}:R);const C=T.ok===!0;de(C?T.alreadyRunning===!0?"RemoteAgent already running.":T.skipped===!0?T.reason||"RemoteAgent connect skipped.":"RemoteAgent connect requested.":T.error||"RemoteAgent connect failed."),g.emit("remoteMonitor.node.agent.connect",{nodeId:e.id,ok:C,alreadyRunning:T.alreadyRunning===!0,skipped:T.skipped===!0,reason:T.reason||"",status:w((d=T.agent)==null?void 0:d.status),managerCount:((u=Gt.managerCandidates)==null?void 0:u.length)??0,error:T.error||""}),C&&await se("agent-connect")}catch(T){const C=T instanceof Error?T.message:String(T);de(C),g.emit("remoteMonitor.node.agent.connect",{nodeId:e.id,ok:!1,managerCount:((f=Gt.managerCandidates)==null?void 0:f.length)??0,error:C})}finally{mt("")}},[po,e.id,se,uo,Gt,l.auth,l.baseUrl]),Zr=p.useCallback(async i=>{var d;if(i.stopPropagation(),!mo){de("RemoteAgent is not running.");return}mt("disconnect"),de("Stopping RemoteAgent...");try{const u=await ol("react-remote-monitor-manual",l.auth,l.baseUrl);u.agent&&b(T=>T.source==="bridge"?{...T,agent:u.agent,message:T.message}:T);const f=u.ok===!0;de(f?"RemoteAgent stopped.":u.error||"RemoteAgent stop failed."),g.emit("remoteMonitor.node.agent.disconnect",{nodeId:e.id,ok:f,status:w((d=u.agent)==null?void 0:d.status),error:u.error||""}),f&&await se("agent-disconnect")}catch(u){const f=u instanceof Error?u.message:String(u);de(f),g.emit("remoteMonitor.node.agent.disconnect",{nodeId:e.id,ok:!1,error:f})}finally{mt("")}},[mo,e.id,se,l.auth,l.baseUrl]),ei=p.useCallback(async i=>{var u;i.stopPropagation();const d=jr(l.hub);try{const f=await Mn(d);we("Connect command copied."),g.emit("remoteMonitor.node.connectCommand.copy",{nodeId:e.id,ok:!0,method:f,source:l.source,hasPairPreview:!!((u=l.hub)!=null&&u.pairTokenPreview)})}catch(f){we(f instanceof Error?f.message:"Clipboard is unavailable."),g.emit("remoteMonitor.node.connectCommand.copy",{nodeId:e.id,ok:!1})}},[e.id,l.hub,l.source]),vt=p.useCallback(async(i,d)=>{if(l.source!=="bridge"||Ce.current)return!1;Ce.current=!0,we(i?"Requesting host target...":"Clearing host target...");try{const u=await fa(e.id,i,l.auth,l.baseUrl,{leaseMs:$t});if(u.ok===!0){const f=i&&u.active===!0;Ma(e.id,f),ht(f)}return we(u.ok===!0?u.active?"This monitor node is the host target.":"Host target cleared.":u.error||"Host target update failed."),g.emit("remoteMonitor.node.hostTarget",{nodeId:e.id,reason:d,autoHost:me,ok:u.ok===!0,active:u.active===!0}),await se("host-target"),u.ok===!0&&(i?u.active===!0:u.active!==!0)}catch(u){return we(u instanceof Error?u.message:String(u)),g.emit("remoteMonitor.node.hostTarget",{nodeId:e.id,reason:d,autoHost:me,ok:!1}),!1}finally{Ce.current=!1}},[me,e.id,se,l.auth,l.baseUrl,l.source]),ti=p.useCallback(i=>{i.stopPropagation(),vt(!ie,"manual")},[ie,vt]),oi=p.useCallback(i=>{i.stopPropagation();const d=!me;Ma(e.id,d),ht(d),we(d?"Auto Host enabled for this monitor.":"Auto Host disabled."),g.emit("remoteMonitor.node.autoHost",{nodeId:e.id,enabled:d,source:l.source}),!d&&ie&&vt(!1,"auto-host-disabled")},[me,ie,e.id,vt,l.source]);p.useEffect(()=>{if(l.source!=="bridge"||!me||ie||ee.current)return;if(!tn(e.id)){ht(!1);return}let i=!1;return ee.current=!0,we("Restoring Auto Host..."),g.emit("remoteMonitor.node.autoHost.restore",{nodeId:e.id,requested:!0,source:l.source}),vt(!0,"auto-host-restore").then(d=>{i||(g.emit("remoteMonitor.node.autoHost.restore",{nodeId:e.id,ok:d,source:l.source}),d||we("Auto Host restore failed."))}).finally(()=>{ee.current=!1}),()=>{i=!0}},[me,ie,e.id,vt,l.source]),p.useEffect(()=>{if(l.source!=="bridge"||!ie)return;let i=!1;const d=async()=>{if(!(i||h.current)){h.current=!0;try{const f=await fa(e.id,!0,l.auth,l.baseUrl,{leaseMs:$t});g.emit("remoteMonitor.node.hostTarget.renew",{nodeId:e.id,ok:f.ok===!0,active:f.active===!0,leaseMs:$t}),!i&&(f.ok!==!0||f.active!==!0)&&(we(f.error||"Host target renewal lost ownership."),await se("host-target-renew"))}catch(f){g.emit("remoteMonitor.node.hostTarget.renew",{nodeId:e.id,ok:!1,active:!1,leaseMs:$t,error:f instanceof Error?f.message:String(f)}),i||we(f instanceof Error?f.message:String(f))}finally{h.current=!1}}},u=window.setInterval(()=>{d()},fo);return g.emit("remoteMonitor.node.hostTarget.renew.timer",{nodeId:e.id,active:!0,intervalMs:fo,leaseMs:$t}),()=>{i=!0,window.clearInterval(u),g.emit("remoteMonitor.node.hostTarget.renew.timer",{nodeId:e.id,active:!1})}},[ie,e.id,se,l.auth,l.baseUrl,l.source]),p.useEffect(()=>{if(l.source!=="bridge"||!gt||!ke){gt||(L.current="",Y.current=0);return}let i=!1,d=0;L.current!==ke&&(L.current=ke,Y.current=0);const u=f=>{window.clearTimeout(d),d=window.setTimeout(async()=>{if(i||L.current!==ke)return;const T=Y.current;if(T>=Rt){g.emit("remoteMonitor.node.task.follow",{nodeId:e.id,active:!1,batchKey:ke,tick:T,maxTicks:Rt,reason:"max-ticks"});return}const C=T+1;Y.current=C,g.emit("remoteMonitor.node.task.follow",{nodeId:e.id,active:!0,batchKey:ke,tick:C,maxTicks:Rt}),await se("task-follow"),!i&&L.current===ke&&Y.current<Rt&&u(Io)},Math.max(0,f))};return g.emit("remoteMonitor.node.task.follow",{nodeId:e.id,active:!0,batchKey:ke,intervalMs:Io,maxTicks:Rt,reason:"start"}),u(Nl),()=>{i=!0,window.clearTimeout(d),g.emit("remoteMonitor.node.task.follow",{nodeId:e.id,active:!1,batchKey:ke,tick:Y.current,reason:"cleanup"})}},[e.id,se,l.source,gt,ke]);const ni=p.useCallback(i=>{if(i.stopPropagation(),S){Q(!1),ae("Remote input locked."),g.emit("remoteMonitor.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"manual",deviceId:H});return}if(!Le){ne("unavailable"),ae(nt||"Remote input unavailable."),g.emit("remoteMonitor.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"unavailable",deviceId:H});return}Q(!0),ae("Connecting remote input adapter..."),g.emit("remoteMonitor.node.input.lock",{nodeId:e.id,unlocked:!0,reason:"manual",deviceId:H})},[Le,nt,S,e.id,H]),Ve=p.useCallback(i=>{var $;const d=F.current;if(!S||!Le||!H||(d==null?void 0:d.readyState)!==WebSocket.OPEN){i.ack&&ae(S?"Remote input socket is not ready.":"Remote input locked.");return}const u=`remote-node-input-${Date.now()}-${++J.current}`,{ack:f,...T}=i,C=mr({requestId:u,deviceId:H,ack:f,controlLeaseId:($=l.hub)==null?void 0:$.hostTargetLeaseId,input:T});if(!C){f&&ae("Remote input payload is invalid.");return}const R=w(C.input.type);try{d.send(JSON.stringify(C));const G=++Z.current;(C.ack||G%24===1)&&g.emit("remoteMonitor.node.input.sent",{nodeId:e.id,deviceId:H,inputType:R,sampled:!C.ack,sent:G})}catch(G){const ge=G instanceof Error?G.message:String(G);ne("error"),ae(ge),g.emit("remoteMonitor.node.input.ws",{nodeId:e.id,ok:!1,deviceId:H,error:ge})}},[Le,S,e.id,H,(ca=l.hub)==null?void 0:ca.hostTargetLeaseId]);p.useEffect(()=>{if(typeof document>"u")return;const i=d=>{const u=d.detail;if(!u||typeof u!="object")return;const f=w(u.nodeId);if(f&&f!==e.id)return;const T=w(u.deviceId);if(T&&T!==H)return;const C=u.input;!C||typeof C!="object"||Array.isArray(C)||Ve({...C,ack:u.ack!==!1})};return document.addEventListener(va,i),()=>document.removeEventListener(va,i)},[e.id,H,Ve]);const Ct=p.useCallback((i,d,u,f=!1)=>{const T=So(i,f);return T?(Ve({type:d,...T,button:Pr(i.button),ack:u}),!0):!1},[Ve]),ai=p.useCallback((i,d,u)=>{if(i.stopPropagation(),Fe(d),!u){Ho(i);return}if(Ct(i,"pointerDown",!0,!1)){i.preventDefault(),i.currentTarget.focus();try{i.currentTarget.setPointerCapture(i.pointerId)}catch{}}},[Ct,Ho]),ri=p.useCallback((i,d)=>{var C,R;if(!d){Ko(i);return}const u=performance.now();if(u-pe.current<Tr)return;pe.current=u;const f=((R=(C=i.currentTarget).hasPointerCapture)==null?void 0:R.call(C,i.pointerId))===!0;Ct(i,"pointerMove",!1,f)&&(i.preventDefault(),i.stopPropagation())},[Ct,Ko]),ii=p.useCallback((i,d)=>{if(!d){It(i);return}i.preventDefault(),i.stopPropagation();try{i.currentTarget.releasePointerCapture(i.pointerId)}catch{}Ct(i,"pointerUp",!0,!0)},[Ct,It]),si=p.useCallback((i,d)=>{d||It(i)},[It]),li=p.useCallback((i,d)=>{if(!d)return;const u=So(i,!1);u&&(Ve({type:"wheel",...u,deltaX:i.deltaX,deltaY:i.deltaY,ack:!0}),i.preventDefault(),i.stopPropagation())},[Ve]),ci=p.useCallback((i,d,u)=>{if(!u){(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),i.stopPropagation(),Fe(d));return}i.key!=="Escape"&&(i.preventDefault(),i.stopPropagation(),Ve({type:"keyDown",key:i.key,code:i.code,repeat:i.repeat,ack:!0}))},[Ve]),di=p.useCallback((i,d)=>{!d||i.key==="Escape"||(i.preventDefault(),i.stopPropagation(),Ve({type:"keyUp",key:i.key,code:i.code,repeat:!1,ack:!0}))},[Ve]),Yo=p.useCallback(async(i,d="selected")=>{var R;if(i.preventDefault(),i.stopPropagation(),l.source!=="bridge"){Ue("LocalBridge is not connected.");return}const u=Re.trim();if(!u){Ue("Remote task is empty.");return}if(d==="selected"&&(!H||!Vo||(oe==null?void 0:oe.connected)!==!0)){Ue("Selected device cannot accept remote tasks.");return}if(d==="all"&&io.length<=0){Ue("No task-capable connected devices are available.");return}if(d==="ai"&&so.length<=0){Ue("No AI assist devices are connected.");return}const f=d==="ai"?"ai-assist":"task-only",T=((R=u.split(/\r?\n/)[0])==null?void 0:R.slice(0,96))||"Remote task",C=d==="ai"?so:io;to(d),Ue(d==="selected"?"Queueing selected task...":"Queueing fleet task...");try{const $=d==="selected"?await ir(H,{instruction:u,title:T,approvalLevel:f},l.auth,l.baseUrl):await nl({instruction:u,title:T,approvalLevel:f,deviceIds:C,allConnected:!1},l.auth,l.baseUrl),G=$.ok===!0,ge=d==="selected"?G?1:0:Number("queued"in $?$.queued:0);Ue(G?`Queued ${ge||1} remote task${(ge||1)===1?"":"s"}.`:$.error||"Remote task queue failed."),g.emit("remoteMonitor.node.task.queue",{nodeId:e.id,mode:d,ok:G,queued:ge,approvalLevel:f,deviceId:d==="selected"?H:"",targetCount:d==="selected"?1:C.length,batchId:"batchId"in $?$.batchId:"",error:$.error||""}),G&&(eo(""),await se("task-queued"))}catch($){const G=$ instanceof Error?$.message:String($);Ue(G),g.emit("remoteMonitor.node.task.queue",{nodeId:e.id,mode:d,ok:!1,approvalLevel:f,deviceId:d==="selected"?H:"",targetCount:d==="selected"?1:C.length,error:G})}finally{to("")}},[Ft,so,e.id,se,Vo,oe==null?void 0:oe.connected,H,l.auth,l.baseUrl,l.source,io,Re]),ui=a.jsxs("div",{className:"node-remote-monitor__head-actions",children:[a.jsx("i",{"aria-label":`Remote route ${lo}`}),a.jsxs("span",{className:"node-remote-monitor__head-status","data-testid":"remote-monitor-node-agent-status","data-agent-status":Bt,children:["AGENT ",a.jsx("strong",{children:Bt})]}),a.jsxs("span",{className:`node-remote-monitor__head-status node-remote-monitor__route-status is-${re.tone}`,"data-testid":"remote-monitor-node-registry-route","data-registry-route":re.status,"data-account-route-ready":re.accountRouteReady?"true":"false","data-registry-migration-blocked":re.migrationBlocked?"true":"false",title:re.title,children:["ROUTE ",a.jsx("strong",{children:re.value})]}),l.source==="bridge"?a.jsxs(a.Fragment,{children:[a.jsxs("button",{type:"button","data-testid":"remote-monitor-node-host",onClick:ti,children:[a.jsx(ko,{size:12}),ie?"Clear Host":"Set Host"]}),a.jsxs("button",{type:"button",className:me?"is-active":"","data-testid":"remote-monitor-node-auto-host","data-auto-host-active":me?"true":"false",onClick:oi,title:me?"Disable Auto Host restore for this monitor":"Remember this monitor as the Auto Host target",children:[a.jsx(ko,{size:12}),"Auto"]}),a.jsxs("button",{type:"button","data-testid":"remote-monitor-node-agent-connect",onClick:Jr,disabled:!po,title:po?"Connect managed RemoteAgent":uo,children:[a.jsx(xi,{size:12,className:Se==="connect"?"spin-icon":""}),"Start"]}),a.jsxs("button",{type:"button","data-testid":"remote-monitor-node-agent-disconnect",onClick:Zr,disabled:!mo,title:mo?"Stop managed RemoteAgent":"RemoteAgent is not running",children:[a.jsx(wi,{size:12,className:Se==="disconnect"?"spin-icon":""}),"Stop"]})]}):l.source==="blocked"?a.jsxs("button",{type:"button",onClick:Qr,children:[a.jsx(ko,{size:12}),"Enable"]}):a.jsxs("button",{type:"button",onClick:Qn,children:[a.jsx(vo,{size:12,className:l.loading?"spin-icon":""}),"Refresh"]})]}),pi=a.jsxs("form",{className:"node-remote-monitor__taskbar","data-testid":"remote-monitor-node-taskbar",onSubmit:i=>Yo(i,"selected"),children:[a.jsx("input",{"aria-label":"Remote task",value:Re,maxLength:1200,onChange:i=>eo(i.target.value),onPointerDown:i=>i.stopPropagation(),placeholder:oe?`Task for ${ft(oe)}`:"Remote task"}),a.jsxs("button",{type:"submit",disabled:!$n,title:$n?"Queue task for selected device":"Selected device cannot accept remote tasks",children:[a.jsx(nn,{size:12,className:Je==="selected"?"spin-icon":""}),"Selected"]}),a.jsxs("button",{type:"button",disabled:!Vn,title:Vn?"Queue task for connected devices":"No connected devices can accept tasks",onClick:i=>Yo(i,"all"),children:[a.jsx(nn,{size:12,className:Je==="all"?"spin-icon":""}),"All"]}),a.jsxs("button",{type:"button",disabled:!qn,title:qn?"Queue AI assist task for connected AI devices":"No AI assist device is connected",onClick:i=>Yo(i,"ai"),children:[a.jsx(Si,{size:12,className:Je==="ai"?"spin-icon":""}),"AI"]})]}),mi=a.jsxs("div",{className:"node-remote-monitor__footer",children:[a.jsxs("div",{className:"node-remote-monitor__footer-scale","data-testid":"remote-monitor-node-tile-scale","data-tile-scale-index":He,"data-tile-scale":Ot,children:[a.jsx("button",{type:"button","aria-label":"Shrink remote monitor tiles","data-testid":"remote-monitor-node-tile-shrink",disabled:He<=0,onClick:i=>Xn(i,-1),children:a.jsx(Ri,{size:12})}),a.jsx("button",{type:"button","aria-label":"Grow remote monitor tiles","data-testid":"remote-monitor-node-tile-grow",disabled:He>=Vt.length-1,onClick:i=>Xn(i,1),children:a.jsx(ja,{size:12})})]}),a.jsxs("label",{className:"node-remote-monitor__footer-group","data-testid":"remote-monitor-node-group","data-group-mode":ze,children:[a.jsx("span",{children:"GROUP"}),a.jsx("select",{"aria-label":"Remote monitor grouping","data-testid":"remote-monitor-node-group-mode",value:ze,onPointerDown:i=>i.stopPropagation(),onChange:qr,children:Cr.map(i=>a.jsx("option",{value:i,children:tc(i)},i))})]}),a.jsxs("label",{className:"node-remote-monitor__footer-filter","data-testid":"remote-monitor-node-filter","data-filter-active":N?"true":"false",children:[a.jsx("span",{children:"FILTER"}),a.jsx("input",{"aria-label":"Remote monitor search","data-testid":"remote-monitor-node-filter-text",value:Dt,maxLength:64,onPointerDown:i=>i.stopPropagation(),onChange:Wr,placeholder:"Any"}),a.jsx("select",{"aria-label":"Remote monitor visibility filter","data-testid":"remote-monitor-node-visibility-filter",value:Ae,onPointerDown:i=>i.stopPropagation(),onChange:Hr,children:xr.map(i=>a.jsx("option",{value:i,children:oc(i)},i))}),a.jsx("select",{"aria-label":"Remote monitor capability filter","data-testid":"remote-monitor-node-capability-filter",value:Ee,onPointerDown:i=>i.stopPropagation(),onChange:Kr,children:wr.map(i=>a.jsx("option",{value:i,children:nc(i)},i))})]}),a.jsxs("div",{className:"node-remote-monitor__footer-status",children:[a.jsxs("span",{children:[a.jsx("i",{})," HUB ",a.jsx("strong",{children:Uo})]}),a.jsxs("span",{children:["CONNECTED ",a.jsxs("strong",{children:[_t,"/",et]})]}),a.jsxs("span",{children:["TASK ",a.jsx("strong",{children:Bo})]}),a.jsxs("span",{children:["AI ",a.jsx("strong",{children:Ft})]}),a.jsxs("span",{children:["INPUT ",a.jsx("strong",{children:qo})]}),a.jsxs("span",{children:["PAGE ",a.jsx("strong",{children:Fo})]}),a.jsxs("span",{children:[a.jsx("i",{})," ROUTE ",a.jsx("strong",{children:lo})]}),a.jsxs("button",{type:"button","data-testid":"remote-monitor-node-copy-connect",onClick:ei,children:[a.jsx(Na,{size:12}),"Connect"]}),a.jsxs("button",{type:"button","data-testid":"remote-monitor-node-refresh",onClick:Qn,children:[a.jsx(vo,{size:12,className:l.loading?"spin-icon":""}),"Refresh"]}),l.source==="bridge"&&a.jsxs("button",{type:"button","data-testid":"remote-monitor-node-input",onClick:ni,disabled:!Le&&!S,title:S||Le?jt:nt,children:[S?a.jsx(Da,{size:12}):a.jsx(Oa,{size:12}),S?"Lock":"Unlock"]})]})]});return a.jsxs("div",{ref:s,className:"node-remote-monitor","data-testid":"remote-monitor-node","data-remote-source":l.source,"data-remote-canonical-total":et,"data-remote-connected":_t,"data-remote-projection":en,"data-remote-projected-count":D,"data-remote-visible-budget":Me,"data-remote-page-index":O,"data-remote-page-count":P,"data-remote-page-start":X,"data-remote-host-active":ie?"true":"false","data-remote-registry-route":re.status,"data-remote-registry-ready":re.accountRouteReady?"true":"false","data-remote-registry-migration-blocked":re.migrationBlocked?"true":"false","data-remote-registry-reason":re.reason,"data-remote-host-renew-ms":ie?fo:0,"data-remote-auto-host":me?"true":"false","data-remote-agent-status":Bt,"data-remote-agent-running":co?"true":"false","data-remote-agent-ready":Wo?"true":"false","data-remote-task-follow-active":gt?"true":"false","data-remote-task-follow-key":ke,"data-remote-task-follow-refresh-ms":gt?Io:0,"data-remote-transport-visible":m?"true":"false","data-remote-frame-subscription-active":m&&$e.length>0?"true":"false","data-remote-tile-scale-index":He,"data-remote-tile-scale":Ot,"data-remote-tile-min-width":Bn,"data-remote-tile-min-height":Gn,"data-remote-group-mode":ze,"data-remote-visible-group-count":_n,"data-remote-filter-text":y,"data-remote-filter-active":N?"true":"false","data-remote-visibility-filter":Ae,"data-remote-capability-filter":Ee,"data-remote-filtered-count":U.length,"data-disable-mindcanvas-wheel":"true",children:[a.jsxs("div",{className:"node-remote-monitor__surface",children:[a.jsx("div",{className:"node-remote-monitor__head",children:a.jsxs("div",{className:"node-remote-monitor__titlemark",children:[a.jsx("span",{children:a.jsx(Mi,{size:15})}),a.jsxs("div",{children:[a.jsx("small",{children:"REMOTE"}),a.jsx("strong",{children:"Multi Desktop Monitor"})]})]})}),a.jsxs("div",{className:"node-remote-monitor__wall-shell",children:[a.jsxs("div",{ref:c,className:"node-remote-monitor__wall","data-testid":"remote-monitor-node-wall","data-page-index":O,"data-page-count":P,"data-page-start":X,"data-visible-devices":he.length,"data-visible-device-ids":tt.join(","),"data-visible-connected-devices":$e.length,"data-frame-subscription-device-ids":ot,"data-frame-subscription-active":m&&$e.length>0?"true":"false","data-transport-visible":m?"true":"false","data-canonical-device-count":et,"data-connected-device-count":_t,"data-wall-projection":en,"data-projected-device-count":D,"data-visible-budget":Me,"data-tile-scale-index":He,"data-tile-scale":Ot,"data-group-mode":ze,"data-visible-group-count":_n,"data-filter-text":y,"data-filter-active":N?"true":"false","data-visibility-filter":Ae,"data-capability-filter":Ee,"data-filtered-device-count":U.length,style:{"--remote-node-tile-min-width":`${Bn}px`,"--remote-node-tile-min-height":`${Gn}px`},onPointerDown:i=>Ho(i),onPointerMove:i=>Ko(i),onPointerUp:i=>It(i),onPointerCancel:i=>It(i),onWheel:Vr,children:[he.map(i=>{const d=it(i),u=ft(i),f=qt(i),T=d===H,C=S&&Le&&T;return a.jsxs("span",{className:`${i.connected===!0?"is-online":""} ${T?"is-selected":""} ${C?"is-input-active":""}`,"aria-label":`${u} remote desktop`,title:`${u} / ${Kt(i)}`,role:"button",tabIndex:C||T?0:-1,"data-device-id":d,"data-connected":i.connected===!0?"true":"false","data-frame-seq":(f==null?void 0:f.frameSeq)??0,"data-can-control":ce(i,"control")?"true":"false","data-can-dispatch-task":ce(i,"taskDispatch")?"true":"false","data-ai-assist":ce(i,"aiAssist")?"true":"false","data-input-active":C?"true":"false","data-group-mode":ze,"data-group-key":ac(i,ze),onClick:R=>{if(R.stopPropagation(),Pe.current){Pe.current=!1,R.preventDefault();return}Fe(d)},onDoubleClick:R=>Xr(R,i),onPointerDown:R=>ai(R,d,C),onPointerMove:R=>ri(R,C),onPointerUp:R=>ii(R,C),onPointerCancel:R=>si(R,C),onWheel:R=>li(R,C),onKeyDown:R=>ci(R,d,C),onKeyUp:R=>di(R,C),children:[a.jsx("canvas",{ref:R=>Yr(d,R)}),C&&a.jsxs("em",{children:[a.jsx(_a,{size:10}),"input"]}),a.jsx("small",{children:u})]},d)}),Array.from({length:Ur},(i,d)=>a.jsx("span",{"aria-label":`Remote desktop slot ${X+he.length+d+1}`,"data-placeholder-slot":"true"},`empty-${O}-${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:O<=0,onClick:i=>Kn(i,-1),children:a.jsx(Pi,{size:12})}),a.jsx("span",{className:"node-remote-monitor__pager-track",style:{"--remote-node-page-top":`${zr}%`,"--remote-node-page-height":`${Fn}%`},children:a.jsx("strong",{})}),a.jsx("button",{type:"button","aria-label":"Next monitor page",disabled:O>=P-1,onClick:i=>Kn(i,1),children:a.jsx(Ai,{size:12})})]})]})]}),a.jsxs("div",{className:"node-remote-monitor__external-rail","data-testid":"remote-monitor-node-external-rail",onPointerDown:i=>i.stopPropagation(),onClick:i=>i.stopPropagation(),children:[ui,pi,mi,a.jsx("p",{className:"node-remote-monitor__message",children:$r})]})]})}function ou({node:e,onPatch:t}){var oo,Dt,no,Ae,ao,Ee,ro,me,ht,et;const o=Rr(e),n=p.useRef(null),r=Sr(n,e.id,"control"),[s,c]=p.useState(()=>{var y;return{source:At()?"loading":"blocked",loading:!1,message:At()?"Remote device not checked yet.":"Hosted LocalBridge access is gated.",baseUrl:((y=e.metadata)==null?void 0:y.RemoteBaseUrl)||j(),device:St(e)}}),m=p.useRef(null),l=p.useRef(new Set),b=p.useRef(new Map),k=p.useRef(new Map),x=p.useRef(null),v=p.useRef(0),V=p.useRef(0),M=p.useRef(!1),F=p.useRef(0),J=p.useRef(0),Z=p.useRef(0),E=p.useRef(0),ue=p.useRef(e.metadata??{}),[B,pe]=p.useState(!1),[Ce,h]=p.useState("locked"),[ee,L]=p.useState("Remote input locked."),[Y,Oe]=p.useState(""),[W,Pe]=p.useState(!1),[_e,be]=p.useState(""),A=s.device,xe=A?ft(A):e.title||"Remote device",Fe=A?Kt(A):((oo=e.metadata)==null?void 0:oo.RemoteFleetDevicePlatform)||"unknown",S=Qa((Dt=s.bridge)==null?void 0:Dt.status),Q=Ja((no=s.bridge)==null?void 0:no.status),te=s.source==="bridge"&&!!o&&(A==null?void 0:A.connected)===!0&&!!Q&&ce(A,"control"),ne=A?ce(A,"taskDispatch"):!1,jt=s.source==="bridge"&&!!o&&(A==null?void 0:A.connected)===!0&&ne&&!!Y.trim()&&!W,ae=B?Er(Ce):te?"Locked":"Off",Do=_e||ee||s.message;p.useEffect(()=>{ue.current=e.metadata??{}},[e.metadata]);const we=p.useCallback((y,I)=>{const N=ue.current??{},U=Object.entries(I).filter(([D,P])=>N[D]!==P).map(([D])=>D);if(U.length===0)return;const z={...N,...I};ue.current=z,t(e.id,{metadata:z}),g.emit("remoteControl.node.metadata.patch",{nodeId:e.id,reason:y,keys:U})},[e.id,t]),Se=p.useCallback(async(y="manual")=>{const I=++E.current,N=j();if(c(U=>({...U,loading:!0,baseUrl:N})),!o){c({source:"unavailable",loading:!1,message:"Remote control node has no device id.",baseUrl:N,device:St(e)});return}if(!At()){c({source:"blocked",loading:!1,message:"Hosted LocalBridge access is gated.",baseUrl:N,device:St(e)}),g.emit("remoteControl.node.preview",{nodeId:e.id,reason:"hosted-localbridge-gated",deviceId:o});return}try{const U=await Rn(N);if(I!==E.current)return;if(U.state!=="connected"){c({source:"unavailable",loading:!1,message:U.message||"LocalBridge is unavailable.",baseUrl:N,bridge:U,device:St(e)});return}const z=or(U.status),[D,P]=await Promise.all([nr(z,N),ar(z,N,{includeDataUrl:!1})]);if(I!==E.current)return;const O=(Array.isArray(P.devices)?P.devices:[]).find(he=>it(he)===o),X=O||St(e);c({source:O?"bridge":"unavailable",loading:!1,message:O?`${ft(X)} ${X.connected===!0?"online.":"offline."}`:"Selected remote device is not in the current RemoteHub inventory.",baseUrl:N,bridge:U,auth:z,hub:D,device:X}),g.emit("remoteControl.node.refresh",{nodeId:e.id,reason:y,deviceId:o,found:!!O,connected:X.connected===!0})}catch(U){if(I!==E.current)return;c({source:"unavailable",loading:!1,message:U instanceof Error?U.message:String(U),baseUrl:N,device:St(e)})}},[o,e]);p.useEffect(()=>{Se("mount")},[Se]),p.useEffect(()=>{var y,I,N;we("snapshot",{SemanticType:"RemoteFleetDevice",RemoteFleetSchemaVersion:"remote-fleet-device@1",RemoteFleetDeviceId:o,RemoteFleetDeviceName:xe,RemoteFleetDevicePlatform:Fe,RemoteFleetDeviceConnected:String((A==null?void 0:A.connected)===!0),RemoteFleetDeviceCanControl:String(te),RemoteFleetDeviceCanDispatchTask:String(ne),RemoteFleetDeviceTasksQueued:String(((y=A==null?void 0:A.counters)==null?void 0:y.tasksQueued)||0),RemoteFleetSourceMonitorNodeId:((I=e.metadata)==null?void 0:I.RemoteFleetSourceMonitorNodeId)||"",RemoteInput:ae,RemoteTask:ne?"available":"unavailable",RemoteHub:s.source==="bridge"?((N=s.hub)==null?void 0:N.started)===!0?"Online":"Ready":s.source==="blocked"?"Gated":s.source,RemoteRoute:s.source==="bridge"?"Local":s.source==="blocked"?"Gated":"Preview",RemoteBaseUrl:s.baseUrl,AdapterState:s.source==="bridge"?"localbridge-connected":s.source==="blocked"?"adapter-gated":s.source})},[te,ne,A==null?void 0:A.connected,(Ae=A==null?void 0:A.counters)==null?void 0:Ae.tasksQueued,o,xe,ae,e.metadata,we,Fe,s.baseUrl,(ao=s.hub)==null?void 0:ao.started,s.source]);const mt=p.useCallback((y,I)=>{if(!o)return!1;const N=Br(k.current,o);if(!N)return!1;const{cached:U,scope:z}=N;return Ro(y,U,l.current,b.current).then(D=>{D&&g.emit("remoteControl.node.frameCache",{nodeId:e.id,deviceId:o,frameSeq:pt(U.metadata),scope:z,reason:I})}),!0},[o,e.id]);p.useEffect(()=>{const y=m.current;if(!y||!A)return;const I=qt(A),N=En(I);s.source==="bridge"&&N?Gr(y,N,s.baseUrl).catch(()=>Mo(y,A,s.source)):s.source==="bridge"&&mt(y,"projection-rerender")||Mo(y,A,s.source)},[A,mt,s.baseUrl,s.source]);const Nt=p.useCallback(async(y,I)=>{if(!o||w(y.deviceId).trim()!==o)return;const N=Number(y.frameSeq||0)||0,U=Ln(b.current,k.current,o);if(N>0&&N<=U){g.emit("remoteControl.node.frameStaleDropped",{nodeId:e.id,deviceId:o,frameSeq:N,previous:U,source:"ws"});return}const z=dr(y,I.byteLength);z.level!=="nominal"&&g.emit("remoteControl.node.framePressure",{nodeId:e.id,deviceId:o,frameSeq:N,...z});const D=_r(k.current,o,y,I),P=m.current;if(P){if(l.current.has(o)){g.emit("remoteControl.node.frameCache",{nodeId:e.id,deviceId:o,frameSeq:N,scope:"local",reason:"decode-pending"});return}l.current.add(o);try{await jn(P,D.metadata,D.payload)&&(N>0&&b.current.set(o,N),J.current+=1,g.emit("remoteControl.node.framePainted",{nodeId:e.id,deviceId:o,frameSeq:N,painted:J.current,source:"ws"}))}catch{}finally{l.current.delete(o);const O=k.current.get(o),X=pt(O==null?void 0:O.metadata),he=b.current.get(o)||0,tt=m.current;O&&tt&&(X<=0?he<=0:X>he)&&Ro(tt,O,l.current,b.current).then($e=>{$e&&(J.current+=1,g.emit("remoteControl.node.frameCache",{nodeId:e.id,deviceId:o,frameSeq:X,scope:"local",reason:"latest-pending"}),g.emit("remoteControl.node.framePainted",{nodeId:e.id,deviceId:o,frameSeq:X,painted:J.current,source:"ws-cache"}))})}}},[o,e.id]);p.useEffect(()=>{if(s.source!=="bridge"||!o||(A==null?void 0:A.connected)!==!0||!r)return;let y=!1,I=null,N=0;M.current=!1;const U=()=>{var z,D;if(!y){try{I=new WebSocket(Ar(s.baseUrl,S,(D=(z=s.bridge)==null?void 0:z.status)==null?void 0:D.bridgeToken,[o])),I.binaryType="arraybuffer"}catch(P){g.emit("remoteControl.node.frameWs",{nodeId:e.id,ok:!1,error:P instanceof Error?P.message:String(P)});return}I.onopen=()=>{M.current=!0,F.current=performance.now(),g.emit("remoteControl.node.frameWs",{nodeId:e.id,ok:!0,deviceId:o,fps:20}),I==null||I.send(JSON.stringify({type:"subscribe",deviceIds:[o],autoStartLive:!0,fps:20,maxWidth:960,maxHeight:540,quality:62,mode:"remote-fast-control"}))},I.onmessage=async P=>{if(!y){if(F.current=performance.now(),P.data instanceof ArrayBuffer){const O=wo(P.data);O&&await Nt(O.metadata,O.payload)}else if(P.data instanceof Blob){const O=wo(await P.data.arrayBuffer());O&&await Nt(O.metadata,O.payload)}}},I.onerror=()=>{M.current=!1,g.emit("remoteControl.node.frameWs",{nodeId:e.id,ok:!1,deviceId:o,reason:"socket-error"})},I.onclose=()=>{M.current=!1,y||(N=window.setTimeout(U,1500))}}};return U(),()=>{y=!0,M.current=!1,window.clearTimeout(N),I==null||I.close()}},[A==null?void 0:A.connected,o,e.id,Nt,S,s.baseUrl,(ro=(Ee=s.bridge)==null?void 0:Ee.status)==null?void 0:ro.bridgeToken,s.source,r]),p.useEffect(()=>{if(s.source!=="bridge"||!o||(A==null?void 0:A.connected)!==!0||!r)return;let y=!1,I=!1;const N=async()=>{var D;if(!(y||I)&&!(M.current&&performance.now()-F.current<kr)){I=!0;try{const P=await rr([o],s.auth,s.baseUrl);if(y||P.ok===!1)return;const O=(D=P.frames)==null?void 0:D.find($e=>$e.deviceId===o),X=await bn(m.current??void 0,o,O?Or(O):void 0,s.baseUrl,l.current,b.current,k.current),he=X.painted?1:0,tt=X.staleDropped?1:0;X.staleDropped&&g.emit("remoteControl.node.frameStaleDropped",{nodeId:e.id,deviceId:o,frameSeq:X.frameSeq,previous:X.previous,source:"snapshot"}),g.emit("remoteControl.node.frameSnapshot",{nodeId:e.id,deviceId:o,frameCount:O?1:0,painted:he,staleDropped:tt})}catch{}finally{I=!1}}},U=window.setTimeout(N,250),z=window.setInterval(N,2500);return()=>{y=!0,window.clearTimeout(U),window.clearInterval(z)}},[A==null?void 0:A.connected,o,e.id,s.auth,s.baseUrl,s.source,r]),p.useEffect(()=>{!B||te||(pe(!1),h("unavailable"),L("Remote input unavailable."),g.emit("remoteControl.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"control-unavailable",deviceId:o}))},[te,o,B,e.id]),p.useEffect(()=>{var N,U,z;if(!B){(N=x.current)==null||N.close(),x.current=null,h("locked");return}if(!te||!o){h("unavailable"),L("Remote input unavailable.");return}let y=!1,I=null;h("connecting"),L("Connecting remote input adapter...");try{I=new WebSocket(Mr(s.baseUrl,Q,(z=(U=s.bridge)==null?void 0:U.status)==null?void 0:z.bridgeToken)),x.current=I}catch(D){h("error");const P=D instanceof Error?D.message:String(D);L(P),g.emit("remoteControl.node.input.ws",{nodeId:e.id,ok:!1,deviceId:o,error:P});return}return I.onopen=()=>{y||(h("ready"),L("Remote input ready."),g.emit("remoteControl.node.input.ws",{nodeId:e.id,ok:!0,deviceId:o}))},I.onmessage=D=>{if(y)return;const P=hr(String(D.data||"{}"));if(P){if(P.type==="RemoteInputSocketReady"){h("ready");return}g.emit("remoteControl.node.input.result",{nodeId:e.id,ok:P.ok,deviceId:P.deviceId||o,inputType:P.inputType,error:P.error}),!P.ok||P.error?L(P.error||"Remote input failed."):/^pointermove$/i.test(P.inputType)||L(`${P.inputType||"Input"} queued.`)}},I.onerror=()=>{y||(h("error"),L("Remote input socket error."),g.emit("remoteControl.node.input.ws",{nodeId:e.id,ok:!1,deviceId:o,reason:"socket-error"}))},I.onclose=()=>{y||(x.current=null,h("error"),L("Remote input socket closed."),g.emit("remoteControl.node.input.ws",{nodeId:e.id,ok:!1,deviceId:o,reason:"socket-closed"}))},()=>{y=!0,x.current===I&&(x.current=null),I==null||I.close()}},[te,o,B,e.id,Q,s.baseUrl,(ht=(me=s.bridge)==null?void 0:me.status)==null?void 0:ht.bridgeToken]),p.useEffect(()=>{if(!B)return;const y=I=>{I.key==="Escape"&&(I.preventDefault(),pe(!1),L("Remote input locked."),g.emit("remoteControl.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"escape",deviceId:o}))};return window.addEventListener("keydown",y,!0),()=>window.removeEventListener("keydown",y,!0)},[o,B,e.id]);const de=p.useCallback(y=>{var O;const I=x.current;if(!B||!te||!o||(I==null?void 0:I.readyState)!==WebSocket.OPEN){y.ack&&L(B?"Remote input socket is not ready.":"Remote input locked.");return}const N=`remote-control-input-${Date.now()}-${++v.current}`,{ack:U,...z}=y,D=mr({requestId:N,deviceId:o,ack:U,controlLeaseId:(O=s.hub)==null?void 0:O.hostTargetLeaseId,input:z});if(!D){U&&L("Remote input payload is invalid.");return}const P=w(D.input.type);try{I.send(JSON.stringify(D));const X=++V.current;(D.ack||X%24===1)&&g.emit("remoteControl.node.input.sent",{nodeId:e.id,deviceId:o,inputType:P,sampled:!D.ack,sent:X})}catch(X){h("error"),L(X instanceof Error?X.message:String(X))}},[te,o,B,e.id,(et=s.hub)==null?void 0:et.hostTargetLeaseId]),Re=p.useCallback((y,I,N,U=!1)=>{const z=So(y,U);return z?(de({type:I,...z,button:Pr(y.button),ack:N}),!0):!1},[de]),eo=p.useCallback(y=>{if(!(!B||!Re(y,"pointerDown",!0,!1))){y.preventDefault(),y.stopPropagation(),y.currentTarget.focus();try{y.currentTarget.setPointerCapture(y.pointerId)}catch{}}},[Re,B]),Je=p.useCallback(y=>{var z,D;if(!B)return;const I=performance.now();if(I-Z.current<Tr)return;Z.current=I;const N=((D=(z=y.currentTarget).hasPointerCapture)==null?void 0:D.call(z,y.pointerId))===!0;Re(y,"pointerMove",!1,N)&&(y.preventDefault(),y.stopPropagation())},[Re,B]),to=p.useCallback(y=>{if(B){y.preventDefault(),y.stopPropagation();try{y.currentTarget.releasePointerCapture(y.pointerId)}catch{}Re(y,"pointerUp",!0,!0)}},[Re,B]),Oo=p.useCallback(y=>{if(!B)return;const I=So(y,!1);I&&(de({type:"wheel",...I,deltaX:y.deltaX,deltaY:y.deltaY,ack:!0}),y.preventDefault(),y.stopPropagation())},[B,de]),Ue=p.useCallback(y=>{!B||y.key==="Escape"||(y.preventDefault(),y.stopPropagation(),de({type:"keyDown",key:y.key,code:y.code,repeat:y.repeat,ack:!0}))},[B,de]),kt=p.useCallback(y=>{!B||y.key==="Escape"||(y.preventDefault(),y.stopPropagation(),de({type:"keyUp",key:y.key,code:y.code,repeat:!1,ack:!0}))},[B,de]),Ze=p.useCallback(y=>{y.stopPropagation(),tr(!0),Se("hosted-access-enabled")},[Se]),He=p.useCallback(y=>{if(y.stopPropagation(),B){pe(!1),L("Remote input locked."),g.emit("remoteControl.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"manual",deviceId:o});return}if(!te){h("unavailable"),L("Remote input unavailable."),g.emit("remoteControl.node.input.lock",{nodeId:e.id,unlocked:!1,reason:"unavailable",deviceId:o});return}pe(!0),L("Connecting remote input adapter..."),g.emit("remoteControl.node.input.lock",{nodeId:e.id,unlocked:!0,reason:"manual",deviceId:o})},[te,o,B,e.id]),_o=p.useCallback(y=>{y.stopPropagation(),Se("manual")},[Se]),ze=p.useCallback(async y=>{var z;if(y.preventDefault(),y.stopPropagation(),s.source!=="bridge"){be("LocalBridge is not connected.");return}const I=Y.trim();if(!I){be("Remote task is empty.");return}if(!o||(A==null?void 0:A.connected)!==!0||!ne){be("This device cannot accept remote tasks.");return}const N="task-only",U=((z=I.split(/\r?\n/)[0])==null?void 0:z.slice(0,96))||"Remote task";Pe(!0),be("Queueing device task...");try{const D=await ir(o,{instruction:I,title:U,approvalLevel:N},s.auth,s.baseUrl),P=D.ok===!0;be(P?"Queued remote task.":D.error||"Remote task queue failed."),g.emit("remoteControl.node.task.queue",{nodeId:e.id,ok:P,deviceId:o,approvalLevel:N,queued:P?1:0,taskId:D.taskId||"",commandId:D.commandId||"",error:D.error||""}),P&&(Oe(""),await Se("task-queued"))}catch(D){const P=D instanceof Error?D.message:String(D);be(P),g.emit("remoteControl.node.task.queue",{nodeId:e.id,ok:!1,deviceId:o,approvalLevel:N,queued:0,error:P})}finally{Pe(!1)}},[ne,A==null?void 0:A.connected,o,e.id,Se,s.auth,s.baseUrl,s.source,Y]);return a.jsxs("div",{ref:n,className:"node-remote-control","data-testid":"remote-control-node","data-remote-source":s.source,"data-remote-transport-visible":r?"true":"false","data-remote-frame-subscription-active":r&&s.source==="bridge"&&(A==null?void 0:A.connected)===!0?"true":"false",onPointerDown:y=>y.stopPropagation(),children:[a.jsxs("div",{className:"node-remote-control__bar",children:[a.jsx("strong",{title:xe,children:xe}),a.jsx("span",{children:Fe}),a.jsx("button",{type:"button",title:"Refresh remote device",onClick:_o,children:a.jsx(vo,{size:12,className:s.loading?"spin-icon":""})}),s.source==="blocked"?a.jsxs("button",{type:"button",onClick:Ze,children:[a.jsx(ko,{size:12}),"Enable"]}):a.jsxs("button",{type:"button",disabled:!te&&!B,onClick:He,children:[B?a.jsx(Da,{size:12}):a.jsx(Oa,{size:12}),B?"Lock":"Unlock"]})]}),a.jsxs("div",{className:`node-remote-control__screen ${B&&te?"is-input-active":""}`,tabIndex:B&&te?0:-1,onPointerDown:eo,onPointerMove:Je,onPointerUp:to,onWheel:Oo,onKeyDown:Ue,onKeyUp:kt,children:[a.jsx("canvas",{ref:m}),B&&te&&a.jsxs("em",{children:[a.jsx(_a,{size:11}),"input"]})]}),a.jsxs("form",{className:"node-remote-control__taskbar","data-testid":"remote-control-node-taskbar",onSubmit:ze,children:[a.jsx("input",{"aria-label":"Remote control task",value:Y,maxLength:1200,onChange:y=>Oe(y.target.value),onPointerDown:y=>y.stopPropagation(),placeholder:ne?`Task for ${xe}`:"Task unavailable"}),a.jsxs("button",{type:"submit",disabled:!jt,title:jt?"Queue task for this device":"This device cannot accept remote tasks",children:[a.jsx(nn,{size:12,className:W?"spin-icon":""}),"Queue"]})]}),a.jsxs("div",{className:"node-remote-control__footer",children:[a.jsxs("span",{children:["DEVICE ",a.jsx("strong",{children:o||"missing"})]}),a.jsxs("span",{children:["STATE ",a.jsx("strong",{children:(A==null?void 0:A.connected)===!0?"online":"offline"})]}),a.jsxs("span",{children:["INPUT ",a.jsx("strong",{children:ae})]}),a.jsxs("span",{children:["TASK ",a.jsx("strong",{children:ne?"ready":"off"})]}),a.jsxs("span",{children:["ROUTE ",a.jsx("strong",{children:s.source==="bridge"?"Local":s.source==="blocked"?"Gated":"Preview"})]})]}),a.jsx("p",{className:"node-remote-control__message",children:Do})]})}function Rr(e){var t,o,n;return w(((t=e.metadata)==null?void 0:t.RemoteFleetDeviceId)||((o=e.metadata)==null?void 0:o.RemoteSelectedDeviceId)||((n=e.metadata)==null?void 0:n.DeviceId)).trim()}function St(e){var n,r,s,c,m,l,b,k,x,v,V,M,F;const t=new Date().toISOString();return{deviceId:Rr(e)||"remote-control-preview",deviceName:((n=e.metadata)==null?void 0:n.RemoteFleetDeviceName)||e.title||"Remote device",platform:((r=e.metadata)==null?void 0:r.RemoteFleetDevicePlatform)||"unknown",arch:((s=e.metadata)==null?void 0:s.RemoteFleetDeviceArch)||"",connected:/^(1|true|yes|online)$/i.test(((c=e.metadata)==null?void 0:c.RemoteFleetDeviceConnected)||""),lastSeenAt:t,capabilities:{control:/^(1|true|yes|on)$/i.test(((m=e.metadata)==null?void 0:m.RemoteFleetDeviceCanControl)||""),taskDispatch:/^(1|true|yes|on)$/i.test(((l=e.metadata)==null?void 0:l.RemoteFleetDeviceCanDispatchTask)||"")},latestLiveFrame:(b=e.metadata)!=null&&b.RemoteFleetLatestFramePath||(k=e.metadata)!=null&&k.RemoteFleetLatestFrameUrl||(x=e.metadata)!=null&&x.RemoteFleetLatestFrameDataUrl?{framePath:(v=e.metadata)==null?void 0:v.RemoteFleetLatestFramePath,frameUrl:(V=e.metadata)==null?void 0:V.RemoteFleetLatestFrameUrl,dataUrl:(M=e.metadata)==null?void 0:M.RemoteFleetLatestFrameDataUrl,frameSeq:fn((F=e.metadata)==null?void 0:F.RemoteFleetLatestFrameSeq,0)}:void 0}}function fn(e,t){const o=Number(e);return Number.isFinite(o)&&o>=0?o:t}function w(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):""}function ye(e,t){const o=Number(e);return Number.isFinite(o)?o:t}function ce(e,t){var n;const o=(n=e.capabilities)==null?void 0:n[t];return typeof o=="boolean"?o:typeof o=="number"?o!==0:typeof o=="string"?/^(1|true|yes|on)$/i.test(o):!1}function Mr(e,t,o){const n=e.replace(/^http:/i,"ws:").replace(/^https:/i,"wss:").replace(/\/+$/,""),r=t||"/api/remote/input/ws",s=new URLSearchParams;o&&s.set("token",o);const c=s.toString();return c?`${n}${r}?${c}`:`${n}${r}`}function Pr(e){return e===2?"right":e===1?"middle":"left"}function So(e,t=!1){const o=Gl(e.currentTarget);if(!o)return null;const n=o.getBoundingClientRect();if(n.width<=0||n.height<=0)return null;const r=Zt.get(o)??{left:0,top:0,width:n.width,height:n.height};return Cl(e,n,r,t)}function Gl(e){return e instanceof HTMLCanvasElement?e:e.querySelector("canvas")}function Ra(e){return e.split(",").map(t=>t.trim()).filter(Boolean)}function Ar(e,t,o,n){const r=e.replace(/^http:/i,"ws:").replace(/^https:/i,"wss:").replace(/\/+$/,""),s=t||"/api/remote/frames/ws",c=new URLSearchParams;o&&c.set("token",o),n.length>0&&c.set("devices",n.join(","));const m=c.toString();return m?`${r}${s}?${m}`:`${r}${s}`}function Er(e){switch(e){case"ready":return"ready";case"connecting":return"connecting";case"unavailable":return"unavailable";case"error":return"error";default:return"locked"}}function bo(e,t){const o=new Date().toISOString(),n=Math.max(12,Math.min(El,Math.floor(e||Me)));return Array.from({length:n},(r,s)=>({deviceId:`remote-node-preview-${s+1}`,deviceName:`Remote ${String(s+1).padStart(2,"0")}`,platform:s%4===0?"linux":"win32",arch:"x64",connected:s<t,lastSeenAt:o,capabilities:{control:!1}}))}function tn(e){if(typeof window>"u")return!1;try{const t=window.localStorage.getItem(hn);if(String(t||"").trim().toLowerCase()!=="true")return!1;const o=String(window.localStorage.getItem(gn)||"").trim(),n=String(e||"").trim();return!o||o===n}catch{return!1}}function Ma(e,t){if(!(typeof window>"u"))try{t?(window.localStorage.setItem(hn,"true"),window.localStorage.setItem(gn,String(e||"").trim())):(window.localStorage.removeItem(hn),window.localStorage.removeItem(gn))}catch{}}function Ul({source:e,hub:t,baseUrl:o,hubLabel:n,routeLabel:r,connected:s,total:c,taskCount:m,taskDispatchCount:l,aiCount:b,pageLabel:k,pageStart:x,pageIndex:v,pageCount:V,projectionMode:M,projectedCount:F,visibleBudget:J,selectedDeviceId:Z,inputLabel:E,devices:ue,latestTaskBatch:B,recentTaskBatches:pe,taskFollowActive:Ce,taskFollowKey:h,isHostActiveForNode:ee,registryRouteInfo:L,hostTargetRenewMs:Y,autoHostEnabled:Oe,agent:W,agentStatusLabel:Pe,agentRunning:_e,agentReady:be,message:A}){const xe=An(t),Fe=ee?"hosting":(t==null?void 0:t.hostTargetActive)===!0?"other-monitor":"inactive",S=Vl(ue);return{SemanticType:"RemoteFleetMonitor",RemoteFleetSchemaVersion:"remote-fleet@1",RemoteFleetViewMode:"all-devices",RemoteFleetLastRefreshAtUtc:new Date().toISOString(),RemoteFleetHubStatus:(t==null?void 0:t.started)===!0?"online":e==="blocked"?"gated":e==="bridge"?"ready":e,RemoteFleetHubEndpoint:xe,RemoteFleetManagerPackage:w(t==null?void 0:t.managerPackage)||"@mindexec/cli",RemoteFleetManagerVersion:w(t==null?void 0:t.managerVersion),RemoteFleetAgentPackage:w(t==null?void 0:t.agentPackage)||"@mindexec/remote",RemoteFleetPairTokenPreview:w(t==null?void 0:t.pairTokenPreview)||"<pair-token>",RemoteFleetConnectCommand:jr(t),RemoteFleetDeviceCount:String(c),RemoteFleetConnectedDeviceCount:String(s),RemoteFleetDevicesJson:JSON.stringify(S),RemoteFleetLatestTaskBatchJson:B?JSON.stringify(Pa(B)):"",RemoteFleetRecentTaskBatchesJson:JSON.stringify((pe??[]).slice(0,6).map(Pa)),RemoteFleetTaskFollowActive:String(Ce),RemoteFleetTaskFollowKey:h,RemoteFleetTaskFollowRefreshMs:String(Ce?Io:0),RemoteFleetTaskFollowMaxTicks:String(Rt),RemoteFleetProjectionMode:M,RemoteFleetProjectedDeviceCount:String(F),RemoteFleetCanvasPagination:`${M}:${v+1}/${V}`,RemoteFleetHostTargetState:Fe,RemoteFleetHostTargetNodeId:w(t==null?void 0:t.hostTargetNodeId),RemoteFleetHostTargetLeaseId:w(t==null?void 0:t.hostTargetLeaseId),RemoteFleetRegistryStatus:L.status,RemoteFleetRegistryReason:L.reason,RemoteFleetAccountRouteReady:String(L.accountRouteReady),RemoteFleetRegistryMigrationBlocked:String(L.migrationBlocked),RemoteFleetHostTargetRenewMs:String(Y),RemoteFleetAutoHost:String(Oe),RemoteFleetHostTargetEndpoint:w(t==null?void 0:t.hostTargetEndpoint)||xe,RemoteFleetHostTargetActivatedAtUtc:w(t==null?void 0:t.hostTargetActivatedAt),RemoteFleetHostTargetUpdatedAtUtc:w(t==null?void 0:t.hostTargetUpdatedAt),RemoteFleetHostTargetExpiresAtUtc:w(t==null?void 0:t.hostTargetExpiresAt),RemoteAgentStatus:Pe,RemoteAgentRunning:String(_e),RemoteAgentReady:String(be),RemoteAgentManager:w(W==null?void 0:W.manager),RemoteAgentLeaseId:w(W==null?void 0:W.leaseId),RemoteAgentNodeId:w(W==null?void 0:W.nodeId),RemoteAgentUpdatedAtUtc:w(W==null?void 0:W.updatedAt),RemoteAgentLastError:w((W==null?void 0:W.lastError)||(W==null?void 0:W.reconnectReason)),RemoteFleetLastError:e==="bridge"?w(t==null?void 0:t.lastError):A,RemoteHub:n,RemoteRoute:r,RemoteRegistryRoute:L.status,RemoteRegistryReason:L.reason,RemoteConnected:String(s),RemoteTotal:String(c),RemoteProjected:String(F),RemoteProjection:M,RemotePage:k,RemotePageStart:String(x),RemoteVisibleBudget:String(J),RemoteSelectedDeviceId:Z,RemoteInput:E,RemoteTasksQueued:String(m),RemoteTaskDevices:String(l),RemoteAiDevices:String(b),RemoteBaseUrl:o,AdapterState:e==="bridge"?"localbridge-connected":e==="blocked"?"adapter-gated":e}}function zl(e,t){const o=w(e==null?void 0:e.agentEndpointRouteReason).trim(),n=(e==null?void 0:e.agentEndpointAccountRouteReady)===!0,r=Lr(o);return(t?"account":(e==null?void 0:e.hostTargetActive)===!0?"other-monitor":"idle")==="other-monitor"?{status:"other-monitor",value:"Other",tone:"default",reason:o,accountRouteReady:n,migrationBlocked:r,title:o||"Another monitor currently owns the host route."}:t?n?{status:"account",value:"Account",tone:"online",reason:o||"ok",accountRouteReady:!0,migrationBlocked:!1,title:"Published to the account route registry for same-account agent pairing."}:$l(o)?{status:"blocked",value:"Blocked",tone:"warn",reason:o,accountRouteReady:!1,migrationBlocked:r,title:r?"Account route registry needs the Supabase remote_host_targets migration.":o||"The local host is active, but account route publishing failed."}:{status:"local",value:"Local",tone:"warn",reason:o,accountRouteReady:!1,migrationBlocked:r,title:o||"The local host is active, but account route publishing is not available."}:{status:"idle",value:"Idle",tone:"default",reason:o,accountRouteReady:n,migrationBlocked:r,title:o||"No active host route."}}function Lr(e){return/registry-table-unavailable|PGRST20[25]|remote_host_targets|set_remote_host_target|clear_remote_host_target/i.test(String(e||""))}function $l(e){return Lr(e)||/invalid-manager-endpoint|blocked|failed|error|unavailable|unauthori[sz]ed|forbidden/i.test(String(e||""))}function An(e){const t=w(e==null?void 0:e.agentEndpoint).trim();if(t)return t;const o=w((e==null?void 0:e.agentHost)||(e==null?void 0:e.host)).trim()||"127.0.0.1",n=Number((e==null?void 0:e.port)||5197);return`${o}:${Number.isFinite(n)&&n>0?n:5197}`}function jr(e){const t=An(e),o=w(e==null?void 0:e.pairTokenPreview).trim()||"<pair-token>";return`npx @mindexec/remote connect --manager ${t} --pair ${o}`}function Vl(e){return e.filter(t=>t.connected===!0).map(t=>{var r,s,c,m,l,b,k,x,v,V,M;const o=qt(t),n=t.latestTask;return{deviceId:it(t),sessionId:w(t.sessionId),name:ft(t),hostname:w(t.hostname),platform:Kt(t),arch:w(t.arch),agentVersion:w(t.agentVersion),connected:t.connected===!0,lastSeenAt:w(t.lastSeenAt),lastStatusAt:w(t.lastStatusAt),computerAgentEnabled:ce(t,"taskDispatch"),controlEnabled:ce(t,"control"),thumbnailEnabled:ce(t,"thumbnail")||ce(t,"screen"),liveStreamEnabled:ce(t,"liveStream"),aiAssistEnabled:ce(t,"aiAssist"),aiModel:w((r=t.capabilities)==null?void 0:r.aiModel),aiProvider:w((s=t.capabilities)==null?void 0:s.aiProvider),thumbnailFrameUrl:w(((c=t.latestThumbnail)==null?void 0:c.frameUrl)||((m=t.latestThumbnail)==null?void 0:m.framePath)),liveFrameUrl:w(((l=t.latestLiveFrame)==null?void 0:l.frameUrl)||((b=t.latestLiveFrame)==null?void 0:b.framePath)),latestFrameSeq:pt(o),liveStreamActive:((k=t.activeLiveStream)==null?void 0:k.active)===!0,liveStreamId:w((x=t.activeLiveStream)==null?void 0:x.streamId),liveStreamFps:ye((v=t.activeLiveStream)==null?void 0:v.fps,0),latestTaskBatchId:w(n==null?void 0:n.batchId),latestTaskId:w(n==null?void 0:n.taskId),latestTaskStatus:w(n==null?void 0:n.status),latestTaskApprovalLevel:w(n==null?void 0:n.approvalLevel),latestTaskResultModel:w(n==null?void 0:n.resultModel),latestTaskResultResponseId:w(n==null?void 0:n.resultResponseId),latestTaskResultSummary:w(n==null?void 0:n.resultSummary),tasksQueued:ye((V=t.counters)==null?void 0:V.tasksQueued,0),taskResultsReceived:ye((M=t.counters)==null?void 0:M.taskResultsReceived,0)}})}function Pa(e){return{batchId:w(e.batchId),title:w(e.title),instructionPreview:w(e.instructionPreview),approvalLevel:w(e.approvalLevel),status:w(e.status),requestedAt:w(e.requestedAt),updatedAt:w(e.updatedAt),total:ye(e.total,0),queued:ye(e.queued,0),pending:ye(e.pending,0),completed:ye(e.completed,0),failed:ye(e.failed,0),timedOut:ye(e.timedOut,0)}}function ql(e,t){return Aa(e)?e:(t??[]).find(Aa)}function Wl(e){if(!e)return"";const t=w(e.batchId).trim();return t||[w(e.title).trim(),w(e.requestedAt).trim(),w(e.updatedAt).trim(),String(ye(e.total,0)||"")].filter(Boolean).join(":")}function Aa(e){if(!e)return!1;const t=w(e.status).trim().toLocaleLowerCase(),o=ye(e.pending,0),n=ye(e.total,0),r=ye(e.completed,0),s=ye(e.failed,0),c=ye(e.timedOut,0);return["completed","completed-with-failures","failed","cancelled","canceled","done"].includes(t)?!1:o>0||["running","queued","pending","targeted","dispatching","in-progress"].includes(t)?!0:n>0&&r+s+c<n}function Hl(e,t){const o=Kl(e);return{manager:o[0]||"",managerCandidates:o,pairToken:w(e==null?void 0:e.pairToken).trim(),leaseId:w(e==null?void 0:e.hostTargetLeaseId).trim(),nodeId:t,engine:"auto",source:"react-remote-monitor"}}function Kl(e){const t=Array.isArray(e==null?void 0:e.agentEndpointCandidateDetails)?e.agentEndpointCandidateDetails:[],o=[e==null?void 0:e.hostTargetEndpoint,...Array.isArray(e==null?void 0:e.hostTargetEndpointCandidates)?e.hostTargetEndpointCandidates:[],e==null?void 0:e.agentEndpoint,...Array.isArray(e==null?void 0:e.agentEndpointCandidates)?e.agentEndpointCandidates:[],...t.map(s=>s.endpoint||s.address),An(e)],n=new Set,r=[];for(const s of o){const c=Xl(s),m=c.toLowerCase();if(!(!c||n.has(m))&&(n.add(m),r.push(c),r.length>=12))break}return r}function Xl(e){const t=w(e).trim(),o=t.match(/^(\[[^\]]+\]|[^:\s]+):(\d{1,5})$/);if(!o)return"";const n=Number(o[2]);return!Number.isInteger(n)||n<=0||n>65535?"":t}function Yl(e,t){if(t==="blocked")return"gated";if(t!=="bridge")return t;if(!e)return"unknown";const o=w(e.status).trim().toLowerCase();return Dr(e)?"ready":o||(Nr(e)?"running":"idle")}function Nr(e){const t=w(e==null?void 0:e.status).trim().toLowerCase();return(e==null?void 0:e.running)===!0||t==="running"||t==="starting"}function Dr(e){const t=w(e==null?void 0:e.status).trim().toLowerCase();return(e==null?void 0:e.ready)===!0||t==="ready"}function Ql({source:e,hasAuth:t,isHostActiveForNode:o,request:n,busy:r}){return r?"RemoteAgent action is already running.":e!=="bridge"?"LocalBridge is not connected.":t?o?"This monitor is already the active host target.":n.manager?n.pairToken?"":"RemoteAgent pair token is missing.":"RemoteAgent manager endpoint is missing.":"LocalBridge auth token is not available."}function it(e){return String(e.deviceId||e.sessionId||e.deviceName||"").trim()}function ft(e){return String(e.deviceName||e.hostname||it(e)||"Remote device").trim()}function Kt(e){var t;return String(((t=e.status)==null?void 0:t.platform)||e.platform||"unknown").trim()}function Jl(e){return Cr.includes(e)?e:"status"}function Zl(e){return xr.includes(e)?e:"connected"}function ec(e){return wr.includes(e)?e:"all"}function tc(e){switch(e){case"activity":return"Activity";case"platform":return"Platform";case"capability":return"Capability";default:return"Status"}}function oc(e){switch(e){case"all":return"All";case"offline":return"Offline";default:return"Live"}}function nc(e){switch(e){case"control":return"Control";case"task":return"Task";case"ai":return"AI";default:return"Any"}}function ac(e,t){switch(t){case"activity":return rc(e);case"platform":return Kt(e).toLocaleLowerCase()||"unknown";case"capability":return ic(e);default:return e.connected===!0?"online":"offline"}}function rc(e){var o,n,r,s;const t=w((o=e.latestTask)==null?void 0:o.status).toLocaleLowerCase();return t==="running"||t==="queued"?`task-${t}`:((n=e.activeLiveStream)==null?void 0:n.active)===!0?"live":Number(((r=e.counters)==null?void 0:r.liveFramesReceived)||0)>0?"live-recent":Number(((s=e.counters)==null?void 0:s.thumbnailFramesReceived)||0)>0?"thumbnail":e.lastStatusAt||e.lastSeenAt?"heartbeat":"idle"}function ic(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 qt(e){return e.latestLiveFrame||e.latestThumbnail}function En(e){return(e==null?void 0:e.dataUrl)||(e==null?void 0:e.frameUrl)||(e==null?void 0:e.framePath)||""}function Or(e){return e.live||e.thumbnail}function pt(e){const t=Number((e==null?void 0:e.frameSeq)||0);return Number.isFinite(t)&&t>0?t:0}function Ln(e,t,o){var n,r;return Math.max(e.get(o)||0,pt((n=t.get(o))==null?void 0:n.metadata),pt((r=Fr(o))==null?void 0:r.metadata))}function _r(e,t,o,n){e.has(t)&&e.delete(t);const r={metadata:{...o,deviceId:t},payload:n.slice(0),cachedAt:Date.now()};return e.set(t,r),Xt(e,mn),sc(t,r),r}function Xt(e,t,o=Number.POSITIVE_INFINITY){const n=Date.now();for(const[r,s]of e)(!s||!s.payload||Number.isFinite(o)&&n-s.cachedAt>o)&&e.delete(r);for(;e.size>t;){const r=e.keys().next().value;if(!r)break;e.delete(r)}}function sc(e,t){e&&(Mt.has(e)&&Mt.delete(e),Mt.set(e,{metadata:{...t.metadata,deviceId:e},payload:t.payload,cachedAt:t.cachedAt}),Xt(Mt,Ir,vr))}function Fr(e){return Xt(Mt,Ir,vr),Mt.get(e)}function Br(e,t){Xt(e,mn);const o=e.get(t);if(o)return{cached:o,scope:"local"};const n=Fr(t);return n?(e.set(t,n),Xt(e,mn),{cached:n,scope:"global"}):null}async function Ro(e,t,o,n){const r=w(t.metadata.deviceId).trim();if(!r||o.has(r))return!1;const s=pt(t.metadata),c=n.get(r)||0;if(s>0&&s<=c)return!1;o.add(r);try{const m=await jn(e,t.metadata,t.payload);return m&&s>0&&n.set(r,s),m}catch{return!1}finally{o.delete(r)}}function No(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(jl,Math.max(1,window.devicePixelRatio||1)),s=Math.round(o*r),c=Math.round(n*r),m=Math.abs(e.width-s),l=Math.abs(e.height-c);(e.width<=0||e.height<=0||m>Ca||l>Ca)&&(e.width=s,e.height=c);const k=e.getContext("2d",{alpha:!1});return k?(k.setTransform(r,0,0,r,0,0),{ctx:k,width:o,height:n}):null}function Mo(e,t,o){const n=No(e);if(!n)return;const{ctx:r,width:s,height:c}=n;Zt.set(e,{left:0,top:0,width:s,height:c});const m=t.connected===!0;r.fillStyle=m?"#ffffff":"#f8fafc",r.fillRect(0,0,s,c),r.strokeStyle=m?"#dbeafe":"#e2e8f0",r.lineWidth=1,r.strokeRect(.5,.5,s-1,c-1),r.fillStyle=m?"#bfdbfe":"#e2e8f0",r.fillRect(8,8,Math.max(12,s*.34),5),r.fillRect(8,18,Math.max(20,s*.52),5),r.fillStyle=o==="blocked"?"#94a3b8":"#cbd5e1",r.font="700 9px Inter, sans-serif",r.fillText(o==="bridge"?"waiting":o,8,c-8)}async function Gr(e,t,o){const n=t.startsWith("data:")?t:al(t,o);if(!n)return!1;const r=new Image;r.decoding="async",r.loading="eager",r.src=n,await r.decode();const s=No(e);if(!s)return!1;const{ctx:c,width:m,height:l}=s;return c.fillStyle="#020617",c.fillRect(0,0,m,l),Zt.set(e,Nn(c,r,m,l)),!0}async function jn(e,t,o){const n=new Blob([o],{type:t.mimeType||"image/jpeg"});let r=null;try{r=await createImageBitmap(n);const s=No(e);if(!s)return!1;const{ctx:c,width:m,height:l}=s;return c.fillStyle="#020617",c.fillRect(0,0,m,l),Zt.set(e,Nn(c,r,m,l)),!0}catch{return lc(e,t,n)}finally{r==null||r.close()}}async function lc(e,t,o){const n=URL.createObjectURL(o);try{const r=new Image;r.decoding="async",r.loading="eager",r.src=n,await r.decode();const s=No(e);if(!s)return!1;const{ctx:c,width:m,height:l}=s;return c.fillStyle="#020617",c.fillRect(0,0,m,l),Zt.set(e,Nn(c,r,m,l)),!0}catch{return g.emit("remoteMonitor.node.frameDecodeFailed",{deviceId:w(t.deviceId),frameSeq:Number(t.frameSeq||0)||0,mimeType:t.mimeType||"",byteLength:Number(t.byteLength||o.size||0)||0}),!1}finally{URL.revokeObjectURL(n)}}async function bn(e,t,o,n,r,s,c){const m=En(o),l={painted:!1,busy:!1,staleDropped:!1,frameSeq:0,previous:0};if(!e||!m)return l;if(r.has(t))return{...l,busy:!0};const b=Number((o==null?void 0:o.frameSeq)||0)||0,k=Ln(s,c,t);if(b>0&&b<=k||b<=0&&k>0)return{painted:!1,busy:!1,staleDropped:!0,frameSeq:b,previous:k};r.add(t);try{const x=await Gr(e,m,n);return x&&b>0&&s.set(t,b),{painted:x,busy:!1,staleDropped:!1,frameSeq:b,previous:k}}catch{return{painted:!1,busy:!1,staleDropped:!1,frameSeq:b,previous:k}}finally{r.delete(t)}}function Nn(e,t,o,n){const r="width"in t?Number(t.width):o,s="height"in t?Number(t.height):n,c=Math.min(o/Math.max(1,r),n/Math.max(1,s)),m=r*c,l=s*c,b=(o-m)/2,k=(n-l)/2;return e.drawImage(t,b,k,m,l),{left:b,top:k,width:m,height:l}}function nu({launchers:e,activeLauncher:t,template:o,selectedOptionId:n,values:r,validationMessage:s,canCreate:c,primaryLabel:m="Create board",onLauncherSelected:l,onOptionSelected:b,onInputChanged:k,onCreate:x,onClose:v}){const V=(o==null?void 0:o.inputs)??[];return a.jsx("div",{className:"template-launcher-backdrop","data-testid":"template-launcher-panel",onMouseDown:v,children:a.jsxs("section",{className:"template-launcher-panel floating-panel",onMouseDown:M=>M.stopPropagation(),children:[a.jsxs("header",{className:"template-launcher-head",children:[a.jsxs("div",{children:[a.jsx("span",{children:"Execution Canvas"}),a.jsx("strong",{children:t.label})]}),a.jsx("button",{type:"button",title:"Close template launcher",onClick:v,children:a.jsx(Po,{size:16})})]}),a.jsx("div",{className:"template-launcher-tabs","aria-label":"Template launchers",children:e.map(M=>a.jsxs("button",{type:"button",className:M.id===t.id?"is-active":"","data-testid":"template-launcher-tab","data-launcher-id":M.id,onClick:()=>l(M.id),children:[a.jsx(Ei,{size:14}),a.jsx("span",{children:M.label})]},M.id))}),a.jsx("p",{className:"template-launcher-description",children:t.description}),t.options.length>0&&a.jsxs("div",{className:"template-launcher-option-block",children:[a.jsx("div",{className:"template-launcher-prompt",children:t.prompt||"Choose the board to create."}),a.jsx("div",{className:"template-launcher-chips",children:t.options.map(M=>a.jsxs("button",{type:"button",className:n===M.id?"is-active":"","data-testid":"template-option","data-option-id":M.id,onClick:()=>b(M.id),children:[a.jsx("strong",{children:M.label}),a.jsx("span",{children:M.description})]},M.id))})]}),V.length>0&&a.jsx("div",{className:"template-launcher-form",children:V.map(M=>a.jsx(cc,{input:M,value:r[M.key]??"",onChange:F=>k(M.key,F)},M.key))}),s&&a.jsx("div",{className:"template-launcher-validation",children:s}),a.jsxs("footer",{className:"template-launcher-footer",children:[a.jsx("button",{type:"button",className:"template-launcher-secondary",onClick:v,children:"Cancel"}),a.jsxs("button",{type:"button",className:"template-launcher-primary","data-testid":"template-create",disabled:!c,onClick:x,children:[a.jsx(ja,{size:15}),a.jsx("span",{children:m})]})]})]})})}function cc({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 au({node:e,onSave:t,onClose:o}){var b,k,x,v,V,M;const[n,r]=p.useState(((b=e.metadata)==null?void 0:b.DirectoryPath)??e.sourceFilePath??""),[s,c]=p.useState(((k=e.metadata)==null?void 0:k.Include)??""),[m,l]=p.useState(((x=e.metadata)==null?void 0:x.Exclude)??"");return p.useEffect(()=>{var F,J,Z;r(((F=e.metadata)==null?void 0:F.DirectoryPath)??e.sourceFilePath??""),c(((J=e.metadata)==null?void 0:J.Include)??""),l(((Z=e.metadata)==null?void 0:Z.Exclude)??"")},[e.id,(v=e.metadata)==null?void 0:v.DirectoryPath,(V=e.metadata)==null?void 0:V.Exclude,(M=e.metadata)==null?void 0:M.Include,e.sourceFilePath]),a.jsx("div",{className:"directory-settings-backdrop","data-testid":"directory-settings-dialog",onMouseDown:o,children:a.jsxs("section",{className:"directory-settings-dialog","aria-label":"Folder scan settings","data-disable-mindcanvas-hotkeys":"true",onMouseDown:F=>F.stopPropagation(),children:[a.jsxs("header",{className:"directory-settings-head",children:[a.jsxs("div",{children:[a.jsxs("span",{children:[a.jsx(Li,{size:15}),"Folder scan settings"]}),a.jsx("strong",{title:e.sourceFilePath||e.title,children:e.title})]}),a.jsx("button",{type:"button",title:"Close folder scan settings","aria-label":"Close folder scan settings","data-testid":"directory-settings-close",onClick:o,children:a.jsx(Po,{size:16})})]}),a.jsxs("div",{className:"directory-settings-body",children:[a.jsxs("label",{className:"directory-setting-row",children:[a.jsxs("span",{children:[a.jsx(ji,{size:14}),"LocalBridge path"]}),a.jsx("input",{value:n,placeholder:"E:\\\\Dev@Work\\\\Project or relative/path","data-testid":"directory-settings-path",onChange:F=>r(F.target.value)})]}),a.jsxs("label",{className:"directory-setting-row",children:[a.jsxs("span",{children:[a.jsx(Ni,{size:14}),"Extensions to include"]}),a.jsx("input",{value:s,placeholder:".cs, .js, .razor, .css","data-testid":"directory-settings-include",onChange:F=>c(F.target.value)})]}),a.jsxs("label",{className:"directory-setting-row",children:[a.jsxs("span",{children:[a.jsx(Di,{size:14}),"Paths/files to exclude"]}),a.jsx("input",{value:m,placeholder:"bin, obj, .git, node_modules","data-testid":"directory-settings-exclude",onChange:F=>l(F.target.value)})]})]}),a.jsxs("footer",{className:"directory-settings-footer",children:[a.jsx("button",{type:"button","data-testid":"directory-settings-cancel",onClick:o,children:"Cancel"}),a.jsxs("button",{type:"button",className:"is-primary","data-testid":"directory-settings-save",onClick:()=>t(e.id,{DirectoryPath:n.trim(),Include:s.trim(),Exclude:m.trim()}),children:[a.jsx(Fa,{size:15}),"Save"]})]})]})})}const Dn=.001,dc=1,uc=5,pc=1.35,mc=1.3,hc=1.45,gc=.002,fc=.01,bc=.03,yc=.002,kc=.015,Tc=.05,Ic=5,vc=20,Cc=100,xc=2,Ea=2500,wc=800,Sc=1200,Rc=1800,Mc=2600,Pc={"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 Ac(e){const t=Gc(e.reasoningEffort);return e.mode==="Text"?Dc(e.provider,t,e.vendorPricing):e.mode==="Image"&&e.provider==="openai-codex"&&zc(e.modelId)?ct("Free",0,"Codex Responses image generation",void 0,"codex",!1):e.mode==="Image"?_c(e.vendorPricing):e.mode==="Video"?Fc(e.vendorPricing):Et("Unavailable")}function Ec(e){const t=e.settings.inputMode==="Image"||e.settings.inputMode==="Video"?e.settings.inputMode:"Text",o=Nc(e.settings,t);return Ac({mode:t,provider:jc(e.settings),modelId:o,reasoningEffort:e.settings.effort,vendorPricing:Lc(o)})}function Lc(e){const t=$c(e);return Pc[t]??null}function jc(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 Nc(e,t){return t==="Image"?rn("Image",e).id:t==="Video"?rn("Video",e).id:e.model}function Dc(e,t,o){switch(e){case"local-ollama":return ct("Free",0,"Local execution",void 0,"ollama",!1);case"byok":return ct("ServiceFeeOnly",xc,"BYOK platform fee",void 0,"byok",!1);case"openai-codex":return ct("Free",0,"Codex CLI local execution",void 0,"codex",!1);case"google-gemini-cli":return ct("Free",0,"Gemini CLI local execution",void 0,"gemini-cli",!1);case"managed-cloud":default:return Oc(t,o)}}function Oc(e,t){if(!bt(t==null?void 0:t.promptUsdPerToken)||!bt(t==null?void 0:t.completionUsdPerToken))return Et("Pricing unavailable");const o=Bc(e),n=((t==null?void 0:t.requestUsd)??0)+t.promptUsdPerToken*Ea+t.completionUsdPerToken*o,r=n*pc+gc+yc,s=On(Math.max(r/Dn,Ic),dc);return ct("FixedPoints",s,`Base run (${yn(Ea)} in / ${yn(o)} out)`,n,t.source,!0)}function _c(e){if(!e)return Et("Pricing unavailable");let t=e.averageUsd??e.maxUsd??e.minUsd;if(!bt(t))return Et("Pricing unavailable");bt(e.minUsd)&&(t=Math.max(t,e.minUsd*1.15));const o=t*mc+fc+kc,n=On(Math.max(o/Dn,vc),uc);return ct("FixedPoints",n,"Base image generation",t,e.source,!0)}function Fc(e){if(!e)return Et("Pricing unavailable");let t=0;if(bt(e.maxUsd)&&(t=Math.max(t,e.maxUsd)),bt(e.averageUsd)&&(t=Math.max(t,e.averageUsd*1.25)),bt(e.minUsd)&&(t=Math.max(t,e.minUsd)),t<=0)return Et("Pricing unavailable");const o=t*hc+bc+Tc,n=On(Math.max(o/Dn,Cc),10);return ct("FixedPoints",n,"Base video generation",t,e.source,!0)}function Bc(e){switch(e){case"low":return wc;case"high":return Rc;case"xhigh":return Mc;case"medium":default:return Sc}}function Gc(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 On(e,t){return t<=1?Math.ceil(e):Math.ceil(e/t)*t}function ct(e,t,o,n,r,s){return{billingKind:e,displayPoints:t,displayLabel:Uc(t),basisLabel:o,isEstimatedFromCatalog:s,vendorCostUsdSnapshot:n,vendorPricingSource:r}}function Et(e){return{billingKind:"Unavailable",displayPoints:0,displayLabel:e,basisLabel:"Pricing unavailable",isEstimatedFromCatalog:!1}}function Uc(e){return`${yn(e)}P`}function yn(e){return e.toLocaleString("en-US",{maximumFractionDigits:0})}function zc(e){return String(e??"").trim().toLowerCase().startsWith("codex-image:")}function $c(e){return String(e??"").trim()}function bt(e){return typeof e=="number"&&Number.isFinite(e)}const on=[{id:"frame",label:"Frame Perf",icon:Oi},{id:"render",label:"Render Debug",icon:_i},{id:"prompt",label:"Prompt Debug",icon:Fi},{id:"points",label:"Points",icon:Bi},{id:"dev",label:"Dev",icon:Gi}],yo=[{key:"frameProbe",label:"Frame profiler",description:"Tracks local React frame budget and viewport pressure.",defaultValue:!0},{key:"motionGuard",label:"Motion guard",description:"Highlights pan and zoom paths that must stay patch-only.",defaultValue:!0},{key:"overlayAudit",label:"Overlay debug",description:"Checks floating panels, popovers, and result overlays.",defaultValue:!0},{key:"bridgeGate",label:"LocalBridge gate monitor",description:"Keeps hosted loopback access explicit and visible.",defaultValue:!0},{key:"storageTrace",label:"Storage trace",description:"Surfaces local save and restore evidence for this board.",defaultValue:!0}],Vc=[{route:"/code",label:"CodeGraph",description:"Repository graph, agent commands, and code notes."},{route:"/planmaster",label:"PlanMaster",description:"Goal planning, step states, and execution memory."},{route:"/youtube",label:"YouTube Capture",description:"Local YouTube search flow and MindCanvas handoff."},{route:"/company-core",label:"CompanyCore",description:"Company cockpit, approvals, artifacts, and publishing jobs."},{route:"/admin/dashboard",label:"Admin Dashboard",description:"Billing, entitlement, refund, and audit shell."},{route:"/tools",label:"Free Tools",description:"Markdown, note, and clipboard mini workflows."}];function qc(e,t,o){const n=(0-t.x)/t.scale,r=(0-t.y)/t.scale,s=(o.width-t.x)/t.scale,c=(o.height-t.y)/t.scale;return e.nodes.filter(m=>{const l=m.x+m.width,b=m.y+m.height;return l>=n&&m.x<=s&&b>=r&&m.y<=c}).length}function Wc(e,t){const o=e.trim().split(/\s+/).filter(Boolean).length,n=Math.max(1,Math.ceil(o/120)),r=t==="Deep"?3:t==="Fast"?1:2;return{words:o,estimatedTokens:Math.max(8,Math.ceil(e.length/4)),points:n*r}}function Hc(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
44
|
`)}function ru({board:e,selectedNode:t,selectedCount:o,input:n,viewport:r,viewportSize:s,localBridgeState:c,syncStatus:m,syncMessage:l,buildPrompt:b,navigate:k,onClose:x}){const[v,V]=p.useState("frame"),[M,F]=p.useState(""),[J,Z]=p.useState("idle"),[E,ue]=p.useState(null),[B,pe]=p.useState(()=>Object.fromEntries(yo.map(S=>[S.key,S.defaultValue]))),Ce=p.useMemo(()=>qc(e,r,s),[e,r,s]),h=M||b(),ee=p.useMemo(()=>Wc(h,e.settings.effort),[e.settings.effort,h]),L=p.useMemo(()=>Ec(e),[e,e.settings.aiProvider,e.settings.effort,e.settings.imageRouterImageModel,e.settings.imageRouterVideoModel,e.settings.inputMode,e.settings.model]),Y=on.find(S=>S.id===v)??on[0],Oe=Y.icon;p.useEffect(()=>{if(v!=="points")return;const S=e.settings.inputMode==="Image"?e.settings.imageRouterImageModel:e.settings.inputMode==="Video"?e.settings.imageRouterVideoModel:e.settings.model;g.emit("promptDebug.points.quote",{mode:e.settings.inputMode,model:S??"",billingKind:L.billingKind,displayPoints:L.displayPoints,pricingSource:L.vendorPricingSource??"none",estimatedFromCatalog:L.isEstimatedFromCatalog})},[v,e.settings.imageRouterImageModel,e.settings.imageRouterVideoModel,e.settings.inputMode,e.settings.model,L.billingKind,L.displayPoints,L.isEstimatedFromCatalog,L.vendorPricingSource]);const W=S=>{V(S),g.emit("promptDebug.tab",{tab:S})},Pe=()=>{const S=b();F(S),ue(new Date().toLocaleTimeString()),Z("idle"),g.emit("promptDebug.build",{tab:v,selectedKind:(t==null?void 0:t.kind)??"none",chars:S.length})},_e=async()=>{const S=Hc(e,t,M||b());try{const Q=await Mn(S);Z("copied"),g.emit("promptDebug.copy",{ok:!0,tab:v,method:Q})}catch(Q){const te=document.querySelector('[data-testid="prompt-debug-preview"]');if(te){te.focus(),te.select(),V("prompt"),Z("selected"),g.emit("promptDebug.copy",{ok:!1,selected:!0,tab:v,message:Q instanceof Error?Q.message:String(Q)});return}Z("failed"),g.emit("promptDebug.copy",{ok:!1,tab:v,message:Q instanceof Error?Q.message:String(Q)})}},be=()=>{F(""),ue(null),Z("idle"),g.emit("promptDebug.clear",{tab:v})},A=S=>{pe(Object.fromEntries(yo.map(Q=>[Q.key,S]))),g.emit("promptDebug.renderToggle",{all:S})},xe=()=>{pe(Object.fromEntries(yo.map(S=>[S.key,S.defaultValue]))),g.emit("promptDebug.renderToggle",{reset:!0})},Fe=(S,Q)=>{pe(te=>({...te,[S]:Q})),g.emit("promptDebug.renderToggle",{key:S,value:Q})};return a.jsx("div",{className:"prompt-debug-backdrop","data-testid":"prompt-debug-dialog",onMouseDown:x,children:a.jsxs("section",{className:"prompt-debug-dialog","aria-label":"Prompt debugger","data-disable-mindcanvas-hotkeys":"true",onMouseDown:S=>S.stopPropagation(),children:[a.jsxs("header",{className:"prompt-debug-header",children:[a.jsxs("div",{children:[a.jsx(Ui,{size:16}),a.jsx("strong",{children:"Prompt Debugger"})]}),a.jsxs("div",{className:"prompt-debug-header__actions",children:[a.jsxs("button",{type:"button",onClick:Pe,"data-testid":"prompt-debug-build",children:[a.jsx(zi,{size:13}),"Build"]}),a.jsxs("button",{type:"button",onClick:_e,"data-testid":"prompt-debug-copy",children:[J==="copied"?a.jsx(Fa,{size:13}):a.jsx(Na,{size:13}),J==="copied"?"Copied":J==="selected"?"Selected":J==="failed"?"Copy failed":"Copy"]}),a.jsxs("button",{type:"button",onClick:be,children:[a.jsx($i,{size:13}),"Clear"]}),a.jsx("button",{type:"button",title:"Close debugger",onClick:x,children:a.jsx(Po,{size:15})})]})]}),a.jsxs("div",{className:"prompt-debug-content",children:[a.jsx("nav",{className:"prompt-debug-tabs","aria-label":"Prompt debugger sections",children:on.map(S=>{const Q=S.icon;return a.jsxs("button",{type:"button",className:v===S.id?"is-active":"","data-testid":`prompt-debug-tab-${S.id}`,onClick:()=>W(S.id),children:[a.jsx(Q,{size:14}),S.label]},S.id)})}),a.jsxs("main",{className:"prompt-debug-main",children:[a.jsxs("div",{className:"prompt-debug-section-title",children:[a.jsx(Oe,{size:15}),a.jsx("strong",{children:Y.label}),a.jsx("span",{children:E?`Built ${E}`:"Local React diagnostics"})]}),v==="frame"&&a.jsxs("div",{className:"prompt-debug-metric-grid",children:[a.jsx(qe,{label:"Nodes",value:e.nodes.length,detail:`${Ce} visible`}),a.jsx(qe,{label:"Edges",value:e.edges.length,detail:`${o} selected`}),a.jsx(qe,{label:"Zoom",value:`${Math.round(r.scale*100)}%`,detail:`${Math.round(r.x)}, ${Math.round(r.y)}`}),a.jsx(qe,{label:"Storage",value:m,detail:l||"Local browser state"}),a.jsx(qe,{label:"Bridge",value:c,detail:"Loopback stays gated on hosted Pages"}),a.jsx(qe,{label:"Selected",value:(t==null?void 0:t.kind)||"none",detail:(t==null?void 0:t.title)||"No selected node"})]}),v==="render"&&a.jsxs("div",{className:"prompt-debug-stack",children:[a.jsxs("div",{className:"prompt-debug-actions",children:[a.jsx("button",{type:"button",onClick:()=>A(!0),children:"Enable all"}),a.jsx("button",{type:"button",onClick:()=>A(!1),children:"Disable all"}),a.jsxs("button",{type:"button",onClick:xe,children:[a.jsx(vo,{size:13}),"Reset"]})]}),yo.map(S=>a.jsxs("label",{className:"prompt-debug-toggle",children:[a.jsxs("span",{children:[a.jsx("strong",{children:S.label}),a.jsx("small",{children:S.description})]}),a.jsx("input",{type:"checkbox",checked:B[S.key]??!1,onChange:Q=>Fe(S.key,Q.target.checked)})]},S.key))]}),v==="prompt"&&a.jsxs("div",{className:"prompt-debug-stack",children:[a.jsxs("div",{className:"prompt-debug-readout",children:[a.jsx("span",{children:"Selected node"}),a.jsx("strong",{children:t?`${t.title} / ${t.kind}`:"No selected node"})]}),a.jsx("textarea",{"data-testid":"prompt-debug-preview",value:M||h,onChange:S=>F(S.target.value),spellCheck:!1})]}),v==="points"&&a.jsxs("div",{className:"prompt-debug-stack",children:[a.jsxs("div",{className:"prompt-debug-metric-grid prompt-debug-metric-grid--small",children:[a.jsx(qe,{label:"Mode",value:e.settings.inputMode,detail:e.settings.aiProvider??"OpenAI Codex"}),a.jsx(qe,{label:"Words",value:ee.words,detail:"Prompt preview"}),a.jsx(qe,{label:"Tokens",value:ee.estimatedTokens,detail:"Local estimate"}),a.jsx(qe,{label:"Points",value:L.displayLabel,detail:L.basisLabel})]}),a.jsxs("div",{className:"prompt-debug-point-quote","data-testid":"prompt-debug-point-quote","data-billing-kind":L.billingKind,"data-pricing-source":L.vendorPricingSource??"none","data-estimated-from-catalog":L.isEstimatedFromCatalog?"true":"false",children:[a.jsx("span",{children:L.billingKind}),a.jsx("strong",{children:L.displayLabel}),a.jsx("small",{children:L.vendorCostUsdSnapshot===void 0?L.vendorPricingSource??"Local provider":`${L.vendorPricingSource??"catalog"} vendor snapshot $${L.vendorCostUsdSnapshot.toFixed(4)}`})]}),a.jsx("div",{className:"prompt-debug-note",children:"Point quote follows the original local PointQuoteService policy. It does not bill credits or call server-side accounting."})]}),v==="dev"&&a.jsx("div",{className:"prompt-debug-dev-grid",children:Vc.map(S=>a.jsxs("button",{type:"button",onClick:()=>{g.emit("promptDebug.devTool.open",{route:S.route}),k(S.route)},children:[a.jsx(Vi,{size:14}),a.jsxs("span",{children:[a.jsx("strong",{children:S.label}),a.jsx("small",{children:S.description})]})]},S.route))})]})]})]})})}function qe({label:e,value:t,detail:o}){return a.jsxs("article",{className:"prompt-debug-card",children:[a.jsx("span",{children:e}),a.jsx("strong",{children:t}),a.jsx("small",{children:o})]})}export{Qc as $,Md as A,td as B,Is as C,Lt as D,id as E,Yd as F,Yt as G,Xi as H,Ji as I,Ua as J,Ao as K,sn as L,ln as M,rn as N,ld as O,sd as P,Lo as Q,tu as R,Cs as S,Ie as T,cd as U,Mn as V,vs as W,rd as X,$d as Y,nu as Z,bs as _,Wd as a,au as a0,eu as a1,ru as a2,Ba as a3,is as a4,za as a5,Zd as a6,Ad as a7,Jd as a8,Xd as a9,md as aA,pd as aB,dd as aC,ud as aD,Sd as aE,vd as aF,Cd as aG,xd as aH,wd as aI,Pn as aa,Ed as ab,es as ac,Zi as ad,In as ae,Tn as af,rt as ag,Ld as ah,jd as ai,Nd as aj,Dd as ak,Od as al,_d as am,Fd as an,Bd as ao,Gd as ap,Ud as aq,zd as ar,fd as as,bd as at,yd as au,kd as av,Td as aw,Id as ax,hd as ay,gd as az,qd as b,ou as c,Kd as d,nd as e,Qd as f,j as g,ks as h,Js as i,Eo as j,Zc as k,Jc as l,Ts as m,ed as n,Rn as o,Va as p,Rd as q,Vd as r,At as s,al as t,od as u,ad as v,Hd as w,tr as x,or as y,Pd as z};
|