@codeyam-editor/codeyam-editor 0.1.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/npm/cli.js +5 -2
- package/npm/cloud-branch-switch.js +442 -0
- package/npm/cloud.js +1521 -0
- package/npm/container.js +28 -5
- package/npm/editor-dev.js +378 -0
- package/npm/editor.js +199 -12
- package/npm/empty-project-dir.js +33 -0
- package/npm/fleet-auth.js +111 -0
- package/npm/fleet-cleanup.js +124 -0
- package/npm/fleet-env.js +125 -0
- package/npm/fleet-memory.js +127 -0
- package/npm/fleet-pool-policy.js +78 -0
- package/npm/fleet-pool.js +401 -0
- package/npm/fleet-queue.js +40 -0
- package/npm/fleet-reconcile.js +36 -0
- package/npm/fleet-reset.js +144 -0
- package/npm/fleet-roster.js +81 -0
- package/npm/launch-config.js +544 -0
- package/npm/preflight-guidance.js +68 -0
- package/npm/scenario-check.js +355 -290
- package/npm/scenario-handlers.js +82 -0
- package/npm/scenario-interactivity.js +199 -0
- package/npm/scenario-issues.js +35 -0
- package/npm/scenario-metrics.js +108 -0
- package/npm/scenario-mocks.js +107 -0
- package/npm/scenario-playwright.js +355 -0
- package/npm/utils.js +548 -22
- package/npm/vm-urls.js +117 -0
- package/package.json +13 -6
- package/ui/dist/assets/ContainerInspector-C8EkH4PP.js +2 -0
- package/ui/dist/assets/EditorShell-DWaeBxgj.js +186 -0
- package/ui/dist/assets/Markdown-BHBqz-Mj.js +1 -0
- package/ui/dist/assets/ScenarioDataPanel-DYP7pi_n.css +32 -0
- package/ui/dist/assets/ScenarioDataPanel-zJSXtXL4.js +5 -0
- package/ui/dist/assets/ScenarioDataPanelFullPage-C0YHQB-T.js +1 -0
- package/ui/dist/assets/ScenarioRenderer-CgDxuigm.js +1 -0
- package/ui/dist/assets/StepsSimulator-CRtmlyNZ.js +1 -0
- package/ui/dist/assets/index-BUYNFqKK.js +27 -0
- package/ui/dist/assets/index-DVr5rY2d.css +1 -0
- package/ui/dist/assets/markdown-v0F0UEt3.js +37 -0
- package/ui/dist/assets/react-CSS0HapR.js +28 -0
- package/ui/dist/assets/useEvents-DggWrtHe.js +1 -0
- package/ui/dist/assets/xterm--24IGk-x.js +9 -0
- package/ui/dist/favicon.ico +0 -0
- package/ui/dist/favicon.png +0 -0
- package/ui/dist/index.html +16 -0
- package/npm/postinstall.js +0 -95
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
var Xi=Object.defineProperty;var Qi=(e,t,r)=>t in e?Xi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var He=(e,t,r)=>Qi(e,typeof t!="symbol"?t+"":t,r);import{j as n}from"./markdown-v0F0UEt3.js";import{b as i,R as Ne,c as Ft}from"./react-CSS0HapR.js";import{S as Zi,X as it,Y as Ve,j as Sn,Z as or,_ as gn,$ as Ca,a0 as Sa,a1 as Ea,a2 as Ra,a3 as Ta,W as el,a4 as tl,a5 as nl,a6 as rl,a7 as sl,a8 as Sr,f as al,a9 as ol,e as Pa,aa as il,ab as ll,ac as cl,h as dl,ad as ms,ae as ul,af as fl,ag as Er}from"./ScenarioDataPanel-zJSXtXL4.js";import{e as pl,a as ml,l as V,g as Rr,d as hl,p as Lt,t as xl,u as gl}from"./index-BUYNFqKK.js";import{M as mt}from"./Markdown-BHBqz-Mj.js";function hs({onRunTests:e,disabled:t,currentRunner:r}){return t?n.jsxs("span",{className:"text-xs font-medium text-[var(--text-dim)] inline-flex items-center gap-1.5",children:[n.jsx("span",{className:"inline-block h-3 w-3 animate-spin rounded-full border-2 border-current border-r-transparent"}),r?`Running ${r}…`:"Running…"]}):n.jsx("span",{role:"button",tabIndex:0,onClick:s=>{s.stopPropagation(),e()},onKeyDown:s=>{(s.key==="Enter"||s.key===" ")&&(s.stopPropagation(),e())},className:"text-xs font-medium text-[var(--accent-active)] hover:underline cursor-pointer",children:"Run Tests"})}function bl({passed:e,failed:t,notRun:r}){const s=e+t+r;if(s===0)return null;const a=2,o=[{count:e,color:"var(--accent-green)"},{count:t,color:"var(--accent-red)"},{count:r,color:"var(--text-dim)"}].filter(u=>u.count>0),l=o.map(u=>Math.max(u.count/s*100,a)),c=l.reduce((u,f)=>u+f,0),d=l.map(u=>u/c*100);return n.jsx("div",{className:"h-1.5 flex-1 rounded-full bg-[var(--bg-input)] overflow-hidden max-w-32",children:n.jsx("div",{className:"h-full flex",children:o.map((u,f)=>n.jsx("div",{className:"h-full transition-all",style:{width:`${d[f]}%`,background:u.color}},u.color))})})}function Da({tests:e,loading:t,refreshing:r,onRunTests:s,currentRunner:a}){const o=e.total>0,l=e.discovered>0,c=e.discovered>e.total?e.discovered-e.total:0;return t?n.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[n.jsx("div",{className:"h-1.5 w-16 rounded-full bg-[var(--bg-input)] animate-pulse"}),n.jsx("span",{className:"text-xs text-[var(--text-dim)]",children:r?"Running tests…":"Loading tests…"})]}):o?n.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[n.jsx(bl,{passed:e.passed,failed:e.failed,notRun:c}),n.jsxs("span",{className:"text-xs font-medium text-[var(--accent-green)]",children:[e.passed," passed"]}),e.failed>0&&n.jsxs("span",{className:"text-xs font-medium text-[var(--accent-red)]",children:["· ",e.failed," failed"]}),e.ignored>0&&n.jsxs("span",{className:"text-xs text-[var(--text-dim)]",children:["· ",e.ignored," skipped"]}),c>0&&n.jsxs("span",{className:"text-xs text-[var(--text-dim)]",children:["· ",c," not run"]}),s&&n.jsx(hs,{onRunTests:s,disabled:r,currentRunner:a})]}):l?n.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[n.jsxs("span",{className:"text-xs text-[var(--text-dim)]",children:[e.discovered," ",e.discovered===1?"test":"tests"," (not run)"]}),s&&n.jsx(hs,{onRunTests:s})]}):n.jsx("span",{className:"text-xs text-[var(--text-dim)]",children:"No tests"})}function vl({tests:e,loading:t,refreshing:r,onRunTests:s,currentRunner:a}){return n.jsxs("div",{className:"px-5 pb-5 pt-2 flex items-center gap-5 border-t border-[var(--border-default)]",children:[n.jsx(Da,{tests:e,loading:t,refreshing:r,onRunTests:s,currentRunner:a}),n.jsx("span",{className:"text-[var(--text-dim)] group-hover:text-[var(--accent-active)] transition ml-auto text-sm",children:"→"})]})}function Aa({type:e}){const t=e==="web";return n.jsx("span",{className:`rounded px-1.5 py-0.5 text-xs font-medium ${t?"bg-[var(--accent-blue)]/20 text-[var(--accent-blue)]":"bg-[var(--accent-purple)]/20 text-[var(--accent-purple)]"}`,children:t?"web":"backend"})}function yl({app:e}){return n.jsxs("div",{className:"px-5 pt-5 pb-2",children:[n.jsxs("div",{className:"flex items-center gap-3 mb-1",children:[n.jsx("h3",{className:"text-lg font-semibold text-[var(--text-primary)]",children:e.name}),n.jsx(Aa,{type:e.type})]}),e.description?n.jsx("p",{className:"text-sm text-[var(--text-muted)] leading-relaxed",children:e.description}):null]})}function Ge(e){return e.startsWith("http")?e:`/api/screenshots/${e}`}function wl({thumbnails:e}){return n.jsx("div",{className:"flex gap-2 overflow-hidden",children:e.map((t,r)=>n.jsx("img",{src:Ge(t),alt:"",className:"h-20 w-32 rounded border border-[var(--border-default)] object-cover object-top"},`${t}:${r}`))})}function jl({thumbnails:e}){return n.jsx("div",{className:"px-5 py-3 flex-1",children:e.length>0?n.jsx(wl,{thumbnails:e.slice(0,4)}):n.jsx("div",{className:"h-20"})})}function kl({stats:e,onClick:t,testsLoading:r,testsRefreshing:s,onRunTests:a,currentRunner:o}){const{app:l,tests:c,scenarios:d}=e;return n.jsxs("button",{onClick:t,className:"group flex w-full cursor-pointer flex-col rounded-lg border border-[var(--border-default)] bg-[var(--bg-card)] text-left transition hover:border-[var(--accent-active)]/40 hover:bg-[var(--bg-surface)]",children:[n.jsx(yl,{app:l}),n.jsx(jl,{thumbnails:d.thumbnails}),n.jsx(vl,{tests:c,loading:r,refreshing:s,onRunTests:a,currentRunner:o})]})}const ht={apps:[],isSingleApp:!1,onSelectApps:()=>{},onSelectApp:()=>{},onSelectRoute:()=>{}};function En(e){return e.scenarioType==="application"||e.scenarioType==="component"?e.scenarioType:e.componentName?"component":"application"}function Ct(e){return En(e)==="application"}function Tr(e){return En(e)==="component"}function Pr(e){return{overrideCounts:{mocks:0,seeds:0,inheritedMocks:0,inheritedSeeds:0},...e,scenarioType:En(e)}}function xt(){const[e,t]=i.useState({}),r=i.useRef({});return i.useEffect(()=>{let s=!1;const a=async()=>{try{const l=await fetch("/api/editor-dev-server");if(!l.ok)return;const c=await l.json();if(s)return;const d=typeof c.scenariosVersion=="number"?c.scenariosVersion:void 0,u=typeof c.plansVersion=="number"?c.plansVersion:void 0,f=typeof c.testsVersion=="number"?c.testsVersion:void 0,p=typeof c.claimsVersion=="number"?c.claimsVersion:void 0;(d!==r.current.scenariosVersion||u!==r.current.plansVersion||f!==r.current.testsVersion||p!==r.current.claimsVersion)&&(r.current={scenariosVersion:d,plansVersion:u,testsVersion:f,claimsVersion:p},t(r.current))}catch{}};a();const o=setInterval(a,500);return()=>{s=!0,clearInterval(o)}},[]),e}function Nl(e){const[t,r]=i.useState({status:"idle"}),{scenariosVersion:s}=xt();return i.useEffect(()=>{if(!e){r({status:"idle"});return}let a=!1;return r({status:"loading"}),(async()=>{try{const o=await fetch(`/api/entities/${e}`);if(a)return;if(o.status===404){r({status:"not-found"});return}if(!o.ok){r({status:"error",message:`HTTP ${o.status}`});return}const l=await o.json(),c={...l,scenarios:Array.isArray(l.scenarios)?l.scenarios.map(Pr):[]};r({status:"loaded",entity:c})}catch(o){if(a)return;r({status:"error",message:o instanceof Error?o.message:"Failed to load entity"})}})(),()=>{a=!0}},[e,s]),t}function Wn({message:e}){return n.jsx("div",{className:"px-5 py-8 text-center text-[var(--accent-red)]",children:e})}function xs(){return n.jsx("div",{className:"px-5 py-8 text-center text-[var(--text-dim)]",children:"Loading routes..."})}function Cl(e){return e.kind==="function"?"Functions don't have visual scenarios. Coverage for this function lives in its unit tests.":e.kind==="component"?`No component scenarios for ${e.displayName}. Create one with \`codeyam-editor editor register\` or capture from the live preview.`:"No scenarios for this entity yet."}function Sl({entityRef:e,onNavigate:t}){return n.jsxs("button",{type:"button",onClick:()=>t(e.hash),className:"w-full rounded-lg border border-[var(--border-subtle)] bg-[var(--bg-card)] p-3 text-left transition hover:border-[var(--border-default)]",children:[n.jsxs("div",{className:"flex items-baseline gap-2",children:[n.jsx("span",{className:"rounded-md border border-[var(--border-subtle)] bg-[var(--bg-page)] px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-[var(--text-dim)]",children:e.kind}),n.jsx("span",{className:"text-sm font-medium text-[var(--text-primary)]",children:e.name})]}),n.jsx("p",{className:"mt-0.5 font-mono text-[10px] text-[var(--text-dim)]",children:e.filePath})]})}function Vn({refs:e,onNavigate:t}){return n.jsx("ul",{className:"grid grid-cols-1 gap-1",children:e.map(r=>n.jsx("li",{children:n.jsx(Sl,{entityRef:r,onNavigate:t})},r.hash))})}function El(e,t,r){const[s,a]=i.useState(!1),[o,l]=i.useState(""),[c,d]=i.useState(!1),u=i.useCallback(()=>{a(!0),l(t)},[t]),f=i.useCallback(()=>{a(!1)},[]),p=i.useCallback(async()=>{if(!(!o.trim()||c)){d(!0);try{const m=await fetch(`/api/scenarios/${encodeURIComponent(e)}`);if(!m.ok)throw new Error(`HTTP ${m.status}`);const h=await m.json();h.name=o.trim(),await fetch(`/api/scenarios/${encodeURIComponent(e)}`,{method:"DELETE"}),await fetch("/api/scenarios",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h)}),a(!1),r()}catch{}finally{d(!1)}}},[o,c,e,r]);return{renaming:s,renameName:o,renameSaving:c,setRenameName:l,startRename:u,cancelRename:f,submitRename:p}}function Rl(e,t,r){const[s,a]=i.useState(!1),o=i.useCallback(async l=>{if(l.stopPropagation(),!!confirm(`Delete scenario "${t}"?`)){a(!0);try{await fetch(`/api/scenarios/${encodeURIComponent(e)}`,{method:"DELETE"}),r()}catch{}finally{a(!1)}}},[t,e,r]);return{deleting:s,handleDelete:o}}function Tl({mocks:e,seeds:t}){const r=[];return e>0&&r.push(`${e} ${e===1?"mock":"mocks"} overridden`),t>0&&r.push(`${t} ${t===1?"seed":"seeds"} overridden`),r.length===0?null:r.join(" · ")}function Pl({overrideCounts:e}){const t=e?Tl(e):null;return t?n.jsx("div",{className:"text-xs text-[var(--text-dim)] mt-1",children:t}):null}const Dl=new Set(["Desktop"]);function Al({scenario:e,isSelected:t}){const r=e.dimensions.length>0&&!(e.dimensions.length===1&&Dl.has(e.dimensions[0]));return n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:`text-base font-medium truncate ${t?"text-[var(--accent-active)]":"text-[var(--text-primary)]"}`,children:e.name}),e.description?n.jsx("div",{className:"text-sm text-[var(--text-secondary)] mt-1 whitespace-pre-line",children:e.description}):null,n.jsx(Pl,{overrideCounts:e.overrideCounts}),n.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[r?n.jsx("span",{className:"text-xs text-[var(--text-dim)]",children:e.dimensions.join(", ")}):null,e.componentName?n.jsx("span",{className:"text-xs text-[var(--accent-purple)]",children:e.componentName}):null]})]})}function Fl({screenshotPath:e}){const[t,r]=i.useState(!1);return e&&!t?n.jsx("img",{src:Ge(e),alt:"",className:"h-[180px] w-[288px] rounded border border-[var(--border-subtle)] bg-[var(--bg-card)] object-cover object-top shrink-0",onError:()=>r(!0)}):n.jsx("div",{className:"h-[180px] w-[288px] rounded border border-[var(--border-subtle)] bg-[var(--bg-card)] shrink-0 flex items-center justify-center",children:n.jsx("span",{className:"text-[10px] text-[var(--text-dim)]",children:"No preview"})})}function Ll({onViewData:e,onRename:t,onDelete:r,deleting:s}){return n.jsxs("div",{className:"flex items-center gap-4 mt-2",children:[n.jsx("button",{onClick:e,className:"text-xs text-[var(--accent-active)] hover:opacity-70 cursor-pointer bg-transparent border-none p-0",children:"View / Edit Data"}),n.jsx("button",{onClick:t,className:"text-xs text-[var(--text-dim)] hover:text-[var(--text-primary)] cursor-pointer bg-transparent border-none p-0",children:"Rename"}),n.jsx("button",{onClick:r,disabled:s,className:"text-xs text-red-400/60 hover:text-red-400 cursor-pointer bg-transparent border-none p-0",children:"Delete"})]})}function Ml({name:e,saving:t,onChange:r,onSubmit:s,onCancel:a}){return n.jsxs("form",{className:"flex items-center gap-2",onSubmit:s,onClick:o=>o.stopPropagation(),children:[n.jsx("input",{type:"text",value:e,onChange:o=>r(o.target.value),className:"flex-1 px-2 py-1.5 text-sm bg-[var(--bg-input)] text-[var(--text-primary)] border border-[var(--border-default)] rounded outline-none focus:border-[var(--accent-active)] min-w-0",autoFocus:!0,disabled:t}),n.jsx("button",{type:"submit",disabled:t||!e.trim(),className:"px-3 py-1.5 text-xs bg-[var(--accent-active)] text-[var(--bg-base)] rounded hover:opacity-90 disabled:opacity-40 cursor-pointer border-none",children:t?"...":"Save"}),n.jsx("button",{type:"button",onClick:a,className:"px-3 py-1.5 text-xs text-[var(--text-dim)] hover:text-[var(--text-primary)] cursor-pointer bg-transparent border-none",children:"Cancel"})]})}function Il({scenario:e,isSelected:t,onSelect:r,onViewData:s,onScenariosChanged:a,children:o}){const l=El(e.slug,e.name,a),{deleting:c,handleDelete:d}=Rl(e.slug,e.name,a);return n.jsxs("div",{onClick:l.renaming?void 0:r,className:`rounded-lg p-3 text-left transition cursor-pointer ${t?"bg-[#1a2e1a] border border-[var(--accent-active)]/40":"bg-[var(--bg-card)] border border-transparent hover:bg-[var(--bg-input)]"}`,style:{opacity:c?.4:1},children:[n.jsxs("div",{className:"flex items-start gap-4",children:[n.jsx(Fl,{screenshotPath:e.screenshotPaths[0]??null}),n.jsx("div",{className:"flex-1 min-w-0",children:l.renaming?n.jsx(Ml,{name:l.renameName,saving:l.renameSaving,onChange:l.setRenameName,onSubmit:u=>{u.preventDefault(),l.submitRename()},onCancel:l.cancelRename}):n.jsxs(n.Fragment,{children:[n.jsx(Al,{scenario:e,isSelected:t}),t&&n.jsx(Ll,{onViewData:u=>{u.stopPropagation(),s()},onRename:u=>{u.stopPropagation(),l.startRename()},onDelete:d,deleting:c})]})})]}),o&&n.jsx("div",{className:"mt-3 cursor-default",onClick:u=>u.stopPropagation(),children:o})]})}function $l(){return n.jsx("div",{className:"rounded-xl border border-dashed border-[var(--border-default)] px-4 py-5 text-sm text-[var(--text-dim)]",children:"No scenarios registered for this route yet."})}function Fa({scenarios:e,selectedSlug:t,onSelectScenario:r,onScenariosChanged:s}){const[a,o]=i.useState(null);return e.length===0?n.jsx($l,{}):n.jsx("div",{className:"grid grid-cols-1 gap-2",children:e.map(l=>n.jsx(Il,{scenario:l,isSelected:l.slug===t,onSelect:()=>{a&&a!==l.slug&&o(null),r(l.slug)},onViewData:()=>o(a===l.slug?null:l.slug),onScenariosChanged:s,children:a===l.slug&&n.jsx(Zi,{variant:"inline",slug:l.slug,scenarioName:l.name,onClose:()=>o(null)})},l.slug))})}const Ol="This component renders no other tracked components.",Bl="This component imports no tracked functions.",_l="Not called from any tracked entity. This may be a public export, an unused function, or a function whose callers haven't been re-analyzed yet.";function zl({activeTab:e,entity:t,componentRefs:r,functionRefs:s,selectedSlug:a,onSelectScenario:o,onNavigateToEntity:l,onScenariosChanged:c}){return n.jsxs("div",{className:"flex-1 overflow-auto px-5 py-4",children:[e==="scenarios"&&(t.scenarios.length===0?n.jsx(en,{copy:Cl(t)}):n.jsx(Fa,{scenarios:t.scenarios,selectedSlug:a,onSelectScenario:o,onScenariosChanged:c})),e==="components"&&(r.length===0?n.jsx(en,{copy:Ol}):n.jsx(Vn,{refs:r,onNavigate:l})),e==="functions"&&(s.length===0?n.jsx(en,{copy:Bl}):n.jsx(Vn,{refs:s,onNavigate:l})),e==="callers"&&(t.callers.length===0?n.jsx(en,{copy:_l}):n.jsx(Vn,{refs:t.callers,onNavigate:l}))]})}function en({copy:e}){return n.jsx("p",{className:"text-xs italic text-[var(--text-dim)]",children:e})}function Hl(e){return typeof e!="string"&&typeof e.onClick=="function"}function Wl(e){return typeof e=="string"?e:e.label}function Vl(e,t){(e.key==="Enter"||e.key===" ")&&(e.preventDefault(),t())}function Ul({segments:e}){if(e.length===0)return null;const t=e.length-1;return n.jsx("span",{className:"text-sm",style:{color:"var(--text-muted)"},children:e.map((r,s)=>{const a=Wl(r),o=s===t,l=!o&&Hl(r);return n.jsxs("span",{children:[n.jsx("span",{style:{color:"var(--text-dim)"},children:" / "}),l?n.jsx("button",{type:"button",onClick:r.onClick,onKeyDown:c=>Vl(c,r.onClick),className:"cursor-pointer hover:text-[var(--text-primary)] transition",style:{color:"inherit",background:"none",padding:0},children:a}):n.jsx("span",{style:o?{color:"var(--text-primary)"}:void 0,children:a})]},s)})})}function Dr({apps:e,selectedApp:t,selectedRouteEntity:r,currentEntity:s,isSingleApp:a,onSelectApps:o,onSelectApp:l,onSelectRoute:c}){const d=[];return!a&&e.length>0&&d.push({label:"Apps",onClick:o}),t&&d.push({label:t.name,onClick:()=>l(t.dir)}),r!==null&&s!=null&&r?d.push({label:r.displayName,onClick:()=>c(r.route)}):r&&d.push({label:r.displayName}),s&&d.push({label:s.displayName}),n.jsx(Ul,{segments:d})}function Kl({entity:e,app:t=null,routeEntity:r=null,navContext:s=ht}){var o;const a=e.kind==="component"?"Component":"Function";return n.jsxs("header",{className:"border-b border-[var(--border-subtle)] px-5 py-3",children:[n.jsx("div",{className:"mb-1",children:n.jsx(Dr,{apps:s.apps,selectedApp:t,selectedRouteEntity:r,currentEntity:e,isSingleApp:s.isSingleApp,onSelectApps:s.onSelectApps,onSelectApp:s.onSelectApp,onSelectRoute:s.onSelectRoute})}),n.jsxs("div",{className:"flex items-baseline gap-2",children:[n.jsx("span",{className:"rounded-md border border-[var(--border-subtle)] bg-[var(--bg-card)] px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-[var(--text-dim)]",children:a}),n.jsx("h2",{className:"text-base font-semibold text-[var(--text-primary)]",children:e.displayName})]}),n.jsx("p",{className:"mt-0.5 font-mono text-[10px] text-[var(--text-dim)]",children:e.filePath}),((o=e.glossaryEntry)==null?void 0:o.description)&&n.jsx("p",{className:"mt-2 text-xs text-[var(--text-secondary)]",children:e.glossaryEntry.description})]})}const Gl=["scenarios","components","functions"];function La({activeTab:e,onTabChange:t,scenarioCount:r,componentCount:s=0,functionCount:a=0,callersCount:o=0,tabs:l=Gl}){const c={scenarios:"Scenarios",components:"Components",functions:"Functions",callers:"Callers"},d={scenarios:r,components:s,functions:a,callers:o};return n.jsx("div",{className:"flex w-full border-t border-b border-[var(--border-default)]",children:l.map(u=>n.jsxs("button",{onClick:()=>t(u),className:`cursor-pointer px-4 py-2 font-mono text-xs font-medium uppercase tracking-wider transition border-b-2 ${e===u?"text-[var(--accent-active)] border-[var(--accent-active)]":"text-[var(--text-dim)] border-transparent hover:text-[var(--text-muted)]"}`,type:"button",children:[c[u]," (",d[u],")"]},u))})}const Yl=["scenarios","components","functions"],ql=["scenarios","callers"];function Jl({app:e=null,navContext:t=ht,routeEntity:r=null,entity:s,selectedSlug:a,onSelectScenario:o,onNavigateToEntity:l,onScenariosChanged:c}){const[d,u]=i.useState("scenarios"),{componentRefs:f,functionRefs:p}=i.useMemo(()=>{const h=[],v=[];for(const g of s.directImports)g.kind==="function"?v.push(g):h.push(g);return{componentRefs:h,functionRefs:v}},[s.directImports]),m=s.kind==="function"?ql:Yl;return n.jsxs("div",{className:"flex flex-col",children:[n.jsx(Kl,{app:e,navContext:t,routeEntity:r,entity:s}),n.jsx(La,{activeTab:d,onTabChange:u,scenarioCount:s.scenarios.length,componentCount:f.length,functionCount:p.length,callersCount:s.callers.length,tabs:m}),n.jsx(zl,{activeTab:d,entity:s,componentRefs:f,functionRefs:p,selectedSlug:a,onSelectScenario:o,onNavigateToEntity:l,onScenariosChanged:c})]})}function Vt(e,t){const r=`${e}:${t}`;let s=2166136261;for(let a=0;a<r.length;a++)s^=r.charCodeAt(a),s=Math.imul(s,16777619);return(s>>>0).toString(16).padStart(8,"0")}function gt(e){return(e.split("/").pop()??e).replace(/\.[^.]+$/,"")}function Xl(e){const t=[],r=[];for(const s of e){const a=gt(s);/^[A-Z]/.test(a)&&!a.startsWith("use")?t.push(s):r.push(s)}return{componentImports:t,functionImports:r}}function Ql({ancestor:e,onNavigateToEntity:t}){const r=t?()=>t(Vt(e.filePath,gt(e.filePath))):void 0;return n.jsxs("div",{role:"button",tabIndex:0,onClick:r,onKeyDown:s=>{r&&(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),r())},className:"cursor-pointer rounded-md border border-[var(--border-subtle)] bg-[var(--bg-card)] px-3 py-2 transition hover:border-[var(--border-default)]",children:[n.jsx("p",{className:"text-sm font-medium text-[var(--text-primary)]",children:e.displayName}),n.jsx("p",{className:"mt-0.5 font-mono text-[10px] text-[var(--text-dim)]",children:e.filePath})]})}function Zl({layoutChain:e,onNavigateToEntity:t}){return e.length===0?null:n.jsxs("section",{className:"border-b border-[var(--border-subtle)] px-5 py-3",children:[n.jsx("h3",{className:"mb-2 text-xs font-medium uppercase tracking-wide text-[var(--text-dim)]",children:"Layout chain"}),n.jsx("div",{className:"flex flex-col gap-1",children:e.map(r=>n.jsx(Ql,{ancestor:r,onNavigateToEntity:t},`${r.kind}:${r.filePath}`))})]})}function ec({importPath:e,derivedName:t,allScenarios:r,routeEntities:s}){const a=r.filter(l=>l.scenarioType==="component"&&(l.pageFilePath===e||l.componentName===t)),o=s.filter(l=>l.directImports.length===1&&l.directImports[0]===e&>(l.directImports[0])===t);if(o.length===1){const l=o[0].scenarios,c=[...a];for(const d of l)c.some(u=>u.slug===d.slug)||c.push(d);return c}return a}function fn(e){const t=[];for(const r of e.split("/"))r===""||r==="."||(r===".."?t.pop():t.push(r));return t.join("/")}function tc(e){const t=new Map;for(const[r,s]of Object.entries(e)){const a=fn(r),o=gt(a),l=Vt(a,o);t.has(l)||t.set(l,{hash:l,filePath:a,entityName:o,imports:s.imports.map(fn),importedBy:s.importedBy.map(fn)})}return t}function nc(e,t){if(!e)return null;const r=fn(t);for(const s of e.values())if(s.filePath===r)return s;return null}function Ma(e,t){if(!e)return[];const r=[];for(const s of t){const a=nc(e,s);a&&r.push(a)}return r}function rc(e,t){return e.find(r=>r.pageFilePath===t)??null}function Ia(e){const t=e.split("/"),r=t.pop()??e,s=t.join("/");return{fileName:r,dirPath:s}}function sc({displayName:e,entity:t,isNavigable:r}){return n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("span",{className:"text-lg font-semibold text-[var(--text-secondary)]",children:e}),t?n.jsx("span",{className:"rounded bg-[var(--bg-input)] px-1.5 py-0.5 font-mono text-[9px] text-[var(--text-dim)]",children:t.hash.slice(0,8)}):null,r?n.jsx("span",{className:"ml-auto text-[10px] text-[var(--text-dim)]",children:"→"}):null]})}function ac({scenarios:e,onSelectScenario:t}){return e.length===0?n.jsx("p",{className:"mt-1 text-[10px] text-[var(--text-dim)]",children:"No scenarios"}):n.jsxs("div",{className:"mt-2 flex flex-row gap-1.5",children:[e.slice(0,4).map(r=>{const s=r.screenshotPaths[0]??null;return n.jsxs("button",{type:"button",onClick:a=>{a.stopPropagation(),t(r.slug)},className:"flex w-[192px] shrink-0 flex-col gap-1 transition",children:[n.jsx("div",{className:"rounded border border-[var(--border-subtle)] bg-[var(--bg-card)] transition hover:border-[var(--border-default)]",children:s?n.jsx("img",{src:Ge(s),alt:r.name,className:"h-[120px] w-[192px] rounded object-cover object-top",onError:a=>{a.currentTarget.style.visibility="hidden"}}):n.jsx("div",{className:"flex h-[120px] w-[192px] items-center justify-center rounded",children:n.jsx("span",{className:"text-[8px] text-[var(--text-dim)]",children:"--"})})}),n.jsx("span",{className:"w-full truncate text-center text-[10px] text-[var(--text-secondary)]",children:r.name})]},r.slug)}),e.length>4&&n.jsx("div",{className:"flex h-[120px] items-center px-1",children:n.jsxs("span",{className:"text-[10px] text-[var(--text-dim)]",children:["+",e.length-4]})})]})}function oc({importPath:e,entity:t,scenarios:r,onNavigate:s,onSelectScenario:a}){const{fileName:o,dirPath:l}=Ia(e),c=(t==null?void 0:t.entityName)??o.replace(/\.[^.]+$/,"");return n.jsxs("div",{role:s?"button":void 0,tabIndex:s?0:void 0,onClick:s??void 0,onKeyDown:s?d=>{(d.key==="Enter"||d.key===" ")&&s()}:void 0,className:`rounded-lg border border-[var(--border-subtle)] bg-[var(--bg-card)] p-3 transition hover:border-[var(--border-default)] ${s?"cursor-pointer":""}`,children:[n.jsx(sc,{displayName:c,entity:t,isNavigable:s!==null}),n.jsxs("p",{className:"mt-0.5 font-mono text-[10px] text-[var(--text-dim)]",children:[l,"/"]}),n.jsx(ac,{scenarios:r,onSelectScenario:a})]})}function ic(){return n.jsx("p",{className:"py-4 text-center text-xs text-[var(--text-dim)]",children:"No dependencies found"})}function lc({directImports:e,entityLookup:t,allScenarios:r,routeEntities:s,onNavigateToRoute:a,onNavigateToEntity:o,onSelectScenario:l}){const c=i.useMemo(()=>Ma(t,e),[t,e]);return e.length===0?n.jsx(ic,{}):n.jsx("div",{className:"grid grid-cols-1 gap-1",children:e.map(d=>{const u=c.find(g=>g.filePath===d)??null,f=(u==null?void 0:u.entityName)??gt(d),p=ec({importPath:d,derivedName:f,allScenarios:r??[],routeEntities:s??[]}),m=rc(s??[],d),h=Vt(d,f),v=m?()=>a(m.route):o?()=>o(h):null;return n.jsx(oc,{importPath:d,entity:u,scenarios:p,onNavigate:v,onSelectScenario:l},d)})})}function cc(e,t,r){const s=new Set,a=e.replace(/\.(ts|tsx)$/,"");s.add(`${a}.test.ts`),s.add(`${a}.test.tsx`);const o=t.get(e);if(o!=null&&o.importedBy)for(const c of o.importedBy)/\.test\.(ts|tsx)$/.test(c)&&s.add(c);return r.flatMap(c=>c.tests).filter(c=>s.has(c.file))}function dc({status:e}){return e==="passed"?n.jsx("span",{className:"mt-0.5 text-xs text-[var(--accent-green)]",children:"✓"}):e==="failed"?n.jsx("span",{className:"mt-0.5 text-xs text-[var(--accent-red)]",children:"✗"}):n.jsx("span",{className:"mt-0.5 text-xs text-[var(--text-dim)]",children:"○"})}function uc({test:e}){const t=e.description.length>0;return n.jsxs("div",{className:"flex items-start gap-2 py-1",children:[n.jsx(dc,{status:e.status}),n.jsx("div",{children:t?n.jsxs(n.Fragment,{children:[n.jsx("p",{className:"text-sm text-[var(--text-secondary)]",children:e.description}),n.jsx("p",{className:"font-mono text-xs text-[var(--text-dim)]",children:e.key})]}):n.jsxs(n.Fragment,{children:[n.jsx("p",{className:"text-sm text-[var(--text-secondary)]",children:e.key}),n.jsx("p",{className:"text-xs italic text-[var(--text-dim)]",children:"no description"})]})})]})}function fc({importPath:e,entityName:t,tests:r,onNavigate:s}){const{dirPath:a}=Ia(e);return n.jsxs("div",{role:s?"button":void 0,tabIndex:s?0:void 0,onClick:s??void 0,onKeyDown:s?o=>{(o.key==="Enter"||o.key===" ")&&s()}:void 0,className:`rounded-lg border border-[var(--border-subtle)] bg-[var(--bg-card)] p-3 transition hover:border-[var(--border-default)] ${s?"cursor-pointer":""}`,children:[n.jsx("p",{className:"text-sm font-medium text-[var(--text-primary)]",children:t}),n.jsxs("p",{className:"mt-0.5 font-mono text-[10px] text-[var(--text-dim)]",children:[a,"/"]}),n.jsx("div",{className:"mt-2",children:r.length>0?n.jsx("div",{className:"space-y-0.5",children:r.map((o,l)=>n.jsx(uc,{test:o},`${o.file}:${o.key??o.line??l}`))}):n.jsx("p",{className:"text-xs text-[var(--text-dim)] italic",children:"No tests"})})]})}function pc(){return n.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[n.jsx("p",{className:"text-sm text-[var(--text-muted)]",children:"No function imports found"}),n.jsx("p",{className:"mt-1 text-xs text-[var(--text-dim)]",children:"This component only imports other components"})]})}function mc({functionImports:e,entityLookup:t,testGroups:r,onNavigateToEntity:s}){const a=i.useMemo(()=>Ma(t,e),[t,e]);return e.length===0?n.jsx(pc,{}):n.jsx("div",{className:"grid grid-cols-1 gap-1",children:e.map(o=>{const l=a.find(f=>f.filePath===o)??null,c=(l==null?void 0:l.entityName)??gt(o),d=cc(o,t,r),u=s?()=>s(Vt(o,c)):null;return n.jsx(fc,{importPath:o,entityName:c,tests:d,onNavigate:u},o)})})}function hc({activeTab:e,routeEntity:t,componentImports:r,functionImports:s,testGroups:a,selectedSlug:o,entityLookup:l,allScenarios:c,routeEntities:d,onSelectScenario:u,onNavigateToRoute:f,onNavigateToEntity:p,onScenariosChanged:m}){return n.jsxs("div",{className:"flex-1 overflow-auto px-5 py-4",children:[e==="scenarios"&&n.jsx(Fa,{scenarios:t.scenarios,selectedSlug:o,onSelectScenario:u,onScenariosChanged:m}),e==="components"&&n.jsx(lc,{directImports:r,entityLookup:l,allScenarios:c,routeEntities:d,onNavigateToRoute:f,onNavigateToEntity:p,onSelectScenario:u}),e==="functions"&&n.jsx(mc,{functionImports:s,entityLookup:l,testGroups:a,onNavigateToEntity:p})]})}function xc({displayName:e,pageFilePath:t,app:r=null,routeEntity:s=null,navContext:a=ht}){return n.jsxs("div",{className:"px-5 py-4",children:[n.jsx("div",{className:"mb-2",children:n.jsx(Dr,{apps:a.apps,selectedApp:r,selectedRouteEntity:s,isSingleApp:a.isSingleApp,onSelectApps:a.onSelectApps,onSelectApp:a.onSelectApp,onSelectRoute:a.onSelectRoute})}),n.jsx("h2",{className:"text-xl font-medium text-[var(--text-primary)]",children:e}),t?n.jsx("p",{className:"mt-1 font-mono text-xs text-[var(--text-dim)]",children:t}):null]})}function gc({app:e=null,navContext:t=ht,routeEntity:r,selectedSlug:s,entityLookup:a,allScenarios:o,routeEntities:l,testGroups:c,onSelectScenario:d,onNavigateToRoute:u,onNavigateToEntity:f,onScenariosChanged:p}){const[m,h]=i.useState("scenarios"),{componentImports:v,functionImports:g}=i.useMemo(()=>Xl(r.directImports),[r.directImports]);return n.jsxs("div",{className:"flex flex-col",children:[n.jsx(xc,{app:e,navContext:t,routeEntity:r,displayName:r.displayName,pageFilePath:r.pageFilePath}),n.jsx(Zl,{layoutChain:r.layoutChain??[],onNavigateToEntity:f}),n.jsx(La,{activeTab:m,onTabChange:h,scenarioCount:r.scenarios.length,componentCount:v.length,functionCount:g.length}),n.jsx(hc,{activeTab:m,routeEntity:r,componentImports:v,functionImports:g,testGroups:c,selectedSlug:s,entityLookup:a,allScenarios:o,routeEntities:l,onSelectScenario:d,onNavigateToRoute:u,onNavigateToEntity:f,onScenariosChanged:p})]})}function Un(e){const t=pl(e);if(t)return{selectedAppDir:t,selectedEntityHash:null};const r=ml(e);return r?{selectedAppDir:null,selectedEntityHash:r}:{selectedAppDir:null,selectedEntityHash:null}}function Kn(e){return`/apps/${e}`}function bc(e){return`/entities/${e}`}function ir(e){return e.pageFilePath?Vt(e.pageFilePath,gt(e.pageFilePath)):null}function $a(e){const t=ir(e);return t===null?null:bc(t)}function Oa({href:e,onNavigate:t,children:r,...s}){return n.jsx("a",{...s,href:e,onClick:a=>{a.button===0&&!a.metaKey&&!a.ctrlKey&&!a.shiftKey&&!a.altKey&&(a.preventDefault(),t())},children:r})}function vc({scenario:e,onSelect:t}){const r=e.screenshotPaths[0]??null,[s,a]=i.useState(!1),o=r&&!s;return n.jsxs("button",{type:"button",onClick:t,className:`relative text-left w-full${t?" cursor-pointer group/thumb":""}`,children:[o?n.jsx("img",{src:Ge(r),alt:e.name,className:"aspect-[16/10] w-full rounded border border-[var(--border-subtle)] bg-[var(--bg-card)] object-cover object-top transition group-hover/thumb:border-[var(--text-dim)]",onError:()=>a(!0)}):n.jsx("div",{className:"aspect-[16/10] w-full rounded border border-[var(--border-subtle)] bg-[var(--bg-card)] flex items-center justify-center transition group-hover/thumb:border-[var(--text-dim)]",children:n.jsx("span",{className:"text-[10px] text-[var(--text-dim)]",children:"No preview"})}),e.dimensions.length>0?n.jsx("span",{className:"absolute bottom-1 right-1 rounded bg-black/60 px-1 py-0.5 text-[8px] text-white",children:e.dimensions[0]}):null,n.jsx("p",{className:"mt-1 truncate text-[10px] text-[var(--text-dim)]",children:e.name})]})}function yc({routeEntity:e,onSelectRoute:t,onSelectScenario:r}){const s=e.scenarios.length,a=$a(e),o="group flex w-full cursor-pointer items-center gap-2 text-left",l=n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"text-sm font-medium text-[var(--text-secondary)] group-hover:text-[var(--text-primary)] transition",children:e.displayName}),n.jsx("span",{className:"font-mono text-xs text-[var(--text-dim)]",children:e.route}),s>0?n.jsxs("span",{className:"text-xs text-[var(--text-dim)]",children:["[",s,"]"]}):null,n.jsx("span",{className:"ml-auto text-xs text-[var(--text-dim)] group-hover:text-[var(--text-muted)] transition",children:"›"})]});return n.jsxs("div",{className:"mb-4",children:[a?n.jsx(Oa,{href:a,onNavigate:()=>t(e.route),className:o,children:l}):n.jsx("button",{onClick:()=>t(e.route),className:o,type:"button",children:l}),s>0?n.jsx("div",{className:"mt-2 grid grid-cols-3 gap-2",children:e.scenarios.map(c=>n.jsx(vc,{scenario:c,onSelect:r?()=>r(c.slug):void 0},c.slug))}):n.jsx("p",{className:"mt-1 text-[10px] text-[var(--text-dim)]",children:"No scenarios yet"})]})}function wc(){return n.jsx("div",{className:"px-5 py-8 text-center text-[var(--text-dim)]",children:"No routes discovered yet."})}function jc(){return n.jsx("div",{className:"mb-3",children:n.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.18em] text-[var(--text-dim)]",children:"Pages"})})}function kc({routeEntities:e,onSelectRoute:t,onSelectScenario:r}){return e.length===0?n.jsx(wc,{}):n.jsxs("div",{className:"px-5 py-5",children:[n.jsx(jc,{}),n.jsx("div",{children:e.map(s=>n.jsx(yc,{routeEntity:s,onSelectRoute:t,onSelectScenario:r},s.route))})]})}function Nc({feature:e,passed:t,failed:r,total:s}){return n.jsxs("div",{className:"px-5 py-2 flex items-center gap-3",children:[n.jsx("span",{className:"text-sm font-medium text-[var(--text-primary)]",children:e}),n.jsxs("span",{className:"text-xs text-[var(--text-dim)]",children:[s," test",s!==1?"s":""]}),s>0&&n.jsxs("span",{className:`text-xs font-medium ${r>0?"text-[var(--accent-red)]":"text-[var(--accent-green)]"}`,children:[t,"/",s]})]})}function Cc({test:e}){const t=(e.description??"").length>0,r=e.status==="passed"?"text-[var(--accent-green)]":e.status==="failed"?"text-[var(--accent-red)]":"text-[var(--text-dim)]",s=e.status==="passed"?"✓":e.status==="failed"?"✗":"○";return n.jsxs("div",{className:"flex items-start gap-2 py-1 px-3",children:[n.jsx("span",{className:`text-xs leading-5 ${r}`,children:s}),n.jsx("div",{className:"min-w-0",children:t?n.jsxs(n.Fragment,{children:[n.jsx("p",{className:"text-xs text-[var(--text-secondary)] truncate",children:e.description}),n.jsx("p",{className:"font-mono text-[10px] text-[var(--text-dim)] truncate",children:e.key})]}):n.jsx("p",{className:"text-xs text-[var(--text-secondary)] truncate",children:e.key})})]})}function Sc({groups:e}){return e.length===0?n.jsx("div",{className:"px-5 py-8 text-center text-[var(--text-dim)]",children:"No tests found."}):n.jsx("div",{className:"py-3",children:e.map(t=>{const r=t.tests.filter(o=>o.status==="passed").length,s=t.tests.filter(o=>o.status==="failed").length,a=t.tests.length;return n.jsxs("div",{className:"mb-1",children:[n.jsx(Nc,{feature:t.feature,passed:r,failed:s,total:a}),n.jsx("div",{className:"px-5 pb-2",children:t.tests.map((o,l)=>n.jsx(Cc,{test:o},`${o.file}-${o.key??o.line??l}`))})]},t.feature)})})}function Ec({app:e=null,navContext:t=ht,isWeb:r,routeEntities:s,routesLoading:a,routesError:o,selectedEntityHash:l,selectedRouteEntity:c,testGroups:d,selectedSlug:u,entityLookup:f,allScenarios:p,onSelectScenario:m,onSelectRoute:h,onSelectEntity:v,onBackToRoutes:g,onScenariosChanged:y}){const j=Nl(l&&!c?l:null);return r?a?n.jsx(xs,{}):o?n.jsx(Wn,{message:o}):c?n.jsx(gc,{app:e,navContext:t,routeEntity:c,selectedSlug:u,entityLookup:f,allScenarios:p,routeEntities:s,testGroups:d,onSelectScenario:m,onNavigateToRoute:h,onNavigateToEntity:v,onScenariosChanged:y}):l?j.status==="loading"||j.status==="idle"?n.jsx(xs,{}):j.status==="not-found"?n.jsx(Wn,{message:"Entity not found. The dependency graph may need to be refreshed."}):j.status==="error"?n.jsx(Wn,{message:j.message}):n.jsx(Jl,{app:e,navContext:t,routeEntity:c,entity:j.entity,selectedSlug:u,onSelectScenario:m,onNavigateToEntity:v??(()=>{}),onScenariosChanged:y}):n.jsx(kc,{routeEntities:s,onSelectRoute:h,onSelectScenario:m}):n.jsx(Sc,{groups:d})}function Rc({app:e,showDetail:t,navContext:r=ht,stats:s,testsLoading:a,testsRefreshing:o,onRunTests:l,currentRunner:c}){return t?null:n.jsxs("div",{className:"px-5 py-4 border-b border-[var(--border-default)]",children:[n.jsx("div",{className:"mb-2",children:n.jsx(Dr,{apps:r.apps,selectedApp:e,selectedRouteEntity:null,isSingleApp:r.isSingleApp,onSelectApps:r.onSelectApps,onSelectApp:r.onSelectApp,onSelectRoute:r.onSelectRoute})}),n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("h2",{className:"text-lg font-medium text-[var(--text-primary)]",children:e.name}),n.jsx(Aa,{type:e.type})]}),e.description?n.jsx("p",{className:"text-sm text-[var(--text-muted)] mt-1",children:e.description}):null,s?n.jsx("div",{className:"mt-3",children:n.jsx(Da,{tests:s.tests,loading:a,refreshing:o,onRunTests:l,currentRunner:c})}):null]})}function Ar({coverage:e,prefix:t,testId:r,className:s,onClick:a}){if(!e||e.totalLines===0)return null;const o=`${Math.round(e.percent)}% coverage`,l=n.jsxs(n.Fragment,{children:[t??"",o]}),c=`${e.hitLines}/${e.totalLines} lines covered`;return a?n.jsx("span",{role:"button",tabIndex:0,className:s??"text-xs font-medium text-[var(--accent-active)] hover:underline cursor-pointer","data-testid":r??"coverage-badge",title:c,onClick:d=>{d.stopPropagation(),a()},onKeyDown:d=>{(d.key==="Enter"||d.key===" ")&&(d.stopPropagation(),d.preventDefault(),a())},children:l}):n.jsx("span",{className:s??"text-xs font-medium text-[var(--text-secondary)]","data-testid":r??"coverage-badge",title:c,children:l})}function Tc({projectTitle:e,coverage:t,onCoverageClick:r}){const s=typeof e=="string"&&e.length>0,a=!!(t&&t.totalLines>0);return!s&&!a?null:n.jsxs("div",{className:"px-5 pt-5 pb-3 flex items-center justify-between",children:[s?n.jsx("h2",{className:"text-lg font-semibold text-[var(--text-primary)]",children:e}):n.jsx("span",{}),n.jsx(Ar,{coverage:t,testId:"app-detail-coverage",onClick:r})]})}function Pc({name:e,id:t,capabilitiesTally:r,expanded:s,onToggle:a}){const o=e??t;return n.jsxs("button",{type:"button",onClick:a,className:"flex w-full items-center gap-2 text-left text-xs text-[var(--text-secondary)] hover:text-[var(--text-primary)]","data-testid":"stack-summary","aria-expanded":s,children:[n.jsx("span",{className:`inline-block transition-transform ${s?"rotate-90":""}`,children:"▶"}),n.jsxs("span",{className:"font-medium text-[var(--text-primary)]",children:["Stack",o?` — ${o}`:""]}),e&&t?n.jsxs("span",{className:"text-[var(--text-dim)]",children:["(",t,")"]}):null,n.jsxs("span",{className:"text-[var(--text-dim)]",children:["— ",r]})]})}const lr=["layout-web","interactions-click","interactions-touch-gestures","native-haptics","native-geolocation","native-clipboard","native-network","native-storage","routing","http-mocks","real-device"],Ba={"layout-web":{label:"Web layout",description:"Visual layout and styling rendered in the web preview"},"interactions-click":{label:"Click interactions",description:"Pointer / click-driven UI behavior"},"interactions-touch-gestures":{label:"Touch gestures",description:"Swipe, pinch, and other multi-touch gestures"},"native-haptics":{label:"Haptic feedback",description:"Vibration / tactile feedback APIs"},"native-geolocation":{label:"Geolocation",description:"Device location APIs"},"native-clipboard":{label:"Clipboard",description:"Native copy / paste access"},"native-network":{label:"Network status",description:"Connectivity / reachability APIs"},"native-storage":{label:"Persistent storage",description:"On-device persistence (preferences, local DB, secure store)"},routing:{label:"Routing",description:"Navigation between screens / pages"},"http-mocks":{label:"HTTP mocking",description:"Network requests intercepted and replayed from scenarios"},"real-device":{label:"Real-device behavior",description:"Behavior that only manifests on a physical device or native build"}},_a={verified:{label:"Verified",badgeClass:"bg-[var(--accent-green)]/20 text-[var(--accent-green)]",meaning:"The editor's scenarios actually exercise this — a regression fails a test."},stubbed:{label:"Stubbed",badgeClass:"bg-[var(--accent-orange)]/20 text-[var(--accent-orange)]",meaning:"No-op'd in web preview (e.g. a native API logged to console). Tests don't fail, but nothing is really verified — check on a real device."},manual:{label:"Manual",badgeClass:"bg-[var(--accent-blue)]/20 text-[var(--accent-blue)]",meaning:"Must be checked by hand on a real device or native build target."},"not-applicable":{label:"N/A",badgeClass:"bg-[var(--bg-subtle)] text-[var(--text-dim)]",meaning:"This stack doesn't expose the capability."}};function Dc(e){var t;return((t=Ba[e])==null?void 0:t.label)??e}function Ac(e,t){var a,o;const r=(a=Ba[e])==null?void 0:a.description,s=((o=_a[t])==null?void 0:o.meaning)??"";return r?`${r}. ${s}`:s}function Fc({capabilities:e,defaultExpanded:t=!1}){const[r,s]=i.useState(t),a=lr.filter(c=>c in e),o=Object.keys(e).filter(c=>!lr.includes(c)),l={verified:0,stubbed:0,manual:0,"not-applicable":0};for(const c of a){const d=e[c];d in l&&(l[d]+=1)}return n.jsxs("div",{className:"px-5 py-2","data-testid":"capabilities-panel",children:[n.jsxs("button",{type:"button",onClick:()=>s(c=>!c),className:"flex w-full items-center gap-2 text-left text-xs text-[var(--text-secondary)] hover:text-[var(--text-primary)]","data-testid":"capabilities-summary","aria-expanded":r,children:[n.jsx("span",{className:`inline-block transition-transform ${r?"rotate-90":""}`,children:"▶"}),n.jsx("span",{className:"font-medium text-[var(--text-primary)]",children:"Stack capabilities"}),n.jsxs("span",{className:"text-[var(--text-dim)]",children:["— ",l.verified," verified · ",l.stubbed," stubbed ·"," ",l.manual," manual · ",l["not-applicable"]," n/a"]})]}),r?n.jsxs("div",{className:"mt-2 space-y-1","data-testid":"capabilities-rows",children:[a.map(c=>n.jsx(gs,{token:c,state:e[c]},c)),o.length>0?n.jsxs("div",{className:"mt-3","data-testid":"capabilities-unknown-group",children:[n.jsxs("div",{className:"flex items-center gap-1 text-xs font-medium text-[var(--accent-warn)]",children:[n.jsx("span",{title:"These tokens aren't recognized — likely typos",children:"⚠"}),"Unknown capabilities"]}),o.map(c=>n.jsx(gs,{token:c,state:e[c],unknown:!0},c))]}):null]}):null]})}function gs({token:e,state:t,unknown:r}){const s=_a[t],a=r?"This token isn't recognized — may be a typo.":Ac(e,t);return n.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs","data-testid":`capability-row-${e}`,children:[n.jsxs("span",{className:"flex items-center gap-1 text-[var(--text-secondary)]",children:[Dc(e),n.jsx("span",{className:"cursor-help text-[var(--text-dim)]",title:a,"aria-label":a,children:"ⓘ"})]}),n.jsx("span",{className:`rounded px-1.5 py-0.5 ${(s==null?void 0:s.badgeClass)??"bg-[var(--bg-subtle)] text-[var(--text-dim)]"}`,children:(s==null?void 0:s.label)??t})]})}function Lc({capabilities:e}){return e&&Object.keys(e).length>0?n.jsx(Fc,{capabilities:e,defaultExpanded:!1}):n.jsxs("div",{className:"text-xs text-[var(--text-dim)]","data-testid":"stack-capabilities-empty-hint",children:["Capabilities not declared. Run"," ",n.jsx("code",{className:"rounded bg-[var(--bg-subtle)] px-1 py-0.5 text-[var(--text-secondary)]",children:"codeyam-editor editor capabilities-list"})," ","to learn more."]})}function Mc({fields:e,capabilities:t}){return n.jsxs("div",{className:"mt-2 space-y-2","data-testid":"stack-body",children:[e.description?n.jsx("p",{className:"text-xs text-[var(--text-secondary)]","data-testid":"stack-description",children:e.description}):null,e.technologies.length>0?n.jsx("ul",{className:"flex flex-wrap gap-1","data-testid":"stack-technologies",children:e.technologies.map(r=>n.jsx("li",{className:"rounded bg-[var(--bg-subtle)] px-1.5 py-0.5 text-[10px] text-[var(--text-secondary)]",children:r},r))}):null,e.commands.length>0?n.jsx("dl",{className:"space-y-0.5 text-xs","data-testid":"stack-commands",children:e.commands.map(({key:r,value:s})=>n.jsxs("div",{className:"flex items-baseline gap-2",children:[n.jsx("dt",{className:"w-10 text-[var(--text-dim)]",children:r}),n.jsx("dd",{className:"text-[var(--text-secondary)]",children:n.jsx("code",{className:"rounded bg-[var(--bg-subtle)] px-1 py-0.5",children:s})})]},r))}):null,e.routingSummary?n.jsxs("div",{className:"text-xs text-[var(--text-secondary)]","data-testid":"stack-routing",children:[n.jsx("span",{className:"text-[var(--text-dim)]",children:"routing"})," ",e.routingSummary]}):null,n.jsx("div",{className:"border-t border-[var(--border-subtle)] pt-2",children:n.jsx(Lc,{capabilities:t})})]})}function Ic({skip:e=!1}={}){const[t,r]=i.useState(null);return i.useEffect(()=>{if(e)return;let s=!1;return fetch("/api/project-stack").then(a=>a.ok?a.json():{}).then(a=>{s||r(a&&typeof a=="object"&&!Array.isArray(a)?a:{})}).catch(()=>{s||r({})}),()=>{s=!0}},[e]),t}const $c=["dev","test","build"];function at(e){return typeof e=="string"&&e.length>0?e:null}function za(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Oc(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Bc(e){const t=za(e);if(!t)return[];const r=[];for(const s of $c){const a=at(t[s]);a&&r.push({key:s,value:a})}return r}function _c(e){const t=za(e);if(!t)return null;const r=at(t.type);if(!r)return null;const s=at(t.pagesDir)??at(t.isolationRoute)??at(t.componentManifest);return s?`${r} (${s})`:r}function zc(e){const t=e.capabilities;return!t||typeof t!="object"||Array.isArray(t)?null:t}function Hc(e){if(!e||Object.keys(e).length===0)return"capabilities not declared";const t={verified:0,stubbed:0,manual:0,"not-applicable":0};for(const r of lr){const s=e[r];s&&s in t&&(t[s]+=1)}return`${t.verified} verified · ${t.stubbed} stubbed · ${t.manual} manual · ${t["not-applicable"]} n/a`}function Wc(e){return e?{id:at(e.id),name:at(e.name),description:at(e.description),technologies:Oc(e.technologies),commands:Bc(e.commands),routingSummary:_c(e.routing)}:{id:null,name:null,description:null,technologies:[],commands:[],routingSummary:null}}function Vc({stack:e,defaultExpanded:t=!1}){const r=e!==void 0,[s,a]=i.useState(t),o=Ic({skip:r}),l=r?e:o;if(!l||Object.keys(l).length===0)return null;const c=Wc(l),d=zc(l);return n.jsxs("div",{className:"px-5 py-2","data-testid":"stack-panel",children:[n.jsx(Pc,{name:c.name,id:c.id,capabilitiesTally:Hc(d),expanded:s,onToggle:()=>a(u=>!u)}),s?n.jsx(Mc,{fields:c,capabilities:d}):null]})}function Uc({app:e,navContext:t=ht,routeEntities:r,routesLoading:s,routesError:a,selectedEntityHash:o,selectedRouteEntity:l,testGroups:c,selectedSlug:d,entityLookup:u,allScenarios:f,onSelectScenario:p,onSelectRoute:m,onSelectEntity:h,onBackToRoutes:v,onScenariosChanged:g,projectTitle:y,coverage:j,showProjectBand:b,onCoverageClick:x,stats:w,testsLoading:k,testsRefreshing:C,onRunTests:N,currentRunner:E}){const R=e.type==="web",S=!!b&&!l;return n.jsxs("div",{children:[S?n.jsxs(n.Fragment,{children:[n.jsx(Tc,{projectTitle:y,coverage:j,onCoverageClick:x}),n.jsx(Vc,{})]}):null,n.jsx(Rc,{app:e,showDetail:!!(l||o),navContext:t,stats:w,testsLoading:k,testsRefreshing:C,onRunTests:N,currentRunner:E}),n.jsx(Ec,{app:e,navContext:t,isWeb:R,routeEntities:r,routesLoading:s,routesError:a,selectedEntityHash:o??null,selectedRouteEntity:l,testGroups:c,selectedSlug:d,entityLookup:u,allScenarios:f,onSelectScenario:p,onSelectRoute:m,onSelectEntity:h,onBackToRoutes:v,onScenariosChanged:g})]})}function Ha(e){const t=new Date(e);if(isNaN(t.getTime()))return e;const r=new Date,s=r.getTime()-t.getTime(),a=Math.floor(s/6e4),o=Math.floor(s/36e5),l=Math.floor(s/864e5);return a<1?"just now":a<60?`${a}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:t.toLocaleDateString("en-US",{month:"short",day:"numeric",year:t.getFullYear()!==r.getFullYear()?"numeric":void 0})}function Kc(e){switch(e){case"feature":return"text-[#D7FF63]";case"fix":return"text-red-400";case"refactor":return"text-purple-400";case"milestone":return"text-yellow-400";default:return"text-gray-400"}}function T1(e){let t=0,r=0,s=0;for(const a of e)a.status==="added"?t++:a.status==="deleted"?s++:r++;return{added:t,modified:r,deleted:s}}function Gc({total:e,passed:t,failed:r}){if(e===0)return null;const s=r>0?"text-[var(--accent-red)]":"text-[var(--accent-green)]";return n.jsxs("span",{className:`text-xs ${s}`,children:[t,"/",e," passed"]})}const Yc=192;function Wa({children:e,variant:t="compact",maxHeight:r=Yc}){const s=i.useRef(null),[a,o]=i.useState(!1),[l,c]=i.useState(!1);return i.useEffect(()=>{const d=s.current;if(!d)return;const u=()=>c(d.scrollHeight>r);u();const f=new ResizeObserver(u);return f.observe(d),()=>f.disconnect()},[e,r]),n.jsxs("div",{children:[n.jsxs("div",{ref:s,style:{maxHeight:a?"none":`${r}px`,overflow:"hidden",position:"relative"},children:[n.jsx(mt,{variant:t,children:e}),!a&&l&&n.jsx("div",{style:{position:"absolute",bottom:0,left:0,right:0,height:"2rem",background:"linear-gradient(transparent, var(--bg-card))",pointerEvents:"none"}})]}),l&&n.jsx("button",{onClick:()=>o(d=>!d),className:"text-xs cursor-pointer mt-1",style:{color:"var(--accent-blue)",background:"none",border:"none",padding:0},children:a?"Show less":"Show more"})]})}function qc({screenshots:e}){return e.length===0?null:n.jsx("div",{className:"flex flex-wrap gap-2",children:e.map((t,r)=>n.jsxs("div",{className:"text-center",children:[t.screenshotPath?n.jsx("img",{src:Ge(t.screenshotPath),alt:t.name,className:"h-16 w-24 rounded border border-[var(--border-default)] object-cover"}):n.jsx("div",{className:"flex h-16 w-24 items-center justify-center rounded border border-dashed border-[var(--border-default)] text-xs text-[var(--text-dim)]",children:"No shot"}),n.jsx("p",{className:"mt-0.5 text-xs text-[var(--text-dim)] truncate w-24",children:t.name})]},`${t.screenshotPath??"missing"}:${t.name}:${r}`))})}const Jc={1:"Plan",2:"Explore",3:"Confirm",4:"Prepare",5:"Seed Data",6:"Live Preview Loop",7:"Verify Prototype",8:"Confirm Mode",9:"Demo",10:"Deconstruct",11:"Extract TDD",12:"Glossary",13:"Dependency Graph",14:"Isolation Routes",15:"Component Scenarios",16:"App Scenarios",17:"Present",18:"Reconcile",19:"Finalize",20:"Journal",21:"Pre-Commit Sync",22:"Commit",23:"Push",24:"Feature Complete"},Xc={1:"Plan",2:"Explore",3:"Confirm Plan",4:"Prepare",5:"Prototype",6:"Confirm Mode",7:"Demo",8:"Deconstruct",9:"Extract TDD",10:"Glossary",11:"Dependency Graph",12:"Present",13:"Reconcile",14:"Finalize",15:"Journal",16:"Pre-Commit Sync",17:"Commit",18:"Push",19:"Feature Complete"},Qc={1:"Plan the feature and confirm the approach with the user before writing any code.",2:"Map out all the files you'll need to read or modify; check for reference implementations.",3:"Repeat the plan back to the user and gate on explicit approval before any code is written.",4:"Prepare the project environment and dependencies for prototyping.",5:"Wire up API routes and seed the database with realistic, demo-rich data.",6:"Iterate on the prototype with the live preview — navigate, edit, verify.",7:"Verify the prototype's routes, images, and client errors before presenting.",8:"Confirm or switch the workflow mode before the demo.",9:"Present the live preview and get user approval to proceed.",10:"Read the code and plan all component and function extractions.",11:"Extract components and functions via TDD; cover library functions with multiple tests.",12:"Register every new test and glossary entry produced in the prior step.",13:"Rebuild the dependency graph after extraction.",14:"Create isolation routes for every visual component.",15:"Register and capture component-level scenarios for every visual component.",16:"Create app-level scenarios that show full pages with realistic data.",17:"Final approval gate — recapture screenshots and present a summary of all work to the user.",18:"Run the audit gate, reconcile any registry/glossary drift until clean.",19:"Finalize the session — run the full suite once.",20:"Create or update the journal entry documenting what was built.",21:"Sync local state with the remote so the next commit lands on a merged tree.",22:"Commit all changes to git.",23:"Push the branch to the remote repository.",24:"Fire the feature-complete modal — the cycle ends here."},Zc={1:"Plan the feature and confirm the approach with the user before writing any code.",2:"Map out all the files you'll need to read or modify; check for reference implementations.",3:"Repeat the plan back to the user and gate on explicit approval before any code is written.",4:"Prepare the project environment.",5:"Build the feature. Tests come at the Deconstruct cluster.",6:"Confirm or switch the workflow mode before the demo.",7:"Show the prototype results and gate on the user's yes/iterate decision before any verification work.",8:"Read the code and plan all function/method/helper extractions.",9:"Extract functions/methods/helpers via TDD; every change must have a red-if-reverted test.",10:"Register every new test and glossary entry produced in the prior step.",11:"Rebuild the dependency graph after extraction.",12:"Present the /results page with architecture diagram, tests, and changed files.",13:"Run the audit gate, reconcile any registry/glossary drift until clean.",14:"Finalize the session — run the full suite once.",15:"Author the session narrative against post-Verify code, then create the journal entry.",16:"Sync local state with the remote so the next commit lands on a merged tree.",17:"Commit all changes to git.",18:"Push the branch to the remote repository.",19:"Fire the feature-complete modal — the cycle ends here."},ed=24,Va=19;function Ye(e){return e==="backend"?"backend":"ui"}function Fr(e,t){return(Ye(t)==="backend"?Xc:Jc)[e]??"?"}function td(e,t){return(Ye(t)==="backend"?Zc:Qc)[e]??""}function nd(e){return Ye(e)==="backend"?Va:ed}function rd(e){return Ye(e)==="backend"?"Backend Flow":"UI Flow"}function Ua(e,t){const r=Ye(t);return{description:td(e,r),label:Fr(e,r),prefix:rd(r),totalSteps:nd(r)}}const sd=[{phaseId:"understand",phaseLabel:"Understanding your idea",phaseSteps:[1,2,3]},{phaseId:"setup",phaseLabel:"Setting things up",phaseSteps:[4,5]},{phaseId:"build",phaseLabel:"Building your app",phaseSteps:[6,7,8,9]},{phaseId:"tidy",phaseLabel:"Making the code maintainable",phaseSteps:[10,11,12,13,14,15,16]},{phaseId:"review",phaseLabel:"Final Review",phaseSteps:[17,18,19,20,21]},{phaseId:"save",phaseLabel:"Saving your work",phaseSteps:[22,23,24]}],ad=[{phaseId:"understand",phaseLabel:"Understanding your idea",phaseSteps:[1,2,3]},{phaseId:"setup",phaseLabel:"Setting things up",phaseSteps:[4]},{phaseId:"build",phaseLabel:"Building your app",phaseSteps:[5,6,7]},{phaseId:"tidy",phaseLabel:"Making the code maintainable",phaseSteps:[8,9,10,11]},{phaseId:"review",phaseLabel:"Final Review",phaseSteps:[12,13,14,15,16]},{phaseId:"save",phaseLabel:"Saving your work",phaseSteps:[17,18,19]}];function od(e){return Ye(e)==="backend"?ad:sd}function id({currentStep:e}){const t=Array.from({length:Va},(r,s)=>s+1);return n.jsx("div",{className:"bg-[var(--bg-card)] border border-[var(--border-default)] rounded-lg p-4 overflow-x-auto",children:n.jsx("div",{className:"flex items-center gap-1 min-w-max",children:t.map((r,s)=>{const a=r<e,o=r===e,l=Fr(r,"backend");return n.jsxs("div",{className:"flex items-center",children:[s>0&&n.jsx("div",{className:`w-4 h-px mx-0.5 ${a?"bg-[#005c75]":"bg-[var(--border-default)]"}`}),n.jsxs("div",{className:`flex items-center gap-1 px-2 py-1 rounded text-xs whitespace-nowrap ${o?"bg-[#005c75] text-white font-medium":a?"bg-[#e0f5f9] text-[#005c75] font-medium":"text-[var(--text-muted)]"}`,children:[a&&n.jsx("span",{className:"text-[10px]",children:"✓"}),o&&n.jsx("span",{className:"text-[10px]",children:"●"}),l]})]},r)})})})}function cr(e){if(e<1e3)return`${e}ms`;const t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;const r=Math.floor(t/60),s=(t%60).toFixed(0);return`${r}m ${s}s`}function ld({stats:e}){const[t,r]=i.useState(!1);if(!e)return n.jsx("div",{className:"bg-[var(--bg-card)] border border-[var(--border-default)] rounded-lg px-4 py-2 text-center","data-testid":"runner-stats-bar",children:n.jsx("span",{className:"text-xs text-[var(--text-muted)]",children:"No test results cached"})});const s=e.per_runner&&e.per_runner.length>1;return n.jsxs("div",{className:"bg-[var(--bg-card)] border border-[var(--border-default)] rounded-lg px-4 py-2","data-testid":"runner-stats-bar",children:[n.jsxs("div",{className:`flex items-center justify-between ${s?"cursor-pointer":""}`,onClick:()=>s&&r(!t),children:[n.jsxs("div",{className:"flex items-center gap-4",children:[n.jsxs("span",{className:"text-sm font-medium text-[var(--text-primary)]","data-testid":"runner-stats-total",children:[e.total," tests"]}),e.passed>0&&n.jsxs("span",{className:"text-xs text-green-600 font-medium","data-testid":"runner-stats-passed",children:[e.passed," passed"]}),e.failed>0&&n.jsxs("span",{className:"text-xs text-red-500 font-medium","data-testid":"runner-stats-failed",children:[e.failed," failed"]}),e.ignored>0&&n.jsxs("span",{className:"text-xs text-[var(--text-muted)] font-medium","data-testid":"runner-stats-ignored",children:[e.ignored," ignored"]}),e.duration_ms!=null&&n.jsx("span",{className:"text-xs text-[var(--text-muted)]","data-testid":"runner-stats-duration",children:cr(e.duration_ms)})]}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[e.runners.map(a=>n.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-[var(--bg-input)] text-[var(--text-secondary)] rounded font-mono","data-testid":"runner-badge",children:a},a)),s&&n.jsx("span",{className:"text-xs text-[var(--text-muted)] ml-1",children:t?"▲":"▼"})]})]}),t&&s&&n.jsx("div",{className:"mt-2 pt-2 border-t border-[var(--border-subtle)] space-y-1","data-testid":"per-runner-breakdown",children:e.per_runner.map(a=>n.jsxs("div",{className:"flex items-center justify-between text-xs","data-testid":"per-runner-row",children:[n.jsx("span",{className:"font-mono text-[var(--text-secondary)]",children:a.name}),n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsxs("span",{className:"text-[var(--text-muted)]",children:[a.total," tests"]}),a.passed>0&&n.jsxs("span",{className:"text-green-600",children:[a.passed," passed"]}),a.failed>0&&n.jsxs("span",{className:"text-red-500",children:[a.failed," failed"]}),a.ignored>0&&n.jsxs("span",{className:"text-[var(--text-muted)]",children:[a.ignored," ignored"]}),a.duration_ms!=null&&n.jsx("span",{className:"text-[var(--text-muted)]",children:cr(a.duration_ms)})]})]},a.name))})]})}function Ka({status:e}){switch(e){case"passing":return n.jsx("span",{className:"text-green-500 text-xs mt-0.5 shrink-0",children:"✓"});case"failing":return n.jsx("span",{className:"text-red-500 text-xs mt-0.5 shrink-0",children:"✗"});case"running":return n.jsx("span",{className:"text-[#D7FF63] text-xs mt-0.5 shrink-0 animate-spin",children:"◠"});default:return n.jsx("span",{className:"text-gray-400 text-xs mt-0.5 shrink-0",children:"●"})}}function cd({narrative:e}){const t=e.changes.flatMap(l=>l.tests);if(t.length===0)return null;const r=t.filter(l=>l.verified===!0),s=t.filter(l=>l.verified===!1),a=r.filter(l=>l.status==="passing").length,o=r.filter(l=>l.status==="failing").length;return n.jsxs("div",{className:"bg-[var(--bg-card)] border border-[var(--border-default)] rounded-lg overflow-hidden","data-testid":"tests-summary-card",children:[n.jsxs("div",{className:"px-4 py-2 border-b border-[var(--border-subtle)] bg-[var(--bg-input)] flex items-center justify-between",children:[n.jsx("h2",{className:"text-sm font-semibold text-[var(--text-primary)] m-0",children:"Tests"}),n.jsxs("div",{className:"flex items-center gap-3 text-xs",children:[a>0&&n.jsxs("span",{className:"text-green-600 font-medium",children:[a," passing"]}),o>0&&n.jsxs("span",{className:"text-red-500 font-medium",children:[o," failing"]}),s.length>0&&n.jsxs("span",{className:"text-amber-600 font-medium","data-testid":"unverified-count",children:[s.length," unverified"]})]})]}),n.jsxs("div",{className:"p-3 space-y-1",children:[r.map(l=>n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Ka,{status:l.status}),n.jsx("span",{className:"text-xs text-[var(--text-secondary)] font-mono",children:l.name}),l.file&&n.jsx("span",{className:"text-[10px] text-[var(--text-muted)] font-mono",children:l.file})]},l.name)),s.length>0&&n.jsxs("div",{className:"mt-2 pt-2 border-t border-amber-200","data-testid":"unverified-tests",children:[n.jsx("div",{className:"text-[10px] font-medium text-amber-600 mb-1",children:"Unverified — not found in test files"}),s.map(l=>n.jsxs("div",{className:"flex items-center gap-2 opacity-50",children:[n.jsx("span",{className:"text-amber-500 text-xs",children:"?"}),n.jsx("span",{className:"text-xs text-[var(--text-muted)] font-mono line-through",children:l.name})]},l.name))]})]})]})}function dd({narrative:e}){return n.jsxs("div",{className:"space-y-4",children:[n.jsx("div",{className:"bg-[var(--bg-card)] border border-[var(--border-default)] rounded-lg p-4",children:n.jsx("p",{className:"text-sm text-[var(--text-primary)] leading-relaxed",children:e.summary})}),e.changes.map((t,r)=>n.jsx(ud,{change:t},r))]})}function ud({change:e}){const[t,r]=i.useState(!1),s=e.tests.filter(l=>l.verified!==!1),a=s.filter(l=>l.status==="passing").length,o=s.filter(l=>l.status==="failing").length;return n.jsxs("div",{className:"bg-[var(--bg-card)] border border-[var(--border-default)] rounded-lg overflow-hidden","data-testid":"narrative-change-card",children:[n.jsx("div",{className:"p-4 cursor-pointer select-none",onClick:()=>r(!t),"data-testid":"narrative-change-header",children:n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("h3",{className:"text-sm font-semibold text-[var(--text-primary)] m-0",children:e.title}),n.jsxs("div",{className:"flex items-center gap-2",children:[t&&s.length>0&&n.jsxs("span",{className:"text-[10px] text-[var(--text-muted)]","data-testid":"collapsed-test-summary",children:[a>0&&n.jsxs("span",{className:"text-green-600",children:[a,"✓"]}),o>0&&n.jsxs("span",{className:"text-red-500 ml-1",children:[o,"✗"]})]}),n.jsx("span",{className:"text-[var(--text-muted)] text-xs",children:t?"▶":"▼"})]})]})}),!t&&n.jsxs("div",{className:"px-4 pb-4 -mt-2",children:[n.jsx("p",{className:"text-sm text-[var(--text-secondary)] m-0",children:e.description}),e.files.length>0&&n.jsx("div",{className:"mt-2 space-y-0.5",children:e.files.map(l=>n.jsx("div",{className:"text-xs text-[var(--text-muted)] font-mono",children:l},l))}),e.tests.length>0&&n.jsxs("div",{className:"mt-3 space-y-1.5",children:[s.map(l=>n.jsx(fd,{test:l},l.name)),e.tests.some(l=>l.verified===!1)&&n.jsxs("div",{className:"text-[10px] text-amber-600 mt-1",children:[e.tests.filter(l=>l.verified===!1).length," test(s) not found in source files"]})]})]})]})}function fd({test:e}){const[t,r]=i.useState(!1),s=e.status==="failing"&&e.failureMessage;return n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx(Ka,{status:e.status}),n.jsxs("div",{className:"flex-1",children:[e.description&&n.jsx("div",{className:"text-xs text-[var(--text-secondary)] leading-relaxed",children:e.description}),n.jsx("div",{className:"text-[11px] text-[var(--text-muted)] font-mono",children:e.name}),e.file&&n.jsx("div",{className:"text-[10px] text-[var(--text-dim)] font-mono",children:e.file}),s&&n.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-600 mt-0.5 underline cursor-pointer",onClick:()=>r(!t),"data-testid":"toggle-failure-message",children:t?"Hide error":"Show error"})]})]}),s&&t&&n.jsx("div",{className:"mt-1 ml-5 p-2 bg-red-50 border border-red-200 rounded text-[11px] font-mono text-red-700 whitespace-pre-wrap overflow-x-auto","data-testid":"failure-message",children:e.failureMessage})]})}function pd({step:e,fileCount:t,testCount:r}){return n.jsx("div",{className:"bg-[var(--bg-card)] border border-[var(--border-default)] rounded-lg p-6 text-center",children:e<=2?n.jsx("p",{className:"text-sm text-[var(--text-muted)]",children:"Build will begin at the Prototype step."}):n.jsxs("div",{className:"space-y-2",children:[n.jsx("p",{className:"text-sm text-[var(--text-secondary)]",children:"Building in progress..."}),n.jsxs("div",{className:"flex justify-center gap-6",children:[n.jsx(bs,{label:"Files Modified",value:t}),n.jsx(bs,{label:"Tests Modified",value:r,color:r>0?"green":void 0})]})]})})}function bs({label:e,value:t,color:r}){return n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:`text-lg font-bold ${r==="green"?"text-green-600":"text-[var(--text-primary)]"}`,children:t}),n.jsx("span",{className:"text-xs text-[var(--text-muted)]",children:e})]})}function Lr({status:e}){const t=e==="added"?"var(--accent-green)":e==="deleted"?"var(--accent-red)":"var(--accent-blue)",r=e==="added"?"+":e==="deleted"?"-":"~";return n.jsx("span",{className:"font-mono text-xs font-semibold",style:{color:t,minWidth:"0.75rem",textAlign:"center"},children:r})}const md=[/\.test\.[jt]sx?$/,/\.spec\.[jt]sx?$/,/__tests__\//,/tests?\//];function Gn(e){return md.some(t=>t.test(e))}function hd({files:e,defaultCollapsed:t}){const[r,s]=i.useState(t),a=e.filter(d=>d.path&&Gn(d.path)),o=e.filter(d=>d.path&&d.path.endsWith(".rs")&&!Gn(d.path)),l=e.filter(d=>d.path&&(d.path.endsWith(".json")||d.path.endsWith(".toml")||d.path.endsWith(".lock")||d.path.endsWith(".txt"))),c=e.filter(d=>d.path&&!Gn(d.path)&&!d.path.endsWith(".rs")&&!d.path.endsWith(".json")&&!d.path.endsWith(".toml")&&!d.path.endsWith(".lock")&&!d.path.endsWith(".txt"));return n.jsxs("div",{className:"bg-[var(--bg-card)] border border-[var(--border-default)] rounded-lg overflow-hidden","data-testid":"modified-files-section",children:[n.jsxs("div",{className:"px-4 py-2 border-b border-[var(--border-subtle)] bg-[var(--bg-input)] cursor-pointer select-none flex items-center justify-between",onClick:()=>s(!r),"data-testid":"modified-files-header",children:[n.jsxs("h2",{className:"text-sm font-semibold text-[var(--text-primary)] m-0",children:["Modified Files (",e.length,")"]}),n.jsx("span",{className:"text-[var(--text-muted)] text-xs",children:r?"▶":"▼"})]}),!r&&n.jsxs("div",{className:"divide-y divide-gray-100",children:[a.length>0&&n.jsx(tn,{title:"Tests",files:a}),o.length>0&&n.jsx(tn,{title:"Rust Source",files:o}),c.length>0&&n.jsx(tn,{title:"Other Source",files:c}),l.length>0&&n.jsx(tn,{title:"Configuration",files:l})]})]})}function tn({title:e,files:t}){return n.jsxs("div",{className:"p-3","data-testid":"file-group",children:[n.jsxs("div",{className:"text-xs font-medium text-[var(--text-secondary)] mb-1","data-testid":"file-group-title",children:[e," (",t.length,")"]}),n.jsx("div",{className:"space-y-0.5",children:t.map(r=>n.jsxs("div",{className:"text-xs text-[var(--text-secondary)] font-mono pl-4 flex items-center gap-1",children:[n.jsx(Lr,{status:r.status}),n.jsx("span",{children:r.path})]},r.path))})]})}const xd=5e3,vs=50;function gd(){const[e,t]=i.useState([]),[r,s]=i.useState(0),[a,o]=i.useState(null),[l,c]=i.useState(!0),[d,u]=i.useState(!1),[f,p]=i.useState(null),m=i.useRef("idle"),h=i.useRef([]),v=i.useRef(null);i.useEffect(()=>{h.current=e},[e]),i.useEffect(()=>{v.current=a},[a]);const g=i.useCallback(async()=>{if(m.current==="idle"){m.current="initial",c(!0),p(null);try{const b=await fetch(`/api/history?limit=${vs}`);if(!b.ok)throw new Error(`HTTP ${b.status}`);const x=await b.json();t(x.entries??[]),s(x.total??0),o(x.nextCursor??null),x.error&&p(x.error)}catch(b){p(b instanceof Error?b.message:"Failed to load history")}finally{c(!1),m.current="idle"}}},[]),y=i.useCallback(async()=>{var x;if(m.current!=="idle")return;const b=(x=h.current[0])==null?void 0:x.commit.sha;if(!b){await g();return}m.current="poll";try{const w=await fetch(`/api/history?since=${encodeURIComponent(b)}`);if(!w.ok)throw new Error(`HTTP ${w.status}`);const k=await w.json(),C=new Set(h.current.map(E=>E.commit.sha)),N=(k.entries??[]).filter(E=>!C.has(E.commit.sha));N.length>0&&(t(E=>[...N,...E]),s(E=>E+N.length))}catch(w){p(w instanceof Error?w.message:"Failed to poll history")}finally{m.current="idle"}},[g]),j=i.useCallback(async()=>{if(m.current!=="idle")return;const b=v.current;if(b){m.current="more",u(!0);try{const x=await fetch(`/api/history?limit=${vs}&before=${encodeURIComponent(b)}`);if(!x.ok)throw new Error(`HTTP ${x.status}`);const w=await x.json();t(k=>[...k,...w.entries??[]]),o(w.nextCursor??null),typeof w.total=="number"&&s(w.total)}catch(x){p(x instanceof Error?x.message:"Failed to load more commits")}finally{u(!1),m.current="idle"}}},[]);return i.useEffect(()=>{g();const b=setInterval(()=>{y()},xd);return()=>clearInterval(b)},[g,y]),{rows:e,total:r,hasMore:a!==null,loading:l,loadingMore:d,error:f,loadMore:j,reload:g}}function bd({commit:e}){return n.jsxs("div",{className:"rounded-lg border px-4 py-3",style:{borderColor:"var(--border-default)",background:"var(--bg-card)"},children:[n.jsxs("div",{className:"flex items-center gap-2 text-xs",style:{color:"var(--text-dim)"},children:[n.jsx("span",{className:"font-mono uppercase tracking-wide",style:{color:"var(--text-muted)"},children:"commit"}),n.jsx("span",{className:"font-mono",style:{color:"var(--text-secondary)"},children:e.shortSha}),n.jsx("span",{"aria-hidden":!0,children:"·"}),n.jsx("span",{children:Ha(e.timestamp)}),e.authorName&&n.jsxs(n.Fragment,{children:[n.jsx("span",{"aria-hidden":!0,children:"·"}),n.jsx("span",{children:e.authorName})]})]}),n.jsx("p",{className:"mt-1 text-sm truncate",style:{color:"var(--text-primary)"},children:e.subject})]})}const vd=[/\.test\.[jt]sx?$/,/\.spec\.[jt]sx?$/,/__tests__\//,/tests?\//];function yd(e){return e.filter(t=>vd.some(r=>r.test(t.path)))}function Ga({entry:e,commit:t}){const r=yd(e.modifiedFiles??[]);return n.jsxs("div",{className:"rounded-lg border",style:{borderColor:"var(--border-default)",background:"var(--bg-card)"},children:[n.jsxs("div",{className:"px-4 pt-4 pb-3",style:{borderBottom:"1px solid var(--border-subtle)"},children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[n.jsx("span",{className:`text-xs font-medium uppercase tracking-wide ${Kc(e.type)}`,children:e.type}),n.jsx("span",{className:"text-xs",style:{color:"var(--text-dim)"},children:Ha(e.timestamp)}),t&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"text-xs",style:{color:"var(--text-dim)"},children:"·"}),n.jsx("span",{className:"font-mono text-xs",style:{color:"var(--text-secondary)"},children:t.shortSha}),t.authorName&&n.jsxs("span",{className:"text-xs",style:{color:"var(--text-dim)"},children:["· ",t.authorName]})]})]}),n.jsx("h3",{className:"text-sm font-semibold",style:{color:"var(--text-primary)"},children:e.title})]}),n.jsxs("div",{className:"px-4 py-3 flex flex-col gap-3",children:[e.userRequest&&n.jsxs("div",{children:[n.jsx("p",{className:"text-xs font-medium mb-1",style:{color:"var(--text-muted)"},children:"Prompt"}),n.jsx(Wa,{children:e.userRequest})]}),(e.scenarioScreenshots??[]).length>0&&n.jsxs("div",{children:[n.jsx("p",{className:"text-xs font-medium mb-1",style:{color:"var(--text-muted)"},children:"Screenshots"}),n.jsx(qc,{screenshots:e.scenarioScreenshots??[]})]}),n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[n.jsx("p",{className:"text-xs font-medium",style:{color:"var(--text-muted)"},children:"Tests"}),e.testResults&&n.jsx(Gc,{total:e.testResults.total,passed:e.testResults.passed,failed:e.testResults.failed})]}),r.length>0?n.jsx("ul",{className:"flex flex-col gap-0.5",children:r.map(s=>n.jsxs("li",{className:"flex items-center gap-1.5",children:[n.jsx(Lr,{status:s.status}),n.jsx("span",{className:"font-mono text-xs truncate",style:{color:"var(--text-secondary)"},children:s.path})]},s.path))}):n.jsx("p",{className:"text-xs",style:{color:"var(--text-dim)"},children:"No test files changed"})]})]})]})}function Mr({children:e,testId:t}){return n.jsx("div",{className:"overflow-y-auto px-4 py-4",style:{maxHeight:"calc(100vh - 110px)"},"data-testid":t,children:e})}function wd(){const{rows:e,total:t,hasMore:r,loading:s,loadingMore:a,error:o,loadMore:l}=gd();if(s)return n.jsx("div",{className:"py-12 text-center text-[var(--text-muted)]",children:"Loading history..."});if(o&&e.length===0)return n.jsxs("div",{className:"py-12 text-center text-[var(--accent-red)]",children:["Failed to load history: ",o]});if(e.length===0)return n.jsxs("div",{className:"py-12 text-center text-[var(--text-dim)]",children:[n.jsx("p",{children:"No commits yet."}),n.jsx("p",{className:"mt-2 text-sm",children:"Commits and journal entries will appear here as you build features."})]});const c=Math.max(t,e.length);return n.jsxs(Mr,{children:[n.jsxs("p",{className:"mb-3 text-xs",style:{color:"var(--text-dim)"},children:[e.length," of ",c," commit",c===1?"":"s"]}),n.jsx("div",{className:"flex flex-col gap-3",children:e.map(d=>d.entry?n.jsx(Ga,{entry:d.entry,commit:d.commit},d.commit.sha):n.jsx(bd,{commit:d.commit},d.commit.sha))}),r?n.jsx("div",{className:"mt-4 flex justify-center",children:n.jsx("button",{type:"button",onClick:()=>void l(),disabled:a,className:"rounded border border-[var(--border)] px-3 py-1 text-sm text-[var(--text-muted)] hover:bg-[var(--bg-subtle)] disabled:opacity-50",children:a?"Loading...":"Load older commits"})}):null]})}const Yn={sound:"soft-double-tap",systemNotification:!0,idleOnStop:!1,idleOnNotification:!0},jd=[{id:"soft-double-tap",label:"Soft double tap"},{id:"gentle-chime",label:"Gentle chime"},{id:"warm-ding",label:"Warm ding"},{id:"mellow-two-tone",label:"Mellow two-tone"},{id:"triangle-bell",label:"Triangle bell"},{id:"off",label:"No sound"}],Ya="codeyam-editor-notifications";function kd(){try{const e=localStorage.getItem(Ya);if(!e)return Yn;const t=JSON.parse(e);return{...Yn,...t}}catch{return Yn}}function Nd(e){localStorage.setItem(Ya,JSON.stringify(e))}const Cd={"soft-double-tap":e=>([0,.12].forEach(t=>{const r=e.createOscillator(),s=e.createGain();r.connect(s),s.connect(e.destination),r.type="sine",r.frequency.value=392,s.gain.setValueAtTime(.25,e.currentTime+t),s.gain.exponentialRampToValueAtTime(.01,e.currentTime+t+.1),r.start(e.currentTime+t),r.stop(e.currentTime+t+.1)}),{count:2,longestStopSec:.22}),"gentle-chime":e=>{const t=e.createOscillator(),r=e.createGain();return t.connect(r),r.connect(e.destination),t.type="sine",t.frequency.setValueAtTime(523,e.currentTime),t.frequency.setValueAtTime(659,e.currentTime+.15),r.gain.setValueAtTime(.3,e.currentTime),r.gain.exponentialRampToValueAtTime(.01,e.currentTime+.4),t.start(),t.stop(e.currentTime+.4),{count:1,longestStopSec:.4}},"warm-ding":e=>{const t=e.createOscillator(),r=e.createGain();return t.connect(r),r.connect(e.destination),t.type="sine",t.frequency.value=330,r.gain.setValueAtTime(.35,e.currentTime),r.gain.exponentialRampToValueAtTime(.01,e.currentTime+.6),t.start(),t.stop(e.currentTime+.6),{count:1,longestStopSec:.6}},"mellow-two-tone":e=>{const t=e.createOscillator(),r=e.createGain();return t.connect(r),r.connect(e.destination),t.type="sine",t.frequency.setValueAtTime(294,e.currentTime),t.frequency.setValueAtTime(440,e.currentTime+.18),r.gain.setValueAtTime(.3,e.currentTime),r.gain.exponentialRampToValueAtTime(.01,e.currentTime+.5),t.start(),t.stop(e.currentTime+.5),{count:1,longestStopSec:.5}},"triangle-bell":e=>{const t=e.createOscillator(),r=e.createGain();return t.connect(r),r.connect(e.destination),t.type="triangle",t.frequency.value=523,r.gain.setValueAtTime(.4,e.currentTime),r.gain.exponentialRampToValueAtTime(.01,e.currentTime+.8),t.start(),t.stop(e.currentTime+.8),{count:1,longestStopSec:.8}}};function qn(e,t){const r=t;V(e,{name:r==null?void 0:r.name,message:r==null?void 0:r.message})}function qa(e){if(e==="off")return;V("audio-playsound-entered",{soundId:e});let t;try{t=new AudioContext}catch(s){qn("audio-context-failed",s);return}V("audio-context-created",{state:t.state});const r=()=>{let s;try{s=Cd[e](t)}catch(a){qn("audio-context-failed",a),t.close().catch(()=>{});return}V("audio-oscillators-scheduled",{soundId:e,count:s.count,longestStopSec:s.longestStopSec}),setTimeout(()=>{t.close().then(()=>V("audio-context-closed")).catch(()=>{})},(s.longestStopSec+.1)*1e3)};t.state==="running"?r():t.state==="suspended"?(V("audio-context-resume-attempted"),t.resume().then(()=>{V("audio-context-resume-ok",{state:t.state}),r()},s=>{qn("audio-context-resume-failed",s),t.close().catch(()=>{})})):(V("audio-context-failed",{name:"UnexpectedState",message:`AudioContext state "${t.state}"`}),t.close().catch(()=>{}))}const Sd="I came to the Build tab to find the AI waiting for me but never saw any of the idle notifications — no sound, no orange dot on the Build tab, no idle banner. Please diagnose using the trace below.\n\nStart with the **UI idle trace** section: a single `debounce-cancelled` line with a `trigger` field identifies which silent path killed the 1500ms debounce before `debounce-resolved` could fire. Cross-reference with the **Rust idle trace** and **editor-server.log** sections to confirm the backend actually sent `agent-idle` and to see the timing.";function Ed(){const e=typeof Notification<"u"?Notification.permission:"unknown",t=typeof document<"u"&&typeof document.hasFocus=="function"?document.hasFocus():!1,r=typeof document<"u"?document.hidden:!1;let s=null;try{s=typeof localStorage<"u"?localStorage.getItem("codeyam.idleDebug"):null}catch{}const a=typeof navigator<"u"?navigator.userAgent:"unknown";return{notificationPermission:e,hasFocus:t,hidden:r,idleDebug:s,userAgent:a}}function ys(e){return e.length===0?"_(no events in window)_":`\`\`\`jsonl
|
|
2
|
+
${e.map(r=>JSON.stringify(r)).join(`
|
|
3
|
+
`)}
|
|
4
|
+
\`\`\``}function Jn(e,t){return e.trim().length===0?`_(${t} empty)_`:`\`\`\`
|
|
5
|
+
${e}
|
|
6
|
+
\`\`\``}function Rd(e){var y,j,b;const{bundle:t,browser:r,uiBufferText:s,prompt:a,agentName:o}=e,l=(t==null?void 0:t.now)??new Date().toISOString(),c=(t==null?void 0:t.session)??Rr(),d=(t==null?void 0:t.windowMinutes)??10,u=((y=t==null?void 0:t.environment)==null?void 0:y.editorVersion)??"unknown",f=((j=t==null?void 0:t.environment)==null?void 0:j.platform)??"unknown",p=((b=t==null?void 0:t.environment)==null?void 0:b.projectDir)??"unknown",m=(a??Sd).trim(),h=[`- Notification.permission: ${r.notificationPermission}`,`- document.hasFocus(): ${r.hasFocus}`,`- document.hidden: ${r.hidden}`,`- localStorage.codeyam.idleDebug: ${r.idleDebug===null?"(unset)":JSON.stringify(r.idleDebug)}`,`- userAgent: ${r.userAgent}`].join(`
|
|
7
|
+
`),v=t&&t.truncations.length>0?`> **Truncations:** ${t.truncations.join("; ")}`:"";return["# CodeYam Notification Debug Bundle","",m,"","---","",`**Captured:** ${l}`,`**UI session:** ${c} (window: last ${d} minutes)`,`**Editor version:** ${u}`,`**Platform:** ${f}`,`**Project:** ${p}`,o?`**Agent:** ${o}`:null,"","**Browser state:**",h,"",v,"","## UI idle trace (persisted)","",ys((t==null?void 0:t.uiTrace)??[]),"","## UI idle trace (in-memory ring buffer — may be ahead of persisted)","",Jn(s,"in-memory buffer"),"","## Rust idle trace","",ys((t==null?void 0:t.rustTrace)??[]),"","## editor-server.log (filtered to idle= within window)","",Jn((t==null?void 0:t.editorServerLog)??"","editor-server.log"),"","## dev-server.log (last lines)","",Jn((t==null?void 0:t.devServerLog)??"","dev-server.log"),""].filter(x=>x!==null).join(`
|
|
8
|
+
`)}async function Td(e={}){const t=encodeURIComponent(Rr());let r=null,s=null;try{const c=await fetch(`/api/idle-trace/bundle?session=${t}&minutes=10`);c.ok?r=await c.json():s=`HTTP ${c.status}`}catch(c){s=c instanceof Error?c.message:String(c)}const a=Ed(),o=hl({agentName:e.agentName});return{markdown:Rd({bundle:r,browser:a,uiBufferText:o,prompt:e.prompt,agentName:e.agentName}),bundle:r,error:s}}const Pd=1500;function Dd(e=Pd){const[t,r]=i.useState(null),s=i.useRef(null),a=i.useCallback((o,l)=>{s.current!==null&&clearTimeout(s.current),r(o),s.current=setTimeout(()=>{r(null),s.current=null},l??e)},[e]);return i.useEffect(()=>()=>{s.current!==null&&(clearTimeout(s.current),s.current=null)},[]),{label:t,flash:a}}const Ad=2500;function Fd({agentName:e}){const[t,r]=i.useState(!1),{label:s,flash:a}=Dd(Ad),o=async()=>{r(!0);const{markdown:l,bundle:c,error:d}=await Td({agentName:e});try{await navigator.clipboard.writeText(l);const u=((c==null?void 0:c.uiTrace.length)??0)+((c==null?void 0:c.rustTrace.length)??0),f=Math.round(l.length/1024*10)/10,p=d?`Copied (offline — ${u} events, ${f} KB)`:`Copied ${u} events · ${f} KB`;a(p)}catch{a("Copy failed")}finally{r(!1)}};return n.jsx("button",{onClick:()=>void o(),disabled:t,className:"text-left text-[11px] px-2 py-1 rounded cursor-pointer transition-colors font-medium",style:{background:"transparent",color:"var(--text-secondary)"},"data-testid":"notification-debug-copy",children:s??(t?"Gathering bundle…":"Debug Notifications")})}function ws({label:e,checked:t,onChange:r,className:s}){return n.jsxs("label",{className:`flex items-center gap-2 cursor-pointer${s?` ${s}`:""}`,children:[n.jsx("input",{type:"checkbox",checked:t,onChange:a=>r(a.target.checked),className:"accent-green-500"}),n.jsx("span",{className:"text-[11px]",style:{color:"var(--text-secondary)"},children:e})]})}function Ld({settings:e,onChange:t,agentName:r}){const[s,a]=i.useState(!1),o=i.useRef(null),l=e.idleOnStop??!1,c=e.idleOnNotification??!0,d=e.sound!=="off"||e.systemNotification||l||c;return i.useEffect(()=>{if(!s)return;const u=f=>{o.current&&!o.current.contains(f.target)&&a(!1)};return document.addEventListener("mousedown",u),()=>document.removeEventListener("mousedown",u)},[s]),n.jsxs("div",{className:"h-7 flex items-center px-3 text-xs shrink-0",style:{background:"var(--bg-nav)",borderTop:"1px solid var(--border-default)"},children:[n.jsx("div",{className:"flex-1"}),n.jsxs("div",{className:"relative",ref:o,children:[n.jsx("button",{onClick:()=>{a(!s),typeof Notification<"u"&&Notification.permission==="default"&&Notification.requestPermission()},className:"cursor-pointer transition-colors",style:{color:d?"var(--accent-green)":"var(--text-dim)",fontSize:"11px"},children:d?"Notifications On":"Notifications Off"}),s&&n.jsxs("div",{className:"absolute bottom-full right-0 mb-2 w-56 rounded-lg shadow-xl p-3 flex flex-col gap-3 z-50",style:{background:"var(--bg-surface)",border:"1px solid var(--border-default)"},children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-[11px] mb-1.5",style:{color:"var(--text-muted)"},children:"Notification sound"}),n.jsx("div",{className:"flex flex-col gap-0.5",children:jd.map(u=>n.jsx("button",{onClick:()=>{t({...e,sound:u.id}),u.id!=="off"&&qa(u.id)},className:"text-left text-[11px] px-2 py-1 rounded cursor-pointer transition-colors",style:{background:e.sound===u.id?"var(--bg-input)":"transparent",color:e.sound===u.id?"var(--text-primary)":"var(--text-secondary)"},children:u.label},u.id))})]}),n.jsxs("div",{className:"pt-2",style:{borderTop:"1px solid var(--border-default)"},children:[n.jsx("div",{className:"text-[11px] mb-1.5",style:{color:"var(--text-muted)"},children:"Trigger idle on"}),n.jsx(ws,{label:"Claude stops",checked:l,onChange:u=>t({...e,idleOnStop:u})}),n.jsx(ws,{label:"Claude sends a notification",checked:c,onChange:u=>t({...e,idleOnNotification:u}),className:"mt-1"})]}),n.jsxs("div",{className:"pt-2",style:{borderTop:"1px solid var(--border-default)"},children:[n.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:e.systemNotification,onChange:u=>{const f=u.target.checked;t({...e,systemNotification:f}),f&&typeof Notification<"u"&&Notification.permission==="default"&&Notification.requestPermission()},className:"accent-green-500"}),n.jsx("span",{className:"text-[11px]",style:{color:"var(--text-secondary)"},children:"System notification"})]}),n.jsx("div",{className:"text-[10px] mt-1 ml-5",style:{color:"var(--text-dim)"},children:"Shows when tab is not visible"}),typeof Notification<"u"&&Notification.permission==="denied"&&n.jsx("div",{className:"text-[10px] mt-1 ml-5",style:{color:"var(--accent-red, #ef4444)"},children:"Notifications are blocked. Click the lock icon in your address bar → Site settings → Notifications → Allow"})]}),n.jsx("div",{className:"pt-2",style:{borderTop:"1px solid var(--border-default)"},children:n.jsx(Fd,{agentName:r})})]})]})]})}function Md(){const[e,t]=i.useState(null);return i.useEffect(()=>{fetch("/api/editor-setup-answers").then(r=>{if(!r.ok)throw new Error(`HTTP ${r.status}`);return r.json()}).then(r=>{t(r!==null)}).catch(()=>{t(!1)})},[]),{saved:e}}function Id({projectDescription:e}){return n.jsxs(n.Fragment,{children:[n.jsx("h2",{className:"text-xl font-semibold",children:"Building your project…"}),n.jsx("blockquote",{className:"mt-4 border-l-2 border-[var(--accent-active)] pl-4 text-sm italic text-[var(--text-dim)]",children:e}),n.jsxs("p",{className:"mt-6 text-sm text-[var(--text-dim)]",children:["Your app will appear here as it’s built. The agent is scaffolding it now on the ",n.jsx("strong",{children:"Build"})," tab — open it to follow along."]})]})}function $d(){return n.jsxs(n.Fragment,{children:[n.jsx("h2",{className:"text-xl font-semibold",children:"No app scaffolded yet"}),n.jsxs("p",{className:"mt-4 text-sm text-[var(--text-dim)]",children:["Your project hasn’t been scaffolded yet. Open the"," ",n.jsx("strong",{children:"Build"})," tab to start building."]})]})}function Od({onClick:e}){return n.jsx("button",{type:"button",onClick:e,"data-testid":"app-overview-empty-open-build",className:"mt-6 inline-flex items-center gap-2 rounded border border-[var(--accent-active)] bg-[var(--accent-active)] px-4 py-2 text-xs font-medium uppercase tracking-wide text-black transition-colors hover:bg-[var(--accent-active)]/90 cursor-pointer",children:"Open Build tab"})}function Bd({projectDescription:e,onOpenBuildTab:t}){const r=e!==null&&e.trim().length>0;return n.jsxs("div",{className:"mx-auto max-w-2xl px-5 py-12 text-[var(--text-primary)]",children:[r?n.jsx(Id,{projectDescription:e}):n.jsx($d,{}),n.jsx(Od,{onClick:t})]})}function _d({stats:e,onSelectApp:t,testsLoading:r,testsRefreshing:s,onRunTests:a,currentRunner:o}){return n.jsx("div",{className:"flex flex-col gap-4",children:e.map(l=>n.jsx(kl,{stats:l,onClick:()=>t(l.app.dir),testsLoading:r,testsRefreshing:s,onRunTests:a,currentRunner:o},l.app.dir))})}function zd({projectTitle:e,coverage:t,onCoverageClick:r}){return n.jsxs("div",{className:"flex items-center justify-between mb-4",children:[n.jsx("h2",{className:"text-lg font-semibold text-[var(--text-primary)]",children:e}),n.jsx(Ar,{coverage:t,testId:"app-overview-coverage",onClick:r})]})}async function Hd(e){try{e.description&&await fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDescription:e.description,allowOverwrite:!0})});const t={appFormats:e.appFormats,techStackId:e.techStackId,designApproach:e.designApproach};e.defaultDevice&&(t.defaultDevice=e.defaultDevice),await fetch("/api/editor-setup-answers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}catch{}}const js=["product-type","description","tech-stack","design-approach"];function Wd(e){return e==="files"||e==="chat"?[...js,"design-details"]:js}const Ir="codeyam.questionnaire.draft";function Vd(e){if(e===null||typeof e!="object")return!1;const t=e;if(typeof t.step!="number"||!Number.isFinite(t.step)||typeof t.savedAt!="string")return!1;const r=t.answers;if(r===null||typeof r!="object")return!1;const s=r;return!(!Array.isArray(s.appFormats)||!s.appFormats.every(a=>typeof a=="string")||typeof s.description!="string"||s.techStackId!==null&&typeof s.techStackId!="string"||s.designApproach!==null&&typeof s.designApproach!="string"||s.defaultDevice!==null&&typeof s.defaultDevice!="string")}function ks(){try{const e=localStorage.getItem(Ir);if(e===null)return null;const t=JSON.parse(e);return Vd(t)?t:null}catch{return null}}function Ud(e){try{localStorage.setItem(Ir,JSON.stringify(e))}catch{}}function Kd(){try{localStorage.removeItem(Ir)}catch{}}function Gd(){const[e,t]=i.useState([]);return i.useEffect(()=>{fetch("/api/editor-stacks").then(r=>r.json()).then(t).catch(()=>{})},[]),{techStacks:e}}const bn=20*1024*1024,Yd=3e4,qd=3e3;function Ja(e){return new Promise((t,r)=>{const s=new FileReader;s.onload=()=>{const a=s.result;if(typeof a!="string"){r(new Error("Unexpected FileReader result"));return}const o=a.indexOf(",");t(o===-1?a:a.slice(o+1))},s.onerror=()=>r(s.error??new Error("read failed")),s.readAsDataURL(e)})}function Jd(){return typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`drop-${Date.now()}-${Math.random().toString(36).slice(2)}`}function Xd(e){return/^[A-Za-z0-9._/\-]+$/.test(e)?e:`"${e.replace(/(["\\$`])/g,"\\$1")}"`}function Qd(e){const t=e.items;if(!t||t.length===0||typeof t[0].webkitGetAsEntry!="function")return!1;for(const s of Array.from(t)){const a=s.webkitGetAsEntry();if(a&&a.isDirectory)return!0}return!1}function pt({title:e,subtitle:t,children:r}){return n.jsxs("div",{children:[n.jsx("h2",{style:{fontSize:"var(--text-xl, 22px)",fontWeight:700,color:"var(--text-primary)",marginBottom:"var(--spacing-xs, 4px)"},children:e}),n.jsx("p",{style:{fontSize:"var(--text-sm, 14px)",color:"var(--text-muted)",marginBottom:"var(--spacing-lg, 24px)"},children:t}),r]})}function Zd({onUploadComplete:e}){const[t,r]=i.useState([]),[s,a]=i.useState(!1),[o,l]=i.useState(null),[c,d]=i.useState(null),[u,f]=i.useState(!1),p=i.useRef(null),m=i.useCallback(j=>{d(null);const b=j.filter(x=>x.size>bn?(d(`${x.name} is larger than the ${bn/(1024*1024)}MB cap`),!1):!0);r(x=>[...x,...b.map(w=>({id:`${w.name}-${w.size}-${Math.random().toString(36).slice(2)}`,file:w,description:""}))])},[]),h=i.useCallback(j=>{j.target.files&&m(Array.from(j.target.files)),j.target.value=""},[m]),v=i.useCallback((j,b)=>{r(x=>x.map(w=>w.id===j?{...w,description:b}:w))},[]),g=i.useCallback(j=>{r(b=>b.filter(x=>x.id!==j))},[]),y=i.useCallback(async()=>{if(t.length!==0){a(!0),d(null);try{const j=await Promise.all(t.map(async k=>({filename:k.file.name,contentBase64:await Ja(k.file),description:k.description}))),b=await fetch("/api/editor-design-uploads",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({files:j})});if(!b.ok)throw new Error(`Upload failed: ${b.status}`);const w=(await b.json()).written??j.map(k=>k.filename);l(w),e==null||e(w)}catch(j){d(j instanceof Error?j.message:String(j))}finally{a(!1)}}},[t,e]);return n.jsxs(pt,{title:"Add your design files",subtitle:"Drop in anything: brand assets, mockups, references. Tell us briefly what each one shows.",children:[n.jsxs("label",{onDragOver:j=>{j.preventDefault(),f(!0)},onDragLeave:()=>f(!1),onDrop:j=>{j.preventDefault(),f(!1),m(Array.from(j.dataTransfer.files))},style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"var(--spacing-xl, 32px)",border:`2px dashed ${u?"var(--accent-default)":"var(--border-default)"}`,borderRadius:12,background:u?"var(--bg-elevated, rgba(255,255,255,0.03))":"var(--bg-input)",cursor:"pointer",textAlign:"center",gap:"var(--spacing-xs, 4px)"},children:[n.jsx("input",{ref:p,type:"file",multiple:!0,onChange:h,style:{display:"none"}}),n.jsx("div",{style:{fontSize:"var(--text-sm, 14px)",color:"var(--text-primary)",fontWeight:500},children:"Drop files here, or click to choose"}),n.jsx("div",{style:{fontSize:"var(--text-xs, 12px)",color:"var(--text-secondary)"},children:"PNG, JPG, PDF, Markdown — anything that describes your design"})]}),t.length>0&&n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"var(--spacing-sm, 8px)",marginTop:"var(--spacing-md, 12px)"},children:t.map(j=>n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"var(--spacing-xs, 4px)",padding:"var(--spacing-sm, 8px)",border:"1px solid var(--border-default)",borderRadius:8,background:"var(--bg-input)"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[n.jsx("span",{style:{fontSize:"var(--text-sm, 14px)",color:"var(--text-primary)",fontWeight:500},children:j.file.name}),n.jsx("button",{type:"button",onClick:()=>g(j.id),style:{fontSize:"var(--text-xs, 12px)",color:"var(--text-secondary)",background:"transparent",border:"none",cursor:"pointer"},children:"Remove"})]}),n.jsx("textarea",{value:j.description,onChange:b=>v(j.id,b.target.value),placeholder:"What does this file show? (optional)",rows:2,style:{width:"100%",padding:"var(--spacing-sm, 8px)",background:"var(--bg-default)",border:"1px solid var(--border-default)",borderRadius:6,color:"var(--text-primary)",fontSize:"var(--text-xs, 12px)",resize:"vertical",outline:"none",fontFamily:"inherit"}})]},j.id))}),c&&n.jsx("div",{style:{marginTop:"var(--spacing-sm, 8px)",color:"var(--accent-danger, #f87171)",fontSize:"var(--text-xs, 12px)"},children:c}),o&&o.length>0&&n.jsxs("div",{style:{marginTop:"var(--spacing-sm, 8px)",color:"var(--text-secondary)",fontSize:"var(--text-xs, 12px)"},children:["Uploaded ",o.length," file",o.length===1?"":"s","."]}),n.jsx("button",{type:"button",onClick:y,disabled:t.length===0||s,style:{marginTop:"var(--spacing-md, 12px)",padding:"var(--spacing-sm, 8px) var(--spacing-md, 12px)",background:t.length===0||s?"var(--bg-elevated)":"var(--accent-default)",color:"var(--text-on-accent, white)",border:"none",borderRadius:6,fontSize:"var(--text-sm, 14px)",fontWeight:500,cursor:t.length===0||s?"not-allowed":"pointer"},children:s?"Uploading…":"Save uploads"})]})}function Mt({label:e,description:t,selected:r,onClick:s,multi:a}){return n.jsxs("button",{onClick:s,style:{display:"flex",alignItems:"center",gap:"var(--spacing-md, 12px)",width:"100%",textAlign:"left",padding:"var(--spacing-sm, 8px) var(--spacing-md, 12px)",background:"var(--bg-input)",border:r?"1.5px solid var(--accent-active)":"1px solid var(--border-default)",borderRadius:8,cursor:"pointer",transition:"border-color 0.15s"},children:[n.jsx(eu,{selected:r,multi:a}),n.jsxs("div",{children:[n.jsx("span",{style:{fontSize:"var(--text-sm, 14px)",fontWeight:500,color:"var(--text-primary)"},children:e}),t&&n.jsx("span",{style:{display:"block",fontSize:"var(--text-xs, 12px)",color:"var(--text-muted)",marginTop:2},children:t})]})]})}function eu({selected:e,multi:t}){return n.jsx("span",{style:{width:16,height:16,borderRadius:t?3:"50%",border:e?"none":"1.5px solid var(--text-dim)",background:e?"var(--accent-active)":"transparent",flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center"},children:e&&n.jsx("span",{style:{color:"#000",fontSize:11,fontWeight:700,lineHeight:1},children:"✓"})})}const tu=[{id:"files",label:"I have design files and/or a design system",description:"Upload screenshots, mockups, brand guides — anything that defines the look you want."},{id:"chat",label:"I need help on this, can we chat about it?",description:"After setup we'll generate mockups against curated moodboards and you pick a direction."},{id:"skip",label:"I'm not too worried about design, can we start building?",description:"Skip design for now. You can revisit it any time."}];function nu({selected:e,onSelect:t}){return n.jsx(pt,{title:"How should we approach design?",subtitle:"Pick whichever feels right — you can always change direction later.",children:n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"var(--spacing-sm, 8px)"},children:tu.map(r=>n.jsx(Mt,{label:r.label,description:r.description,selected:e===r.id,onClick:()=>t(r.id)},r.id))})})}function ru(e,t){const r=i.useRef(t);i.useEffect(()=>{r.current=t},[t]),i.useEffect(()=>{if(!e)return;let s=!1,a=null;const o=async()=>{try{const c=await(await fetch("/api/editor-design-state")).json();!s&&c.active&&r.current(c.active)}catch{}finally{s||(a=window.setTimeout(o,3e3))}};return o(),()=>{s=!0,a!==null&&window.clearTimeout(a)}},[e])}function su({providerLabel:e,preparing:t,onLaunch:r}){return n.jsxs("div",{children:[n.jsxs("p",{style:{margin:"0 0 var(--spacing-lg, 16px)",fontSize:"var(--text-md, 15px)",lineHeight:1.5,color:"var(--text-primary)"},children:["Click the button below to launch a chat window with ",e," so that ",e," can generate some design options for you to consider and iterate on."]}),n.jsx("button",{onClick:r,disabled:t,style:{background:t?"var(--bg-surface)":"var(--accent-active)",border:"none",color:t?"var(--text-dim)":"#000",padding:"var(--spacing-sm, 8px) var(--spacing-lg, 16px)",borderRadius:6,cursor:t?"not-allowed":"pointer",fontSize:"var(--text-sm, 14px)",fontWeight:600},children:t?"Preparing design moodboards…":`Launch ${e} Design Chat`})]})}function au({description:e,onDesignSelected:t,onPreviewUrl:r}){const[s,a]=i.useState({kind:"preparing"}),[o,l]=i.useState(!1),{config:c}=it(),d=Ve(c==null?void 0:c.provider);i.useEffect(()=>(r==null||r("/design-exploration"),()=>{r==null||r(null)}),[r]),i.useEffect(()=>{let f=!1;return(async()=>{try{const[p,m]=await Promise.all([fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDescription:e,allowOverwrite:!0})}),fetch("/api/editor-design-systems-install",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"})]);if(!m.ok){const h=await m.text().catch(()=>`${m.status}`);throw new Error(h||`install failed: ${m.status}`)}p.ok||console.warn("[QuestionnaireDesignChatStep] editor-project-info failed; skill will prompt for description",p.status),f||a({kind:"ready"})}catch(p){f||a({kind:"error",message:p instanceof Error?p.message:String(p)})}})(),()=>{f=!0}},[e]),ru(o,t);const u=s.kind==="preparing";return n.jsx(pt,{title:"Explore design directions",subtitle:"Chat with the agent, then pick a mockup by number from the Live Preview.",children:o?n.jsx(Sn,{chatName:"initial-design",slashCommand:"/codeyam-design",height:420}):s.kind==="error"?n.jsxs("div",{style:{padding:"var(--spacing-md, 12px)",marginBottom:"var(--spacing-sm, 8px)",borderRadius:8,background:"var(--bg-danger-soft, rgba(248,113,113,0.12))",color:"var(--accent-danger, #f87171)",fontSize:"var(--text-sm, 14px)"},children:["Couldn't prepare design moodboards: ",s.message,". Try the Files or Skip approach instead."]}):n.jsx(su,{providerLabel:d,preparing:u,onLaunch:()=>l(!0)})})}const ou=[{id:"Desktop",label:"Desktop",description:"Standard desktop browser viewport"},{id:"Tablet",label:"Tablet",description:"Tablet-sized portrait viewport"},{id:"Mobile",label:"Mobile",description:"Phone-sized portrait viewport"}];function iu({selected:e,onSelect:t}){return n.jsx("div",{style:{marginTop:"var(--spacing-xl, 32px)"},children:n.jsx(pt,{title:"Where will this web app primarily be viewed?",subtitle:"This sets the default viewport for every scenario captured in your project.",children:n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"var(--spacing-sm, 8px)"},children:ou.map(r=>n.jsx(Mt,{label:r.label,description:r.description,selected:e===r.id,onClick:()=>t(r.id)},r.id))})})})}function lu(){return n.jsx("div",{style:{padding:"var(--spacing-sm, 8px) var(--spacing-lg, 16px)",background:"var(--bg-surface)",borderBottom:"1px solid var(--border-subtle)",fontSize:"var(--text-sm, 14px)",color:"var(--text-muted)"},children:"Before we dive in, help us comprehend what you want to build better."})}function cu({step:e,canAdvance:t,isFinalStep:r,isAdvancing:s,onBack:a,onNext:o,onFinish:l}){return n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"var(--spacing-md, 12px)",marginTop:"var(--spacing-lg, 24px)"},children:[e>1&&n.jsx("button",{onClick:a,style:{background:"none",border:"1px solid var(--border-default)",color:"var(--text-secondary)",padding:"var(--spacing-sm, 8px) var(--spacing-lg, 16px)",borderRadius:6,cursor:"pointer",fontSize:"var(--text-sm, 14px)"},children:"← Back"}),r?n.jsx("button",{onClick:l,disabled:!t,style:{background:t?"var(--accent-active)":"var(--bg-surface)",border:"none",color:t?"#000":"var(--text-dim)",padding:"var(--spacing-sm, 8px) var(--spacing-lg, 16px)",borderRadius:6,cursor:t?"pointer":"not-allowed",fontSize:"var(--text-sm, 14px)",fontWeight:600},children:"FINISH →"}):n.jsx("button",{onClick:o,disabled:!t||s,style:{background:t?"var(--accent-active)":"var(--bg-surface)",border:"none",color:t?"#000":"var(--text-dim)",padding:"var(--spacing-sm, 8px) var(--spacing-lg, 16px)",borderRadius:6,cursor:t&&!s?"pointer":"not-allowed",fontSize:"var(--text-sm, 14px)",fontWeight:600,opacity:s?.7:1},children:s?"…":"NEXT →"})]})}function du({currentStep:e,stepLabels:t,onStepClick:r}){return n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"var(--spacing-xs, 4px)",paddingTop:"var(--spacing-lg, 24px)"},children:t.map((s,a)=>{const o=a+1,l=o===e,c=o<e;return n.jsx("button",{onClick:()=>{c&&r(o)},style:{background:"none",border:"none",cursor:c?"pointer":"default",padding:"var(--spacing-xs, 4px) 0",fontSize:"var(--text-sm, 14px)",color:l?"var(--text-primary)":c?"var(--text-secondary)":"var(--text-dim)",fontWeight:l?500:400,textAlign:"left",transition:"color 0.15s"},children:s},o)})})}const uu=[{id:"web",label:"Website/Web App"},{id:"desktop",label:"Desktop App"},{id:"chrome-extension",label:"Chrome Extension"},{id:"mobile",label:"Mobile App"},{id:"other",label:"Other"}],fu={"product-type":"What Type Of Product Do You Want To Build?",description:"Describe Your Product","tech-stack":"Do You Have A Preferred Tech Stack?","design-approach":"How Should We Approach Design","design-details":"Design Details"},Ns=560,pu=960;function mu({onComplete:e,onPreviewUrl:t}){const[r,s]=i.useState(()=>{const N=ks();return N?N.step:1}),[a,o]=i.useState(()=>{const N=ks();return(N==null?void 0:N.answers)??{appFormats:[],description:"",techStackId:null,designApproach:null,defaultDevice:null}}),[l,c]=i.useState(null),{techStacks:d}=Gd(),u=Wd(a.designApproach),f=u[r-1],p=r===u.length,m=u.map(N=>fu[N]);i.useEffect(()=>{r>u.length&&s(u.length)},[r,u.length]);const h=i.useRef(!0);i.useEffect(()=>{if(h.current){h.current=!1;return}Ud({step:r,answers:a,savedAt:new Date().toISOString()})},[r,a]);const v=i.useCallback(N=>{o(E=>{const R=E.appFormats.includes(N),S=R?E.appFormats.filter(P=>P!==N):[...E.appFormats,N],D=N==="web"&&R?null:E.defaultDevice;return{...E,appFormats:S,defaultDevice:D}})},[]),g=i.useCallback(N=>{o(E=>({...E,defaultDevice:N}))},[]),y=i.useCallback(N=>{o(E=>({...E,designApproach:E.designApproach===N?null:N}))},[]),j=i.useCallback(async()=>{await Hd(a),Kd(),e==null||e(a)},[a,e]),b=i.useRef(!1);i.useEffect(()=>{b.current||f==="design-details"&&a.designApproach==="chat"&&l!==null&&(b.current=!0,j())},[f,a.designApproach,l,j]);const x=i.useCallback(()=>{s(N=>N+1)},[]),w=a.appFormats.includes("web"),k=(()=>{switch(f){case"product-type":return a.appFormats.length>0&&(!w||a.defaultDevice!==null);case"description":return a.description.trim().length>0;case"design-approach":return a.designApproach!==null;case"design-details":return a.designApproach==="chat"?l!==null:!0;default:return!0}})(),C=f==="description"?pu:f==="design-details"&&a.designApproach==="chat"?"100%":Ns;return n.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"auto"},children:[n.jsx(lu,{}),n.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",padding:"var(--spacing-xl, 32px)"},children:[n.jsxs("div",{style:{maxWidth:C},children:[f==="product-type"&&n.jsxs(n.Fragment,{children:[n.jsx(pt,{title:"What type of product do you want to build?",subtitle:"Select as many as you need.",children:n.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"var(--spacing-sm, 8px)"},children:uu.map(N=>n.jsx(Mt,{label:N.label,selected:a.appFormats.includes(N.id),onClick:()=>v(N.id),multi:!0},N.id))})}),w&&n.jsx(iu,{selected:a.defaultDevice,onSelect:g})]}),f==="description"&&n.jsx(pt,{title:"Describe your product",subtitle:"What are you building? This helps us set up the right starting point.",children:n.jsx("textarea",{value:a.description,onChange:N=>o(E=>({...E,description:N.target.value})),placeholder:"e.g. A task management app for remote teams with real-time collaboration...",style:{width:"100%",minHeight:180,padding:"var(--spacing-md, 12px)",background:"var(--bg-input)",border:"1px solid var(--border-default)",borderRadius:8,color:"var(--text-primary)",fontSize:"var(--text-sm, 14px)",resize:"vertical",outline:"none",fontFamily:"inherit"}})}),f==="tech-stack"&&n.jsx(pt,{title:"Do you have a preferred tech stack?",subtitle:"Choose a starting template, or let CodeYam decide.",children:n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"var(--spacing-sm, 8px)"},children:[n.jsx(Mt,{label:"Let CodeYam decide",description:"We'll pick the best stack based on your product",selected:a.techStackId===null,onClick:()=>o(N=>({...N,techStackId:null}))}),d.map(N=>n.jsx(Mt,{label:N.name,description:N.description,selected:a.techStackId===N.id,onClick:()=>o(E=>({...E,techStackId:N.id}))},N.id))]})}),f==="design-approach"&&n.jsx(nu,{selected:a.designApproach,onSelect:y}),f==="design-details"&&a.designApproach==="files"&&n.jsx(Zd,{}),f==="design-details"&&a.designApproach==="chat"&&n.jsx(au,{description:a.description,onDesignSelected:c,onPreviewUrl:t})]}),n.jsxs("div",{style:{maxWidth:Ns},children:[n.jsx(cu,{step:r,canAdvance:k,isFinalStep:p,onBack:()=>s(N=>N-1),onNext:()=>{k&&x()},onFinish:j}),n.jsx(du,{currentStep:r,stepLabels:m,onStepClick:s})]})]})]})}function hu({projectTitle:e,projectDescription:t,stats:r,coverage:s,onSelectApp:a,configLoading:o,testsLoading:l,testsRefreshing:c,onRunTests:d,currentRunner:u,stepState:f,onPreviewUrl:p,onComplete:m,onOpenBuildTab:h,onCoverageClick:v}){const{saved:g}=Md();return r.length===0?o||g===null?null:!f&&!g?n.jsx(mu,{onPreviewUrl:p,onComplete:m}):n.jsx(Bd,{projectDescription:t??null,onOpenBuildTab:h??(()=>{})}):n.jsxs("div",{className:"px-5 py-5",children:[n.jsx(zd,{projectTitle:e,coverage:s,onCoverageClick:v}),n.jsx(_d,{stats:r,onSelectApp:a,testsLoading:l,testsRefreshing:c,onRunTests:d,currentRunner:u})]})}function xu({sessionContent:e,stepIndicator:t}){return n.jsxs("div",{className:"flex flex-col h-full",children:[t,e]})}function gu({activeTab:e,buildTab:t,footer:r,resultsPanel:s,showResultsPanel:a}){return n.jsxs("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:e==="build"?"visible":"hidden",pointerEvents:e==="build"?"auto":"none"},children:[n.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden",children:[n.jsx("div",{style:{flex:a?"0 0 50%":"1 1 auto",minHeight:0,overflow:"hidden",display:"flex",flexDirection:"column"},children:t}),a?s:null]}),r]})}function bu(e=!1){return{title:"Session Ready to Resume",description:e?"CodeYam saved this build session while it was waiting on the next workflow action. Review the current feature and step below, then click resume when you're ready to continue.":"CodeYam found a saved build session for this feature. Review the current feature and step below, then click resume when you're ready to continue.",buttonLabel:"Resume Session",providersLabel:null}}function vu(e,t){const r=Ve(e),s=Ve(t);return{title:"Saved Handoff Ready",description:`A ${r} build session is still in progress for this feature. CodeYam saved the workflow state so ${s} can continue from the same step instead of starting over.`,buttonLabel:"Continue with Saved Handoff",providersLabel:`${r} to ${s}`}}function yu({resumeMode:e,previousProvider:t,currentProvider:r,awaitingUserInput:s=!1}){return e!=="handoff"||t==null||r==null||t===r?bu(s):vu(t,r)}function wu({label:e,onContinue:t}){return n.jsx("button",{onClick:t,className:"w-full px-4 py-2 text-sm rounded transition-colors cursor-pointer font-medium",style:{background:"var(--accent-active, #D7FF63)",color:"var(--text-on-accent, #0F0F0F)"},children:e})}function ju({children:e}){return n.jsx("div",{className:"flex items-center justify-center h-full",role:"dialog","aria-modal":"true",style:{background:"var(--bg-deep)",color:"var(--text-secondary)"},children:n.jsx("div",{className:"max-w-md w-full mx-4 p-6 rounded-lg",style:{background:"var(--bg-surface)",border:"1px solid var(--border-default)"},children:e})})}function ku({description:e,title:t}){return n.jsxs(n.Fragment,{children:[n.jsx("h2",{className:"text-lg font-semibold mb-3",style:{color:"var(--text-primary)"},children:t}),n.jsx("p",{className:"text-sm mb-4",style:{color:"var(--text-muted)"},children:e})]})}function Xn({label:e,rowClassName:t,value:r}){return n.jsxs("div",{className:t,children:[n.jsxs("span",{style:{color:"var(--text-muted)"},children:[e,":"]})," ",n.jsx("span",{style:{color:"var(--text-primary)"},children:r})]})}function Nu({featureName:e,editorStep:t,editorStepLabel:r,providersLabel:s}){return n.jsxs("div",{className:"rounded p-3 mb-5 text-sm",style:{background:"var(--bg-deep)"},children:[e&&n.jsx(Xn,{label:"Feature",value:e,rowClassName:"mb-1"}),t!=null&&r&&n.jsx(Xn,{label:"Step",value:`${t} (${r})`}),s&&n.jsx(Xn,{label:"Providers",value:s,rowClassName:"mt-1"})]})}function Cu(e){const t=i.useCallback(r=>{r.key==="Enter"&&(r.preventDefault(),e())},[e]);i.useEffect(()=>(window.addEventListener("keydown",t),()=>window.removeEventListener("keydown",t)),[t])}function Su({featureName:e,editorStep:t,workflowMode:r,previousProvider:s,currentProvider:a,resumeMode:o,awaitingUserInput:l=!1,onContinue:c}){const d=yu({resumeMode:o,previousProvider:s,currentProvider:a,awaitingUserInput:l}),u=t==null?null:Fr(t,r);return Cu(c),n.jsxs(ju,{children:[n.jsx(ku,{title:d.title,description:d.description}),n.jsx(Nu,{featureName:e,editorStep:t,editorStepLabel:u,providersLabel:d.providersLabel}),n.jsx(wu,{label:d.buttonLabel,onContinue:c})]})}function Eu({awaitingUserInput:e,currentProvider:t,editorStep:r,featureName:s,onContinue:a,previousProvider:o,resumeMode:l,workflowMode:c}){return n.jsx(Su,{featureName:s,editorStep:r,workflowMode:c,previousProvider:o,currentProvider:t,resumeMode:l,awaitingUserInput:e,onContinue:a})}function Ru({sessionDecision:e,sessionInfo:t,stepState:r}){return{recoveryFeatureName:(r==null?void 0:r.feature)??(t==null?void 0:t.feature)??null,recoveryStep:(r==null?void 0:r.step)??(t==null?void 0:t.step)??null,recoveryMode:(r==null?void 0:r.mode)??(t==null?void 0:t.mode)??null,showTerminal:(e==="continue"||e==="fresh"||e==="no-session")&&(r!==null||t!==null),shouldResumeSameProvider:e==="continue"&&(t==null?void 0:t.resumeMode)==="resume"}}const pn=8e3,Tu="agent-banner-ready",Pu="agent-auth-required";let vn=!1,yn=!1,Ke=[],Cs=!1,nt=null,st=null,mn=!1;function Du(){Cs||typeof window>"u"||(Cs=!0,window.addEventListener(Tu,()=>{const e=!yn;if(e){yn=!0;const t=Ke;Ke=[];for(const r of t)r("banner")}if(mn&&(mn=!1,st&&nt===null)){V("dispatch-rename-after-auth",{label:st.label,reason:"first-observed-frame-after-auth"}),nt=st,gn(st.label,st.send);return}nt&&(V("dispatch-rename-reapply",{label:nt.label,reason:e?"first-observed-frame":"second-observed-frame"}),gn(nt.label,nt.send))}),window.addEventListener(Pu,()=>{mn=!0,V("agent-auth-required-observed",{});const e=Ke;Ke=[];for(const t of e)t("auth-required")}))}Du();function Au(){return yn?Promise.resolve("banner"):new Promise(e=>{let t=!1;const r=a=>{t||(t=!0,clearTimeout(s),e(a))};Ke.push(r);const s=setTimeout(()=>{if(t)return;t=!0;const a=Ke.indexOf(r);a>=0&&Ke.splice(a,1),e("fallback")},pn)})}async function Xa(e,t,r=0,s=or,a=!1){if(vn){V("dispatch-rename-suppressed",{caller:t,label:e});return}vn=!0,st={label:e,send:s},V("dispatch-rename",{phase:"queued",caller:t,label:e,fallbackMs:pn,postReadyDelayMs:r});const o=await Au();if(o==="auth-required"){V("dispatch-rename-deferred-for-auth",{caller:t,label:e});return}if(a&&o==="fallback"){V("dispatch-rename-skipped-no-banner",{caller:t,label:e,fallbackMs:pn});return}r>0&&await new Promise(l=>setTimeout(l,r)),o==="fallback"&&V("dispatch-rename-fallback",{caller:t,label:e,fallbackMs:pn}),V("dispatch-rename",{phase:"fired",caller:t,label:e,source:o,postReadyDelayMs:r}),nt={label:e,send:s},gn(e,s)}function Fu(){vn=!1,yn=!1,Ke=[],nt=null,st=null,mn=!1}function Lu(){vn=!1,Ke=[],st=null}const Mu="Editor";function Iu({provider:e,agentStartMode:t,currentFeature:r}){const s=i.useRef(!1);i.useEffect(()=>{if(!(s.current||e!=="claude"||t!=="fresh")){if(r!==null){s.current=!0;return}s.current=!0,Xa(Mu,"build-session-seed",Ca,void 0,!0)}},[e,t,r])}function $u({snippet:e,onRetry:t,onDismiss:r}){return n.jsx("div",{"data-testid":"build-tab-startup-error",className:"border-b border-red-500/30 bg-red-950/40 text-red-100 px-4 py-3",children:n.jsxs("div",{className:"flex items-start justify-between gap-4",children:[n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"font-medium text-sm mb-1",children:"Claude didn't start"}),n.jsx("pre",{"data-testid":"build-tab-startup-error-snippet",className:"font-mono text-xs whitespace-pre-wrap break-words bg-black/40 text-red-50 px-2 py-1 rounded max-h-40 overflow-auto",children:e})]}),n.jsxs("div",{className:"flex items-start gap-2 shrink-0",children:[n.jsx("button",{type:"button",onClick:t,"data-testid":"build-tab-startup-error-retry",className:"px-3 py-1.5 rounded bg-red-500 text-white text-sm font-medium cursor-pointer hover:bg-red-400",children:"Retry"}),n.jsx("button",{type:"button",onClick:r,"data-testid":"build-tab-startup-error-dismiss","aria-label":"Dismiss",title:"Dismiss",className:"px-2 py-1.5 rounded text-red-200 text-sm cursor-pointer hover:bg-red-900/40",children:"×"})]})]})})}const Ou=1e3;let dr=0;function nn(){dr=Date.now()}function Bu(){return dr===0?1/0:Date.now()-dr}function _u(){return Bu()<Ou}function wn(){window.focus()}function Qa(e,t,r=50){const s=i.useRef(t);s.current=t,i.useEffect(()=>{const a=e.current;if(!a)return;let o=null;const l=new ResizeObserver(c=>{o&&clearTimeout(o);const d=c[0];d&&(o=setTimeout(()=>{s.current(d)},r))});return l.observe(a),()=>{o&&clearTimeout(o),l.disconnect()}},[e,r])}function zu({wsRef:e,insertInput:t}){const[r,s]=i.useState(!1),[a,o]=i.useState(null),l=i.useRef(new Map),c=i.useRef(0);i.useEffect(()=>{if(a===null)return;const x=window.setTimeout(()=>o(null),qd);return()=>window.clearTimeout(x)},[a]);const d=i.useCallback(x=>{o(x)},[]),u=i.useCallback((x,w)=>{const k=l.current.get(x);k&&(l.current.delete(x),k.resolve(w))},[]),f=i.useCallback((x,w)=>{const k=l.current.get(x);k&&(l.current.delete(x),k.reject(w))},[]),p=i.useCallback(x=>{for(const[,w]of l.current)w.reject(x);l.current.clear()},[]),m=i.useCallback(async x=>{if(x.size>bn)throw new Error(`File too large (max ${bn/(1024*1024)} MB)`);const w=e.current;if(!w||w.readyState!==WebSocket.OPEN)throw new Error("Not connected — try again in a moment");const k=await Ja(x),C=Jd(),N=new Promise((E,R)=>{const S=window.setTimeout(()=>{l.current.delete(C)&&R(new Error("Timed out waiting for save to complete"))},Yd);l.current.set(C,{resolve:D=>{window.clearTimeout(S),E(D)},reject:D=>{window.clearTimeout(S),R(new Error(D))}})});return w.send(JSON.stringify({type:"drop",id:C,name:x.name||"unnamed",mime:x.type||"application/octet-stream",data:k})),N},[e]),h=i.useCallback(async x=>{if(x.length===0)return;const w=[];for(const k of x)try{w.push(await m(k))}catch(C){const N=C instanceof Error?C.message:String(C);d(`Attach failed: ${N}`);return}t(w.map(Xd).join(" ")+" ")},[m,d,t]),v=i.useCallback(x=>{x.dataTransfer.types.includes("Files")&&(x.preventDefault(),c.current+=1,s(!0))},[]),g=i.useCallback(x=>{x.dataTransfer.types.includes("Files")&&x.preventDefault()},[]),y=i.useCallback(x=>{x.dataTransfer.types.includes("Files")&&(c.current=Math.max(0,c.current-1),c.current===0&&s(!1))},[]),j=i.useCallback(async x=>{if(!x.dataTransfer.types.includes("Files"))return;if(x.preventDefault(),c.current=0,s(!1),Qd(x.dataTransfer)){d("Folder drops are not supported — drag individual files instead");return}const w=Array.from(x.dataTransfer.files).filter(k=>k.size>0);await h(w)},[h,d]),b=i.useCallback(async x=>{var C;const w=(C=x.clipboardData)==null?void 0:C.items;if(!w)return;const k=[];for(const N of Array.from(w))if(N.kind==="file"&&N.type.startsWith("image/")){const E=N.getAsFile();E&&k.push(E)}k.length!==0&&(x.preventDefault(),await h(k))},[h]);return{dragActive:r,errorToast:a,dropHandlers:{onDragEnter:v,onDragOver:g,onDragLeave:y,onDrop:j},pasteHandler:b,resolveDrop:u,rejectDrop:f,cancelAllDrops:p,showError:d}}function Za(e){const[t,r]=i.useState(0);i.useEffect(()=>{if(t===0)return;const a=window.setTimeout(()=>r(0),e);return()=>window.clearTimeout(a)},[t,e]);const s=i.useCallback(()=>{r(a=>a+1)},[]);return[t>0,s]}function bt(e=typeof window<"u"?window:void 0){return e?e.self!==e.top:!1}function Hu({isInIframe:e,previewKind:t,selectedScenario:r}){return e?!1:t!=="application"?!0:!r||!Ct(r)}function Wu(){return n.jsx("div",{"data-testid":"terminal-drop-overlay",style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(30, 30, 30, 0.85)",color:"#D7FF63",fontFamily:"'IBM Plex Mono', monospace",fontSize:14,border:"2px dashed #D7FF63",borderRadius:6,pointerEvents:"none",zIndex:5},children:"Drop file to attach"})}function Vu({message:e}){return n.jsx("div",{"data-testid":"terminal-drop-toast",style:{position:"absolute",bottom:12,left:"50%",transform:"translateX(-50%)",background:"#3a1f1f",color:"#ff9494",border:"1px solid #7a3939",borderRadius:4,padding:"6px 12px",fontFamily:"'IBM Plex Mono', monospace",fontSize:12,zIndex:6,pointerEvents:"none"},children:e})}function eo(){return n.jsx("div",{"data-testid":"terminal-copied-toast",style:{position:"absolute",bottom:12,left:"50%",transform:"translateX(-50%)",background:"#1f3a23",color:"#94ff94",border:"1px solid #397a39",borderRadius:4,padding:"6px 12px",fontFamily:"'IBM Plex Mono', monospace",fontSize:12,zIndex:6,pointerEvents:"none"},children:"Copied"})}const Ss=15;function Uu({provider:e,agentStartMode:t,sessionId:r,onAgentIdle:s,onAgentActive:a,onUserInput:o,onStartupFailed:l,onStartupFailedCleared:c}){if(bt())return null;const d=i.useRef(null),u=i.useRef(null),f=i.useRef(null),p=i.useRef(null),m=i.useRef(!1),h=i.useRef(t??"fresh"),v=i.useRef(r??null),[g,y]=i.useState({kind:"connecting"}),[j,b]=i.useState(0),[x,w]=Za(1200);i.useEffect(()=>{h.current=t??"fresh",v.current=r??null},[t,r]);const k=i.useRef(s);k.current=s;const C=i.useRef(a);C.current=a;const N=i.useRef(o);N.current=o;const E=i.useRef(l);E.current=l;const R=i.useRef(c);R.current=c;const S=zu({wsRef:p,insertInput:P=>{var I,O;((I=p.current)==null?void 0:I.readyState)===WebSocket.OPEN&&p.current.send(JSON.stringify({type:"input",data:P})),nn(),(O=N.current)==null||O.call(N)}}),D=i.useRef(S);return D.current=S,Qa(d,()=>{var P;f.current&&u.current&&(f.current.fit(),((P=p.current)==null?void 0:P.readyState)===WebSocket.OPEN&&p.current.send(JSON.stringify({type:"resize",cols:u.current.cols,rows:u.current.rows})))}),i.useEffect(()=>{if(!d.current||m.current)return;m.current=!0;const P=new Sa.Terminal({cursorBlink:!0,fontSize:13,fontFamily:"'IBM Plex Mono', monospace",rightClickSelectsWord:!1,theme:{background:"#1e1e1e",foreground:"#cccccc",cursor:"#D7FF63",selectionBackground:"#264f78"}}),I=new Ea.FitAddon;P.loadAddon(I),P.open(d.current),u.current=P,f.current=I;const O=Ra(P,d.current,{onError:_=>D.current.showError(_),onCopy:()=>w()}),U=Ta(P,{sendInput:_=>{var $,Q;(($=p.current)==null?void 0:$.readyState)===WebSocket.OPEN&&p.current.send(JSON.stringify({type:"input",data:_})),nn(),(Q=N.current)==null||Q.call(N)}});requestAnimationFrame(()=>{I.fit(),P.focus()});let J=!1,T=0,L=null;function W(){try{const _=new WebSocket(tl({provider:e,mode:h.current,sessionId:v.current??void 0}));p.current=_,_.binaryType="arraybuffer",_.onmessage=$=>{var Q,H,G,ae;if($.data instanceof ArrayBuffer)P.write(new Uint8Array($.data));else if(typeof $.data=="string")try{const z=JSON.parse($.data);if(z.type==="error"){J=!0,y({kind:"server-error",message:nl(z)});return}if(z.type==="session-id")h.current="resume",v.current=z.sessionId??null;else if(z.type==="agent-idle"||z.type==="claude-idle"){const oe=typeof z.source=="string"?z.source:void 0;V("ws-message-received",{type:z.type,source:oe}),(Q=k.current)==null||Q.call(k,oe)}else if(z.type==="agent-active"||z.type==="claude-active")V("ws-message-received-active",{type:z.type}),(H=C.current)==null||H.call(C);else if(z.type==="idle-diag"){const{site:oe,event:pe,...ne}=z;V(`rust:${pe??"unknown"}`,{site:oe,...ne})}else z.type==="drop-complete"?D.current.resolveDrop(String(z.id??""),String(z.path??"")):z.type==="drop-error"?D.current.rejectDrop(String(z.id??""),String(z.message??"drop failed")):z.type==="startup-failed"?(G=E.current)==null||G.call(E,String(z.snippet??"")):z.type==="startup-failed-cleared"?(ae=R.current)==null||ae.call(R):z.type==="agent-banner-ready"?(V("agent-banner-ready",{}),window.dispatchEvent(new CustomEvent("agent-banner-ready"))):z.type==="agent-auth-required"&&(V("agent-auth-required",{}),window.dispatchEvent(new CustomEvent("agent-auth-required")))}catch{}},_.onopen=()=>{T=0,y({kind:"open"}),V("ws-open"),_.send(JSON.stringify({type:"resize",cols:P.cols,rows:P.rows}));try{typeof localStorage<"u"&&localStorage.getItem("codeyam.idleDebug")==="1"&&(_.send(JSON.stringify({type:"enable-idle-diag",sessionId:Rr()})),V("idle-diag-enabled"))}catch{}},_.onerror=()=>{},_.onclose=async()=>{if(V("ws-close",{reconnectAttempts:T}),D.current.cancelAllDrops("Not connected"),J){y(Q=>Q.kind==="server-error"?Q:{kind:"ended"}),P.writeln(`\r
|
|
9
|
+
\x1B[90m[Terminal session ended]\x1B[0m`);return}const $=await rl();if(!J){if(!$){y({kind:"server-stopped"}),L==null||L(),L=sl(2e3,()=>{J||window.location.reload()});return}if(T<Ss){const Q=T<4?1e3*Math.pow(2,T):1e4;T++,y({kind:"reconnecting",attempt:T,maxAttempts:Ss}),setTimeout(()=>{J||W()},Q)}else y({kind:"failed"})}}}catch{y({kind:"failed"})}}W();let B=0;const Y=1e3;function A(){var $;const _=Date.now();_-B>=Y&&(($=p.current)==null?void 0:$.readyState)===WebSocket.OPEN&&(p.current.send(JSON.stringify({type:"browser-activity"})),B=_)}document.addEventListener("mousemove",A),document.addEventListener("keydown",A),document.addEventListener("mousedown",A),P.onData(_=>{var $,Q;(($=p.current)==null?void 0:$.readyState)===WebSocket.OPEN?p.current.send(JSON.stringify({type:"input",data:_})):b(H=>H+1),nn(),(Q=N.current)==null||Q.call(N)});const F=d.current;function M(_){var z,oe,pe,ne;const $=_,Q=(z=$.clipboardData)==null?void 0:z.items;if(Q){for(const le of Array.from(Q))if(le.kind==="file"&&le.type.startsWith("image/")){_.preventDefault(),_.stopPropagation(),D.current.pasteHandler($);return}}const H=((oe=$.clipboardData)==null?void 0:oe.getData("text"))??"";if(!H)return;_.preventDefault(),_.stopPropagation();const G=H.replace(/\r\n/g,"\r").replace(/\n/g,"\r"),ae=P.modes.bracketedPasteMode?`\x1B[200~${G}\x1B[201~`:G;((pe=p.current)==null?void 0:pe.readyState)===WebSocket.OPEN?p.current.send(JSON.stringify({type:"input",data:ae})):b(le=>le+1),nn(),(ne=N.current)==null||ne.call(N)}F.addEventListener("paste",M,!0);function X(_){var H,G;const $=_.detail;if(!$)return;((H=p.current)==null?void 0:H.readyState)===WebSocket.OPEN?((G=p.current)==null||G.send(JSON.stringify({type:"input",data:$})),V("terminal-send-input",{len:$.length,firstChars:$.slice(0,16),wsOpen:!0,dropped:!1})):V("terminal-send-input",{len:$.length,firstChars:$.slice(0,16),wsOpen:!1,dropped:!0})}window.addEventListener("terminal-send-input",X);function Z(){wn(),P.focus()}return window.addEventListener("terminal-focus",Z),()=>{var _;J=!0,L==null||L(),L=null,document.removeEventListener("mousemove",A),document.removeEventListener("keydown",A),document.removeEventListener("mousedown",A),window.removeEventListener("terminal-send-input",X),window.removeEventListener("terminal-focus",Z),F.removeEventListener("paste",M,!0),U(),(_=p.current)==null||_.close(),O(),P.dispose(),m.current=!1}},[e]),n.jsxs("div",{className:"relative flex-1 flex flex-col",style:{minHeight:0},"data-terminal-emulator":!0,onDragEnter:S.dropHandlers.onDragEnter,onDragOver:S.dropHandlers.onDragOver,onDragLeave:S.dropHandlers.onDragLeave,onDrop:S.dropHandlers.onDrop,onPaste:S.pasteHandler,children:[n.jsx("div",{ref:d,className:"flex-1",style:{background:"#1e1e1e",minHeight:0,paddingTop:3,paddingLeft:3},onClick:()=>{var P;wn(),(P=u.current)==null||P.focus()}}),S.dragActive&&n.jsx(Wu,{}),S.errorToast&&n.jsx(Vu,{message:S.errorToast}),x&&n.jsx(eo,{}),n.jsx(el,{status:g,pulseKey:j,onRefresh:()=>window.location.reload()})]})}function Ku({onAgentActive:e,onAgentIdle:t,onUserInput:r,provider:s,sessionId:a,shouldResumeSameProvider:o,currentFeature:l}){const[c,d]=i.useState(null),[u,f]=i.useState(0);Iu({provider:s,agentStartMode:o?"resume":"fresh",currentFeature:l}),i.useEffect(()=>()=>{Fu()},[]);const p=i.useCallback(v=>{d(v)},[]),m=i.useCallback(()=>{d(null)},[]),h=i.useCallback(()=>{d(null),f(v=>v+1)},[]);return n.jsxs("div",{className:"flex flex-col flex-1 min-h-0",children:[c!==null&&n.jsx($u,{snippet:c,onRetry:h,onDismiss:m}),n.jsx(Uu,{provider:s,agentStartMode:o?"resume":"fresh",sessionId:o?a:null,onAgentIdle:t,onAgentActive:e,onUserInput:r,onStartupFailed:p,onStartupFailedCleared:m},u)]})}function Gu(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return i.useMemo(()=>s=>{t.forEach(a=>a(s))},t)}const Rn=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function St(e){const t=Object.prototype.toString.call(e);return t==="[object Window]"||t==="[object global]"}function $r(e){return"nodeType"in e}function Ce(e){var t,r;return e?St(e)?e:$r(e)&&(t=(r=e.ownerDocument)==null?void 0:r.defaultView)!=null?t:window:window}function Or(e){const{Document:t}=Ce(e);return e instanceof t}function Ut(e){return St(e)?!1:e instanceof Ce(e).HTMLElement}function to(e){return e instanceof Ce(e).SVGElement}function Et(e){return e?St(e)?e.document:$r(e)?Or(e)?e:Ut(e)||to(e)?e.ownerDocument:document:document:document}const Ue=Rn?i.useLayoutEffect:i.useEffect;function Br(e){const t=i.useRef(e);return Ue(()=>{t.current=e}),i.useCallback(function(){for(var r=arguments.length,s=new Array(r),a=0;a<r;a++)s[a]=arguments[a];return t.current==null?void 0:t.current(...s)},[])}function Yu(){const e=i.useRef(null),t=i.useCallback((s,a)=>{e.current=setInterval(s,a)},[]),r=i.useCallback(()=>{e.current!==null&&(clearInterval(e.current),e.current=null)},[]);return[t,r]}function _t(e,t){t===void 0&&(t=[e]);const r=i.useRef(e);return Ue(()=>{r.current!==e&&(r.current=e)},t),r}function Kt(e,t){const r=i.useRef();return i.useMemo(()=>{const s=e(r.current);return r.current=s,s},[...t])}function jn(e){const t=Br(e),r=i.useRef(null),s=i.useCallback(a=>{a!==r.current&&(t==null||t(a,r.current)),r.current=a},[]);return[r,s]}function ur(e){const t=i.useRef();return i.useEffect(()=>{t.current=e},[e]),t.current}let Qn={};function Gt(e,t){return i.useMemo(()=>{if(t)return t;const r=Qn[e]==null?0:Qn[e]+1;return Qn[e]=r,e+"-"+r},[e,t])}function no(e){return function(t){for(var r=arguments.length,s=new Array(r>1?r-1:0),a=1;a<r;a++)s[a-1]=arguments[a];return s.reduce((o,l)=>{const c=Object.entries(l);for(const[d,u]of c){const f=o[d];f!=null&&(o[d]=f+e*u)}return o},{...t})}}const kt=no(1),zt=no(-1);function qu(e){return"clientX"in e&&"clientY"in e}function _r(e){if(!e)return!1;const{KeyboardEvent:t}=Ce(e.target);return t&&e instanceof t}function Ju(e){if(!e)return!1;const{TouchEvent:t}=Ce(e.target);return t&&e instanceof t}function fr(e){if(Ju(e)){if(e.touches&&e.touches.length){const{clientX:t,clientY:r}=e.touches[0];return{x:t,y:r}}else if(e.changedTouches&&e.changedTouches.length){const{clientX:t,clientY:r}=e.changedTouches[0];return{x:t,y:r}}}return qu(e)?{x:e.clientX,y:e.clientY}:null}const Ht=Object.freeze({Translate:{toString(e){if(!e)return;const{x:t,y:r}=e;return"translate3d("+(t?Math.round(t):0)+"px, "+(r?Math.round(r):0)+"px, 0)"}},Scale:{toString(e){if(!e)return;const{scaleX:t,scaleY:r}=e;return"scaleX("+t+") scaleY("+r+")"}},Transform:{toString(e){if(e)return[Ht.Translate.toString(e),Ht.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:t,duration:r,easing:s}=e;return t+" "+r+"ms "+s}}}),Es="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function Xu(e){return e.matches(Es)?e:e.querySelector(Es)}const Qu={display:"none"};function Zu(e){let{id:t,value:r}=e;return Ne.createElement("div",{id:t,style:Qu},r)}function ef(e){let{id:t,announcement:r,ariaLiveType:s="assertive"}=e;const a={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return Ne.createElement("div",{id:t,style:a,role:"status","aria-live":s,"aria-atomic":!0},r)}function tf(){const[e,t]=i.useState("");return{announce:i.useCallback(s=>{s!=null&&t(s)},[]),announcement:e}}const ro=i.createContext(null);function nf(e){const t=i.useContext(ro);i.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of <DndContext>");return t(e)},[e,t])}function rf(){const[e]=i.useState(()=>new Set),t=i.useCallback(s=>(e.add(s),()=>e.delete(s)),[e]);return[i.useCallback(s=>{let{type:a,event:o}=s;e.forEach(l=>{var c;return(c=l[a])==null?void 0:c.call(l,o)})},[e]),t]}const sf={draggable:`
|
|
10
|
+
To pick up a draggable item, press the space bar.
|
|
11
|
+
While dragging, use the arrow keys to move the item.
|
|
12
|
+
Press space again to drop the item in its new position, or press escape to cancel.
|
|
13
|
+
`},af={onDragStart(e){let{active:t}=e;return"Picked up draggable item "+t.id+"."},onDragOver(e){let{active:t,over:r}=e;return r?"Draggable item "+t.id+" was moved over droppable area "+r.id+".":"Draggable item "+t.id+" is no longer over a droppable area."},onDragEnd(e){let{active:t,over:r}=e;return r?"Draggable item "+t.id+" was dropped over droppable area "+r.id:"Draggable item "+t.id+" was dropped."},onDragCancel(e){let{active:t}=e;return"Dragging was cancelled. Draggable item "+t.id+" was dropped."}};function of(e){let{announcements:t=af,container:r,hiddenTextDescribedById:s,screenReaderInstructions:a=sf}=e;const{announce:o,announcement:l}=tf(),c=Gt("DndLiveRegion"),[d,u]=i.useState(!1);if(i.useEffect(()=>{u(!0)},[]),nf(i.useMemo(()=>({onDragStart(p){let{active:m}=p;o(t.onDragStart({active:m}))},onDragMove(p){let{active:m,over:h}=p;t.onDragMove&&o(t.onDragMove({active:m,over:h}))},onDragOver(p){let{active:m,over:h}=p;o(t.onDragOver({active:m,over:h}))},onDragEnd(p){let{active:m,over:h}=p;o(t.onDragEnd({active:m,over:h}))},onDragCancel(p){let{active:m,over:h}=p;o(t.onDragCancel({active:m,over:h}))}}),[o,t])),!d)return null;const f=Ne.createElement(Ne.Fragment,null,Ne.createElement(Zu,{id:s,value:a.draggable}),Ne.createElement(ef,{id:c,announcement:l}));return r?Ft.createPortal(f,r):f}var me;(function(e){e.DragStart="dragStart",e.DragMove="dragMove",e.DragEnd="dragEnd",e.DragCancel="dragCancel",e.DragOver="dragOver",e.RegisterDroppable="registerDroppable",e.SetDroppableDisabled="setDroppableDisabled",e.UnregisterDroppable="unregisterDroppable"})(me||(me={}));function kn(){}function Rs(e,t){return i.useMemo(()=>({sensor:e,options:t??{}}),[e,t])}function lf(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return i.useMemo(()=>[...t].filter(s=>s!=null),[...t])}const Oe=Object.freeze({x:0,y:0});function so(e,t){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function ao(e,t){let{data:{value:r}}=e,{data:{value:s}}=t;return r-s}function cf(e,t){let{data:{value:r}}=e,{data:{value:s}}=t;return s-r}function Ts(e){let{left:t,top:r,height:s,width:a}=e;return[{x:t,y:r},{x:t+a,y:r},{x:t,y:r+s},{x:t+a,y:r+s}]}function oo(e,t){if(!e||e.length===0)return null;const[r]=e;return r[t]}function Ps(e,t,r){return t===void 0&&(t=e.left),r===void 0&&(r=e.top),{x:t+e.width*.5,y:r+e.height*.5}}const df=e=>{let{collisionRect:t,droppableRects:r,droppableContainers:s}=e;const a=Ps(t,t.left,t.top),o=[];for(const l of s){const{id:c}=l,d=r.get(c);if(d){const u=so(Ps(d),a);o.push({id:c,data:{droppableContainer:l,value:u}})}}return o.sort(ao)},uf=e=>{let{collisionRect:t,droppableRects:r,droppableContainers:s}=e;const a=Ts(t),o=[];for(const l of s){const{id:c}=l,d=r.get(c);if(d){const u=Ts(d),f=a.reduce((m,h,v)=>m+so(u[v],h),0),p=Number((f/4).toFixed(4));o.push({id:c,data:{droppableContainer:l,value:p}})}}return o.sort(ao)};function ff(e,t){const r=Math.max(t.top,e.top),s=Math.max(t.left,e.left),a=Math.min(t.left+t.width,e.left+e.width),o=Math.min(t.top+t.height,e.top+e.height),l=a-s,c=o-r;if(s<a&&r<o){const d=t.width*t.height,u=e.width*e.height,f=l*c,p=f/(d+u-f);return Number(p.toFixed(4))}return 0}const pf=e=>{let{collisionRect:t,droppableRects:r,droppableContainers:s}=e;const a=[];for(const o of s){const{id:l}=o,c=r.get(l);if(c){const d=ff(c,t);d>0&&a.push({id:l,data:{droppableContainer:o,value:d}})}}return a.sort(cf)};function mf(e,t,r){return{...e,scaleX:t&&r?t.width/r.width:1,scaleY:t&&r?t.height/r.height:1}}function io(e,t){return e&&t?{x:e.left-t.left,y:e.top-t.top}:Oe}function hf(e){return function(r){for(var s=arguments.length,a=new Array(s>1?s-1:0),o=1;o<s;o++)a[o-1]=arguments[o];return a.reduce((l,c)=>({...l,top:l.top+e*c.y,bottom:l.bottom+e*c.y,left:l.left+e*c.x,right:l.right+e*c.x}),{...r})}}const xf=hf(1);function gf(e){if(e.startsWith("matrix3d(")){const t=e.slice(9,-1).split(/, /);return{x:+t[12],y:+t[13],scaleX:+t[0],scaleY:+t[5]}}else if(e.startsWith("matrix(")){const t=e.slice(7,-1).split(/, /);return{x:+t[4],y:+t[5],scaleX:+t[0],scaleY:+t[3]}}return null}function bf(e,t,r){const s=gf(t);if(!s)return e;const{scaleX:a,scaleY:o,x:l,y:c}=s,d=e.left-l-(1-a)*parseFloat(r),u=e.top-c-(1-o)*parseFloat(r.slice(r.indexOf(" ")+1)),f=a?e.width/a:e.width,p=o?e.height/o:e.height;return{width:f,height:p,top:u,right:d+f,bottom:u+p,left:d}}const vf={ignoreTransform:!1};function Rt(e,t){t===void 0&&(t=vf);let r=e.getBoundingClientRect();if(t.ignoreTransform){const{transform:u,transformOrigin:f}=Ce(e).getComputedStyle(e);u&&(r=bf(r,u,f))}const{top:s,left:a,width:o,height:l,bottom:c,right:d}=r;return{top:s,left:a,width:o,height:l,bottom:c,right:d}}function Ds(e){return Rt(e,{ignoreTransform:!0})}function yf(e){const t=e.innerWidth,r=e.innerHeight;return{top:0,left:0,right:t,bottom:r,width:t,height:r}}function wf(e,t){return t===void 0&&(t=Ce(e).getComputedStyle(e)),t.position==="fixed"}function jf(e,t){t===void 0&&(t=Ce(e).getComputedStyle(e));const r=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(a=>{const o=t[a];return typeof o=="string"?r.test(o):!1})}function Tn(e,t){const r=[];function s(a){if(t!=null&&r.length>=t||!a)return r;if(Or(a)&&a.scrollingElement!=null&&!r.includes(a.scrollingElement))return r.push(a.scrollingElement),r;if(!Ut(a)||to(a)||r.includes(a))return r;const o=Ce(e).getComputedStyle(a);return a!==e&&jf(a,o)&&r.push(a),wf(a,o)?r:s(a.parentNode)}return e?s(e):r}function lo(e){const[t]=Tn(e,1);return t??null}function Zn(e){return!Rn||!e?null:St(e)?e:$r(e)?Or(e)||e===Et(e).scrollingElement?window:Ut(e)?e:null:null}function co(e){return St(e)?e.scrollX:e.scrollLeft}function uo(e){return St(e)?e.scrollY:e.scrollTop}function pr(e){return{x:co(e),y:uo(e)}}var ge;(function(e){e[e.Forward=1]="Forward",e[e.Backward=-1]="Backward"})(ge||(ge={}));function fo(e){return!Rn||!e?!1:e===document.scrollingElement}function po(e){const t={x:0,y:0},r=fo(e)?{height:window.innerHeight,width:window.innerWidth}:{height:e.clientHeight,width:e.clientWidth},s={x:e.scrollWidth-r.width,y:e.scrollHeight-r.height},a=e.scrollTop<=t.y,o=e.scrollLeft<=t.x,l=e.scrollTop>=s.y,c=e.scrollLeft>=s.x;return{isTop:a,isLeft:o,isBottom:l,isRight:c,maxScroll:s,minScroll:t}}const kf={x:.2,y:.2};function Nf(e,t,r,s,a){let{top:o,left:l,right:c,bottom:d}=r;s===void 0&&(s=10),a===void 0&&(a=kf);const{isTop:u,isBottom:f,isLeft:p,isRight:m}=po(e),h={x:0,y:0},v={x:0,y:0},g={height:t.height*a.y,width:t.width*a.x};return!u&&o<=t.top+g.height?(h.y=ge.Backward,v.y=s*Math.abs((t.top+g.height-o)/g.height)):!f&&d>=t.bottom-g.height&&(h.y=ge.Forward,v.y=s*Math.abs((t.bottom-g.height-d)/g.height)),!m&&c>=t.right-g.width?(h.x=ge.Forward,v.x=s*Math.abs((t.right-g.width-c)/g.width)):!p&&l<=t.left+g.width&&(h.x=ge.Backward,v.x=s*Math.abs((t.left+g.width-l)/g.width)),{direction:h,speed:v}}function Cf(e){if(e===document.scrollingElement){const{innerWidth:o,innerHeight:l}=window;return{top:0,left:0,right:o,bottom:l,width:o,height:l}}const{top:t,left:r,right:s,bottom:a}=e.getBoundingClientRect();return{top:t,left:r,right:s,bottom:a,width:e.clientWidth,height:e.clientHeight}}function mo(e){return e.reduce((t,r)=>kt(t,pr(r)),Oe)}function Sf(e){return e.reduce((t,r)=>t+co(r),0)}function Ef(e){return e.reduce((t,r)=>t+uo(r),0)}function Rf(e,t){if(t===void 0&&(t=Rt),!e)return;const{top:r,left:s,bottom:a,right:o}=t(e);lo(e)&&(a<=0||o<=0||r>=window.innerHeight||s>=window.innerWidth)&&e.scrollIntoView({block:"center",inline:"center"})}const Tf=[["x",["left","right"],Sf],["y",["top","bottom"],Ef]];class zr{constructor(t,r){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const s=Tn(r),a=mo(s);this.rect={...t},this.width=t.width,this.height=t.height;for(const[o,l,c]of Tf)for(const d of l)Object.defineProperty(this,d,{get:()=>{const u=c(s),f=a[o]-u;return this.rect[d]+f},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class It{constructor(t){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(r=>{var s;return(s=this.target)==null?void 0:s.removeEventListener(...r)})},this.target=t}add(t,r,s){var a;(a=this.target)==null||a.addEventListener(t,r,s),this.listeners.push([t,r,s])}}function Pf(e){const{EventTarget:t}=Ce(e);return e instanceof t?e:Et(e)}function er(e,t){const r=Math.abs(e.x),s=Math.abs(e.y);return typeof t=="number"?Math.sqrt(r**2+s**2)>t:"x"in t&&"y"in t?r>t.x&&s>t.y:"x"in t?r>t.x:"y"in t?s>t.y:!1}var Me;(function(e){e.Click="click",e.DragStart="dragstart",e.Keydown="keydown",e.ContextMenu="contextmenu",e.Resize="resize",e.SelectionChange="selectionchange",e.VisibilityChange="visibilitychange"})(Me||(Me={}));function As(e){e.preventDefault()}function Df(e){e.stopPropagation()}var re;(function(e){e.Space="Space",e.Down="ArrowDown",e.Right="ArrowRight",e.Left="ArrowLeft",e.Up="ArrowUp",e.Esc="Escape",e.Enter="Enter",e.Tab="Tab"})(re||(re={}));const ho={start:[re.Space,re.Enter],cancel:[re.Esc],end:[re.Space,re.Enter,re.Tab]},Af=(e,t)=>{let{currentCoordinates:r}=t;switch(e.code){case re.Right:return{...r,x:r.x+25};case re.Left:return{...r,x:r.x-25};case re.Down:return{...r,y:r.y+25};case re.Up:return{...r,y:r.y-25}}};class Hr{constructor(t){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=t;const{event:{target:r}}=t;this.props=t,this.listeners=new It(Et(r)),this.windowListeners=new It(Ce(r)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(Me.Resize,this.handleCancel),this.windowListeners.add(Me.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(Me.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:r}=this.props,s=t.node.current;s&&Rf(s),r(Oe)}handleKeyDown(t){if(_r(t)){const{active:r,context:s,options:a}=this.props,{keyboardCodes:o=ho,coordinateGetter:l=Af,scrollBehavior:c="smooth"}=a,{code:d}=t;if(o.end.includes(d)){this.handleEnd(t);return}if(o.cancel.includes(d)){this.handleCancel(t);return}const{collisionRect:u}=s.current,f=u?{x:u.left,y:u.top}:Oe;this.referenceCoordinates||(this.referenceCoordinates=f);const p=l(t,{active:r,context:s.current,currentCoordinates:f});if(p){const m=zt(p,f),h={x:0,y:0},{scrollableAncestors:v}=s.current;for(const g of v){const y=t.code,{isTop:j,isRight:b,isLeft:x,isBottom:w,maxScroll:k,minScroll:C}=po(g),N=Cf(g),E={x:Math.min(y===re.Right?N.right-N.width/2:N.right,Math.max(y===re.Right?N.left:N.left+N.width/2,p.x)),y:Math.min(y===re.Down?N.bottom-N.height/2:N.bottom,Math.max(y===re.Down?N.top:N.top+N.height/2,p.y))},R=y===re.Right&&!b||y===re.Left&&!x,S=y===re.Down&&!w||y===re.Up&&!j;if(R&&E.x!==p.x){const D=g.scrollLeft+m.x,P=y===re.Right&&D<=k.x||y===re.Left&&D>=C.x;if(P&&!m.y){g.scrollTo({left:D,behavior:c});return}P?h.x=g.scrollLeft-D:h.x=y===re.Right?g.scrollLeft-k.x:g.scrollLeft-C.x,h.x&&g.scrollBy({left:-h.x,behavior:c});break}else if(S&&E.y!==p.y){const D=g.scrollTop+m.y,P=y===re.Down&&D<=k.y||y===re.Up&&D>=C.y;if(P&&!m.x){g.scrollTo({top:D,behavior:c});return}P?h.y=g.scrollTop-D:h.y=y===re.Down?g.scrollTop-k.y:g.scrollTop-C.y,h.y&&g.scrollBy({top:-h.y,behavior:c});break}}this.handleMove(t,kt(zt(p,this.referenceCoordinates),h))}}}handleMove(t,r){const{onMove:s}=this.props;t.preventDefault(),s(r)}handleEnd(t){const{onEnd:r}=this.props;t.preventDefault(),this.detach(),r()}handleCancel(t){const{onCancel:r}=this.props;t.preventDefault(),this.detach(),r()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}Hr.activators=[{eventName:"onKeyDown",handler:(e,t,r)=>{let{keyboardCodes:s=ho,onActivation:a}=t,{active:o}=r;const{code:l}=e.nativeEvent;if(s.start.includes(l)){const c=o.activatorNode.current;return c&&e.target!==c?!1:(e.preventDefault(),a==null||a({event:e.nativeEvent}),!0)}return!1}}];function Fs(e){return!!(e&&"distance"in e)}function Ls(e){return!!(e&&"delay"in e)}class Wr{constructor(t,r,s){var a;s===void 0&&(s=Pf(t.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=t,this.events=r;const{event:o}=t,{target:l}=o;this.props=t,this.events=r,this.document=Et(l),this.documentListeners=new It(this.document),this.listeners=new It(s),this.windowListeners=new It(Ce(l)),this.initialCoordinates=(a=fr(o))!=null?a:Oe,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){const{events:t,props:{options:{activationConstraint:r,bypassActivationConstraint:s}}}=this;if(this.listeners.add(t.move.name,this.handleMove,{passive:!1}),this.listeners.add(t.end.name,this.handleEnd),t.cancel&&this.listeners.add(t.cancel.name,this.handleCancel),this.windowListeners.add(Me.Resize,this.handleCancel),this.windowListeners.add(Me.DragStart,As),this.windowListeners.add(Me.VisibilityChange,this.handleCancel),this.windowListeners.add(Me.ContextMenu,As),this.documentListeners.add(Me.Keydown,this.handleKeydown),r){if(s!=null&&s({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(Ls(r)){this.timeoutId=setTimeout(this.handleStart,r.delay),this.handlePending(r);return}if(Fs(r)){this.handlePending(r);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(t,r){const{active:s,onPending:a}=this.props;a(s,t,this.initialCoordinates,r)}handleStart(){const{initialCoordinates:t}=this,{onStart:r}=this.props;t&&(this.activated=!0,this.documentListeners.add(Me.Click,Df,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(Me.SelectionChange,this.removeTextSelection),r(t))}handleMove(t){var r;const{activated:s,initialCoordinates:a,props:o}=this,{onMove:l,options:{activationConstraint:c}}=o;if(!a)return;const d=(r=fr(t))!=null?r:Oe,u=zt(a,d);if(!s&&c){if(Fs(c)){if(c.tolerance!=null&&er(u,c.tolerance))return this.handleCancel();if(er(u,c.distance))return this.handleStart()}if(Ls(c)&&er(u,c.tolerance))return this.handleCancel();this.handlePending(c,u);return}t.cancelable&&t.preventDefault(),l(d)}handleEnd(){const{onAbort:t,onEnd:r}=this.props;this.detach(),this.activated||t(this.props.active),r()}handleCancel(){const{onAbort:t,onCancel:r}=this.props;this.detach(),this.activated||t(this.props.active),r()}handleKeydown(t){t.code===re.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const Ff={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class Vr extends Wr{constructor(t){const{event:r}=t,s=Et(r.target);super(t,Ff,s)}}Vr.activators=[{eventName:"onPointerDown",handler:(e,t)=>{let{nativeEvent:r}=e,{onActivation:s}=t;return!r.isPrimary||r.button!==0?!1:(s==null||s({event:r}),!0)}}];const Lf={move:{name:"mousemove"},end:{name:"mouseup"}};var mr;(function(e){e[e.RightClick=2]="RightClick"})(mr||(mr={}));class Mf extends Wr{constructor(t){super(t,Lf,Et(t.event.target))}}Mf.activators=[{eventName:"onMouseDown",handler:(e,t)=>{let{nativeEvent:r}=e,{onActivation:s}=t;return r.button===mr.RightClick?!1:(s==null||s({event:r}),!0)}}];const tr={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class If extends Wr{constructor(t){super(t,tr)}static setup(){return window.addEventListener(tr.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(tr.move.name,t)};function t(){}}}If.activators=[{eventName:"onTouchStart",handler:(e,t)=>{let{nativeEvent:r}=e,{onActivation:s}=t;const{touches:a}=r;return a.length>1?!1:(s==null||s({event:r}),!0)}}];var $t;(function(e){e[e.Pointer=0]="Pointer",e[e.DraggableRect=1]="DraggableRect"})($t||($t={}));var Nn;(function(e){e[e.TreeOrder=0]="TreeOrder",e[e.ReversedTreeOrder=1]="ReversedTreeOrder"})(Nn||(Nn={}));function $f(e){let{acceleration:t,activator:r=$t.Pointer,canScroll:s,draggingRect:a,enabled:o,interval:l=5,order:c=Nn.TreeOrder,pointerCoordinates:d,scrollableAncestors:u,scrollableAncestorRects:f,delta:p,threshold:m}=e;const h=Bf({delta:p,disabled:!o}),[v,g]=Yu(),y=i.useRef({x:0,y:0}),j=i.useRef({x:0,y:0}),b=i.useMemo(()=>{switch(r){case $t.Pointer:return d?{top:d.y,bottom:d.y,left:d.x,right:d.x}:null;case $t.DraggableRect:return a}},[r,a,d]),x=i.useRef(null),w=i.useCallback(()=>{const C=x.current;if(!C)return;const N=y.current.x*j.current.x,E=y.current.y*j.current.y;C.scrollBy(N,E)},[]),k=i.useMemo(()=>c===Nn.TreeOrder?[...u].reverse():u,[c,u]);i.useEffect(()=>{if(!o||!u.length||!b){g();return}for(const C of k){if((s==null?void 0:s(C))===!1)continue;const N=u.indexOf(C),E=f[N];if(!E)continue;const{direction:R,speed:S}=Nf(C,E,b,t,m);for(const D of["x","y"])h[D][R[D]]||(S[D]=0,R[D]=0);if(S.x>0||S.y>0){g(),x.current=C,v(w,l),y.current=S,j.current=R;return}}y.current={x:0,y:0},j.current={x:0,y:0},g()},[t,w,s,g,o,l,JSON.stringify(b),JSON.stringify(h),v,u,k,f,JSON.stringify(m)])}const Of={x:{[ge.Backward]:!1,[ge.Forward]:!1},y:{[ge.Backward]:!1,[ge.Forward]:!1}};function Bf(e){let{delta:t,disabled:r}=e;const s=ur(t);return Kt(a=>{if(r||!s||!a)return Of;const o={x:Math.sign(t.x-s.x),y:Math.sign(t.y-s.y)};return{x:{[ge.Backward]:a.x[ge.Backward]||o.x===-1,[ge.Forward]:a.x[ge.Forward]||o.x===1},y:{[ge.Backward]:a.y[ge.Backward]||o.y===-1,[ge.Forward]:a.y[ge.Forward]||o.y===1}}},[r,t,s])}function _f(e,t){const r=t!=null?e.get(t):void 0,s=r?r.node.current:null;return Kt(a=>{var o;return t==null?null:(o=s??a)!=null?o:null},[s,t])}function zf(e,t){return i.useMemo(()=>e.reduce((r,s)=>{const{sensor:a}=s,o=a.activators.map(l=>({eventName:l.eventName,handler:t(l.handler,s)}));return[...r,...o]},[]),[e,t])}var Wt;(function(e){e[e.Always=0]="Always",e[e.BeforeDragging=1]="BeforeDragging",e[e.WhileDragging=2]="WhileDragging"})(Wt||(Wt={}));var hr;(function(e){e.Optimized="optimized"})(hr||(hr={}));const Ms=new Map;function Hf(e,t){let{dragging:r,dependencies:s,config:a}=t;const[o,l]=i.useState(null),{frequency:c,measure:d,strategy:u}=a,f=i.useRef(e),p=y(),m=_t(p),h=i.useCallback(function(j){j===void 0&&(j=[]),!m.current&&l(b=>b===null?j:b.concat(j.filter(x=>!b.includes(x))))},[m]),v=i.useRef(null),g=Kt(j=>{if(p&&!r)return Ms;if(!j||j===Ms||f.current!==e||o!=null){const b=new Map;for(let x of e){if(!x)continue;if(o&&o.length>0&&!o.includes(x.id)&&x.rect.current){b.set(x.id,x.rect.current);continue}const w=x.node.current,k=w?new zr(d(w),w):null;x.rect.current=k,k&&b.set(x.id,k)}return b}return j},[e,o,r,p,d]);return i.useEffect(()=>{f.current=e},[e]),i.useEffect(()=>{p||h()},[r,p]),i.useEffect(()=>{o&&o.length>0&&l(null)},[JSON.stringify(o)]),i.useEffect(()=>{p||typeof c!="number"||v.current!==null||(v.current=setTimeout(()=>{h(),v.current=null},c))},[c,p,h,...s]),{droppableRects:g,measureDroppableContainers:h,measuringScheduled:o!=null};function y(){switch(u){case Wt.Always:return!1;case Wt.BeforeDragging:return r;default:return!r}}}function xo(e,t){return Kt(r=>e?r||(typeof t=="function"?t(e):e):null,[t,e])}function Wf(e,t){return xo(e,t)}function Vf(e){let{callback:t,disabled:r}=e;const s=Br(t),a=i.useMemo(()=>{if(r||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:o}=window;return new o(s)},[s,r]);return i.useEffect(()=>()=>a==null?void 0:a.disconnect(),[a]),a}function Pn(e){let{callback:t,disabled:r}=e;const s=Br(t),a=i.useMemo(()=>{if(r||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:o}=window;return new o(s)},[r]);return i.useEffect(()=>()=>a==null?void 0:a.disconnect(),[a]),a}function Uf(e){return new zr(Rt(e),e)}function Is(e,t,r){t===void 0&&(t=Uf);const[s,a]=i.useState(null);function o(){a(d=>{if(!e)return null;if(e.isConnected===!1){var u;return(u=d??r)!=null?u:null}const f=t(e);return JSON.stringify(d)===JSON.stringify(f)?d:f})}const l=Vf({callback(d){if(e)for(const u of d){const{type:f,target:p}=u;if(f==="childList"&&p instanceof HTMLElement&&p.contains(e)){o();break}}}}),c=Pn({callback:o});return Ue(()=>{o(),e?(c==null||c.observe(e),l==null||l.observe(document.body,{childList:!0,subtree:!0})):(c==null||c.disconnect(),l==null||l.disconnect())},[e]),s}function Kf(e){const t=xo(e);return io(e,t)}const $s=[];function Gf(e){const t=i.useRef(e),r=Kt(s=>e?s&&s!==$s&&e&&t.current&&e.parentNode===t.current.parentNode?s:Tn(e):$s,[e]);return i.useEffect(()=>{t.current=e},[e]),r}function Yf(e){const[t,r]=i.useState(null),s=i.useRef(e),a=i.useCallback(o=>{const l=Zn(o.target);l&&r(c=>c?(c.set(l,pr(l)),new Map(c)):null)},[]);return i.useEffect(()=>{const o=s.current;if(e!==o){l(o);const c=e.map(d=>{const u=Zn(d);return u?(u.addEventListener("scroll",a,{passive:!0}),[u,pr(u)]):null}).filter(d=>d!=null);r(c.length?new Map(c):null),s.current=e}return()=>{l(e),l(o)};function l(c){c.forEach(d=>{const u=Zn(d);u==null||u.removeEventListener("scroll",a)})}},[a,e]),i.useMemo(()=>e.length?t?Array.from(t.values()).reduce((o,l)=>kt(o,l),Oe):mo(e):Oe,[e,t])}function Os(e,t){t===void 0&&(t=[]);const r=i.useRef(null);return i.useEffect(()=>{r.current=null},t),i.useEffect(()=>{const s=e!==Oe;s&&!r.current&&(r.current=e),!s&&r.current&&(r.current=null)},[e]),r.current?zt(e,r.current):Oe}function qf(e){i.useEffect(()=>{if(!Rn)return;const t=e.map(r=>{let{sensor:s}=r;return s.setup==null?void 0:s.setup()});return()=>{for(const r of t)r==null||r()}},e.map(t=>{let{sensor:r}=t;return r}))}function Jf(e,t){return i.useMemo(()=>e.reduce((r,s)=>{let{eventName:a,handler:o}=s;return r[a]=l=>{o(l,t)},r},{}),[e,t])}function go(e){return i.useMemo(()=>e?yf(e):null,[e])}const Bs=[];function Xf(e,t){t===void 0&&(t=Rt);const[r]=e,s=go(r?Ce(r):null),[a,o]=i.useState(Bs);function l(){o(()=>e.length?e.map(d=>fo(d)?s:new zr(t(d),d)):Bs)}const c=Pn({callback:l});return Ue(()=>{c==null||c.disconnect(),l(),e.forEach(d=>c==null?void 0:c.observe(d))},[e]),a}function Qf(e){if(!e)return null;if(e.children.length>1)return e;const t=e.children[0];return Ut(t)?t:e}function Zf(e){let{measure:t}=e;const[r,s]=i.useState(null),a=i.useCallback(u=>{for(const{target:f}of u)if(Ut(f)){s(p=>{const m=t(f);return p?{...p,width:m.width,height:m.height}:m});break}},[t]),o=Pn({callback:a}),l=i.useCallback(u=>{const f=Qf(u);o==null||o.disconnect(),f&&(o==null||o.observe(f)),s(f?t(f):null)},[t,o]),[c,d]=jn(l);return i.useMemo(()=>({nodeRef:c,rect:r,setRef:d}),[r,c,d])}const ep=[{sensor:Vr,options:{}},{sensor:Hr,options:{}}],tp={current:{}},hn={draggable:{measure:Ds},droppable:{measure:Ds,strategy:Wt.WhileDragging,frequency:hr.Optimized},dragOverlay:{measure:Rt}};class Ot extends Map{get(t){var r;return t!=null&&(r=super.get(t))!=null?r:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(t=>{let{disabled:r}=t;return!r})}getNodeFor(t){var r,s;return(r=(s=this.get(t))==null?void 0:s.node.current)!=null?r:void 0}}const np={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new Ot,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:kn},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:hn,measureDroppableContainers:kn,windowRect:null,measuringScheduled:!1},rp={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:kn,draggableNodes:new Map,over:null,measureDroppableContainers:kn},Dn=i.createContext(rp),bo=i.createContext(np);function sp(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new Ot}}}function ap(e,t){switch(t.type){case me.DragStart:return{...e,draggable:{...e.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case me.DragMove:return e.draggable.active==null?e:{...e,draggable:{...e.draggable,translate:{x:t.coordinates.x-e.draggable.initialCoordinates.x,y:t.coordinates.y-e.draggable.initialCoordinates.y}}};case me.DragEnd:case me.DragCancel:return{...e,draggable:{...e.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case me.RegisterDroppable:{const{element:r}=t,{id:s}=r,a=new Ot(e.droppable.containers);return a.set(s,r),{...e,droppable:{...e.droppable,containers:a}}}case me.SetDroppableDisabled:{const{id:r,key:s,disabled:a}=t,o=e.droppable.containers.get(r);if(!o||s!==o.key)return e;const l=new Ot(e.droppable.containers);return l.set(r,{...o,disabled:a}),{...e,droppable:{...e.droppable,containers:l}}}case me.UnregisterDroppable:{const{id:r,key:s}=t,a=e.droppable.containers.get(r);if(!a||s!==a.key)return e;const o=new Ot(e.droppable.containers);return o.delete(r),{...e,droppable:{...e.droppable,containers:o}}}default:return e}}function op(e){let{disabled:t}=e;const{active:r,activatorEvent:s,draggableNodes:a}=i.useContext(Dn),o=ur(s),l=ur(r==null?void 0:r.id);return i.useEffect(()=>{if(!t&&!s&&o&&l!=null){if(!_r(o)||document.activeElement===o.target)return;const c=a.get(l);if(!c)return;const{activatorNode:d,node:u}=c;if(!d.current&&!u.current)return;requestAnimationFrame(()=>{for(const f of[d.current,u.current]){if(!f)continue;const p=Xu(f);if(p){p.focus();break}}})}},[s,t,a,l,o]),null}function ip(e,t){let{transform:r,...s}=t;return e!=null&&e.length?e.reduce((a,o)=>o({transform:a,...s}),r):r}function lp(e){return i.useMemo(()=>({draggable:{...hn.draggable,...e==null?void 0:e.draggable},droppable:{...hn.droppable,...e==null?void 0:e.droppable},dragOverlay:{...hn.dragOverlay,...e==null?void 0:e.dragOverlay}}),[e==null?void 0:e.draggable,e==null?void 0:e.droppable,e==null?void 0:e.dragOverlay])}function cp(e){let{activeNode:t,measure:r,initialRect:s,config:a=!0}=e;const o=i.useRef(!1),{x:l,y:c}=typeof a=="boolean"?{x:a,y:a}:a;Ue(()=>{if(!l&&!c||!t){o.current=!1;return}if(o.current||!s)return;const u=t==null?void 0:t.node.current;if(!u||u.isConnected===!1)return;const f=r(u),p=io(f,s);if(l||(p.x=0),c||(p.y=0),o.current=!0,Math.abs(p.x)>0||Math.abs(p.y)>0){const m=lo(u);m&&m.scrollBy({top:p.y,left:p.x})}},[t,l,c,s,r])}const vo=i.createContext({...Oe,scaleX:1,scaleY:1});var rt;(function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initializing=1]="Initializing",e[e.Initialized=2]="Initialized"})(rt||(rt={}));const dp=i.memo(function(t){var r,s,a,o;let{id:l,accessibility:c,autoScroll:d=!0,children:u,sensors:f=ep,collisionDetection:p=pf,measuring:m,modifiers:h,...v}=t;const g=i.useReducer(ap,void 0,sp),[y,j]=g,[b,x]=rf(),[w,k]=i.useState(rt.Uninitialized),C=w===rt.Initialized,{draggable:{active:N,nodes:E,translate:R},droppable:{containers:S}}=y,D=N!=null?E.get(N):null,P=i.useRef({initial:null,translated:null}),I=i.useMemo(()=>{var fe;return N!=null?{id:N,data:(fe=D==null?void 0:D.data)!=null?fe:tp,rect:P}:null},[N,D]),O=i.useRef(null),[U,J]=i.useState(null),[T,L]=i.useState(null),W=_t(v,Object.values(v)),B=Gt("DndDescribedBy",l),Y=i.useMemo(()=>S.getEnabled(),[S]),A=lp(m),{droppableRects:F,measureDroppableContainers:M,measuringScheduled:X}=Hf(Y,{dragging:C,dependencies:[R.x,R.y],config:A.droppable}),Z=_f(E,N),_=i.useMemo(()=>T?fr(T):null,[T]),$=et(),Q=Wf(Z,A.draggable.measure);cp({activeNode:N!=null?E.get(N):null,config:$.layoutShiftCompensation,initialRect:Q,measure:A.draggable.measure});const H=Is(Z,A.draggable.measure,Q),G=Is(Z?Z.parentElement:null),ae=i.useRef({activatorEvent:null,active:null,activeNode:Z,collisionRect:null,collisions:null,droppableRects:F,draggableNodes:E,draggingNode:null,draggingNodeRect:null,droppableContainers:S,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),z=S.getNodeFor((r=ae.current.over)==null?void 0:r.id),oe=Zf({measure:A.dragOverlay.measure}),pe=(s=oe.nodeRef.current)!=null?s:Z,ne=C?(a=oe.rect)!=null?a:H:null,le=!!(oe.nodeRef.current&&oe.rect),je=Kf(le?null:H),ie=go(pe?Ce(pe):null),te=Gf(C?z??Z:null),Be=Xf(te),ke=ip(h,{transform:{x:R.x-je.x,y:R.y-je.y,scaleX:1,scaleY:1},activatorEvent:T,active:I,activeNodeRect:H,containerNodeRect:G,draggingNodeRect:ne,over:ae.current.over,overlayNodeRect:oe.rect,scrollableAncestors:te,scrollableAncestorRects:Be,windowRect:ie}),K=_?kt(_,R):null,qe=Yf(te),vt=Os(qe),Tt=Os(qe,[H]),Se=kt(ke,vt),_e=ne?xf(ne,ke):null,Ae=I&&_e?p({active:I,collisionRect:_e,droppableRects:F,droppableContainers:Y,pointerCoordinates:K}):null,yt=oo(Ae,"id"),[be,Je]=i.useState(null),Ee=le?ke:kt(ke,Tt),Re=mf(Ee,(o=be==null?void 0:be.rect)!=null?o:null,H),Xe=i.useRef(null),Qe=i.useCallback((fe,ve)=>{let{sensor:he,options:q}=ve;if(O.current==null)return;const se=E.get(O.current);if(!se)return;const ce=fe.nativeEvent,ue=new he({active:O.current,activeNode:se,event:ce,options:q,context:ae,onAbort(de){if(!E.get(de))return;const{onDragAbort:xe}=W.current,Le={id:de};xe==null||xe(Le),b({type:"onDragAbort",event:Le})},onPending(de,Fe,xe,Le){if(!E.get(de))return;const{onDragPending:dt}=W.current,Ie={id:de,constraint:Fe,initialCoordinates:xe,offset:Le};dt==null||dt(Ie),b({type:"onDragPending",event:Ie})},onStart(de){const Fe=O.current;if(Fe==null)return;const xe=E.get(Fe);if(!xe)return;const{onDragStart:Le}=W.current,ct={activatorEvent:ce,active:{id:Fe,data:xe.data,rect:P}};Ft.unstable_batchedUpdates(()=>{Le==null||Le(ct),k(rt.Initializing),j({type:me.DragStart,initialCoordinates:de,active:Fe}),b({type:"onDragStart",event:ct}),J(Xe.current),L(ce)})},onMove(de){j({type:me.DragMove,coordinates:de})},onEnd:ye(me.DragEnd),onCancel:ye(me.DragCancel)});Xe.current=ue;function ye(de){return async function(){const{active:xe,collisions:Le,over:ct,scrollAdjustedTranslate:dt}=ae.current;let Ie=null;if(xe&&dt){const{cancelDrop:Pe}=W.current;Ie={activatorEvent:ce,active:xe,collisions:Le,delta:dt,over:ct},de===me.DragEnd&&typeof Pe=="function"&&await Promise.resolve(Pe(Ie))&&(de=me.DragCancel)}O.current=null,Ft.unstable_batchedUpdates(()=>{j({type:de}),k(rt.Uninitialized),Je(null),J(null),L(null),Xe.current=null;const Pe=de===me.DragEnd?"onDragEnd":"onDragCancel";if(Ie){const Pt=W.current[Pe];Pt==null||Pt(Ie),b({type:Pe,event:Ie})}})}}},[E]),Te=i.useCallback((fe,ve)=>(he,q)=>{const se=he.nativeEvent,ce=E.get(q);if(O.current!==null||!ce||se.dndKit||se.defaultPrevented)return;const ue={active:ce};fe(he,ve.options,ue)===!0&&(se.dndKit={capturedBy:ve.sensor},O.current=q,Qe(he,ve))},[E,Qe]),Ze=zf(f,Te);qf(f),Ue(()=>{H&&w===rt.Initializing&&k(rt.Initialized)},[H,w]),i.useEffect(()=>{const{onDragMove:fe}=W.current,{active:ve,activatorEvent:he,collisions:q,over:se}=ae.current;if(!ve||!he)return;const ce={active:ve,activatorEvent:he,collisions:q,delta:{x:Se.x,y:Se.y},over:se};Ft.unstable_batchedUpdates(()=>{fe==null||fe(ce),b({type:"onDragMove",event:ce})})},[Se.x,Se.y]),i.useEffect(()=>{const{active:fe,activatorEvent:ve,collisions:he,droppableContainers:q,scrollAdjustedTranslate:se}=ae.current;if(!fe||O.current==null||!ve||!se)return;const{onDragOver:ce}=W.current,ue=q.get(yt),ye=ue&&ue.rect.current?{id:ue.id,rect:ue.rect.current,data:ue.data,disabled:ue.disabled}:null,de={active:fe,activatorEvent:ve,collisions:he,delta:{x:se.x,y:se.y},over:ye};Ft.unstable_batchedUpdates(()=>{Je(ye),ce==null||ce(de),b({type:"onDragOver",event:de})})},[yt]),Ue(()=>{ae.current={activatorEvent:T,active:I,activeNode:Z,collisionRect:_e,collisions:Ae,droppableRects:F,draggableNodes:E,draggingNode:pe,draggingNodeRect:ne,droppableContainers:S,over:be,scrollableAncestors:te,scrollAdjustedTranslate:Se},P.current={initial:ne,translated:_e}},[I,Z,Ae,_e,E,pe,ne,F,S,be,te,Se]),$f({...$,delta:R,draggingRect:_e,pointerCoordinates:K,scrollableAncestors:te,scrollableAncestorRects:Be});const we=i.useMemo(()=>({active:I,activeNode:Z,activeNodeRect:H,activatorEvent:T,collisions:Ae,containerNodeRect:G,dragOverlay:oe,draggableNodes:E,droppableContainers:S,droppableRects:F,over:be,measureDroppableContainers:M,scrollableAncestors:te,scrollableAncestorRects:Be,measuringConfiguration:A,measuringScheduled:X,windowRect:ie}),[I,Z,H,T,Ae,G,oe,E,S,F,be,M,te,Be,A,X,ie]),lt=i.useMemo(()=>({activatorEvent:T,activators:Ze,active:I,activeNodeRect:H,ariaDescribedById:{draggable:B},dispatch:j,draggableNodes:E,over:be,measureDroppableContainers:M}),[T,Ze,I,H,j,B,E,be,M]);return Ne.createElement(ro.Provider,{value:x},Ne.createElement(Dn.Provider,{value:lt},Ne.createElement(bo.Provider,{value:we},Ne.createElement(vo.Provider,{value:Re},u)),Ne.createElement(op,{disabled:(c==null?void 0:c.restoreFocus)===!1})),Ne.createElement(of,{...c,hiddenTextDescribedById:B}));function et(){const fe=(U==null?void 0:U.autoScrollEnabled)===!1,ve=typeof d=="object"?d.enabled===!1:d===!1,he=C&&!fe&&!ve;return typeof d=="object"?{...d,enabled:he}:{enabled:he}}}),up=i.createContext(null),_s="button",fp="Draggable";function pp(e){let{id:t,data:r,disabled:s=!1,attributes:a}=e;const o=Gt(fp),{activators:l,activatorEvent:c,active:d,activeNodeRect:u,ariaDescribedById:f,draggableNodes:p,over:m}=i.useContext(Dn),{role:h=_s,roleDescription:v="draggable",tabIndex:g=0}=a??{},y=(d==null?void 0:d.id)===t,j=i.useContext(y?vo:up),[b,x]=jn(),[w,k]=jn(),C=Jf(l,t),N=_t(r);Ue(()=>(p.set(t,{id:t,key:o,node:b,activatorNode:w,data:N}),()=>{const R=p.get(t);R&&R.key===o&&p.delete(t)}),[p,t]);const E=i.useMemo(()=>({role:h,tabIndex:g,"aria-disabled":s,"aria-pressed":y&&h===_s?!0:void 0,"aria-roledescription":v,"aria-describedby":f.draggable}),[s,h,g,y,v,f.draggable]);return{active:d,activatorEvent:c,activeNodeRect:u,attributes:E,isDragging:y,listeners:s?void 0:C,node:b,over:m,setNodeRef:x,setActivatorNodeRef:k,transform:j}}function mp(){return i.useContext(bo)}const hp="Droppable",xp={timeout:25};function gp(e){let{data:t,disabled:r=!1,id:s,resizeObserverConfig:a}=e;const o=Gt(hp),{active:l,dispatch:c,over:d,measureDroppableContainers:u}=i.useContext(Dn),f=i.useRef({disabled:r}),p=i.useRef(!1),m=i.useRef(null),h=i.useRef(null),{disabled:v,updateMeasurementsFor:g,timeout:y}={...xp,...a},j=_t(g??s),b=i.useCallback(()=>{if(!p.current){p.current=!0;return}h.current!=null&&clearTimeout(h.current),h.current=setTimeout(()=>{u(Array.isArray(j.current)?j.current:[j.current]),h.current=null},y)},[y]),x=Pn({callback:b,disabled:v||!l}),w=i.useCallback((E,R)=>{x&&(R&&(x.unobserve(R),p.current=!1),E&&x.observe(E))},[x]),[k,C]=jn(w),N=_t(t);return i.useEffect(()=>{!x||!k.current||(x.disconnect(),p.current=!1,x.observe(k.current))},[k,x]),i.useEffect(()=>(c({type:me.RegisterDroppable,element:{id:s,key:o,disabled:r,node:k,rect:m,data:N}}),()=>c({type:me.UnregisterDroppable,key:o,id:s})),[s]),i.useEffect(()=>{r!==f.current.disabled&&(c({type:me.SetDroppableDisabled,id:s,key:o,disabled:r}),f.current.disabled=r)},[s,o,r,c]),{active:l,rect:m,isOver:(d==null?void 0:d.id)===s,node:k,over:d,setNodeRef:C}}function Ur(e,t,r){const s=e.slice();return s.splice(r<0?s.length+r:r,0,s.splice(t,1)[0]),s}function bp(e,t){return e.reduce((r,s,a)=>{const o=t.get(s);return o&&(r[a]=o),r},Array(e.length))}function rn(e){return e!==null&&e>=0}function vp(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}function yp(e){return typeof e=="boolean"?{draggable:e,droppable:e}:e}const yo=e=>{let{rects:t,activeIndex:r,overIndex:s,index:a}=e;const o=Ur(t,s,r),l=t[a],c=o[a];return!c||!l?null:{x:c.left-l.left,y:c.top-l.top,scaleX:c.width/l.width,scaleY:c.height/l.height}},sn={scaleX:1,scaleY:1},wp=e=>{var t;let{activeIndex:r,activeNodeRect:s,index:a,rects:o,overIndex:l}=e;const c=(t=o[r])!=null?t:s;if(!c)return null;if(a===r){const u=o[l];return u?{x:0,y:r<l?u.top+u.height-(c.top+c.height):u.top-c.top,...sn}:null}const d=jp(o,a,r);return a>r&&a<=l?{x:0,y:-c.height-d,...sn}:a<r&&a>=l?{x:0,y:c.height+d,...sn}:{x:0,y:0,...sn}};function jp(e,t,r){const s=e[t],a=e[t-1],o=e[t+1];return s?r<t?a?s.top-(a.top+a.height):o?o.top-(s.top+s.height):0:o?o.top-(s.top+s.height):a?s.top-(a.top+a.height):0:0}const wo="Sortable",jo=Ne.createContext({activeIndex:-1,containerId:wo,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:yo,disabled:{draggable:!1,droppable:!1}});function kp(e){let{children:t,id:r,items:s,strategy:a=yo,disabled:o=!1}=e;const{active:l,dragOverlay:c,droppableRects:d,over:u,measureDroppableContainers:f}=mp(),p=Gt(wo,r),m=c.rect!==null,h=i.useMemo(()=>s.map(C=>typeof C=="object"&&"id"in C?C.id:C),[s]),v=l!=null,g=l?h.indexOf(l.id):-1,y=u?h.indexOf(u.id):-1,j=i.useRef(h),b=!vp(h,j.current),x=y!==-1&&g===-1||b,w=yp(o);Ue(()=>{b&&v&&f(h)},[b,h,v,f]),i.useEffect(()=>{j.current=h},[h]);const k=i.useMemo(()=>({activeIndex:g,containerId:p,disabled:w,disableTransforms:x,items:h,overIndex:y,useDragOverlay:m,sortedRects:bp(h,d),strategy:a}),[g,p,w.draggable,w.droppable,x,h,y,d,m,a]);return Ne.createElement(jo.Provider,{value:k},t)}const Np=e=>{let{id:t,items:r,activeIndex:s,overIndex:a}=e;return Ur(r,s,a).indexOf(t)},Cp=e=>{let{containerId:t,isSorting:r,wasDragging:s,index:a,items:o,newIndex:l,previousItems:c,previousContainerId:d,transition:u}=e;return!u||!s||c!==o&&a===l?!1:r?!0:l!==a&&t===d},Sp={duration:200,easing:"ease"},ko="transform",Ep=Ht.Transition.toString({property:ko,duration:0,easing:"linear"}),Rp={roleDescription:"sortable"};function Tp(e){let{disabled:t,index:r,node:s,rect:a}=e;const[o,l]=i.useState(null),c=i.useRef(r);return Ue(()=>{if(!t&&r!==c.current&&s.current){const d=a.current;if(d){const u=Rt(s.current,{ignoreTransform:!0}),f={x:d.left-u.left,y:d.top-u.top,scaleX:d.width/u.width,scaleY:d.height/u.height};(f.x||f.y)&&l(f)}}r!==c.current&&(c.current=r)},[t,r,s,a]),i.useEffect(()=>{o&&l(null)},[o]),o}function Pp(e){let{animateLayoutChanges:t=Cp,attributes:r,disabled:s,data:a,getNewIndex:o=Np,id:l,strategy:c,resizeObserverConfig:d,transition:u=Sp}=e;const{items:f,containerId:p,activeIndex:m,disabled:h,disableTransforms:v,sortedRects:g,overIndex:y,useDragOverlay:j,strategy:b}=i.useContext(jo),x=Dp(s,h),w=f.indexOf(l),k=i.useMemo(()=>({sortable:{containerId:p,index:w,items:f},...a}),[p,a,w,f]),C=i.useMemo(()=>f.slice(f.indexOf(l)),[f,l]),{rect:N,node:E,isOver:R,setNodeRef:S}=gp({id:l,data:k,disabled:x.droppable,resizeObserverConfig:{updateMeasurementsFor:C,...d}}),{active:D,activatorEvent:P,activeNodeRect:I,attributes:O,setNodeRef:U,listeners:J,isDragging:T,over:L,setActivatorNodeRef:W,transform:B}=pp({id:l,data:k,attributes:{...Rp,...r},disabled:x.draggable}),Y=Gu(S,U),A=!!D,F=A&&!v&&rn(m)&&rn(y),M=!j&&T,X=M&&F?B:null,_=F?X??(c??b)({rects:g,activeNodeRect:I,activeIndex:m,overIndex:y,index:w}):null,$=rn(m)&&rn(y)?o({id:l,items:f,activeIndex:m,overIndex:y}):w,Q=D==null?void 0:D.id,H=i.useRef({activeId:Q,items:f,newIndex:$,containerId:p}),G=f!==H.current.items,ae=t({active:D,containerId:p,isDragging:T,isSorting:A,id:l,index:w,items:f,newIndex:H.current.newIndex,previousItems:H.current.items,previousContainerId:H.current.containerId,transition:u,wasDragging:H.current.activeId!=null}),z=Tp({disabled:!ae,index:w,node:E,rect:N});return i.useEffect(()=>{A&&H.current.newIndex!==$&&(H.current.newIndex=$),p!==H.current.containerId&&(H.current.containerId=p),f!==H.current.items&&(H.current.items=f)},[A,$,p,f]),i.useEffect(()=>{if(Q===H.current.activeId)return;if(Q!=null&&H.current.activeId==null){H.current.activeId=Q;return}const pe=setTimeout(()=>{H.current.activeId=Q},50);return()=>clearTimeout(pe)},[Q]),{active:D,activeIndex:m,attributes:O,data:k,rect:N,index:w,newIndex:$,items:f,isOver:R,isSorting:A,isDragging:T,listeners:J,node:E,overIndex:y,over:L,setNodeRef:Y,setActivatorNodeRef:W,setDroppableNodeRef:S,setDraggableNodeRef:U,transform:z??_,transition:oe()};function oe(){if(z||G&&H.current.newIndex===w)return Ep;if(!(M&&!_r(P)||!u)&&(A||ae))return Ht.Transition.toString({...u,property:ko})}}function Dp(e,t){var r,s;return typeof e=="boolean"?{draggable:e,droppable:!1}:{draggable:(r=e==null?void 0:e.draggable)!=null?r:t.draggable,droppable:(s=e==null?void 0:e.droppable)!=null?s:t.droppable}}function Cn(e){if(!e)return!1;const t=e.data.current;return!!(t&&"sortable"in t&&typeof t.sortable=="object"&&"containerId"in t.sortable&&"items"in t.sortable&&"index"in t.sortable)}const Ap=[re.Down,re.Right,re.Up,re.Left],Fp=(e,t)=>{let{context:{active:r,collisionRect:s,droppableRects:a,droppableContainers:o,over:l,scrollableAncestors:c}}=t;if(Ap.includes(e.code)){if(e.preventDefault(),!r||!s)return;const d=[];o.getEnabled().forEach(p=>{if(!p||p!=null&&p.disabled)return;const m=a.get(p.id);if(m)switch(e.code){case re.Down:s.top<m.top&&d.push(p);break;case re.Up:s.top>m.top&&d.push(p);break;case re.Left:s.left>m.left&&d.push(p);break;case re.Right:s.left<m.left&&d.push(p);break}});const u=uf({collisionRect:s,droppableRects:a,droppableContainers:d});let f=oo(u,"id");if(f===(l==null?void 0:l.id)&&u.length>1&&(f=u[1].id),f!=null){const p=o.get(r.id),m=o.get(f),h=m?a.get(m.id):null,v=m==null?void 0:m.node.current;if(v&&h&&p&&m){const y=Tn(v).some((C,N)=>c[N]!==C),j=No(p,m),b=Lp(p,m),x=y||!j?{x:0,y:0}:{x:b?s.width-h.width:0,y:b?s.height-h.height:0},w={x:h.left,y:h.top};return x.x&&x.y?w:zt(w,x)}}}};function No(e,t){return!Cn(e)||!Cn(t)?!1:e.data.current.sortable.containerId===t.data.current.sortable.containerId}function Lp(e,t){return!Cn(e)||!Cn(t)||!No(e,t)?!1:e.data.current.sortable.index<t.data.current.sortable.index}function ot(e,t=Date.now()){if(!e)return"unknown";const r=Date.parse(e);if(Number.isNaN(r))return e;const s=Math.round((t-r)/1e3);if(s<60)return"just now";const a=Math.round(s/60);if(a<60)return`${a}m ago`;const o=Math.round(a/60);return o<24?`${o}h ago`:`${Math.round(o/24)}d ago`}function Co({title:e,filePath:t}){return n.jsxs("div",{className:"px-3 py-2 border-b border-[var(--border-subtle)]",children:[n.jsx("div",{className:"text-sm font-medium text-[var(--text-primary)] break-words",children:e}),n.jsx("div",{"data-testid":"plan-expanded-header-file-path",className:"mt-0.5 text-xs font-mono text-[var(--text-dim)] break-all",children:t})]})}function Yt(){const[e,t]=i.useState(()=>Date.now());return i.useEffect(()=>{const r=setInterval(()=>t(Date.now()),1e3);return()=>clearInterval(r)},[]),e}function So(e){return{dead:e.sessionAlive===!1}}function Mp({claim:e,staleFetch:t=!1}){const r=Yt(),{dead:s}=So(e),a=e.claimedBy.agentProvider??"agent",o=s?" (inactive)":"",l=ot(e.claimedBy.startedAt,r),c=e.source==="local"?`● this session · started ${l}`:e.source==="same-machine"?`claimed by ${a}@${e.claimedBy.machine} (same machine) · ${l}`:`claimed by ${a}@${e.claimedBy.machine} · ${l}`;return n.jsxs("span",{"data-testid":`plan-row-claim-badge-${e.slug}`,title:`Source: ${e.source}${o}${t?" (data may be stale)":""}`,className:"text-[10px] whitespace-nowrap px-1.5 py-0.5 rounded border",style:{borderColor:"var(--border-subtle)",color:s?"var(--text-muted)":"var(--text-dim)"},children:[c,o]})}function Ip(){const[e,t]=i.useState(!1),[r,s]=i.useState(null);return{updatePlan:i.useCallback(async(o,l)=>{t(!0),s(null);try{const c=await fetch(`/api/plans/${o}`,{method:"PUT",headers:{"content-type":"application/json"},body:JSON.stringify(l)});if(!c.ok){const d=await c.json().catch(()=>({}));throw new Error(d.error??`HTTP ${c.status}`)}}catch(c){const d=c instanceof Error?c.message:"Failed to save plan";throw s(d),c instanceof Error?c:new Error(d)}finally{t(!1)}},[]),saving:e,error:r}}function $p({slug:e,onClose:t}){return n.jsx("div",{className:"px-3 py-2 border-t border-[var(--border-subtle)]",children:n.jsx(Sn,{chatName:`edit-plan-${e}`,slashCommand:`/codeyam-edit-plan ${e}`,height:360,onClose:t})})}function Op({titleDraft:e,bodyDraft:t,saving:r,error:s,onTitleChange:a,onBodyChange:o,onSave:l,onCancel:c}){const d=Math.min(20,Math.max(8,t.split(`
|
|
14
|
+
`).length));return n.jsxs("div",{className:"border-t border-[var(--border-subtle)] px-3 py-2 flex flex-col gap-2",children:[n.jsx("input",{type:"text",value:e,onChange:u=>a(u.target.value),"aria-label":"Plan title",className:"w-full px-2 py-1 text-sm rounded border border-[var(--border-subtle)] bg-[var(--bg-input,transparent)] text-[var(--text-primary)]"}),n.jsx("textarea",{value:t,onChange:u=>o(u.target.value),"aria-label":"Plan body",rows:d,className:"w-full px-2 py-1 text-xs rounded border border-[var(--border-subtle)] bg-[var(--bg-input,transparent)] text-[var(--text-primary)] font-mono resize-y"}),s&&n.jsx("p",{className:"text-xs text-[var(--accent-red)]",role:"alert",children:s}),n.jsxs("div",{className:"flex gap-2 justify-end",children:[n.jsx("button",{type:"button",onClick:c,disabled:r,className:"px-2.5 py-1 text-xs rounded border border-[var(--border-default)] bg-transparent text-[var(--text-muted)] hover:text-[var(--text-primary)] cursor-pointer disabled:opacity-60",children:"Cancel"}),n.jsx("button",{type:"button",onClick:l,disabled:r,className:"px-2.5 py-1 text-xs rounded border border-[var(--accent-active)] bg-[var(--accent-active)] text-black hover:bg-[var(--accent-active)]/90 cursor-pointer disabled:opacity-60",children:r?"Saving…":"Save"})]})]})}function Bp({onClick:e}){return n.jsx("button",{type:"button",onClick:e,className:"px-2.5 py-1 text-xs rounded border border-[var(--border-default)] bg-transparent text-[var(--text-muted)] hover:text-[var(--text-primary)] cursor-pointer",children:"Edit"})}function _p({providerLabel:e,onClick:t}){return n.jsxs("button",{type:"button",onClick:t,className:"flex items-center gap-1.5 px-2.5 py-1 rounded border text-xs cursor-pointer transition-colors border-[var(--border-default)] bg-transparent text-[var(--text-muted)] hover:text-[var(--text-primary)] hover:border-[var(--accent-active)]/40",title:`Open a chat with ${e} seeded with this plan's contents`,children:[n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),"Edit with ",e]})}function zp({dep:e}){const t=e.title===null,r=e.satisfied?"completed":t?"missing":"blocked",s=e.satisfied?{borderColor:"var(--border-subtle)",color:"var(--text-dim)"}:{borderColor:"var(--accent-warn, #c08a2c)",color:"var(--accent-warn, #c08a2c)"};return n.jsxs("li",{"data-testid":`plan-row-dep-${e.slug}`,className:"text-sm flex items-center gap-2",children:[n.jsx("span",{className:"text-[10px] uppercase tracking-wide px-1.5 py-0.5 rounded border whitespace-nowrap",style:s,children:r}),n.jsx("span",{className:e.satisfied?"text-[var(--text-dim)] truncate":"text-[var(--text-primary)] truncate",children:t?`missing: ${e.slug}`:e.title})]})}function Hp({dependencies:e}){return n.jsxs("div",{"data-testid":"plan-row-deps",className:"px-3 py-2 border-b border-[var(--border-subtle)]",children:[n.jsx("p",{className:"text-[10px] uppercase tracking-wide text-[var(--text-dim)] mb-1.5",children:"Depends on"}),n.jsx("ul",{className:"flex flex-col gap-1",children:e.map(t=>n.jsx(zp,{dep:t},t.slug))})]})}function Wp({title:e,filePath:t,body:r,providerLabel:s,onEdit:a,onChat:o,dependencies:l}){return n.jsxs("div",{className:"border-t border-[var(--border-subtle)]",children:[n.jsx(Co,{title:e,filePath:t}),l&&l.length>0&&n.jsx(Hp,{dependencies:l}),n.jsx("div",{className:"px-3 py-2 max-h-[40vh] overflow-y-auto",children:n.jsx(mt,{variant:"compact",children:r})}),n.jsxs("div",{className:"flex gap-2 justify-end px-3 py-2 border-t border-[var(--border-subtle)]",children:[n.jsx(Bp,{onClick:a}),n.jsx(_p,{providerLabel:s,onClick:o})]})]})}function Vp({plan:e,dependencies:t}){const[r,s]=i.useState("view"),[a,o]=i.useState(e.title),[l,c]=i.useState(e.body),{updatePlan:d,saving:u,error:f}=Ip(),{config:p}=it(),m=Ve(p==null?void 0:p.provider);return i.useEffect(()=>{o(e.title),c(e.body),s("view")},[e.slug]),r==="chat"?n.jsx($p,{slug:e.slug,onClose:()=>s("view")}):r==="edit"?n.jsx(Op,{titleDraft:a,bodyDraft:l,saving:u,error:f,onTitleChange:o,onBodyChange:c,onSave:async()=>{try{await d(e.slug,{title:a,body:l}),s("view")}catch{}},onCancel:()=>{o(e.title),c(e.body),s("view")}}):n.jsx(Wp,{title:e.title,filePath:e.filePath,body:e.body,providerLabel:m,onEdit:()=>s("edit"),onChat:()=>s("chat"),dependencies:t})}const Eo="Building is in progress, please wait for it to complete before starting a new build session.";function Up({slug:e,onRun:t,launching:r=!1,blocked:s=!1,onBlockedClick:a}){const o=f=>{if(f.stopPropagation(),!r){if(s){a==null||a();return}t(e)}},l="text-[10px] uppercase tracking-wide px-2 py-0.5 rounded border border-[var(--accent)] text-[var(--accent)] cursor-pointer hover:bg-[var(--accent)] hover:text-[var(--surface-bg)] disabled:opacity-60 disabled:cursor-not-allowed transition",c=" opacity-60 cursor-not-allowed hover:bg-transparent hover:text-[var(--accent)]",d=r,u=s&&!r;return n.jsx("button",{type:"button",onClick:o,disabled:d,"data-testid":`plan-run-${e}`,title:u?Eo:void 0,className:l+(u?c:""),children:r?"Launching…":"Run"})}function Ro({plan:e,expanded:t,onToggle:r,onRun:s,launching:a=!1,blocked:o=!1,onBlockedClick:l,position:c,dragHandleRef:d,dragHandleAttributes:u,dragHandleListeners:f,sortableRef:p,sortableStyle:m,isDragging:h=!1,unsatisfiedDepCount:v=0,unsatisfiedDepTooltip:g,dependencies:y,claim:j,staleFetch:b=!1,expandedBodyVariant:x="full"}){const w=k=>{(k.key==="Enter"||k.key===" ")&&(k.preventDefault(),r())};return n.jsxs("li",{ref:p,style:m,className:`border border-[var(--border-subtle)] rounded-lg bg-[var(--bg-surface,transparent)] ${h?"opacity-60 shadow-lg":""}`,children:[n.jsxs("div",{role:"button",tabIndex:0,onClick:r,onKeyDown:w,className:"w-full text-left px-3 py-2 flex items-center justify-between gap-3 bg-transparent cursor-pointer",children:[d&&n.jsx("span",{ref:d,"data-testid":`plan-drag-${e.slug}`,"aria-label":"Reorder plan",...u??{},...f??{},onClick:k=>k.stopPropagation(),className:"cursor-grab active:cursor-grabbing text-[var(--text-dim)] select-none leading-none px-1 -ml-1",children:"⋮⋮"}),typeof c=="number"&&n.jsxs("span",{className:"text-xs text-[var(--text-dim)] tabular-nums min-w-[1.25rem]",children:[c,"."]}),n.jsx("span",{className:"flex-1 min-w-0 truncate text-sm text-[var(--text-primary)]",children:e.title}),s&&n.jsx(Up,{slug:e.slug,onRun:s,launching:a,blocked:o,onBlockedClick:l}),n.jsx("span",{className:"text-[10px] uppercase tracking-wide px-1.5 py-0.5 rounded border border-[var(--border-subtle)] text-[var(--text-dim)]",children:e.mode}),v>0&&n.jsxs("span",{"data-testid":`plan-row-blocked-${e.slug}`,title:g,className:"text-[10px] whitespace-nowrap px-1.5 py-0.5 rounded border border-[var(--border-subtle)] text-[var(--text-dim)] inline-flex items-center gap-1",children:["🔒 blocked · ",v," dep",v===1?"":"s"]}),j&&n.jsx(Mp,{claim:j,staleFetch:b}),n.jsx("span",{className:"text-[10px] text-[var(--text-dim)] whitespace-nowrap",children:ot(e.createdAt)})]}),t&&(x==="view"?n.jsxs("div",{className:"border-t border-[var(--border-subtle)]",children:[n.jsx(Co,{title:e.title,filePath:e.filePath}),n.jsx("div",{className:"px-3 py-2 max-h-[40vh] overflow-y-auto",children:n.jsx(mt,{variant:"compact",children:e.body})})]}):n.jsx(Vp,{plan:e,dependencies:y}))]})}function Kp({plan:e,position:t,expanded:r,onToggle:s,onRun:a,launching:o,blocked:l,onBlockedClick:c,draggable:d,unsatisfiedDepCount:u,unsatisfiedDepTooltip:f,dependencies:p,claim:m,staleFetch:h}){const{attributes:v,listeners:g,setNodeRef:y,setActivatorNodeRef:j,transform:b,transition:x,isDragging:w}=Pp({id:e.slug,disabled:!d}),k={transform:Ht.Transform.toString(b),transition:x};return n.jsx(Ro,{plan:e,expanded:r,onToggle:s,onRun:a,launching:o,blocked:l,onBlockedClick:c,position:t,sortableRef:y,sortableStyle:k,isDragging:w,dragHandleRef:d?j:void 0,dragHandleAttributes:d?v:void 0,dragHandleListeners:d?g:void 0,unsatisfiedDepCount:u,unsatisfiedDepTooltip:f,dependencies:p,claim:m,staleFetch:h})}function Kr({plans:e,loading:t,error:r,onRun:s,launchingSlug:a,launchError:o,blocked:l=!1,onBlockedClick:c,onReorder:d,depAnnotationsBySlug:u,dependenciesBySlug:f,claimsBySlug:p,staleFetch:m}){const[h,v]=i.useState(null),[g,y]=i.useState(null),[j,b]=i.useState(null);i.useEffect(()=>{y(null)},[e]);const x=g??e,w=x.length;return n.jsxs("div",{className:"mt-6",children:[n.jsxs("h3",{className:"text-xs font-medium uppercase tracking-wide text-[var(--text-dim)]",children:["Queued Changes (",w,")"]}),o&&n.jsxs("p",{className:"mt-2 text-sm text-[var(--accent-red)]",children:["Failed to launch plan: ",o]}),j&&n.jsxs("p",{className:"mt-2 text-sm text-[var(--accent-red)]",children:["Failed to reorder plans: ",j]}),n.jsx(Gp,{plans:x,loading:t,error:r,expandedSlug:h,onToggle:k=>v(C=>C===k?null:k),onRun:s,launchingSlug:a??null,blocked:l,onBlockedClick:c,depAnnotationsBySlug:u,dependenciesBySlug:f,claimsBySlug:p,staleFetch:m,onReorder:d?async k=>{y(k),b(null);try{await d(k.map(C=>C.slug))}catch(C){y(null),b(C instanceof Error?C.message:"Unknown error")}}:void 0})]})}function Gp({plans:e,loading:t,error:r,expandedSlug:s,onToggle:a,onRun:o,launchingSlug:l,blocked:c,onBlockedClick:d,onReorder:u,depAnnotationsBySlug:f,dependenciesBySlug:p,claimsBySlug:m,staleFetch:h}){const v=lf(Rs(Vr,{activationConstraint:{distance:4}}),Rs(Hr,{coordinateGetter:Fp})),g=i.useMemo(()=>e.map(b=>b.slug),[e]);if(t)return n.jsx("p",{className:"mt-3 text-sm text-[var(--text-muted)]",children:"Loading plans…"});if(r)return n.jsxs("p",{className:"mt-3 text-sm text-[var(--accent-red)]",children:["Failed to load plans: ",r]});if(e.length===0)return n.jsx("p",{className:"mt-3 text-sm text-[var(--text-dim)]",children:"No plans yet. Click PLAN NEXT CHANGE to create one."});const y=b=>{const{active:x,over:w}=b;if(!w||x.id===w.id||!u)return;const k=e.findIndex(N=>N.slug===x.id),C=e.findIndex(N=>N.slug===w.id);k===-1||C===-1||u(Ur(e,k,C))},j=n.jsx("ul",{className:"mt-3 flex flex-col gap-2","data-testid":"plan-list",children:e.map((b,x)=>{const w=f==null?void 0:f[b.slug],k=m==null?void 0:m.get(b.slug);return n.jsx(Kp,{plan:b,position:x+1,expanded:s===b.slug,onToggle:()=>a(b.slug),onRun:o,launching:l===b.slug,blocked:c,onBlockedClick:d,draggable:!!u,unsatisfiedDepCount:w==null?void 0:w.count,unsatisfiedDepTooltip:w==null?void 0:w.tooltip,dependencies:p==null?void 0:p[b.slug],claim:k,staleFetch:h},b.slug)})});return u?n.jsx(dp,{sensors:v,collisionDetection:df,onDragEnd:y,children:n.jsx(kp,{items:g,strategy:wp,children:j})}):j}function Yp({awaitingPlanLaunchChoice:e,configLoading:t,sessionLoading:r,sessionDecision:s,sessionInfo:a,stepState:o,provider:l,onContinueSession:c,onAgentIdle:d,onAgentActive:u,onUserInput:f,pendingPlans:p,pendingPlansLoading:m,pendingPlansError:h,onLaunchPlan:v,launchingSlug:g,launchError:y,onReorderPlans:j,isAgentBuilding:b}){const{recoveryFeatureName:x,recoveryStep:w,recoveryMode:k,showTerminal:C,shouldResumeSameProvider:N}=Ru({sessionDecision:s,sessionInfo:a,stepState:o});return s==="pending"?n.jsx(Eu,{featureName:x,editorStep:w,workflowMode:k,currentProvider:l,previousProvider:(a==null?void 0:a.provider)??null,resumeMode:(a==null?void 0:a.resumeMode)??"fresh",awaitingUserInput:(a==null?void 0:a.awaitingUserInput)??!1,onContinue:c}):e&&p.length>0&&a===null&&o===null?n.jsx(Mr,{children:n.jsx(Kr,{plans:p,loading:m,error:h,onRun:E=>{var S;const R=((S=p.find(D=>D.slug===E))==null?void 0:S.title)??E;v(E,R)},launchingSlug:g,launchError:y,blocked:b,onReorder:j})}):C?n.jsx(Ku,{provider:l,shouldResumeSameProvider:N,sessionId:(a==null?void 0:a.sessionId)??null,onAgentIdle:d,onAgentActive:u,onUserInput:f,currentFeature:(o==null?void 0:o.feature)??null}):s==="no-session"&&o===null?n.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-slate-500 space-y-4 px-10 text-center",children:[n.jsx("div",{className:"text-lg font-medium text-slate-400",children:"Ready to build"}),n.jsx("p",{className:"max-w-md",children:"Your first session will start automatically. You can queue changes or wait for the project to initialize."})]}):null}function qp(e){return e?{step:e.step??0,feature:e.feature??null,startedAt:e.startedAt??"",mode:Ye(e.mode),slug:e.slug??null}:null}const Jp=3e3;function qt(){const[e,t]=i.useState(null),[r,s]=i.useState(!0),a=i.useRef(null),o=i.useRef(null);return i.useEffect(()=>{const l=()=>{fetch("/api/step").then(c=>c.json()).then(c=>{const d=qp(c),u=JSON.stringify(d);u!==o.current&&(o.current=u,t(d)),s(!1)}).catch(()=>{s(!1)})};return l(),a.current=setInterval(l,Jp),()=>{a.current&&clearInterval(a.current)}},[]),{stepState:e,loading:r}}const De={hasSession:!1,resumeMode:"fresh",provider:null,feature:null,step:null,mode:null,label:null,sessionId:null,awaitingUserInput:!1,reopenResults:!1,preview:null,agentBrokerLive:!1};function Xp(e){return{hasSession:(e==null?void 0:e.hasSession)??De.hasSession,resumeMode:(e==null?void 0:e.resumeMode)??De.resumeMode,provider:(e==null?void 0:e.provider)??De.provider,feature:(e==null?void 0:e.feature)??De.feature,step:(e==null?void 0:e.step)??De.step,mode:(e==null?void 0:e.mode)==null?De.mode:Ye(e.mode),label:(e==null?void 0:e.label)??De.label,sessionId:(e==null?void 0:e.sessionId)??De.sessionId,awaitingUserInput:(e==null?void 0:e.awaitingUserInput)??De.awaitingUserInput,reopenResults:(e==null?void 0:e.reopenResults)??De.reopenResults,preview:(e==null?void 0:e.preview)??De.preview,agentBrokerLive:(e==null?void 0:e.agentBrokerLive)??De.agentBrokerLive}}function To(e){const t=e==null?void 0:e.pollIntervalMs,[r,s]=i.useState(null),[a,o]=i.useState(!0),l=i.useCallback(async()=>{o(!0);try{const d=await(await fetch("/api/session-info")).json();s(Xp(d))}catch{s(De)}finally{o(!1)}},[]);return i.useEffect(()=>{l()},[l]),i.useEffect(()=>{if(t==null||t<=0)return;const c=setInterval(()=>{l()},t);return()=>clearInterval(c)},[t,l]),{sessionInfo:r,loading:a,refetch:l}}const Qp=5e3;function Zp(){const[e,t]=i.useState(null),[r,s]=i.useState(!0),a=i.useRef(null);return i.useEffect(()=>{const o=()=>{fetch("/api/prompt").then(l=>l.json()).then(l=>{t(l.prompt??null),s(!1)}).catch(()=>s(!1))};return o(),a.current=setInterval(o,Qp),()=>{a.current&&clearInterval(a.current)}},[]),{prompt:e,loading:r}}function em({currentDecision:e,sessionInfo:t,sessionLoading:r}){return r||!t?e:e==="continue"&&t.hasSession?"continue":e==="fresh"&&t.hasSession&&t.resumeMode==="resume"?"fresh":t.resumeMode==="resume"||t.resumeMode==="handoff"?"pending":"fresh"}let xn=null;const tm=1e4;function nm(){xn=Date.now()}function rm(){if(xn==null)return!1;const e=Date.now()-xn;return xn=null,e<=tm}function sm({sessionLoading:e,sessionInfo:t,onSessionDetected:r}){const s=i.useRef(!1),[a,o]=i.useState(()=>rm()?"fresh":"no-session");i.useEffect(()=>{o(c=>em({currentDecision:c,sessionInfo:t,sessionLoading:e})),!e&&t&&(t.resumeMode==="resume"||t.resumeMode==="handoff")&&!s.current&&r&&(s.current=!0,r())},[e,t,r]);const l=i.useCallback(()=>{o("continue")},[]);return{sessionDecision:a,handleContinueSession:l}}function am(){const e=document.activeElement;return e===null||e===document.body||e===document.documentElement||e instanceof HTMLElement&&e.dataset.navTab==="true"}function om(e,t,r,s=0){return e>=r.left-s&&e<=r.right+s&&t>=r.top-s&&t<=r.bottom+s}function zs(e){wn(),e.blur(),window.dispatchEvent(new Event("terminal-focus")),queueMicrotask(()=>{document.activeElement instanceof HTMLIFrameElement&&window.dispatchEvent(new Event("terminal-focus"))})}function im(e){const t=i.useRef(!1);i.useEffect(()=>{if(!e)return;function r(){if(!t.current&&am()){t.current=!0;try{wn(),window.dispatchEvent(new Event("terminal-focus"))}finally{t.current=!1}}}function s(){queueMicrotask(r)}function a(l){const c=document.activeElement;c instanceof HTMLIFrameElement&&l.target!==c&&zs(c)}function o(l){const c=document.activeElement;if(!(c instanceof HTMLIFrameElement))return;const d=c.getBoundingClientRect();om(l.clientX,l.clientY,d,1)||zs(c)}return document.addEventListener("focusout",s),window.addEventListener("focus",s),document.addEventListener("visibilitychange",s),document.addEventListener("mouseup",s),document.addEventListener("pointerdown",a,!0),document.addEventListener("mousedown",a,!0),document.addEventListener("click",a,!0),document.addEventListener("pointermove",o,{capture:!0,passive:!0}),()=>{document.removeEventListener("focusout",s),window.removeEventListener("focus",s),document.removeEventListener("visibilitychange",s),document.removeEventListener("mouseup",s),document.removeEventListener("pointerdown",a,!0),document.removeEventListener("mousedown",a,!0),document.removeEventListener("click",a,!0),document.removeEventListener("pointermove",o,{capture:!0})}},[e])}function lm({sessionLoading:e,sessionInfo:t,onRestorePreview:r}){const s=i.useRef(!1);i.useEffect(()=>{e||!(t!=null&&t.preview)||t.resumeMode!=="resume"&&t.resumeMode!=="handoff"||s.current||(s.current=!0,r==null||r(t.preview))},[r,t,e])}function cm(e){const t=i.useRef(e);i.useEffect(()=>{e&&e!==t.current&&(gn(e),t.current=e)},[e])}function Hs(e,t,r){i.useEffect(()=>{if(!t)return;const s=a=>{e.current&&!e.current.contains(a.target)&&r()};return document.addEventListener("mousedown",s),()=>document.removeEventListener("mousedown",s)},[e,t,r])}function dm({displayName:e,hasPrompt:t,expanded:r,onToggle:s}){return t?n.jsxs("button",{onClick:s,className:"flex items-center gap-1 cursor-pointer transition-colors min-w-0",style:{color:"var(--text-secondary)"},children:[n.jsx("span",{className:"font-medium truncate",children:e}),n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",className:`shrink-0 transition-transform ${r?"rotate-180":""}`,children:n.jsx("path",{d:"M2 4l3 3 3-3"})})]}):n.jsx("span",{className:"font-medium truncate",style:{color:"var(--text-secondary)"},children:e})}function um({prompt:e}){return n.jsx("div",{style:{background:"var(--bg-input)",borderBottom:"1px solid var(--border-default)",maxHeight:"16rem",overflowY:"auto",padding:"0 0.75rem 0.75rem"},children:n.jsx(mt,{variant:"compact",children:e})})}function fm({currentStep:e,isExpanded:t,mode:r,onToggle:s=()=>{},stepNum:a}){const o=a===e,l=a<e,{description:c,label:d}=Ua(a,r);return n.jsxs("div",{onClick:s,className:"cursor-pointer",children:[n.jsxs("div",{className:"w-full px-3 py-1 flex items-center gap-2 text-left transition-colors",style:{color:o?"var(--accent-active)":l?"var(--text-secondary)":"var(--text-muted)",fontWeight:o?500:void 0},onMouseEnter:u=>u.currentTarget.style.background="var(--bg-input)",onMouseLeave:u=>u.currentTarget.style.background="transparent",children:[n.jsxs("span",{className:"w-5 text-right tabular-nums shrink-0",children:[a,"."]}),n.jsx("span",{className:"flex-1",children:d}),c&&n.jsx("svg",{width:"8",height:"8",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",className:`shrink-0 opacity-40 transition-transform ${t?"rotate-180":""}`,children:n.jsx("path",{d:"M2 4l3 3 3-3"})})]}),t&&c&&n.jsx("div",{className:"px-3 pb-1.5 pl-10",children:n.jsx("p",{className:"text-[10px] m-0 leading-relaxed",style:{color:"var(--text-dim)"},children:c})})]},a)}function pm({step:e,feature:t,mode:r,projectTitle:s,userPrompt:a}){const[o,l]=i.useState(!1),[c,d]=i.useState(null),[u,f]=i.useState(!1),p=i.useRef(null),m=i.useRef(null);Hs(p,o,i.useCallback(()=>l(!1),[])),Hs(m,u,i.useCallback(()=>f(!1),[]));const h=t&&e>0,v=t||"New Working Session",g=Ye(r),y=Ua(e,g),j=h?y.label:null,b=y.totalSteps,x=y.prefix;return e===0?n.jsxs("div",{className:"h-8 flex items-center justify-between px-3 text-xs shrink-0 select-none",style:{background:"var(--bg-input)",borderBottom:"1px solid var(--border-default)"},children:[n.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[n.jsx("span",{className:"truncate",style:{color:"var(--text-dim)"},children:s||"New Project"}),n.jsx("span",{style:{color:"var(--text-dim)",opacity:.5},children:">"}),n.jsx("span",{className:"font-medium truncate",style:{color:"var(--text-muted)"},children:v})]}),n.jsx("span",{style:{color:"var(--text-dim)"},children:t?"Starting…":"Waiting for session"})]}):n.jsxs("div",{className:"shrink-0",ref:m,children:[n.jsxs("div",{className:"h-8 flex items-center justify-between px-3 text-xs select-none",style:{background:"var(--bg-input)",borderBottom:u?"none":"1px solid var(--border-default)"},children:[n.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[n.jsx("span",{className:"truncate",style:{color:"var(--text-dim)"},children:s||"New Project"}),n.jsx("span",{style:{color:"var(--text-dim)",opacity:.5},children:">"}),n.jsx(dm,{displayName:v,hasPrompt:!!a,expanded:u,onToggle:()=>f(w=>!w)})]}),h&&n.jsxs("div",{className:"relative",ref:p,children:[n.jsxs("button",{onClick:()=>l(w=>!w),className:"flex items-center gap-1.5 cursor-pointer transition-colors",style:{color:"var(--text-secondary)"},children:[n.jsx("span",{style:{color:"var(--text-dim)"},children:"::"}),n.jsxs("span",{children:[x," ",e,n.jsxs("span",{style:{color:"var(--text-dim)"},children:[" / ",b]}),": ",j]}),n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",className:`transition-transform ${o?"rotate-180":""}`,children:n.jsx("path",{d:"M2 4l3 3 3-3"})})]}),o&&n.jsx("div",{className:"absolute right-0 top-full mt-1 w-52 rounded-lg shadow-lg z-30 py-1",style:{background:"var(--bg-surface)",border:"1px solid var(--border-default)"},children:Array.from({length:b},(w,k)=>k+1).map(w=>{const k=c===w;return n.jsx(fm,{currentStep:e,isExpanded:k,mode:g,onToggle:()=>d(k?null:w),stepNum:w},w)})})]})]}),u&&a&&n.jsx(um,{prompt:a})]})}function mm({awaitingPlanLaunchChoice:e,isActive:t,onSessionDetected:r,onAgentIdle:s,onAgentActive:a,onUserInput:o,provider:l,onRestorePreview:c,pendingPlans:d,pendingPlansLoading:u,pendingPlansError:f,onLaunchPlan:p,launchingSlug:m,launchError:h,onReorderPlans:v,isAgentBuilding:g}){const{stepState:y}=qt(),{config:j,loading:b}=it(),{prompt:x}=Zp(),{sessionInfo:w,loading:k}=To(),{sessionDecision:C,handleContinueSession:N}=sm({sessionLoading:k,sessionInfo:w,onSessionDetected:r});return im(t),lm({sessionLoading:k,sessionInfo:w,onRestorePreview:c}),cm((y==null?void 0:y.feature)??null),n.jsx(xu,{stepIndicator:n.jsx(pm,{step:(y==null?void 0:y.step)??0,feature:(y==null?void 0:y.feature)??null,mode:(y==null?void 0:y.mode)??"ui",projectTitle:(j==null?void 0:j.projectTitle)??null,userPrompt:x}),sessionContent:n.jsx(Yp,{awaitingPlanLaunchChoice:e,configLoading:b,sessionLoading:k,sessionDecision:C,sessionInfo:w,stepState:y,provider:l,onContinueSession:N,onAgentIdle:s,onAgentActive:a,onUserInput:o,pendingPlans:d,pendingPlansLoading:u,pendingPlansError:f,onLaunchPlan:p,launchingSlug:m,launchError:h,onReorderPlans:v,isAgentBuilding:g})})}function Po({screenshotPath:e,cacheBuster:t,alt:r,className:s="",title:a}){const[o,l]=i.useState("loading"),[c,d]=i.useState(!1),u=i.useRef(null),f=e?Ge(e):"",p=f.startsWith("http"),m=t&&!p?`${f}?cb=${t}`:f,h=()=>{l("success"),d(!0)},v=()=>{l("error"),d(!1)};return i.useEffect(()=>{l("loading"),d(!1);const g=u.current;g!=null&&g.complete&&(g.naturalHeight!==0?(l("success"),d(!0)):(l("error"),d(!1)))},[m]),e?n.jsxs("div",{className:"relative w-full h-full flex items-center justify-center",title:a,children:[n.jsx("img",{ref:u,src:m,alt:r,onLoad:h,onError:v,className:s||"max-w-full max-h-full object-contain",style:{visibility:c?"visible":"hidden",position:c?"relative":"absolute"}}),o==="loading"&&n.jsx("div",{className:"absolute inset-0 bg-gray-100 animate-pulse rounded flex items-center justify-center",children:n.jsx("svg",{className:"w-8 h-8 text-gray-300",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:n.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})})}),o==="error"&&n.jsxs("div",{className:"absolute inset-0 border-2 border-dashed border-gray-300 bg-gray-50 rounded flex flex-col items-center justify-center text-xs gap-1",children:[n.jsx("span",{className:"text-2xl text-gray-400",children:"📷"}),n.jsx("span",{className:"text-gray-400 whitespace-nowrap",children:"No Screenshot"})]})]}):n.jsx("div",{className:"w-full h-full border-2 border-dashed border-gray-300 bg-gray-50 rounded flex flex-col items-center justify-center text-xs gap-1",title:a,children:n.jsx("span",{className:"text-2xl text-gray-400",children:"📷"})})}function hm({refreshing:e,onRefresh:t,onClose:r}){return n.jsxs("div",{className:"shrink-0 px-4 py-2 bg-[var(--bg-card)] border-b border-[var(--border-default)] flex items-center justify-between",children:[n.jsx("div",{className:"flex items-center gap-2",children:n.jsx("h2",{className:"text-sm font-semibold text-[var(--text-primary)] m-0",children:"Working Session Results"})}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("button",{onClick:t,disabled:e,className:"text-[var(--text-muted)] hover:text-[var(--text-secondary)] text-xs leading-none px-2 py-1 border border-[var(--border-default)] rounded disabled:opacity-50",title:"Refresh session data",children:e?"…":"↻"}),n.jsx("button",{onClick:r,className:"text-[var(--text-muted)] hover:text-[var(--text-secondary)] text-lg leading-none px-1",title:"Close results panel",children:"✕"})]})]})}function jt(e,t){if(e.length===0)return{selectedIndex:-1,scenario:null};if("direction"in t){const s=t.direction==="next"?1:-1,a=(t.selectedIndex+s+e.length)%e.length;return{selectedIndex:a,scenario:e[a]}}if("slug"in t){const s=e.findIndex(a=>a.slug===t.slug);return s>=0?{selectedIndex:s,scenario:e[s]}:jt(e,{defaultSelection:!0,selectedIndex:t.selectedIndex})}const r=Math.min(t.selectedIndex??0,e.length-1);return{selectedIndex:r,scenario:e[r]}}function xm(e){return e==null?"":typeof e=="string"?e:typeof e=="object"&&typeof e.name=="string"?e.name:String(e)}const gm="/api/editor-session-summary",bm=3e3;function vm(e=bm){const[t,r]=i.useState(null),[s,a]=i.useState(!0),[o,l]=i.useState(!1),c=i.useCallback(async()=>{l(!0);try{const d=await fetch(gm);d.ok&&r(await d.json())}catch{}l(!1),a(!1)},[]);return i.useEffect(()=>{c()},[c]),i.useEffect(()=>{if(e<=0)return;const d=window.setInterval(c,e);return()=>window.clearInterval(d)},[c,e]),{summary:t,loading:s,refreshing:o,refresh:c}}function ym({onClose:e,onSelectScenario:t,previewSlug:r=null}){var g;const{summary:s,loading:a,refreshing:o,refresh:l}=vm(),[c,d]=i.useState(0),u=i.useMemo(()=>s?[...s.application,...s.components]:[],[s]),f=i.useMemo(()=>r&&u.some(y=>y.slug===r)?r:null,[u,r]),p=f??((g=u[c])==null?void 0:g.slug);i.useEffect(()=>{if(!f)return;const y=u.findIndex(j=>j.slug===f);y>=0&&y!==c&&d(y)},[u,f,c]);const m=i.useCallback(y=>{u.length!==0&&(document.activeElement instanceof HTMLIFrameElement||_u()||(y.key==="ArrowRight"?(y.preventDefault(),d(j=>{const b=jt(u,{direction:"next",selectedIndex:j});return b.scenario&&(t==null||t(b.scenario.slug,b.scenario.url)),b.selectedIndex})):y.key==="ArrowLeft"&&(y.preventDefault(),d(j=>{const b=jt(u,{direction:"previous",selectedIndex:j});return b.scenario&&(t==null||t(b.scenario.slug,b.scenario.url)),b.selectedIndex}))))},[u,t]);i.useEffect(()=>(window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)),[m]);const h=i.useRef(!1);if(i.useEffect(()=>{if(h.current||u.length===0)return;h.current=!0;const y=jt(u,{defaultSelection:!0,selectedIndex:c});y.scenario&&(t==null||t(y.scenario.slug,y.scenario.url))},[u,t,c]),a)return n.jsx("div",{className:"flex-1 flex items-center justify-center p-8 bg-[var(--bg-deep)]",children:n.jsx("div",{className:"animate-spin w-6 h-6 border-2 border-[var(--border-default)] border-t-[#005c75] rounded-full"})});if(!s)return n.jsx("div",{className:"flex-1 flex items-center justify-center p-8 bg-[var(--bg-deep)]",children:n.jsx("div",{className:"text-sm text-[var(--text-muted)]",children:"No session data available."})});const v=s.application.length+s.components.length;return n.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col bg-[var(--bg-deep)]",style:{borderTop:"2px solid #005c75"},children:[n.jsx(hm,{refreshing:o,onRefresh:l,onClose:e}),n.jsxs("div",{className:"flex-1 overflow-auto p-4 space-y-4",children:[s.userPrompt&&n.jsx(wm,{text:s.userPrompt}),n.jsx(an,{title:"Application",icon:"🌐",count:s.application.length,empty:v===0?"No scenarios in this session":void 0,children:s.application.length>0&&n.jsx(km,{scenarios:s.application,selectedSlug:p,onSelect:(y,j)=>{var x,w;const b=jt(u,{slug:y,selectedIndex:c});b.selectedIndex>=0&&d(b.selectedIndex),t==null||t(((x=b.scenario)==null?void 0:x.slug)??y,((w=b.scenario)==null?void 0:w.url)??j)}})}),n.jsx(an,{title:"Components",icon:"🧩",count:s.components.length,children:s.components.length>0&&n.jsx(jm,{scenarios:s.components,selectedSlug:p,onSelect:(y,j)=>{var x,w;const b=jt(u,{slug:y,selectedIndex:c});b.selectedIndex>=0&&d(b.selectedIndex),t==null||t(((x=b.scenario)==null?void 0:x.slug)??y,((w=b.scenario)==null?void 0:w.url)??j)}})}),n.jsx(an,{title:"Functions",icon:"⚙️",count:s.functions.length,children:s.functions.length>0&&n.jsx(Cm,{functions:s.functions})}),n.jsx(an,{title:"Modified Files",icon:"📄",count:s.modifiedFiles.length,children:s.modifiedFiles.length>0&&n.jsx(Sm,{files:s.modifiedFiles})})]})]})}function wm({text:e}){const[t,r]=i.useState(!1),s=e.split(`
|
|
15
|
+
`)[0],a=e.includes(`
|
|
16
|
+
`)||e.length>120;return n.jsxs("div",{className:"px-1 pb-2",children:[n.jsx("div",{className:"text-[10px] font-semibold text-[var(--text-muted)] uppercase tracking-wide mb-1",children:"User Request"}),t?n.jsxs("div",{children:[n.jsx(mt,{variant:"compact",children:e}),a&&n.jsx("button",{onClick:()=>r(!1),className:"text-[#D7FF63] hover:underline text-xs mt-1",children:"Show less"})]}):n.jsxs("div",{className:"text-xs text-[var(--text-secondary)] leading-relaxed",children:[s.slice(0,120),a&&n.jsx("button",{onClick:()=>r(!0),className:"text-[#D7FF63] hover:underline ml-1 text-xs",children:"Read more..."})]})]})}function an({title:e,icon:t,count:r,empty:s,children:a}){return n.jsxs("div",{className:"bg-[var(--bg-card)] border border-[var(--border-default)] rounded-lg overflow-hidden",children:[n.jsxs("div",{className:"px-4 py-2 border-b border-[var(--border-subtle)] bg-[var(--bg-input)] flex items-center gap-2",children:[n.jsx("span",{className:"text-xs",children:t}),n.jsx("span",{className:"text-xs font-semibold text-[var(--text-primary)]",children:e}),n.jsxs("span",{className:"text-[10px] text-[var(--text-muted)]",children:["(",r,")"]})]}),n.jsx("div",{className:"p-3",children:r===0?n.jsx("div",{className:"text-xs text-[var(--text-muted)] italic",children:s||`No ${e.toLowerCase()} in this session`}):a})]})}function xr({scenarios:e,selectedSlug:t,onSelect:r}){return n.jsx("div",{className:"overflow-x-auto",children:n.jsx("div",{className:"flex gap-2",style:{minWidth:"min-content"},children:e.map(s=>n.jsx(Nm,{scenario:s,isSelected:s.slug===t,onSelect:r},s.slug))})})}function jm({scenarios:e,selectedSlug:t,onSelect:r}){const s={};for(const o of e){const l=o.componentName||"Unknown";s[l]||(s[l]=[]),s[l].push(o)}const a=Object.keys(s).sort();return n.jsx("div",{className:"space-y-3",children:a.map(o=>n.jsxs("div",{children:[n.jsx("div",{className:"text-[11px] font-medium text-[var(--text-secondary)] mb-1",children:o}),n.jsx(xr,{scenarios:s[o],selectedSlug:t,onSelect:r})]},o))})}function km({scenarios:e,selectedSlug:t,onSelect:r}){if(!e.some(l=>l.routeName))return n.jsx(xr,{scenarios:e,selectedSlug:t,onSelect:r});const a={};for(const l of e){const c=l.routeName||"Other";a[c]||(a[c]=[]),a[c].push(l)}const o=Object.keys(a).sort();return n.jsx("div",{className:"space-y-3",children:o.map(l=>n.jsxs("div",{children:[n.jsx("div",{className:"text-[11px] font-medium text-[var(--text-secondary)] mb-1",children:l}),n.jsx(xr,{scenarios:a[l],selectedSlug:t,onSelect:r})]},l))})}function Nm({scenario:e,isSelected:t,onSelect:r}){const s=e.name.replace(/\s*\[.*\]\s*$/,"").trim();return n.jsxs("div",{className:"shrink-0 cursor-pointer group",onClick:()=>r==null?void 0:r(e.slug,e.url),title:e.name,children:[n.jsx("div",{className:`w-24 h-24 rounded overflow-hidden transition-colors ${t?"border-2 border-[#005c75] shadow-md":"border border-[var(--border-default)] group-hover:border-[#005c75]"}`,style:{background:"#e8edf1"},children:e.screenshotPaths.length>0?n.jsx(Po,{screenshotPath:e.screenshotPaths[0],alt:e.name,className:"w-full h-full object-cover object-top"}):n.jsx("div",{className:"w-full h-full flex items-center justify-center text-[var(--text-muted)] text-lg",children:"📷"})}),n.jsx("div",{className:`mt-1 text-[10px] truncate w-24 ${t?"text-[#005c75] font-medium":"text-[var(--text-secondary)] group-hover:text-[#005c75]"}`,children:s})]})}function Cm({functions:e}){return n.jsx("div",{className:"divide-y divide-gray-100 -mx-3 -mb-3",children:e.map(t=>n.jsxs("div",{className:"px-3 py-2",children:[n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx("span",{className:"text-[10px] text-[var(--text-muted)] mt-0.5 shrink-0",children:"fn"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("div",{className:"text-xs font-medium text-[var(--text-primary)]",children:t.name}),t.description&&n.jsx("div",{className:"text-[10px] text-[var(--text-muted)] mt-0.5",children:t.description}),n.jsx("div",{className:"text-[10px] text-[var(--text-muted)] font-mono mt-0.5",children:t.filePath})]})]}),t.tests.length>0&&n.jsx("div",{className:"ml-5 mt-1.5 space-y-0.5",children:t.tests.map((r,s)=>n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("span",{className:"text-green-500 text-[10px]",children:"✓"}),n.jsx("span",{className:"text-[10px] text-[var(--text-secondary)]",children:xm(r)})]},s))}),t.testFile&&t.tests.length===0&&n.jsx("div",{className:"ml-5 mt-1 text-[10px] text-[var(--text-muted)] font-mono",children:t.testFile})]},`${t.filePath}::${t.name}`))})}function Sm({files:e}){return n.jsx("div",{className:"divide-y divide-gray-100 -mx-3 -mb-3",children:e.map(t=>n.jsxs("div",{className:"px-3 py-1.5 flex items-center gap-2",children:[n.jsx(Lr,{status:t.status}),n.jsx("span",{className:"text-xs text-[var(--text-secondary)] font-mono truncate",children:t.path})]},t.path))})}function Em({showStepResults:e,showResultsPanel:t,openResults:r,closeResults:s}){const a=i.useRef(!1);i.useEffect(()=>{if(e){a.current=!0,t||r();return}a.current&&(a.current=!1,s())},[s,r,t,e])}function Rm({showResultsCommandKey:e,hideResultsCommandKey:t,showStepResults:r}){const[s,a]=i.useState(!1),[o,l]=i.useState(0),c=i.useCallback(()=>{a(!0),l(u=>u+1)},[]),d=i.useCallback(()=>{a(!1)},[]);return i.useEffect(()=>{e&&c()},[c,e]),i.useEffect(()=>{t&&d()},[d,t]),Em({showStepResults:r,showResultsPanel:s,openResults:c,closeResults:d}),{closeResults:d,openResults:c,resultsKey:o,showResultsPanel:s}}function Tm(e){return(e==null?void 0:e.mode)==="ui"&&(e==null?void 0:e.slug)==="feature-complete"}function Pm({awaitingPlanLaunchChoice:e,buildActivated:t,activeTab:r,onSessionDetected:s,onSelectScenario:a,previewSlug:o=null,showResultsCommandKey:l,hideResultsCommandKey:c,onAgentIdle:d,onAgentActive:u,onUserInput:f,notifSettings:p,onSettingsChange:m,provider:h,onRestorePreview:v,pendingPlans:g,pendingPlansLoading:y,pendingPlansError:j,onLaunchPlan:b,launchingSlug:x,launchError:w,onReorderPlans:k,isAgentBuilding:C}){const{stepState:N}=qt(),{closeResults:E,resultsKey:R,showResultsPanel:S}=Rm({showResultsCommandKey:l,hideResultsCommandKey:c,showStepResults:Tm(N)});return t?n.jsx(gu,{activeTab:r,showResultsPanel:S,buildTab:n.jsx(mm,{awaitingPlanLaunchChoice:e,isActive:r==="build",onSessionDetected:s,onAgentIdle:d,onAgentActive:u,onUserInput:f,provider:h,onRestorePreview:v,pendingPlans:g,pendingPlansLoading:y,pendingPlansError:j,onLaunchPlan:b,launchingSlug:x,launchError:w,onReorderPlans:k,isAgentBuilding:C}),resultsPanel:n.jsx(ym,{onClose:E,onSelectScenario:a,previewSlug:o},R),footer:n.jsx(Ld,{settings:p,onChange:m,agentName:h})}):null}function Dm({className:e="h-5"}){return n.jsxs("svg",{className:e,viewBox:"0 0 79 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",role:"img","aria-label":"CodeYam Editor",children:[n.jsx("path",{d:"M5.50742 6.94462H6.6669C6.89825 6.94462 7.12013 6.85463 7.28372 6.69444C7.44731 6.53426 7.53921 6.317 7.53921 6.09047C7.53921 5.86394 7.44731 5.64668 7.28372 5.4865C7.12013 5.32631 6.89825 5.23633 6.6669 5.23633H5.51133C5.27997 5.23633 5.05809 5.32631 4.8945 5.4865C4.73091 5.64668 4.639 5.86394 4.639 6.09047C4.639 6.20264 4.61644 6.31372 4.57261 6.41735C4.52877 6.52098 4.46451 6.61513 4.38351 6.69444C4.3025 6.77376 4.20634 6.83668 4.1005 6.8796C3.99467 6.92253 3.88124 6.94462 3.76668 6.94462H2.61111C2.38009 6.94462 2.15851 7.03435 1.99498 7.19412C1.83144 7.35389 1.7393 7.57066 1.73878 7.79687C1.73878 8.02307 1.64715 8.24003 1.48398 8.40016C1.32081 8.56029 1.09944 8.6505 0.868421 8.65101C0.637744 8.65202 0.416859 8.74245 0.25411 8.90253C0.0913609 9.0626 -2.30897e-06 9.27929 0 9.50516C-5.79344e-07 9.73086 0.0914247 9.94733 0.254229 10.1071C0.417033 10.2669 0.637923 10.3569 0.868421 10.3574C1.09944 10.3579 1.32081 10.4481 1.48398 10.6082C1.64715 10.7684 1.73878 10.9853 1.73878 11.2115C1.73878 11.4381 1.83069 11.6553 1.99429 11.8155C2.15788 11.9757 2.37976 12.0657 2.61111 12.0657H3.76668C3.9977 12.0657 4.21928 12.1554 4.38282 12.3152C4.54635 12.475 4.63848 12.6917 4.639 12.9179C4.639 13.1445 4.73091 13.3617 4.8945 13.5219C5.05809 13.6821 5.27997 13.7721 5.51133 13.7721H6.6669C6.78136 13.7721 6.8947 13.75 7.00043 13.707C7.10615 13.6641 7.20218 13.6011 7.28303 13.5218C7.36388 13.4424 7.42794 13.3483 7.47157 13.2447C7.51519 13.141 7.53753 13.03 7.53727 12.9179C7.53727 12.6919 7.44556 12.4751 7.28234 12.3153C7.11911 12.1555 6.89773 12.0657 6.6669 12.0657H5.50937C5.27836 12.0652 5.05698 11.975 4.89381 11.8148C4.73064 11.6547 4.639 11.4377 4.639 11.2115C4.639 10.985 4.5471 10.7678 4.38351 10.6076C4.21991 10.4474 3.99804 10.3574 3.76668 10.3574H2.59745C2.36929 10.3574 2.15025 10.2697 1.98746 10.1132C1.82468 9.95667 1.73117 9.74381 1.72707 9.52044C1.72707 9.52044 1.72707 9.52045 1.72707 9.50516C1.72707 9.50516 1.72707 9.49369 1.72707 9.48796C1.73117 9.26459 1.82468 9.05173 1.98746 8.89519C2.15025 8.73866 2.36929 8.65097 2.59745 8.65101H3.76668C3.99804 8.65101 4.21991 8.56102 4.38351 8.40084C4.5471 8.24065 4.639 8.0234 4.639 7.79687C4.639 7.57117 4.73043 7.35468 4.89324 7.19491C5.05604 7.03514 5.27692 6.94513 5.50742 6.94462Z",fill:"currentColor"}),n.jsx("path",{d:"M17.1351 5.27098C16.9037 5.27098 16.6818 5.36096 16.5183 5.52115C16.3547 5.68133 16.2628 5.89859 16.2628 6.12512V7.83152C16.2628 7.94368 16.2402 8.05475 16.1964 8.15838C16.1525 8.26201 16.0883 8.35618 16.0073 8.43549C15.9263 8.51481 15.8301 8.57771 15.7243 8.62064C15.6184 8.66356 15.505 8.68566 15.3904 8.68566C15.1594 8.68616 14.938 8.77637 14.7749 8.9365C14.6117 9.09663 14.5201 9.31361 14.5201 9.53981C14.5196 9.76602 14.4274 9.98278 14.2639 10.1426C14.1003 10.3023 13.8788 10.392 13.6477 10.392C13.4167 10.392 13.1951 10.3023 13.0316 10.1426C12.8681 9.98278 12.7759 9.76602 12.7754 9.53981C12.7754 9.31361 12.6838 9.09663 12.5206 8.9365C12.3574 8.77637 12.1361 8.68616 11.9051 8.68566C11.7905 8.68566 11.6771 8.66356 11.5712 8.62064C11.4654 8.57771 11.3692 8.51481 11.2882 8.43549C11.2072 8.35618 11.143 8.26201 11.0991 8.15838C11.0553 8.05475 11.0327 7.94368 11.0327 7.83152V6.13086C11.0383 6.01542 11.0199 5.90007 10.9786 5.7918C10.9374 5.68352 10.8741 5.58458 10.7926 5.50095C10.7112 5.41732 10.6132 5.35074 10.5047 5.30526C10.3962 5.25977 10.2794 5.23633 10.1614 5.23633C10.0434 5.23633 9.92656 5.25977 9.81805 5.30526C9.70955 5.35074 9.61161 5.41732 9.53015 5.50095C9.44869 5.58458 9.38541 5.68352 9.34414 5.7918C9.30287 5.90007 9.28446 6.01542 9.29004 6.13086V7.83724C9.29004 8.06345 9.38168 8.28041 9.54485 8.44054C9.70802 8.60067 9.9294 8.69089 10.1604 8.6914C10.3918 8.6914 10.6136 8.78138 10.7772 8.94157C10.9408 9.10175 11.0327 9.31901 11.0327 9.54554C11.0332 9.77174 11.1254 9.98851 11.2889 10.1483C11.4525 10.308 11.674 10.3978 11.9051 10.3978C12.1351 10.3983 12.3556 10.4877 12.5186 10.6466C12.6816 10.8055 12.7739 11.021 12.7754 11.2462V12.966C12.7754 13.1922 12.8671 13.4091 13.0302 13.5693C13.1934 13.7294 13.4148 13.8196 13.6458 13.8201C13.8771 13.8201 14.099 13.7301 14.2626 13.5699C14.4262 13.4097 14.5181 13.1925 14.5181 12.966V11.2596C14.5181 11.0334 14.6097 10.8164 14.7729 10.6563C14.9361 10.4961 15.1575 10.4059 15.3885 10.4054C15.6195 10.4054 15.8411 10.3157 16.0046 10.1559C16.1682 9.99616 16.2603 9.77938 16.2608 9.55318C16.2608 9.32664 16.3527 9.10939 16.5163 8.9492C16.6799 8.78902 16.9018 8.69904 17.1331 8.69904C17.3641 8.69853 17.5855 8.60832 17.7487 8.44819C17.9119 8.28806 18.0035 8.07109 18.0035 7.84488V6.13086C18.0043 6.01853 17.9824 5.90715 17.9392 5.80311C17.8959 5.69907 17.8321 5.6044 17.7515 5.52453C17.6708 5.44466 17.5748 5.38115 17.4691 5.33764C17.3633 5.29414 17.2498 5.27148 17.1351 5.27098Z",fill:"currentColor"}),n.jsx("path",{d:"M28.609 14.209C27.883 14.209 27.2597 14.0807 26.739 13.824C26.2183 13.5673 25.793 13.2337 25.463 12.823C25.1403 12.4123 24.902 11.965 24.748 11.481C24.594 10.997 24.517 10.5313 24.517 10.084V9.842C24.517 9.34333 24.594 8.852 24.748 8.368C24.9093 7.884 25.155 7.444 25.485 7.048C25.815 6.652 26.233 6.33667 26.739 6.102C27.2523 5.86 27.8573 5.739 28.554 5.739C29.28 5.739 29.9107 5.871 30.446 6.135C30.9887 6.39167 31.4213 6.75833 31.744 7.235C32.0667 7.70433 32.261 8.25433 32.327 8.885H30.754C30.6953 8.51833 30.5633 8.21033 30.358 7.961C30.16 7.70433 29.907 7.51367 29.599 7.389C29.291 7.257 28.9427 7.191 28.554 7.191C28.158 7.191 27.806 7.26067 27.498 7.4C27.19 7.532 26.9333 7.72267 26.728 7.972C26.5227 8.22133 26.365 8.51467 26.255 8.852C26.1523 9.18933 26.101 9.56333 26.101 9.974C26.101 10.37 26.1523 10.7367 26.255 11.074C26.365 11.4113 26.5263 11.7083 26.739 11.965C26.9517 12.2143 27.212 12.4087 27.52 12.548C27.8353 12.6873 28.1983 12.757 28.609 12.757C29.2103 12.757 29.7163 12.6103 30.127 12.317C30.545 12.0163 30.798 11.5983 30.886 11.063H32.459C32.3857 11.635 32.1913 12.1593 31.876 12.636C31.5607 13.1127 31.128 13.494 30.578 13.78C30.028 14.066 29.3717 14.209 28.609 14.209ZM36.5271 14.209C35.9991 14.209 35.5334 14.1247 35.1301 13.956C34.7268 13.7873 34.3858 13.56 34.1071 13.274C33.8284 12.9807 33.6158 12.6507 33.4691 12.284C33.3298 11.9173 33.2601 11.536 33.2601 11.14V10.909C33.2601 10.4983 33.3334 10.1097 33.4801 9.743C33.6341 9.369 33.8504 9.039 34.1291 8.753C34.4151 8.45967 34.7598 8.23233 35.1631 8.071C35.5664 7.90233 36.0211 7.818 36.5271 7.818C37.0331 7.818 37.4878 7.90233 37.8911 8.071C38.2944 8.23233 38.6354 8.45967 38.9141 8.753C39.2001 9.039 39.4164 9.369 39.5631 9.743C39.7098 10.1097 39.7831 10.4983 39.7831 10.909V11.14C39.7831 11.536 39.7098 11.9173 39.5631 12.284C39.4238 12.6507 39.2148 12.9807 38.9361 13.274C38.6574 13.56 38.3164 13.7873 37.9131 13.956C37.5098 14.1247 37.0478 14.209 36.5271 14.209ZM36.5271 12.9C36.9011 12.9 37.2164 12.8193 37.4731 12.658C37.7298 12.4893 37.9241 12.2657 38.0561 11.987C38.1881 11.701 38.2541 11.3783 38.2541 11.019C38.2541 10.6523 38.1844 10.3297 38.0451 10.051C37.9131 9.765 37.7151 9.54133 37.4511 9.38C37.1944 9.21133 36.8864 9.127 36.5271 9.127C36.1678 9.127 35.8561 9.21133 35.5921 9.38C35.3354 9.54133 35.1374 9.765 34.9981 10.051C34.8588 10.3297 34.7891 10.6523 34.7891 11.019C34.7891 11.3783 34.8551 11.701 34.9871 11.987C35.1264 12.2657 35.3244 12.4893 35.5811 12.658C35.8378 12.8193 36.1531 12.9 36.5271 12.9ZM43.5969 14.198C43.1789 14.198 42.7939 14.121 42.4419 13.967C42.0899 13.813 41.7856 13.5967 41.5289 13.318C41.2723 13.0393 41.0743 12.7167 40.9349 12.35C40.7956 11.976 40.7259 11.5727 40.7259 11.14V10.909C40.7259 10.4837 40.7919 10.084 40.9239 9.71C41.0633 9.336 41.2539 9.00967 41.4959 8.731C41.7453 8.45233 42.0423 8.236 42.3869 8.082C42.7389 7.92067 43.1276 7.84 43.5529 7.84C44.0223 7.84 44.4329 7.94267 44.7849 8.148C45.1443 8.346 45.4303 8.64667 45.6429 9.05C45.8556 9.45333 45.9729 9.95933 45.9949 10.568L45.5439 10.04V5.97H47.0729V14H45.8629V11.459H46.1269C46.1049 12.0677 45.9803 12.5773 45.7529 12.988C45.5256 13.3913 45.2249 13.6957 44.8509 13.901C44.4843 14.099 44.0663 14.198 43.5969 14.198ZM43.9379 12.911C44.2386 12.911 44.5136 12.845 44.7629 12.713C45.0123 12.5737 45.2103 12.3757 45.3569 12.119C45.5109 11.855 45.5879 11.547 45.5879 11.195V10.755C45.5879 10.403 45.5109 10.1097 45.3569 9.875C45.2029 9.633 45.0013 9.44967 44.7519 9.325C44.5026 9.193 44.2313 9.127 43.9379 9.127C43.6079 9.127 43.3146 9.20767 43.0579 9.369C42.8086 9.523 42.6106 9.743 42.4639 10.029C42.3246 10.315 42.2549 10.6487 42.2549 11.03C42.2549 11.4113 42.3283 11.745 42.4749 12.031C42.6216 12.3097 42.8196 12.526 43.0689 12.68C43.3256 12.834 43.6153 12.911 43.9379 12.911ZM51.4863 14.209C50.973 14.209 50.522 14.121 50.1333 13.945C49.752 13.769 49.433 13.5343 49.1763 13.241C48.927 12.9403 48.7363 12.6067 48.6043 12.24C48.4797 11.8733 48.4173 11.4993 48.4173 11.118V10.909C48.4173 10.513 48.4797 10.1317 48.6043 9.765C48.7363 9.391 48.927 9.061 49.1763 8.775C49.433 8.48167 49.7483 8.25067 50.1223 8.082C50.4963 7.906 50.929 7.818 51.4203 7.818C52.0657 7.818 52.6047 7.961 53.0373 8.247C53.4773 8.52567 53.8073 8.896 54.0273 9.358C54.2473 9.81267 54.3573 10.304 54.3573 10.832V11.382H49.0663V10.447H53.4003L52.9273 10.909C52.9273 10.5277 52.8723 10.2013 52.7623 9.93C52.6523 9.65867 52.4837 9.44967 52.2563 9.303C52.0363 9.15633 51.7577 9.083 51.4203 9.083C51.083 9.083 50.797 9.16 50.5623 9.314C50.3277 9.468 50.148 9.69167 50.0233 9.985C49.906 10.271 49.8473 10.6157 49.8473 11.019C49.8473 11.393 49.906 11.7267 50.0233 12.02C50.1407 12.306 50.3203 12.5333 50.5623 12.702C50.8043 12.8633 51.1123 12.944 51.4863 12.944C51.8603 12.944 52.1647 12.8707 52.3993 12.724C52.634 12.57 52.7843 12.383 52.8503 12.163H54.2583C54.1703 12.5737 54.0017 12.933 53.7523 13.241C53.503 13.549 53.184 13.7873 52.7953 13.956C52.414 14.1247 51.9777 14.209 51.4863 14.209ZM57.2956 10.931L54.8756 5.97H56.4816L58.3296 9.853L57.9776 9.743H59.0226L58.6486 9.853L60.3316 5.97H61.8496L59.6166 10.931H57.2956ZM57.6916 14V10.689H59.2206V14H57.6916ZM66.0534 14V12.229H65.8004V10.26C65.8004 9.91533 65.7161 9.65867 65.5474 9.49C65.3788 9.32133 65.1184 9.237 64.7664 9.237C64.5831 9.237 64.3631 9.24067 64.1064 9.248C63.8498 9.25533 63.5894 9.26633 63.3254 9.281C63.0688 9.28833 62.8378 9.29933 62.6324 9.314V8.016C62.8011 8.00133 62.9918 7.98667 63.2044 7.972C63.4171 7.95733 63.6334 7.95 63.8534 7.95C64.0808 7.94267 64.2934 7.939 64.4914 7.939C65.1074 7.939 65.6171 8.01967 66.0204 8.181C66.4311 8.34233 66.7391 8.59533 66.9444 8.94C67.1571 9.28467 67.2634 9.73567 67.2634 10.293V14H66.0534ZM64.1284 14.154C63.6958 14.154 63.3144 14.077 62.9844 13.923C62.6618 13.769 62.4088 13.549 62.2254 13.263C62.0494 12.977 61.9614 12.6323 61.9614 12.229C61.9614 11.789 62.0678 11.4297 62.2804 11.151C62.5004 10.8723 62.8048 10.6633 63.1934 10.524C63.5894 10.3847 64.0514 10.315 64.5794 10.315H65.9654V11.228H64.5574C64.2054 11.228 63.9341 11.316 63.7434 11.492C63.5601 11.6607 63.4684 11.8807 63.4684 12.152C63.4684 12.4233 63.5601 12.6433 63.7434 12.812C63.9341 12.9807 64.2054 13.065 64.5574 13.065C64.7701 13.065 64.9644 13.0283 65.1404 12.955C65.3238 12.8743 65.4741 12.7423 65.5914 12.559C65.7161 12.3683 65.7858 12.1117 65.8004 11.789L66.1744 12.218C66.1378 12.636 66.0351 12.988 65.8664 13.274C65.7051 13.56 65.4778 13.78 65.1844 13.934C64.8984 14.0807 64.5464 14.154 64.1284 14.154ZM68.9012 14V8.027H70.1112V10.59H70.0012C70.0012 9.98867 70.0782 9.48633 70.2322 9.083C70.3862 8.67233 70.6136 8.36433 70.9142 8.159C71.2222 7.94633 71.6036 7.84 72.0582 7.84H72.1242C72.5862 7.84 72.9676 7.94633 73.2682 8.159C73.5762 8.36433 73.8036 8.67233 73.9502 9.083C74.1042 9.48633 74.1812 9.98867 74.1812 10.59H73.7962C73.7962 9.98867 73.8732 9.48633 74.0272 9.083C74.1886 8.67233 74.4196 8.36433 74.7202 8.159C75.0282 7.94633 75.4096 7.84 75.8642 7.84H75.9302C76.3922 7.84 76.7772 7.94633 77.0852 8.159C77.3932 8.36433 77.6242 8.67233 77.7782 9.083C77.9396 9.48633 78.0202 9.98867 78.0202 10.59V14H76.4912V10.447C76.4912 10.073 76.3959 9.776 76.2052 9.556C76.0146 9.32867 75.7432 9.215 75.3912 9.215C75.0392 9.215 74.7569 9.33233 74.5442 9.567C74.3316 9.79433 74.2252 10.1023 74.2252 10.491V14H72.6962V10.447C72.6962 10.073 72.6009 9.776 72.4102 9.556C72.2196 9.32867 71.9482 9.215 71.5962 9.215C71.2442 9.215 70.9619 9.33233 70.7492 9.567C70.5366 9.79433 70.4302 10.1023 70.4302 10.491V14H68.9012Z",fill:"currentColor"})]})}function Am({name:e}){const t={width:13,height:13,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round"};return e==="Desktop"?n.jsxs("svg",{...t,children:[n.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),n.jsx("path",{d:"M8 21h8M12 17v4"})]}):e==="Laptop"?n.jsxs("svg",{...t,children:[n.jsx("path",{d:"M4 6a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v8H4V6z"}),n.jsx("path",{d:"M2 18h20"})]}):e==="Tablet"?n.jsxs("svg",{...t,children:[n.jsx("rect",{x:"5",y:"2",width:"14",height:"20",rx:"2"}),n.jsx("path",{d:"M12 18h.01"})]}):e==="Mobile"?n.jsxs("svg",{...t,children:[n.jsx("rect",{x:"7",y:"2",width:"10",height:"20",rx:"2"}),n.jsx("path",{d:"M12 18h.01"})]}):n.jsx("span",{className:"text-xs",children:e})}const Ws=["·","✢","✳","✶","✻","✽"],Fm=160;function Do(){const[e,t]=i.useState(0);return i.useEffect(()=>{const r=window.setInterval(()=>t(s=>(s+1)%Ws.length),Fm);return()=>window.clearInterval(r)},[]),n.jsx("span",{"data-testid":"nav-build-dot-active","aria-label":"Build in progress",className:"mr-1 inline-block w-3 text-center text-[#D7FF63] leading-none text-[11px] tabular-nums",children:Ws[e]})}function Lm({size:e=16}){return n.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),n.jsx("path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"})]})}function Mm({onNavigateToBuild:e,onDismiss:t}){return i.useEffect(()=>(V("banner-mounted",{}),()=>{V("banner-unmounted",{})}),[]),n.jsx("div",{className:"bg-black border-t border-[#333] px-4 py-1.5 flex items-center justify-center",children:n.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 rounded-lg border border-[#FF8B43]/60 bg-[#2a1500] shrink-0",children:[n.jsxs("button",{type:"button",onClick:e,className:"flex items-center gap-2 cursor-pointer",children:[n.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-[#FF8B43] shrink-0"}),n.jsxs("span",{className:"text-sm text-[#FF8B43]",children:["Claude is waiting for you."," ",n.jsx("span",{className:"text-[#FF8B43] font-medium underline",children:"Build."})]})]}),n.jsx("button",{type:"button",onClick:r=>{r.stopPropagation(),t()},className:"p-0.5 text-[#FF8B43]/60 hover:text-[#FF8B43] transition-colors cursor-pointer",title:"Dismiss",children:n.jsx("svg",{width:"12",height:"12",viewBox:"0 0 14 14",fill:"none",children:n.jsx("path",{d:"M3 3l8 8M11 3l-8 8",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})})]})})}function We(){const e=()=>{typeof window<"u"&&window.dispatchEvent(new Event("terminal-focus"))};e();const t=requestAnimationFrame(e),r=setTimeout(e,50);return()=>{cancelAnimationFrame(t),clearTimeout(r)}}const Im=[{key:"home",label:"Home"},{key:"plan",label:"Plan"},{key:"build",label:"Build"},{key:"history",label:"History"}];function Vs(){if(typeof document>"u")return;const e=document.activeElement;e instanceof HTMLElement&&e.blur()}function $m({activeTab:e,onTabChange:t,onSendTranscript:r,buildIdle:s=!1,isAgentBuilding:a=!1,bannerVisible:o=!1,onDismissIdleBanner:l,buildDisabled:c=!1}){const d=o&&e!=="build",u=s,f=a&&!s,p=f?"green":u?"orange":"none",m=i.useRef(p);return i.useEffect(()=>{m.current!==p&&(V("build-tab-dot-change",{from:m.current,to:p}),m.current=p)},[p]),n.jsxs("div",{className:"shrink-0",children:[n.jsxs("div",{className:"bg-black h-10 flex items-center px-4 gap-4",children:[n.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[n.jsx("div",{className:"flex items-center gap-2 shrink-0",children:n.jsx(Dm,{className:"h-5 text-white shrink-0"})}),n.jsx("span",{className:"text-[#8E8E8E] text-sm shrink-0",children:"/"}),n.jsx("div",{className:"flex items-center gap-1",children:Im.map(h=>h.key==="build"&&c?n.jsx("button",{type:"button","data-nav-tab":"true","data-testid":"nav-build-disabled",title:"Connect your provider account on the Home tab to enable Build",onClick:()=>{t("home"),Vs()},className:"px-2.5 py-2.5 text-sm text-[#5A5A5A] cursor-not-allowed font-light",children:h.label},h.key):n.jsxs(Oa,{href:Lt(h.key),"data-nav-tab":"true",onNavigate:()=>{t(h.key),Vs(),h.key==="build"&&We()},className:`px-2.5 py-2.5 text-sm transition-colors cursor-pointer ${e===h.key?"text-[#D7FF63] font-medium":"text-[#8E8E8E] hover:text-white font-light"}`,children:[h.key==="build"&&f&&n.jsx(Do,{}),h.key==="build"&&u&&n.jsx("span",{"data-testid":"nav-build-dot-idle",className:"mr-1 inline-block w-2 h-2 rounded-full bg-[#FF8B43]"}),h.label]},h.key))})]}),n.jsx("div",{className:"flex-1"}),n.jsx("button",{onClick:r,className:"p-1.5 rounded-md transition-colors cursor-pointer text-[#8E8E8E] hover:text-white",title:"Send Session Feedback",children:n.jsx(Lm,{})}),!1]}),d&&n.jsx(Mm,{onNavigateToBuild:()=>t("build"),onDismiss:l??(()=>{})})]})}function Om(e,t){for(const r of e.filesByDirectory)for(const s of r.files)if(s.filePath===t)return s;return null}function Ao(e){return e>=80?"#16a34a":e>=50?"#eab308":"#dc2626"}function Jt({coverage:e}){const t=Math.max(0,Math.min(100,e.percent)),r=Ao(t);return n.jsxs("div",{className:"flex items-center gap-2 min-w-[140px]","data-testid":"coverage-bar",children:[n.jsx("div",{className:"flex-1 h-1.5 rounded-full bg-gray-200 overflow-hidden",children:n.jsx("div",{"data-testid":"coverage-bar-fill",className:"h-full rounded-full",style:{width:`${t}%`,backgroundColor:r}})}),n.jsxs("span",{className:"text-xs font-mono tabular-nums",style:{color:r},children:[Math.round(t),"%"]})]})}function Bm({file:e,onSelectFile:t}){return n.jsxs("li",{className:"flex items-center gap-3 py-2","data-testid":"coverage-details-directory-file-row",children:[n.jsx("button",{type:"button",onClick:()=>t(e),className:"flex-1 min-w-0 text-left text-xs text-gray-700 truncate hover:underline cursor-pointer",children:e.filePath}),n.jsx(Jt,{coverage:e.coverage})]})}function _m({group:e,onSelectFile:t}){return n.jsxs("details",{"data-testid":"coverage-details-directory-group",children:[n.jsxs("summary",{className:"cursor-pointer text-sm font-medium text-gray-800",children:[e.directory||"(root)"," ·"," ",n.jsxs("span",{className:"text-gray-500",children:[e.files.length," file",e.files.length===1?"":"s"]})]}),n.jsx("ul",{className:"divide-y divide-gray-100 mt-2",children:e.files.map(r=>n.jsx(Bm,{file:r,onSelectFile:t},r.filePath))})]})}function zm({directories:e,onSelectFile:t}){return e.length===0?null:n.jsxs("section",{className:"bg-white border border-gray-200 rounded-lg p-4","data-testid":"coverage-details-directories-section",children:[n.jsx("h3",{className:"text-sm font-semibold text-gray-900 m-0 mb-2",children:"By directory"}),n.jsx("div",{className:"flex flex-col gap-3",children:e.map(r=>n.jsx(_m,{group:r,onSelectFile:t},r.directory||"(root)"))})]})}function Hm({entry:e,onSelectFile:t}){return n.jsxs("li",{className:"flex items-center gap-3 py-2","data-testid":"coverage-details-entry-row",children:[n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("button",{type:"button",onClick:()=>t(e.filePath),className:"text-sm font-medium text-gray-900 truncate text-left hover:underline cursor-pointer",children:e.name}),n.jsx("div",{className:"text-xs text-gray-500 truncate",children:e.filePath}),e.linkedTests.length>0&&n.jsxs("div",{className:"text-xs text-gray-400 truncate",children:[e.linkedTests.length," linked test",e.linkedTests.length===1?"":"s"]})]}),n.jsx(Jt,{coverage:{percent:e.percent,hitLines:e.hitLines,totalLines:e.totalLines}})]})}function Wm({entries:e,onSelectFile:t}){return n.jsxs("section",{className:"bg-white border border-gray-200 rounded-lg p-4","data-testid":"coverage-details-entries-section",children:[n.jsx("h3",{className:"text-sm font-semibold text-gray-900 m-0 mb-2",children:"By glossary entry"}),e.length===0?n.jsx("p",{className:"text-xs text-gray-500","data-testid":"coverage-details-entries-empty",children:"No glossary entries have coverage data yet."}):n.jsx("ul",{className:"divide-y divide-gray-100",children:e.map(r=>n.jsx(Hm,{entry:r,onSelectFile:t},`${r.filePath}::${r.name}`))})]})}function Fo({file:e}){return n.jsxs("li",{className:"flex items-center gap-3 py-2","data-testid":"orphaned-file-row",children:[n.jsx("div",{className:"flex-1 min-w-0",children:n.jsx("div",{className:"text-xs text-gray-500 truncate",children:e.filePath})}),n.jsx("span",{className:"text-[10px] uppercase tracking-wide text-gray-400",title:"Coverage at file level — no glossary entry maps to this file.",children:"file-level"}),n.jsx(Jt,{coverage:e.coverage})]})}function Vm({files:e,onSelectFile:t}){return e.length===0?null:n.jsxs("section",{className:"bg-white border border-gray-200 rounded-lg p-4","data-testid":"coverage-details-orphaned-section",children:[n.jsx("h3",{className:"text-sm font-semibold text-gray-900 m-0 mb-2",children:"Orphaned files"}),n.jsxs("div",{className:"text-xs text-gray-500 mb-2",children:[e.length," file",e.length===1?"":"s"," with coverage but no glossary entry."]}),n.jsx("ul",{className:"divide-y divide-gray-100",children:e.map(r=>n.jsx("div",{onClick:()=>t(r.filePath),role:"button",tabIndex:0,className:"cursor-pointer",onKeyDown:s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),t(r.filePath))},children:n.jsx(Fo,{file:r})},r.filePath))})]})}function Um({line:e,hits:t}){const r=t>0;return n.jsxs("li",{className:"flex items-center gap-3 py-1 font-mono text-xs","data-testid":r?"coverage-line-hit":"coverage-line-miss",children:[n.jsx("span",{className:"w-12 text-right text-gray-400",children:e}),n.jsx("span",{className:r?"px-2 py-0.5 rounded bg-green-100 text-green-800":"px-2 py-0.5 rounded bg-red-100 text-red-800",children:r?`×${t}`:"miss"})]})}function Km({file:e,onBack:t}){const r=Object.entries(e.lines).map(([s,a])=>({line:Number(s),hits:a})).sort((s,a)=>s.line-a.line);return n.jsxs("div",{"data-testid":"coverage-file-drilldown",className:"flex flex-col gap-3",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("button",{type:"button",onClick:t,className:"text-xs font-medium text-[var(--accent-active)] hover:underline cursor-pointer","data-testid":"coverage-file-drilldown-back",children:"← Back"}),n.jsx("div",{className:"text-sm font-medium text-gray-900 truncate mt-1",children:e.filePath})]}),n.jsx(Jt,{coverage:e.coverage})]}),r.length===0?n.jsx("p",{className:"text-xs text-gray-500",children:"No instrumented lines in this file."}):n.jsx("ul",{className:"divide-y divide-gray-100 max-h-[50vh] overflow-y-auto","data-testid":"coverage-file-drilldown-lines",children:r.map(({line:s,hits:a})=>n.jsx(Um,{line:s,hits:a},s))})]})}function Gr({title:e,aggregate:t,aggregateTestId:r}){return n.jsxs("div",{className:"flex items-center justify-between mb-3",children:[n.jsx("h2",{className:"text-sm font-semibold text-gray-900 m-0",children:e}),t&&t.totalLines>0&&n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs("span",{className:"text-xs text-gray-500",children:[t.hitLines,"/",t.totalLines," lines"]}),n.jsxs("span",{className:"text-xs font-semibold",style:{color:Ao(t.percent)},"data-testid":r,children:[Math.round(t.percent),"% overall"]})]})]})}function Lo({warnings:e}){return e.length===0?null:n.jsx("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-4","data-testid":"coverage-warnings-banner",children:n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx("span",{className:"text-amber-600 text-lg leading-none mt-0.5","aria-hidden":"true",children:"!"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("h3",{className:"text-sm font-semibold text-amber-800 m-0",children:"Coverage Warnings"}),n.jsx("ul",{className:"mt-1 space-y-1 text-sm text-amber-700 list-none p-0 m-0",children:e.map((t,r)=>n.jsx("li",{className:"break-words",children:t},r))})]})]})})}function Gm({onClose:e,fetchDetails:t=Ym,initialData:r}){const[s,a]=i.useState(r??null),[o,l]=i.useState(null),[c,d]=i.useState(null);i.useEffect(()=>{if(r)return;let p=!1;return t().then(m=>{p||a(m)}).catch(m=>{p||l(m instanceof Error?m.message:String(m))}),()=>{p=!0}},[t,r]);const u=i.useCallback(p=>{p.key==="Escape"&&(p.preventDefault(),c?d(null):e())},[e,c]);i.useEffect(()=>(window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)),[u]);const f=p=>{if(!s)return;const m=Om(s,p);m&&d(m)};return n.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(30, 30, 30, 0.90)"},"data-testid":"coverage-details-modal",onClick:e,children:n.jsxs("div",{className:"max-w-3xl w-full mx-4 p-6 rounded-lg bg-[var(--bg-card)] max-h-[90vh] overflow-y-auto",onClick:p=>p.stopPropagation(),children:[n.jsxs("div",{className:"flex items-start justify-between gap-3 mb-4",children:[n.jsx("h2",{className:"text-lg font-semibold text-[var(--text-primary)] m-0",children:"Project coverage"}),n.jsx("button",{type:"button",onClick:e,className:"text-sm text-[var(--text-muted)] hover:text-[var(--text-primary)] cursor-pointer","data-testid":"coverage-details-modal-close","aria-label":"Close",children:"✕"})]}),o&&n.jsxs("p",{className:"text-sm text-red-700","data-testid":"coverage-details-modal-error",children:["Failed to load coverage details: ",o]}),!s&&!o&&n.jsx("p",{className:"text-sm text-[var(--text-muted)]","data-testid":"coverage-details-modal-loading",children:"Loading coverage details…"}),s&&c&&n.jsx(Km,{file:c,onBack:()=>d(null)}),s&&!c&&n.jsxs("div",{className:"flex flex-col gap-6",children:[n.jsx(Gr,{title:"Overall",aggregate:s.projectWide,aggregateTestId:"coverage-details-modal-aggregate"}),s.coverageWarnings.length>0&&n.jsx(Lo,{warnings:s.coverageWarnings}),n.jsx(Wm,{entries:s.entries,onSelectFile:f}),n.jsx(Vm,{files:s.orphanedFiles,onSelectFile:f}),n.jsx(zm,{directories:s.filesByDirectory,onSelectFile:d})]})]})})}function Ym(){return fetch("/api/coverage/details").then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}`);return e.json()})}function qm({appDetailProps:e,appOverviewProps:t,selectedApp:r}){const[s,a]=i.useState(!1),o=()=>a(!0),l=()=>a(!1),c=r?n.jsx(Uc,{app:r,...e,onCoverageClick:o}):n.jsx(hu,{...t,onCoverageClick:o},"app-overview");return n.jsxs(n.Fragment,{children:[c,s&&n.jsx(Gm,{onClose:l})]})}function Jm({activeTab:e,awaitingPlanLaunchChoice:t,buildActivated:r,hideResultsCommandKey:s,onSelectScenario:a,onSessionDetected:o,previewSlug:l,showResultsCommandKey:c,onAgentIdle:d,onAgentActive:u,onUserInput:f,notifSettings:p,onSettingsChange:m,provider:h,onRestorePreview:v,pendingPlans:g,pendingPlansLoading:y,pendingPlansError:j,onLaunchPlan:b,launchingSlug:x,launchError:w,onReorderPlans:k,isAgentBuilding:C}){return r?n.jsx(Pm,{awaitingPlanLaunchChoice:t,buildActivated:r,activeTab:e,onSessionDetected:o,onSelectScenario:a,previewSlug:l,showResultsCommandKey:c,hideResultsCommandKey:s,onAgentIdle:d,onAgentActive:u,onUserInput:f,notifSettings:p,onSettingsChange:m,provider:h,onRestorePreview:v,pendingPlans:g,pendingPlansLoading:y,pendingPlansError:j,onLaunchPlan:b,launchingSlug:x,launchError:w,onReorderPlans:k,isAgentBuilding:C}):null}function Xm({onMouseDown:e}){return n.jsx("div",{onMouseDown:e,className:"shrink-0 flex items-center justify-center group",style:{width:12,cursor:"col-resize",background:"var(--bg-surface)",borderLeft:"1px solid var(--border-default)",borderRight:"1px solid var(--border-default)"},children:n.jsx("div",{className:"w-0.5 h-8 rounded-full opacity-0 group-hover:opacity-100 transition-opacity",style:{background:"var(--text-dim)"}})})}const Qm=[{key:"editor",label:"Editor"},{key:"preview",label:"Preview"}];function Zm({active:e,onChange:t,isAgentBuilding:r=!1,buildIdle:s=!1}){const a=r&&!s,o=s;return n.jsx("div",{"data-testid":"mobile-pane-switcher",className:"shrink-0 flex w-full",style:{background:"var(--bg-nav)",borderTop:"1px solid var(--border-default)",paddingBottom:"env(safe-area-inset-bottom)"},children:Qm.map(l=>{const c=e===l.key;return n.jsxs("button",{"data-testid":`mobile-pane-switcher-${l.key}`,onClick:()=>t(l.key),"aria-pressed":c,className:`flex-1 flex items-center justify-center gap-1 h-12 text-sm border-t-2 transition-colors cursor-pointer ${c?"text-[#D7FF63] border-[#D7FF63] font-medium":"text-[#8E8E8E] border-transparent font-light"}`,children:[l.key==="editor"&&a&&n.jsx(Do,{}),l.key==="editor"&&o&&n.jsx("span",{"data-testid":"mobile-pane-switcher-dot-idle",className:"mr-1 inline-block w-2 h-2 rounded-full bg-[#FF8B43]"}),l.label]},l.key)})})}function eh({isCollapsed:e,leftPane:t,onResizeStart:r,previewPane:s,splitRef:a,isNarrow:o,mobilePane:l,onMobilePaneChange:c,isAgentBuilding:d=!1,buildIdle:u=!1}){return o?n.jsxs("div",{ref:a,className:"fixed inset-0 flex flex-col",style:{background:"var(--bg-surface)"},children:[n.jsxs("div",{className:"flex-1 min-h-0 relative",children:[n.jsx("div",{className:`absolute inset-0 flex ${l==="editor"?"":"hidden"}`,children:t}),n.jsx("div",{className:`absolute inset-0 flex ${l==="preview"?"":"hidden"}`,children:s})]}),n.jsx(Zm,{active:l,onChange:c,isAgentBuilding:d,buildIdle:u})]}):n.jsxs("div",{ref:a,className:"fixed inset-0 flex",style:{background:"var(--bg-surface)"},children:[!e&&n.jsxs(n.Fragment,{children:[t,n.jsx(Xm,{onMouseDown:r})]}),s]})}function Yr(){const[e,t]=i.useState([]),[r,s]=i.useState(!0),[a,o]=i.useState(null),{plansVersion:l}=xt(),c=i.useCallback(async()=>{s(!0),o(null);try{const d=await fetch("/api/plans");if(!d.ok)throw new Error(`HTTP ${d.status}`);const u=await d.json();t(Array.isArray(u)?u.map(f=>({...f,dependsOn:Array.isArray(f.dependsOn)?f.dependsOn:[]})):[])}catch(d){o(d instanceof Error?d.message:"Failed to load plans")}finally{s(!1)}},[]);return i.useEffect(()=>{c()},[c,l]),{plans:e,loading:r,error:a,refetch:c}}function th(){const[e,t]=i.useState([]),[r,s]=i.useState(!0),[a,o]=i.useState(null),{plansVersion:l,claimsVersion:c}=xt(),d=i.useCallback(async()=>{s(!0),o(null);try{const u=await fetch("/api/plan-claims");if(!u.ok)throw new Error(`HTTP ${u.status}`);const f=await u.json();t(Array.isArray(f)?f:[])}catch(u){o(u instanceof Error?u.message:"Failed to load plan claims")}finally{s(!1)}},[]);return i.useEffect(()=>{d()},[d,l,c]),{claims:e,loading:r,error:a,refetch:d}}function nh(){const[e,t]=i.useState(null),{claimsVersion:r}=xt(),s=i.useCallback(async()=>{try{const a=await fetch("/api/plan-claims/sync-status");if(!a.ok)return;const o=await a.json();t(o)}catch{}},[]);return i.useEffect(()=>{s()},[s,r]),i.useEffect(()=>{const a=setInterval(()=>void s(),1e4);return()=>clearInterval(a)},[s]),{status:e}}function rh(){const[e,t]=i.useState(null),r=i.useCallback(async()=>{try{const s=await fetch("/api/server/staleness");if(!s.ok)return;const a=await s.json();t(a)}catch{}},[]);return i.useEffect(()=>{r()},[r]),i.useEffect(()=>{const s=setInterval(()=>void r(),6e4);return()=>clearInterval(s)},[r]),{staleness:e}}const nr="codeyam-editor editor plan-claims-status",sh="git push origin HEAD";function ah(e,t){switch(e){case"credential":return{message:"Plan tracking isn't reaching the remote — git credentials need refreshing. Run the command below from a shell to wake the credential helper.",command:sh};case"network":return{message:"Plan tracking can't reach the remote (network failure). Check connectivity, then run the command below for details.",command:nr};case"git-spawn":return{message:"Plan tracking can't launch git. Run the command below for the failing invocation.",command:nr};default:return{message:`Plan tracking is failing (${t} failed ticks). Teammates' in-flight plans may not appear. Run the command below for details.`,command:nr}}}function oh({status:e}){const{copied:t,copy:r}=Sr(),s=(e==null?void 0:e.consecutiveFailures)??0;if((e==null?void 0:e.enabled)===!1||s<3)return null;const{message:a,command:o}=ah(e==null?void 0:e.lastErrorCategory,s);return n.jsx("div",{className:"bg-amber-50 border border-amber-200 rounded-lg p-3","data-testid":"plan-claim-sync-banner",role:"alert",children:n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx("span",{className:"text-amber-600 text-lg leading-none mt-0.5","aria-hidden":"true",children:"!"}),n.jsxs("div",{className:"flex-1 min-w-0 text-sm text-amber-800",children:[a," ",n.jsx("code",{className:"text-xs",children:o})," ",n.jsx("button",{type:"button",className:"underline text-amber-700 hover:text-amber-900",onClick:()=>void r(o),children:t?"Copied":"Copy command"})]})]})})}const Us="codeyam-editor editor restart-server";function Mo({staleness:e,backendOutOfDate:t=!1}){var l;const{copied:r,copy:s}=Sr(),a=!!(e!=null&&e.stale);if(!a&&!t)return null;const o=((l=e==null?void 0:e.info)==null?void 0:l.minutesStale)??0;return n.jsx("div",{className:"bg-rose-50 border border-rose-200 rounded-lg p-3","data-testid":"server-staleness-banner",role:"alert",children:n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx("span",{className:"text-rose-600 text-lg leading-none mt-0.5","aria-hidden":"true",children:"!"}),n.jsxs("div",{className:"flex-1 min-w-0 text-sm text-rose-800",children:[a?n.jsxs(n.Fragment,{children:["The editor-server is running a stale binary (rebuilt ",o," min ago). Restart it to pick up the latest plan tracking fixes."]}):n.jsx(n.Fragment,{children:"The editor-server is out of date — it's running an older build that can't drive the Build tab. Restart it to reconnect."})," ","Run ",n.jsx("code",{className:"text-xs",children:Us}),"."," ",n.jsx("button",{type:"button",className:"underline text-rose-700 hover:text-rose-900",onClick:()=>void s(Us),children:r?"Copied":"Copy command"})]})]})})}function ih(e){const t=new Map;for(const r of e){const s=t.get(r.slug);(!s||s.source!=="local"&&r.source==="local")&&t.set(r.slug,r)}return t}function lh(e=10){const[t,r]=i.useState([]),[s,a]=i.useState(!0),[o,l]=i.useState(null),c=i.useCallback(async()=>{a(!0),l(null);try{const d=await fetch(`/api/plans/completed?limit=${e}`);if(!d.ok)throw new Error(`HTTP ${d.status}`);const u=await d.json();r(Array.isArray(u)?u:[])}catch(d){l(d instanceof Error?d.message:"Failed to load completed plans")}finally{a(!1)}},[e]);return i.useEffect(()=>{c()},[c]),{plans:t,loading:s,error:o,refetch:c}}function ch(e,t,r){const s=new Map(t.map(a=>[a.slug,a]));return e.dependsOn.map(a=>{var o;return{slug:a,title:((o=s.get(a))==null?void 0:o.title)??null,satisfied:r.has(a)}})}function Io(e){return e.filter(t=>!t.satisfied)}function dh(){const[e,t]=i.useState(()=>new Set),[r,s]=i.useState(!0),[a,o]=i.useState(null),l=i.useCallback(async()=>{s(!0),o(null);try{const c=await fetch("/api/plans/completed/slugs");if(!c.ok)throw new Error(`HTTP ${c.status}`);const d=await c.json(),u=Array.isArray(d==null?void 0:d.slugs)?d.slugs:[];t(new Set(u.filter(f=>typeof f=="string")))}catch(c){o(c instanceof Error?c.message:"Failed to load completed plan slugs")}finally{s(!1)}},[]);return i.useEffect(()=>{l()},[l]),{slugs:e,loading:r,error:a,refetch:l}}function $o(e){const{slugs:t}=dh();return i.useMemo(()=>{const r={},s={};for(const a of e){const o=a.dependsOn??[];if(o.length===0)continue;const l=ch({...a,dependsOn:o},e,t);s[a.slug]=l;const c=Io(l);c.length!==0&&(r[a.slug]={count:c.length,tooltip:c.map(d=>d.title??`missing: ${d.slug}`).join(", ")})}return{annotationsBySlug:r,dependenciesBySlug:s}},[e,t])}let Nt={hasActiveSession:!1,isAgentBuilding:!1,stepStateFeature:null};function qr(e){Nt={...Nt,...e}}function uh(){return Nt}function fh(){return Nt.hasActiveSession||Nt.isAgentBuilding||!!Nt.stepStateFeature}const ph=500;async function mh(){var e;try{const t=await fetch("/api/config");if(!t.ok)return!0;const r=await t.json();return((e=r==null?void 0:r.providerAuth)==null?void 0:e.state)==="authenticated"}catch{return!0}}async function Jr(){let e=!1,t;try{const r=await fetch("/api/session",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"clear"})});t=r.status,r.ok&&(e=!0)}catch{}e&&qr({hasActiveSession:!1,isAgentBuilding:!1,stepStateFeature:null}),V("clear-editor-session",{ok:e,...t!==void 0?{status:t}:{},snapshotReset:e})}async function hh(){let e=!1,t;try{const r=await fetch("/api/stop-building",{method:"POST",headers:{"Content-Type":"application/json"}});t=r.status,r.ok&&(e=!0)}catch{}e&&qr({hasActiveSession:!1,isAgentBuilding:!1,stepStateFeature:null}),V("stop-building",{ok:e,...t!==void 0?{status:t}:{},snapshotReset:e})}async function Xr(e={}){const t=uh(),r=e.caller??"unknown",s=e.bypassLiveGuard===!0;if(fh()&&!s){V("launch-editor-skill",{caller:r,suppressed:!0,snapshot:t,bypassLiveGuard:!1});return}Lu(),V("launch-editor-skill",{caller:r,suppressed:!1,snapshot:t,bypassLiveGuard:s}),e.provider!=="gemini"&&(Xa(e.renameLabel??"Editor",r,Ca),or("/clear\r"),await new Promise(a=>setTimeout(()=>{or("/codeyam-editor\r"),a()},ph)))}async function xh(e={}){if(await Jr(),!await mh()){V("launch-editor-skill",{caller:e.caller??"unknown",suppressed:!0,reason:"provider-not-authenticated"}),console.warn("[launchEditorWorkflow] provider not authenticated; aborting launch (the terminal gate would refuse the PTY).");return}await Xr(e)}function Qr(e,t=!1,r=t){const s=xl(e),a=t&&s==="build"?"home":s,[o,l]=i.useState(a==="build"),[c,d]=i.useState(a==="plan");i.useEffect(()=>{a==="build"&&l(!0),a==="plan"&&d(!0)},[a]),i.useEffect(()=>{r&&s==="build"&&window.history.replaceState(null,"",Lt("home"))},[r,s]);const u=i.useCallback(p=>{if(t&&p==="build"){window.history.pushState(null,"",Lt("home"));return}window.history.pushState(null,"",Lt(p)),p==="build"&&l(!0),p==="plan"&&d(!0)},[t]),f=i.useCallback(()=>{t||(window.history.pushState(null,"",Lt("build")),l(!0))},[t]);return{activeTab:a,buildActivated:o,planActivated:c,navigateToTab:u,showBuildTab:f}}function Zr(){const{showBuildTab:e}=Qr(typeof window>"u"?"/":window.location.pathname),{config:t}=it(),[r,s]=i.useState(null),[a,o]=i.useState(null),l=i.useCallback(async(c,d)=>{if(r)return!1;o(null),s(c);try{try{await Jr(),nm()}catch{}const u=await fetch(`/api/plans/${encodeURIComponent(c)}/select`,{method:"POST"});if(!u.ok){let f=`HTTP ${u.status}`;try{const p=await u.json();p!=null&&p.error&&(f=p.error)}catch{}throw new Error(f)}e()}catch(u){return o(u instanceof Error?u.message:"Failed to launch plan"),s(null),!1}return s(null),Xr({caller:"plan-launcher",renameLabel:d,provider:t==null?void 0:t.provider,bypassLiveGuard:!0}).catch(u=>{o(u instanceof Error?u.message:"Failed to launch plan")}),!0},[r,e,t==null?void 0:t.provider]);return{launchingSlug:r,error:a,launchPlan:l}}function Oo(e){return{reorderPlans:i.useCallback(async r=>{const s=await fetch("/api/plans/reorder",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({slugs:r})});if(!s.ok){const a=await s.json().catch(()=>({}));throw new Error(a.error??`HTTP ${s.status}`)}e==null||e()},[e])}}const gh={describe:"Claude Code will remember your plans and suggest them once the current building session is over.",prototype:"Build a working prototype with the agent. When it's right, formalize into Build to decompose, test, and ship."};function bh({subTab:e="describe"}={}){return n.jsxs(n.Fragment,{children:[n.jsx("h2",{className:"text-lg font-medium text-[var(--text-primary)]",children:"Plan your next move"}),n.jsx("p",{className:"mt-1 text-sm text-[var(--text-dim)]",children:gh[e]})]})}function vh({onClose:e}){const t=r=>{r.target===r.currentTarget&&e()};return n.jsx("div",{"data-testid":"plan-run-blocked-modal",onClick:t,className:"absolute inset-0 z-10 flex items-center justify-center",style:{background:"rgba(30, 30, 30, 0.90)"},children:n.jsxs("div",{className:"max-w-md w-full mx-4 p-6 rounded-lg",style:{background:"var(--bg-surface)",border:"1px solid var(--border-default)"},children:[n.jsx("h2",{className:"text-lg font-semibold text-[var(--text-primary)] mb-2",children:"Build in progress"}),n.jsx("p",{className:"text-sm text-[var(--text-muted)] mb-4",children:Eo}),n.jsx("div",{className:"flex flex-col gap-3",children:n.jsx("button",{onClick:e,"data-testid":"plan-run-blocked-ok",className:"w-full px-4 py-2.5 rounded-md text-sm font-medium transition",style:{background:"var(--accent-active)",color:"var(--bg-deep)"},type:"button",children:"OK"})})]})})}function yh({claim:e,onCancel:t,onConfirm:r}){const s=Yt(),a=e.claimedBy.agentProvider??"agent",o=e.claimedBy.currentStep??"unknown",l=e.sessionAlive===!1,c=l?"Previous session (no longer running)":"Another session is working on this plan",d=l?"Reclaim and run":"Run anyway";i.useEffect(()=>{const f=p=>{p.key==="Escape"&&t()};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[t]);const u=f=>{f.target===f.currentTarget&&t()};return n.jsx("div",{"data-testid":"plan-run-foreign-claim-modal",onClick:u,className:"absolute inset-0 z-10 flex items-center justify-center",style:{background:"rgba(30, 30, 30, 0.90)"},children:n.jsxs("div",{className:"max-w-md w-full mx-4 p-6 rounded-lg",style:{background:"var(--bg-surface)",border:"1px solid var(--border-default)"},children:[n.jsx("h2",{"data-testid":"plan-foreign-claim-heading",className:"text-lg font-semibold text-[var(--text-primary)] mb-2",children:c}),n.jsxs("div",{className:"text-sm text-[var(--text-muted)] mb-4 flex flex-col gap-1",children:[n.jsxs("span",{"data-testid":"plan-foreign-claim-identity",children:["claimed by ",a,"@",e.claimedBy.machine]}),n.jsxs("span",{children:["started ",ot(e.claimedBy.startedAt,s)]}),n.jsxs("span",{"data-testid":"plan-foreign-claim-step",children:["on step ",o," (",ot(e.currentStepEnteredAt,s)," on step)"]})]}),n.jsxs("div",{className:"flex gap-3",children:[n.jsx("button",{onClick:t,"data-testid":"plan-run-foreign-claim-cancel",className:"flex-1 px-4 py-2.5 rounded-md text-sm font-medium transition",style:{background:"var(--bg-elevated, transparent)",border:"1px solid var(--border-default)",color:"var(--text-primary)"},type:"button",children:"Cancel"}),n.jsx("button",{onClick:r,"data-testid":"plan-run-foreign-claim-confirm",className:"flex-1 px-4 py-2.5 rounded-md text-sm font-medium transition",style:{background:"var(--accent-warn, #c08a2c)",color:"var(--bg-deep)"},type:"button",children:d})]})]})})}function wh({deps:e,onClose:t}){const r=s=>{s.target===s.currentTarget&&t()};return n.jsx("div",{"data-testid":"plan-run-dependencies-modal",onClick:r,className:"absolute inset-0 z-10 flex items-center justify-center",style:{background:"rgba(30, 30, 30, 0.90)"},children:n.jsxs("div",{className:"max-w-md w-full mx-4 p-6 rounded-lg",style:{background:"var(--bg-surface)",border:"1px solid var(--border-default)"},children:[n.jsx("h2",{className:"text-lg font-semibold text-[var(--text-primary)] mb-2",children:"Prerequisite plans not yet built"}),n.jsx("p",{className:"text-sm text-[var(--text-muted)] mb-4",children:"This plan depends on the following changes that have not yet been built. Run them first, then come back to this one."}),n.jsx("ul",{className:"flex flex-col gap-1.5 mb-4",children:e.map(s=>n.jsx("li",{"data-testid":`plan-dep-${s.slug}`,className:"text-sm text-[var(--text-primary)]",children:s.title===null?n.jsxs("span",{className:"text-[var(--text-muted)]",children:["missing: ",s.slug," — was the prerequisite plan deleted?"]}):s.title},s.slug))}),n.jsx("div",{className:"flex flex-col gap-3",children:n.jsx("button",{onClick:t,"data-testid":"plan-run-dependencies-ok",className:"w-full px-4 py-2.5 rounded-md text-sm font-medium transition",style:{background:"var(--accent-active)",color:"var(--bg-deep)"},type:"button",children:"OK"})})]})})}const jh=[{id:"describe",label:"Describe A Plan"},{id:"prototype",label:"Prototype A Plan"}];function kh({active:e,onChange:t}){return n.jsx("div",{className:"mt-3 flex items-center gap-1 border-b border-[var(--border-subtle)]",role:"tablist","data-testid":"plan-sub-tabs",children:jh.map(r=>{const s=r.id===e;return n.jsx("button",{type:"button",role:"tab","aria-selected":s,"data-testid":`plan-sub-tab-${r.id}`,onClick:()=>t(r.id),className:"px-2.5 py-2 text-sm transition-colors cursor-pointer border-b -mb-px "+(s?"text-[var(--accent-active)] border-[var(--accent-active)] font-medium":"text-[var(--text-dim)] border-transparent hover:text-[var(--text-primary)] font-light"),children:r.label},r.id)})})}function Ks(e){return e.source==="prototype"}function Nh(e,t){const[r,s]=i.useState(!1),a=i.useRef(new Set),o=Zr(),l=()=>{a.current=new Set(e.filter(Ks).map(c=>c.slug)),s(!0)};return i.useEffect(()=>{if(!r||o.launchingSlug)return;const c=e.filter(Ks).find(d=>!a.current.has(d.slug));c&&(s(!1),o.launchPlan(c.slug,c.title).then(d=>{d&&(t==null||t())}))},[r,o,e,t]),{awaitingFormalize:r,launchError:o.error,launchingSlug:o.launchingSlug,beginFormalize:l}}function Ch({onClose:e}){return n.jsx(Sn,{chatName:"prototype",slashCommand:"/codeyam-prototype",height:480,onClose:e})}const Sh="Building is in-process. Prototyping is only available when building is not ongoing. Please wait for the current building session to complete before prototyping.";function Eh(){return n.jsxs("div",{"data-testid":"prototype-building-banner",className:"mt-3 rounded border px-4 py-3 text-sm",style:{background:"var(--bg-surface)",borderColor:"var(--border-default)",color:"var(--text-muted)"},children:[n.jsx("span",{className:"font-medium text-[var(--text-primary)]",children:"Build in progress."})," ",Sh]})}function Gs({open:e,disabled:t=!1,onToggle:r}){const s="mt-3 inline-flex items-center gap-2 rounded border px-3 py-1.5 text-xs font-medium uppercase tracking-wide transition-colors",a=t?"border-[var(--border-default)] text-[var(--text-dim)] cursor-not-allowed":"border-[var(--accent-active)] text-[var(--accent-active)] hover:bg-[var(--accent-active)] hover:text-black cursor-pointer";return n.jsx("button",{type:"button",onClick:t?void 0:r,disabled:t,"aria-disabled":t,title:t?"Building is in progress.":e?"Close Prototype":"Start Prototyping","data-testid":"start-prototyping",className:`${s} ${a}`,children:e?"Close Prototype":"Start Prototyping"})}const gr=800;function Bt(e){window.dispatchEvent(new CustomEvent("miniagent-send-input",{detail:e}))}function br(e){return new Promise(t=>{let r=!1;const s=()=>{r||(r=!0,window.removeEventListener("miniagent-output",s),clearTimeout(a),t())},a=setTimeout(s,e);window.addEventListener("miniagent-output",s,{once:!0})})}const Rh='The user has clicked "Finish and Formalize in Build". Stop prototyping. Write a plan file at .codeyam/plans/<slug>.md describing what was prototyped. Use frontmatter with `mode: ui` and `step: 10` (or `mode: backend` and `step: 8` for backend mode) and `source: prototype`. Pick a kebab-case slug that matches the feature you prototyped. Once the Write succeeds, output "Done — opening Build to finalize." and stop.';function Th({disabled:e=!1,onClick:t}={}){const[r,s]=i.useState(!1),a=i.useRef(!1),o=async()=>{if(!(e||a.current)){a.current=!0,s(!0);try{Bt(Rh),await br(gr),Bt("\r"),t==null||t()}finally{a.current=!1,s(!1)}}},l=e||r;return n.jsx("button",{type:"button",onClick:o,disabled:l,"data-testid":"finish-and-formalize",className:"mt-3 inline-flex items-center gap-2 rounded border px-3 py-1.5 text-xs font-medium uppercase tracking-wide transition-colors "+(l?"border-[var(--border-default)] text-[var(--text-dim)] cursor-not-allowed":"border-[var(--accent-active)] text-[var(--accent-active)] hover:bg-[var(--accent-active)] hover:text-black cursor-pointer"),children:"Finish and Formalize in Build"})}function Ph(e,t){return`Launches a chat window with ${e} to ${t==="describe"?"describe your plan":"start prototyping"}.`}function Bo({providerLabel:e,kind:t}){return n.jsx("p",{className:"mt-2 text-xs text-[var(--text-dim)]","data-testid":`plan-chat-launch-caption-${t}`,children:Ph(e,t)})}function Dh({isAgentBuilding:e,onLaunched:t}){const[r,s]=i.useState(!1),{plans:a}=Yr(),{config:o}=it(),l=Ve(o==null?void 0:o.provider),c=Nh(a,()=>{s(!1),t==null||t()}),d=()=>{if(e)return;const f=!r;f&&We(),s(f)},u=()=>{s(!1)};return e?n.jsxs("div",{"data-testid":"prototype-pane",children:[n.jsx(Eh,{}),n.jsx(Gs,{open:!1,disabled:!0,onToggle:()=>{}})]}):n.jsxs("div",{"data-testid":"prototype-pane",children:[n.jsx(Gs,{open:r,onToggle:d}),!r&&n.jsx(Bo,{providerLabel:l,kind:"prototype"}),r&&n.jsxs(n.Fragment,{children:[n.jsx(Ch,{onClose:u}),n.jsx(Th,{disabled:c.awaitingFormalize||c.launchingSlug!==null,onClick:c.beginFormalize}),c.awaitingFormalize&&n.jsx("p",{className:"mt-2 text-xs text-[var(--text-dim)]","data-testid":"prototype-awaiting-formalize",children:"Waiting for the agent to write the plan file…"}),c.launchError&&n.jsxs("p",{className:"mt-2 text-xs",style:{color:"var(--accent-error, #ff6b6b)"},"data-testid":"prototype-launch-error",children:["Launch failed: ",c.launchError]})]})]})}function Ah({open:e,onToggle:t}){return n.jsx("button",{type:"button",onClick:t,className:"mt-3 inline-flex items-center gap-2 rounded border border-[var(--accent-active)] px-3 py-1.5 text-xs font-medium uppercase tracking-wide text-[var(--accent-active)] hover:bg-[var(--accent-active)] hover:text-black transition-colors cursor-pointer","data-testid":"plan-next-change",children:e?"Close Planner":"Plan Next Change"})}function Fh({onClose:e}){return n.jsx(Sn,{chatName:"plan",slashCommand:"/codeyam-plan",height:360,onClose:e})}function Lh({providerLabel:e,chatOpen:t,onChatToggle:r,onChatClose:s}){return n.jsxs("div",{"data-testid":"describe-pane",children:[n.jsx(Ah,{open:t,onToggle:r}),!t&&n.jsx(Bo,{providerLabel:e,kind:"describe"}),t&&n.jsx(Fh,{onClose:s})]})}function Mh({claim:e}){const t=Yt(),r=e.claimedBy.agentProvider??"agent",s=e.claimedBy.machine,a=e.claimedBy.currentStep??null,o=ot(e.currentStepEnteredAt,t),l=ot(e.claimedBy.startedAt,t),{dead:c}=So(e);return n.jsxs("li",{className:"flex flex-col gap-1 rounded border border-[var(--border-subtle)] px-3 py-2","data-testid":`in-flight-row-${e.slug}`,"data-session-alive":c?"false":void 0,children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("span",{className:"font-medium text-sm text-[var(--text-default)]",children:e.title}),n.jsx("span",{className:"text-[10px] uppercase tracking-wide text-[var(--text-dim)]","data-testid":`in-flight-source-${e.slug}`,children:e.source})]}),n.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-[var(--text-muted)]",children:[n.jsxs("span",{"data-testid":`plan-claim-identity-${e.slug}`,children:["claimed by ",r,"@",s]}),a&&n.jsxs("span",{"data-testid":`plan-claim-step-${e.slug}`,children:["step ",a," · ",o," on step"]}),n.jsxs("span",{"data-testid":`plan-claim-started-${e.slug}`,children:["started ",l]}),c&&n.jsx("span",{className:"text-[var(--text-muted)]",children:"(inactive)"})]})]})}function Ih({claims:e}){return e.length===0?null:n.jsxs("div",{className:"mt-6","data-testid":"in-flight-section",children:[n.jsxs("h3",{className:"text-xs font-medium uppercase tracking-wide text-[var(--text-dim)]",children:["In Flight (",e.length,")"]}),n.jsx("ul",{className:"mt-3 flex flex-col gap-2","data-testid":"in-flight-list",children:e.map(t=>n.jsx(Mh,{claim:t},`${t.slug}:${t.claimedBy.sessionId}:${t.claimedBy.pid}`))})]})}const $h=5e3;function Oh(){const[e,t]=i.useState([]),[r,s]=i.useState(null),[a,o]=i.useState(null),[l,c]=i.useState(!0),[d,u]=i.useState(null),f=i.useRef(!1),p=i.useCallback(async()=>{c(!0),u(null);try{const v=await fetch("/api/branch-queue/status");if(!v.ok)throw new Error(`HTTP ${v.status}`);const g=await v.json();if(f.current)return;t(Array.isArray(g.entries)?g.entries:[]),s(g.branch??null),o(g.remote??null)}catch(v){if(f.current)return;u(v instanceof Error?v.message:"Failed to load branch queue"),t([])}finally{f.current||c(!1)}},[]);i.useEffect(()=>{f.current=!1,p();const v=setInterval(()=>{p()},$h);return()=>{f.current=!0,clearInterval(v)}},[p]);const m=i.useCallback(async(v,g,y)=>{const j={uuid:v,priority:g};typeof y=="number"&&(j.expectedPriority=y);const b=await fetch("/api/branch-queue/set-priority",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(j)});if(!b.ok){const x=await b.text().catch(()=>"");throw new Error(`set-priority ${b.status}: ${x}`)}await p()},[p]),h=i.useCallback(async v=>{const g=await fetch("/api/branch-queue/release",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({uuid:v})});if(!g.ok){const y=await g.text().catch(()=>"");throw new Error(`release ${g.status}: ${y}`)}await p()},[p]);return{entries:e,branch:r,remote:a,loading:l,error:d,setPriority:m,release:h,refetch:p}}function Bh(){const[e,t]=i.useState(null),[r,s]=i.useState(null),a=i.useCallback(c=>{t(c)},[]),o=i.useCallback(c=>{s(c)},[]),l=i.useCallback(()=>{t(null),s(null)},[]);return{dragSourceUuid:e,dragOverUuid:r,beginDrag:a,hoverOver:o,reset:l}}function _h(e,t,r){var c;if(e.length===0)return 0;if(t===r)return e[t].meta.priority;if(t<0||t>=e.length)return((c=e[0])==null?void 0:c.meta.priority)??0;const s=e[t];if(r<=0)return e[0].meta.priority+1;if(r>=e.length-1){const d=e[e.length-1];return d.uuid===s.uuid?e[e.length-2].meta.priority-1:d.meta.priority-1}const a=e.filter((d,u)=>u!==t),o=r-1>=0&&r-1<a.length?a[r-1]:null,l=r>=0&&r<a.length?a[r]:null;return o&&l?o.meta.priority-l.meta.priority>=2?l.meta.priority+1:o.meta.priority:o?o.meta.priority:l?l.meta.priority+1:s.meta.priority}function zh({priority:e,uuid:t,onNudge:r}){const s=e===0?"priority 0":e>0?`priority +${e}`:`priority ${e}`;return n.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] rounded border border-[var(--border-subtle)] px-2 py-1 text-[var(--text-muted)]","data-testid":`commit-queue-priority-chip-${t}`,children:[n.jsx("button",{type:"button",className:"text-[var(--text-dim)] hover:text-[var(--text-default)] px-0.5","data-testid":`commit-queue-nudge-down-${t}`,onClick:()=>void r(-1),"aria-label":"Lower priority",children:"−"}),n.jsx("span",{"data-testid":`commit-queue-priority-value-${t}`,children:s}),n.jsx("button",{type:"button",className:"text-[var(--text-dim)] hover:text-[var(--text-default)] px-0.5","data-testid":`commit-queue-nudge-up-${t}`,onClick:()=>void r(1),"aria-label":"Raise priority",children:"+"})]})}function Hh({uuid:e,onRelease:t}){const[r,s]=i.useState(!1);return r?n.jsxs("span",{className:"flex items-center gap-1",children:[n.jsx("button",{type:"button",className:"text-xs px-2 py-1 rounded border border-[var(--accent-danger)] text-[var(--accent-danger)] hover:bg-[var(--accent-danger)] hover:text-white cursor-pointer","data-testid":`commit-queue-release-confirm-${e}`,onClick:async()=>{await t(),s(!1)},children:"Confirm release"}),n.jsx("button",{type:"button",className:"text-xs px-2 py-1 rounded border border-[var(--border-subtle)] text-[var(--text-dim)] cursor-pointer",onClick:()=>s(!1),children:"Cancel"})]}):n.jsx("button",{type:"button",className:"opacity-0 group-hover:opacity-100 transition-opacity text-xs px-2 py-1 rounded border border-[var(--border-subtle)] text-[var(--text-dim)] hover:border-[var(--accent-danger)] hover:text-[var(--accent-danger)] cursor-pointer","data-testid":`commit-queue-release-${e}`,onClick:()=>s(!0),title:"Force release this queue entry",children:"Force release"})}function Wh({entry:e,isHead:t}){const r=Yt(),s=e.meta.agentProvider??"agent",a=e.meta.machine,o=e.meta.currentStep??null,l=ot(e.meta.startedAt??e.committerDate,r);return n.jsxs("div",{className:"flex-1 flex flex-col gap-1 min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs("span",{className:"text-sm font-medium text-[var(--text-default)] truncate",children:[s,"@",a]}),t&&n.jsx("span",{className:"text-[10px] uppercase tracking-wide text-[var(--accent-strong)]","data-testid":`commit-queue-head-marker-${e.uuid}`,children:"← head"})]}),n.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-[var(--text-muted)]",children:[o&&n.jsxs("span",{"data-testid":`commit-queue-step-${e.uuid}`,children:["step ",o]}),n.jsxs("span",{"data-testid":`commit-queue-started-${e.uuid}`,children:["started ",l]}),n.jsxs("span",{"data-testid":`commit-queue-pid-${e.uuid}`,children:["pid ",e.meta.pid]})]})]})}function Vh({entry:e,position:t,isHead:r,onPriorityNudge:s,onRelease:a,onDragStart:o,onDragOver:l,onDrop:c,isDragging:d,isDragOver:u}){return n.jsxs("li",{"data-testid":`commit-queue-row-${e.uuid}`,draggable:!0,onDragStart:f=>{f.dataTransfer.effectAllowed="move",f.dataTransfer.setData("text/plain",e.uuid),o()},onDragOver:f=>{f.preventDefault(),f.dataTransfer.dropEffect="move",l()},onDrop:f=>{f.preventDefault(),c()},className:`group flex items-center gap-3 rounded border px-3 py-2 ${r?"border-[var(--accent-strong)]":"border-[var(--border-subtle)]"} ${d?"opacity-40":""} ${u?"ring-2 ring-[var(--accent-strong)]":""}`,children:[n.jsx("span",{"aria-hidden":!0,className:"cursor-grab select-none text-[var(--text-dim)] hover:text-[var(--text-default)]",title:"Drag to reorder","data-testid":`commit-queue-drag-${e.uuid}`,children:"⋮⋮"}),n.jsxs("span",{className:"text-xs font-mono text-[var(--text-dim)] w-6 text-right","data-testid":`commit-queue-position-${e.uuid}`,children:[t,"."]}),n.jsx(Wh,{entry:e,isHead:r}),n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx(zh,{priority:e.meta.priority,uuid:e.uuid,onNudge:s}),n.jsx(Hh,{uuid:e.uuid,onRelease:a})]})]})}function Uh({entriesOverride:e,branchOverride:t}={}){const r=Oh(),s=e??r.entries,a=t??r.branch,o=e?async()=>{}:r.setPriority,l=e?async()=>{}:r.release,c=Bh(),[d,u]=i.useState(null);if(!e&&r.loading&&s.length===0||s.length===0)return null;const f=async h=>{const v=c.dragSourceUuid;if(v===null)return;const g=s.findIndex(b=>b.uuid===v);if(c.reset(),g===-1||g===h)return;const y=_h(s,g,h),j=s[g].meta.priority;if(y!==j){u(null);try{await o(v,y,j)}catch(b){u(b instanceof Error?b.message:"Failed to update priority")}}},p=async(h,v)=>{const g=h.meta.priority;u(null);try{await o(h.uuid,g+v,g)}catch(y){u(y instanceof Error?y.message:"Failed to update priority")}},m=async h=>{u(null);try{await l(h.uuid)}catch(v){u(v instanceof Error?v.message:"Failed to release")}};return n.jsxs("div",{className:"mt-6","data-testid":"commit-queue-section",children:[n.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[n.jsxs("h3",{className:"text-xs font-medium uppercase tracking-wide text-[var(--text-dim)]",children:["Commit Queue (",s.length,")"]}),a&&n.jsx("span",{className:"text-[11px] text-[var(--text-dim)]","data-testid":"commit-queue-branch",children:a})]}),d&&n.jsx("div",{className:"mt-2 text-xs text-[var(--accent-danger)]","data-testid":"commit-queue-error",children:d}),n.jsx("ol",{className:"mt-3 flex flex-col gap-2","data-testid":"commit-queue-list",children:s.map((h,v)=>n.jsx(Vh,{entry:h,position:v+1,isHead:v===0,onPriorityNudge:g=>p(h,g),onRelease:()=>m(h),onDragStart:()=>c.beginDrag(h.uuid),onDragOver:()=>c.hoverOver(h.uuid),onDrop:()=>f(v),isDragging:c.dragSourceUuid===h.uuid,isDragOver:c.dragOverUuid===h.uuid&&c.dragSourceUuid!==h.uuid},h.uuid))})]})}function Kh(e){const[t,r]=i.useState(null),[s,a]=i.useState(!0),[o,l]=i.useState(null);return i.useEffect(()=>{let c=!1;return(async()=>{a(!0),l(null);try{const d=new Date(new Date(e).getTime()-1).toISOString(),u=await fetch(`/api/journal?since=${encodeURIComponent(d)}`);if(!u.ok)throw new Error(`HTTP ${u.status}`);const p=((await u.json()).entries??[]).find(m=>m.timestamp===e)??null;c||r(p)}catch(d){c||(r(null),l(d instanceof Error?d.message:"Failed to load journal entry"))}finally{c||a(!1)}})(),()=>{c=!0}},[e]),{entry:t,loading:s,error:o}}function Gh({journalTimestamp:e}){const{entry:t,loading:r,error:s}=Kh(e);return r?n.jsx("p",{className:"text-sm text-[var(--text-muted)]",children:"Loading journal entry…"}):s?n.jsxs("p",{className:"text-sm text-[var(--accent-red)]",children:["Failed to load journal entry: ",s]}):t?n.jsx(Ga,{entry:t}):n.jsx("p",{className:"text-sm text-[var(--text-dim)]",children:"No journal entry found for this plan yet."})}function Yh({plan:e,expanded:t,onToggle:r}){return n.jsxs("li",{className:"border border-[var(--border-subtle)] rounded-lg",children:[n.jsxs("button",{type:"button",onClick:r,className:"w-full text-left px-3 py-2 flex items-center justify-between gap-3 bg-transparent cursor-pointer","data-testid":"completed-plan-row",children:[n.jsx("span",{className:"flex-1 min-w-0 truncate text-sm text-[var(--text-primary)]",children:e.title}),n.jsx("span",{className:"text-[10px] uppercase tracking-wide px-1.5 py-0.5 rounded border border-[var(--border-subtle)] text-[var(--text-dim)]",children:e.mode}),n.jsx("span",{className:"text-[10px] text-[var(--text-dim)] whitespace-nowrap",children:ot(e.completedAt)}),e.completedBy&&n.jsxs("span",{className:"text-[10px] text-[var(--text-dim)] whitespace-nowrap","data-testid":`completed-plan-by-${e.slug}`,children:["completed by ",e.completedBy.agentProvider??"agent","@",e.completedBy.machine]}),n.jsx("span",{className:"text-xs text-[var(--text-dim)] whitespace-nowrap","data-testid":"completed-plan-row-chevron",children:t?"▼":"▶"})]}),t&&n.jsx("div",{className:"px-3 py-2 border-t border-[var(--border-subtle)]","data-testid":"completed-plan-row-body",children:n.jsx(Gh,{journalTimestamp:e.journalTimestamp})})]})}function qh({plans:e,loading:t,error:r}){const[s,a]=i.useState(null),o=e.length;return n.jsxs("div",{className:"mt-6",children:[n.jsxs("h3",{className:"text-xs font-medium uppercase tracking-wide text-[var(--text-dim)]",children:["Completed Plans (",o,")"]}),n.jsx(Jh,{plans:e,loading:t,error:r,expandedSlug:s,onToggle:l=>a(c=>c===l?null:l)})]})}function Jh({plans:e,loading:t,error:r,expandedSlug:s,onToggle:a}){return t?n.jsx("p",{className:"mt-3 text-sm text-[var(--text-muted)]",children:"Loading completed plans…"}):r?n.jsxs("p",{className:"mt-3 text-sm text-[var(--accent-red)]",children:["Failed to load completed plans: ",r]}):e.length===0?n.jsx("p",{className:"mt-3 text-sm text-[var(--text-dim)]",children:"Plans you complete will appear here."}):n.jsx("ul",{className:"mt-3 flex flex-col gap-2","data-testid":"recent-plans-list",children:e.map(o=>n.jsx(Yh,{plan:o,expanded:s===o.slug,onToggle:()=>a(o.slug)},o.slug))})}function Xh({chatOpen:e,onChatOpenChange:t,isActive:r=!0,isAgentBuilding:s=!1,launchingSlug:a,launchError:o,onLaunchPlan:l,initialSubTab:c="describe"}={}){const{plans:d,loading:u,error:f,refetch:p}=Yr(),{claims:m}=th(),{status:h}=nh(),{staleness:v}=rh(),g=((h==null?void 0:h.consecutiveFailures)??0)>=3,{plans:y,loading:j,error:b}=lh(),{config:x}=it(),w=Ve(x==null?void 0:x.provider),k=l!==void 0,C=Zr(),N=k?a??null:C.launchingSlug,E=k?o??null:C.error,[R,S]=i.useState(!1),[D,P]=i.useState(!1),[I,O]=i.useState(null),[U,J]=i.useState(null),T=i.useMemo(()=>ih(m),[m]),[L,W]=i.useState(c),B=e!==void 0,Y=B?e:R,A=G=>{B||S(G),t==null||t(G)},F=()=>{A(!1),p()},M=()=>{const G=!Y;G&&We(),A(G)};i.useEffect(()=>{if(!(!r||!Y))return We()},[r,Y]);const{annotationsBySlug:X,dependenciesBySlug:Z}=$o(d),_=G=>{var z;const ae=((z=d.find(oe=>oe.slug===G))==null?void 0:z.title)??G;if(l){l(G,ae);return}C.launchPlan(G,ae)},$=G=>{const ae=Io(Z[G]??[]);if(ae.length>0){O(ae);return}const z=T.get(G);if(z&&z.source!=="local"){J(z);return}_(G)},Q=()=>{const G=U;if(G){if(J(null),G.sessionAlive===!1){fetch(`/api/plan-claims/${encodeURIComponent(G.slug)}/reclaim`,{method:"POST"}).catch(()=>{}).finally(()=>_(G.slug));return}_(G.slug)}},{reorderPlans:H}=Oo(p);return n.jsxs(Mr,{testId:"plan-tab",children:[n.jsx(bh,{subTab:L}),n.jsx(kh,{active:L,onChange:W}),L==="describe"&&n.jsx(Lh,{providerLabel:w,chatOpen:Y,onChatToggle:M,onChatClose:F}),L==="prototype"&&n.jsx(Dh,{isAgentBuilding:s,onLaunched:()=>W("describe")}),n.jsx(Mo,{staleness:v}),n.jsx(oh,{status:h}),n.jsx(Kr,{plans:d,loading:u,error:f,onRun:$,launchingSlug:N,launchError:E,blocked:s,onBlockedClick:()=>P(!0),onReorder:H,depAnnotationsBySlug:X,dependenciesBySlug:Z,claimsBySlug:T,staleFetch:g}),n.jsx(Ih,{claims:m}),n.jsx(Uh,{}),n.jsx(qh,{plans:y,loading:j,error:b}),D&&n.jsx(vh,{onClose:()=>P(!1)}),I&&!D&&n.jsx(wh,{deps:I,onClose:()=>O(null)}),U&&n.jsx(yh,{claim:U,onCancel:()=>J(null),onConfirm:Q})]})}function Qh({activeTab:e,planActivated:t,chatOpen:r,onChatOpenChange:s,isAgentBuilding:a=!1,launchingPlanSlug:o,planLaunchError:l,onLaunchPlan:c}){return t?n.jsx("div",{className:"absolute inset-0 flex flex-col overflow-hidden",style:{visibility:e==="plan"?"visible":"hidden",pointerEvents:e==="plan"?"auto":"none"},children:n.jsx(Xh,{chatOpen:r,onChatOpenChange:s,isActive:e==="plan",isAgentBuilding:a,launchingSlug:o,launchError:l,onLaunchPlan:c})}):null}function Zh({visible:e,children:t}){return n.jsx("div",{className:"absolute inset-0 flex flex-col overflow-auto",style:{visibility:e?"visible":"hidden"},children:t})}function ex({activeTab:e,children:t}){const r=["home","build","plan","history","settings"];return n.jsx("div",{className:"flex-1 min-h-0 overflow-hidden relative",children:r.map(s=>n.jsx(Zh,{visible:e===s,children:t[s]},s))})}function tx({title:e}){return n.jsx("div",{className:"flex h-full items-center justify-center",style:{color:"var(--text-dim)"},children:n.jsxs("p",{className:"text-sm",children:[e," — coming soon"]})})}function nx({activeTab:e,appTabContent:t,leftWidth:r}){const s=e!=="build"&&e!=="plan",[a,o]=i.useState(!1);return i.useEffect(()=>{e==="history"&&o(!0)},[e]),n.jsx("div",{className:"absolute inset-0 flex flex-col",style:{visibility:s?"visible":"hidden",pointerEvents:s?"auto":"none"},children:n.jsx(ex,{activeTab:e,width:r,children:{home:t,build:null,plan:null,history:a?n.jsx(wd,{}):null,settings:n.jsx(tx,{title:"Settings"})}})})}function rx({plans:e,onPickPlan:t,launchingSlug:r,planError:s,onSubmitPrompt:a,submittingPrompt:o,promptError:l,onCancel:c,pendingPlansLoading:d,pendingPlansError:u,isAgentBuilding:f}){const[p,m]=i.useState(""),{annotationsBySlug:h,dependenciesBySlug:v}=$o(e),g=i.useCallback(w=>{w.key==="Escape"&&(w.preventDefault(),c())},[c]);i.useEffect(()=>(window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)),[g]);const y=p.trim(),j=y.length===0||o||r!==null,b=()=>{j||a(y)},x=w=>{(w.metaKey||w.ctrlKey)&&w.key==="Enter"&&(w.preventDefault(),b())};return n.jsx("div",{className:"absolute inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(30, 30, 30, 0.90)"},"data-testid":"build-launch-modal",children:n.jsxs("div",{className:"max-w-lg w-full mx-4 p-6 rounded-lg",style:{background:"var(--bg-surface)",border:"1px solid var(--border-default)"},children:[n.jsx("h2",{className:"text-lg font-semibold text-[var(--text-primary)] mb-2",children:"What do you want to build?"}),n.jsx("p",{className:"text-sm text-[var(--text-muted)] mb-4",children:"Pick a queued plan to run, or describe a new build and kick it off directly."}),e.length>0&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"max-h-48 overflow-y-auto mb-3","data-testid":"build-launch-modal-plan-list",children:n.jsx(Kr,{plans:e,loading:d,error:u,onRun:w=>{var C;const k=((C=e.find(N=>N.slug===w))==null?void 0:C.title)??w;t(w,k)},launchingSlug:r,launchError:s,blocked:f,depAnnotationsBySlug:h,dependenciesBySlug:v})}),n.jsxs("div",{className:"flex items-center gap-3 my-4 text-xs text-[var(--text-dim)]","aria-hidden":"true",children:[n.jsx("span",{className:"flex-1 h-px bg-[var(--border-subtle)]"}),n.jsx("span",{children:"or"}),n.jsx("span",{className:"flex-1 h-px bg-[var(--border-subtle)]"})]})]}),n.jsx("p",{className:"text-xs uppercase tracking-wide text-[var(--text-dim)] mb-2",children:"Describe what you want to build"}),n.jsx("textarea",{value:p,onChange:w=>m(w.target.value),onKeyDown:x,rows:4,disabled:o||r!==null,placeholder:"e.g. Add a dark-mode toggle to the settings page",className:"w-full px-3 py-2 rounded-md text-sm resize-y disabled:opacity-50 disabled:cursor-not-allowed",style:{background:"var(--bg-deep, #0e0e0e)",color:"var(--text-primary)",border:"1px solid var(--border-default)"},"data-testid":"build-launch-modal-textarea"}),l&&n.jsx("p",{className:"mt-2 text-xs",style:{color:"var(--text-danger, #ff6b6b)"},"data-testid":"build-launch-modal-prompt-error",children:l}),n.jsxs("div",{className:"mt-4 flex items-center justify-end gap-2",children:[n.jsx("button",{type:"button",onClick:c,className:"px-4 py-2 rounded-md text-sm font-medium transition cursor-pointer",style:{background:"transparent",color:"var(--text-secondary)",border:"1px solid var(--border-default)"},"data-testid":"build-launch-modal-cancel",children:"Cancel"}),n.jsx("button",{type:"button",onClick:b,disabled:j,className:"px-4 py-2 rounded-md text-sm font-medium transition cursor-pointer disabled:cursor-not-allowed disabled:opacity-50",style:{background:"var(--accent-active, #D7FF63)",color:"var(--text-on-accent, #fff)",border:"1px solid transparent"},"data-testid":"build-launch-modal-submit",children:o?"Starting…":"Start build"})]}),n.jsx("p",{className:"mt-3 text-center text-xs text-[var(--text-dim)]",children:"Cmd/Ctrl+Enter submits · Escape cancels"})]})})}function sx({onCreateNewPlan:e,onViewPlans:t}){return n.jsxs("div",{className:"max-w-md w-full mx-4 p-6 rounded-lg",style:{background:"var(--bg-surface)",border:"1px solid var(--border-default)"},"data-testid":"plan-complete-dialog",children:[n.jsx("h2",{className:"text-lg font-semibold text-[var(--text-primary)] mb-2",children:"Plan Saved!"}),n.jsx("p",{className:"text-sm text-[var(--text-muted)] mb-6",children:"Your plan has been committed. Start another plan, or head back to see the list."}),n.jsxs("div",{className:"flex flex-col gap-3",children:[n.jsx("button",{onClick:e,className:"w-full px-4 py-2.5 rounded-md text-sm font-medium transition cursor-pointer",style:{background:"var(--accent-active)",color:"var(--bg-deep)"},type:"button",children:"Create New Plan"}),n.jsx("button",{onClick:t,className:"w-full px-4 py-2.5 rounded-md text-sm font-medium transition cursor-pointer",style:{background:"transparent",color:"var(--text-secondary)",border:"1px solid var(--border-default)"},type:"button",children:"View Plans"})]})]})}function ax({onCreateNewPlan:e,onViewPlans:t}){return n.jsx("div",{className:"absolute inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(30, 30, 30, 0.90)"},children:n.jsx(sx,{onCreateNewPlan:e,onViewPlans:t})})}function ox(e){return!e||!(e instanceof Element)?!1:!!e.closest("[data-terminal-emulator], .xterm")}function ix(e){return!e||!(e instanceof Element)?!1:!!e.closest("[data-post-push-modal]")}function lx({onStartNextFeature:e,onContinueInSession:t,onStopBuilding:r,onSendTranscript:s,onSelectPlan:a,pendingPlanCount:o=0}){const l=o>0&&a,c={background:"var(--accent-active)",color:"var(--bg-deep)"},d={background:"transparent",color:"var(--text-secondary)",border:"1px solid var(--border-default)"},u={background:"transparent",color:"var(--accent-danger, #f87171)",border:"1px solid var(--accent-danger, #f87171)"};return n.jsxs("div",{className:"max-w-md w-full mx-4 p-6 rounded-lg",style:{background:"var(--bg-surface)",border:"1px solid var(--border-default)"},children:[n.jsx("h2",{className:"text-lg font-semibold text-[var(--text-primary)] mb-2",children:"Feature Complete!"}),n.jsx("p",{className:"text-sm text-[var(--text-muted)] mb-6",children:"Your changes have been committed and pushed. You can start a new feature with a fresh context, or continue working in the current session."}),n.jsxs("div",{className:"flex flex-col gap-3",children:[l&&n.jsx("button",{onClick:a,className:"w-full px-4 py-2.5 rounded-md text-sm font-medium transition cursor-pointer",style:c,type:"button",children:"Select A Plan"}),n.jsx("button",{onClick:e,className:"w-full px-4 py-2.5 rounded-md text-sm font-medium transition cursor-pointer",style:l?d:c,type:"button",children:"Start Next Feature"}),n.jsx("button",{onClick:t,className:"w-full px-4 py-2.5 rounded-md text-sm font-medium transition cursor-pointer",style:d,type:"button",children:"Continue in Current Session"}),n.jsx("button",{onClick:r,className:"w-full px-4 py-2.5 rounded-md text-sm font-medium transition cursor-pointer",style:u,type:"button","data-testid":"post-push-stop-building",children:"Stop Building"}),s&&n.jsx("button",{onClick:s,className:"w-full px-4 py-2.5 rounded-md text-sm font-medium transition cursor-pointer",style:{background:"transparent",color:"var(--text-dim)",border:"1px solid var(--border-default)"},type:"button",children:"Send Session Feedback"})]}),n.jsx("p",{className:"mt-4 text-center text-xs text-[var(--text-dim)]",children:l?"Press Enter to pick a queued plan":"Press Enter to start a new feature with a fresh context"})]})}function cx({onStartNextFeature:e,onContinueInSession:t,onStopBuilding:r,onSendTranscript:s,onSelectPlan:a,pendingPlanCount:o=0}){const l=i.useCallback(c=>{if(c.key!=="Enter"||ox(c.target))return;const d=c.target===document.body||c.target===document.documentElement||c.target===document;!ix(c.target)&&!d||(c.preventDefault(),o>0&&a?a():e())},[a,e,o]);return i.useEffect(()=>(window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)),[l]),n.jsx("div",{className:"absolute inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(30, 30, 30, 0.90)"},"data-post-push-modal":!0,children:n.jsx(lx,{onStartNextFeature:e,onContinueInSession:t,onStopBuilding:r,onSendTranscript:s,onSelectPlan:a,pendingPlanCount:o})})}function dx({plans:e,onSelect:t,onCancel:r,launchingSlug:s,error:a}){const[o,l]=i.useState(null),c=i.useMemo(()=>{const f={};for(const p of e)f[p.slug]=p;return f},[e]),d=i.useCallback(f=>{const p=c[f];p&&t(p.slug,p.title)},[t,c]),u=i.useCallback(f=>{if(f.key==="Escape"){f.preventDefault(),r();return}f.key==="Enter"&&e.length>0&&!s&&(f.preventDefault(),t(e[0].slug,e[0].title))},[s,r,t,e]);return i.useEffect(()=>(window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)),[u]),e.length===0?null:n.jsx("div",{className:"absolute inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(30, 30, 30, 0.90)"},"data-testid":"select-plan-modal",children:n.jsxs("div",{className:"max-w-md w-full mx-4 p-6 rounded-lg",style:{background:"var(--bg-surface)",border:"1px solid var(--border-default)"},children:[n.jsx("h2",{className:"text-lg font-semibold text-[var(--text-primary)] mb-2",children:"Select A Plan"}),n.jsx("p",{className:"text-sm text-[var(--text-muted)] mb-4",children:"Pick a queued plan to run next. Its body primes the editor workflow in a fresh session."}),n.jsx("ul",{className:"flex flex-col gap-2 max-h-[50vh] overflow-y-auto mb-2",children:e.map((f,p)=>n.jsx(Ro,{plan:f,position:p+1,expanded:o===f.slug,onToggle:()=>l(m=>m===f.slug?null:f.slug),onRun:d,launching:s===f.slug,expandedBodyVariant:"view"},f.slug))}),a&&n.jsx("p",{className:"text-xs mb-3",style:{color:"var(--text-danger, #ff6b6b)"},"data-testid":"select-plan-error",children:a}),n.jsx("button",{type:"button",onClick:r,className:"w-full px-4 py-2 rounded-md text-sm font-medium transition cursor-pointer",style:{background:"transparent",color:"var(--text-secondary)",border:"1px solid var(--border-default)"},children:"Cancel"}),n.jsx("p",{className:"mt-3 text-center text-xs text-[var(--text-dim)]",children:"Press Enter to launch the first plan, Escape to cancel"})]})})}function ux({activeTab:e,onSendTranscript:t,appTabContent:r,awaitingPlanLaunchChoice:s,buildActivated:a,planActivated:o,buildIdle:l=!1,isAgentBuilding:c=!1,bannerVisible:d=!1,onDismissIdleBanner:u,hideResultsCommandKey:f,leftWidth:p,fullWidth:m=!1,navigateToTab:h,onAgentActive:v,onAgentIdle:g,onUserInput:y,notifSettings:j,onSettingsChange:b,provider:x,onContinueInSession:w,onRestorePreview:k,onResultsScenarioSelect:C,previewSlug:N=null,onSessionDetected:E,onStartNextFeature:R,onStopBuilding:S,showPostPushModal:D,showResultsCommandKey:P,planChatOpen:I,onPlanChatOpenChange:O,showPlanCompleteModal:U,onCreateNewPlan:J,onViewPlans:T,pendingPlans:L,onSelectPlan:W,selectPlanOpen:B,onPickPlan:Y,onCancelSelectPlan:A,launchingPlanSlug:F,planLaunchError:M,showBuildLaunchModal:X=!1,onSubmitBuildPrompt:Z,submittingBuildPrompt:_=!1,buildPromptError:$=null,onCancelBuildLaunchModal:Q,pendingPlansLoading:H,pendingPlansError:G,onReorderPlans:ae,buildDisabled:z=!1}){return n.jsxs("div",{className:`${m?"flex-1 w-full min-w-0":"shrink-0"} flex flex-col overflow-hidden`,style:m?{background:"var(--bg-deep)"}:{width:p,background:"var(--bg-deep)"},children:[n.jsx($m,{activeTab:e,onTabChange:h,onSendTranscript:t,buildIdle:l,isAgentBuilding:c,bannerVisible:d,onDismissIdleBanner:u,buildDisabled:z}),n.jsxs("div",{className:"flex-1 min-h-0 overflow-hidden relative",children:[n.jsx(Jm,{awaitingPlanLaunchChoice:s,buildActivated:a,activeTab:e,onSessionDetected:E,onSelectScenario:C,previewSlug:N,showResultsCommandKey:P,hideResultsCommandKey:f,onAgentIdle:g,onAgentActive:v,onUserInput:y,notifSettings:j,onSettingsChange:b,provider:x,onRestorePreview:k,pendingPlans:L,pendingPlansLoading:H,pendingPlansError:G,onLaunchPlan:Y,launchingSlug:F,launchError:M,onReorderPlans:ae,isAgentBuilding:c}),n.jsx(Qh,{activeTab:e,planActivated:o,chatOpen:I,onChatOpenChange:O,isAgentBuilding:c,launchingPlanSlug:F,planLaunchError:M,onLaunchPlan:Y}),n.jsx(nx,{activeTab:e,appTabContent:r,leftWidth:p}),D&&e==="build"&&!B?n.jsx(cx,{onStartNextFeature:R,onContinueInSession:w,onStopBuilding:S,onSendTranscript:t,onSelectPlan:W,pendingPlanCount:L.length}):null,B&&e==="build"?n.jsx(dx,{plans:L,onSelect:Y,onCancel:A,launchingSlug:F,error:M}):null,X&&e==="build"&&!D&&Z&&Q?n.jsx(rx,{plans:L,onPickPlan:Y,launchingSlug:F,planError:M,onSubmitPrompt:Z,submittingPrompt:_,promptError:$,onCancel:Q,pendingPlansLoading:H,pendingPlansError:G,isAgentBuilding:c}):null,U&&e==="plan"?n.jsx(ax,{onCreateNewPlan:J,onViewPlans:T}):null]})]})}const Ys=5173;function es(e){if(e.startsWith("http"))try{return new URL(e).pathname}catch{return e}return e.split("?")[0]??e}function _o(e){return e?parseInt(e.port||(e.protocol==="https:"?"443":"80"),10):0}function zo(e,{appPort:t,currentPort:r,previewOrigin:s}){return e.startsWith("http")?e:s?`${s}${e}`:r===t?e:`http://localhost:${t}${e}`}function Ho(e,t,r,s,a){if(r&&r.length>0)return zo(r,{appPort:s,currentPort:t,previewOrigin:a});const o=`/scenario/${e}`;return a?`${a}${o}`:t===Ys?o:`http://localhost:${Ys}${o}`}async function qs(e,t=null){try{const r={pid:e};t&&(r.url=t),await fetch("/api/editor-iframe-loaded",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)})}catch{}}async function fx(e){try{await fetch("/api/editor-iframe-error",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({error:e})})}catch{}}async function px(e){try{await fetch("/api/editor-iframe-banner",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({seedError:e})})}catch{}}function mx(e,t,r,s,a){const o=e-a*2,l=t-a*2;return o<=0||l<=0?1:Math.min(1,o/r,l/s)}const hx=32;function xx({currentHeight:e,currentWidth:t,isFilled:r}){const[s,a]=i.useState(null),o=i.useRef(null),l=i.useRef(null),c=i.useCallback(f=>{const p=f.getBoundingClientRect();a({width:p.width,height:p.height})},[]),d=i.useCallback(f=>{if(o.current&&(o.current.disconnect(),o.current=null),l.current=f,!f){a(null);return}c(f);const p=new ResizeObserver(()=>{const m=l.current;m&&c(m)});p.observe(f),o.current=p},[c]),u=r||!s?1:mx(s.width,s.height,t,e,hx);return{containerRef:d,containerSize:s,scale:u}}function gx(){const[e,t]=i.useState({kind:"iframe",fallbackKind:null,fallbackPort:null,loading:!0});return i.useEffect(()=>{let r=!1;return fetch("/api/project-stack").then(s=>s.ok?s.json():{}).then(s=>{r||t(bx(s))}).catch(()=>{r||t({kind:"iframe",fallbackKind:null,fallbackPort:null,loading:!1})}),()=>{r=!0}},[]),e}function bx(e){const t=e&&typeof e=="object"&&"preview"in e?e.preview:null;if(!t||typeof t!="object")return{kind:"iframe",fallbackKind:null,fallbackPort:null,loading:!1};const r=t;return{kind:vx(r.kind),fallbackKind:yx(r.fallbackKind),fallbackPort:typeof r.fallbackPort=="number"?r.fallbackPort:null,loading:!1}}function vx(e){return e==="simulator-ios"?"simulator-ios":"iframe"}function yx(e){return e==="iframe"||e==="simulator-ios"?e:null}function wx(e,t,r){switch(e){case 1:case 2:return"Setting up...";case 3:return`Building — ${t} files modified, ${r} tests modified`;case 4:return"Verifying — running tests...";case 5:return"Ready for review";case 6:return"Refactoring...";case 7:case 8:return"Finalizing...";case 9:return"Ready for approval";case 10:return"Complete";default:return""}}async function Js(){const e=Date.now();try{const t=await fetch("/api/editor-session-summary"),r=Date.now()-e;return t.ok?{ok:!0,data:await t.json(),statusCode:t.status,durationMs:r,error:null}:{ok:!1,data:null,statusCode:t.status,durationMs:r,error:`HTTP ${t.status}`}}catch(t){return{ok:!1,data:null,statusCode:null,durationMs:Date.now()-e,error:t instanceof Error?t.message:String(t)}}}const jx=50,kx={status:"loading",lastSuccessAt:null,lastErrorAt:null,lastErrorMessage:null,fetchCount:0,errorCount:0};function Nx(e,t,r){return{status:t.ok?"connected":"disconnected",lastSuccessAt:t.ok?r:e.lastSuccessAt,lastErrorAt:t.ok?e.lastErrorAt:r,lastErrorMessage:t.ok?e.lastErrorMessage:t.error,fetchCount:e.fetchCount+1,errorCount:e.errorCount+(t.ok?0:1)}}function Cx(e,t){return{timestamp:t,success:e.ok,statusCode:e.statusCode,durationMs:e.durationMs,error:e.error}}function Sx(e,t){return[t,...e].slice(0,jx)}function Ex(){const[e,t]=i.useState(kx),[r,s]=i.useState([]),a=i.useCallback(l=>{const c=Date.now();s(d=>Sx(d,Cx(l,c))),t(d=>Nx(d,l,c))},[]),o=i.useCallback(()=>{t(l=>({...l,status:"polling"}))},[]);return{connectionState:e,fetchLog:r,recordFetch:a,markPolling:o}}function Rx(e){switch(e.status){case"connected":return{dotClass:"bg-green-500",label:"Connected",labelClass:"text-green-400"};case"polling":return{dotClass:"bg-yellow-400 animate-pulse",label:"Polling...",labelClass:"text-yellow-400"};case"disconnected":return{dotClass:"bg-red-500",label:"Disconnected",labelClass:"text-red-400"};case"loading":default:return{dotClass:"bg-[var(--text-muted)]",label:"Connecting...",labelClass:"text-[var(--text-muted)]"}}}function Tx({state:e}){const t=Yt(),{dotClass:r,label:s,labelClass:a}=Rx(e);return n.jsxs("span",{className:"inline-flex items-center gap-1.5 text-[11px] font-medium","data-testid":"connection-status-badge",children:[n.jsx("span",{className:`w-2 h-2 rounded-full ${r}`,"data-testid":"connection-status-dot"}),n.jsx("span",{className:a,"data-testid":"connection-status-label",children:s}),e.lastSuccessAt!=null&&n.jsxs("span",{className:"text-[var(--text-muted)]","data-testid":"connection-status-updated",children:["Updated ",al(e.lastSuccessAt,t)]})]})}function Px({entry:e}){return n.jsxs("div",{className:"flex items-center gap-2","data-testid":"connection-log-entry",children:[n.jsx("span",{className:"text-[var(--text-muted)] w-20 shrink-0","data-testid":"connection-log-time",children:new Date(e.timestamp).toLocaleTimeString()}),e.success?n.jsx("span",{className:"text-green-600 w-4 shrink-0","data-testid":"connection-log-result",children:"✓"}):n.jsx("span",{className:"text-red-500 w-4 shrink-0","data-testid":"connection-log-result",children:"✗"}),n.jsx("span",{className:`w-12 shrink-0 ${e.success?"text-[var(--text-secondary)]":"text-red-500"}`,"data-testid":"connection-log-status",children:e.statusCode!=null?e.statusCode:"—"}),n.jsx("span",{className:"text-[var(--text-muted)] w-14 shrink-0","data-testid":"connection-log-duration",children:cr(e.durationMs)}),e.error&&n.jsx("span",{className:"text-red-500 truncate","data-testid":"connection-log-error",children:e.error})]})}function Dx({state:e,entries:t}){const[r,s]=i.useState(!0);return n.jsxs("div",{className:"bg-[var(--bg-card)] border border-[var(--border-default)] rounded-lg overflow-hidden","data-testid":"connection-log-section",children:[n.jsxs("div",{className:"px-4 py-2 border-b border-[var(--border-subtle)] bg-[var(--bg-input)] cursor-pointer select-none flex items-center justify-between",onClick:()=>s(!r),"data-testid":"connection-log-header",children:[n.jsxs("h2",{className:"text-sm font-semibold text-[var(--text-primary)] m-0",children:["Connection Log (",e.fetchCount," fetches, ",e.errorCount," errors)"]}),n.jsx("span",{className:"text-[var(--text-muted)] text-xs",children:r?"▶":"▼"})]}),!r&&n.jsx("div",{className:"p-3","data-testid":"connection-log-body",children:t.length===0?n.jsx("div",{className:"text-xs text-[var(--text-muted)] text-center py-2",children:"No fetch attempts yet"}):n.jsx("div",{className:"space-y-1 font-mono text-[11px]",children:t.map(a=>n.jsx(Px,{entry:a},a.timestamp))})})]})}function Ax({totalLines:e}){return n.jsxs("div",{className:"text-xs text-[var(--text-secondary)] bg-[var(--bg-input)] border border-[var(--border-subtle)] rounded-md p-3","data-testid":"functions-coverage-empty-state",children:["Your runner reported coverage on ",e," instrumented lines, but no glossary entries are defined for functions. Add entries with"," ",n.jsx("code",{className:"font-mono text-[11px] bg-[var(--bg-card)] px-1 py-0.5 border border-[var(--border-default)] rounded",children:"codeyam-editor editor glossary-add"})," ","to see per-function coverage here."]})}function Fx({functions:e,aggregate:t,projectWide:r=null}){const s=e.length===0&&r!==null&&r.totalLines>0;return e.length===0&&!s?null:n.jsxs("div",{className:"bg-[var(--bg-card)] border border-[var(--border-default)] rounded-lg p-4",children:[n.jsx(Gr,{title:"Function Coverage",aggregate:t,aggregateTestId:"functions-coverage-aggregate"}),s&&n.jsx(Ax,{totalLines:r.totalLines}),e.length>0&&n.jsx("ul",{className:"divide-y divide-gray-100",children:e.map(a=>n.jsxs("li",{className:"flex items-center gap-3 py-2",children:[n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-sm font-medium text-[var(--text-primary)] truncate",children:a.name}),n.jsx("div",{className:"text-xs text-[var(--text-muted)] truncate",children:a.filePath})]}),a.coverage&&a.coverage.totalLines>0?n.jsx(Jt,{coverage:a.coverage}):n.jsx("span",{className:"text-xs text-[var(--text-muted)] min-w-[140px] text-right",children:"no coverage"})]},`${a.filePath}::${a.name}`))})]})}function Lx({projectWide:e,orphanedFiles:t}){return!e||e.totalLines===0?null:n.jsxs("div",{className:"bg-[var(--bg-card)] border border-[var(--border-default)] rounded-lg p-4","data-testid":"project-wide-coverage-rollup",children:[n.jsx(Gr,{title:"Project Coverage",aggregate:e,aggregateTestId:"project-wide-coverage-percent"}),t.length>0&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"text-xs text-[var(--text-muted)] mb-2",children:[t.length," file",t.length===1?"":"s"," with file-level coverage (no glossary entry)"]}),n.jsx("ul",{className:"divide-y divide-gray-100",children:t.map(r=>n.jsx(Fo,{file:r},r.filePath))})]})]})}function Mx(){return n.jsxs("div",{className:"bg-[var(--bg-card)] border border-[var(--border-default)] rounded-lg p-4","data-testid":"coverage-thresholds-empty",children:[n.jsx("h2",{className:"text-sm font-semibold text-[var(--text-primary)] m-0 mb-2",children:"Coverage Thresholds"}),n.jsxs("p",{className:"text-xs text-[var(--text-muted)] m-0",children:["No threshold report yet — run"," ",n.jsx("code",{className:"text-[11px] bg-[var(--bg-input)] px-1 rounded",children:"codeyam-editor editor coverage-check"}),"."]})]})}function Ix({global:e,failureCount:t}){const r=t===0;return n.jsxs("div",{className:"flex items-center justify-between mb-3",children:[n.jsx("h2",{className:"text-sm font-semibold text-[var(--text-primary)] m-0",children:"Coverage Thresholds"}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Ar,{coverage:e}),n.jsx("span",{className:r?"text-xs font-semibold text-green-700":"text-xs font-semibold text-red-700","data-testid":"coverage-thresholds-status",children:r?"PASS":`FAIL (${t})`})]})]})}function $x(){return n.jsxs("p",{className:"text-[11px] text-[var(--text-muted)] mb-3 m-0",children:["Using built-in defaults (global ≥ 70%, per-file ≥ 50%). Add a",n.jsx("code",{className:"mx-1 bg-[var(--bg-input)] px-1 rounded",children:"coverageThresholds"}),"block to editor.json to customize."]})}function Ox({ranRunners:e}){return n.jsxs("p",{className:"text-xs text-[var(--text-secondary)] m-0",children:["All configured thresholds passed across"," ",e.join(", ")||"no runners","."]})}function on(e){return e.kind==="global"?`${e.actual.toFixed(1)}% < required ${e.required.toFixed(1)}%`:e.kind==="perFile"?`${e.path}: ${e.actual.toFixed(1)}% < ${e.required.toFixed(1)}%`:e.kind==="perGlossaryEntry"?`${e.name}: ${e.actual.toFixed(1)}% < ${e.required.toFixed(1)}%`:`dropped ${e.actualDrop.toFixed(1)}% (max allowed ${e.maxAllowed.toFixed(1)}%)`}function Bx(e){const t={global:[],perFile:[],perGlossaryEntry:[],regression:[]};for(const r of e)r.kind==="global"?t.global.push(r):r.kind==="perFile"?t.perFile.push(r):r.kind==="perGlossaryEntry"?t.perGlossaryEntry.push(r):t.regression.push(r);return t}function ln({title:e,items:t}){return n.jsxs("div",{children:[n.jsx("div",{className:"text-[11px] uppercase tracking-wide text-gray-500 mb-1",children:e}),n.jsx("ul",{className:"text-xs text-red-700 space-y-1 m-0 pl-4 list-disc",children:t.map(r=>n.jsx("li",{children:r},r))})]})}function _x({failures:e}){const t=Bx(e);return n.jsxs("div",{className:"space-y-3",children:[t.global.length>0&&n.jsx(ln,{title:"Global",items:t.global.map(on)}),t.perFile.length>0&&n.jsx(ln,{title:"Per-file",items:t.perFile.map(on)}),t.perGlossaryEntry.length>0&&n.jsx(ln,{title:"Per-glossary-entry",items:t.perGlossaryEntry.map(on)}),t.regression.length>0&&n.jsx(ln,{title:"Regression",items:t.regression.map(on)})]})}function zx({report:e}){if(!e)return n.jsx(Mx,{});const t=e.failures.length===0;return n.jsxs("div",{className:"bg-[var(--bg-card)] border border-[var(--border-default)] rounded-lg p-4","data-testid":"coverage-thresholds-panel",children:[n.jsx(Ix,{global:e.global,failureCount:e.failures.length}),e.usedDefaultThresholds&&n.jsx($x,{}),t?n.jsx(Ox,{ranRunners:e.ranRunners}):n.jsx(_x,{failures:e.failures})]})}const Hx=new Set([3,4,6]),Wx=5e3;function Vx(){const[e,t]=i.useState(null),[r,s]=i.useState(!0),{connectionState:a,fetchLog:o,recordFetch:l,markPolling:c}=Ex(),d=i.useRef(null);if(i.useEffect(()=>{async function m(){const h=await Js();l(h),h.ok&&h.data&&t(h.data),s(!1)}return m(),()=>{d.current&&clearInterval(d.current)}},[l]),i.useEffect(()=>(d.current&&(clearInterval(d.current),d.current=null),e!=null&&e.step&&Hx.has(e.step)&&(d.current=setInterval(async()=>{c();const m=await Js();l(m),m.ok&&m.data&&t(m.data)},Wx)),()=>{d.current&&clearInterval(d.current)}),[e==null?void 0:e.step,l,c]),r)return n.jsx("div",{className:"min-h-screen bg-[var(--bg-deep)] flex items-center justify-center",children:n.jsx("div",{className:"animate-spin w-6 h-6 border-2 border-[var(--border-default)] border-t-[#005c75] rounded-full"})});if(!e)return n.jsx("div",{className:"min-h-screen bg-[var(--bg-deep)] flex items-center justify-center text-[var(--text-muted)] text-sm",children:"No session data available."});const u=e.step??0,f=e.functions.reduce((m,h)=>m+h.tests.length,0),p=wx(u,e.modifiedFiles.length,f);return n.jsx("div",{className:"min-h-screen bg-[var(--bg-deep)] p-6",children:n.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[n.jsxs("div",{className:"bg-[var(--bg-card)] border border-[var(--border-default)] rounded-lg p-4",children:[n.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[n.jsx("span",{className:"text-xs px-2 py-0.5 bg-[#005c75] text-white rounded font-medium",children:"BACKEND"}),n.jsx(Tx,{state:a}),n.jsx("h1",{className:"text-lg font-semibold text-[var(--text-primary)] m-0",children:e.feature||"Working Session Results"})]}),e.userPrompt&&n.jsxs("div",{className:"mt-3 bg-[var(--bg-input)] border border-[var(--border-subtle)] rounded-md p-3","data-testid":"user-prompt-section",children:[n.jsx("div",{className:"text-xs font-semibold text-[var(--text-muted)] uppercase tracking-wide mb-1",children:"Prompt"}),n.jsx(Wa,{children:e.userPrompt})]})]}),n.jsx(id,{currentStep:u}),n.jsx(ld,{stats:e.testRunnerStats}),n.jsx(Lo,{warnings:e.coverageWarnings??[]}),p&&n.jsx("div",{className:"text-sm text-[var(--text-secondary)] text-center",children:p}),e.narrative&&n.jsx(cd,{narrative:e.narrative}),e.narrative?n.jsx(dd,{narrative:e.narrative}):n.jsx(pd,{step:u,fileCount:e.modifiedFiles.length,testCount:f}),n.jsx(Lx,{projectWide:e.projectWideCoverage??null,orphanedFiles:e.orphanedFiles??[]}),n.jsx(Fx,{functions:e.functions,aggregate:e.coverage??null,projectWide:e.projectWideCoverage??null}),n.jsx(zx,{report:e.coverageThresholds??null}),e.modifiedFiles.length>0&&n.jsx(hd,{files:e.modifiedFiles,defaultCollapsed:e.narrative!==null}),n.jsx(Dx,{state:a,entries:o})]})})}function Ux(){return n.jsx("div",{className:"flex-1 flex flex-col min-w-0 overflow-auto",style:{background:"var(--bg-deep)"},children:n.jsx(Vx,{})})}function Kx({onClose:e}){const[t,r]=i.useState(""),s=i.useRef(null);return i.useEffect(()=>{var a;(a=s.current)==null||a.focus()},[]),i.useEffect(()=>{const a=o=>{o.key==="Escape"&&e()};return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[e]),n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onMouseDown:a=>{a.target===a.currentTarget&&e()},children:n.jsxs("div",{className:"max-w-md w-full mx-4 p-6 rounded-lg",style:{background:"var(--bg-surface)",border:"1px solid var(--border-default)"},children:[n.jsx("h2",{className:"text-lg font-semibold text-[var(--text-primary)] mb-1",children:"Create New State"}),n.jsx("p",{className:"text-sm text-[var(--text-muted)] mb-4",children:"Describe the state you want Claude to build."}),n.jsx("textarea",{ref:s,value:t,onChange:a=>r(a.target.value),placeholder:"e.g. Empty inbox with a friendly empty-state illustration",rows:5,className:"w-full px-3 py-2 text-sm rounded mb-4 resize-none focus:outline-none",style:{background:"var(--bg-input)",border:"1px solid var(--border-default)",color:"var(--text-primary)"}}),n.jsxs("div",{className:"flex justify-end gap-2",children:[n.jsx("button",{type:"button",onClick:e,className:"px-4 py-2 rounded-md text-sm transition cursor-pointer",style:{background:"transparent",color:"var(--text-secondary)",border:"1px solid var(--border-default)"},children:"Cancel"}),n.jsx("button",{type:"button",disabled:!0,title:"Coming soon",className:"px-4 py-2 rounded-md text-sm font-medium opacity-50 cursor-not-allowed",style:{background:"var(--accent-active)",color:"var(--bg-deep)"},children:"Send to Claude"})]})]})})}function Gx(e,t){var c;const r=[],s=Object.entries(t.vars).filter(([,d])=>d&&d.trim());if(s.length>0){const d=s.map(([u,f])=>` ${u}: ${f};`).join(`
|
|
17
|
+
`);r.push(`:root {
|
|
18
|
+
${d}
|
|
19
|
+
}`)}if(t.primaryFont){const d=Xs(t.primaryFont,t.primaryFontStack);r.push(`body, p, li, span, button, input, textarea, select, label { font-family: ${d} !important; }`)}if(t.secondaryFont){const d=Xs(t.secondaryFont,t.secondaryFontStack);r.push(`h1, h2, h3, h4, h5, h6, .heading, [class*="title"], [class*="headline"] { font-family: ${d} !important; }`)}const a=r.length>0?`<style data-codeyam-overrides="1">
|
|
20
|
+
${r.join(`
|
|
21
|
+
|
|
22
|
+
`)}
|
|
23
|
+
</style>`:"",o=t.fontsHref?`<link rel="preconnect" href="https://fonts.googleapis.com">
|
|
24
|
+
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
|
25
|
+
<link rel="stylesheet" href="${t.fontsHref}" data-codeyam-fonts="1">`:"";if(!a&&!o)return e;const l=e.search(/<\/head\s*>/i);if(l===-1){const d=e.search(/<body[^>]*>/i);if(d===-1)return`${o}
|
|
26
|
+
${a}
|
|
27
|
+
${e}`;const u=d+(((c=e.match(/<body[^>]*>/i))==null?void 0:c[0].length)??0);return`${e.slice(0,u)}
|
|
28
|
+
${o}
|
|
29
|
+
${a}
|
|
30
|
+
${e.slice(u)}`}return`${e.slice(0,l)}
|
|
31
|
+
${o}
|
|
32
|
+
${a}
|
|
33
|
+
${e.slice(l)}`}function Xs(e,t){const r=/\s/.test(e)?`"${e}"`:e,s=(t==null?void 0:t.trim())||"system-ui, sans-serif";return`${r}, ${s}`}const Yx={vars:{},primaryFont:null,secondaryFont:null,primaryFontStack:null,secondaryFontStack:null};function ts(e){return e.replace(/^\d{1,2}-/,"").replace(/-mockup\.html$/i,"").replace(/\.html$/i,"")}const qx="\x1B[200~",Jx="\x1B[201~";function Xx(e,t=Qx){const r=e.replace(/\r\n/g,"\r").replace(/\n/g,"\r"),s=`${qx}${r}${Jx}`;return t(s),new Promise(a=>{setTimeout(()=>{t("\r"),a()},ol)})}function Qx(e){window.dispatchEvent(new CustomEvent("miniagent-send-input",{detail:e}))}function Zx({feedbackByFilename:e,mockupFilenames:t}){const r={};for(const o of t){const l=e[o];if(!l)continue;const c=typeof l.rating=="number",d=l.comment.trim().length>0;!c&&!d||(r[o]={rating:c?l.rating:null,comment:l.comment.trim()})}return Object.keys(r).length===0?"Iterate: before regenerating anything, first ask the user in the chat which of these designs (if any) are close enough to keep and just tweak — and let them know that every other design will be discarded and redesigned fresh. Wait for their reply before writing any mockup. No per-card feedback was provided, so let their answer guide what to keep vs. redesign from scratch.":`Iterate: before regenerating anything, first ask the user in the chat which of these designs (if any) are close enough to keep and just tweak — and let them know that every other design will be discarded and redesigned fresh from the feedback below. Wait for their reply before writing any mockup.
|
|
34
|
+
|
|
35
|
+
Once they answer: for designs they choose to keep, refine them in place using their specific feedback, keeping the same numeric prefix and design system. For every other design, redesign it fresh from the feedback — each redesign must directly address the specific comment and rating for that card (a pointed comment is a concrete instruction the redesign must visibly resolve; a low rating means change direction further). For fresh redesigns, weigh the rating and comment to decide whether to keep the same design system with a new layout, or swap in a different system from .codeyam/design/design_systems/ — avoid duplicating a system already used by a kept card. When you change a slot's design system, delete the old NN-*.html file before writing the new NN-<newsystem>-mockup.html so each slot has exactly one file. Keep numeric filename prefixes stable so slots don't move.
|
|
36
|
+
|
|
37
|
+
Per-card feedback (rating is 1-100 or null; comment may be empty):
|
|
38
|
+
|
|
39
|
+
\`\`\`json
|
|
40
|
+
`+JSON.stringify(r,null,2)+"\n```"}function eg(e){const t={},r={},s=e.split(`
|
|
41
|
+
`);let a=!1,o=[];for(const l of s){const c=l.trim();if(/^```/.test(c)){a=!a;continue}if(a)continue;const d=/^(#{1,6})\s+(.+)$/.exec(c);if(d){const v=d[1].length;o=o.slice(0,v-1),o[v-1]=d[2].trim();continue}if(!c.startsWith("|"))continue;const u=c.split("|").map(v=>v.trim());if(u.length<3)continue;const f=u[1].replace(/`/g,"").trim(),p=u[2].replace(/`/g,"").trim();if(!/^--[A-Za-z0-9_-]+$/.test(f)||!tg(p))continue;const m=o.filter(Boolean).join(" / "),h=Wo(m)?r:t;f in h||(h[f]=p)}return{light:t,dark:r}}function Wo(e){return/\bdark[\s-]?mode\b|\bdark\b\s*(palette|variant|theme)?/i.test(e)}function tg(e){return!!(/^#[0-9a-fA-F]{3,8}$/.test(e)||/^rgba?\(/i.test(e)||/^hsla?\(/i.test(e)||/^oklch\(/i.test(e))}const ng=["Background","Surface","Text","Primary","Secondary","Accent"],rg={Background:[/^--bg(-default|-page|-canvas|-base)?$/,/^--page(-bg)?$/,/^--canvas$/,/^--background$/,/^--light-linen$/,/^--paper$/,/^--body-bg$/,/-canvas$/,/-page-bg$/],Surface:[/^--bg-surface$/,/^--surface(-1|-elevated)?$/,/^--card(-bg)?$/,/^--bg-elevated$/,/^--marketplace-gray$/,/^--panel(-bg)?$/,/^--cream$/,/-surface$/,/-porcelain-surface$/],Text:[/^--text(-primary|-default)?$/,/^--fg(-default)?$/,/^--foreground$/,/^--ink$/,/^--pitch-black$/,/^--body-text$/,/^--ink-text$/,/-ink-text$/,/-graphite-text$/],Primary:[/^--primary$/,/^--accent(-primary)?$/,/^--brand(-primary)?$/,/^--creator-pink$/,/^--palette-1$/,/^--lime$/,/^--burgundy$/,/-amethyst-accent$/,/-accent$/],Secondary:[/^--secondary$/,/^--accent-secondary$/,/^--brand-secondary$/,/^--sunshine-yellow$/,/^--palette-2$/,/^--sage$/,/^--sky-blue$/,/-sky-blue-highlight$/,/-highlight$/],Accent:[/^--accent(-tertiary|-highlight)?$/,/^--highlight$/,/^--lime-glow$/,/^--lime-deep$/,/^--firecracker-orange$/,/^--sky-blue$/,/^--gold$/,/^--palette-3$/,/-detail$/]};function sg(e){const t=[],r=e.split(`
|
|
42
|
+
`);let s=!1,a="",o=0,l=null,c=[];for(let d=0;d<r.length;d++){const f=r[d].trim();if(!s){const p=/^(#{1,6})\s+(.+)$/.exec(f);if(p){const h=p[1].length;c=c.slice(0,h-1),c[h-1]=p[2].trim(),l=p[2].trim();continue}const m=/^```(\w*)/.exec(f);m&&(s=!0,a=m[1].toLowerCase(),o=d+1);continue}if(f==="```"){if(a==="css"||a===""){const p=r.slice(o,d).join(`
|
|
43
|
+
`);for(const m of og(p)){const h=c.filter(Boolean).join(" / "),v=ag(m.selector)||Wo(h);t.push({selector:m.selector,heading:l,isDark:v,vars:m.vars})}}s=!1,a=""}}return t}function ag(e){return/\[data-theme[~|*$^]?="?dark"?\]/.test(e)}function og(e){const t=[],r=/(:root[^\{]*?)\{([\s\S]*?)\}/g;let s;for(;(s=r.exec(e))!==null;){const a=s[1].trim(),o=s[2],l={},c=/(--[A-Za-z0-9_-]+)\s*:\s*([^;\n]+?)\s*(?:;|$)/g;let d;for(;(d=c.exec(o))!==null;){const u=d[1],f=d[2].replace(/\/\*.*?\*\//g,"").trim();f&&(l[u]=f)}Object.keys(l).length>0&&t.push({selector:a,vars:l})}return t}function ig(e,t){const r=rg[t];for(const s of Object.keys(e))for(const a of r)if(a.test(s))return{cssVar:s,value:e[s]};return{cssVar:null,value:null}}function lg(e){const t=/\[data-palette[~|*$^]?="?([^"\]]+)"?\]/.exec(e);return t?t[1].split("-").map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join(" "):null}function cg(e){if(!e)return"Default";let t=e.replace(/\(.+?\)/g,"");return t=t.replace(/\bpalette\b/i,"").replace(/\bmode\b/i,""),/\bdark\b/i.test(t)?"Default":(t=t.replace(/\bdark\b/i,""),t=t.replace(/\blight\b/i,""),t=t.trim().replace(/\s+/g," "),t||"Default")}function Qs(e){const t=ng.map(r=>{const{cssVar:s,value:a}=ig(e,r);return{label:r,cssVar:s,value:a}});return{vars:e,slots:t}}function Vo(e){const t=sg(e),r=new Map,s=new Map,a=[];for(const o of t){const c=lg(o.selector)??cg(o.heading);a.includes(c)||a.push(c),o.isDark?s.has(c)||s.set(c,o.vars):r.has(c)||r.set(c,o.vars)}if(r.size===0){const o=eg(e);o.light&&Object.keys(o.light).length>0&&(a.unshift("Default"),r.set("Default",o.light),o.dark&&Object.keys(o.dark).length>0&&s.set("Default",o.dark))}return a.map(o=>{const l=r.get(o);if(!l)return null;const c=s.get(o)??null;return{name:o,light:Qs(l),dark:c?Qs(c):null}}).filter(o=>o!==null)}function dg(e){const[t,r]=i.useState({}),s=i.useRef(!0);return i.useEffect(()=>(s.current=!0,()=>{s.current=!1}),[]),i.useEffect(()=>{if(!e)return;const a=new Set,o=e.map(l=>ts(l.filename)).filter(l=>a.has(l)?!1:(a.add(l),!(l in t)));o.length!==0&&(async()=>{var l,c;for(const d of o)try{const u=await fetch(`/api/editor-design-systems/${d}`);if(!u.ok)continue;const f=await u.json().catch(()=>null);if(!(f!=null&&f.content)){s.current&&r(h=>({...h,[d]:null}));continue}const m=((c=(l=Vo(f.content)[0])==null?void 0:l.dark)==null?void 0:c.vars)??null;s.current&&r(h=>({...h,[d]:m}))}catch{s.current&&r(u=>({...u,[d]:null}))}})()},[e,t]),t}function ug(){const[e,t]=i.useState([]);return i.useEffect(()=>{let r=!1;async function s(){try{const o=await fetch("/api/editor-mockups-history");if(!o.ok)return;const l=await o.json();r||t(Array.isArray(l)?l:[])}catch{}}s();const a=window.setInterval(s,4e3);return()=>{r=!0,window.clearInterval(a)}},[]),e}function fg({round:e}){return n.jsx("div",{"data-mockup-archived-round":!0,style:{display:"grid",gridTemplateColumns:"1fr 1fr",columnGap:"var(--spacing-lg, 16px)",rowGap:"var(--spacing-xl, 28px)"},children:e.mockups.map((t,r)=>{const s=e.feedback[t.filename],a=r+1,o=t.name.replace(/^\d{1,2}-/,"").replace(/-/g," ");return n.jsxs("div",{style:{display:"flex",flexDirection:"column",border:"1px solid var(--border-default)",borderRadius:12,overflow:"hidden",background:"var(--bg-surface)"},children:[n.jsxs("div",{style:{padding:"var(--spacing-sm, 10px) var(--spacing-md, 14px)",display:"flex",alignItems:"center",gap:6,color:"var(--text-primary)",fontSize:"var(--text-sm, 14px)"},children:[n.jsx("span",{style:{fontWeight:700,color:"var(--text-muted)"},children:String(a).padStart(2,"0")}),n.jsx("a",{href:t.url,target:"_blank",rel:"noopener noreferrer",style:{textTransform:"capitalize",fontWeight:500,color:"var(--text-primary)",textDecoration:"none"},children:o})]}),n.jsx("iframe",{src:t.url,title:t.name,sandbox:"",style:{width:"100%",aspectRatio:"1 / 1",border:"none",pointerEvents:"none",background:"var(--bg-card, #1a1a1a)"}}),s&&(typeof s.rating=="number"||s.comment.trim().length>0)&&n.jsxs("div",{style:{padding:"var(--spacing-sm, 10px) var(--spacing-md, 14px)",borderTop:"1px solid var(--border-default)",display:"flex",flexDirection:"column",gap:4,fontSize:"var(--text-xs, 12px)",color:"var(--text-secondary)"},children:[typeof s.rating=="number"&&n.jsxs("div",{children:[n.jsxs("span",{style:{color:"var(--text-muted)"},children:["Rating ·"," "]}),n.jsxs("span",{style:{color:"var(--text-primary)"},children:[s.rating,"/100"]})]}),s.comment.trim().length>0&&n.jsxs("div",{style:{lineHeight:1.4},children:[n.jsxs("span",{style:{color:"var(--text-muted)"},children:["Note ·"," "]}),n.jsx("span",{style:{color:"var(--text-primary)"},children:s.comment})]})]})]},t.filename)})})}const ns=[{family:"Archivo",category:"sans",weights:[400,500,600,700]},{family:"DM Sans",category:"sans",weights:[400,500,700]},{family:"Inter",category:"sans",weights:[400,500,600,700]},{family:"Karla",category:"sans",weights:[400,500,700]},{family:"Manrope",category:"sans",weights:[400,500,700]},{family:"Nunito",category:"sans",weights:[400,600,700]},{family:"Plus Jakarta Sans",category:"sans",weights:[400,500,700]},{family:"Public Sans",category:"sans",weights:[400,500,700]},{family:"Roboto",category:"sans",weights:[400,500,700]},{family:"Work Sans",category:"sans",weights:[400,500,700]},{family:"Cormorant Garamond",category:"serif",weights:[400,500,700]},{family:"Crimson Pro",category:"serif",weights:[400,600,700]},{family:"Fraunces",category:"serif",weights:[400,600,700]},{family:"Lora",category:"serif",weights:[400,500,700]},{family:"Merriweather",category:"serif",weights:[400,700]},{family:"Playfair Display",category:"serif",weights:[400,600,700]},{family:"Source Serif 4",category:"serif",weights:[400,600,700]},{family:"Abril Fatface",category:"display",weights:[400]},{family:"Bebas Neue",category:"display",weights:[400]},{family:"Bricolage Grotesque",category:"display",weights:[400,600,800]},{family:"Chakra Petch",category:"display",weights:[400,600,700]},{family:"Lexend",category:"display",weights:[400,500,700]},{family:"Outfit",category:"display",weights:[400,600,800]},{family:"Rubik",category:"display",weights:[400,500,700]},{family:"Space Grotesk",category:"display",weights:[400,500,700]},{family:"Syne",category:"display",weights:[400,600,800]},{family:"Unbounded",category:"display",weights:[400,600,800]},{family:"Fira Code",category:"mono",weights:[400,500,700]},{family:"IBM Plex Mono",category:"mono",weights:[400,500,600]},{family:"JetBrains Mono",category:"mono",weights:[400,500,700]},{family:"Space Mono",category:"mono",weights:[400,700]}],pg={sans:"Sans-serif",serif:"Serif",display:"Display",mono:"Monospace"};function Uo(e){const t=new Set,r=[];for(const s of e){if(!s||t.has(s))continue;t.add(s);const a=ns.find(c=>c.family===s),o=(a==null?void 0:a.weights)??[400,700],l=s.replace(/ /g,"+");r.push(`family=${l}:wght@${o.join(";")}`)}return r.length===0?"":`https://fonts.googleapis.com/css2?${r.join("&")}&display=swap`}function mg(e,t,r){const s={},a=Zs(e,r),o=Zs(t,r),l=new Map;for(const c of a)c.cssVar&&l.set(c.label,c.cssVar);for(const c of o){if(!c.value)continue;const d=l.get(c.label)??c.cssVar;d&&(s[d]=c.value)}return s}function Zs(e,t){return e?t==="dark"&&e.dark?e.dark.slots:e.light.slots:[]}function hg(e,t,r){var a,o;return t!=="dark"?r:{...((o=(a=e[0])==null?void 0:a.dark)==null?void 0:o.vars)??{},...r}}function xg(e,t){const[r,s]=i.useState({kind:"loading"});return i.useEffect(()=>{let a=!1;return s({kind:"loading"}),(async()=>{try{const[o,l]=await Promise.all([fetch(e),fetch(`/api/editor-design-systems/${t}`)]),c=await o.text();let d="";if(l.ok){const u=await l.json().catch(()=>null);d=(u==null?void 0:u.content)??""}if(a)return;s({kind:"ready",html:c,palettes:Vo(d)})}catch(o){a||s({kind:"error",message:o instanceof Error?o.message:String(o)})}})(),()=>{a=!0}},[e,t]),r}function Ko(e,t,r){i.useEffect(()=>{if(!e)return;const s=o=>{var c;const l=o.target;(c=t.current)!=null&&c.contains(l)||r()},a=o=>{o.key==="Escape"&&r()};return document.addEventListener("mousedown",s),document.addEventListener("keydown",a),()=>{document.removeEventListener("mousedown",s),document.removeEventListener("keydown",a)}},[e,t,r])}function cn(e,t,r){return{name:e,light:ea(t),dark:r?ea(r):null}}function ea(e){const t=[{label:"Background",cssVar:"--bg-default",value:e.bg},{label:"Surface",cssVar:"--bg-surface",value:e.surface},{label:"Text",cssVar:"--text-primary",value:e.text},{label:"Primary",cssVar:"--accent-primary",value:e.primary},{label:"Secondary",cssVar:"--accent-secondary",value:e.secondary},{label:"Accent",cssVar:"--accent-highlight",value:e.accent}],r={};for(const s of t)s.cssVar&&s.value&&(r[s.cssVar]=s.value);return{vars:r,slots:t}}function gg(){return[cn("Lime Bright",{bg:"#F4F4EE",surface:"#FFFFFF",text:"#0F0F0F",primary:"#D7FF63",secondary:"#9DA48F",accent:"#FF6B5C"},{bg:"#14160F",surface:"#25251F",text:"#F1EFEA",primary:"#D7FF63",secondary:"#4D5247",accent:"#FF6B5C"}),cn("Warm Cream",{bg:"#EFE9DA",surface:"#F8F3E7",text:"#3B2F1C",primary:"#C44536",secondary:"#7A9E7E",accent:"#EAA64A"},{bg:"#1F1A11",surface:"#2A2418",text:"#EFE9DA",primary:"#E07767",secondary:"#A9CBA9",accent:"#EAA64A"}),cn("Cool Mono",{bg:"#F5F6F8",surface:"#FFFFFF",text:"#101218",primary:"#2B2D3A",secondary:"#8B8FA3",accent:"#5C8DFF"},{bg:"#0E1016",surface:"#181B23",text:"#E9EBF2",primary:"#E9EBF2",secondary:"#8B8FA3",accent:"#7CA0FF"}),cn("Bold Pop",{bg:"#FFF8F0",surface:"#FFFFFF",text:"#181818",primary:"#FF3D7F",secondary:"#3DD2FF",accent:"#FFD60A"},{bg:"#161113",surface:"#1F1A1D",text:"#FFF8F0",primary:"#FF3D7F",secondary:"#3DD2FF",accent:"#FFD60A"})]}function bg({palettes:e,activeName:t,theme:r,onApply:s}){const a=(()=>{const o=new Set(e.map(c=>c.name.toLowerCase())),l=gg().filter(c=>!o.has(c.name.toLowerCase()));return[...e,...l]})();return n.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:8},children:a.map(o=>{const l=r==="dark"&&o.dark?o.dark:o.light,c=o.name===t;return n.jsx("button",{type:"button",onClick:()=>s(o),"aria-pressed":c,"aria-label":`Apply ${o.name} palette`,title:o.name,style:{padding:4,border:c?"2px solid var(--accent-active, #D7FF63)":"1px solid var(--border-default)",borderRadius:8,background:"var(--bg-elevated)",cursor:"pointer"},children:n.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, 18px)",gridTemplateRows:"repeat(2, 18px)",gap:2},children:l.slots.map(d=>n.jsx("span",{title:d.label,style:{width:18,height:18,borderRadius:4,border:"1px solid var(--border-default)",background:d.value??"transparent"}},d.label))})},o.name)})})}function vg({slots:e,values:t,onChange:r}){return n.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(2, minmax(0, 1fr))",gap:"8px 16px"},children:e.map(s=>{const a=!s.cssVar,o=s.cssVar?t[s.cssVar]??s.value??"":"",l=yg(o);return n.jsxs("div",{style:{display:"grid",gridTemplateColumns:"70px 1fr 80px",alignItems:"center",gap:6,opacity:a?.4:1,minWidth:0},children:[n.jsx("span",{style:{fontSize:"var(--text-xs, 12px)",color:"var(--text-primary)",fontWeight:500},children:s.label}),n.jsx("input",{type:"color","aria-label":`${s.label} color`,disabled:a,value:l,onChange:c=>{s.cssVar&&r(s.cssVar,c.target.value)},style:{width:"100%",height:28,border:"1px solid var(--border-default)",borderRadius:6,background:"var(--bg-elevated)",cursor:a?"not-allowed":"pointer"}}),n.jsx("input",{type:"text","aria-label":`${s.label} hex`,disabled:a,value:o,onChange:c=>{s.cssVar&&r(s.cssVar,c.target.value)},spellCheck:!1,style:{padding:"4px 6px",fontSize:"var(--text-xs, 12px)",fontFamily:"var(--font-mono, monospace)",border:"1px solid var(--border-default)",borderRadius:6,background:"var(--bg-elevated)",color:"var(--text-primary)"}})]},s.label)})})}function yg(e){const t=e.trim();return/^#[0-9a-fA-F]{6}$/.test(t)?t.toLowerCase():/^#[0-9a-fA-F]{3}$/.test(t)?`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`.toLowerCase():"#000000"}function ta({children:e}){return n.jsx("h4",{style:{margin:"0 0 8px",fontFamily:"var(--font-mono, 'IBM Plex Mono', monospace)",fontSize:11,fontWeight:500,color:"var(--text-secondary)",textTransform:"uppercase",letterSpacing:"0.08em"},children:e})}function wg({palettes:e,activeName:t,theme:r,slots:s,vars:a,onApplyPalette:o,onColorChange:l}){return n.jsxs("div",{role:"menu",style:{padding:"var(--spacing-md, 12px)",background:"var(--bg-surface)",borderBottom:"1px solid var(--border-default)",display:"flex",flexDirection:"column",gap:12},children:[n.jsxs("div",{children:[n.jsx(ta,{children:"Palettes"}),n.jsx(bg,{palettes:e,activeName:t,theme:r,onApply:o})]}),n.jsxs("div",{children:[n.jsx(ta,{children:"Individual colors"}),n.jsx(vg,{slots:s,values:a,onChange:l})]})]})}function jg({message:e}){return n.jsx("div",{style:{padding:"var(--spacing-md, 12px)",color:"var(--accent-danger, #f87171)",fontSize:"var(--text-sm, 14px)"},children:e})}let na=!1;function kg(){if(na||typeof document>"u")return;na=!0;const e=Uo(ns.map(r=>r.family));if(!e)return;const t=document.createElement("link");t.rel="stylesheet",t.href=e,t.dataset.codeyamFontPreviews="1",document.head.appendChild(t)}function ra({label:e,value:t,onChange:r,hint:s}){const[a,o]=i.useState(!1),l=i.useRef(null),c=i.useRef(null),d=i.useRef(null);i.useEffect(()=>{kg()},[]);const u=i.useCallback(()=>o(!1),[]);Ko(a,d,u);const f={sans:[],serif:[],display:[],mono:[]};for(const p of ns)f[p.category].push(p);return n.jsxs("div",{ref:d,style:{display:"flex",flexDirection:"column",gap:4,fontSize:"var(--text-xs, 12px)",color:"var(--text-primary)",position:"relative"},children:[n.jsx("span",{style:{fontFamily:"var(--font-mono, 'IBM Plex Mono', monospace)",fontSize:11,fontWeight:500,letterSpacing:"0.08em",textTransform:"uppercase",color:"var(--text-secondary)"},children:e}),s&&n.jsx("span",{style:{color:"var(--text-secondary)",fontStyle:"italic"},children:s}),n.jsxs("button",{ref:l,type:"button","aria-haspopup":"listbox","aria-expanded":a,onClick:()=>o(p=>!p),style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:6,padding:"6px 10px",background:"var(--bg-elevated)",color:"var(--text-primary)",border:"1px solid var(--border-default)",borderRadius:6,fontSize:"var(--text-sm, 14px)",fontFamily:t?`"${t}", system-ui, sans-serif`:"inherit",cursor:"pointer",textAlign:"left"},children:[n.jsx("span",{children:t??"System default"}),n.jsx("span",{"aria-hidden":!0,style:{opacity:.6},children:"▾"})]}),a&&n.jsxs("div",{ref:c,role:"listbox",style:{position:"absolute",top:"100%",left:0,right:0,marginTop:4,zIndex:20,background:"var(--bg-surface)",border:"1px solid var(--border-default)",borderRadius:8,boxShadow:"0 8px 24px rgba(0,0,0,0.12)",maxHeight:320,overflowY:"auto",padding:4},children:[n.jsx(sa,{family:null,label:"System default",isActive:t===null,onPick:()=>{r(null),o(!1)}}),Object.keys(f).map(p=>n.jsxs("div",{children:[n.jsx("div",{style:{padding:"6px 10px 2px",fontSize:"var(--text-xs, 11px)",color:"var(--text-secondary)",textTransform:"uppercase",letterSpacing:"0.06em",fontWeight:700},children:pg[p]}),f[p].map(m=>n.jsx(sa,{family:m.family,label:m.family,isActive:t===m.family,onPick:()=>{r(m.family),o(!1)}},m.family))]},p))]})]})}function sa({family:e,label:t,isActive:r,onPick:s}){return n.jsx("button",{type:"button",role:"option","aria-selected":r,onClick:s,style:{display:"block",width:"100%",padding:"8px 10px",background:r?"var(--bg-elevated)":"transparent",color:"var(--text-primary)",border:"none",borderRadius:4,fontSize:16,fontFamily:e?`"${e}", system-ui, sans-serif`:"inherit",textAlign:"left",cursor:"pointer"},children:t})}function Ng({primaryFont:e,secondaryFont:t,onPrimaryChange:r,onSecondaryChange:s}){return n.jsxs("div",{role:"menu",style:{padding:"var(--spacing-md, 12px)",background:"var(--bg-surface)",borderBottom:"1px solid var(--border-default)",display:"grid",gridTemplateColumns:"1fr 1fr",gap:16},children:[n.jsx(ra,{label:"Headings",value:t,onChange:s}),n.jsx(ra,{label:"Body text",value:e,onChange:r})]})}function Go(e){const t=/<meta\b[^>]*>/gi;let r;for(;(r=t.exec(e))!==null;){const s=r[0];if(!/name=["']codeyam-viewport["']/i.test(s))continue;const a=/content=["']([^"']+)["']/i.exec(s);if(!a)continue;const o=a[1].toLowerCase().trim();return o==="desktop"||o==="tablet"||o==="mobile"?o:null}return null}function Cg(e,t){const r=Object.entries(t).filter(([,o])=>o&&o.trim());if(r.length===0)return e;const s=`<style data-codeyam-dark="1">:root {
|
|
44
|
+
`+r.map(([o,l])=>` ${o}: ${l};`).join(`
|
|
45
|
+
`)+`
|
|
46
|
+
}</style>`,a=e.search(/<\/head\s*>/i);return a===-1?`${s}
|
|
47
|
+
${e}`:`${e.slice(0,a)}
|
|
48
|
+
${s}
|
|
49
|
+
${e.slice(a)}`}function Sg({html:e,srcDoc:t,theme:r,mockupUrl:s,mockupName:a}){const o=Go(e)??"desktop",l=o==="mobile"||o==="tablet",c=o==="mobile"?390:o==="tablet"?834:null;return n.jsx("div",{style:{flex:1,minHeight:0,overflow:"auto",background:l?"#1a1a1a":"white",backgroundImage:l?"radial-gradient(circle, rgba(255,255,255,0.07) 1px, transparent 1px)":void 0,backgroundSize:l?"12px 12px":void 0,display:"flex",justifyContent:"center"},children:n.jsx("iframe",{title:`Customize preview: ${a}`,srcDoc:t,sandbox:"",style:{width:l&&c?`${c}px`:"100%",height:"100%",minHeight:800,border:"none",background:"white",flexShrink:0}},`${s}-${r}`)})}function Yo({theme:e,onToggle:t,size:r=28}){return n.jsx("button",{type:"button",onClick:t,"aria-label":e==="light"?"Switch to dark mode":"Switch to light mode","aria-pressed":e==="dark",title:e==="light"?"Dark mode":"Light mode",style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:r,height:r,background:"var(--bg-card, #1a1a1a)",border:"1px solid var(--border-default)",borderRadius:6,cursor:"pointer",color:"var(--text-primary)",padding:0,fontSize:14,lineHeight:1},children:e==="light"?"☾":"☀"})}function dn(e){return{height:28,padding:"0 8px",background:e?"#555":"#3a3a3a",color:e?"#ffffff":"#d1d5db",border:"none",borderRadius:4,fontSize:11,fontFamily:"var(--font-mono, 'IBM Plex Mono', monospace)",fontWeight:400,letterSpacing:"0.04em",cursor:"pointer",display:"inline-flex",alignItems:"center",gap:4}}function Eg({systemName:e,openMenu:t,theme:r,hasDark:s,saving:a,toolbarRef:o,onBack:l,onToggleMenu:c,onToggleTheme:d,onReset:u,onSave:f}){return n.jsxs("div",{ref:o,style:{display:"flex",alignItems:"center",gap:8,padding:"0 8px",height:40,borderBottom:"1px solid #3d3d3d",background:"#2d2d2d",flexWrap:"nowrap"},children:[n.jsx("button",{type:"button",onClick:l,"aria-label":"Back to mockups",style:{...dn(!1),background:"transparent"},children:"← Back"}),n.jsxs("span",{style:{color:"#9ca3af",fontSize:13,fontFamily:"'IBM Plex Sans', system-ui, sans-serif",fontWeight:400,marginRight:4},children:["Customize: ",e]}),n.jsxs("button",{type:"button","aria-haspopup":"menu","aria-expanded":t==="fonts",onClick:()=>c("fonts"),style:dn(t==="fonts"),children:["Fonts ",n.jsx("span",{"aria-hidden":!0,style:{opacity:.7},children:"▾"})]}),n.jsxs("button",{type:"button","aria-haspopup":"menu","aria-expanded":t==="colors",onClick:()=>c("colors"),style:dn(t==="colors"),children:["Colors ",n.jsx("span",{"aria-hidden":!0,style:{opacity:.7},children:"▾"})]}),n.jsx("button",{type:"button",onClick:u,style:{...dn(!1),background:"transparent",color:"#9ca3af"},children:"Reset"}),n.jsx("div",{style:{flex:1}}),s&&n.jsx(Yo,{theme:r,onToggle:d,size:28}),n.jsx("button",{type:"button",onClick:f,disabled:a,style:{height:28,padding:"0 10px",background:"var(--accent-active, #D7FF63)",color:"var(--text-on-accent, #0F0F0F)",border:"none",borderRadius:4,fontSize:11,fontFamily:"var(--font-mono, 'IBM Plex Mono', monospace)",fontWeight:500,letterSpacing:"0.04em",cursor:a?"wait":"pointer",opacity:a?.7:1},children:a?"SAVING…":"SAVE"})]})}function Rg({mockup:e,systemName:t,initial:r,onBack:s,onSave:a,saving:o=!1}){var R;const l=xg(e.url,t),[c,d]=i.useState(r),[u,f]=i.useState(null),[p,m]=i.useState("light"),[h,v]=i.useState(null),g=i.useRef(null),y=i.useCallback(()=>v(null),[]);Ko(h!==null,g,y);const j=i.useMemo(()=>{const S=[];return c.primaryFont&&S.push(c.primaryFont),c.secondaryFont&&S.push(c.secondaryFont),S.length===0?null:Uo(S)},[c.primaryFont,c.secondaryFont]),b=i.useMemo(()=>l.kind!=="ready"?c.vars:hg(l.palettes,p,c.vars),[l,c.vars,p]),x=i.useMemo(()=>l.kind!=="ready"?"":Gx(l.html,{...c,vars:b,fontsHref:j}),[l,c,b,j]),w=i.useCallback(S=>{f(S.name);const D=l.kind==="ready"?l.palettes[0]:void 0,P=mg(D,S,p);d(I=>({...I,vars:{...I.vars,...P}}))},[l,p]),k=i.useCallback((S,D)=>{f(null),d(P=>({...P,vars:{...P.vars,[S]:D}}))},[]),C=i.useCallback(()=>{d({vars:{},primaryFont:null,secondaryFont:null,primaryFontStack:null,secondaryFontStack:null}),f(null)},[]),N=i.useMemo(()=>{if(l.kind!=="ready"||l.palettes.length===0)return[{label:"Background",cssVar:"--bg-default",value:null},{label:"Surface",cssVar:"--bg-surface",value:null},{label:"Text",cssVar:"--text-primary",value:null},{label:"Primary",cssVar:"--accent-primary",value:null},{label:"Secondary",cssVar:"--accent-secondary",value:null},{label:"Accent",cssVar:"--accent-highlight",value:null}];const S=l.palettes[0];return p==="dark"&&S.dark?S.dark.slots:S.light.slots},[l,p]),E=l.kind==="ready"&&!!((R=l.palettes[0])!=null&&R.dark);return n.jsxs("div",{"data-testid":"mockup-customize-view",className:"flex-1 flex flex-col min-w-0",style:{overflow:"hidden",position:"relative"},children:[n.jsxs("div",{ref:g,children:[n.jsx(Eg,{systemName:t,openMenu:h,theme:p,hasDark:E,saving:o,toolbarRef:{current:null},onBack:()=>s(c),onToggleMenu:S=>v(D=>D===S?null:S),onToggleTheme:()=>m(S=>S==="light"?"dark":"light"),onReset:C,onSave:()=>a(c)}),h==="fonts"&&n.jsx(Ng,{primaryFont:c.primaryFont,secondaryFont:c.secondaryFont,onPrimaryChange:S=>d(D=>({...D,primaryFont:S})),onSecondaryChange:S=>d(D=>({...D,secondaryFont:S}))}),h==="colors"&&n.jsx(wg,{palettes:l.kind==="ready"?l.palettes:[],activeName:u,theme:p,slots:N,vars:c.vars,onApplyPalette:w,onColorChange:k})]}),l.kind==="error"&&n.jsx(jg,{message:l.message}),l.kind==="loading"?n.jsx("div",{style:{flex:1,minHeight:0,overflow:"auto",background:"white",padding:"var(--spacing-lg, 16px)",color:"var(--text-secondary)"},children:"Loading mockup…"}):l.kind==="ready"?n.jsx(Sg,{html:l.html,srcDoc:x,theme:p,mockupUrl:e.url,mockupName:e.name}):null]})}const Tg={desktop:{w:1440,h:900},tablet:{w:834,h:1112},mobile:{w:390,h:844}},aa="desktop",Pg=1280,Dg=1280,Ag="#1a1a1a",Fg="radial-gradient(circle, rgba(255,255,255,0.07) 1px, transparent 1px)",Lg="12px 12px";function Mg(e,t,r,s){if(e<=0||t<=0||r<=0||s<=0)return{scale:0,offsetX:0,offsetY:0};const a=Math.min(e/r,t/s),o=r*a,l=s*a;return{scale:a,offsetX:Math.max(0,(e-o)/2),offsetY:Math.max(0,(t-l)/2)}}function Ig(){return n.jsxs("svg",{width:"11",height:"11",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[n.jsx("path",{d:"M4.5 2.5h-2v7h7v-2"}),n.jsx("path",{d:"M7 2.5h2.5V5"}),n.jsx("path",{d:"M9.5 2.5L5.5 6.5"})]})}function $g({displayNumber:e,formattedName:t,theme:r,showThemeToggle:s,busy:a,openInNewTabUrl:o,onToggleTheme:l,onChoose:c,onCustomize:d}){return n.jsxs("div",{style:{padding:"var(--spacing-sm, 10px) var(--spacing-md, 14px)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},children:[n.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6,color:"var(--text-primary)",fontSize:"var(--text-sm, 14px)",minWidth:0},children:[n.jsx("span",{style:{fontWeight:700,color:"var(--text-muted)"},children:String(e).padStart(2,"0")}),o?n.jsxs("a",{href:o,target:"_blank",rel:"noopener noreferrer","aria-label":`Open ${t} in new tab`,title:"Open in new tab",onClick:u=>u.stopPropagation(),style:{display:"inline-flex",alignItems:"center",gap:4,minWidth:0,color:"var(--text-primary)",textDecoration:"none"},children:[n.jsx("span",{style:{textTransform:"capitalize",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t}),n.jsx("span",{style:{display:"inline-flex",alignItems:"center",color:"var(--text-muted)",lineHeight:1,flexShrink:0},children:n.jsx(Ig,{})})]}):n.jsx("span",{style:{textTransform:"capitalize",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t})]}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"var(--spacing-xs, 8px)",flexShrink:0},children:[s&&n.jsx(Yo,{theme:r,onToggle:l}),n.jsx("button",{type:"button",onClick:d,disabled:a,style:{padding:"6px 14px",background:"var(--bg-card, #1a1a1a)",color:"var(--text-primary)",border:"1px solid var(--border-default)",borderRadius:6,fontSize:"var(--text-xs, 12px)",fontWeight:500,cursor:a?"wait":"pointer",opacity:a?.6:1},children:"Customize"}),n.jsx("button",{type:"button",onClick:c,disabled:a,style:{padding:"6px 14px",background:"var(--accent-active, #7c3aed)",color:"var(--text-on-accent, #fff)",border:"1px solid transparent",borderRadius:6,fontSize:"var(--text-xs, 12px)",fontWeight:600,cursor:a?"wait":"pointer",opacity:a?.6:1,boxShadow:a?"none":"0 0 0 3px color-mix(in srgb, var(--accent-active, #7c3aed) 30%, transparent), 0 2px 6px color-mix(in srgb, var(--accent-active, #7c3aed) 40%, transparent)"},children:"Select"})]})]})}function Og({html:e,url:t,title:r,viewport:s,theme:a,darkVars:o}){const l=i.useRef(null),[c,d]=i.useState(0),[u,f]=i.useState(0),p=Tg[s];i.useEffect(()=>{const C=l.current;if(!C)return;const N=()=>{const R=C.clientWidth,S=C.clientHeight;R>0&&d(R),S>0&&f(S)};if(N(),typeof ResizeObserver>"u")return;const E=new ResizeObserver(N);return E.observe(C),()=>E.disconnect()},[]);const{scale:m,offsetX:h,offsetY:v}=Mg(c,u,p.w,p.h),g=e&&a==="dark"&&o?Cg(e,o):e,[y,j]=i.useState(!1),[b,x]=i.useState(!1);i.useEffect(()=>{j(!1),x(!1);const C=window.setTimeout(()=>x(!0),700);return()=>window.clearTimeout(C)},[g,t,a]);const w=e===null||!y||!b,k=()=>window.open(t,"_blank","noopener,noreferrer");return n.jsxs("div",{ref:l,onClick:k,style:{position:"relative",width:"100%",aspectRatio:`${Pg} / ${Dg}`,overflow:"hidden",cursor:"pointer",backgroundColor:Ag,backgroundImage:Fg,backgroundSize:Lg},children:[e!==null&&n.jsx("iframe",{src:g?void 0:t,srcDoc:g??void 0,title:r,sandbox:"",onLoad:()=>j(!0),style:{width:p.w,height:p.h,border:"none",background:"white",transform:m>0?`scale(${m})`:"scale(0)",transformOrigin:"top left",pointerEvents:"none",position:"absolute",top:v,left:h,visibility:y?"visible":"hidden"}},a),w&&n.jsx(Bg,{})]})}function Bg(){return n.jsxs("div",{"aria-label":"Loading mockup",style:{position:"absolute",inset:0,padding:"10%",display:"flex",flexDirection:"column",gap:"5%"},children:[n.jsx("style",{children:`
|
|
50
|
+
@keyframes mockup-skeleton-shimmer {
|
|
51
|
+
0% { background-position: -200% 0; }
|
|
52
|
+
100% { background-position: 200% 0; }
|
|
53
|
+
}
|
|
54
|
+
`}),n.jsx(ut,{widthPct:45,heightPx:14}),n.jsx(ut,{widthPct:70,heightPx:10}),n.jsx("div",{style:{height:"6%"}}),n.jsx(ut,{widthPct:100,heightPx:32}),n.jsxs("div",{style:{display:"flex",gap:"4%"},children:[n.jsx(ut,{widthPct:48,heightPx:48}),n.jsx(ut,{widthPct:48,heightPx:48})]}),n.jsx(ut,{widthPct:88,heightPx:10}),n.jsx(ut,{widthPct:60,heightPx:10})]})}function ut({widthPct:e,heightPx:t}){return n.jsx("div",{style:{width:`${e}%`,height:t,borderRadius:4,background:"linear-gradient(90deg, rgba(255,255,255,0.04) 0%, rgba(255,255,255,0.12) 45%, rgba(255,255,255,0.04) 90%)",backgroundSize:"200% 100%",animation:"mockup-skeleton-shimmer 1.6s linear infinite"}})}const _g=`
|
|
55
|
+
.mockup-feedback-slider {
|
|
56
|
+
-webkit-appearance: none;
|
|
57
|
+
appearance: none;
|
|
58
|
+
background: transparent;
|
|
59
|
+
height: 18px;
|
|
60
|
+
padding: 0;
|
|
61
|
+
margin: 0;
|
|
62
|
+
cursor: pointer;
|
|
63
|
+
}
|
|
64
|
+
.mockup-feedback-slider:focus { outline: none; }
|
|
65
|
+
.mockup-feedback-slider::-webkit-slider-runnable-track {
|
|
66
|
+
height: 4px;
|
|
67
|
+
background: #4a4a4a;
|
|
68
|
+
border-radius: 2px;
|
|
69
|
+
}
|
|
70
|
+
.mockup-feedback-slider::-moz-range-track {
|
|
71
|
+
height: 4px;
|
|
72
|
+
background: #4a4a4a;
|
|
73
|
+
border-radius: 2px;
|
|
74
|
+
border: none;
|
|
75
|
+
}
|
|
76
|
+
.mockup-feedback-slider::-moz-range-progress {
|
|
77
|
+
background: #4a4a4a;
|
|
78
|
+
height: 4px;
|
|
79
|
+
border-radius: 2px;
|
|
80
|
+
}
|
|
81
|
+
.mockup-feedback-slider::-webkit-slider-thumb {
|
|
82
|
+
-webkit-appearance: none;
|
|
83
|
+
appearance: none;
|
|
84
|
+
width: 14px;
|
|
85
|
+
height: 14px;
|
|
86
|
+
border-radius: 50%;
|
|
87
|
+
background: #5a5a5a;
|
|
88
|
+
border: none;
|
|
89
|
+
margin-top: -5px;
|
|
90
|
+
cursor: pointer;
|
|
91
|
+
transition: background 120ms ease;
|
|
92
|
+
}
|
|
93
|
+
.mockup-feedback-slider::-moz-range-thumb {
|
|
94
|
+
width: 14px;
|
|
95
|
+
height: 14px;
|
|
96
|
+
border-radius: 50%;
|
|
97
|
+
background: #5a5a5a;
|
|
98
|
+
border: none;
|
|
99
|
+
cursor: pointer;
|
|
100
|
+
transition: background 120ms ease;
|
|
101
|
+
}
|
|
102
|
+
.mockup-feedback-slider[data-rated="true"]::-webkit-slider-runnable-track {
|
|
103
|
+
/* Two stacked layers: a grey overlay that masks the right portion of
|
|
104
|
+
* the track from progress% onward, and a full-width red-amber-keylime
|
|
105
|
+
* rainbow underneath. The visible filled portion is the slice of the
|
|
106
|
+
* rainbow up to the thumb position. */
|
|
107
|
+
background:
|
|
108
|
+
linear-gradient(
|
|
109
|
+
to right,
|
|
110
|
+
transparent 0%,
|
|
111
|
+
transparent var(--mockup-feedback-progress, 0%),
|
|
112
|
+
#4a4a4a var(--mockup-feedback-progress, 0%),
|
|
113
|
+
#4a4a4a 100%
|
|
114
|
+
),
|
|
115
|
+
linear-gradient(
|
|
116
|
+
to right,
|
|
117
|
+
rgb(239, 68, 68) 0%,
|
|
118
|
+
rgb(251, 191, 36) 50%,
|
|
119
|
+
rgb(215, 255, 99) 100%
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
.mockup-feedback-slider[data-rated="true"]::-moz-range-track {
|
|
123
|
+
background: linear-gradient(
|
|
124
|
+
to right,
|
|
125
|
+
rgb(239, 68, 68) 0%,
|
|
126
|
+
rgb(251, 191, 36) 50%,
|
|
127
|
+
rgb(215, 255, 99) 100%
|
|
128
|
+
);
|
|
129
|
+
}
|
|
130
|
+
.mockup-feedback-slider[data-rated="true"]::-moz-range-progress {
|
|
131
|
+
/* Firefox draws ::-moz-range-progress on top of ::-moz-range-track,
|
|
132
|
+
* so the progress layer would otherwise hide the rainbow below it.
|
|
133
|
+
* Leave it transparent so the rainbow shows through up to the value. */
|
|
134
|
+
background: transparent;
|
|
135
|
+
}
|
|
136
|
+
.mockup-feedback-slider[data-rated="true"]::-webkit-slider-thumb {
|
|
137
|
+
background: var(--mockup-feedback-color, var(--accent-active, #D7FF63));
|
|
138
|
+
}
|
|
139
|
+
.mockup-feedback-slider[data-rated="true"]::-moz-range-thumb {
|
|
140
|
+
background: var(--mockup-feedback-color, var(--accent-active, #D7FF63));
|
|
141
|
+
}
|
|
142
|
+
`,zg=`
|
|
143
|
+
.mockup-feedback-comment {
|
|
144
|
+
width: 100%;
|
|
145
|
+
padding: var(--spacing-sm, 8px) var(--spacing-sm, 10px);
|
|
146
|
+
background: var(--bg-card, #1a1a1a);
|
|
147
|
+
color: var(--text-primary);
|
|
148
|
+
border: 1px solid var(--border-default);
|
|
149
|
+
border-radius: 6px;
|
|
150
|
+
font-size: var(--text-xs, 12px);
|
|
151
|
+
line-height: 1.4;
|
|
152
|
+
resize: vertical;
|
|
153
|
+
box-sizing: border-box;
|
|
154
|
+
min-height: 56px;
|
|
155
|
+
outline: none;
|
|
156
|
+
}
|
|
157
|
+
.mockup-feedback-comment:focus,
|
|
158
|
+
.mockup-feedback-comment:focus-visible {
|
|
159
|
+
border-color: var(--text-primary, #ffffff);
|
|
160
|
+
outline: none;
|
|
161
|
+
box-shadow: 0 0 0 1px var(--text-primary, #ffffff);
|
|
162
|
+
}
|
|
163
|
+
`;function Hg({comment:e,onCommentChange:t}){return n.jsxs(n.Fragment,{children:[n.jsx("style",{children:zg}),n.jsx("textarea",{value:e,onChange:r=>t(r.target.value),placeholder:"What do you like or would like to change? (optional)",rows:3,className:"mockup-feedback-comment"})]})}const qo=[239,68,68],vr=[251,191,36],Jo=[215,255,99];function Wg(e){const t=Math.max(1,Math.min(100,e));let r,s,a;t<=50?(r=qo,s=vr,a=(t-1)/49):(r=vr,s=Jo,a=(t-50)/50);const o=Math.round(r[0]+(s[0]-r[0])*a),l=Math.round(r[1]+(s[1]-r[1])*a),c=Math.round(r[2]+(s[2]-r[2])*a);return`rgb(${o}, ${l}, ${c})`}`${qo.join(", ")}${vr.join(", ")}${Jo.join(", ")}`;function Vg(){return n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[n.jsx("path",{d:"M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3z"}),n.jsx("path",{d:"M17 2h2.5a2.5 2.5 0 0 1 2.5 2.5v6A2.5 2.5 0 0 1 19.5 13H17"})]})}function Ug(){return n.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[n.jsx("path",{d:"M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3z"}),n.jsx("path",{d:"M7 22H4.5a2.5 2.5 0 0 1-2.5-2.5v-6A2.5 2.5 0 0 1 4.5 11H7"})]})}function Kg({rating:e,onRatingChange:t}){const r=e!=null,s=r&&e<=33,a=r&&e>=67;return n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"var(--spacing-sm, 10px)"},children:[n.jsx("span",{"aria-hidden":"true",style:{color:s?"var(--text-primary)":"var(--text-muted)",display:"inline-flex",alignItems:"center"},children:n.jsx(Vg,{})}),n.jsx("input",{type:"range",min:1,max:100,step:1,value:e??50,onPointerDown:()=>{r||t(50)},onChange:o=>t(Number(o.target.value)),"aria-label":"Rate this mockup from 1 to 100",className:"mockup-feedback-slider","data-rated":r?"true":"false",style:{flex:1,"--mockup-feedback-progress":`${e??0}%`,"--mockup-feedback-color":r?Wg(e):"var(--accent-active, #D7FF63)"}}),n.jsx("span",{"aria-hidden":"true",style:{color:a?"var(--text-primary)":"var(--text-muted)",display:"inline-flex",alignItems:"center"},children:n.jsx(Ug,{})})]})}const Gg={rating:null,comment:""};function Yg({value:e,onChange:t}){return n.jsxs("div",{"data-mockup-feedback":!0,style:{padding:"var(--spacing-sm, 10px) var(--spacing-md, 14px)",borderTop:"1px solid var(--border-default)",display:"flex",flexDirection:"column",gap:"var(--spacing-sm, 10px)",background:"var(--bg-surface)"},children:[n.jsx("style",{children:_g}),n.jsx(Kg,{rating:e.rating,onRatingChange:r=>t({...e,rating:r})}),n.jsx(Hg,{comment:e.comment,onCommentChange:r=>t({...e,comment:r})})]})}function qg({mockup:e,displayNumber:t,onChoose:r,onCustomize:s,busy:a=!1,darkVars:o=null,feedback:l,onFeedbackChange:c}){const[d,u]=i.useState(null),[f,p]=i.useState(aa),[m,h]=i.useState("light");i.useEffect(()=>{let g=!1;return(async()=>{try{const y=await fetch(e.url);if(!y.ok)return;const j=await y.text();if(g)return;u(j),p(Go(j)??aa)}catch{}})(),()=>{g=!0}},[e.url]);const v=e.name.replace(/^\d{1,2}-/,"").replace(/-/g," ");return n.jsxs("div",{style:{position:"relative",display:"flex",flexDirection:"column",border:"1px solid var(--border-default)",borderRadius:12,overflow:"hidden",background:"var(--bg-surface)"},children:[n.jsx($g,{displayNumber:t,formattedName:v,theme:m,showThemeToggle:!!o,busy:a,openInNewTabUrl:e.url,onToggleTheme:()=>h(g=>g==="light"?"dark":"light"),onChoose:()=>r==null?void 0:r(e),onCustomize:()=>s==null?void 0:s(e)}),n.jsx(Og,{html:d,url:e.url,title:e.name,viewport:f,theme:m,darkVars:o}),c&&n.jsx(Yg,{value:l??Gg,onChange:c})]})}function ft({widthPct:e,heightPx:t,variant:r="surface"}){const s=r==="overlay"?"linear-gradient(90deg, rgba(255,255,255,0.04) 0%, rgba(255,255,255,0.12) 45%, rgba(255,255,255,0.04) 90%)":"linear-gradient(90deg, var(--bg-surface) 0%, var(--border-default) 45%, var(--bg-surface) 90%)";return n.jsx("div",{style:{width:`${e}%`,height:t,borderRadius:4,background:s,backgroundSize:"200% 100%",animation:"mockup-skeleton-shimmer 1.6s linear infinite",opacity:r==="surface"?.85:1}})}function Jg({displayNumber:e}){return n.jsxs("div",{"data-mockup-placeholder":!0,"aria-label":"The AI is designing this mockup",style:{position:"relative",display:"flex",flexDirection:"column",border:"1px solid var(--border-default)",borderRadius:12,overflow:"hidden",background:"var(--bg-surface)"},children:[n.jsx("style",{children:`
|
|
164
|
+
@keyframes mockup-skeleton-shimmer {
|
|
165
|
+
0% { background-position: -200% 0; }
|
|
166
|
+
100% { background-position: 200% 0; }
|
|
167
|
+
}
|
|
168
|
+
`}),n.jsxs("div",{style:{position:"relative",width:"100%",aspectRatio:"1 / 1",overflow:"hidden",background:"var(--bg-elevated, #141414)",padding:"10%",display:"flex",flexDirection:"column",gap:"5%"},children:[n.jsx(ft,{widthPct:45,heightPx:14}),n.jsx(ft,{widthPct:70,heightPx:10}),n.jsx("div",{style:{height:"6%"}}),n.jsx(ft,{widthPct:100,heightPx:32}),n.jsxs("div",{style:{display:"flex",gap:"4%"},children:[n.jsx(ft,{widthPct:48,heightPx:48}),n.jsx(ft,{widthPct:48,heightPx:48})]}),n.jsx(ft,{widthPct:88,heightPx:10}),n.jsx(ft,{widthPct:60,heightPx:10})]}),n.jsx("div",{style:{padding:"var(--spacing-sm, 8px) var(--spacing-md, 12px)",display:"flex",alignItems:"center",gap:"var(--spacing-sm, 8px)"},children:n.jsxs("span",{style:{display:"inline-flex",alignItems:"baseline",gap:6,color:"var(--text-primary)",fontSize:"var(--text-sm, 14px)",minWidth:0},children:[n.jsx("span",{style:{fontWeight:700,color:"var(--text-muted)"},children:String(e).padStart(2,"0")}),n.jsx("span",{style:{color:"var(--text-secondary)",fontStyle:"italic"},"data-testid":"mockup-placeholder-label",children:"The AI is designing this mockup…"})]})})]})}function Xg({slots:e,darkVarsBySystem:t,busyFilename:r,feedbackByFilename:s,onFeedbackChange:a,onChoose:o,onCustomize:l}){return n.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",columnGap:"var(--spacing-lg, 16px)",rowGap:"var(--spacing-xl, 28px)"},children:e.map(c=>c.mockup?n.jsx(qg,{mockup:c.mockup,displayNumber:c.number,onChoose:o,onCustomize:l,busy:r===c.mockup.filename,darkVars:t[ts(c.mockup.filename)]??null,feedback:s==null?void 0:s[c.mockup.filename],onFeedbackChange:a?d=>a(c.mockup.filename,d):void 0},`mockup-${c.number}`):n.jsx(Jg,{displayNumber:c.number},`placeholder-${c.number}`))})}function Qg(){return n.jsxs("div",{style:{padding:"var(--spacing-lg, 16px)"},children:[n.jsx("h3",{style:{margin:0,color:"var(--text-primary)"},children:"Design exploration"}),n.jsx("p",{style:{color:"var(--text-secondary)",fontSize:"var(--text-sm, 14px)",lineHeight:1.5,marginTop:"var(--spacing-sm, 8px)"},children:"Generating mockups — they'll appear here as the agent writes them."})]})}function Zg(){return n.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[n.jsx("path",{d:"M9 18h6"}),n.jsx("path",{d:"M10 22h4"}),n.jsx("path",{d:"M12 2a7 7 0 0 0-4 12.74V17a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1v-2.26A7 7 0 0 0 12 2z"})]})}function eb(){return n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[n.jsx("path",{d:"M18 6L6 18"}),n.jsx("path",{d:"M6 6l12 12"})]})}function tb({onDismiss:e}){return n.jsxs("div",{role:"note","data-mockup-info-banner":!0,style:{display:"flex",alignItems:"flex-start",gap:"var(--spacing-md, 14px)",padding:"var(--spacing-md, 14px) var(--spacing-md, 16px)",border:"1px solid var(--accent-active, #D7FF63)",borderRadius:12,background:"rgba(215, 255, 99, 0.04)"},children:[n.jsx("span",{"aria-hidden":"true",style:{color:"var(--accent-active, #D7FF63)",display:"inline-flex",alignItems:"center",flexShrink:0,paddingTop:1},children:n.jsx(Zg,{})}),n.jsxs("p",{style:{flex:1,margin:0,color:"var(--text-primary)",fontSize:"var(--text-sm, 14px)",lineHeight:1.5},children:[n.jsx("strong",{style:{fontWeight:700},children:"Not sure which to pick?"})," ","Rate these designs and jot a quick note. We'll refine them into a fresh round — no need to choose yet."]}),n.jsx("button",{type:"button",onClick:e,"aria-label":"Dismiss tip",title:"Dismiss",style:{flexShrink:0,padding:4,background:"transparent",color:"var(--text-muted)",border:"none",cursor:"pointer",display:"inline-flex",alignItems:"center",justifyContent:"center"},children:n.jsx(eb,{})})]})}function nb(){return n.jsxs("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[n.jsx("path",{d:"M21 12a9 9 0 1 1-3.36-7"}),n.jsx("polyline",{points:"21 4 21 10 15 10"})]})}function rb({feedbackCount:e,busy:t,onIterate:r}){const s=e===0?"Add a rating or note above, then iterate.":e===1?"1 card has feedback — iterate to refresh the round.":`${e} cards have feedback — iterate to refresh the round.`;return n.jsxs("div",{style:{marginTop:"var(--spacing-md, 12px)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:"var(--spacing-md, 16px)",padding:"var(--spacing-md, 16px) var(--spacing-lg, 20px)",border:"1px solid var(--border-default)",borderRadius:12,background:"var(--bg-card, #1a1a1a)"},children:[n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"var(--spacing-md, 14px)",minWidth:0},children:[n.jsx("span",{"aria-hidden":"true",style:{color:"var(--accent-active, #D7FF63)",display:"inline-flex",alignItems:"center",flexShrink:0},children:n.jsx(nb,{})}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",minWidth:0},children:[n.jsx("span",{style:{color:"var(--text-primary)",fontSize:"var(--text-sm, 14px)",fontWeight:600,lineHeight:1.3},children:"Ready for the next round?"}),n.jsx("span",{style:{color:"var(--text-muted)",fontSize:"var(--text-xs, 12px)",lineHeight:1.4,marginTop:2},children:s})]})]}),n.jsx("button",{type:"button",onClick:r,disabled:t,"data-mockup-iterate":!0,style:{flexShrink:0,padding:"10px 22px",background:"var(--accent-active, #D7FF63)",color:"var(--text-on-accent, #0F0F0F)",border:"1px solid var(--accent-active, #D7FF63)",borderRadius:8,fontSize:"var(--text-sm, 14px)",fontWeight:600,cursor:t?"wait":"pointer",opacity:t?.6:1},children:t?"Sending…":"Iterate"})]})}function sb(){return n.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:n.jsx("polyline",{points:"15 18 9 12 15 6"})})}function ab(){return n.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:n.jsx("polyline",{points:"9 18 15 12 9 6"})})}function ob({archivedRoundsNewestFirst:e,selected:t,onSelect:r}){if(e.length===0)return null;const a=[...[...e].reverse(),"current"],o=a.length,l=a.indexOf(t),c=l===-1?o-1:l,d=t==="current",u=c>0,f=c<o-1,p=d?`Round ${o} of ${o} · Current`:`Round ${c+1} of ${o} · Archived`;return n.jsxs("div",{"data-mockup-round-pager":!0,style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"var(--spacing-sm, 10px)",padding:"var(--spacing-xs, 6px) var(--spacing-md, 14px)",border:"1px solid var(--border-default)",borderRadius:10,background:"var(--bg-card, #1a1a1a)"},children:[n.jsx(oa,{ariaLabel:"Previous round",disabled:!u,onClick:()=>u&&r(a[c-1]),icon:n.jsx(sb,{})}),n.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"var(--spacing-md, 12px)",fontSize:"var(--text-xs, 12px)",color:"var(--text-secondary)"},children:[n.jsx("span",{style:{fontWeight:500,color:"var(--text-primary)"},children:p}),!d&&n.jsx("button",{type:"button",onClick:()=>r("current"),style:{padding:"4px 10px",background:"transparent",color:"var(--accent-active, #D7FF63)",border:"1px solid var(--accent-active, #D7FF63)",borderRadius:6,fontSize:"var(--text-xs, 11px)",fontWeight:500,cursor:"pointer"},children:"Return to current"})]}),n.jsx(oa,{ariaLabel:"Next round",disabled:!f,onClick:()=>f&&r(a[c+1]),icon:n.jsx(ab,{})})]})}function oa({ariaLabel:e,disabled:t,onClick:r,icon:s}){return n.jsx("button",{type:"button",onClick:r,disabled:t,"aria-label":e,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,background:"transparent",color:t?"var(--text-dim, #666)":"var(--text-primary)",border:"1px solid var(--border-default)",borderRadius:6,cursor:t?"default":"pointer",opacity:t?.5:1,padding:0},children:s})}function ib({mockup:e,busy:t,onCancel:r,onConfirm:s}){i.useEffect(()=>{const o=l=>{l.key==="Escape"&&!t&&r()};return window.addEventListener("keydown",o),()=>window.removeEventListener("keydown",o)},[t,r]);const a=e.name.replace(/^\d{1,2}-/,"").replace(/-/g," ");return n.jsx("div",{role:"presentation",onClick:r,style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.6)",backdropFilter:"blur(2px)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:200,padding:24},children:n.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":"Ready to start building?",onClick:o=>o.stopPropagation(),style:{background:"var(--bg-elevated, #141414)",border:"1px solid var(--border-default)",borderRadius:12,padding:24,width:"min(440px, 100%)",display:"flex",flexDirection:"column",gap:16,fontFamily:"'IBM Plex Mono', monospace",boxShadow:"0 20px 60px rgba(0,0,0,0.5)"},children:[n.jsx("div",{style:{border:"1px solid var(--border-subtle)",borderRadius:8,overflow:"hidden",aspectRatio:"16 / 9",background:"#1a1a1a",position:"relative"},children:n.jsx("iframe",{src:e.url,title:`${a} thumbnail`,sandbox:"",style:{width:1440,height:900,border:"none",background:"white",transform:"scale(0.305)",transformOrigin:"top left",pointerEvents:"none",position:"absolute",top:0,left:0}})}),n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[n.jsx("h2",{style:{margin:0,color:"var(--text-primary)",fontSize:16,fontWeight:600},children:"Ready to start building?"}),n.jsxs("p",{style:{margin:0,color:"var(--text-secondary)",fontSize:13,textTransform:"capitalize"},children:["Using ",n.jsx("strong",{style:{color:"var(--text-primary)"},children:a})]})]}),n.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,marginTop:4},children:[n.jsx("button",{type:"button",onClick:r,disabled:t,style:{padding:"8px 16px",background:"transparent",color:"var(--text-secondary)",border:"1px solid var(--border-default)",borderRadius:6,fontSize:13,fontWeight:500,cursor:t?"wait":"pointer",opacity:t?.5:1,fontFamily:"inherit"},children:"Cancel"}),n.jsx("button",{type:"button",onClick:s,disabled:t,style:{padding:"8px 18px",background:"var(--accent-active, #D7FF63)",color:"var(--text-on-accent, #0F0F0F)",border:"1px solid var(--accent-active, #D7FF63)",borderRadius:6,fontSize:13,fontWeight:600,cursor:t?"wait":"pointer",opacity:t?.7:1,fontFamily:"inherit"},children:t?"Starting…":"Start building"})]})]})})}function lb({onDesignConfirmed:e}={}){const[t,r]=i.useState(null),[s,a]=i.useState(null),[o,l]=i.useState(null),[c,d]=i.useState(null),[u,f]=i.useState(null),[p,m]=i.useState(null),[h,v]=i.useState({}),[g,y]=i.useState({}),[j,b]=i.useState(!1),[x,w]=i.useState(()=>typeof window>"u"?!1:window.sessionStorage.getItem("mockup-grid-tip-dismissed")==="1"),[k,C]=i.useState("current"),N=ug(),E=i.useRef(null),R=dg(t),S=i.useRef(!0),D=i.useCallback(async()=>{try{const[A,F]=await Promise.all([fetch("/api/editor-mockups"),fetch("/api/editor-mockups-target")]),M=await A.json(),X=await F.json();S.current&&(r(M),a(X.count))}catch(A){S.current&&l(A instanceof Error?A.message:String(A))}},[]);i.useEffect(()=>{S.current=!0,D();const A=window.setInterval(D,4e3);return()=>{S.current=!1,window.clearInterval(A)}},[D]),i.useEffect(()=>{let A=!1;return(async()=>{try{const F=await fetch("/api/editor-mockups-feedback");if(!F.ok)return;const M=await F.json();if(A||!M||typeof M!="object"||Array.isArray(M))return;const X={};for(const[Z,_]of Object.entries(M)){if(!_||typeof _!="object")continue;const $=_;$.rating!=null&&typeof $.rating!="number"||$.comment!=null&&typeof $.comment!="string"||(X[Z]={rating:typeof $.rating=="number"?$.rating:null,comment:typeof $.comment=="string"?$.comment:""})}y(X)}catch{}})(),()=>{A=!0}},[]);const P=i.useCallback((A,F)=>{y(M=>{const X={...M,[A]:F};return E.current!=null&&window.clearTimeout(E.current),E.current=window.setTimeout(()=>{fetch("/api/editor-mockups-feedback",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(X)}).catch(()=>{})},400),X})},[]);i.useEffect(()=>()=>{E.current!=null&&window.clearTimeout(E.current)},[]);const I=i.useCallback(()=>{if(!t)return;b(!0),C("current");const A=Zx({feedbackByFilename:g,mockupFilenames:t.map(F=>F.filename)});Xx(A),y({}),fetch("/api/editor-mockups-feedback",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})}).catch(()=>{}),window.setTimeout(()=>{S.current&&b(!1)},1e3)},[g,t]),O=i.useCallback(A=>{m(A)},[]),U=i.useCallback(async()=>{if(!p)return;const A=p;d(A.filename);try{const F=await fetch("/api/editor-design-select",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:A.filename})});if(!F.ok){const M=await F.text().catch(()=>`${F.status}`);throw new Error(M||`select failed: ${F.status}`)}S.current&&(m(null),e==null||e())}catch(F){l(F instanceof Error?F.message:String(F))}finally{S.current&&d(null)}},[p,e]),J=i.useCallback(A=>{const F=ts(A.filename);f({mockup:A,systemName:F})},[]),T=i.useCallback(A=>{u&&v(F=>({...F,[u.mockup.filename]:A})),f(null)},[u]),L=i.useCallback(async A=>{if(u){d(u.mockup.filename);try{const F=await fetch("/api/editor-design-select",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:u.mockup.filename,overrides:{vars:A.vars,primaryFont:A.primaryFont,secondaryFont:A.secondaryFont}})});if(!F.ok){const M=await F.text().catch(()=>`${F.status}`);throw new Error(M||`select failed: ${F.status}`)}v(M=>({...M,[u.mockup.filename]:A})),f(null),e==null||e()}catch(F){l(F instanceof Error?F.message:String(F))}finally{S.current&&d(null)}}},[u,e]);if(u)return n.jsx(Rg,{mockup:u.mockup,systemName:u.systemName,initial:h[u.mockup.filename]??Yx,onBack:T,onSave:L,saving:c===u.mockup.filename});if(!t)return n.jsx("div",{style:{padding:"var(--spacing-lg, 16px)"},children:n.jsx("div",{style:{color:"var(--text-secondary)"},children:"Loading design mockups…"})});const W=t.reduce((A,F)=>{const M=/^(\d{1,2})-/.exec(F.filename);return M?Math.max(A,parseInt(M[1],10)):A},0),B=Math.max(s??0,W);if(B===0)return n.jsx(Qg,{});const Y=Array.from({length:B},(A,F)=>{const M=F+1,X=String(M).padStart(2,"0"),Z=t.find(_=>_.filename.startsWith(`${X}-`))??null;return{number:M,mockup:Z}});return n.jsxs("div",{className:"flex-1 flex flex-col min-w-0",style:{padding:"var(--spacing-lg, 16px)",gap:"var(--spacing-md, 12px)",overflow:"auto"},children:[!x&&n.jsx(tb,{onDismiss:()=>{w(!0),typeof window<"u"&&window.sessionStorage.setItem("mockup-grid-tip-dismissed","1")}}),n.jsx(ob,{archivedRoundsNewestFirst:N.map(A=>A.round),selected:k,onSelect:C}),o&&n.jsx("div",{style:{padding:"var(--spacing-sm, 8px) var(--spacing-md, 12px)",borderRadius:8,background:"var(--bg-danger-soft, rgba(248,113,113,0.12))",color:"var(--accent-danger, #f87171)",fontSize:"var(--text-sm, 14px)"},children:o}),k==="current"?n.jsxs(n.Fragment,{children:[n.jsx(Xg,{slots:Y,darkVarsBySystem:R,busyFilename:c,feedbackByFilename:g,onFeedbackChange:P,onChoose:O,onCustomize:J}),t.length>0&&n.jsx(rb,{feedbackCount:Object.values(g).filter(A=>typeof A.rating=="number"||A.comment.trim().length>0).length,busy:j,onIterate:I})]}):(()=>{const A=N.find(F=>F.round===k);return A?n.jsx(fg,{round:A}):n.jsx("div",{style:{padding:"var(--spacing-md, 14px)",color:"var(--text-secondary)",fontSize:"var(--text-sm, 14px)"},children:"Loading archived round…"})})(),p&&n.jsx(ib,{mockup:p,busy:c===p.filename,onCancel:()=>m(null),onConfirm:U})]})}function yr(e){const t=e.replace(/\s*\[[^\]]*\]\s*$/,""),r=t.indexOf(" - ");return r===-1?{pageName:null,stateName:t}:{pageName:t.slice(0,r),stateName:t.slice(r+3)}}function Xo(e){return Tr(e)?e.componentName??yr(e.name).pageName:yr(e.name).pageName}function rs(e){return yr(e.name).stateName}function cb({isCollapsed:e,onToggle:t}){return n.jsx("button",{onClick:t,className:`p-1.5 rounded transition-colors cursor-pointer ${e?"text-white bg-[#666] hover:bg-[#777]":"text-gray-500 hover:text-gray-300"}`,title:e?"Show editor":"Hide editor",children:n.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:e?n.jsxs(n.Fragment,{children:[n.jsx("path",{d:"M13 17l5-5-5-5"}),n.jsx("path",{d:"M6 17l5-5-5-5"})]}):n.jsxs(n.Fragment,{children:[n.jsx("path",{d:"M11 17l-5-5 5-5"}),n.jsx("path",{d:"M18 17l-5-5 5-5"})]})})})}function ia({label:e,value:t,disabled:r,onCommit:s}){const[a,o]=i.useState(String(t));i.useEffect(()=>{o(String(t))},[t]);const l=()=>{const c=Number.parseInt(a,10);if(!Number.isFinite(c)||c<=0){o(String(t));return}c!==t&&s(c)};return n.jsxs("label",{className:`flex items-center gap-0.5 px-1 py-0.5 rounded bg-[#2A2929] text-xs ${r?"opacity-50 cursor-not-allowed":""}`,children:[n.jsx("span",{className:"text-[10px] font-semibold text-gray-500 select-none",children:e}),n.jsx("input",{type:"text",inputMode:"numeric",value:a,disabled:r,"aria-label":e==="H"?"Height":"Width",onChange:c=>o(c.target.value.replace(/[^0-9]/g,"")),onBlur:l,onKeyDown:c=>{c.key==="Enter"?(l(),c.target.blur()):c.key==="Escape"&&(o(String(t)),c.target.blur())},className:"w-8 bg-transparent text-gray-200 text-center text-[11px] font-mono focus:outline-none disabled:cursor-not-allowed [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"})]})}function db({isFilled:e,onToggle:t}){return n.jsx("button",{onClick:t,className:`p-1.5 rounded transition-colors cursor-pointer ${e?"text-white bg-[#555]":"text-gray-500 hover:text-gray-300"}`,title:e?"Exit fullscreen":"Fill page with preview",children:n.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:e?n.jsxs(n.Fragment,{children:[n.jsx("polyline",{points:"4 14 10 14 10 20"}),n.jsx("polyline",{points:"20 10 14 10 14 4"}),n.jsx("line",{x1:"14",y1:"10",x2:"21",y2:"3"}),n.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]}):n.jsxs(n.Fragment,{children:[n.jsx("polyline",{points:"15 3 21 3 21 9"}),n.jsx("polyline",{points:"9 21 3 21 3 15"}),n.jsx("line",{x1:"21",y1:"3",x2:"14",y2:"10"}),n.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]})})})}function ub({previewUrl:e}){return n.jsx("button",{onClick:()=>{e&&window.open(e,"_blank")},className:"p-1.5 rounded text-gray-500 hover:text-gray-300 transition-colors cursor-pointer",title:"Open preview in new window",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),n.jsx("polyline",{points:"15 3 21 3 21 9"}),n.jsx("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]})})}function fb(){return n.jsx("button",{onClick:()=>Pa(),className:"p-1.5 rounded text-gray-500 hover:text-gray-300 transition-colors cursor-pointer",title:"Refresh preview","aria-label":"Refresh preview",children:n.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("polyline",{points:"23 4 23 10 17 10"}),n.jsx("polyline",{points:"1 20 1 14 7 14"}),n.jsx("path",{d:"M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"})]})})}function Qo(e){const t=new Map;for(const r of e){const s=r.url??"Uncategorized",a=t.get(s)??[];a.push(r),t.set(s,a)}return Array.from(t.entries()).map(([r,s])=>({route:r,scenarios:s})).sort((r,s)=>r.route==="Uncategorized"?1:s.route==="Uncategorized"?-1:r.route.localeCompare(s.route))}function pb(e,t){const r=t.trim().toLowerCase();return r?e.filter(s=>{const a=(s.url??"").toLowerCase(),o=s.name.toLowerCase(),l=(s.componentName??"").toLowerCase();return a.includes(r)||o.includes(r)||l.includes(r)}):e}function Zo(e,t,r){i.useEffect(()=>{const s=o=>{const l=o.target;e.current&&e.current.contains(l)||r!=null&&r.current&&r.current.contains(l)||t()},a=o=>{o.key==="Escape"&&t()};return document.addEventListener("mousedown",s),document.addEventListener("keydown",a),()=>{document.removeEventListener("mousedown",s),document.removeEventListener("keydown",a)}},[e,t,r])}function mb({tab:e,hasQuery:t}){return t?n.jsx("p",{className:"text-xs text-gray-500 px-2 py-6 text-center",children:"No matches for your search."}):n.jsxs("p",{className:"text-xs text-gray-500 px-2 py-6 text-center",children:["No ",e==="pages"?"pages":"components"," yet."]})}function hb({scenario:e,active:t,onClick:r}){const s=e.screenshotPaths[0],a=rs(e);return n.jsxs("button",{onClick:r,className:`w-32 text-left rounded border transition-colors cursor-pointer ${t?"border-[#007a99] bg-[#1a2a30]":"border-[#3d3d3d] bg-[#1a1a1a] hover:border-[#555]"}`,title:e.name,children:[n.jsx("div",{className:"aspect-[4/3] w-full overflow-hidden rounded-t border-b border-[#3d3d3d] bg-[#0f0f0f] flex items-center justify-center",children:s?n.jsx("img",{src:Ge(s),alt:e.name,className:"w-full h-full object-cover"}):n.jsx("span",{className:"text-[10px] text-gray-600",children:"No screenshot"})}),n.jsx("div",{className:"px-2 py-1 text-[11px] text-gray-200 truncate",children:a})]})}function xb({group:e,currentSlug:t,onSelect:r}){const s=e.scenarios[0]?Xo(e.scenarios[0]):null;return n.jsxs("div",{className:"mb-4 last:mb-0",children:[n.jsxs("div",{className:"flex items-baseline gap-1.5 mb-1.5 px-1",children:[n.jsx("span",{className:"text-xs font-semibold text-gray-200 truncate",children:s??e.route}),s?n.jsx("span",{className:"text-[10px] text-gray-500 font-mono truncate",children:e.route}):null]}),n.jsx("div",{className:"flex flex-wrap gap-2",children:e.scenarios.map(a=>n.jsx(hb,{scenario:a,active:a.slug===t,onClick:()=>r(a.slug)},a.slug))})]})}function la({label:e,active:t,count:r,onClick:s}){return n.jsxs("button",{onClick:s,className:`flex items-center gap-1.5 px-2 py-1 rounded text-[10px] font-semibold tracking-wider cursor-pointer transition-colors ${t?"text-white bg-[#3a3a3a]":"text-gray-500 hover:text-gray-300"}`,children:[e,n.jsx("span",{className:`text-[10px] font-mono px-1 rounded ${t?"bg-[#555] text-gray-200":"bg-[#2a2a2a] text-gray-500"}`,children:r})]})}function gb({scenarioGroups:e,currentSlug:t,onSelect:r,onClose:s,triggerRef:a}){const[o,l]=i.useState("pages"),[c,d]=i.useState(""),u=i.useRef(null),f=i.useRef(null);i.useEffect(()=>{var j;(j=f.current)==null||j.focus()},[]),Zo(u,s,a);const p=i.useMemo(()=>e.flatMap(j=>j.scenarios),[e]),m=i.useMemo(()=>pb(p,c),[p,c]),h=i.useMemo(()=>m.filter(Ct),[m]),v=i.useMemo(()=>m.filter(Tr),[m]),g=o==="pages"?h:v,y=i.useMemo(()=>Qo(g),[g]);return n.jsxs("div",{ref:u,className:"absolute top-full left-0 mt-1 bg-[#222] border border-[#3d3d3d] rounded-lg shadow-2xl z-50 w-[560px] max-h-[480px] flex flex-col",role:"dialog",children:[n.jsxs("div",{className:"flex items-center border-b border-[#3d3d3d] px-2 py-1.5 gap-2",children:[n.jsx(la,{label:"PAGES",active:o==="pages",count:h.length,onClick:()=>l("pages")}),n.jsx(la,{label:"COMPONENTS",active:o==="components",count:v.length,onClick:()=>l("components")}),n.jsx("div",{className:"flex-1"}),n.jsx("input",{ref:f,value:c,onChange:j=>d(j.target.value),placeholder:"Search…",className:"w-48 px-2 py-1 text-xs bg-[#1a1a1a] border border-[#3d3d3d] rounded text-gray-200 focus:outline-none focus:border-[#007a99]"}),n.jsx("button",{onClick:s,"aria-label":"Close",className:"p-1 text-gray-500 hover:text-gray-200 cursor-pointer",children:n.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:n.jsx("path",{d:"M18 6L6 18M6 6l12 12"})})})]}),n.jsx("div",{className:"overflow-y-auto p-3 flex-1 min-h-0",children:y.length===0?n.jsx(mb,{tab:o,hasQuery:c.trim().length>0}):y.map(j=>n.jsx(xb,{group:j,currentSlug:t,onSelect:b=>{r(b),s()}},j.route))})]})}function bb(){return n.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[n.jsx("path",{d:"M14 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"}),n.jsx("path",{d:"M14 3v6h6"})]})}function vb(){return n.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[n.jsx("rect",{x:"3",y:"3",width:"8",height:"8",rx:"1"}),n.jsx("rect",{x:"13",y:"3",width:"8",height:"8",rx:"1"}),n.jsx("rect",{x:"3",y:"13",width:"8",height:"8",rx:"1"}),n.jsx("rect",{x:"13",y:"13",width:"8",height:"8",rx:"1"})]})}function ei({className:e}){return n.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:e??"opacity-70 shrink-0 text-gray-400",children:n.jsx("polyline",{points:"6 9 12 15 18 9"})})}function yb({currentScenario:e,isOpen:t,onClick:r,buttonRef:s}){const a=e?Tr(e):!1,o=(e==null?void 0:e.screenshotPaths[0])??null,l=e?a?e.componentName??e.name:Xo(e)??e.url??e.name:"Select a page";return n.jsxs("button",{ref:s,onClick:r,className:`flex items-center gap-1.5 max-w-[260px] pl-0.5 pr-1.5 py-0.5 rounded transition-colors cursor-pointer text-xs ${e?"text-gray-200":"text-gray-500"} ${t?"bg-[#555]":"hover:bg-[#4a4a4a]"}`,title:l,"aria-haspopup":"menu","aria-expanded":t,children:[n.jsxs("span",{className:"flex items-center gap-0.5 bg-[#1f1f1f] border border-[#3d3d3d] rounded p-0.5",children:[n.jsx("span",{className:"w-6 h-4 overflow-hidden rounded-sm bg-[#0f0f0f] flex items-center justify-center text-gray-500",children:o?n.jsx("img",{src:Ge(o),alt:"",className:"w-full h-full object-cover"}):a?n.jsx(vb,{}):n.jsx(bb,{})}),n.jsx(ei,{})]}),n.jsx("span",{className:"truncate",children:l})]})}function wb(e,t){const r=e.url??"Uncategorized",s=t.find(a=>a.route===r);return(s==null?void 0:s.scenarios)??[e]}function jb({scenario:e,active:t,onClick:r}){const s=e.screenshotPaths[0];return n.jsxs("button",{onClick:r,className:`flex items-center gap-2 w-full px-2 py-1.5 text-left transition-colors cursor-pointer ${t?"bg-[#1a2a30]":"hover:bg-[#2a2a2a]"}`,children:[n.jsx("div",{className:"w-10 h-7 shrink-0 rounded overflow-hidden border border-[#3d3d3d] bg-[#0f0f0f] flex items-center justify-center",children:s?n.jsx("img",{src:Ge(s),alt:"",className:"w-full h-full object-cover"}):null}),n.jsx("div",{className:`text-xs truncate flex-1 min-w-0 ${t?"text-white":"text-gray-200"}`,children:rs(e)})]})}function kb({currentScenario:e,scenarioGroups:t,onSelect:r,onCreateNew:s,onClose:a,triggerRef:o}){const l=i.useRef(null);Zo(l,a,o);const c=i.useMemo(()=>wb(e,t),[e,t]);return n.jsxs("div",{ref:l,className:"absolute top-full right-0 mt-1 bg-[#222] border border-[#3d3d3d] rounded-lg shadow-2xl z-50 w-72 max-h-[400px] flex flex-col",role:"menu",children:[n.jsx("div",{className:"overflow-y-auto py-1 flex-1 min-h-0",children:c.map(d=>n.jsx(jb,{scenario:d,active:d.slug===e.slug,onClick:()=>{r(d.slug),a()}},d.slug))}),n.jsx("button",{onClick:()=>{s(),a()},className:"border-t border-[#3d3d3d] px-3 py-2 text-left text-[11px] font-mono tracking-wide text-[var(--accent-active)] hover:bg-[var(--accent-active)]/10 cursor-pointer",children:"+ CREATE NEW STATE"})]})}function Nb({label:e,disabled:t,isOpen:r,onClick:s,buttonRef:a}){return n.jsxs("button",{ref:a,onClick:()=>{t||s()},disabled:t,className:`flex items-center gap-1.5 max-w-[200px] h-7 px-2.5 rounded transition-colors text-xs ${t?"bg-[#3a3a3a] text-gray-600 cursor-not-allowed":r?"bg-[#444] text-gray-200 cursor-pointer":"bg-[#3a3a3a] text-gray-200 hover:bg-[#444] cursor-pointer"}`,title:t?"No active state":e,"aria-haspopup":"menu","aria-expanded":r,children:[n.jsx("span",{className:"truncate",children:e}),n.jsx(ei,{className:"opacity-70 shrink-0"})]})}function Cb({viewport:e,isActive:t,onSelect:r}){return n.jsx("button",{onClick:r,className:`p-1 rounded transition-colors cursor-pointer ${t?"text-white bg-[#555]":"text-gray-500 hover:text-gray-300"}`,title:`${e.name} (${e.width}×${e.height})`,children:n.jsx(Am,{name:e.name})})}function Sb({viewports:e,active:t,onChange:r,currentWidth:s,currentHeight:a,previewUrl:o,isCollapsed:l,onToggleCollapsed:c,isFilled:d,onToggleFilled:u,containerWidth:f,containerHeight:p,onCustomSizeChange:m,currentScenario:h,scenarioGroups:v,onShowScenarioPreview:g,onCreateStateRequest:y,isNarrow:j=!1}){const[b,x]=i.useState(!1),[w,k]=i.useState(!1),C=i.useRef(null),N=i.useRef(null),E=d&&f?Math.round(f):s,R=d&&p?Math.round(p):a,S=h?rs(h):"No state",D=!h;return n.jsxs("div",{className:"bg-[#2d2d2d] border-b border-[#3d3d3d] shrink-0 h-10 grid grid-cols-[1fr_auto_1fr] items-center px-2",children:[n.jsx("div",{className:"justify-self-start",children:!j&&n.jsx(cb,{isCollapsed:l,onToggle:c})}),n.jsxs("div",{className:`flex items-center gap-2 justify-self-center ${j?"min-w-0 overflow-x-auto":""}`,children:[n.jsxs("div",{className:"relative flex items-center bg-[#3a3a3a] rounded h-7 px-1 gap-1",children:[n.jsx(yb,{currentScenario:h,isOpen:b,onClick:()=>{x(P=>!P),k(!1)},buttonRef:C}),b&&n.jsx(gb,{scenarioGroups:v,currentSlug:(h==null?void 0:h.slug)??null,onSelect:g,onClose:()=>x(!1),triggerRef:C}),n.jsx("span",{className:"w-px h-5 bg-[#555] mx-1 shrink-0","aria-hidden":"true"}),e.map(P=>n.jsx(Cb,{viewport:P,isActive:!d&&t===P.name,onSelect:()=>{d&&u(),r(P.name)}},P.name)),n.jsx(db,{isFilled:d,onToggle:u}),n.jsx(ia,{label:"H",value:R,disabled:d,onCommit:P=>m(s,P)}),n.jsx(ia,{label:"W",value:E,disabled:d,onCommit:P=>m(P,a)}),n.jsx(fb,{}),n.jsx(ub,{previewUrl:o})]}),n.jsx("div",{className:"flex items-center gap-2 shrink-0",children:n.jsxs("div",{className:"relative",children:[n.jsx(Nb,{label:S,disabled:D,isOpen:w,onClick:()=>{k(P=>!P),x(!1)},buttonRef:N}),w&&h&&n.jsx(kb,{currentScenario:h,scenarioGroups:v,onSelect:g,onCreateNew:y,onClose:()=>k(!1),triggerRef:N})]})})]}),n.jsx("div",{"aria-hidden":"true"})]})}function Eb(){return n.jsxs("div",{style:{padding:"3rem 1rem",textAlign:"center",color:"var(--text-muted)"},children:[n.jsx("h2",{style:{fontSize:"1.125rem",fontWeight:600,color:"var(--text-secondary)",margin:"0 0 0.5rem 0"},children:"No plan loaded"}),n.jsx("p",{style:{margin:0,fontSize:"0.875rem"},children:"Ask the AI to draft a plan, or pick one from the Plan tab."})]})}function Rb({title:e}){return n.jsx("h1",{style:{fontSize:"1.5rem",fontWeight:600,color:"var(--text-primary)",margin:"0 0 1rem 0",paddingBottom:"0.75rem",borderBottom:"1px solid var(--border-subtle)"},children:e})}const ca={prompt:null,title:null};function ti(){const[e,t]=i.useState(ca),[r,s]=i.useState(!0);return i.useEffect(()=>{let a=!1;return(async()=>{try{const l=await(await fetch("/api/prompt")).json();a||t({prompt:l.prompt??null,title:l.title??null})}catch{a||t(ca)}finally{a||s(!1)}})(),()=>{a=!0}},[]),{...e,loading:r}}function Tb(){const{prompt:e,title:t,loading:r}=ti();return n.jsx("div",{className:"flex-1 flex flex-col min-w-0 overflow-auto",style:{background:"var(--bg-deep)"},children:n.jsx("div",{style:{padding:"1.5rem 2rem",maxWidth:"880px",width:"100%",margin:"0 auto"},children:r?null:e?n.jsxs(n.Fragment,{children:[t?n.jsx(Rb,{title:t}):null,n.jsx(mt,{children:e})]}):n.jsx(Eb,{})})})}function Pb({message:e}){return n.jsx("span",{style:{color:"var(--text-dim)"},children:e})}function Db({hasDevServerConfigured:e}){const t=e?"Starting your app…":"Your app will display here once set up";return n.jsx("div",{"data-testid":"preview-waiting-placeholder",style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"none",color:"var(--text-dim)"},children:n.jsx("span",{children:t})})}function Ab(e,t,r){const s=[e];return t&&s.push(`reload:${t}`),r&&s.push(`command:${r}`),s.join("::")}function Fb({currentWidth:e,currentHeight:t,isFilled:r,scale:s}){const a=n.jsx("div",{className:"w-full h-full border border-dashed rounded flex items-center justify-center text-center px-6",style:{borderColor:"var(--border-default)",background:"var(--bg-surface)",color:"var(--text-dim)"},children:n.jsxs("div",{className:"text-sm leading-relaxed",children:[n.jsx("div",{className:"font-medium",children:"Live Preview unavailable"}),n.jsxs("div",{className:"opacity-70 mt-1",children:[e,"×",t]})]})});return r?a:n.jsx("div",{className:"shadow-[0_10px_30px_rgba(0,0,0,0.45)]",style:{width:e,height:t,transform:s<1?`scale(${s})`:void 0,transformOrigin:"center center",flexShrink:0},children:a})}const Lb=i.forwardRef(function({currentHeight:t,currentWidth:r,isFilled:s,previewUrl:a,scale:o,reloadNonce:l,commandNonce:c,onLoad:d,onError:u},f){if(bt())return n.jsx(Fb,{currentWidth:r,currentHeight:t,isFilled:s,scale:o});const p=Ab(a,l,c),m=()=>{u&&u("iframe error event")};return s?n.jsx("iframe",{ref:f,src:a,title:"Live Preview",className:"w-full h-full border-none",style:{background:"var(--bg-deep)"},onLoad:d,onError:m},p):n.jsx("div",{className:"shadow-[0_10px_30px_rgba(0,0,0,0.45)]",style:{width:r,height:t,transform:o<1?`scale(${o})`:void 0,transformOrigin:"center center",flexShrink:0},children:n.jsx("iframe",{ref:f,src:a,title:"Live Preview",style:{width:"100%",height:"100%",border:"none",background:"var(--bg-deep)"},onLoad:d,onError:m},p)})});function Mb(e,t){const r=i.useRef(!1);i.useEffect(()=>{r.current||e&&e.startCommand&&(e.intendedRunning||e.status==="stopped"&&(r.current=!0,t()))},[e,t])}function Ib(e,t){const[r,s]=i.useState(!1),a=i.useCallback(()=>{r?(s(!1),e.deactivate(),e.clearSelection()):(s(!0),e.activate())},[r,e]);return i.useEffect(()=>{r&&(s(!1),e.clearSelection())},[t]),{isActive:r,toggle:a}}function $b(e,t){const[r,s]=i.useState(e),a=i.useRef(null);return i.useEffect(()=>{if(e!==!1){a.current!==null&&(window.clearTimeout(a.current),a.current=null),s(e);return}if(a.current===null)return a.current=window.setTimeout(()=>{a.current=null,s(!1)},t),()=>{a.current!==null&&(window.clearTimeout(a.current),a.current=null)}},[e,t]),r}function Ob(e,t=!0,r="running"){const s=i.useRef(null),a=i.useRef(!1),[o,l]=i.useState(0),c=i.useRef(null);i.useEffect(()=>{e!=null&&(s.current!=null&&e!==s.current?(a.current=!1,l(f=>f+1)):s.current==null&&(a.current?t&&qs(e,c.current):l(f=>f+1)),s.current=e)},[e,t]);const d=i.useCallback(f=>{a.current=!0,f&&(c.current=f),t&&e!=null&&qs(e,f??c.current)},[e,t]),u=i.useCallback(f=>{t&&fx(f)},[t]);return{reloadNonce:o,handleIframeLoad:d,handleIframeError:u}}const Bb=1500,_b=2e3,zb=3e3,Hb=2;function Wb(){return typeof window>"u"?!1:window.location.pathname.startsWith("/scenario/")?!0:bt()}function Vb(e,t=!1){const r=Wb(),[s,a]=i.useState(r?!0:null),[o,l]=i.useState(null),[c,d]=i.useState(0),[u,f]=i.useState(0),p=i.useRef(null),m=i.useRef(null),h=i.useRef(null),v=i.useRef(!1),g=i.useRef(e),y=i.useRef(t);i.useEffect(()=>{g.current=e},[e]),i.useEffect(()=>{y.current=t},[t]);const j=i.useCallback(()=>{m.current!=null&&(clearTimeout(m.current),m.current=null)},[]),b=i.useCallback(async()=>{if(v.current||y.current)return;const C=g.current;if(!C)return;h.current&&h.current.abort();const N=new AbortController;h.current=N;const E=setTimeout(()=>N.abort(),zb);let R=!1;try{await fetch(C,{mode:"no-cors",cache:"no-store",signal:N.signal}),R=!0}catch{R=!1}finally{clearTimeout(E)}if(!v.current){if(l(Date.now()),R){if(d(0),p.current!==!0){const S=p.current===!1;p.current=!0,a(!0),S&&f(D=>D+1)}}else d(S=>{const D=S+1;return D>=Hb&&p.current!==!1&&(p.current=!1,a(!1)),D});x()}},[]),x=i.useCallback(()=>{if(v.current)return;j();const C=p.current===!0?_b:Bb;m.current=setTimeout(()=>{m.current=null,b()},C)},[j,b]),w=i.useCallback(()=>{j(),b()},[j,b]);i.useEffect(()=>{if(!r)return v.current=!1,b(),()=>{v.current=!0,j(),h.current&&(h.current.abort(),h.current=null)}},[b,j,r]),i.useEffect(()=>{r||b()},[e,b,r]);const k=i.useRef(t);return i.useEffect(()=>{if(r)return;const C=k.current;k.current=t,C&&!t&&b()},[t,b,r]),{healthy:s,lastProbeAt:o,failedProbeCount:c,reloadNonce:u,invalidate:w}}const da={loaded:!1,stalledRequests:0,fastRequests:0,longestStallMs:0,tailReadFailedReason:null};function Ub(e){const{active:t,trigger:r}=e,[s,a]=i.useState(da),o=i.useRef(null),l=i.useCallback(()=>{var d;(d=o.current)==null||d.abort();const c=new AbortController;o.current=c,fetch("/api/dev-server-recent-requests",{signal:c.signal}).then(u=>{if(!u.ok)throw new Error(`HTTP ${u.status}`);return u.json()}).then(u=>{if(c.signal.aborted)return;const p=(u.stalls??[]).reduce((m,h)=>Math.max(m,h.durationMs??0),0);a({loaded:!0,stalledRequests:u.stalledRequests??0,fastRequests:u.fastRequests??0,longestStallMs:p,tailReadFailedReason:u.tailReadFailedReason??null})}).catch(u=>{c.signal.aborted||a({loaded:!0,stalledRequests:0,fastRequests:0,longestStallMs:0,tailReadFailedReason:u instanceof Error?u.message:"fetch failed"})})},[]);return i.useEffect(()=>{var c;if(!t){a(da),(c=o.current)==null||c.abort();return}return l(),()=>{var d;(d=o.current)==null||d.abort()}},[t,r,l]),s}function Kb(e){return!e||!e.loaded||e.tailReadFailedReason?null:e.stalledRequests>0?`Recent requests took up to ${Math.max(1,Math.round(e.longestStallMs/1e3))}s — the dev server is responding, just slowly. Check the dev-server log for what's blocking the render.`:e.fastRequests===0?"No recent activity in the dev-server log — the dev server may have stopped accepting connections. Restart it if this persists.":null}function Gb({liveIframeHealthy:e,previewReachable:t}){return e===!0||t===!0}function Yb({hasDevServerConfigured:e,hasServed:t}){return!e||t}const qb=2e3;function Jb(e,t){const[r,s]=i.useState(0),a=i.useRef(e),o=i.useRef(t),l=i.useRef(0);return i.useEffect(()=>{const c=a.current,d=o.current;if(a.current=e,o.current=t,!(t===!1)||!(e===!0)||!(c===!1&&e===!0)&&!(d===!0&&t===!1))return;const h=Date.now();h-l.current<qb||(l.current=h,s(v=>v+1))},[e,t]),r}const un={windowMs:1e4,threshold:4,ringBufferSize:16};function Xb({pidNonce:e,probeNonce:t,draftNonce:r,windowMs:s=un.windowMs,threshold:a=un.threshold}){const[o,l]=i.useState(!1),[c,d]=i.useState([]),[u,f]=i.useState(0),p=i.useRef(!1),m=i.useRef(e),h=i.useRef(t),v=i.useRef(r),g=i.useCallback(j=>{const b=Date.now(),x=b-s;let w=[];d(C=>{const N=C.filter(E=>E.timestampMs>=x);return N.push({reason:j,timestampMs:b}),N.length>un.ringBufferSize&&N.splice(0,N.length-un.ringBufferSize),w=N,N});const k=w.filter(C=>C.timestampMs>=x).length;if(!p.current&&k>=a){p.current=!0,l(!0);return}p.current||f(C=>C+1)},[s,a]);i.useEffect(()=>{e!==m.current&&(m.current=e,g("pid"))},[e,g]),i.useEffect(()=>{t!==h.current&&(h.current=t,g("probe"))},[t,g]),i.useEffect(()=>{r!==v.current&&(v.current=r,g("draft"))},[r,g]);const y=i.useCallback(()=>{p.current=!1,l(!1),d([]),f(j=>j+1)},[]);return{tripped:o,recentReloads:c,gatedNonce:u,reset:y}}const ua=20,Qb="codeyam-error-capture";function Zb(e,t=0){const[r,s]=i.useState([]),a=i.useCallback(()=>s([]),[]);return i.useEffect(()=>{s([])},[t]),i.useEffect(()=>{function o(l){const c=l.data;if(!c||c.source!==Qb)return;const d=e.current;if(d&&l.source!==d.contentWindow)return;const u=c.payload;!u||typeof u!="object"||!u.dedupeKey||s(f=>{const p=f.findIndex(h=>h.dedupeKey===u.dedupeKey);if(p>=0){const h=f.slice();return h[p]={...h[p],count:h[p].count+1,timestampMs:u.timestampMs},h}const m=[...f,{...u,count:1}];return m.length>ua?m.slice(m.length-ua):m})}return window.addEventListener("message",o),()=>window.removeEventListener("message",o)},[e]),{errors:r,clear:a}}const rr=[500,1e3,2e3];async function ev(e){try{const r=await(await fetch(`/api/probe-url?url=${encodeURIComponent(e)}`)).json();return{status:typeof(r==null?void 0:r.status)=="number"?r.status:null}}catch{return{status:null}}}async function tv(){try{const t=await(await fetch("/api/dev-server-log/slice?lines=40")).json();return Array.isArray(t==null?void 0:t.lines)?t.lines:[]}catch{return[]}}function nv(e,t){const[r,s]=i.useState({status:null,clickThroughBroken:!1,logLines:[],loading:!1});return i.useEffect(()=>{if(!e){s({status:null,clickThroughBroken:!1,logLines:[],loading:!1});return}let a=!1;return s({status:null,clickThroughBroken:!1,logLines:[],loading:!0}),(async()=>{const o=1+rr.length;let l=null;for(let d=0;d<o;d++){if(a)return;const{status:u}=await ev(e);if(a)return;if(l=u,u===null||u<500){s({status:u,clickThroughBroken:!1,logLines:[],loading:!1});return}d<rr.length&&await new Promise(f=>setTimeout(f,rr[d]))}const c=await tv();a||s({status:l,clickThroughBroken:!0,logLines:c,loading:!1})})(),()=>{a=!0}},[e,t]),r}function rv({url:e,status:t,logLines:r,onRetry:s}){return n.jsx("div",{role:"alert","data-testid":"iframe-click-through-error-card",className:"absolute inset-0 z-20 flex items-center justify-center bg-zinc-950/85 p-6",children:n.jsxs("div",{className:"max-w-2xl w-full rounded-md border border-red-700 bg-zinc-900 text-zinc-100 shadow-xl",children:[n.jsxs("div",{className:"px-5 py-4 border-b border-red-800 flex justify-between items-start",children:[n.jsxs("div",{className:"flex-1 min-w-0 pr-4",children:[n.jsxs("div",{className:"text-sm font-semibold text-red-300",children:["Scenario render failed (HTTP ",t,")"]}),n.jsx("div",{className:"mt-1 text-xs text-zinc-400 break-all",children:e}),n.jsx("div",{className:"mt-2 text-xs text-zinc-300",children:"The iframe URL returned a server error. This is a bug — capture and click should always agree. Check the dev-server log below and refresh once the underlying error is fixed."})]}),n.jsx("button",{type:"button",onClick:s,className:"flex-shrink-0 px-2.5 py-1 text-xs rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 cursor-pointer",children:"Retry"})]}),n.jsx("div",{className:"px-5 py-4 max-h-72 overflow-auto font-mono text-[11px] leading-snug text-zinc-300 whitespace-pre-wrap",children:r.length>0?r.join(`
|
|
169
|
+
`):n.jsxs("span",{className:"text-zinc-500 italic",children:["No dev-server log lines available — see"," ",n.jsx("code",{children:".codeyam/logs/dev-server.log"}),"."]})})]})})}function sv(e){if(e===null||!e.startCommand)return{isRestarting:!1,isFailed:!1,isStarting:!1,isStopped:!1};const t=e.status==="failed",r=!t&&e.status!=="running"&&e.intendedRunning&&(e.restartCount??0)>0,s=!t&&e.intendedRunning&&e.status!=="running"&&(e.restartCount??0)===0,a=e.status==="stopped"&&!e.intendedRunning;return{isRestarting:r,isFailed:t,isStarting:s,isStopped:a}}const av=20;function ov(e){const{hasDevServerConfigured:t,probeHealthy:r,backendIframeHealthy:s,isStarting:a,isRestarting:o,isFailed:l,isStopped:c,isPrePrototype:d,withinStartupGrace:u,previewReachable:f,hasEverServed:p}=e;return t?l?"crashed":s===!0||f===!0||r===!0&&s!==!1?null:d?"scaffolding":c?p?"stopped":null:o?"restarting":a||u||!p?null:r===!1?"reconnecting":s===!1&&r===!0?"disconnected":r===null?"probing":"reconnecting":null}function iv(e){return e===null||e.status!=="running"?!1:e.liveIframeHealthy!==!1}const lv=5,cv=3;function dv(e,t){return e===null||e<=0?!1:e<=(t==="backend"?cv:lv)}const fa="Setting up your project",pa="Preparing your project — the preview will appear once it's ready.",uv={1:"Aligning on the plan with you.",2:"Aligning on the plan with you.",3:"Aligning on the plan with you.",4:"Preparing the project environment.",5:"Wiring routes and seeding sample data."},fv={1:"Aligning on the plan with you.",2:"Aligning on the plan with you.",3:"Preparing the project environment."};function pv(e,t){return e===null?{title:fa,body:pa}:{title:fa,body:(t==="backend"?fv:uv)[e]??pa}}function mv({restartCount:e}){return n.jsxs("div",{className:"relative",children:[n.jsx("div",{className:"w-12 h-12 border-4 border-primary/20 border-t-primary rounded-full animate-spin"}),n.jsx("div",{className:"absolute inset-0 flex items-center justify-center text-[10px] font-bold text-primary",children:e>0?`#${e}`:""})]})}const hv={probing:{title:"Checking Live Preview",body:"Probing the dev server before showing the iframe…",spinner:!0},starting:{title:"Starting Dev Server",body:"Waiting for the development server to start…",spinner:!0},restarting:{title:"Dev Server Restarting",body:"The Live Preview server crashed unexpectedly. CodeYam is automatically recovering it…",spinner:!0},reconnecting:{title:"Reconnecting Live Preview",body:"Waiting for the dev server to respond…",spinner:!0},disconnected:{title:"Preview Disconnected",body:"The dev server is running, but the preview lost its connection after a restart. Reload the preview to reconnect — there's no need to restart the dev server.",spinner:!1},stopped:{title:"Dev Server Not Running",body:"Starting automatically…",spinner:!1},crashed:{title:"Dev Server Crashed",body:"Recovery is taking longer than usual.",spinner:!1},scaffolding:{title:"Setting up your project",body:"Preparing your project — the preview will appear once it's ready.",spinner:!0}};function xv({variant:e,restartCount:t=0,showRetry:r=!1,onRetry:s,bodyOverride:a}){const{title:o,body:l,spinner:c}=hv[e],d=a??l,u=e==="disconnected",f=!!s&&(u||r),p=u?"Reload preview":"Retry now";return n.jsx("div",{"data-testid":"preview-unhealthy-overlay","data-variant":e,className:"absolute inset-0 bg-white/90 dark:bg-gray-900/90 backdrop-blur-sm flex flex-col items-center justify-center z-50 animate-in fade-in duration-300",children:n.jsxs("div",{className:"flex flex-col items-center space-y-4 text-center max-w-md p-6",children:[c?n.jsx(mv,{restartCount:t}):n.jsx("div",{className:"w-12 h-12 rounded-full bg-gray-200 dark:bg-gray-700 flex items-center justify-center",children:n.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",className:"w-6 h-6 text-gray-500 dark:text-gray-400","aria-hidden":"true",children:[n.jsx("rect",{x:"6",y:"5",width:"4",height:"14",rx:"1"}),n.jsx("rect",{x:"14",y:"5",width:"4",height:"14",rx:"1"})]})}),n.jsxs("div",{className:"space-y-1",children:[n.jsx("h3",{className:"text-lg font-semibold text-gray-900 dark:text-gray-100",children:o}),n.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400",children:d})]}),f&&s&&n.jsx("button",{type:"button",onClick:s,className:"mt-2 px-4 py-1.5 text-sm font-medium rounded border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-800",children:p})]})})}function gv(e){return e.slice().reverse().map(t=>{const r=t.filename!=null?`
|
|
170
|
+
at ${t.filename}${t.lineno!=null?`:${t.lineno}`:""}${t.colno!=null?`:${t.colno}`:""}`:"",s=t.stack?`
|
|
171
|
+
${t.stack}`:"",a=t.count>1?` (×${t.count})`:"";return`[${t.type}]${a} ${t.message}${r}${s}`}).join(`
|
|
172
|
+
|
|
173
|
+
`)}function bv(e){if(e.length===0)return"no reloads recorded";const t={};for(const r of e)t[r.reason]=(t[r.reason]??0)+1;return Object.entries(t).map(([r,s])=>`${r}×${s}`).join(", ")}function vv({count:e,onExpand:t,onClear:r}){const s=`${e} ${e===1?"Error":"Errors"}`;return n.jsx("div",{"data-testid":"preview-error-badge",className:"absolute bottom-3 right-3 z-50 pointer-events-auto",children:n.jsxs("div",{className:"flex items-center gap-1.5 rounded-full shadow-lg border border-red-300 dark:border-red-800 bg-white dark:bg-gray-900",style:{background:"var(--bg-surface, rgba(255,255,255,0.97))"},children:[n.jsxs("button",{type:"button",onClick:t,"aria-label":`Expand ${s}`,className:"cursor-pointer flex items-center gap-1.5 pl-2.5 pr-2 py-1 text-xs font-medium text-red-700 dark:text-red-300 hover:bg-red-50 dark:hover:bg-red-950/40 rounded-l-full",children:[n.jsx("span",{"aria-hidden":"true",className:"inline-block h-1.5 w-1.5 rounded-full bg-red-600"}),n.jsx("span",{children:s}),n.jsx("span",{"aria-hidden":"true",className:"text-gray-400",children:"›"})]}),n.jsx("button",{type:"button",onClick:r,"aria-label":"Dismiss errors",className:"cursor-pointer px-2 py-1 text-xs text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 rounded-r-full",children:"✕"})]})})}function yv({headline:e,tripped:t,onClear:r,closeAriaLabel:s="Dismiss errors"}){return n.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-3 border-b border-red-200 dark:border-red-900",children:[n.jsxs("div",{children:[n.jsx("h3",{className:"text-sm font-semibold text-red-700 dark:text-red-300",children:e}),n.jsx("p",{className:"mt-0.5 text-xs text-gray-500 dark:text-gray-400",children:t?"Iframe frozen on its last load attempt. Copy the errors below, fix the code, then click Retry.":"Errors recorded from the running app. Copy them below to share with Claude."})]}),n.jsx("button",{type:"button",onClick:r,className:"cursor-pointer text-xs text-gray-400 hover:text-gray-600 dark:hover:text-gray-200","aria-label":s,children:"✕"})]})}function wv({error:e,expanded:t,onToggle:r}){return n.jsxs("li",{className:"rounded border border-red-200 dark:border-red-900 bg-red-50/60 dark:bg-red-950/30",children:[n.jsxs("button",{type:"button",onClick:r,className:"w-full flex items-start gap-2 text-left px-2 py-1.5 hover:bg-red-100/60 dark:hover:bg-red-900/30",children:[n.jsx("span",{className:"mt-0.5 text-red-500","aria-hidden":"true",children:t?"▾":"▸"}),n.jsxs("span",{className:"flex-1 min-w-0",children:[n.jsx("span",{className:"font-mono text-[10px] uppercase tracking-wide text-red-500 dark:text-red-400 mr-2",children:e.type}),n.jsx("span",{className:"text-gray-900 dark:text-gray-100 break-words",children:e.message}),e.count>1&&n.jsxs("span",{className:"ml-2 text-gray-500",children:["×",e.count]}),e.filename&&n.jsxs("span",{className:"block text-[11px] text-gray-500 mt-0.5 truncate",children:[e.filename,e.lineno!=null?`:${e.lineno}`:"",e.colno!=null?`:${e.colno}`:""]})]})]}),t&&e.stack&&n.jsx("pre",{className:"px-3 pb-2 text-[11px] font-mono text-gray-700 dark:text-gray-300 whitespace-pre-wrap break-words",children:e.stack})]})}function jv({errors:e,emptyHint:t}){const[r,s]=i.useState(null);return e.length===0?n.jsx("ul",{className:"flex-1 overflow-auto px-2 py-2 space-y-1 text-xs",children:n.jsx("li",{className:"text-gray-500 px-2 py-3",children:t??"No runtime errors captured yet."})}):n.jsx("ul",{className:"flex-1 overflow-auto px-2 py-2 space-y-1 text-xs",children:e.slice().reverse().map(a=>n.jsx(wv,{error:a,expanded:r===a.dedupeKey,onToggle:()=>s(r===a.dedupeKey?null:a.dedupeKey)},a.dedupeKey))})}function kv({canCopy:e,reasonsSummary:t,copyState:r,onCopy:s,onCopyForClaude:a,onRetry:o}){return n.jsxs("div",{className:"flex flex-wrap items-center gap-2 px-3 py-2 border-t border-red-200 dark:border-red-900 bg-gray-50 dark:bg-gray-900/40",children:[n.jsx("button",{type:"button",onClick:s,disabled:!e,className:"px-2.5 py-1 text-xs rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 disabled:opacity-50 cursor-pointer disabled:cursor-not-allowed",children:"Copy errors"}),n.jsx("button",{type:"button",onClick:a,disabled:!e,className:"px-2.5 py-1 text-xs rounded bg-red-600 text-white hover:bg-red-700 disabled:opacity-50 cursor-pointer disabled:cursor-not-allowed",children:"Copy and ask Claude"}),n.jsx("button",{type:"button",onClick:o,className:"px-2.5 py-1 text-xs rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 cursor-pointer",children:"Retry"}),n.jsxs("span",{className:"ml-auto text-[11px] text-gray-500",children:["Reloads in last 10s: ",t,r==="copied"&&n.jsx("span",{className:"ml-2 text-emerald-600",children:"copied ✓"}),r==="failed"&&n.jsx("span",{className:"ml-2 text-red-500",children:"copy blocked"})]})]})}const Nv=`Fix this error in the live preview. Here is what the captured runtime error reported:
|
|
174
|
+
|
|
175
|
+
`;function Cv({tripped:e,errors:t,recentReloads:r,serverHealthy:s,onRetry:a,onClear:o}){const[l,c]=i.useState("idle"),[d,u]=i.useState(!0),f=i.useMemo(()=>gv(t),[t]),p=i.useMemo(()=>bv(r),[r]);if(i.useEffect(()=>{t.length===0&&u(!0)},[t.length]),!e&&t.length===0)return null;const m=s&&!e,h=m&&d&&t.length>0,v=e?`Live Preview paused — ${t.length} error${t.length===1?"":"s"} captured`:`${t.length} runtime error${t.length===1?"":"s"} captured`;async function g(y){const j=await il(y+f);c(j?"copied":"failed"),setTimeout(()=>c("idle"),1500)}return h?n.jsx("div",{"data-testid":"preview-error-overlay","data-tripped":"false","data-collapsed":"true",className:"absolute inset-0 z-50 pointer-events-none",children:n.jsx(vv,{count:t.length,onExpand:()=>u(!1),onClear:o})}):n.jsx("div",{"data-testid":"preview-error-overlay","data-tripped":e?"true":"false","data-collapsed":"false",className:"absolute inset-0 z-50 flex flex-col items-stretch p-4 pointer-events-none",children:n.jsxs("div",{className:"mx-auto w-full max-w-2xl rounded-lg shadow-lg pointer-events-auto flex flex-col",style:{background:"var(--bg-surface, rgba(255,255,255,0.97))",border:"1px solid var(--border-default, #ef4444)",maxHeight:"100%"},children:[n.jsx(yv,{headline:v,tripped:e,onClear:m?()=>u(!0):o,closeAriaLabel:m?"Minimize errors":"Dismiss errors"}),n.jsx(jv,{errors:t,emptyHint:e?`Breaker tripped before any runtime error was reported. Reasons in window: ${p}.`:null}),n.jsx(kv,{canCopy:t.length>0,reasonsSummary:p,copyState:l,onCopy:()=>g(""),onCopyForClaude:()=>g(Nv),onRetry:a})]})})}function Sv({previewUrl:e}){const t=i.useMemo(()=>{try{return new URL(e,window.location.origin).searchParams.get("_codeyam_scenario")}catch{return null}},[e]);return t?n.jsxs("div",{className:"absolute top-2 left-2 z-30 flex items-center gap-1.5 px-2 py-1 rounded bg-black/60 backdrop-blur-sm border border-white/10 shadow-lg pointer-events-none select-none",children:[n.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-green-500 animate-pulse"}),n.jsxs("span",{className:"text-[10px] font-medium text-white/90 tracking-wide uppercase",children:["Scenario: ",t]})]}):null}function Ev(){return n.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-800",children:[n.jsxs("div",{className:"flex items-center space-x-2",children:[n.jsx("div",{className:"w-2 h-2 rounded-full bg-red-500 animate-pulse"}),n.jsx("h3",{className:"text-sm font-bold text-gray-900 dark:text-gray-100 uppercase tracking-tight",children:"Dev Server Crash Recovery Failed"})]}),n.jsx("div",{className:"text-[10px] text-gray-500 dark:text-gray-400 font-medium",children:"LAST 50 LOG LINES"})]})}function Rv({logs:e}){return n.jsx("div",{className:"flex-1 bg-black p-4 font-mono text-[11px] leading-relaxed overflow-y-auto text-gray-300",children:e.length>0?e.map((t,r)=>n.jsx("div",{className:"whitespace-pre-wrap break-all border-l-2 border-gray-800 pl-3 mb-1",children:t},r)):n.jsx("div",{className:"italic text-gray-600",children:"No logs captured..."})})}function Tv({text:e,label:t="Copy",copiedLabel:r="Copied!",writer:s,className:a="shrink-0 px-3 py-1.5 text-xs font-medium rounded-md bg-red-600 hover:bg-red-700 disabled:bg-red-300 disabled:cursor-not-allowed text-white transition-colors"}){const{copied:o,copy:l}=Sr({writer:s});return n.jsx("button",{type:"button",onClick:()=>{l(e)},disabled:e.length===0,className:a,children:o?r:t})}function Pv(){return n.jsxs("div",{className:"flex-1",children:[n.jsx("p",{className:"text-sm text-red-800 dark:text-red-300 font-medium mb-1",children:"CodeYam was unable to restart the dev server after several attempts."}),n.jsx("p",{className:"text-xs text-red-700/80 dark:text-red-400/80",children:"Copy the logs and share them with Claude to investigate the underlying bug."})]})}function Dv({logs:e,copyWriter:t}){return n.jsx("div",{className:"p-4 bg-red-50 dark:bg-red-950/30 border-t border-red-100 dark:border-red-900/50",children:n.jsxs("div",{className:"flex items-start justify-between gap-4",children:[n.jsx(Pv,{}),n.jsx(Tv,{text:e.join(`
|
|
176
|
+
`),label:"Copy logs",writer:t})]})})}function Av({logs:e}){return n.jsxs("div",{className:"absolute inset-0 bg-white dark:bg-gray-900 flex flex-col z-[60] overflow-hidden",children:[n.jsx(Ev,{}),n.jsx(Rv,{logs:e}),n.jsx(Dv,{logs:e})]})}const ma=20;function Fv(e){if(!e)return null;try{return new Date(e).toLocaleTimeString()}catch{return null}}function Lv({lastError:e,failureCount:t,failedAtMs:r,holder:s,onRetry:a,onReap:o}){const[l,c]=i.useState(!1),d=e.split(`
|
|
177
|
+
`),u=d.length>ma,f=l||!u?d:d.slice(d.length-ma),p=Fv(r);return n.jsxs("div",{"data-testid":"dev-server-failed-panel",className:"absolute inset-0 bg-white dark:bg-gray-900 flex flex-col z-[60] overflow-hidden",children:[n.jsxs("header",{className:"px-6 py-4 border-b border-gray-200 dark:border-gray-700",children:[n.jsxs("h2",{className:"text-base font-semibold text-gray-900 dark:text-gray-100",children:["Dev server failed to start after ",t," ",t===1?"attempt":"attempts"]}),p&&n.jsxs("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-1",children:["Last attempt: ",p]}),s&&n.jsxs("div",{"data-testid":"dev-server-failed-holder",className:"mt-3 rounded border border-amber-300 dark:border-amber-700 bg-amber-50 dark:bg-amber-900/30 px-3 py-2 text-xs text-amber-900 dark:text-amber-100",children:[n.jsxs("div",{children:["Port ",n.jsx("span",{className:"font-semibold",children:s.port})," is held by:"]}),n.jsxs("div",{className:"mt-1 font-mono",children:["PID ",s.pid," — ",s.command]})]})]}),n.jsx("pre",{"data-testid":"dev-server-failed-error",className:"flex-1 overflow-auto px-6 py-4 m-0 font-mono text-xs leading-relaxed text-gray-800 dark:text-gray-200 whitespace-pre-wrap",children:f.join(`
|
|
178
|
+
`)}),n.jsxs("footer",{className:"px-6 py-3 border-t border-gray-200 dark:border-gray-700 flex items-center justify-between gap-3",children:[u?n.jsx("button",{type:"button",onClick:()=>c(m=>!m),className:"text-xs text-gray-600 dark:text-gray-300 underline hover:text-gray-900 dark:hover:text-gray-100",children:l?"Show less":`Show all ${d.length} lines`}):n.jsx("span",{}),n.jsxs("div",{className:"flex items-center gap-2",children:[s&&o&&n.jsx("button",{type:"button","data-testid":"dev-server-failed-reap",onClick:o,className:"px-4 py-1.5 text-sm font-medium rounded border border-amber-500 text-amber-700 dark:text-amber-200 hover:bg-amber-100 dark:hover:bg-amber-900/50",children:"Kill orphan and retry"}),n.jsx("button",{type:"button","data-testid":"dev-server-failed-retry",onClick:a,className:"px-4 py-1.5 text-sm font-medium rounded bg-blue-600 text-white hover:bg-blue-700",children:"Retry"})]})]})]})}function Mv({diagnostic:e,onRetry:t}){const{expectedPort:r,actualPort:s,appName:a,currentStartCommand:o,remediation:l}=e;return n.jsxs("div",{"data-testid":"preview-port-mismatch-card",className:"absolute inset-0 bg-white dark:bg-gray-900 flex flex-col z-[60] overflow-auto",children:[n.jsxs("header",{className:"px-6 py-4 border-b border-gray-200 dark:border-gray-700",children:[n.jsx("h2",{className:"text-base font-semibold text-gray-900 dark:text-gray-100",children:"Dev server port conflict"}),n.jsxs("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-1",children:[a," bound port"," ",n.jsx("span",{className:"font-semibold",children:s}),", but the editor needs the app on port"," ",n.jsx("span",{className:"font-semibold",children:r})," so its reverse proxy (mocking, capture) can sit in front."]})]}),n.jsxs("div",{className:"flex-1 px-6 py-4 text-sm text-gray-800 dark:text-gray-200 space-y-3",children:[n.jsx("p",{children:l}),n.jsxs("div",{children:[n.jsx("div",{className:"text-xs uppercase tracking-wide text-gray-500 dark:text-gray-400 mb-1",children:"Current start command"}),n.jsx("pre",{className:"m-0 font-mono text-xs leading-relaxed whitespace-pre-wrap rounded bg-gray-100 dark:bg-gray-800 px-3 py-2",children:o||"(none configured)"})]})]}),n.jsx("footer",{className:"px-6 py-3 border-t border-gray-200 dark:border-gray-700 flex items-center justify-end",children:n.jsx("button",{type:"button","data-testid":"preview-port-mismatch-retry",onClick:t,className:"px-4 py-1.5 text-sm font-medium rounded bg-blue-600 text-white hover:bg-blue-700",children:"Retry"})})]})}const ha=48,Iv=100,$v=320,Ov=192;function Bv({containerHeight:e,containerWidth:t,viewportHeight:r,viewportWidth:s}){if(!(s!=null&&r!=null&&t!=null&&e!=null&&s>0&&r>0&&t>0&&e>0))return{width:$v,height:Ov,hasViewport:!1};const o=t-ha*2,l=e-ha*2-Iv,c=Math.min(1,o/s,l/r);return{width:Math.round(s*c),height:Math.round(r*c),hasViewport:!0}}function _v({containerHeight:e,containerWidth:t,onDismiss:r,scenarioName:s,screenshotPath:a,viewportHeight:o,viewportWidth:l}){const{width:c,height:d,hasViewport:u}=Bv({containerWidth:t,containerHeight:e,viewportWidth:l,viewportHeight:o}),f={width:c,height:d,...u?{overflowY:"auto"}:{}};return n.jsx("div",{className:"absolute inset-0 bg-white/90 dark:bg-gray-900/90 backdrop-blur-sm flex flex-col items-center justify-center z-50 animate-in fade-in duration-300",children:n.jsxs("div",{className:"flex flex-col items-center space-y-4 text-center p-6",children:[n.jsx("div",{className:"rounded-lg overflow-hidden border border-gray-200 dark:border-gray-700 shadow-md",style:f,children:n.jsx(Po,{screenshotPath:a??void 0,alt:s??"Scenario preview",className:u?"w-full h-auto":"max-w-full max-h-full object-contain"})}),n.jsxs("div",{className:"space-y-1",children:[n.jsx("h3",{className:"text-lg font-semibold text-gray-900 dark:text-gray-100",children:"The app is being edited"}),n.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400",children:"Live preview will load when the build agent is idle"})]}),n.jsx("button",{onClick:r,className:"text-xs text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors",children:"Dismiss"})]})})}function zv({isActive:e,onToggle:t}){return n.jsx("button",{onClick:t,title:e?"Exit Debug Mode":"Debug Mode",className:"absolute z-50",style:{bottom:16,right:16,width:40,height:40,borderRadius:"50%",border:e?"2px solid var(--accent-blue)":"1px solid var(--border-default)",background:e?"var(--accent-blue)":"var(--bg-surface)",color:e?"#000":"var(--text-secondary)",cursor:"pointer",display:"none",alignItems:"center",justifyContent:"center",opacity:e?1:.6,transition:"all 0.15s ease",fontSize:18},onMouseEnter:r=>{r.currentTarget.style.opacity="1"},onMouseLeave:r=>{e||(r.currentTarget.style.opacity="0.6")},children:e?"✕":"🔍"})}function Hv(){const[e,t]=i.useState(null),r=i.useCallback(async(a,o)=>{try{const l=await fetch("/api/open-in-editor",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({file:a,line:o})}),c=await l.json().catch(()=>({}));if(!l.ok||(c==null?void 0:c.success)!==!0){t({message:(c==null?void 0:c.error)??`HTTP ${l.status}`,command:(c==null?void 0:c.command)??null});return}t(null)}catch(l){t({message:l instanceof Error?l.message:String(l),command:null})}},[]),s=i.useCallback(()=>t(null),[]);return{openInEditor:r,lastError:e,clearError:s}}function Wv({tag:e,id:t,className:r,text:s,detectionMethod:a,previewUrl:o}){return n.jsxs("div",{className:"flex-1 flex flex-col gap-3 min-w-0",children:[n.jsx("div",{className:"rounded overflow-hidden flex-1",style:{background:"var(--bg-deep)",border:"1px solid var(--border-default)",minHeight:200,display:"flex",alignItems:"center",justifyContent:"center"},children:n.jsxs("div",{style:{color:"var(--text-secondary)",fontSize:12},children:[n.jsxs("div",{className:"text-center",style:{color:"var(--text-secondary)"},children:["Preview: ",o.split("/").pop()]}),n.jsxs("div",{className:"mt-2 p-3 rounded",style:{background:"var(--bg-surface)",border:"1px dashed var(--border-default)",fontSize:11,fontFamily:"monospace"},children:["<",e,t?` id="${t}"`:"",r?` class="${r.slice(0,40)}"`:"",">",n.jsx("br",{}),s.slice(0,60),s.length>60?"...":""]})]})}),n.jsxs("div",{style:{fontSize:11,color:"var(--text-secondary)"},children:["Detected via: ",a]})]})}function Vv({ancestors:e,onOpenInEditor:t}){return e.length===0?n.jsx("div",{style:{color:"var(--text-secondary)",fontSize:12,fontStyle:"italic"},children:"No component ancestry available."}):n.jsx("ul",{className:"flex flex-col gap-1",style:{listStyle:"none",padding:0,margin:0},children:e.map((r,s)=>{const a=r.sourceFile&&r.lineNumber?`${r.sourceFile}:${r.lineNumber}`:r.sourceFile??"(unknown source)",o=!!r.sourceFile;return n.jsxs("li",{className:"flex items-center gap-2 px-2 py-1 rounded",style:{background:"var(--bg-deep)"},children:[n.jsx("span",{style:{color:"var(--text-primary)",fontWeight:600,fontSize:12},children:r.componentName??"<anonymous>"}),n.jsx("span",{style:{color:"var(--text-secondary)",fontFamily:"monospace",fontSize:11,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a}),o&&n.jsx("button",{onClick:()=>t(r.sourceFile,r.lineNumber),className:"px-2 py-0.5 rounded text-xs",style:{background:"transparent",border:"1px solid var(--border-default)",color:"var(--accent-blue)",cursor:"pointer",fontSize:11},children:"Open in editor"})]},`${r.componentName??"anon"}-${s}`)})})}function Uv({ancestors:e,onOpenInEditor:t}){const[r,s]=i.useState(e.length>1);return e.length===0?null:n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsxs("button",{onClick:()=>s(a=>!a),className:"text-left",style:{background:"transparent",border:"none",color:"var(--text-secondary)",fontSize:12,cursor:"pointer",padding:0},children:[r?"▾":"▸"," Component ancestry (",e.length,")"]}),r&&n.jsx(Vv,{ancestors:e,onOpenInEditor:t})]})}function Kv({propsNames:e}){if(e.length===0)return null;const t=()=>{var r;(r=navigator.clipboard)==null||r.writeText(e.join(", "))};return n.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[n.jsx("span",{style:{color:"var(--text-secondary)",fontSize:12},children:"props:"}),e.map(r=>n.jsx("span",{onClick:t,className:"px-1.5 py-0.5 rounded",style:{background:"var(--bg-deep)",color:"var(--text-primary)",fontFamily:"monospace",fontSize:11,cursor:"pointer"},title:"Click to copy prop names",children:r},r))]})}function Gv({componentDisplay:e,sourceDisplay:t,tag:r,id:s,boundingBox:a,feedback:o,onFeedbackChange:l,creating:c,hasComponentName:d,ancestors:u,propsNames:f,onOpenInEditor:p,onGoToIsolated:m,onCreatePlan:h,onClose:v}){const g=c||!o.trim();return n.jsxs("div",{className:"flex-1 flex flex-col gap-3 min-w-0",children:[n.jsx("h3",{style:{color:"var(--text-primary)",fontSize:16,fontWeight:600,margin:0},children:e}),t&&n.jsx("div",{className:"px-2 py-1 rounded",style:{background:"var(--bg-deep)",fontSize:12,fontFamily:"monospace",color:"var(--accent-blue)"},children:t}),n.jsxs("div",{className:"flex flex-col gap-1",style:{color:"var(--text-secondary)",fontSize:12},children:[n.jsxs("div",{children:["Element: <",r,">",s?` #${s}`:""]}),n.jsxs("div",{children:["Position: ",Math.round(a.x),", ",Math.round(a.y)," (",Math.round(a.width),"x",Math.round(a.height),")"]})]}),n.jsx(Kv,{propsNames:f}),n.jsx(Uv,{ancestors:u,onOpenInEditor:p}),n.jsx("textarea",{value:o,onChange:y=>l(y.target.value),placeholder:"Describe the issue or desired change...",className:"flex-1 p-2 rounded resize-none",style:{background:"var(--bg-deep)",border:"1px solid var(--border-default)",color:"var(--text-primary)",fontSize:13,minHeight:80,outline:"none"}}),n.jsxs("div",{className:"flex gap-2",children:[d&&n.jsx("button",{onClick:m,className:"px-3 py-1.5 rounded text-sm",style:{background:"var(--bg-deep)",border:"1px solid var(--border-default)",color:"var(--text-primary)",cursor:"pointer"},children:"Go to Isolated Component"}),n.jsx("button",{onClick:h,disabled:g,className:"px-3 py-1.5 rounded text-sm flex-1",style:{background:g?"var(--bg-deep)":"var(--accent-blue)",border:"none",color:g?"var(--text-secondary)":"#000",cursor:g?"not-allowed":"pointer",fontWeight:600},children:c?"Creating...":"Create Fix Plan"}),n.jsx("button",{onClick:v,className:"px-3 py-1.5 rounded text-sm",style:{background:"transparent",border:"1px solid var(--border-default)",color:"var(--text-secondary)",cursor:"pointer"},children:"Cancel"})]})]})}function Yv({error:e,onDismiss:t}){return n.jsxs("div",{onClick:r=>r.stopPropagation(),className:"fixed bottom-4 left-1/2 px-3 py-2 rounded",style:{transform:"translateX(-50%)",background:"var(--bg-surface)",border:"1px solid var(--accent-red, #f85149)",color:"var(--text-primary)",fontSize:12,zIndex:60,maxWidth:520},children:[n.jsxs("div",{children:["Open in editor failed: ",e.message]}),e.command&&n.jsx("div",{style:{fontFamily:"monospace",fontSize:11,marginTop:4},children:e.command}),n.jsx("button",{onClick:t,className:"mt-1",style:{background:"transparent",border:"none",color:"var(--accent-blue)",cursor:"pointer",fontSize:11,padding:0},children:"Dismiss"})]})}function qv({element:e,previewUrl:t,onClose:r,onGoToIsolated:s,onCreatePlan:a}){const[o,l]=i.useState(""),[c,d]=i.useState(!1),{openInEditor:u,lastError:f,clearError:p}=Hv(),m=async()=>{d(!0);try{await a(o,e)}finally{d(!1)}},h=e.componentName??`<${e.element.tag}>`,v=e.sourceFile?`${e.sourceFile}${e.lineNumber?`:${e.lineNumber}`:""}`:null;return n.jsxs("div",{className:"absolute inset-0 z-50 flex items-center justify-center",style:{background:"rgba(0, 0, 0, 0.7)"},onClick:r,children:[n.jsxs("div",{className:"flex gap-4 p-6 rounded-lg max-w-3xl w-full mx-4",style:{background:"var(--bg-surface)",border:"1px solid var(--border-default)",maxHeight:"80vh"},onClick:g=>g.stopPropagation(),children:[n.jsx(Wv,{tag:e.element.tag,id:e.element.id,className:e.element.className,text:e.element.text,detectionMethod:e.detectionMethod,previewUrl:t}),n.jsx(Gv,{componentDisplay:h,sourceDisplay:v,tag:e.element.tag,id:e.element.id,boundingBox:e.element.boundingBox,feedback:o,onFeedbackChange:l,creating:c,hasComponentName:!!e.componentName,ancestors:e.ancestors,propsNames:e.propsNames,onOpenInEditor:u,onGoToIsolated:()=>s(e.componentName),onCreatePlan:m,onClose:r})]}),f&&n.jsx(Yv,{error:f,onDismiss:p})]})}function Jv(){return n.jsx("div",{className:"absolute z-40 px-2 py-1 rounded",style:{bottom:8,right:8,background:"var(--bg-surface)",border:"1px solid var(--accent-blue)",color:"var(--accent-blue)",fontSize:11,fontWeight:600,pointerEvents:"none",fontFamily:"system-ui"},"data-testid":"debug-freeze-pill",children:"Debug — frozen"})}function Xv({hoveredElement:e}){return n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"absolute inset-0 z-40",style:{border:"3px solid var(--accent-blue)",cursor:"crosshair",pointerEvents:"none"}}),e&&n.jsx("div",{className:"absolute z-40 px-2 py-1 rounded",style:{top:8,left:8,background:"var(--accent-blue)",color:"#000",fontSize:12,fontWeight:600,pointerEvents:"none"},children:e.componentName??`<${e.element.tag}>`}),n.jsx(Jv,{})]})}function Qv(){return n.jsx("div",{className:"absolute z-40 pointer-events-none",style:{top:0,left:0,right:0,bottom:0,border:"2px solid var(--accent-blue, #D7FF63)",borderRadius:4,boxSizing:"border-box"},children:n.jsx("div",{style:{position:"absolute",top:0,left:16,padding:"2px 8px",background:"var(--accent-blue, #D7FF63)",color:"#000",fontSize:10,fontWeight:700,fontFamily:"system-ui, -apple-system, sans-serif",borderRadius:"0 0 4px 4px",letterSpacing:.5},children:"INSPECT MODE"})})}function Zv(e,t,r){const{width:s,maxHeight:a,gap:o}=r,l=e.y+e.height+o,c=l+a>t.height,d=c?Math.max(o,e.y-a-o):l,u=Math.max(o,Math.min(e.x,t.width-s-o));return{top:d,left:u,placedAbove:c}}function e0({onDismiss:e}){return n.jsx("div",{onClick:e,style:{position:"fixed",inset:0,zIndex:999998,background:"transparent"}})}function t0({match:e,onOpen:t}){return n.jsxs("button",{onClick:()=>t(e),style:{width:"100%",textAlign:"left",padding:"6px 8px",background:"rgba(88, 166, 255, 0.12)",color:"inherit",border:"1px solid rgba(88, 166, 255, 0.4)",borderRadius:4,cursor:"pointer",fontFamily:"monospace",fontSize:11},children:[n.jsx("div",{style:{fontWeight:600},children:e.endpoint}),n.jsx("div",{style:{opacity:.85},children:e.jsonPath})]})}function n0({matches:e,onOpen:t}){return n.jsx("ul",{style:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:6},children:e.map((r,s)=>n.jsx("li",{children:n.jsx(t0,{match:r,onOpen:t})},`${r.endpoint}${r.jsonPath}${s}`))})}function r0({clickedText:e,matches:t,corpusEmpty:r,onOpenInPanel:s}){return n.jsxs("div",{style:{padding:"8px 12px"},children:[n.jsxs("div",{style:{opacity:.7,marginBottom:6,wordBreak:"break-all"},children:["Clicked: ",n.jsx("code",{children:s0(e,120)||"(empty)"})]}),r?n.jsx("div",{style:{opacity:.85},children:"No mocks were consumed on this page load yet."}):t.length===0?n.jsx("div",{style:{opacity:.85},children:"No direct mock value matches — this value may be computed or concatenated."}):n.jsx(n0,{matches:t,onOpen:s})]})}function s0(e,t){return e.length<=t?e:e.slice(0,t-1)+"…"}function a0({onDismiss:e}){return n.jsxs("div",{style:{padding:"8px 12px",borderBottom:"1px solid var(--border-muted, #374151)",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[n.jsx("span",{style:{fontWeight:600},children:"Data source"}),n.jsx("button",{onClick:e,"aria-label":"Dismiss",style:{background:"transparent",color:"inherit",border:"none",cursor:"pointer",fontSize:14,lineHeight:1},children:"×"})]})}const xa=320,ga=320,o0=8;function i0({clickedText:e,matches:t,anchor:r,onOpenInPanel:s,onDismiss:a,corpusEmpty:o}){i.useEffect(()=>{function f(p){p.key==="Escape"&&a()}return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[a]);const l=typeof window<"u"?window.innerHeight:800,c=typeof window<"u"?window.innerWidth:1200,{top:d,left:u}=Zv(r,{width:c,height:l},{width:xa,maxHeight:ga,gap:o0});return n.jsxs(n.Fragment,{children:[n.jsx(e0,{onDismiss:a}),n.jsxs("div",{style:{position:"fixed",top:d,left:u,width:xa,maxHeight:ga,zIndex:999999,background:"var(--bg-surface, #1f2937)",color:"var(--text-primary, #f3f4f6)",border:"1px solid var(--border-muted, #374151)",borderRadius:8,boxShadow:"0 10px 30px rgba(0,0,0,0.5)",fontFamily:"system-ui, -apple-system, sans-serif",fontSize:12,overflow:"auto"},role:"dialog","aria-label":"Mock data source inspector",children:[n.jsx(a0,{onDismiss:a}),n.jsx(r0,{clickedText:e,matches:t,corpusEmpty:o,onOpenInPanel:s})]})]})}function l0({healthy:e,reason:t}){const r=e===!0?"healthy":e===!1?"unhealthy":"unknown",a={healthy:{bg:"#1f3a24",border:"#2f6b3a",dot:"#4ade80",label:"Live"},unhealthy:{bg:"#3a1f1f",border:"#6b2f2f",dot:"#f87171",label:"Stale"},unknown:{bg:"#2a2a2a",border:"#444",dot:"#9ca3af",label:"—"}}[r];return n.jsxs("div",{role:"status","aria-label":`Live preview iframe: ${r}`,title:r==="healthy"?"Live Preview iframe is healthy and matches the running dev server.":r==="unhealthy"?t?`Live Preview iframe is stale: ${t}`:"Live Preview iframe is stale and out of sync with the dev server.":"Live Preview iframe health unknown.",style:{position:"absolute",top:8,right:8,display:"inline-flex",alignItems:"center",gap:6,padding:"4px 8px",borderRadius:999,backgroundColor:a.bg,border:`1px solid ${a.border}`,color:"#fff",fontSize:11,fontFamily:"monospace",zIndex:30,pointerEvents:"auto"},children:[n.jsx("span",{style:{width:8,height:8,borderRadius:"50%",backgroundColor:a.dot,boxShadow:r==="healthy"?`0 0 6px ${a.dot}`:void 0}}),n.jsx("span",{children:a.label})]})}function ba(e){if(!e||typeof e!="object")return null;const t=e;return{componentName:t.componentName??null,sourceFile:t.sourceFile??null,lineNumber:t.lineNumber??null,detectionMethod:t.detectionMethod??"dom-heuristics",ancestors:Array.isArray(t.ancestors)?t.ancestors:[],propsNames:Array.isArray(t.propsNames)?t.propsNames:[],element:t.element}}function c0(e){const[t,r]=i.useState(!1),[s,a]=i.useState(null),[o,l]=i.useState(null),c=i.useRef(!1),d=i.useCallback(m=>{const h=e.current;h!=null&&h.contentWindow&&h.contentWindow.postMessage({type:m},"*")},[e]),u=i.useCallback(()=>{r(!0),a(null),l(null),d("codeyam:debug:activate")},[d]),f=i.useCallback(()=>{r(!1),a(null),l(null),d("codeyam:debug:deactivate")},[d]),p=i.useCallback(()=>{l(null)},[]);return i.useEffect(()=>{function m(h){!h.data||typeof h.data.type!="string"||(h.data.type==="codeyam:debug:hover"?a(ba(h.data.payload)):h.data.type==="codeyam:debug:selected"&&l(ba(h.data.payload)))}return window.addEventListener("message",m),()=>window.removeEventListener("message",m)},[]),i.useEffect(()=>{c.current&&!t&&(c.current=!1),t&&(c.current=!0)},[t]),{isActive:t,hoveredElement:s,selectedElement:o,activate:u,deactivate:f,clearSelection:p}}const d0=/^\/api\/mock-panel(\/.*)?$/;function u0(e,t){return e.toUpperCase()!=="GET"?!1:d0.test(t)}function f0(e){return Array.isArray(e)?e.filter(t=>t.consumedThisPageLoad&&!u0(t.method,t.pathPattern)).map(t=>({endpoint:`${t.method} ${t.pathPattern}`,body:t.body})):[]}async function p0(e,t,r){return(await fetch("/api/debug/create-plan",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({feedback:e,componentName:t.componentName,sourceFile:t.sourceFile,lineNumber:t.lineNumber,detectionMethod:t.detectionMethod,element:t.element,previewUrl:r})})).json()}const m0=12;function h0(e,t,r){if(t.length===0)return[];const s=[];return wr(e,t,r,"$",0,new Set,s),s}function x0(e,t){const r=[];for(const o of e)for(const l of h0(o.body,t,o.endpoint))r.push(l);const s=new Set,a=[];for(const o of r){const l=`${o.endpoint}\0${o.jsonPath}`;s.has(l)||(s.add(l),a.push(o))}return a.sort((o,l)=>{const c=l.matchedValue.length-o.matchedValue.length;return c!==0?c:l.pathDepth-o.pathDepth}),a}function wr(e,t,r,s,a,o,l){if(e==null)return;const c=typeof e;if(c==="string"||c==="number"||c==="boolean"){String(e)===t&&l.push({endpoint:r,jsonPath:s,matchedValue:String(e),pathDepth:a});return}if(!(a>=m0)&&!o.has(e)){if(o.add(e),Array.isArray(e))for(let d=0;d<e.length;d++)wr(e[d],t,r,`${s}[${d}]`,a+1,o,l);else if(c==="object")for(const[d,u]of Object.entries(e))wr(u,t,r,`${s}.${d}`,a+1,o,l);o.delete(e)}}const g0={backgroundColor:"#1e1e1e",backgroundImage:"conic-gradient(#262626 25%, #1e1e1e 0 50%, #262626 0 75%, #1e1e1e 0)",backgroundSize:"16px 16px"};function b0({buildingScenarioName:e,buildingScenarioSlug:t,buildingScreenshotPath:r,containerHeight:s,containerRef:a,containerWidth:o,currentHeight:l,currentWidth:c,emptyStateMessage:d,isFilled:u,onDismissBuildingOverlay:f,previewSlug:p,previewUrl:m,previewOrigin:h,scale:v,commandNonce:g}){var he,q;const y=i.useRef(null),j=a??y,b=i.useRef(null),{status:x,restart:w}=ll();Mb(x,w);const{isRestarting:k,isFailed:C,isStarting:N,isStopped:E}=sv(x),{stepState:R}=qt(),S=dv((R==null?void 0:R.step)??null,(R==null?void 0:R.mode)??"ui"),D=(x==null?void 0:x.liveIframeHealthy)!==void 0,{reloadNonce:P,handleIframeLoad:I,handleIframeError:O}=Ob((x==null?void 0:x.pid)??null,D,x==null?void 0:x.status),U=(x==null?void 0:x.status)==="failed",{healthy:J,failedProbeCount:T,reloadNonce:L,invalidate:W}=Vb(m,U),B=$b(x==null?void 0:x.liveIframeHealthy,750),Y=Jb(J,B),[A,F]=i.useState(0);i.useEffect(()=>cl(()=>{F(se=>se+1)}),[]);const M=Xb({pidNonce:P,probeNonce:L+Y,draftNonce:A}),X=M.gatedNonce,{errors:Z,clear:_}=Zb(b,X),$=nv(m,X),Q=i.useCallback(()=>{M.reset(),_(),W()},[M,_,W]),H=i.useCallback(()=>Pa(),[]),G=(x==null?void 0:x.devServerStartedSecsAgo)??null,ae=G!==null&&G<av,z=!!(x!=null&&x.startCommand),oe=Gb({liveIframeHealthy:B,previewReachable:(he=x==null?void 0:x.previewProbe)==null?void 0:he.reachable}),[pe,ne]=i.useState(!1);i.useEffect(()=>{oe&&!pe&&ne(!0)},[oe,pe]);const le=oe||pe,je=Yb({hasDevServerConfigured:z,hasServed:le}),ie=je?m:"about:blank",te=ov({hasDevServerConfigured:z,probeHealthy:J,backendRunning:(x==null?void 0:x.status)==="running",backendIframeHealthy:B,isStarting:N,isRestarting:k,isFailed:C,isStopped:E,isPrePrototype:S,withinStartupGrace:ae,previewReachable:((q=x==null?void 0:x.previewProbe)==null?void 0:q.reachable)===!0,hasEverServed:le}),Be=i.useRef(void 0);i.useEffect(()=>{var ce;if(Be.current===te)return;const se=Be.current;Be.current=te,console.debug(`[preview-overlay] ${se===void 0?"(init)":se??"none"} → ${te??"none"}`,{status:x==null?void 0:x.status,intendedRunning:x==null?void 0:x.intendedRunning,restartCount:x==null?void 0:x.restartCount,pid:x==null?void 0:x.pid,liveIframeHealthy:x==null?void 0:x.liveIframeHealthy,previewProbeReachable:(ce=x==null?void 0:x.previewProbe)==null?void 0:ce.reachable,devServerStartedSecsAgo:G,withinStartupGrace:ae,probeHealthy:J,isStarting:N,isRestarting:k,isFailed:C,isStopped:E})},[te,x,G,ae,J,N,k,C,E]);const ke=x==null?void 0:x.portDiagnostic,K=(ke==null?void 0:ke.conflict)===!0,qe=te==="scaffolding"?pv((R==null?void 0:R.step)??null,(R==null?void 0:R.mode)??"ui").body:void 0,vt=Ub({active:te==="reconnecting",trigger:T}),Tt=te==="reconnecting"?Kb(vt):null,Se=qe??Tt??void 0,_e=T>=10,{isActive:Ae,hoveredElement:yt,selectedElement:be,activate:Je,deactivate:Ee,clearSelection:Re}=c0(b),Xe=i.useCallback(()=>{Ae?Ee():Je()},[Ae,Je,Ee]),{entries:Qe}=dl(p??null),{isActive:Te,toggle:Ze}=Ib({activate:Je,deactivate:Ee,clearSelection:Re},P);i.useEffect(()=>(ms({isActive:Te,previewSlug:p??null}),()=>{ms({isActive:!1,previewSlug:null})}),[Te,p]),i.useEffect(()=>ul(()=>{Ze()}),[Ze]);const we=Te&&be?be.element.text.trim():"",lt=i.useMemo(()=>f0(Qe),[Qe]),et=i.useMemo(()=>!Te||!we?[]:x0(lt,we),[Te,we,lt]),fe=i.useCallback(async se=>{Re(),Ee();try{const ue=await(await fetch("/api/scenarios")).json(),ye=Array.isArray(ue)?ue.find(de=>de.componentName===se):null;if(ye!=null&&ye.slug){const de=_o(window.location),Fe=Ho(ye.slug,de,null,0,h);window.history.pushState(null,"",Fe);return}}catch{}window.history.pushState(null,"","/entities")},[Re,Ee,h]),ve=i.useCallback(async(se,ce)=>{try{await p0(se,ce,m),Re(),Ee()}catch(ue){console.error("Failed to create debug plan:",ue)}},[m,Re,Ee]);return n.jsx("div",{ref:j,className:`relative flex-1 flex overflow-hidden ${u?"":"items-center justify-center p-8"}`,style:u?{backgroundColor:"#fff"}:g0,children:m?n.jsxs(n.Fragment,{children:[n.jsx(Lb,{ref:b,currentHeight:l,currentWidth:c,isFilled:u,previewUrl:ie,scale:v,reloadNonce:X,onLoad:()=>{je&&I(m)},onError:O}),!je&&n.jsx(Db,{hasDevServerConfigured:z}),n.jsx(Sv,{previewUrl:m}),n.jsx(l0,{healthy:B,reason:(x==null?void 0:x.iframeLastError)??null}),Ae&&n.jsx(Xv,{hoveredElement:yt}),Te&&n.jsx(Qv,{}),be&&!Te&&n.jsx(qv,{element:be,previewUrl:m,onClose:Re,onGoToIsolated:fe,onCreatePlan:ve}),be&&Te&&n.jsx(i0,{clickedText:we,matches:et,anchor:be.element.boundingBox,corpusEmpty:lt.length===0,onOpenInPanel:se=>{fl({routeKey:se.endpoint,jsonPath:se.jsonPath}),Re()},onDismiss:Re}),!t&&n.jsx(zv,{isActive:Ae,onToggle:Xe}),U?n.jsx(Lv,{lastError:(x==null?void 0:x.lastError)??(x==null?void 0:x.lastExit)??"(no error message captured)",failureCount:(x==null?void 0:x.failureCount)??0,failedAtMs:x==null?void 0:x.failedAtMs,holder:x==null?void 0:x.holder,onRetry:w,onReap:async()=>{await fetch("/api/editor-dev-server/reap",{method:"POST",headers:{"Content-Type":"application/json"}})}}):K&&ke?n.jsx(Mv,{diagnostic:ke,onRetry:w}):te&&(te==="crashed"?n.jsx(Av,{logs:(x==null?void 0:x.logs)??[]}):n.jsx(xv,{variant:te,restartCount:(x==null?void 0:x.restartCount)??0,showRetry:_e,onRetry:te==="disconnected"?H:W,bodyOverride:Se})),n.jsx(Cv,{tripped:M.tripped,errors:Z,recentReloads:M.recentReloads,serverHealthy:iv(x),onRetry:Q,onClear:_}),$.clickThroughBroken&&$.status!==null&&n.jsx(rv,{url:m,status:$.status,logLines:$.logLines,onRetry:Q}),t&&f&&n.jsx(_v,{containerHeight:s,containerWidth:o,onDismiss:f,scenarioName:e??null,screenshotPath:r??null,viewportHeight:l,viewportWidth:c})]}):n.jsx(Pb,{message:d})})}function v0({prompt:e}){const[t,r]=i.useState(!0);return n.jsxs("section",{"aria-label":"What you asked for",style:{border:"1px solid var(--border-subtle)",borderRadius:"8px",padding:"0.875rem 1rem",marginBottom:"1.5rem",background:"var(--bg-elevated)",fontFamily:"'IBM Plex Mono', monospace"},children:[n.jsxs("button",{type:"button",onClick:()=>r(s=>!s),"aria-expanded":t,style:{width:"100%",background:"transparent",border:"none",padding:0,margin:0,color:"var(--text-muted)",fontSize:"0.75rem",fontWeight:500,textAlign:"left",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"space-between",fontFamily:"inherit"},children:[n.jsx("span",{children:"What you asked for"}),n.jsx("span",{"aria-hidden":"true",style:{display:"inline-block",transition:"transform 150ms ease",transform:t?"rotate(0deg)":"rotate(-90deg)",color:"var(--text-muted)",fontSize:"0.75rem"},children:"▾"})]}),t?n.jsx("div",{style:{marginTop:"0.625rem",fontFamily:"ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif",color:"var(--text-secondary)",fontSize:"0.8125rem",lineHeight:1.55},children:n.jsx(mt,{children:e})}):null]})}function y0(){return n.jsxs("header",{style:{marginBottom:"1.5rem",fontFamily:"'IBM Plex Mono', monospace"},children:[n.jsxs("h1",{style:{fontSize:"1.125rem",fontWeight:600,color:"var(--text-primary)",margin:"0 0 0.5rem 0",display:"flex",alignItems:"baseline",gap:"0.5rem"},children:[n.jsx("span",{"aria-hidden":"true",style:{color:"var(--text-muted)",letterSpacing:"-0.1em"},children:"::"}),"Your app is being built!"]}),n.jsx("p",{style:{margin:0,color:"var(--text-muted)",fontSize:"0.8125rem"},children:"This usually takes a few minutes."})]})}function w0(e,t){if(e.phaseSteps.length===0)return"pending";const r=e.phaseSteps[0],s=e.phaseSteps[e.phaseSteps.length-1];return t>s?"complete":t>=r?"active":"pending"}const jr="#D7FF63",j0="var(--text-muted)";function k0({status:e}){return e==="complete"?n.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 18 18","aria-hidden":"true",style:{flexShrink:0,display:"block"},children:[n.jsx("circle",{cx:"9",cy:"9",r:"7.5",fill:"none",stroke:"#FFFFFF",strokeWidth:"1.5"}),n.jsx("path",{d:"M5.5 9.2 L8 11.5 L12.5 6.5",fill:"none",stroke:"#FFFFFF",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round"})]}):e==="active"?n.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 18 18",role:"img","aria-label":"In progress",style:{flexShrink:0,display:"block",animation:"codeyam-setup-spin 1.1s linear infinite"},children:[n.jsx("circle",{cx:"9",cy:"9",r:"7.5",fill:"none",stroke:jr,strokeWidth:"1.5",opacity:"0.25"}),n.jsx("path",{d:"M9 1.5 A 7.5 7.5 0 0 1 16.5 9",fill:"none",stroke:jr,strokeWidth:"1.75",strokeLinecap:"round"})]}):n.jsx("svg",{width:"18",height:"18",viewBox:"0 0 18 18","aria-hidden":"true",style:{flexShrink:0,display:"block"},children:n.jsx("circle",{cx:"9",cy:"9",r:"7.5",fill:"none",stroke:j0,strokeWidth:"1.5"})})}function N0({phase:e,status:t}){const r=t==="active"?jr:t==="complete"?"var(--text-primary)":"var(--text-muted)";return n.jsxs("li",{"data-phase-id":e.phaseId,"data-phase-status":t,style:{display:"flex",alignItems:"center",gap:"0.625rem"},children:[n.jsx(k0,{status:t}),n.jsx("span",{style:{color:r,fontSize:"0.8125rem",fontFamily:"'IBM Plex Mono', monospace",fontWeight:t==="active"?600:400,letterSpacing:"0.01em"},children:e.phaseLabel})]})}function C0({currentStep:e,mode:t}){const r=od(t);return n.jsx("section",{"aria-label":"Progress",style:{marginBottom:"0.5rem"},children:n.jsx("ol",{style:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:"0.875rem"},children:r.map(s=>{const a=w0(s,e);return n.jsx(N0,{phase:s,status:a},s.phaseId)})})})}function S0(e){let t=e;const r=t.match(/^Feature: [^\n]*\n\nProject context: /);return r?t=t.slice(r[0].length):t.startsWith("Project context: ")&&(t=t.slice(17)),t.endsWith(`
|
|
179
|
+
`)&&(t=t.slice(0,-1)),t}function E0({prompt:e,currentStep:t,mode:r}){return n.jsxs("div",{style:{background:"var(--bg-elevated, #141414)",border:"1px solid var(--border-subtle)",borderRadius:"12px",padding:"1.5rem 1.75rem",maxWidth:"520px"},children:[n.jsx(y0,{}),n.jsx(v0,{prompt:S0(e)}),n.jsx(C0,{currentStep:t,mode:r})]})}function R0(){const{prompt:e}=ti(),{stepState:t}=qt();return n.jsx("div",{className:"flex-1 flex flex-col min-w-0 overflow-auto",style:{background:"var(--bg-deep)"},children:n.jsx("div",{style:{padding:"1.5rem 2rem",maxWidth:"880px",width:"100%",margin:"0 auto"},children:n.jsx(E0,{prompt:e??"",currentStep:(t==null?void 0:t.step)??1,mode:(t==null?void 0:t.mode)??"ui"})})})}function T0({error:e,onRetry:t}){return n.jsxs("div",{role:"alert",className:"flex items-center justify-between gap-3 border-b border-[var(--accent-red)] bg-[var(--accent-red)]/10 px-4 py-2 text-sm text-[var(--accent-red)]",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"font-semibold",children:"Seed failed — DB state is unknown"}),n.jsx("div",{className:"truncate text-xs opacity-90",children:e})]}),t?n.jsx("button",{type:"button",onClick:t,className:"shrink-0 rounded border border-[var(--accent-red)] px-2 py-1 text-xs hover:bg-[var(--accent-red)] hover:text-white",children:"Retry"}):null]})}function P0(){return n.jsx("div",{role:"status","aria-live":"polite",className:"pointer-events-none absolute inset-0 flex items-center justify-center bg-[var(--bg-deep)]/90 backdrop-blur-sm text-[var(--text-muted)]",children:"Loading scenario..."})}function D0(e){return e.state==="preflight-running"||e.state==="booting-simulator"||e.state==="simulator-booted"||e.state==="building-app"}function A0({stderrTail:e,onClose:t}){return n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center",style:{background:"rgba(0,0,0,0.6)"},onClick:t,children:n.jsxs("div",{className:"max-w-2xl w-full max-h-[80vh] overflow-auto rounded p-4 font-mono text-xs",style:{background:"var(--bg-elevated)",color:"var(--text-primary)"},onClick:r=>r.stopPropagation(),children:[n.jsxs("div",{className:"flex items-center justify-between mb-2",children:[n.jsx("strong",{children:"Build logs (stderr tail)"}),n.jsx("button",{type:"button",onClick:t,className:"opacity-70 hover:opacity-100",children:"✕"})]}),n.jsx("pre",{className:"whitespace-pre-wrap",children:e||"(no stderr captured)"})]})})}const F0=1500;function L0({stackId:e,pollMs:t=F0,onStateChange:r}){const[s,a]=i.useState({state:"idle"}),[o,l]=i.useState(!1),[c,d]=i.useState(!1),u=i.useRef(r);u.current=r,i.useEffect(()=>{let m=!1,h=!0;const v=async()=>{var y;try{const j=await fetch("/api/simulator-status");if(!j.ok)return;const b=await j.json();if(m||!h)return;const{history:x,...w}=b;a(w),(y=u.current)==null||y.call(u,w)}catch{}};v();const g=window.setInterval(v,t);return()=>{m=!0,h=!1,window.clearInterval(g)}},[t]);const f=i.useCallback(async()=>{if(!o){l(!0);try{const m=e?JSON.stringify({stack_id:e}):"{}";await fetch("/api/start-simulator",{method:"POST",headers:{"content-type":"application/json"},body:m})}finally{l(!1)}}},[e,o]),p=o||D0(s);return n.jsxs("div",{className:"flex items-center gap-3 px-3 py-2 text-sm border-b",style:{background:"var(--bg-deep)",color:"var(--text-primary)"},children:[n.jsx("button",{type:"button",onClick:f,disabled:p,className:"px-3 py-1 rounded font-medium disabled:opacity-40 disabled:cursor-not-allowed",style:{background:"var(--accent)",color:"var(--bg-deep)"},children:s.state==="app-launched"?"Restart simulator":"Start simulator"}),n.jsx(M0,{status:s}),s.state==="build-failed"?n.jsx("button",{type:"button",onClick:()=>d(!0),className:"text-xs underline opacity-80 hover:opacity-100",children:"see logs"}):null,c&&s.state==="build-failed"?n.jsx(A0,{stderrTail:s.stderrTail,onClose:()=>d(!1)}):null]})}function M0({status:e}){const t=I0(e);return n.jsx("span",{className:"text-xs opacity-80","data-testid":"simulator-status-pill",children:t})}function I0(e){switch(e.state){case"idle":return"No simulator running";case"preflight-running":return"Pre-flight checks…";case"preflight-failed":return`Pre-flight failed: ${e.check} — ${e.message}`;case"booting-simulator":return`Booting ${e.device}…`;case"simulator-booted":return`Simulator booted (${e.name})`;case"building-app":return`Building (${$0(e.elapsedSec)})…`;case"build-failed":return"Build failed";case"app-launched":return"App running ▸";case"stopped":return e.reason.kind==="user-requested"?"Stopped":e.reason.kind==="editor-server-shutdown"?"Editor server shut down":e.reason.code!=null?`Stopped (exit ${e.reason.code})`:"Stopped"}}function $0(e){if(e<60)return`${e}s`;const t=Math.floor(e/60),r=e%60;return`${t}m ${r.toString().padStart(2,"0")}s`}function O0({currentWidth:e,currentHeight:t,isFilled:r,scale:s,variant:a}){const o=a==="xcode-missing"?"Xcode tooling not detected":"No iOS Simulator running",l=a==="xcode-missing"?"Install Xcode + command line tools, then boot a simulator.":"Boot a simulator (Xcode → Window → Devices and Simulators) to see the live preview.",c=n.jsx("div",{className:"w-full h-full border border-dashed rounded flex items-center justify-center text-center px-6",style:{borderColor:"var(--border-default)",background:"var(--bg-surface)",color:"var(--text-dim)"},children:n.jsxs("div",{className:"text-sm leading-relaxed",children:[n.jsx("div",{className:"font-medium",children:o}),n.jsx("div",{className:"opacity-70 mt-1",children:l})]})});return r?c:n.jsx("div",{className:"shadow-[0_10px_30px_rgba(0,0,0,0.45)]",style:{width:e,height:t,transform:s<1?`scale(${s})`:void 0,transformOrigin:"center center",flexShrink:0},children:c})}const B0=700;function _0({currentHeight:e,currentWidth:t,isFilled:r,scale:s,pollMs:a=B0,onError:o}){const[l,c]=i.useState(0),[d,u]=i.useState({kind:"loading"}),f=i.useRef(o);if(f.current=o,i.useEffect(()=>{let m=!1;const h=window.setInterval(()=>{m||c(v=>v+1)},a);return()=>{m=!0,window.clearInterval(h)}},[a]),i.useEffect(()=>{let m=!1;return fetch(`/api/simulator-frame?t=${l}`,{method:"HEAD"}).then(async h=>{var g;if(m)return;if(h.ok){u({kind:"ok"});return}if(h.status===503){const y=await z0(h);if(m)return;(typeof(y==null?void 0:y.error)=="string"?y.error:"").includes("xcode")?u({kind:"xcode-missing"}):u({kind:"no-device"});return}const v=`simulator frame request failed (${h.status})`;u({kind:"capture-failed",message:v}),(g=f.current)==null||g.call(f,v)}).catch(h=>{var g;if(m)return;const v=h instanceof Error?h.message:"simulator frame request errored";u({kind:"capture-failed",message:v}),(g=f.current)==null||g.call(f,v)}),()=>{m=!0}},[l]),d.kind==="no-device"||d.kind==="xcode-missing")return n.jsx(O0,{currentWidth:t,currentHeight:e,isFilled:r,scale:s,variant:d.kind});const p=`/api/simulator-frame?t=${l}`;return r?n.jsx("img",{src:p,alt:"iOS Simulator preview",className:"w-full h-full object-contain",style:{background:"var(--bg-deep)"}}):n.jsx("div",{className:"shadow-[0_10px_30px_rgba(0,0,0,0.45)]",style:{width:t,height:e,transform:s<1?`scale(${s})`:void 0,transformOrigin:"center center",flexShrink:0},children:n.jsx("img",{src:p,alt:"iOS Simulator preview",style:{width:"100%",height:"100%",background:"var(--bg-deep)",objectFit:"contain"}})})}async function z0(e){try{return await e.json()}catch{return null}}function H0({emptyStateMessage:e,firstSessionSetup:t,previewSlug:r,previewUrl:s,viewports:a,activeViewport:o,onViewportChange:l,isCollapsed:c,onToggleCollapsed:d,isFilled:u,onToggleFilled:f,currentWidth:p,currentHeight:m,onCustomSizeChange:h,buildingScenarioSlug:v,buildingScreenshotPath:g,buildingScenarioName:y,onDismissBuildingOverlay:j,previewSeeding:b,previewSeedError:x,onRetrySeed:w,currentScenario:k,scenarioGroups:C,onShowScenarioPreview:N,commandNonce:E,previewOrigin:R,isNarrow:S=!1,onDesignConfirmed:D}){const[P,I]=i.useState(!1),{containerRef:O,containerSize:U,scale:J}=xx({currentHeight:m,currentWidth:p,isFilled:u}),T=gx();i.useEffect(()=>{bt()||px(x??null)},[x]);const L=s?es(s):"",W=L==="/results"||L.startsWith("/results/"),B=L==="/plan-preview",Y=L==="/design-exploration";return B?n.jsx(Tb,{}):W?n.jsx(Ux,{}):Y?n.jsx(lb,{onDesignConfirmed:D}):t&&!s?n.jsx(R0,{}):n.jsxs("div",{"data-preview-pane":"true",className:"flex-1 flex flex-col min-w-0",children:[n.jsx(Sb,{viewports:a,active:o,onChange:l,currentWidth:p,currentHeight:m,previewUrl:s,isCollapsed:c,onToggleCollapsed:d,isFilled:u,onToggleFilled:f,containerWidth:(U==null?void 0:U.width)??null,containerHeight:(U==null?void 0:U.height)??null,onCustomSizeChange:h,currentScenario:k??null,scenarioGroups:C??[],onShowScenarioPreview:N??(()=>{}),onCreateStateRequest:()=>I(!0),isNarrow:S}),x?n.jsx(T0,{error:x,onRetry:w}):null,n.jsxs("div",{className:"relative flex-1 flex flex-col min-h-0",children:[T.kind==="simulator-ios"?n.jsxs(n.Fragment,{children:[n.jsx(L0,{}),n.jsx("div",{ref:O,className:"relative flex-1 flex overflow-hidden items-center justify-center p-8",style:{backgroundColor:"#1e1e1e"},children:n.jsx(_0,{currentHeight:m,currentWidth:p,isFilled:u,scale:J})})]}):n.jsx(b0,{containerRef:O,containerHeight:U==null?void 0:U.height,containerWidth:U==null?void 0:U.width,currentHeight:m,currentWidth:p,emptyStateMessage:e??"Select a scenario to preview",isFilled:u,previewSlug:r,previewUrl:s,previewOrigin:R,scale:J,buildingScenarioSlug:v,buildingScreenshotPath:g,buildingScenarioName:y,onDismissBuildingOverlay:j,commandNonce:E}),b?n.jsx(P0,{}):null]}),P?n.jsx(Kx,{onClose:()=>I(!1)}):null]})}function W0(){const[e,t]=i.useState([]),[r,s]=i.useState(!0),[a,o]=i.useState(null),{scenariosVersion:l}=xt(),c=i.useCallback(async()=>{s(!0),o(null);try{const u=await fetch("/api/scenarios");if(!u.ok)throw new Error(`HTTP ${u.status}`);const f=(await u.json()).map(Pr);t(Qo(f))}catch(u){o(u instanceof Error?u.message:"Failed to load scenarios")}finally{s(!1)}},[]);i.useEffect(()=>{c()},[c,l]);const d=e.reduce((u,f)=>u+f.scenarios.length,0);return{groups:e,loading:r,error:a,totalScenarios:d,reload:c}}function V0(){const[e,t]=i.useState([]),[r,s]=i.useState(!0),[a,o]=i.useState(null),{scenariosVersion:l}=xt(),c=i.useCallback(async()=>{s(!0),o(null);try{const d=await fetch("/api/app-route-entities");if(!d.ok)throw new Error(`HTTP ${d.status}`);const u=await d.json();t(Array.isArray(u)?u.map(f=>({...f,scenarios:Array.isArray(f==null?void 0:f.scenarios)?f.scenarios.map(Pr):[]})):[])}catch(d){o(d instanceof Error?d.message:"Failed to load app routes"),t([])}finally{s(!1)}},[]);return i.useEffect(()=>{c()},[c,l]),{routeEntities:e,loading:r,error:a,reload:c}}function va(e){const t=new Map;for(const r of e){const s=U0(r.path);let a=t.get(s);a||(a=[],t.set(s,a));for(const o of r.tests)a.push({...o,file:r.path})}return Array.from(t.entries()).map(([r,s])=>({feature:r,tests:s})).filter(r=>r.tests.length>0).sort((r,s)=>r.feature.localeCompare(s.feature))}function U0(e){const r=e.replace(/\\/g,"/").replace(/^\.\//,"").split("/").filter(s=>s.length>0);return r.length===0?"Other":r[0]==="crates"&&r.length>=2?`crates/${r[1]}`:e==="(no-file)"?"(no-file)":r[0]}function ni(e,t){if(t===".")return e;const r=t.endsWith("/")?t:`${t}/`;return e.map(s=>({feature:s.feature,tests:s.tests.filter(a=>a.file.startsWith(r))})).filter(s=>s.tests.length>0)}function ri(e,t,r){return r==="backend"?[]:e.map(s=>({...s,scenarios:s.scenarios.filter(Ct)})).filter(s=>s.scenarios.length>0)}function si(e){let t=0,r=0,s=0,a=0,o=0;for(const l of e)for(const c of l.tests)o+=1,t+=1,c.status==="passed"?r+=1:c.status==="skipped"?a+=1:c.status==="failed"&&(s+=1);return{total:t,passed:r,failed:s,ignored:a,discovered:o}}function K0(e){return e.reduce((t,r)=>t+r.scenarios.length,0)}const G0=3e3;function Y0(){const[e,t]=i.useState([]),[r,s]=i.useState(!0),[a,o]=i.useState(!1),[l,c]=i.useState(null),[d,u]=i.useState(!1),[f,p]=i.useState(null),[m,h]=i.useState(null),[v,g]=i.useState(null),y=i.useRef(null),j=i.useRef(null),b=i.useRef(!1),x=i.useRef(null),{testsVersion:w}=xt(),k=i.useCallback(async(P=!1)=>{var J;(J=y.current)==null||J.abort();const I=new AbortController;y.current=I;const{signal:O}=I;P&&(b.current=!0,o(!0));const U=!P&&x.current!==null;U||(s(!0),c(null));try{if(!P&&!U)try{const B=await fetch("/api/test-results/summary",{signal:O});if(B.ok){const Y=await B.json();Y.running?p(Y.currentRunner??null):Y.stats&&(h(Y.stats),g(Y.coverage??null))}}catch{}let T,L;if(U){T=x.current;const B=await fetch("/api/test-results",{signal:O});if(!B.ok)throw new Error(`test-results: HTTP ${B.status}`);L=await B.json()}else if(P){const B=await fetch("/api/test-results/refresh",{method:"POST",signal:O});if(!B.ok)throw new Error(`test-results: HTTP ${B.status}`);L=await B.json(),T=x.current??[]}else{const[B,Y]=await Promise.all([fetch("/api/tests",{signal:O}),fetch("/api/test-results",{signal:O})]);if(!B.ok)throw new Error(`tests: HTTP ${B.status}`);if(!Y.ok)throw new Error(`test-results: HTTP ${Y.status}`);T=va(await B.json()),L=await Y.json(),x.current=T}if(p(L.currentRunner??null),L.running&&b.current){j.current=setTimeout(()=>k(!1),G0);return}const W=b.current;if(b.current=!1,W){const B=await fetch("/api/tests",{signal:O});B.ok&&(T=va(await B.json()),x.current=T)}t(T),u(L.cached??!1),g(L.coverage??null),h(null),s(!1),o(!1)}catch(T){if(T instanceof DOMException&&T.name==="AbortError")return;b.current=!1,c(T instanceof Error?T.message:"Failed to load tests"),s(!1),o(!1)}},[]);i.useEffect(()=>(x.current=null,k(),()=>{var P;(P=y.current)==null||P.abort(),j.current&&clearTimeout(j.current)}),[k,w]);const{total:C,passed:N,failed:E,ignored:R,discovered:S}=i.useMemo(()=>si(e),[e]),D=i.useCallback(()=>{b.current||k(!0)},[k]);return{groups:e,loading:r,refreshing:a,error:l,cached:d,currentRunner:f,summaryStats:m,coverage:v,totalTests:C,passedTests:N,failedTests:E,ignoredTests:R,discoveredTests:S,reload:k,refresh:D}}function ss(e,t){return e.filter(r=>r.appDir===t)}function ai(e,t){return t?e.find(r=>r.route===t)??null:null}function oi(e,t,r){const s=ri(e,t,r);return X0(s)}function q0(e){const t=e.filter(o=>o.defaultScenarioSlug);if(t.length===0)return null;const r=t.find(o=>o.route==="/"&&o.defaultScenarioSlug);if(r!=null&&r.defaultScenarioSlug)return r.defaultScenarioSlug;const s=t.find(o=>o.defaultScenarioSlug&&o.scenarios.some(l=>kr(l)));if(s!=null&&s.defaultScenarioSlug)return s.defaultScenarioSlug;const a=[...t].sort((o,l)=>o.route.length-l.route.length||o.route.localeCompare(l.route))[0];return(a==null?void 0:a.defaultScenarioSlug)??null}function J0(e){return(e==null?void 0:e.defaultScenarioSlug)??null}function ii(e,t){const r=e.find(s=>s.type==="web");return r?oi(t,r.dir,r.type):null}function X0(e){const t=e.flatMap(c=>c.scenarios.filter(d=>Ct(d)).map(d=>({route:c.route,scenario:d})));if(t.length===0)return null;const r=t.find(({route:c,scenario:d})=>c==="/"&&kr(d));if(r)return r.scenario.slug;const s=t.find(({route:c})=>c==="/");if(s)return s.scenario.slug;const a=t.find(({scenario:c})=>kr(c));if(a)return a.scenario.slug;let o=null,l=1/0;for(const c of e)if(!(c.route.length>=l)){for(const d of c.scenarios)if(Ct(d)){o=d.slug,l=c.route.length;break}}return o}function kr(e){return/\bhome\b/i.test(e.name)}function ya(e){return new Set(e.flatMap(t=>t.scenarios.map(r=>r.slug)))}function sr({selectedApp:e,appRouteEntities:t,scenarioGroups:r}){return e?q0(t)??oi(r,e.dir,e.type):null}function Q0({apps:e,hasExplicitAppSelection:t,scenarioGroups:r}){return t||e.length===0||r.length===0?null:ii(e,r)}function wa(e){return J0(e)}function Z0({apps:e,routeEntities:t,selectedApp:r,appRouteEntities:s}){if(r)return s;const a=e.find(o=>o.type==="web");return a?ss(t,a.dir):[]}function ey({previewRouteEntities:e,selectedRouteEntity:t}){var s;if(t!=null&&t.route)return t.route;if(e.length===0)return null;const r=e.find(a=>a.route==="/");return r?r.route:((s=[...e].sort((a,o)=>a.route.length-o.route.length||a.route.localeCompare(o.route))[0])==null?void 0:s.route)??null}function ty({previewRouteEntities:e,path:t}){var s;const r=es(t);return((s=ai(e,r))==null?void 0:s.defaultScenarioSlug)??null}function ny(e){return e.startsWith("/scenario/")||e.startsWith("/isolated-components/")}function ry(e){return ny(e)?!1:e==="/"||e==="/apps"||e==="/apps/"}function sy(e,t,r=""){const s=Un(r),[a,o]=i.useState(s.selectedAppDir),[l,c]=i.useState(s.selectedEntityHash);i.useEffect(()=>{const b=Un(r);o(x=>x===b.selectedAppDir?x:b.selectedAppDir),c(x=>x===b.selectedEntityHash?x:b.selectedEntityHash)},[r]),i.useEffect(()=>{if(typeof window>"u"||e.length!==1)return;const b=Un(r);if(b.selectedAppDir||b.selectedEntityHash||!ry(r))return;const x=Kn(e[0].dir);`${window.location.pathname}${window.location.search}`!==x&&(window.history.replaceState({},"",x),o(e[0].dir))},[e,r]);const d=i.useMemo(()=>l?t.find(b=>ir(b)===l)??null:null,[t,l]),u=i.useMemo(()=>a?e.find(b=>b.dir===a)??null:d?e.find(b=>b.dir===d.appDir)??null:l?e.find(b=>b.type==="web")??e[0]??null:null,[e,a,d,l]),f=i.useMemo(()=>u?ss(t,u.dir):[],[t,u]),p=i.useMemo(()=>l?d:null,[l,d]);function m(b){if(typeof window>"u")return;const x=`${window.location.pathname}${window.location.search}`;b!==x&&window.history.pushState({},"",b)}function h(b){o(b),c(null),m(Kn(b))}function v(){o(null),c(null),m("/apps")}function g(b){const x=f.find(C=>C.route===b);if(!x)return;const w=ir(x),k=$a(x);!w||!k||(c(w),m(k))}function y(b){c(b),m(`/entities/${b}`)}function j(){c(null),m(a?Kn(a):"/apps")}return{selectedApp:u,appRouteEntities:f,selectedEntityHash:l,selectedRouteEntity:p,selectApp:h,deselectApp:v,selectRoute:g,selectEntity:y,deselectRoute:j}}function ay(e,t,r,s,a=""){const[o,l]=i.useState(null),c=i.useRef(!1),d=i.useRef(!1),{selectedApp:u,appRouteEntities:f,selectedEntityHash:p,selectedRouteEntity:m,selectApp:h,deselectApp:v,selectRoute:g,selectEntity:y,deselectRoute:j}=sy(e,t,a),b=i.useMemo(()=>ya(f),[f]),x=i.useMemo(()=>ya(m?[m]:[]),[m]),w=i.useMemo(()=>sr({selectedApp:u,appRouteEntities:f,scenarioGroups:r}),[f,r,u]),k=i.useMemo(()=>wa(m),[m]),C=i.useMemo(()=>u?ni(s,u.dir):[],[s,u]);i.useEffect(()=>{if(c.current)return;const I=Q0({apps:e,scenarioGroups:r,hasExplicitAppSelection:!!u});I&&(l(I),c.current=!0)},[e,r,u]),i.useEffect(()=>{if(u){if(d.current){d.current=!1;return}if(m){if(!k||o&&x.has(o))return;l(k);return}w&&(o&&b.has(o)||l(w))}},[w,k,o,u,b,m,x]);function N(I){h(I);const O=e.find(J=>J.dir===I);if(!O)return;const U=sr({selectedApp:O,appRouteEntities:ss(t,O.dir),scenarioGroups:r});l(U)}function E(){v(),l(ii(e,r))}function R(I){g(I);const O=wa(ai(f,I));l(O)}const S=i.useCallback(I=>{d.current=!0,l(I)},[]);function D(){if(j(),!u)return;const I=sr({selectedApp:u,appRouteEntities:f,scenarioGroups:r});I&&l(I)}function P(I){y(I)}return{selectedApp:u,appRouteEntities:f,appTestGroups:C,selectedEntityHash:p,selectedRouteEntity:m,previewSlug:o,setPreviewSlug:l,setPreviewSlugExplicit:S,selectApp:N,deselectApp:E,selectRoute:R,selectEntity:P,deselectRoute:D}}const oy=1e3;function iy(e){const t=i.useRef(e);t.current=e,i.useEffect(()=>{let r=!0;async function s(){if(r){try{const a=await fetch("/api/editor-commands");if(a.ok){const o=await a.json();for(const l of o)t.current(l)}}catch{}r&&setTimeout(s,oy)}}return s(),()=>{r=!1}},[])}function ly(){const[e,t]=i.useState({}),[r,s]=i.useState(!0),[a,o]=i.useState(null);i.useEffect(()=>{let c=!1;return fetch("/api/dependency-graph").then(d=>{if(!d.ok)throw new Error(`HTTP ${d.status}`);return d.json()}).then(d=>{if(c)return;const u="files"in d?d.files:d;t(u),s(!1)}).catch(d=>{c||(o(d.message),s(!1))}),()=>{c=!0}},[]);const l=i.useMemo(()=>tc(e),[e]);return{graph:e,entityLookup:l,loading:r,error:a}}const cy=["/apps","/entities","/app","/build","/history","/settings","/plan"];function li(e){if(!e)return!1;const t=es(e);return cy.some(r=>t===r||t.startsWith(`${r}/`))}function dy(e,t,r){const s=typeof window<"u"?_o(window.location):0;let a="";if(En(e)==="component"?a=Ho(e.slug,s,e.url,t,r):e.url&&(a=zo(e.url,{appPort:t,currentPort:s,previewOrigin:r})),a&&!li(a))try{const o=!a.startsWith("http"),l=typeof window<"u"?window.location.origin:"http://localhost",c=new URL(a,l);return c.searchParams.set("_codeyam_scenario",e.slug),o?c.pathname+c.search+c.hash:c.toString()}catch{return a}return a}function uy(e,t,r){return e.startsWith("http")||e?e:r?`${r}/results`:`http://127.0.0.1:${t}/results`}function fy(e,t,r){return e.startsWith("http")||e?e:r?`${r}/plan-preview`:`http://127.0.0.1:${t}/plan-preview`}function ci(e,t){if(!t)return null;for(const r of e)for(const s of r.scenarios)if(s.slug===t||s.id===t)return s;return null}function py({directPreviewPath:e,fallbackPreviewPath:t,previewKind:r,selectedScenario:s,port:a,previewOrigin:o}){return r==="blank"?"":e&&(r==="application"||r==="results"||r==="plan-preview")?r==="results"?uy(e,a,o):r==="plan-preview"?fy(e,a,o):e.startsWith("http")?e:o?`${o}${e}`:`http://127.0.0.1:${a}${e}`:s?dy({slug:s.slug,scenarioType:s.scenarioType,componentName:s.componentName,url:s.url},a,o):t?t.startsWith("http")?t:o?`${o}${t}`:`http://127.0.0.1:${a}${t}`:""}function my(e,t=Date.now()){const r=e.includes("?")?"&":"?";return`${e}${r}_cb=${t}`}function Nr(e,t){if(!e)return null;for(const r of t)for(const s of r.scenarios)if(s.slug===e)return s;return null}function hy({apps:e,appRouteEntities:t,directPreviewPath:r,fallbackPort:s,previewKind:a,previewOrigin:o,previewSlug:l,routeEntities:c,scenarioGroups:d,selectedApp:u,selectedRouteEntity:f}){const p=ci(d,l),m=Z0({apps:e,routeEntities:c,selectedApp:u,appRouteEntities:t}),h=ey({previewRouteEntities:m,selectedRouteEntity:f}),v=e.some(j=>j.type==="web");let g="blank";a==="plan-preview"&&r?g="plan-preview":a==="results"&&r?g="results":a==="application"&&r?g="application":p?g=Ct(p)?"application":"component":h&&(g="application");const y=py({directPreviewPath:r,fallbackPreviewPath:h,previewKind:g,selectedScenario:p,port:s,previewOrigin:o});return{selectedScenario:p,previewRouteEntities:m,fallbackPreviewPath:h,resolvedPreviewKind:g,basePreviewUrl:y,hasWebApp:v}}function xy({allowEditorRoutePreview:e,command:t,configLoaded:r,previewRouteEntities:s,scenarioGroups:a,scenarioDeferAvailable:o=!1}){const l=t.dimension??null,c=!!t.dimension,d=t.commandNonce;if(t.scenarioSlug??t.scenarioId){const g=t.scenarioSlug??t.scenarioId,y=ci(a,g);return y?{clearCustomSize:c,scenarioSlug:y.slug,type:"show-scenario",viewportName:l,commandNonce:d}:o?{clearCustomSize:c,type:"defer",viewportName:l,commandNonce:d}:t.path?{clearCustomSize:c,path:t.path,previewKind:"application",previewSlug:null,preserveDirectPreviewPathOnSlugChange:!0,type:"show-path",viewportName:l,commandNonce:d}:{clearCustomSize:c,scenarioSlug:g,type:"show-scenario",viewportName:l,commandNonce:d}}if(!t.path)return{clearCustomSize:c,type:"refresh",viewportName:l,commandNonce:d};const u=t.path,f=u.startsWith("http")?new URL(u).pathname:u.split("?")[0]??u,p=f==="/results"||f.startsWith("/results/"),m=f==="/plan-preview",h=li(u);if(m)return{clearCustomSize:c,path:u,previewKind:"plan-preview",previewSlug:null,preserveDirectPreviewPathOnSlugChange:!1,type:"show-path",viewportName:l,commandNonce:d};if(p)return{clearCustomSize:c,path:u,previewKind:"results",previewSlug:null,preserveDirectPreviewPathOnSlugChange:!1,type:"show-path",viewportName:l,commandNonce:d};if(h&&!e)return{clearCustomSize:c,type:r?"ignore":"defer",viewportName:l,commandNonce:d};if(h&&e)return{clearCustomSize:c,path:u,previewKind:"application",previewSlug:null,preserveDirectPreviewPathOnSlugChange:!0,type:"show-path",viewportName:l,commandNonce:d};const v=ty({previewRouteEntities:s,path:u});return v?{clearCustomSize:c,scenarioSlug:v,type:"show-scenario",viewportName:l,commandNonce:d}:{clearCustomSize:c,path:u,previewKind:"application",previewSlug:null,preserveDirectPreviewPathOnSlugChange:!1,type:"show-path",viewportName:l,commandNonce:d}}function gy(e,t,r,s,a){const o=s.dimensions;return o.length===0||o.includes(e)&&t===null&&r===null?null:o.find(l=>a.some(c=>c.name===l))??o[0]}const by=[{name:"Desktop",width:1440,height:900},{name:"Laptop",width:1024,height:768},{name:"Tablet",width:768,height:1024},{name:"Mobile",width:375,height:667}];function vy(e,t){const r=Object.entries(e);if(r.length===0)return by;const s=r.map(([a,o])=>({name:a,width:o.width,height:o.height}));if(t){const a=s.findIndex(o=>o.name===t);if(a>0){const[o]=s.splice(a,1);s.unshift(o)}}return s}function yy({isInIframe:e,persistedPath:t,previewKind:r,resolvedViewport:s,selectedScenario:a}){i.useEffect(()=>{e||fetch("/api/editor-preview-state",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({kind:r==="blank"?null:r,path:t,scenarioSlug:(a==null?void 0:a.slug)??null,scenarioId:(a==null?void 0:a.id)??null,dimension:s.name,width:s.width,height:s.height})}).catch(()=>{})},[e,t,r,s.height,s.name,s.width,a==null?void 0:a.id,a==null?void 0:a.slug])}function wy({isInIframe:e,onActivated:t,previewKind:r,scenariosLoaded:s,selectedScenario:a}){const[o,l]=i.useState(!1),[c,d]=i.useState(null);return i.useEffect(()=>{if(!s||e)return;if(Hu({isInIframe:e,previewKind:r,selectedScenario:a})){fetch("/api/editor-deactivate-scenario",{method:"POST"}).catch(()=>{});return}if(!a||a.scenarioType!=="application")return;let u=!1;return l(!0),d(null),fetch("/api/editor-activate-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({slug:a.slug})}).then(async f=>{const p=await f.json().catch(()=>null);if(!u){if(!p||p.success===!1||p.seedError){d(p&&(p.seedError||p.error)||"scenario activation failed");return}t()}}).catch(f=>{u||d(f instanceof Error?f.message:String(f))}).finally(()=>{u||l(!1)}),()=>{u=!0}},[e,t,r,s,a==null?void 0:a.componentName,a==null?void 0:a.scenarioType,a==null?void 0:a.slug]),{seeding:o,seedError:c}}const jy=3;function ky({apps:e,appRouteEntities:t,configLoaded:r,defaultScreenSize:s,port:a,previewOrigin:o,projectTitle:l,previewSlug:c,routeEntities:d,scenarioGroups:u,scenariosLoaded:f,screenSizes:p,selectedApp:m,selectedRouteEntity:h,setPreviewSlug:v}){const[g,y]=i.useState("Desktop"),[j,b]=i.useState(null),[x,w]=i.useState(null),[k,C]=i.useState(null),[N,E]=i.useState(null),[R,S]=i.useState(()=>Date.now()),[D,P]=i.useState(0),I=i.useRef(null),O=i.useRef(!1),U=i.useMemo(()=>vy(p,s),[s,p]),J=i.useMemo(()=>j!==null&&x!==null?{name:"Custom",width:j,height:x}:U.find(ne=>ne.name===g)??U[0]??{name:"Desktop",width:1440,height:900},[g,x,j,U]),T=bt(),L=l==="CodeYam Editor",{basePreviewUrl:W,fallbackPreviewPath:B,hasWebApp:Y,previewRouteEntities:A,resolvedPreviewKind:F,selectedScenario:M}=i.useMemo(()=>hy({apps:e,appRouteEntities:t,directPreviewPath:k,fallbackPort:a,previewKind:N,previewOrigin:o,previewSlug:c,routeEntities:d,scenarioGroups:u,selectedApp:m,selectedRouteEntity:h}),[e,t,k,a,N,o,c,d,u,m,h]),X=i.useMemo(()=>W?my(W,R):"",[W,R]),Z=i.useCallback(ne=>{y(ne),b(null),w(null)},[]),_=i.useCallback((ne,le)=>{b(ne),w(le)},[]),$=i.useCallback(ne=>{v(ne),C(null),E(null),S(Date.now());const le=Nr(ne,u);if(!le)return;const je=gy(g,j,x,le,U);je!==null&&(y(je),b(null),w(null))},[g,x,j,u,v,U]),Q=i.useCallback((ne,le)=>{const je=(le==null?void 0:le.retriesLeft)??jy,ie=xy({allowEditorRoutePreview:L,command:ne,configLoaded:r,previewRouteEntities:A,scenarioGroups:u,scenarioDeferAvailable:je>0});if(ie.viewportName&&y(ie.viewportName),ie.clearCustomSize&&(b(null),w(null)),ie.type==="show-scenario"){$(ie.scenarioSlug),P(te=>te+1);return}if(ie.type==="defer"){I.current={command:ne,retriesLeft:je};return}if(ie.type==="refresh"){S(Date.now()),P(te=>te+1);return}ie.type!=="ignore"&&(ie.type==="show-path"&&(E(ie.previewKind),C(ie.path),O.current=ie.preserveDirectPreviewPathOnSlugChange,typeof ie.previewSlug=="string"?v(ie.previewSlug):ie.previewSlug===null&&v(null)),S(Date.now()),P(te=>te+1))},[r,L,A,u,v,$]);i.useEffect(()=>{if(!r)return;const ne=I.current;ne&&(I.current=null,Q(ne.command,{retriesLeft:ne.retriesLeft-1}))},[r,u,Q]),i.useEffect(()=>{if(!(!c||k===null)){if(O.current){O.current=!1;return}C(null),E(null),S(Date.now())}},[k,c]);const H=i.useMemo(()=>F==="results"||F==="plan-preview"?k:F==="application"?k??(M==null?void 0:M.url)??B:null,[k,B,F,M==null?void 0:M.url]),G=i.useCallback(()=>{S(Date.now())},[]);yy({isInIframe:T,persistedPath:H,previewKind:F,resolvedViewport:J,selectedScenario:M?{id:M.id??null,slug:M.slug}:null});const{seeding:ae,seedError:z}=wy({isInIframe:T,onActivated:G,previewKind:F,scenariosLoaded:f,selectedScenario:M?{slug:M.slug,scenarioType:M.scenarioType,componentName:M.componentName??null}:null}),oe=Y?"Select a scenario to preview":"No web app is available for Live Preview.",pe=i.useCallback(ne=>{C(ne),E(ne?"application":null),S(Date.now())},[]);return{viewports:U,resolvedViewport:J,previewUrl:X,emptyStateMessage:oe,handleViewportChange:Z,handleCustomSizeChange:_,showScenarioPreview:$,handlePreviewCommand:Q,setPreviewPath:pe,previewSeeding:ae,previewSeedError:z,commandNonce:D}}function Ny(){const[e,t]=i.useState(!1),r=i.useCallback(()=>{t(!0)},[]),s=i.useCallback(()=>{},[]),a=i.useCallback(()=>{},[]),o=i.useCallback(()=>{t(!1)},[]);return{showPostPushModal:e,onFeatureCompleteCommand:r,onAgentIdle:s,onAgentActive:a,dismissModal:o}}function Cy(){const[e,t]=i.useState(!1),r=i.useCallback(()=>{t(!0)},[]),s=i.useCallback(()=>{t(!1)},[]);return{showPlanCompleteModal:e,onPlanCompleteCommand:r,dismissPlanCompleteModal:s}}function Sy(){const{showBuildTab:e}=Qr(typeof window>"u"?"/":window.location.pathname),{config:t}=it(),[r,s]=i.useState(!1),[a,o]=i.useState(null),l=i.useCallback(async c=>{if(r)return!1;o(null),s(!0);try{try{await Jr()}catch{}const d=await fetch("/api/build/start-from-prompt",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:c})});if(!d.ok){let u=`HTTP ${d.status}`;try{const f=await d.json();f!=null&&f.error&&(u=f.error)}catch{}throw new Error(u)}return e(),await Xr({provider:t==null?void 0:t.provider}),!0}catch(d){return o(d instanceof Error?d.message:"Failed to launch build"),!1}finally{s(!1)}},[r,e,t==null?void 0:t.provider]);return{launching:r,error:a,launchPrompt:l}}function Ey({onTransitionToLive:e}){const[t,r]=i.useState(!1),[s,a]=i.useState(null),o=i.useRef(!1),l=i.useRef(null),c=i.useRef(e);c.current=e;const d=i.useCallback(()=>{o.current=!0,r(!0)},[]),u=i.useCallback(()=>{o.current=!1,r(!1);const m=l.current;m&&(l.current=null,a(null),c.current(m))},[]),f=i.useCallback(m=>o.current?(l.current=m,a(m),!0):!1,[]),p=i.useCallback(()=>{l.current=null,a(null)},[]);return{isAgentBuilding:t,isAgentBuildingRef:o,buildingScenarioSlug:s,onAgentIdle:u,onAgentActive:d,guardScenarioSelect:f,clearBuildingOverlay:p}}function Ry(e,t,r){return e.map(s=>{const a=ni(t,s.dir),o=ri(r,s.dir,s.type),{total:l,passed:c,failed:d,ignored:u,discovered:f}=si(a),p=K0(o);return{app:s,tests:{total:l,passed:c,failed:d,ignored:u,discovered:f},scenarios:{total:p,thumbnails:Ty(o)}}})}function Ty(e){const t=[];for(const r of e)for(const s of r.scenarios)if(s.screenshotPaths.length>0&&t.push(s.screenshotPaths[0]),t.length>=6)return t;return t}const Py="Your app will display here once set up.",Dy="Loading your app…";function Ay({configLoading:e,hasNoApps:t,hasStepState:r,defaultMessage:s}){return e?Dy:t&&!r?Py:s}function ja(e,t){return(t==null?void 0:t.previewOrigin)??(e==null?void 0:e.previewOrigin)??null}function Fy(e,t){return t?{scenarioSlug:e,path:t}:{scenarioSlug:e}}function Ly(e){return e.activeTab==="build"&&!e.hasActiveSession&&!e.isAgentBuilding&&!e.showPostPushModal&&e.launchingPlanSlug===null&&!e.submittingBuildPrompt&&!e.stepStateFeature&&e.pendingPlanCount>0&&!e.buildLaunchModalDismissed}const Cr={state:"unknown",provider:Er,credsPresent:!0,reason:null,expiresAt:null,probeInFlight:!1,backendFieldAbsent:!1};function My(e){if(e==null)return{...Cr,backendFieldAbsent:!0};if(typeof e!="object")return Cr;const t=e,r=t.state==="authenticated"||t.state==="needs-login"||t.state==="unknown"?t.state:"unknown",s=t.provider==="claude"||t.provider==="codex"||t.provider==="gemini"?t.provider:Er,a=typeof t.credsPresent=="boolean"?t.credsPresent:!0,o=t.reason==="token-expired"||t.reason==="api-401"||t.reason==="no-credentials"||t.reason==="probe-timeout"?t.reason:null,l=typeof t.tokenExpiresAt=="string"?t.tokenExpiresAt:typeof t.expiresAt=="string"?t.expiresAt:null,c=typeof t.probeInFlight=="boolean"?t.probeInFlight:!1;return{state:r,provider:s,credsPresent:a,reason:o,expiresAt:l,probeInFlight:c,backendFieldAbsent:!1}}const Iy=1e3;function $y(){const[e,t]=i.useState(Cr),r=i.useRef(e.state);r.current=e.state;const s=i.useCallback(async()=>{try{const a=await fetch("/api/config");if(!a.ok)return;const o=await a.json();t(My(o.providerAuth))}catch{}},[]);return i.useEffect(()=>{s()},[s]),i.useEffect(()=>{if(e.state!=="unknown")return;const a=window.setInterval(()=>{r.current==="unknown"&&s()},Iy);return()=>window.clearInterval(a)},[e.state,s]),i.useEffect(()=>{const a=()=>{t(o=>({...o,state:"needs-login"})),s()};return window.addEventListener("agent-auth-required",a),()=>window.removeEventListener("agent-auth-required",a)},[s]),{state:e.state,provider:e.provider,credsPresent:e.credsPresent,reason:e.reason,expiresAt:e.expiresAt,probeInFlight:e.probeInFlight,backendFieldAbsent:e.backendFieldAbsent,refresh:s}}function Oy({provider:e,onAuthenticated:t}){const[r,s]=i.useState(""),[a,o]=i.useState(!1),[l,c]=i.useState(null),d=Ve(e),u=i.useCallback(async()=>{if(r.trim()){o(!0),c(null);try{const f=await fetch("/api/auth/api-key",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({provider:e,key:r.trim()})});if(!f.ok){const p=await f.json().catch(()=>({}));c(p.error??`Could not save the key (HTTP ${f.status}).`);return}s(""),t()}catch{c("Could not reach the editor to save the key.")}finally{o(!1)}}},[r,e,t]);return n.jsxs("div",{"data-testid":"api-key-flow",className:"space-y-3",children:[n.jsxs("p",{className:"text-sm text-[#8E8E8E]",children:["Paste your ",d," API key. It is stored locally in",n.jsx("code",{className:"mx-1 text-[#D7FF63]",children:".codeyam/editor.local.json"}),"and never committed."]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("input",{type:"password",value:r,onChange:f=>s(f.target.value),placeholder:`${d} API key`,className:"flex-1 min-w-0 px-2 py-1.5 rounded bg-black border border-[#3A3A3A] text-white text-sm"}),n.jsx("button",{onClick:()=>void u(),disabled:a||!r.trim(),className:"px-3 py-1.5 text-sm rounded-md bg-[#D7FF63] text-black font-medium cursor-pointer disabled:opacity-50",children:a?"Saving…":"Save"})]}),l?n.jsx("p",{className:"text-sm text-[#FF8B43]",children:l}):null]})}const By=500,_y=2e4;function zy({onAuthenticated:e}){const[t,r]=i.useState({state:"starting"}),[s,a]=i.useState(""),[o,l]=i.useState(!1),[c,d]=i.useState(!1),[u,f]=i.useState(!1),[p,m]=i.useState(!1),h=i.useRef(!1),v=i.useCallback(async()=>{try{const w=await fetch("/api/auth/status");if(!w.ok)return;const k=await w.json();r(k),k.state==="authenticated"&&!h.current&&(h.current=!0,e())}catch{}},[e]),g=i.useCallback(async()=>{h.current=!1,f(!1),r({state:"starting"});try{await fetch("/api/auth/start",{method:"POST"})}catch{r({state:"failed",error:"Could not start the login process."})}},[]);i.useEffect(()=>{g();const w=window.setInterval(()=>void v(),By);return()=>window.clearInterval(w)},[g,v]),i.useEffect(()=>{if(t.state!=="starting"){f(!1);return}const w=window.setTimeout(()=>f(!0),_y);return()=>window.clearTimeout(w)},[t.state]);const y=i.useCallback(async()=>{if(s.trim()){l(!0);try{const w=await fetch("/api/auth/code",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({code:s.trim()})});if(w.ok)a("");else{const k=await w.json().catch(()=>({}));r({state:"failed",error:k.error??"Code not accepted — check the value and try again."})}}catch{r({state:"failed",error:"Could not submit the code."})}finally{l(!1)}}},[s]),j=i.useCallback(async()=>{try{await fetch("/api/auth/cancel",{method:"POST"})}catch{}g()},[g]),b=i.useCallback(async()=>{m(!0);try{await fetch("/api/auth/refresh-cache",{method:"POST"}),e()}catch{}finally{m(!1)}},[e]),x=i.useCallback(()=>{var w;t.url&&((w=navigator.clipboard)==null||w.writeText(t.url),d(!0),window.setTimeout(()=>d(!1),1500))},[t.url]);return u&&t.state==="starting"?n.jsxs("div",{"data-testid":"claude-oauth-timeout",className:"space-y-3",children:[n.jsxs("p",{className:"text-sm text-[#FF8B43]",children:["Login link preparation timed out — the backend may be wedged. Try again, recheck if you already authenticated elsewhere, or open a terminal and run ",n.jsx("code",{className:"text-white",children:"claude /login"})," ","directly."]}),n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsx("button",{onClick:()=>void j(),"data-testid":"claude-oauth-timeout-retry",className:"px-3 py-2 text-sm rounded-md bg-[#D7FF63] text-black font-medium cursor-pointer",children:"Retry"}),n.jsx("button",{onClick:()=>void b(),"data-testid":"claude-oauth-timeout-recheck",disabled:p,className:"px-3 py-2 text-sm rounded-md border border-[#3A3A3A] text-white cursor-pointer disabled:opacity-50",children:p?"Rechecking…":"I already logged in — recheck"})]})]}):t.state==="failed"?n.jsxs("div",{"data-testid":"claude-oauth-failed",className:"space-y-3",children:[n.jsx("p",{className:"text-sm text-[#FF8B43]",children:t.error??"Login failed."}),n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsx("button",{onClick:()=>void j(),className:"px-3 py-2 text-sm rounded-md bg-[#D7FF63] text-black font-medium cursor-pointer",children:"Try again"}),n.jsx("button",{onClick:()=>void b(),"data-testid":"claude-oauth-failed-recheck",disabled:p,className:"px-3 py-2 text-sm rounded-md border border-[#3A3A3A] text-white cursor-pointer disabled:opacity-50",children:p?"Rechecking…":"I already logged in — recheck"})]})]}):t.state==="authenticated"?n.jsx("p",{"data-testid":"claude-oauth-authenticated",className:"text-sm text-[#D7FF63]",children:"Connected. Opening Build…"}):t.state==="url-ready"&&t.url?n.jsxs("div",{"data-testid":"claude-oauth-url-ready",className:"space-y-3",children:[n.jsx("p",{className:"text-sm text-[#8E8E8E]",children:"Open this URL in your browser, approve access, then paste the code back here:"}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("code",{className:"flex-1 min-w-0 truncate px-2 py-1.5 rounded bg-black text-[#D7FF63] text-xs",children:t.url}),n.jsx("button",{onClick:x,className:"px-2 py-1.5 text-xs rounded-md border border-[#3A3A3A] text-white cursor-pointer",children:c?"Copied":"Copy"}),n.jsx("a",{href:t.url,target:"_blank",rel:"noreferrer",className:"px-2 py-1.5 text-xs rounded-md border border-[#3A3A3A] text-white cursor-pointer",children:"Open"})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("input",{type:"text",value:s,onChange:w=>a(w.target.value),placeholder:"Paste the code from the browser here",className:"flex-1 min-w-0 px-2 py-1.5 rounded bg-black border border-[#3A3A3A] text-white text-sm"}),n.jsx("button",{onClick:()=>void y(),disabled:o||!s.trim(),className:"px-3 py-1.5 text-sm rounded-md bg-[#D7FF63] text-black font-medium cursor-pointer disabled:opacity-50",children:o?"Submitting…":"Submit"})]})]}):n.jsx("p",{"data-testid":"claude-oauth-starting",className:"text-sm text-[#8E8E8E]",children:"Preparing the login link…"})}function Hy({provider:e,onAuthenticated:t,onClose:r}){const s=Ve(e);return n.jsx("div",{"data-testid":"provider-auth-modal",className:"fixed inset-0 z-[100] flex items-center justify-center",style:{background:"rgba(30, 30, 30, 0.90)"},children:n.jsxs("div",{className:"w-[32rem] max-w-[90vw] rounded-lg border border-[#3A3A3A] bg-[#1E1E1E] p-6 space-y-4",children:[n.jsxs("div",{className:"flex items-start justify-between",children:[n.jsxs("h2",{className:"text-base font-medium text-white",children:["Connect your ",s," account"]}),n.jsx("button",{onClick:r,"aria-label":"Close",className:"text-[#8E8E8E] hover:text-white cursor-pointer",children:"✕"})]}),e==="claude"?n.jsx(zy,{onAuthenticated:t}):n.jsx(Oy,{provider:e,onAuthenticated:t})]})})}const Wy=4e3;function Vy(e){const t=new Date(e).getTime()-Date.now(),r=Math.abs(Math.round(t/36e5));if(r<1)return t<0?"just now":"very soon";if(r<48)return t<0?`${r} h ago`:`in ${r} h`;const s=Math.round(r/24);return t<0?`${s} d ago`:`in ${s} d`}function Uy({state:e,provider:t,credsPresent:r=!0,reason:s=null,expiresAt:a=null,probeInFlight:o=!1,backendOutOfDate:l=!1,onAuthenticated:c,onAuthorized:d}){const[u,f]=i.useState(!1),[p,m]=i.useState(!1),h=Ve(t),[v,g]=i.useState(!1);i.useEffect(()=>{if(e!=="unknown"){g(!1);return}const N=window.setTimeout(()=>g(!0),Wy);return()=>window.clearTimeout(N)},[e]);const y=i.useCallback(()=>{f(!1),c(),d==null||d()},[c,d]),j=i.useCallback(async()=>{m(!0);try{await fetch("/api/auth/refresh-cache",{method:"POST"}),c()}catch{}finally{m(!1)}},[c]);if(e==="authenticated")return null;const b=u?n.jsx(Hy,{provider:t,onAuthenticated:y,onClose:()=>f(!1)}):null;if(e==="unknown")return o||!v||l?null:n.jsxs("div",{"data-testid":"provider-auth-checking","data-auth-card":!0,className:"m-4 rounded-lg border border-[#3A3A3A] bg-[#1E1E1E] p-5 space-y-3",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("span",{"data-testid":"provider-auth-checking-spinner","aria-hidden":"true",className:"h-4 w-4 rounded-full border-2 border-[#8E8E8E] border-t-transparent animate-spin"}),n.jsxs("p",{className:"text-sm text-[#8E8E8E]",children:["Checking your ",h," account… If this takes more than a few seconds, your token may need refresh."]})]}),n.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[n.jsx("button",{onClick:()=>f(!0),"data-testid":"provider-auth-checking-retry",className:"px-3 py-2 text-sm rounded-md bg-[#D7FF63] text-black font-medium cursor-pointer",children:"Authenticate"}),n.jsx("button",{onClick:()=>void j(),"data-testid":"provider-auth-checking-recheck",disabled:p,className:"px-3 py-2 text-sm rounded-md border border-[#3A3A3A] text-white cursor-pointer disabled:opacity-50",children:p?"Rechecking…":"Already logged in? Recheck"})]}),b]});const x=t==="claude"&&!r,w=a?` (token expired ${Vy(a)})`:"",k=x?`${h} credentials file is missing`:s==="token-expired"?`Your ${h} token has expired`:s==="api-401"?`${h} authentication rejected (401)`:`Connect your ${h} account`,C=x?"The editor couldn't find ~/.claude/.credentials.json on this machine — likely deleted between editor restarts (operator-side action, a Reconfigure, or a stale image). Re-seed by clicking Authenticate to run OAuth, or — on a fleet VM — copy the file from a donor VM through the dashboard.":s==="token-expired"?`Your ${h} token has expired${w} — click Authenticate to refresh it. On a fleet VM the dashboard can copy a fresh token from a donor VM.`:s==="api-401"?`The ${h} server rejected your credentials (401)${w}. This usually means the token was revoked or expired. Click Authenticate to re-connect.`:`Authentication used to happen inside the Build terminal. Now it lives here, out of your way. Connect ${h} to unlock the Build tab. On a cloud VM the dashboard usually does this for you; locally you connect once here.`;return n.jsxs("div",{"data-testid":"provider-auth-gate","data-auth-variant":x?"creds-missing":"needs-login","data-auth-card":!0,className:"m-4 rounded-lg border border-[#D7FF63]/40 bg-[#1E1E1E] p-5 space-y-3",children:[n.jsx("h2",{className:"text-base font-medium text-white",children:k}),n.jsx("p",{className:"text-sm text-[#8E8E8E]",children:C}),n.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[n.jsx("button",{onClick:()=>f(!0),className:"px-3 py-2 text-sm rounded-md bg-[#D7FF63] text-black font-medium cursor-pointer",children:"Authenticate"}),n.jsx("button",{onClick:()=>void j(),"data-testid":"provider-auth-gate-recheck",disabled:p,className:"px-3 py-2 text-sm rounded-md border border-[#3A3A3A] text-white cursor-pointer disabled:opacity-50",children:p?"Rechecking…":"Already logged in? Recheck"})]}),b]})}const Ky=300,ka=150;function Gy(e){const[t,r]=i.useState(null),s=i.useRef(!1),[a,o]=i.useState(!1),l=i.useCallback(()=>{var u;return((u=e.current)==null?void 0:u.clientWidth)??1200},[e]),c=t??Math.floor(l()/2),d=i.useCallback(u=>{u.preventDefault(),s.current=!0,o(!0)},[]);return i.useEffect(()=>{const u=p=>{var g;if(!s.current)return;const m=((g=e.current)==null?void 0:g.getBoundingClientRect().left)??0,h=p.clientX-m,v=l();h<ka?r(0):h>v-ka?r(v):r(Math.max(Ky,h))},f=()=>{s.current&&(s.current=!1,o(!1))};return document.addEventListener("mousemove",u),document.addEventListener("mouseup",f),()=>{document.removeEventListener("mousemove",u),document.removeEventListener("mouseup",f)}},[e,l]),{leftWidth:c,isDragging:a,handleMouseDown:d}}function Yy(e=768){const t=`(max-width: ${e-.02}px)`,[r,s]=i.useState(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(t).matches);return i.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const a=window.matchMedia(t);s(a.matches);const o=l=>s(l.matches);return a.addEventListener("change",o),()=>a.removeEventListener("change",o)},[t]),r}const qy=3e3;function Jy({hot:e,isInIframe:t,reload:r=()=>window.location.reload(),sustainedDisconnectMs:s=qy}){return()=>{}}function Xy(){i.useEffect(()=>Jy({hot:void 0,isInIframe:bt()}),[])}async function Qy(){Bt("\x1B"),await br(gr),Bt("/clear\r"),await br(gr),Bt("/codeyam-plan\r")}function Zy(){fetch("/api/clear-build-agent-session",{method:"POST"}).catch(()=>{})}function e1(e){const t=i.useRef(null),r=i.useRef(null);i.useEffect(()=>{if(typeof document>"u")return;r.current||(r.current=document.createElement("canvas"),r.current.width=64,r.current.height=64);const s=document.querySelector('link[rel="icon"]');if(!s){V("favicon-redraw",{idle:e,hasIcon:!1});return}if(t.current||(t.current=s.href),!e){s.href=t.current,V("favicon-restore",{});return}V("favicon-redraw",{idle:!0,hasIcon:!0});const a=new Image;a.crossOrigin="anonymous",a.onload=()=>{const o=r.current,l=o.getContext("2d");l.clearRect(0,0,64,64);const c=56,d=(64-c)/2;l.drawImage(a,d,d,c,c);const u=12,f=64-u-1,p=u+1;l.beginPath(),l.arc(f,p,u,0,2*Math.PI),l.fillStyle="#ef4444",l.fill(),s.href=o.toDataURL("image/png")},a.src=t.current},[e]),i.useEffect(()=>()=>{if(typeof document>"u")return;const s=document.querySelector('link[rel="icon"]');s&&t.current&&(s.href=t.current)},[])}const t1=120*1e3,di=1500;class n1{constructor(t,r,s=V){He(this,"deferred",!1);He(this,"userActiveSinceLastOutput",!1);He(this,"lastActivitySource",null);He(this,"lastActivityAt",null);He(this,"lastNotificationTime",null);He(this,"actions");He(this,"env");He(this,"now");He(this,"log");this.actions=t,this.env=r,this.now=r.now??(()=>Date.now()),this.log=s}reportUserActivity(t){this.userActiveSinceLastOutput=!0,this.lastActivitySource=t,this.lastActivityAt=this.now()}resetActivityFlag(){this.userActiveSinceLastOutput=!1}onIdle(t,r){this.deferred=!1;const s=this.env.hasBrowserFocus(),a=this.lastNotificationTime===null?null:this.now()-this.lastNotificationTime,o=this.lastActivityAt===null?null:this.now()-this.lastActivityAt,l={buildTabActive:r,hasBrowserFocus:s,msSinceLastNotification:a,userActiveSinceLastOutput:this.userActiveSinceLastOutput,lastActivitySource:this.lastActivitySource,msSinceLastActivity:o},c=o!==null&&o<di;if(r&&s&&c)return this.userActiveSinceLastOutput=!1,this.log("suppressed-user-active",l),"suppressed";if(a!==null&&a<t1)return this.log("cooldown",l),"cooldown";const d=this.notify(t);return this.log(d==="played"?"notify-played":"notify-played-no-sound",l),d}onBuildTabChange(t,r){return!t&&this.deferred?(this.deferred=!1,this.notify(r),!0):!1}onActive(){const t=this.deferred;this.deferred=!1,this.log("on-active",{hadDeferred:t}),this.actions.closeSystemNotification(),this.log("system-notification-closed-on-active",{hadDeferred:t})}onUserEngagement(){const t=this.deferred;return this.deferred=!1,t}get isDeferred(){return this.deferred}notify(t){const r=!!(t!=null&&t.sound)&&t.sound!=="off";r?(this.actions.playSound(t.sound),this.log("sound-played",{soundId:t.sound})):this.log("sound-skipped-off",{});const s=this.env.hasBrowserFocus(),a=typeof Notification<"u"?Notification.permission:"unknown";return!s&&(t!=null&&t.systemNotification)?this.env.hasNotificationPermission()?(this.actions.showSystemNotification(),this.log("system-notification-shown",{notificationPermission:a})):this.log("system-notification-skipped-no-permission",{notificationPermission:a}):s&&this.log("system-notification-skipped-focus",{notificationPermission:a}),this.lastNotificationTime=this.now(),r?"played":"played-no-sound"}}function r1(e,t){return new n1({playSound:qa,showSystemNotification:()=>{if(typeof Notification>"u"||Notification.permission!=="granted")return;t.current&&t.current.close();const r=e.current,s=new Notification(`${r} is ready for you`,{body:`${r} has finished and is waiting for your input.`,tag:"build-agent-idle"});s.onclick=()=>{window.focus(),s.close(),t.current=null},t.current=s},closeSystemNotification:()=>{typeof Notification>"u"||t.current&&(t.current.close(),t.current=null)}},{hasBrowserFocus:()=>document.hasFocus(),hasNotificationPermission:()=>typeof Notification<"u"&&Notification.permission==="granted"})}function s1(e,t){return e==="hook-stop"?t.idleOnStop:t.idleOnNotification}const a1=600*1e3,o1=3e3;function i1({agentName:e,isBuildTabActive:t,isAgentBuilding:r,buildSessionLive:s,featureCompleteKey:a,navigateToTab:o,onAgentIdleImmediate:l,onAgentActiveImmediate:c}){const d=i.useRef(e);d.current=e;const u=i.useRef(t);u.current=t;const f=i.useRef(l);f.current=l;const p=i.useRef(c);p.current=c;const[m,h]=i.useState(kd),[v,g]=i.useState(!1),y=i.useRef(!1);y.current=v;const j=i.useRef(!1),b=i.useRef(null),x=i.useRef(null),w=i.useRef(null),k=i.useRef(typeof document<"u"&&document.hidden?Date.now():null),C=i.useRef(null),N=i.useRef(s??!1);N.current=s??!1,e1(v),w.current||(w.current=r1(d,x));const E=i.useCallback(T=>{h(T),Nd(T)},[]),R=i.useCallback(T=>{b.current!==null&&(clearTimeout(b.current),b.current=null,V("debounce-cancelled",{trigger:T}))},[]),S=i.useCallback(T=>{y.current&&V("idle-cleared",{trigger:T}),g(!1),y.current=!1,C.current=null,x.current&&(x.current.close(),x.current=null)},[]),D=i.useCallback(T=>{var L;if(!s1(T,m)){V("idle-suppressed-by-pref",{source:T});return}V("ws-idle-received",{buildTabActive:u.current,source:T}),(L=f.current)==null||L.call(f),R("re-arm-on-idle"),b.current=setTimeout(()=>{var A;b.current=null;const W=k.current,B=W===null?null:Date.now()-W,Y=W!==null&&Date.now()-W>a1;V("debounce-resolved",{suppressedForOvernight:Y,msHidden:B,buildTabActive:u.current}),Y||(A=w.current)==null||A.onIdle(m,u.current),g(!0),y.current=!0,C.current=Date.now(),j.current=!1,V("agent-currently-idle-set",{suppressedForOvernight:Y}),u.current&&We()},di)},[m,R]),P=i.useCallback(()=>{var T,L,W;(T=p.current)==null||T.call(p),R("agent-active"),(L=w.current)==null||L.onActive(),(W=w.current)==null||W.resetActivityFlag(),y.current&&N.current&&C.current!==null&&Date.now()-C.current>o1&&S("remote-resume")},[R,S]),I=i.useCallback(()=>{var T,L;R("user-input"),y.current&&((T=w.current)==null||T.onUserEngagement(),(L=w.current)==null||L.reportUserActivity("terminal-input"),j.current=!0,S("user-input"))},[R,S]),O=i.useCallback(T=>{var L;T==="build"&&(R("navigate-build"),y.current&&((L=w.current)==null||L.onUserEngagement(),j.current=!0,S("navigate-build"))),o(T)},[o,R,S]),U=i.useCallback(()=>{var T;R("dismiss-banner"),(T=w.current)==null||T.onUserEngagement(),j.current=!0,S("dismiss-banner")},[R,S]);i.useEffect(()=>{function T(){var X;y.current&&(j.current||(R("ack-notification"),(X=w.current)==null||X.onUserEngagement(),j.current=!0,V("notification-acknowledged",{trigger:"user-return"})))}function L(X){var Z;y.current&&u.current&&document.hasFocus()&&(document.hidden||((Z=w.current)==null||Z.onUserEngagement(),j.current=!0,S(X)))}function W(X){var Z;document.hasFocus()&&T(),(Z=w.current)==null||Z.reportUserActivity(X)}const B=()=>W("mousemove"),Y=()=>W("mousedown"),A=()=>W("keydown");function F(){document.hidden?k.current===null&&(k.current=Date.now()):(k.current=null,T(),L("tab-visible-on-build"))}function M(){var X;T(),L("window-focus-on-build"),(X=w.current)==null||X.reportUserActivity("focus")}return window.addEventListener("focus",M),document.addEventListener("visibilitychange",F),document.addEventListener("mousemove",B),document.addEventListener("mousedown",Y),document.addEventListener("keydown",A),()=>{R("unmount"),window.removeEventListener("focus",M),document.removeEventListener("visibilitychange",F),document.removeEventListener("mousemove",B),document.removeEventListener("mousedown",Y),document.removeEventListener("keydown",A)}},[R,S]);const J=i.useRef(a??0);return i.useEffect(()=>{var W;const T=a??0;if(T===J.current)return;J.current=T;const L=u.current&&document.hasFocus();V("feature-complete-fast-path",{skipBecauseWatching:L}),!L&&((W=w.current)==null||W.onIdle(m,!1),g(!0),y.current=!0,C.current=Date.now(),j.current=!1)},[a,m]),i.useEffect(()=>{var T,L;if((T=w.current)==null||T.onBuildTabChange(t,m),t)return y.current&&typeof document<"u"&&document.hasFocus()&&!document.hidden&&((L=w.current)==null||L.onUserEngagement(),j.current=!0,S("build-tab-active-on-focus")),We()},[t,m,S]),{buildIdle:v,bannerVisible:v,notifSettings:m,handleSettingsChange:E,handleAgentIdle:D,handleAgentActive:P,handleUserInput:I,handleNavigateToTab:O,dismissIdleBanner:U}}const l1=1e4;function c1(e){const{isAgentBuilding:t,submittingBuildPrompt:r,launchingPlanSlug:s,sessionInfo:a,refetchSessionInfo:o}=e,[l,c]=i.useState(!1),d=i.useRef(!1),u=i.useCallback((f,p)=>{d.current!==f&&(V("build-session-live-change",{from:d.current,to:f,trigger:p}),d.current=f,c(f))},[]);return i.useEffect(()=>{t&&u(!0,"agent-active")},[t,u]),i.useEffect(()=>{r&&u(!0,"launch-prompt")},[r,u]),i.useEffect(()=>{s!==null&&u(!0,"launch-plan")},[s,u]),i.useEffect(()=>{(a==null?void 0:a.hasSession)===!0&&u(!0,"session-detected")},[a,u]),i.useEffect(()=>{(a==null?void 0:a.agentBrokerLive)===!0&&u(!0,"broker-live-detected")},[a,u]),i.useEffect(()=>{a&&!a.hasSession&&!a.agentBrokerLive&&u(!1,"session-ended")},[a,u]),i.useEffect(()=>{if(!l)return;const f=setInterval(()=>{o()},l1);return()=>clearInterval(f)},[l,o]),{buildSessionLive:l,transitionBuildSessionLive:u}}function Na(e){const{isAgentBuilding:t,trigger:r,transitionBuildSessionLive:s}=e;if(t){V("build-session-live-suppress-clear",{trigger:r,reason:"agent-still-active"});return}s(!1,r)}function d1(){const[e,t]=i.useState({loading:!1,error:null,downloaded:!1}),r=i.useCallback(async a=>{t({loading:!0,error:null,downloaded:!1});try{const l=await(await fetch("/api/editor-transcript-package")).json();if(!l.success){t({loading:!1,error:l.error||"Failed to package transcript",downloaded:!1});return}let c=l.content;a!=null&&a.trim()&&(c=`## User Notes
|
|
180
|
+
|
|
181
|
+
${a.trim()}
|
|
182
|
+
|
|
183
|
+
${c}`);const d=new Blob([c],{type:"text/markdown"}),u=URL.createObjectURL(d),f=document.createElement("a");f.href=u,f.download=l.filename,document.body.appendChild(f),f.click(),document.body.removeChild(f),URL.revokeObjectURL(u),t({loading:!1,error:null,downloaded:!0})}catch(o){t({loading:!1,error:o instanceof Error?o.message:"Network error",downloaded:!1})}},[]),s=i.useCallback(()=>{t({loading:!1,error:null,downloaded:!1})},[]);return{...e,sendTranscript:r,reset:s}}function u1(e,t){var o;const r="feedback@codeyam.com",s=encodeURIComponent(`CodeYam Session Feedback: ${e||"Session"}`+(t!=null&&t.category?` [${t.category}]`:"")),a=encodeURIComponent([((o=t==null?void 0:t.note)==null?void 0:o.trim())||"(no note)","","(Please attach the downloaded transcript file.)"].join(`
|
|
184
|
+
|
|
185
|
+
`));return`mailto:${r}?subject=${s}&body=${a}`}const f1=["bug","suggestion","question","praise"];function p1({featureName:e,onClose:t}){const[r,s]=i.useState(""),[a,o]=i.useState(null),[l,c]=i.useState(!1),{loading:d,error:u,downloaded:f,sendTranscript:p}=d1(),m=i.useCallback(()=>{p(r)},[p,r]),h=i.useCallback(()=>{navigator.clipboard.writeText("feedback@codeyam.com").then(()=>{c(!0),setTimeout(()=>c(!1),2e3)})},[]),v=i.useCallback(g=>{o(y=>y===g?null:g)},[]);return n.jsxs("div",{className:"max-w-md w-full mx-4 p-6 rounded-lg",style:{background:"var(--bg-surface)",border:"1px solid var(--border-default)"},children:[n.jsx("h2",{className:"text-lg font-semibold text-[var(--text-primary)] mb-2",children:"Send Session Transcript"}),n.jsx("p",{className:"text-sm text-[var(--text-muted)] mb-4",children:"Download your session transcript and send it to the CodeYam team for feedback or debugging."}),n.jsxs("div",{className:"mb-3",children:[n.jsx("span",{className:"block text-xs text-[var(--text-muted)] mb-1.5",children:"Tag (optional)"}),n.jsx("div",{className:"flex flex-wrap gap-1.5",children:f1.map(g=>{const y=a===g;return n.jsx("button",{type:"button","aria-pressed":y,onClick:()=>v(g),className:"px-2.5 py-1 rounded-full text-xs transition cursor-pointer",style:{background:y?"var(--accent-active)":"transparent",color:y?"var(--bg-deep)":"var(--text-secondary)",border:"1px solid var(--border-default)"},children:g},g)})})]}),n.jsx("textarea",{value:r,onChange:g=>s(g.target.value),placeholder:"What's on your mind? (optional)",className:"w-full h-20 px-3 py-2 text-sm rounded-md mb-4 resize-none",style:{background:"var(--bg-input, var(--bg-deep))",color:"var(--text-primary)",border:"1px solid var(--border-default)"}}),u&&n.jsx("p",{className:"text-sm text-red-400 mb-3",children:u}),n.jsxs("div",{className:"flex flex-col gap-3",children:[f?n.jsxs(n.Fragment,{children:[n.jsx("p",{className:"text-sm text-green-400 text-center",children:"Transcript downloaded!"}),n.jsx("a",{href:u1(e,{note:r,category:a}),className:"w-full px-4 py-2.5 rounded-md text-sm font-medium transition text-center block",style:{background:"var(--accent-active)",color:"var(--bg-deep)"},children:"Open Email Client"}),n.jsx("button",{onClick:h,className:"w-full px-4 py-2.5 rounded-md text-sm font-medium transition",style:{background:"transparent",color:"var(--text-secondary)",border:"1px solid var(--border-default)"},type:"button",children:l?"Copied!":"Copy Email Address"}),n.jsx("p",{className:"text-xs text-[var(--text-dim)] text-center",children:"Attach the downloaded file to your email"})]}):n.jsx("button",{onClick:m,disabled:d,className:"w-full px-4 py-2.5 rounded-md text-sm font-medium transition",style:{background:"var(--accent-active)",color:"var(--bg-deep)",opacity:d?.6:1},type:"button",children:d?"Packaging transcript...":"Download Transcript"}),n.jsx("button",{onClick:t,className:"w-full px-4 py-2.5 rounded-md text-sm font-medium transition",style:{background:"transparent",color:"var(--text-secondary)",border:f?"none":"1px solid var(--border-default)"},type:"button",children:f?"Done":"Cancel"})]})]})}function m1({sha:e,onClick:t}){if(!e)return null;const r=e.slice(0,6),s="font-mono text-[11px] leading-none px-1.5 py-0.5 rounded border border-white/5 bg-black/55 backdrop-blur-sm hover:bg-black/75";return n.jsx("div",{className:`fixed bottom-1 left-1 z-30 ${t?"":"pointer-events-none"}`,style:{paddingBottom:"env(safe-area-inset-bottom)"},children:t?n.jsx("button",{type:"button",onClick:t,"data-testid":"build-sha-badge",title:e,"aria-label":`Build commit ${e}`,className:`cursor-pointer ${s}`,style:{color:"var(--text-secondary)"},children:r}):n.jsx("span",{"data-testid":"build-sha-badge",title:e,"aria-label":`Build commit ${e}`,className:s,style:{color:"var(--text-secondary)"},children:r})})}function h1(){return`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/raw-terminal`}function x1(){if(bt())return null;const e=i.useRef(null),t=i.useRef(null),r=i.useRef(null),s=i.useRef(null),a=i.useRef(!1),[o,l]=i.useState(!1),[c,d]=Za(1200);function u(f){const p=s.current;(p==null?void 0:p.readyState)===WebSocket.OPEN&&p.send(new TextEncoder().encode(f))}return Qa(e,()=>{if(r.current&&t.current){r.current.fit();const f=s.current;(f==null?void 0:f.readyState)===WebSocket.OPEN&&f.send(JSON.stringify({type:"resize",cols:t.current.cols,rows:t.current.rows}))}}),i.useEffect(()=>{if(!e.current||a.current)return;a.current=!0;const f=new Sa.Terminal({cursorBlink:!0,fontSize:13,fontFamily:"'IBM Plex Mono', monospace",rightClickSelectsWord:!1,theme:{background:"#1e1e1e",foreground:"#cccccc",cursor:"#D7FF63",selectionBackground:"#264f78"}}),p=new Ea.FitAddon;f.loadAddon(p),f.open(e.current),t.current=f,r.current=p;const m=Ra(f,e.current,{onCopy:()=>d()}),h=Ta(f,{sendInput:u});requestAnimationFrame(()=>{p.fit(),f.focus()});const v=new WebSocket(h1());return s.current=v,v.binaryType="arraybuffer",v.onmessage=g=>{g.data instanceof ArrayBuffer&&f.write(new Uint8Array(g.data))},v.onopen=()=>{v.send(JSON.stringify({type:"resize",cols:f.cols,rows:f.rows}))},v.onclose=()=>{l(!0),f.writeln(`\r
|
|
186
|
+
\x1B[90m[Shell session ended]\x1B[0m`)},f.onData(u),()=>{var g;(g=s.current)==null||g.close(),h(),m(),f.dispose(),a.current=!1}},[]),n.jsxs("div",{className:"relative flex-1 flex flex-col",style:{minHeight:0},children:[n.jsx("div",{ref:e,className:"flex-1",style:{background:"#1e1e1e",minHeight:0,paddingTop:3,paddingLeft:3},onClick:()=>{var f;return(f=t.current)==null?void 0:f.focus()}}),o&&n.jsx("div",{role:"alert",className:"absolute bottom-2 left-2 rounded px-2 py-1 text-[11px]",style:{background:"var(--bg-card)",color:"var(--text-secondary)",border:"1px solid var(--border-subtle)"},children:"Shell disconnected — close and reopen for a fresh shell."}),c&&n.jsx(eo,{})]})}function g1({isOpen:e,onClose:t}){return i.useEffect(()=>{if(!e)return;const r=s=>{s.key==="Escape"&&t()};return document.addEventListener("keydown",r),()=>document.removeEventListener("keydown",r)},[e,t]),e?n.jsx("div",{role:"dialog","aria-modal":"true","aria-labelledby":"raw-terminal-modal-title",className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",onMouseDown:r=>{r.target===r.currentTarget&&t()},children:n.jsxs("div",{className:"flex flex-col rounded-lg shadow-xl",style:{width:"80vw",height:"80vh",maxWidth:1200,maxHeight:800,background:"var(--bg-surface)",border:"1px solid var(--border-default)"},children:[n.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-[var(--border-default)]",children:[n.jsx("h2",{id:"raw-terminal-modal-title",className:"text-sm font-semibold text-[var(--text-primary)] m-0",children:"Terminal"}),n.jsx("button",{type:"button",onClick:t,"data-testid":"raw-terminal-modal-close","aria-label":"Close terminal",className:"text-sm text-[var(--text-muted)] hover:text-[var(--text-primary)] cursor-pointer",children:"✕"})]}),n.jsx("div",{className:"flex-1 flex flex-col",style:{minHeight:0},children:n.jsx(x1,{})})]})}):null}let ar=null;function b1(e){if(typeof e!="object"||e===null)return null;const t=e.buildCommitSha;return typeof t!="string"||t===""||t==="unknown"?null:t}async function v1(){try{const e=await fetch("/api/health");return e.ok?b1(await e.json()):null}catch{return null}}function y1(){const[e,t]=i.useState(null);return i.useEffect(()=>{let r=!0;return ar||(ar=v1()),ar.then(s=>{r&&t(s)}),()=>{r=!1}},[]),{sha:e}}function w1(){var fs,ps;Xy();const{sha:e}=y1(),t=gl(),{state:r,provider:s,credsPresent:a,reason:o,expiresAt:l,probeInFlight:c,backendFieldAbsent:d,refresh:u}=$y(),f=r!=="authenticated",{activeTab:p,buildActivated:m,planActivated:h,navigateToTab:v,showBuildTab:g}=Qr(t,f,r==="needs-login"),[y,j]=i.useState(!1),[b,x]=i.useState(!1),[w,k]=i.useState(0),[C,N]=i.useState(0),[E,R]=i.useState(0),{showPostPushModal:S,onFeatureCompleteCommand:D,onAgentIdle:P,onAgentActive:I,dismissModal:O}=Ny(),{showPlanCompleteModal:U,onPlanCompleteCommand:J,dismissPlanCompleteModal:T}=Cy(),[L,W]=i.useState(!1),[B,Y]=i.useState(!1),[A,F]=i.useState(!1),[M,X]=i.useState(!1),Z=i.useCallback(()=>{F(!0)},[]),_=i.useCallback(()=>{F(!1)},[]),{plans:$,loading:Q,error:H,refetch:G}=Yr(),{reorderPlans:ae}=Oo(G),{launchPlan:z,launchingSlug:oe,error:pe}=Zr(),{launchPrompt:ne,launching:le,error:je}=Sy(),{sessionInfo:ie,refetch:te}=To({pollIntervalMs:15e3}),[Be,ke]=i.useState(!1),{stepState:K}=qt(),qe=i.useRef(null),{leftWidth:vt,handleMouseDown:Tt}=Gy(qe),Se=Yy(768),[_e,Ae]=i.useState("editor"),yt=i.useCallback(ee=>{Ae(ee),ee==="editor"&&(We(),typeof window<"u"&&window.dispatchEvent(new Event("resize")))},[]),be=Se?((fs=qe.current)==null?void 0:fs.clientWidth)??(typeof window<"u"?window.innerWidth:vt):vt,{entityLookup:Je}=ly(),{groups:Ee,loading:Re,refreshing:Xe,currentRunner:Qe,coverage:Te,refresh:Ze}=Y0(),{groups:we,loading:lt,reload:et}=W0(),{routeEntities:fe,loading:ve,error:he}=V0(),{config:q,apps:se,loading:ce,refetch:ue}=it(),ye=i.useMemo(()=>Ry(se,Ee,we),[se,we,Ee]),de=i.useCallback(()=>{j(ee=>!ee)},[]),Fe=i.useCallback(()=>{x(ee=>!ee)},[]),{selectedApp:xe,appRouteEntities:Le,appTestGroups:ct,selectedEntityHash:dt,selectedRouteEntity:Ie,previewSlug:Pe,setPreviewSlugExplicit:Pt,selectApp:An,deselectApp:as,selectRoute:Fn,selectEntity:ui,deselectRoute:fi}=ay(se,fe,we,Ee,t),{viewports:pi,resolvedViewport:Ln,previewUrl:mi,emptyStateMessage:hi,handleViewportChange:xi,handleCustomSizeChange:gi,showScenarioPreview:Xt,handlePreviewCommand:$e,setPreviewPath:Mn,previewSeeding:bi,previewSeedError:vi,commandNonce:yi}=ky({apps:se,appRouteEntities:Le,configLoaded:!ce,port:(q==null?void 0:q.port)??5173,previewOrigin:ja(q,xe),projectTitle:(q==null?void 0:q.projectTitle)??null,routeEntities:fe,screenSizes:(q==null?void 0:q.screenSizes)??{},defaultScreenSize:(q==null?void 0:q.defaultScreenSize)??null,scenarioGroups:we,scenariosLoaded:!lt,selectedApp:xe,selectedRouteEntity:Ie,previewSlug:Pe,setPreviewSlug:Pt}),{isAgentBuilding:Dt,isAgentBuildingRef:In,buildingScenarioSlug:$n,onAgentIdle:os,onAgentActive:is,guardScenarioSelect:ls,clearBuildingOverlay:tt}=Ey({onTransitionToLive:Xt}),On=(ie==null?void 0:ie.resumeMode)==="resume"||(ie==null?void 0:ie.resumeMode)==="handoff",{buildSessionLive:Bn,transitionBuildSessionLive:At}=c1({isAgentBuilding:Dt,submittingBuildPrompt:le,launchingPlanSlug:oe,sessionInfo:ie,refetchSessionInfo:te});i.useEffect(()=>{qr({hasActiveSession:On,isAgentBuilding:Dt,stepStateFeature:(K==null?void 0:K.feature)??null})},[On,Dt,K==null?void 0:K.feature]),i.useEffect(()=>{const ee=q==null?void 0:q.projectTitle;document.title=typeof ee=="string"&&ee.length>0?`CodeYam: ${ee}`:"CodeYam"},[q==null?void 0:q.projectTitle]);const wi=i.useCallback(()=>{P(),os()},[P,os]),ji=i.useCallback(()=>{I(),is()},[I,is]),Qt=(q==null?void 0:q.provider)??Er,ki=Ve(Qt),{buildIdle:cs,bannerVisible:Ni,notifSettings:Ci,handleSettingsChange:Si,handleAgentIdle:Ei,handleAgentActive:Ri,handleUserInput:Ti,handleNavigateToTab:Pi,dismissIdleBanner:Di}=i1({agentName:ki,isBuildTabActive:p==="build",isAgentBuilding:Dt,buildSessionLive:Bn,featureCompleteKey:E,navigateToTab:v,onAgentIdleImmediate:wi,onAgentActiveImmediate:ji}),ds=i.useCallback(ee=>{ls(ee)||Xt(ee)},[ls,Xt]),wt=i.useMemo(()=>Nr($n,we),[$n,we]),Ai=((ps=wt==null?void 0:wt.screenshotPaths)==null?void 0:ps[0])??null,Fi=(wt==null?void 0:wt.name)??null,Li=i.useCallback(ee=>{switch(ee.type){case"preview":("scenarioSlug"in ee||"scenarioId"in ee)&&et(),$e(ee);break;case"showResults":tt(),et(),k(ze=>ze+1),(K==null?void 0:K.mode)==="backend"&&$e({path:"/results",dimension:"Desktop"});break;case"hideResults":N(ze=>ze+1);break;case"featureComplete":tt(),D(),R(ze=>ze+1),ue(),Na({isAgentBuilding:In.current,trigger:"feature-complete",transitionBuildSessionLive:At});break;case"planComplete":J(),ue(),Na({isAgentBuilding:In.current,trigger:"plan-complete",transitionBuildSessionLive:At});break}},[tt,$e,In,D,J,ue,et,K,At]);iy(Li);const Zt=(K==null?void 0:K.slug)==="ui-confirm-plan"||(K==null?void 0:K.slug)==="backend-confirm-plan",_n=i.useRef(null);i.useEffect(()=>{if(!K||!Zt){_n.current=null;return}_n.current!==K.step&&(_n.current=K.step,$e({path:"/plan-preview",dimension:"Desktop"}))},[K,Zt,$e]);const zn=i.useRef(null);i.useEffect(()=>{if(!K||K.mode!=="backend"||K.step<2||Zt){zn.current=null;return}zn.current!==K.step&&(zn.current=K.step,$e({path:"/results",dimension:"Desktop"}))},[K,Zt,$e]);const Hn=i.useRef(!1);i.useEffect(()=>{(K==null?void 0:K.slug)==="ui-confirm-plan"?Hn.current=!0:Hn.current&&(Hn.current=!1,Mn(null))},[K,Mn]);const Mi=i.useCallback(async()=>{O(),await xh({provider:Qt,renameLabel:(K==null?void 0:K.feature)??void 0,caller:"post-push-modal",bypassLiveGuard:!0}),We()},[O,Qt,K]),Ii=i.useCallback(()=>{O(),We()},[O]),$i=i.useCallback(async()=>{await hh(),O(),At(!1,"stop-building"),tt(),te()},[O,At,tt,te]),Oi=i.useCallback(()=>{Qy(),T(),We()},[T]),Bi=i.useCallback(()=>{W(!1),Zy(),T()},[T]),_i=i.useCallback(()=>{Y(!0)},[]),zi=i.useCallback(()=>{Y(!1)},[]),Hi=i.useCallback(async(ee,ze)=>{await z(ee,ze)&&(Y(!1),ke(!0),O(),te())},[z,O,te]),Wi=i.useCallback(async ee=>{await ne(ee)&&(ke(!0),te())},[ne,te]),Vi=i.useCallback(()=>{ke(!0)},[]),us=Ly({activeTab:p,hasActiveSession:On,isAgentBuilding:Dt,showPostPushModal:S,launchingPlanSlug:oe,submittingBuildPrompt:le,stepStateFeature:(K==null?void 0:K.feature)??null,pendingPlanCount:$.length,buildLaunchModalDismissed:Be}),Ui=us||B;i.useEffect(()=>{p==="build"&&te()},[p,te]),i.useEffect(()=>{p==="home"&&ue()},[p,ue]);const Ki=i.useCallback(async(ee,ze)=>{tt(),$e(Fy(ee,ze))},[tt,$e]),Gi=i.useCallback(ee=>{(ee.scenarioSlug||ee.path)&&$e({...ee.scenarioSlug?{scenarioSlug:ee.scenarioSlug}:{},...ee.path?{path:ee.path}:{},...ee.dimension?{dimension:ee.dimension}:{}})},[$e]),Yi=i.useMemo(()=>({apps:se,isSingleApp:se.length===1,onSelectApps:as,onSelectApp:An,onSelectRoute:Fn}),[se,as,An,Fn]),qi=i.useMemo(()=>xe?ye.find(ee=>ee.app.dir===xe.dir)??null:null,[ye,xe]),Ji=n.jsxs(n.Fragment,{children:[n.jsx(Mo,{staleness:null,backendOutOfDate:d}),n.jsx(Uy,{state:r,provider:s,credsPresent:a,reason:o,expiresAt:l,probeInFlight:c,backendOutOfDate:d,onAuthenticated:u,onAuthorized:()=>v("build")}),n.jsx(qm,{selectedApp:xe,appDetailProps:{navContext:Yi,routeEntities:Le,routesLoading:ve,routesError:he,selectedEntityHash:dt,selectedRouteEntity:Ie,testGroups:ct,selectedSlug:Pe,entityLookup:Je,allScenarios:we.flatMap(ee=>ee.scenarios),onSelectScenario:ds,onSelectRoute:Fn,onSelectEntity:ui,onBackToRoutes:fi,onScenariosChanged:et,projectTitle:(q==null?void 0:q.projectTitle)??null,coverage:Te,showProjectBand:se.length===1,stats:qi,testsLoading:Re,testsRefreshing:Xe,onRunTests:Ze,currentRunner:Qe},appOverviewProps:{projectTitle:(q==null?void 0:q.projectTitle)??"Project",projectDescription:(q==null?void 0:q.projectDescription)??null,stats:ye,coverage:Te,onSelectApp:An,configLoading:ce,testsLoading:Re,testsRefreshing:Xe,onRunTests:Ze,currentRunner:Qe,stepState:K,onPreviewUrl:Mn,onComplete:async()=>{await ue(),v("build")},onOpenBuildTab:()=>v("build")}})]});return n.jsxs(n.Fragment,{children:[n.jsx(eh,{splitRef:qe,isCollapsed:y,onResizeStart:Tt,isNarrow:Se,mobilePane:_e,onMobilePaneChange:yt,isAgentBuilding:Bn,buildIdle:cs,leftPane:n.jsx(ux,{activeTab:p,onSendTranscript:Z,appTabContent:Ji,awaitingPlanLaunchChoice:Ui,buildActivated:m,planActivated:h,buildIdle:cs,isAgentBuilding:Bn,bannerVisible:Ni,onDismissIdleBanner:Di,hideResultsCommandKey:C,leftWidth:be,fullWidth:Se,navigateToTab:Pi,onAgentActive:Ri,onAgentIdle:Ei,onUserInput:Ti,notifSettings:Ci,onSettingsChange:Si,provider:Qt,onRestorePreview:Gi,onResultsScenarioSelect:Ki,previewSlug:Pe,onSessionDetected:g,showPostPushModal:S,onStartNextFeature:Mi,onContinueInSession:Ii,onStopBuilding:$i,showResultsCommandKey:w,planChatOpen:L,onPlanChatOpenChange:W,showPlanCompleteModal:U,onCreateNewPlan:Oi,onViewPlans:Bi,pendingPlans:$,onSelectPlan:_i,selectPlanOpen:B,onPickPlan:Hi,onCancelSelectPlan:zi,launchingPlanSlug:oe,planLaunchError:pe,showBuildLaunchModal:us,onSubmitBuildPrompt:Wi,submittingBuildPrompt:le,buildPromptError:je,onCancelBuildLaunchModal:Vi,pendingPlansLoading:Q,pendingPlansError:H,onReorderPlans:ae,buildDisabled:f}),previewPane:n.jsx(H0,{emptyStateMessage:Ay({configLoading:ce,hasNoApps:ye.length===0,hasStepState:!!K,defaultMessage:hi}),firstSessionSetup:ye.length===0&&!!K,previewSlug:Pe,previewUrl:mi,viewports:pi,activeViewport:Ln.name,onViewportChange:xi,isCollapsed:y,onToggleCollapsed:de,isNarrow:Se,isFilled:b,onToggleFilled:Fe,currentWidth:Ln.width,currentHeight:Ln.height,onCustomSizeChange:gi,buildingScenarioSlug:$n,buildingScreenshotPath:Ai,buildingScenarioName:Fi,onDismissBuildingOverlay:tt,previewSeeding:bi,previewSeedError:vi,onRetrySeed:()=>{Pe&&Xt(Pe)},currentScenario:Nr(Pe,we),scenarioGroups:we,onShowScenarioPreview:ds,commandNonce:yi,previewOrigin:ja(q,xe),onDesignConfirmed:()=>v("build")})}),A?n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center",style:{background:"rgba(30, 30, 30, 0.90)"},children:n.jsx(p1,{featureName:(K==null?void 0:K.feature)??null,onClose:_})}):null,n.jsx(g1,{isOpen:M,onClose:()=>X(!1)}),n.jsx(m1,{sha:e,onClick:()=>X(!0)})]})}const P1=Object.freeze(Object.defineProperty({__proto__:null,EditorShell:w1},Symbol.toStringTag,{value:"Module"}));export{Av as $,Ll as A,Ml as B,Wa as C,Fl as D,Lm as E,Pl as F,Al as G,Po as H,n0 as I,$l as J,jc as K,wc as L,yc as M,Oa as N,m1 as O,Db as P,Do as Q,mv as R,qc as S,Gc as T,vv as U,wv as V,jv as W,kv as X,yv as Y,Cv as Z,xv as _,uc as a,cx as a$,Rv as a0,Ev as a1,Pv as a2,Dv as a3,Tv as a4,zd as a5,_d as a6,Od as a7,$d as a8,Id as a9,Vx as aA,hm as aB,ym as aC,bb as aD,ei as aE,vb as aF,jb as aG,xb as aH,hb as aI,mb as aJ,la as aK,Cb as aL,Nb as aM,Kx as aN,kb as aO,gb as aP,yb as aQ,Sb as aR,Vu as aS,Wu as aT,x1 as aU,g1 as aV,Uu as aW,ax as aX,sx as aY,dx as aZ,lx as a_,Bd as aa,jl as ab,yl as ac,bl as ad,hs as ae,vl as af,Um as ag,Bm as ah,_m as ai,zm as aj,Vm as ak,Hm as al,Wm as am,Km as an,Gm as ao,Lx as ap,Ax as aq,Fo as ar,Gr as as,Fx as at,Lo as au,Jt as av,Ka as aw,Dx as ax,Px as ay,Tx as az,Kn as b,kc as b$,rx as b0,Mr as b1,Gh as b2,Yh as b3,qh as b4,Kp as b5,Wh as b6,Hh as b7,zh as b8,Vh as b9,kh as bA,Fh as bB,Ah as bC,bh as bD,Xh as bE,tx as bF,ub as bG,db as bH,Vn as bI,Sl as bJ,Kl as bK,zl as bL,Jl as bM,w1 as bN,ia as bO,cb as bP,wl as bQ,dc as bR,Cc as bS,Sc as bT,Nc as bU,Zh as bV,fm as bW,pm as bX,Il as bY,Fa as bZ,vc as b_,Uh as ba,Mh as bb,Ih as bc,Kr as bd,wh as be,yh as bf,vh as bg,Up as bh,Wp as bi,Op as bj,Hp as bk,$p as bl,Vp as bm,_p as bn,Bp as bo,zp as bp,Mp as bq,Ro as br,Co as bs,Bo as bt,Eh as bu,Th as bv,Gs as bw,Ch as bx,Dh as by,Lh as bz,T1 as c,fg as c$,La as c0,xc as c1,mc as c2,pc as c3,fc as c4,hc as c5,gc as c6,ac as c7,lc as c8,ic as c9,v0 as cA,y0 as cB,ib as cC,R0 as cD,E0 as cE,Rb as cF,Eb as cG,Tb as cH,Ux as cI,Lb as cJ,Pb as cK,b0 as cL,um as cM,Xm as cN,Mt as cO,cu as cP,iu as cQ,lu as cR,lb as cS,ob as cT,Jg as cU,rb as cV,tb as cW,Kg as cX,Hg as cY,Yg as cZ,qg as c_,sc as ca,oc as cb,Zl as cc,Ql as cd,Da as ce,gs as cf,Lc as cg,Mc as ch,Pc as ci,Vc as cj,Fc as ck,Tc as cl,Rc as cm,xs as cn,Wn as co,Ec as cp,pt as cq,du as cr,O0 as cs,_0 as ct,L0 as cu,A0 as cv,H0 as cw,l0 as cx,N0 as cy,C0 as cz,Ar as d,Oy as d$,su as d0,au as d1,nu as d2,Zd as d3,mu as d4,hd as d5,pd as d6,dd as d7,cd as d8,ld as d9,Am as dA,Dm as dB,Yv as dC,Jv as dD,Kv as dE,Uv as dF,Vv as dG,Xv as dH,Gv as dI,Wv as dJ,qv as dK,zv as dL,_v as dM,Dr as dN,Ul as dO,Aa as dP,Ku as dQ,$u as dR,Yp as dS,Eu as dT,gu as dU,Pm as dV,xu as dW,mm as dX,hu as dY,Uc as dZ,kl as d_,id as da,ex as db,ws as dc,Fd as dd,Ld as de,bd as df,Ga as dg,wd as dh,Lr as di,dm as dj,Zm as dk,nx as dl,Qh as dm,ux as dn,eh as dp,Jm as dq,qm as dr,Nu as ds,Xn as dt,Su as du,ku as dv,ju as dw,wu as dx,Mm as dy,$m as dz,Kc as e,zy as e0,Hy as e1,Uy as e2,P1 as e3,Ha as f,p1 as g,ft as h,t0 as i,a0 as j,r0 as k,e0 as l,i0 as m,rv as n,Qv as o,Ia as p,ln as q,Ge as r,_x as s,Ox as t,$x as u,Ix as v,Mx as w,zx as x,P0 as y,T0 as z};
|