@codeyam-editor/codeyam-editor 0.1.0-staging.27ed016
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 +16 -0
- package/npm/container.js +35 -0
- package/npm/editor-dev.js +128 -0
- package/npm/editor.js +191 -0
- package/npm/open.js +15 -0
- package/npm/scenario-check.js +215 -0
- package/npm/scenario-handlers.js +71 -0
- package/npm/scenario-issues.js +35 -0
- package/npm/scenario-metrics.js +94 -0
- package/npm/scenario-mocks.js +70 -0
- package/npm/scenario-playwright.js +192 -0
- package/npm/utils.js +356 -0
- package/package.json +32 -0
- package/ui/dist/assets/ContainerInspector-CVhTYjTR.js +2 -0
- package/ui/dist/assets/EditorShell-1FTR28BA.js +32 -0
- package/ui/dist/assets/Markdown-BHBqz-Mj.js +1 -0
- package/ui/dist/assets/ScenarioDataPanel-Bb7egwjC.js +5 -0
- package/ui/dist/assets/ScenarioDataPanel-DYP7pi_n.css +32 -0
- package/ui/dist/assets/ScenarioDataPanelFullPage-I0tbkDlL.js +1 -0
- package/ui/dist/assets/ScenarioRenderer-DIwirbX6.js +1 -0
- package/ui/dist/assets/StepsSimulator-CRtmlyNZ.js +1 -0
- package/ui/dist/assets/index-6jueUhB_.js +27 -0
- package/ui/dist/assets/index-Bik6WLGP.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
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
var uo=Object.defineProperty;var fo=(e,t,r)=>t in e?uo(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Le=(e,t,r)=>fo(e,typeof t!="symbol"?t+"":t,r);import{j as n}from"./markdown-v0F0UEt3.js";import{b as i,R as be,c as ut}from"./react-CSS0HapR.js";import{S as po,P as Vt,Q as Rn,R as vs,U as bs,V as mo,W as xo,X as ho,Y as go,Z as vo,O as bo,_ as yo,$ as wo,a0 as jo,b as ys,a1 as yt,f as No,a2 as wr,a3 as Ut,u as Co,x as So,v as ko,a4 as Eo,a5 as Ro,a6 as ws,a7 as To,a8 as Do,a9 as Po,aa as jr,ab as Ao,ac as Lo,ad as Mo}from"./ScenarioDataPanel-Bb7egwjC.js";import{e as Io,a as Oo,l as z,g as Vn,d as Fo,p as Kt,t as Bo,u as $o}from"./index-6jueUhB_.js";import{M as ot}from"./Markdown-BHBqz-Mj.js";function Nr({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 Ho({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 _o({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 n.jsxs("div",{className:"px-5 pb-5 pt-2 flex items-center gap-5 border-t border-[var(--border-default)]",children:[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(Ho,{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(Nr,{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(Nr,{onRunTests:s})]}):n.jsx("span",{className:"text-xs text-[var(--text-dim)]",children:"No tests"}),n.jsx("span",{className:"text-[var(--text-dim)] group-hover:text-[var(--accent-active)] transition ml-auto text-sm",children:"→"})]})}function js({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 zo({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(js,{type:e.type})]}),e.description?n.jsx("p",{className:"text-sm text-[var(--text-muted)] leading-relaxed",children:e.description}):null]})}function Fe(e){return e.startsWith("http")?e:`/api/screenshots/${e}`}function Wo({thumbnails:e}){return n.jsx("div",{className:"flex gap-2 overflow-hidden",children:e.map((t,r)=>n.jsx("img",{src:Fe(t),alt:"",className:"h-20 w-32 rounded border border-[var(--border-default)] object-cover object-top"},`${t}:${r}`))})}function Vo({thumbnails:e}){return n.jsx("div",{className:"px-5 py-3 flex-1",children:e.length>0?n.jsx(Wo,{thumbnails:e.slice(0,4)}):n.jsx("div",{className:"h-20"})})}function Uo({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(zo,{app:l}),n.jsx(Vo,{thumbnails:d.thumbnails}),n.jsx(_o,{tests:c,loading:r,refreshing:s,onRunTests:a,currentRunner:o})]})}function Ko({message:e}){return n.jsx("div",{className:"px-5 py-8 text-center text-[var(--accent-red)]",children:e})}function Yo(){return n.jsx("div",{className:"px-5 py-8 text-center text-[var(--text-dim)]",children:"Loading routes..."})}function Ns(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 wt(e){return(e.split("/").pop()??e).replace(/\.[^.]+$/,"")}function Go(e){const t=[],r=[];for(const s of e){const a=wt(s);/^[A-Z]/.test(a)&&!a.startsWith("use")?t.push(s):r.push(s)}return{componentImports:t,functionImports:r}}function zt(e){const t=[];for(const r of e.split("/"))r===""||r==="."||(r===".."?t.pop():t.push(r));return t.join("/")}function Jo(e){const t=new Map;for(const[r,s]of Object.entries(e)){const a=zt(r),o=wt(a),l=Ns(a,o);t.has(l)||t.set(l,{hash:l,filePath:a,entityName:o,imports:s.imports.map(zt),importedBy:s.importedBy.map(zt)})}return t}function Xo(e,t){if(!e)return null;const r=zt(t);for(const s of e.values())if(s.filePath===r)return s;return null}function Cs(e,t){if(!e)return[];const r=[];for(const s of t){const a=Xo(e,s);a&&r.push(a)}return r}function qo(e,t){return e.find(r=>r.pageFilePath===t)??null}function Ss(e){const t=e.split("/"),r=t.pop()??e,s=t.join("/");return{fileName:r,dirPath:s}}function Qo({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 Zo({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:Fe(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 ei({importPath:e,entity:t,scenarios:r,onNavigate:s,onSelectScenario:a}){const{fileName:o,dirPath:l}=Ss(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(Qo,{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(Zo,{scenarios:r,onSelectScenario:a})]})}function ti(){return n.jsx("p",{className:"py-4 text-center text-xs text-[var(--text-dim)]",children:"No dependencies found"})}function ni({directImports:e,entityLookup:t,allScenarios:r,routeEntities:s,onNavigateToRoute:a,onSelectScenario:o}){const l=i.useMemo(()=>Cs(t,e),[t,e]);return e.length===0?n.jsx(ti,{}):n.jsx("div",{className:"grid grid-cols-1 gap-1",children:e.map(c=>{const d=l.find(m=>m.filePath===c)??null,u=(d==null?void 0:d.entityName)??wt(c),f=(r??[]).filter(m=>m.scenarioType==="component"&&(m.pageFilePath===c||m.componentName===u)),p=qo(s??[],c);return n.jsx(ei,{importPath:c,entity:d,scenarios:f,onNavigate:p?()=>a(p.route):null,onSelectScenario:o},c)})})}function ri(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 si({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 ai({test:e}){const t=e.description.length>0;return n.jsxs("div",{className:"flex items-start gap-2 py-1",children:[n.jsx(si,{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 oi({importPath:e,entityName:t,tests:r}){const{dirPath:s}=Ss(e);return n.jsxs("div",{className:"rounded-lg border border-[var(--border-subtle)] bg-[var(--bg-card)] p-3",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:[s,"/"]}),n.jsx("div",{className:"mt-2",children:r.length>0?n.jsx("div",{className:"space-y-0.5",children:r.map((a,o)=>n.jsx(ai,{test:a},`${a.file}:${a.key??a.line??o}`))}):n.jsx("p",{className:"text-xs text-[var(--text-dim)] italic",children:"No tests"})})]})}function ii(){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 li({functionImports:e,entityLookup:t,testGroups:r}){const s=i.useMemo(()=>Cs(t,e),[t,e]);return e.length===0?n.jsx(ii,{}):n.jsx("div",{className:"grid grid-cols-1 gap-1",children:e.map(a=>{const o=s.find(d=>d.filePath===a)??null,l=(o==null?void 0:o.entityName)??wt(a),c=ri(a,t,r);return n.jsx(oi,{importPath:a,entityName:l,tests:c},a)})})}function ci(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 x=await m.json();x.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(x)}),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 di(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 ui({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 fi({overrideCounts:e}){const t=e?ui(e):null;return t?n.jsx("div",{className:"text-xs text-[var(--text-dim)] mt-1",children:t}):null}const pi=new Set(["Desktop"]);function mi({scenario:e,isSelected:t}){const r=e.dimensions.length>0&&!(e.dimensions.length===1&&pi.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(fi,{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 xi({screenshotPath:e}){const[t,r]=i.useState(!1);return e&&!t?n.jsx("img",{src:Fe(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 hi({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 gi({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 vi({scenario:e,isSelected:t,onSelect:r,onViewData:s,onScenariosChanged:a,children:o}){const l=ci(e.slug,e.name,a),{deleting:c,handleDelete:d}=di(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(xi,{screenshotPath:e.screenshotPaths[0]??null}),n.jsx("div",{className:"flex-1 min-w-0",children:l.renaming?n.jsx(gi,{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(mi,{scenario:e,isSelected:t}),t&&n.jsx(hi,{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 bi(){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 yi({scenarios:e,selectedSlug:t,onSelectScenario:r,onScenariosChanged:s}){const[a,o]=i.useState(null);return e.length===0?n.jsx(bi,{}):n.jsx("div",{className:"grid grid-cols-1 gap-2",children:e.map(l=>n.jsx(vi,{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(po,{variant:"inline",slug:l.slug,scenarioName:l.name,onClose:()=>o(null)})},l.slug))})}function wi({activeTab:e,routeEntity:t,componentImports:r,functionImports:s,testGroups:a,selectedSlug:o,entityLookup:l,allScenarios:c,routeEntities:d,onSelectScenario:u,onNavigateToRoute:f,onScenariosChanged:p}){return n.jsxs("div",{className:"flex-1 overflow-auto px-5 py-4",children:[e==="scenarios"&&n.jsx(yi,{scenarios:t.scenarios,selectedSlug:o,onSelectScenario:u,onScenariosChanged:p}),e==="components"&&n.jsx(ni,{directImports:r,entityLookup:l,allScenarios:c,routeEntities:d,onNavigateToRoute:f,onSelectScenario:u}),e==="functions"&&n.jsx(li,{functionImports:s,entityLookup:l,testGroups:a})]})}function ji({displayName:e,pageFilePath:t,onBack:r}){return n.jsxs("div",{className:"px-5 py-4",children:[n.jsx("button",{onClick:r,className:"mb-2 flex items-center gap-1 text-xs text-[var(--text-dim)] hover:text-[var(--text-primary)] transition",type:"button",children:"← Back"}),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 Ni({activeTab:e,onTabChange:t,scenarioCount:r,componentCount:s,functionCount:a}){const o=[{key:"scenarios",label:"Scenarios",count:r},{key:"components",label:"Components",count:s},{key:"functions",label:"Functions",count:a}];return n.jsx("div",{className:"flex w-full border-t border-b border-[var(--border-default)]",children:o.map(l=>n.jsxs("button",{onClick:()=>t(l.key),className:`px-4 py-2 font-mono text-xs font-medium uppercase tracking-wider transition border-b-2 ${e===l.key?"text-[var(--accent-active)] border-[var(--accent-active)]":"text-[var(--text-dim)] border-transparent hover:text-[var(--text-muted)]"}`,type:"button",children:[l.label," (",l.count,")"]},l.key))})}function Ci({routeEntity:e,selectedSlug:t,entityLookup:r,allScenarios:s,routeEntities:a,testGroups:o,onSelectScenario:l,onNavigateToRoute:c,onBack:d,onScenariosChanged:u}){const[f,p]=i.useState("scenarios"),{componentImports:m,functionImports:x}=i.useMemo(()=>Go(e.directImports),[e.directImports]);return n.jsxs("div",{className:"flex flex-col",children:[n.jsx(ji,{displayName:e.displayName,pageFilePath:e.pageFilePath,onBack:d}),n.jsx(Ni,{activeTab:f,onTabChange:p,scenarioCount:e.scenarios.length,componentCount:m.length,functionCount:x.length}),n.jsx(wi,{activeTab:f,routeEntity:e,componentImports:m,functionImports:x,testGroups:o,selectedSlug:t,entityLookup:r,allScenarios:s,routeEntities:a,onSelectScenario:l,onNavigateToRoute:c,onScenariosChanged:u})]})}function Cr(e){const t=Io(e);if(t)return{selectedAppDir:t,selectedEntityHash:null};const r=Oo(e);return r?{selectedAppDir:null,selectedEntityHash:r}:{selectedAppDir:null,selectedEntityHash:null}}function Sr(e){return`/apps/${e}`}function Si(e){return`/entities/${e}`}function Tn(e){return e.pageFilePath?Ns(e.pageFilePath,wt(e.pageFilePath)):null}function ks(e){const t=Tn(e);return t===null?null:Si(t)}function Yt({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 ki({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:Fe(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 Ei({routeEntity:e,onSelectRoute:t,onSelectScenario:r}){const s=e.scenarios.length,a=ks(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(Yt,{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(ki,{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 Ri(){return n.jsx("div",{className:"px-5 py-8 text-center text-[var(--text-dim)]",children:"No routes discovered yet."})}function Ti(){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 Di({routeEntities:e,onSelectRoute:t,onSelectScenario:r}){return e.length===0?n.jsx(Ri,{}):n.jsxs("div",{className:"px-5 py-5",children:[n.jsx(Ti,{}),n.jsx("div",{children:e.map(s=>n.jsx(Ei,{routeEntity:s,onSelectRoute:t,onSelectScenario:r},s.route))})]})}function Pi({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 Ai({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 Li({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(Pi,{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(Ai,{test:o},`${o.file}-${o.key??o.line??l}`))})]},t.feature)})})}function Mi({isWeb:e,routeEntities:t,routesLoading:r,routesError:s,selectedRouteEntity:a,testGroups:o,selectedSlug:l,entityLookup:c,allScenarios:d,onSelectScenario:u,onSelectRoute:f,onBackToRoutes:p,onScenariosChanged:m}){return e?r?n.jsx(Yo,{}):s?n.jsx(Ko,{message:s}):a?n.jsx(Ci,{routeEntity:a,selectedSlug:l,entityLookup:c,allScenarios:d,routeEntities:t,testGroups:o,onSelectScenario:u,onNavigateToRoute:f,onBack:p,onScenariosChanged:m}):n.jsx(Di,{routeEntities:t,onSelectRoute:f,onSelectScenario:u}):n.jsx(Li,{groups:o})}function Ii({app:e,showRouteDetail:t,onBack:r}){return t?null:n.jsxs("div",{className:"px-5 py-4 border-b border-[var(--border-default)]",children:[n.jsx(Yt,{href:"/apps",onNavigate:r,className:"mb-2 flex items-center gap-1 text-xs text-[var(--text-dim)] hover:text-[var(--text-primary)] transition",children:"← All Apps"}),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(js,{type:e.type})]}),e.description?n.jsx("p",{className:"text-sm text-[var(--text-muted)] mt-1",children:e.description}):null]})}function Oi({app:e,routeEntities:t,routesLoading:r,routesError:s,selectedRouteEntity:a,testGroups:o,selectedSlug:l,entityLookup:c,allScenarios:d,onSelectScenario:u,onSelectRoute:f,onBackToRoutes:p,onBack:m,onScenariosChanged:x}){const j=e.type==="web";return n.jsxs("div",{children:[n.jsx(Ii,{app:e,showRouteDetail:!!a,onBack:m}),n.jsx(Mi,{isWeb:j,routeEntities:t,routesLoading:r,routesError:s,selectedRouteEntity:a,testGroups:o,selectedSlug:l,entityLookup:c,allScenarios:d,onSelectScenario:u,onSelectRoute:f,onBackToRoutes:p,onScenariosChanged:x})]})}function Es(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 Fi(e){switch(e){case"feature":return"text-blue-400";case"fix":return"text-red-400";case"refactor":return"text-purple-400";case"milestone":return"text-yellow-400";default:return"text-gray-400"}}function Hg(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 Bi({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 $i=192;function Rs({children:e,variant:t="compact",maxHeight:r=$i}){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(ot,{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 Hi({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:Fe(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 _i={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"},zi={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"},Wi={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."},Vi={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."},Ui=24,Ts=19;function Ie(e){return e==="backend"?"backend":"ui"}function Un(e,t){return(Ie(t)==="backend"?zi:_i)[e]??"?"}function Ki(e,t){return(Ie(t)==="backend"?Vi:Wi)[e]??""}function Yi(e){return Ie(e)==="backend"?Ts:Ui}function Gi(e){return Ie(e)==="backend"?"Backend Flow":"UI Flow"}function Ds(e,t){const r=Ie(t);return{description:Ki(e,r),label:Un(e,r),prefix:Gi(r),totalSteps:Yi(r)}}const Ji={1:"Understanding your idea",2:"Looking through your project",3:"Confirming the approach with you",4:"Preparing your workspace",5:"Adding sample data",6:"Building your app",7:"Checking the prototype",8:"Confirming the next step with you",9:"Showing you the result",10:"Reading the code carefully",11:"Adding tests",12:"Documenting the building blocks",13:"Mapping connections in your code",14:"Setting up isolation routes",15:"Capturing component snapshots",16:"Capturing whole-page snapshots",17:"Showing you the final review",18:"Reconciling everything",19:"Finalizing the build",20:"Writing a journal entry",21:"Syncing with the latest",22:"Saving your changes",23:"Pushing your work",24:"All done"},Xi={1:"Understanding your idea",2:"Looking through your project",3:"Confirming the approach with you",4:"Preparing your workspace",5:"Building your app",6:"Confirming the next step with you",7:"Showing you the result",8:"Reading the code carefully",9:"Adding tests",10:"Documenting the building blocks",11:"Mapping connections in your code",12:"Showing you the final review",13:"Reconciling everything",14:"Finalizing the build",15:"Writing a journal entry",16:"Syncing with the latest",17:"Saving your changes",18:"Pushing your work",19:"All done"},qi=[{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:"Tidying the code so it stays 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]}],Qi=[{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:"Tidying the code so it stays 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 Zi(e,t){return(Ie(t)==="backend"?Xi:Ji)[e]??""}function el(e){return Ie(e)==="backend"?Qi:qi}function tl({currentStep:e}){const t=Array.from({length:Ts},(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=Un(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 Dn(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 nl({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:Dn(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:Dn(a.duration_ms)})]})]},a.name))})]})}function Ps({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-blue-400 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 rl({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(Ps,{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 sl({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(al,{change:t},r))]})}function al({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(ol,{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 ol({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(Ps,{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 il({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(kr,{label:"Files Modified",value:t}),n.jsx(kr,{label:"Tests Modified",value:r,color:r>0?"green":void 0})]})]})})}function kr({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 Kn({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 ll=[/\.test\.[jt]sx?$/,/\.spec\.[jt]sx?$/,/__tests__\//,/tests?\//];function xn(e){return ll.some(t=>t.test(e))}function cl({files:e,defaultCollapsed:t}){const[r,s]=i.useState(t),a=e.filter(d=>d.path&&xn(d.path)),o=e.filter(d=>d.path&&d.path.endsWith(".rs")&&!xn(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&&!xn(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(Mt,{title:"Tests",files:a}),o.length>0&&n.jsx(Mt,{title:"Rust Source",files:o}),c.length>0&&n.jsx(Mt,{title:"Other Source",files:c}),l.length>0&&n.jsx(Mt,{title:"Configuration",files:l})]})]})}function Mt({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(Kn,{status:r.status}),n.jsx("span",{children:r.path})]},r.path))})]})}const dl=5e3,Er=50;function ul(){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"),x=i.useRef([]),j=i.useRef(null);i.useEffect(()=>{x.current=e},[e]),i.useEffect(()=>{j.current=a},[a]);const y=i.useCallback(async()=>{if(m.current==="idle"){m.current="initial",c(!0),p(null);try{const v=await fetch(`/api/history?limit=${Er}`);if(!v.ok)throw new Error(`HTTP ${v.status}`);const h=await v.json();t(h.entries??[]),s(h.total??0),o(h.nextCursor??null),h.error&&p(h.error)}catch(v){p(v instanceof Error?v.message:"Failed to load history")}finally{c(!1),m.current="idle"}}},[]),g=i.useCallback(async()=>{var h;if(m.current!=="idle")return;const v=(h=x.current[0])==null?void 0:h.commit.sha;if(!v){await y();return}m.current="poll";try{const b=await fetch(`/api/history?since=${encodeURIComponent(v)}`);if(!b.ok)throw new Error(`HTTP ${b.status}`);const N=await b.json(),k=new Set(x.current.map(C=>C.commit.sha)),S=(N.entries??[]).filter(C=>!k.has(C.commit.sha));S.length>0&&(t(C=>[...S,...C]),s(C=>C+S.length))}catch(b){p(b instanceof Error?b.message:"Failed to poll history")}finally{m.current="idle"}},[y]),w=i.useCallback(async()=>{if(m.current!=="idle")return;const v=j.current;if(v){m.current="more",u(!0);try{const h=await fetch(`/api/history?limit=${Er}&before=${encodeURIComponent(v)}`);if(!h.ok)throw new Error(`HTTP ${h.status}`);const b=await h.json();t(N=>[...N,...b.entries??[]]),o(b.nextCursor??null),typeof b.total=="number"&&s(b.total)}catch(h){p(h instanceof Error?h.message:"Failed to load more commits")}finally{u(!1),m.current="idle"}}},[]);return i.useEffect(()=>{y();const v=setInterval(()=>{g()},dl);return()=>clearInterval(v)},[y,g]),{rows:e,total:r,hasMore:a!==null,loading:l,loadingMore:d,error:f,loadMore:w,reload:y}}function fl({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:Es(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 pl=[/\.test\.[jt]sx?$/,/\.spec\.[jt]sx?$/,/__tests__\//,/tests?\//];function ml(e){return e.filter(t=>pl.some(r=>r.test(t.path)))}function As({entry:e,commit:t}){const r=ml(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 ${Fi(e.type)}`,children:e.type}),n.jsx("span",{className:"text-xs",style:{color:"var(--text-dim)"},children:Es(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(Rs,{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(Hi,{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(Bi,{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(Kn,{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 Yn({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 xl(){const{rows:e,total:t,hasMore:r,loading:s,loadingMore:a,error:o,loadMore:l}=ul();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(Yn,{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(As,{entry:d.entry,commit:d.commit},d.commit.sha):n.jsx(fl,{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 hn={sound:"soft-double-tap",systemNotification:!0,idleOnStop:!1,idleOnNotification:!0},hl=[{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"}],Ls="codeyam-editor-notifications";function gl(){try{const e=localStorage.getItem(Ls);if(!e)return hn;const t=JSON.parse(e);return{...hn,...t}}catch{return hn}}function vl(e){localStorage.setItem(Ls,JSON.stringify(e))}const bl={"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 gn(e,t){const r=t;z(e,{name:r==null?void 0:r.name,message:r==null?void 0:r.message})}function Ms(e){if(e==="off")return;z("audio-playsound-entered",{soundId:e});let t;try{t=new AudioContext}catch(s){gn("audio-context-failed",s);return}z("audio-context-created",{state:t.state});const r=()=>{let s;try{s=bl[e](t)}catch(a){gn("audio-context-failed",a),t.close().catch(()=>{});return}z("audio-oscillators-scheduled",{soundId:e,count:s.count,longestStopSec:s.longestStopSec}),setTimeout(()=>{t.close().then(()=>z("audio-context-closed")).catch(()=>{})},(s.longestStopSec+.1)*1e3)};t.state==="running"?r():t.state==="suspended"?(z("audio-context-resume-attempted"),t.resume().then(()=>{z("audio-context-resume-ok",{state:t.state}),r()},s=>{gn("audio-context-resume-failed",s),t.close().catch(()=>{})})):(z("audio-context-failed",{name:"UnexpectedState",message:`AudioContext state "${t.state}"`}),t.close().catch(()=>{}))}const yl="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 wl(){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 Rr(e){return e.length===0?"_(no events in window)_":`\`\`\`jsonl
|
|
2
|
+
${e.map(r=>JSON.stringify(r)).join(`
|
|
3
|
+
`)}
|
|
4
|
+
\`\`\``}function vn(e,t){return e.trim().length===0?`_(${t} empty)_`:`\`\`\`
|
|
5
|
+
${e}
|
|
6
|
+
\`\`\``}function jl(e){var g,w,v;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)??Vn(),d=(t==null?void 0:t.windowMinutes)??10,u=((g=t==null?void 0:t.environment)==null?void 0:g.editorVersion)??"unknown",f=((w=t==null?void 0:t.environment)==null?void 0:w.platform)??"unknown",p=((v=t==null?void 0:t.environment)==null?void 0:v.projectDir)??"unknown",m=(a??yl).trim(),x=[`- 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
|
+
`),j=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:**",x,"",j,"","## UI idle trace (persisted)","",Rr((t==null?void 0:t.uiTrace)??[]),"","## UI idle trace (in-memory ring buffer — may be ahead of persisted)","",vn(s,"in-memory buffer"),"","## Rust idle trace","",Rr((t==null?void 0:t.rustTrace)??[]),"","## editor-server.log (filtered to idle= within window)","",vn((t==null?void 0:t.editorServerLog)??"","editor-server.log"),"","## dev-server.log (last lines)","",vn((t==null?void 0:t.devServerLog)??"","dev-server.log"),""].filter(h=>h!==null).join(`
|
|
8
|
+
`)}async function Nl(e={}){const t=encodeURIComponent(Vn());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=wl(),o=Fo({agentName:e.agentName});return{markdown:jl({bundle:r,browser:a,uiBufferText:o,prompt:e.prompt,agentName:e.agentName}),bundle:r,error:s}}const Cl=1500;function Sl(e=Cl){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 kl=2500;function El({agentName:e}){const[t,r]=i.useState(!1),{label:s,flash:a}=Sl(kl),o=async()=>{r(!0);const{markdown:l,bundle:c,error:d}=await Nl({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 Tr({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 Rl({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:hl.map(u=>n.jsx("button",{onClick:()=>{t({...e,sound:u.id}),u.id!=="off"&&Ms(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(Tr,{label:"Claude stops",checked:l,onChange:u=>t({...e,idleOnStop:u})}),n.jsx(Tr,{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(El,{agentName:r})})]})]})]})}function Tl(){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 Dl({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 Pl(){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 Al({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 Ll({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(Dl,{projectDescription:e}):n.jsx(Pl,{}),n.jsx(Al,{onClick:t})]})}function Ml({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(Uo,{stats:l,onClick:()=>t(l.app.dir),testsLoading:r,testsRefreshing:s,onRunTests:a,currentRunner:o},l.app.dir))})}function Is({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 Il({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(Is,{coverage:t,testId:"app-overview-coverage",onClick:r})]})}function Ol(e,t){for(const r of e.filesByDirectory)for(const s of r.files)if(s.filePath===t)return s;return null}function Os(e){return e>=80?"#16a34a":e>=50?"#eab308":"#dc2626"}function jt({coverage:e}){const t=Math.max(0,Math.min(100,e.percent)),r=Os(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 Fl({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 Bl({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(Fl,{file:r,onSelectFile:t},r.filePath))})]})}function $l({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(Bl,{group:r,onSelectFile:t},r.directory||"(root)"))})]})}function Hl({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 _l({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(Hl,{entry:r,onSelectFile:t},`${r.filePath}::${r.name}`))})]})}function Fs({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 zl({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(Fs,{file:r})},r.filePath))})]})}function Wl({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 Vl({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(Wl,{line:s,hits:a},s))})]})}function Gn({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:Os(t.percent)},"data-testid":r,children:[Math.round(t.percent),"% overall"]})]})]})}function Bs({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 Ul({onClose:e,fetchDetails:t=Kl,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=Ol(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(Vl,{file:c,onBack:()=>d(null)}),s&&!c&&n.jsxs("div",{className:"flex flex-col gap-6",children:[n.jsx(Gn,{title:"Overall",aggregate:s.projectWide,aggregateTestId:"coverage-details-modal-aggregate"}),s.coverageWarnings.length>0&&n.jsx(Bs,{warnings:s.coverageWarnings}),n.jsx(_l,{entries:s.entries,onSelectFile:f}),n.jsx(zl,{files:s.orphanedFiles,onSelectFile:f}),n.jsx($l,{directories:s.filesByDirectory,onSelectFile:d})]})]})})}function Kl(){return fetch("/api/coverage/details").then(e=>{if(!e.ok)throw new Error(`HTTP ${e.status}`);return e.json()})}async function Yl(e){try{e.description&&await fetch("/api/editor-project-info",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectDescription:e.description})});const t={appFormats:e.appFormats,techStackId:e.techStackId,designSystemId:e.designSystemId};e.defaultDevice&&(t.defaultDevice=e.defaultDevice),await fetch("/api/editor-setup-answers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}catch{}}function Gl(){const[e,t]=i.useState([]),[r,s]=i.useState([]);return i.useEffect(()=>{fetch("/api/editor-design-systems").then(a=>a.json()).then(t).catch(()=>{}),fetch("/api/editor-stacks").then(a=>a.json()).then(s).catch(()=>{})},[]),{designSystems:e,techStacks:r}}function nt({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(Jl,{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 Jl({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:"✓"})})}function ft({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]})}const Xl=[{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 ql({selected:e,onSelect:t}){return n.jsx("div",{style:{marginTop:"var(--spacing-xl, 32px)"},children:n.jsx(ft,{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:Xl.map(r=>n.jsx(nt,{label:r.label,description:r.description,selected:e===r.id,onClick:()=>t(r.id)},r.id))})})})}function Ql(){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 Zl({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,style:{background:"var(--accent-active)",border:"none",color:"#000",padding:"var(--spacing-sm, 8px) var(--spacing-lg, 16px)",borderRadius:6,cursor:"pointer",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 ec({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 tc=[{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"}],nc={"product-type":"What Type Of Your Product Do You Want To Build?",description:"Describe Your Product","tech-stack":"Do You Have A Preferred Tech Stack?","design-system":"Choose A Design System"},bn=["product-type","description","tech-stack","design-system"],Dr=560,rc=960;function sc({onComplete:e,onPreviewUrl:t}){const[r,s]=i.useState(1),[a,o]=i.useState({appFormats:[],description:"",techStackId:null,designSystemId:null,defaultDevice:null}),{designSystems:l,techStacks:c}=Gl(),d=bn[r-1],u=r===bn.length,f=bn.map(h=>nc[h]);i.useEffect(()=>{d!=="design-system"&&(t==null||t(null))},[d,t]);const p=i.useCallback(h=>{o(b=>{const N=b.appFormats.includes(h),k=N?b.appFormats.filter(C=>C!==h):[...b.appFormats,h],S=h==="web"&&N?null:b.defaultDevice;return{...b,appFormats:k,defaultDevice:S}})},[]),m=i.useCallback(h=>{o(b=>({...b,defaultDevice:h}))},[]),x=i.useCallback(h=>{o(b=>({...b,designSystemId:b.designSystemId===h?null:h})),h?t==null||t(`${window.location.origin}/api/editor-design-systems/${h}/preview`):t==null||t(null)},[t]),j=i.useCallback(async()=>{await Yl(a),e==null||e(a)},[a,e]),y=i.useCallback(()=>{s(h=>h+1)},[]),g=a.appFormats.includes("web"),w=(()=>{switch(d){case"product-type":return a.appFormats.length>0&&(!g||a.defaultDevice!==null);case"description":return a.description.trim().length>0;default:return!0}})(),v=d==="description"?rc:Dr;return n.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"auto"},children:[n.jsx(Ql,{}),n.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",padding:"var(--spacing-xl, 32px)"},children:[n.jsxs("div",{style:{maxWidth:v},children:[d==="product-type"&&n.jsxs(n.Fragment,{children:[n.jsx(ft,{title:"What type of your 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:tc.map(h=>n.jsx(nt,{label:h.label,selected:a.appFormats.includes(h.id),onClick:()=>p(h.id),multi:!0},h.id))})}),g&&n.jsx(ql,{selected:a.defaultDevice,onSelect:m})]}),d==="description"&&n.jsx(ft,{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:h=>o(b=>({...b,description:h.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"}})}),d==="tech-stack"&&n.jsx(ft,{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(nt,{label:"Let CodeYam decide",description:"We'll pick the best stack based on your product",selected:a.techStackId===null,onClick:()=>o(h=>({...h,techStackId:null}))}),c.map(h=>n.jsx(nt,{label:h.name,description:h.description,selected:a.techStackId===h.id,onClick:()=>o(b=>({...b,techStackId:h.id}))},h.id))]})}),d==="design-system"&&n.jsx(ft,{title:"Choose a design system",subtitle:"Select a visual style for your app. You can preview each one on the right.",children:n.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"var(--spacing-sm, 8px)"},children:[n.jsx(nt,{label:"No design system",description:"Start with default styling",selected:a.designSystemId===null,onClick:()=>x(null)}),l.map(h=>n.jsx(nt,{label:h.name,description:h.tagline,selected:a.designSystemId===h.id,onClick:()=>x(h.id)},h.id))]})})]}),n.jsxs("div",{style:{maxWidth:Dr},children:[n.jsx(Zl,{step:r,canAdvance:w,isFinalStep:u,onBack:()=>s(h=>h-1),onNext:()=>{w&&y()},onFinish:j}),n.jsx(ec,{currentStep:r,stepLabels:f,onStepClick:s})]})]})]})}function ac({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:x}){const[j,y]=i.useState(!1),{saved:g}=Tl();return r.length===0?o||g===null?null:!f&&!g?n.jsx(sc,{onPreviewUrl:p,onComplete:m}):n.jsx(Ll,{projectDescription:t??null,onOpenBuildTab:x??(()=>{})}):n.jsxs("div",{className:"px-5 py-5",children:[n.jsx(Il,{projectTitle:e,coverage:s,onCoverageClick:()=>y(!0)}),n.jsx(Ml,{stats:r,onSelectApp:a,testsLoading:l,testsRefreshing:c,onRunTests:d,currentRunner:u}),j&&n.jsx(Ul,{onClose:()=>y(!1)})]})}function oc({sessionContent:e,stepIndicator:t}){return n.jsxs("div",{className:"flex flex-col h-full",children:[t,e]})}function ic({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 lc(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 cc(e,t){const r=Vt(e),s=Vt(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 dc({resumeMode:e,previousProvider:t,currentProvider:r,awaitingUserInput:s=!1}){return e!=="handoff"||t==null||r==null||t===r?lc(s):cc(t,r)}function uc({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-blue)",color:"var(--text-primary)"},children:e})}function fc({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 pc({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 yn({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 mc({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(yn,{label:"Feature",value:e,rowClassName:"mb-1"}),t!=null&&r&&n.jsx(yn,{label:"Step",value:`${t} (${r})`}),s&&n.jsx(yn,{label:"Providers",value:s,rowClassName:"mt-1"})]})}function xc(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 hc({featureName:e,editorStep:t,workflowMode:r,previousProvider:s,currentProvider:a,resumeMode:o,awaitingUserInput:l=!1,onContinue:c}){const d=dc({resumeMode:o,previousProvider:s,currentProvider:a,awaitingUserInput:l}),u=t==null?null:Un(t,r);return xc(c),n.jsxs(fc,{children:[n.jsx(pc,{title:d.title,description:d.description}),n.jsx(mc,{featureName:e,editorStep:t,editorStepLabel:u,providersLabel:d.providersLabel}),n.jsx(uc,{label:d.buttonLabel,onContinue:c})]})}function gc({awaitingUserInput:e,currentProvider:t,editorStep:r,featureName:s,onContinue:a,previousProvider:o,resumeMode:l,workflowMode:c}){return n.jsx(hc,{featureName:s,editorStep:r,workflowMode:c,previousProvider:o,currentProvider:t,resumeMode:l,awaitingUserInput:e,onContinue:a})}function vc({awaitingPlanLaunchChoice:e,configLoading:t,sessionDecision:r,sessionInfo:s,sessionLoading:a,stepState:o}){return{recoveryFeatureName:(o==null?void 0:o.feature)??(s==null?void 0:s.feature)??null,recoveryStep:(o==null?void 0:o.step)??(s==null?void 0:s.step)??null,recoveryMode:(o==null?void 0:o.mode)??(s==null?void 0:s.mode)??null,showTerminal:!a&&!t&&!e&&(r==="continue"||r==="fresh"||r==="no-session")&&(o!==null||s!==null),shouldResumeSameProvider:r==="continue"&&(s==null?void 0:s.resumeMode)==="resume"}}const Pn=8e3,bc="agent-banner-ready";let Gt=!1,Jt=!1,Xe=[],Pr=!1;function yc(){Pr||typeof window>"u"||(Pr=!0,window.addEventListener(bc,()=>{if(Jt)return;Jt=!0;const e=Xe;Xe=[];for(const t of e)t()}))}yc();function wc(){return Jt?Promise.resolve("banner"):new Promise(e=>{let t=!1;const r=()=>{t||(t=!0,clearTimeout(s),e("banner"))};Xe.push(r);const s=setTimeout(()=>{if(t)return;t=!0;const a=Xe.indexOf(r);a>=0&&Xe.splice(a,1),e("fallback")},Pn)})}async function $s(e,t,r=0,s=Rn){if(Gt){z("dispatch-rename-suppressed",{caller:t,label:e});return}Gt=!0,z("dispatch-rename",{phase:"queued",caller:t,label:e,fallbackMs:Pn,postReadyDelayMs:r});const a=await wc();r>0&&await new Promise(o=>setTimeout(o,r)),a==="fallback"&&z("dispatch-rename-fallback",{caller:t,label:e,fallbackMs:Pn}),z("dispatch-rename",{phase:"fired",caller:t,label:e,source:a,postReadyDelayMs:r}),vs(e,s)}function jc(){Gt=!1,Jt=!1,Xe=[]}function Nc(){Gt=!1,Xe=[]}function Cc({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,$s(mo("/codeyam-editor"),"build-session-seed",bs)}},[e,t,r])}function Sc({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 kc=1e3;let An=0;function It(){An=Date.now()}function Ec(){return An===0?1/0:Date.now()-An}function Rc(){return Ec()<kc}function Xt(){window.focus()}function Tc(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])}const Ar=20*1024*1024,Dc=3e4,Pc=3e3;function Ac(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 Lc(){return typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`drop-${Date.now()}-${Math.random().toString(36).slice(2)}`}function Mc(e){return/^[A-Za-z0-9._/\-]+$/.test(e)?e:`"${e.replace(/(["\\$`])/g,"\\$1")}"`}function Ic(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 Oc({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 h=window.setTimeout(()=>o(null),Pc);return()=>window.clearTimeout(h)},[a]);const d=i.useCallback(h=>{o(h)},[]),u=i.useCallback((h,b)=>{const N=l.current.get(h);N&&(l.current.delete(h),N.resolve(b))},[]),f=i.useCallback((h,b)=>{const N=l.current.get(h);N&&(l.current.delete(h),N.reject(b))},[]),p=i.useCallback(h=>{for(const[,b]of l.current)b.reject(h);l.current.clear()},[]),m=i.useCallback(async h=>{if(h.size>Ar)throw new Error(`File too large (max ${Ar/(1024*1024)} MB)`);const b=e.current;if(!b||b.readyState!==WebSocket.OPEN)throw new Error("Not connected — try again in a moment");const N=await Ac(h),k=Lc(),S=new Promise((C,D)=>{const R=window.setTimeout(()=>{l.current.delete(k)&&D(new Error("Timed out waiting for save to complete"))},Dc);l.current.set(k,{resolve:E=>{window.clearTimeout(R),C(E)},reject:E=>{window.clearTimeout(R),D(new Error(E))}})});return b.send(JSON.stringify({type:"drop",id:k,name:h.name||"unnamed",mime:h.type||"application/octet-stream",data:N})),S},[e]),x=i.useCallback(async h=>{if(h.length===0)return;const b=[];for(const N of h)try{b.push(await m(N))}catch(k){const S=k instanceof Error?k.message:String(k);d(`Attach failed: ${S}`);return}t(b.map(Mc).join(" ")+" ")},[m,d,t]),j=i.useCallback(h=>{h.dataTransfer.types.includes("Files")&&(h.preventDefault(),c.current+=1,s(!0))},[]),y=i.useCallback(h=>{h.dataTransfer.types.includes("Files")&&h.preventDefault()},[]),g=i.useCallback(h=>{h.dataTransfer.types.includes("Files")&&(c.current=Math.max(0,c.current-1),c.current===0&&s(!1))},[]),w=i.useCallback(async h=>{if(!h.dataTransfer.types.includes("Files"))return;if(h.preventDefault(),c.current=0,s(!1),Ic(h.dataTransfer)){d("Folder drops are not supported — drag individual files instead");return}const b=Array.from(h.dataTransfer.files).filter(N=>N.size>0);await x(b)},[x,d]),v=i.useCallback(async h=>{var k;const b=(k=h.clipboardData)==null?void 0:k.items;if(!b)return;const N=[];for(const S of Array.from(b))if(S.kind==="file"&&S.type.startsWith("image/")){const C=S.getAsFile();C&&N.push(C)}N.length!==0&&(h.preventDefault(),await x(N))},[x]);return{dragActive:r,errorToast:a,dropHandlers:{onDragEnter:j,onDragOver:y,onDragLeave:g,onDrop:w},pasteHandler:v,resolveDrop:u,rejectDrop:f,cancelAllDrops:p,showError:d}}function nn(e){return e.scenarioType==="application"||e.scenarioType==="component"?e.scenarioType:e.componentName?"component":"application"}function qe(e){return nn(e)==="application"}function Jn(e){return nn(e)==="component"}function Hs(e){return{overrideCounts:{mocks:0,seeds:0,inheritedMocks:0,inheritedSeeds:0},...e,scenarioType:nn(e)}}function it(e=typeof window<"u"?window:void 0){return e?e.self!==e.top:!1}function Fc({isInIframe:e,previewKind:t,selectedScenario:r}){return e?!1:t!=="application"?!0:!r||!qe(r)}function Bc(){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 $c({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})}const Lr=15;function Hc({provider:e,agentStartMode:t,sessionId:r,onAgentIdle:s,onAgentActive:a,onUserInput:o,onStartupFailed:l,onStartupFailedCleared:c}){if(it())return null;const d=i.useRef(null),u=i.useRef(null),f=i.useRef(null),p=i.useRef(null),m=i.useRef(!1),x=i.useRef(t??"fresh"),j=i.useRef(r??null),[y,g]=i.useState({kind:"connecting"}),[w,v]=i.useState(0);i.useEffect(()=>{x.current=t??"fresh",j.current=r??null},[t,r]);const h=i.useRef(s);h.current=s;const b=i.useRef(a);b.current=a;const N=i.useRef(o);N.current=o;const k=i.useRef(l);k.current=l;const S=i.useRef(c);S.current=c;const C=Oc({wsRef:p,insertInput:R=>{var E,V;((E=p.current)==null?void 0:E.readyState)===WebSocket.OPEN&&p.current.send(JSON.stringify({type:"input",data:R})),It(),(V=N.current)==null||V.call(N)}}),D=i.useRef(C);return D.current=C,Tc(d,()=>{var R;f.current&&u.current&&(f.current.fit(),((R=p.current)==null?void 0:R.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 R=new xo.Terminal({cursorBlink:!0,fontSize:13,fontFamily:"'IBM Plex Mono', monospace",theme:{background:"#1e1e1e",foreground:"#cccccc",cursor:"#D7FF63",selectionBackground:"#264f78"}}),E=new ho.FitAddon;R.loadAddon(E),R.open(d.current),u.current=R,f.current=E;const V=go(R,d.current,{onError:M=>D.current.showError(M)}),F=vo(R,{sendInput:M=>{var L,G;((L=p.current)==null?void 0:L.readyState)===WebSocket.OPEN&&p.current.send(JSON.stringify({type:"input",data:M})),It(),(G=N.current)==null||G.call(N)}});requestAnimationFrame(()=>{E.fit(),R.focus()});let $=!1,Y=0,B=null;function T(){try{const M=new WebSocket(yo({provider:e,mode:x.current,sessionId:j.current??void 0}));p.current=M,M.binaryType="arraybuffer",M.onmessage=L=>{var G,J,ee,_;if(L.data instanceof ArrayBuffer)R.write(new Uint8Array(L.data));else if(typeof L.data=="string")try{const P=JSON.parse(L.data);if(P.type==="session-id")x.current="resume",j.current=P.sessionId??null;else if(P.type==="agent-idle"||P.type==="claude-idle"){const ne=typeof P.source=="string"?P.source:void 0;z("ws-message-received",{type:P.type,source:ne}),(G=h.current)==null||G.call(h,ne)}else if(P.type==="agent-active"||P.type==="claude-active")z("ws-message-received-active",{type:P.type}),(J=b.current)==null||J.call(b);else if(P.type==="idle-diag"){const{site:ne,event:oe,...re}=P;z(`rust:${oe??"unknown"}`,{site:ne,...re})}else P.type==="drop-complete"?D.current.resolveDrop(String(P.id??""),String(P.path??"")):P.type==="drop-error"?D.current.rejectDrop(String(P.id??""),String(P.message??"drop failed")):P.type==="startup-failed"?(ee=k.current)==null||ee.call(k,String(P.snippet??"")):P.type==="startup-failed-cleared"?(_=S.current)==null||_.call(S):P.type==="agent-banner-ready"&&(z("agent-banner-ready",{}),window.dispatchEvent(new CustomEvent("agent-banner-ready")))}catch{}},M.onopen=()=>{Y=0,g({kind:"open"}),z("ws-open"),M.send(JSON.stringify({type:"resize",cols:R.cols,rows:R.rows}));try{typeof localStorage<"u"&&localStorage.getItem("codeyam.idleDebug")==="1"&&(M.send(JSON.stringify({type:"enable-idle-diag",sessionId:Vn()})),z("idle-diag-enabled"))}catch{}},M.onerror=()=>{},M.onclose=async()=>{if(z("ws-close",{reconnectAttempts:Y}),D.current.cancelAllDrops("Not connected"),$){g({kind:"ended"}),R.writeln(`\r
|
|
9
|
+
\x1B[90m[Terminal session ended]\x1B[0m`);return}const L=await wo();if(!$){if(!L){g({kind:"server-stopped"}),B==null||B(),B=jo(2e3,()=>{$||window.location.reload()});return}if(Y<Lr){const G=Y<4?1e3*Math.pow(2,Y):1e4;Y++,g({kind:"reconnecting",attempt:Y,maxAttempts:Lr}),setTimeout(()=>{$||T()},G)}else g({kind:"failed"})}}}catch{g({kind:"failed"})}}T();let I=0;const A=1e3;function O(){var L;const M=Date.now();M-I>=A&&((L=p.current)==null?void 0:L.readyState)===WebSocket.OPEN&&(p.current.send(JSON.stringify({type:"browser-activity"})),I=M)}document.addEventListener("mousemove",O),document.addEventListener("keydown",O),document.addEventListener("mousedown",O),R.onData(M=>{var L,G;((L=p.current)==null?void 0:L.readyState)===WebSocket.OPEN?p.current.send(JSON.stringify({type:"input",data:M})):v(J=>J+1),It(),(G=N.current)==null||G.call(N)});const Q=d.current;function W(M){var ee,_,P;const L=((ee=M.clipboardData)==null?void 0:ee.getData("text"))??"";if(!L)return;M.preventDefault(),M.stopPropagation();const G=L.replace(/\r\n/g,"\r").replace(/\n/g,"\r"),J=R.modes.bracketedPasteMode?`\x1B[200~${G}\x1B[201~`:G;((_=p.current)==null?void 0:_.readyState)===WebSocket.OPEN?p.current.send(JSON.stringify({type:"input",data:J})):v(ne=>ne+1),It(),(P=N.current)==null||P.call(N)}Q.addEventListener("paste",W,!0);function H(M){var J,ee;const L=M.detail;if(!L)return;((J=p.current)==null?void 0:J.readyState)===WebSocket.OPEN?((ee=p.current)==null||ee.send(JSON.stringify({type:"input",data:L})),z("terminal-send-input",{len:L.length,firstChars:L.slice(0,16),wsOpen:!0,dropped:!1})):z("terminal-send-input",{len:L.length,firstChars:L.slice(0,16),wsOpen:!1,dropped:!0})}window.addEventListener("terminal-send-input",H);function U(){Xt(),R.focus()}return window.addEventListener("terminal-focus",U),()=>{var M;$=!0,B==null||B(),B=null,document.removeEventListener("mousemove",O),document.removeEventListener("keydown",O),document.removeEventListener("mousedown",O),window.removeEventListener("terminal-send-input",H),window.removeEventListener("terminal-focus",U),Q.removeEventListener("paste",W,!0),F(),(M=p.current)==null||M.close(),V(),R.dispose(),m.current=!1}},[e]),n.jsxs("div",{className:"relative flex-1 flex flex-col",style:{minHeight:0},"data-terminal-emulator":!0,onDragEnter:C.dropHandlers.onDragEnter,onDragOver:C.dropHandlers.onDragOver,onDragLeave:C.dropHandlers.onDragLeave,onDrop:C.dropHandlers.onDrop,onPaste:C.pasteHandler,children:[n.jsx("div",{ref:d,className:"flex-1",style:{background:"#1e1e1e",minHeight:0,paddingTop:3,paddingLeft:3},onClick:()=>{var R;Xt(),(R=u.current)==null||R.focus()}}),C.dragActive&&n.jsx(Bc,{}),C.errorToast&&n.jsx($c,{message:C.errorToast}),n.jsx(bo,{status:y,pulseKey:w,onRefresh:()=>window.location.reload()})]})}function _c({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);Cc({provider:s,agentStartMode:o?"resume":"fresh",currentFeature:l}),i.useEffect(()=>()=>{jc()},[]);const p=i.useCallback(j=>{d(j)},[]),m=i.useCallback(()=>{d(null)},[]),x=i.useCallback(()=>{d(null),f(j=>j+1)},[]);return n.jsxs("div",{className:"flex flex-col flex-1 min-h-0",children:[c!==null&&n.jsx(Sc,{snippet:c,onRetry:x,onDismiss:m}),n.jsx(Hc,{provider:s,agentStartMode:o?"resume":"fresh",sessionId:o?a:null,onAgentIdle:t,onAgentActive:e,onUserInput:r,onStartupFailed:p,onStartupFailedCleared:m},u)]})}function zc(){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 lt(e){const t=Object.prototype.toString.call(e);return t==="[object Window]"||t==="[object global]"}function Xn(e){return"nodeType"in e}function ye(e){var t,r;return e?lt(e)?e:Xn(e)&&(t=(r=e.ownerDocument)==null?void 0:r.defaultView)!=null?t:window:window}function qn(e){const{Document:t}=ye(e);return e instanceof t}function Nt(e){return lt(e)?!1:e instanceof ye(e).HTMLElement}function _s(e){return e instanceof ye(e).SVGElement}function ct(e){return e?lt(e)?e.document:Xn(e)?qn(e)?e:Nt(e)||_s(e)?e.ownerDocument:document:document:document}const Me=rn?i.useLayoutEffect:i.useEffect;function Qn(e){const t=i.useRef(e);return Me(()=>{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 Wc(){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 ht(e,t){t===void 0&&(t=[e]);const r=i.useRef(e);return Me(()=>{r.current!==e&&(r.current=e)},t),r}function Ct(e,t){const r=i.useRef();return i.useMemo(()=>{const s=e(r.current);return r.current=s,s},[...t])}function qt(e){const t=Qn(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 Ln(e){const t=i.useRef();return i.useEffect(()=>{t.current=e},[e]),t.current}let wn={};function St(e,t){return i.useMemo(()=>{if(t)return t;const r=wn[e]==null?0:wn[e]+1;return wn[e]=r,e+"-"+r},[e,t])}function zs(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 st=zs(1),gt=zs(-1);function Vc(e){return"clientX"in e&&"clientY"in e}function Zn(e){if(!e)return!1;const{KeyboardEvent:t}=ye(e.target);return t&&e instanceof t}function Uc(e){if(!e)return!1;const{TouchEvent:t}=ye(e.target);return t&&e instanceof t}function Mn(e){if(Uc(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 Vc(e)?{x:e.clientX,y:e.clientY}:null}const vt=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[vt.Translate.toString(e),vt.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:t,duration:r,easing:s}=e;return t+" "+r+"ms "+s}}}),Mr="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function Kc(e){return e.matches(Mr)?e:e.querySelector(Mr)}const Yc={display:"none"};function Gc(e){let{id:t,value:r}=e;return be.createElement("div",{id:t,style:Yc},r)}function Jc(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 be.createElement("div",{id:t,style:a,role:"status","aria-live":s,"aria-atomic":!0},r)}function Xc(){const[e,t]=i.useState("");return{announce:i.useCallback(s=>{s!=null&&t(s)},[]),announcement:e}}const Ws=i.createContext(null);function qc(e){const t=i.useContext(Ws);i.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of <DndContext>");return t(e)},[e,t])}function Qc(){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 Zc={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
|
+
`},ed={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 td(e){let{announcements:t=ed,container:r,hiddenTextDescribedById:s,screenReaderInstructions:a=Zc}=e;const{announce:o,announcement:l}=Xc(),c=St("DndLiveRegion"),[d,u]=i.useState(!1);if(i.useEffect(()=>{u(!0)},[]),qc(i.useMemo(()=>({onDragStart(p){let{active:m}=p;o(t.onDragStart({active:m}))},onDragMove(p){let{active:m,over:x}=p;t.onDragMove&&o(t.onDragMove({active:m,over:x}))},onDragOver(p){let{active:m,over:x}=p;o(t.onDragOver({active:m,over:x}))},onDragEnd(p){let{active:m,over:x}=p;o(t.onDragEnd({active:m,over:x}))},onDragCancel(p){let{active:m,over:x}=p;o(t.onDragCancel({active:m,over:x}))}}),[o,t])),!d)return null;const f=be.createElement(be.Fragment,null,be.createElement(Gc,{id:s,value:a.draggable}),be.createElement(Jc,{id:c,announcement:l}));return r?ut.createPortal(f,r):f}var le;(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"})(le||(le={}));function Qt(){}function Ir(e,t){return i.useMemo(()=>({sensor:e,options:t??{}}),[e,t])}function nd(){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 De=Object.freeze({x:0,y:0});function Vs(e,t){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function Us(e,t){let{data:{value:r}}=e,{data:{value:s}}=t;return r-s}function rd(e,t){let{data:{value:r}}=e,{data:{value:s}}=t;return s-r}function Or(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 Ks(e,t){if(!e||e.length===0)return null;const[r]=e;return r[t]}function Fr(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 sd=e=>{let{collisionRect:t,droppableRects:r,droppableContainers:s}=e;const a=Fr(t,t.left,t.top),o=[];for(const l of s){const{id:c}=l,d=r.get(c);if(d){const u=Vs(Fr(d),a);o.push({id:c,data:{droppableContainer:l,value:u}})}}return o.sort(Us)},ad=e=>{let{collisionRect:t,droppableRects:r,droppableContainers:s}=e;const a=Or(t),o=[];for(const l of s){const{id:c}=l,d=r.get(c);if(d){const u=Or(d),f=a.reduce((m,x,j)=>m+Vs(u[j],x),0),p=Number((f/4).toFixed(4));o.push({id:c,data:{droppableContainer:l,value:p}})}}return o.sort(Us)};function od(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 id=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=od(c,t);d>0&&a.push({id:l,data:{droppableContainer:o,value:d}})}}return a.sort(rd)};function ld(e,t,r){return{...e,scaleX:t&&r?t.width/r.width:1,scaleY:t&&r?t.height/r.height:1}}function Ys(e,t){return e&&t?{x:e.left-t.left,y:e.top-t.top}:De}function cd(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 dd=cd(1);function ud(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 fd(e,t,r){const s=ud(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 pd={ignoreTransform:!1};function dt(e,t){t===void 0&&(t=pd);let r=e.getBoundingClientRect();if(t.ignoreTransform){const{transform:u,transformOrigin:f}=ye(e).getComputedStyle(e);u&&(r=fd(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 Br(e){return dt(e,{ignoreTransform:!0})}function md(e){const t=e.innerWidth,r=e.innerHeight;return{top:0,left:0,right:t,bottom:r,width:t,height:r}}function xd(e,t){return t===void 0&&(t=ye(e).getComputedStyle(e)),t.position==="fixed"}function hd(e,t){t===void 0&&(t=ye(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 sn(e,t){const r=[];function s(a){if(t!=null&&r.length>=t||!a)return r;if(qn(a)&&a.scrollingElement!=null&&!r.includes(a.scrollingElement))return r.push(a.scrollingElement),r;if(!Nt(a)||_s(a)||r.includes(a))return r;const o=ye(e).getComputedStyle(a);return a!==e&&hd(a,o)&&r.push(a),xd(a,o)?r:s(a.parentNode)}return e?s(e):r}function Gs(e){const[t]=sn(e,1);return t??null}function jn(e){return!rn||!e?null:lt(e)?e:Xn(e)?qn(e)||e===ct(e).scrollingElement?window:Nt(e)?e:null:null}function Js(e){return lt(e)?e.scrollX:e.scrollLeft}function Xs(e){return lt(e)?e.scrollY:e.scrollTop}function In(e){return{x:Js(e),y:Xs(e)}}var de;(function(e){e[e.Forward=1]="Forward",e[e.Backward=-1]="Backward"})(de||(de={}));function qs(e){return!rn||!e?!1:e===document.scrollingElement}function Qs(e){const t={x:0,y:0},r=qs(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 gd={x:.2,y:.2};function vd(e,t,r,s,a){let{top:o,left:l,right:c,bottom:d}=r;s===void 0&&(s=10),a===void 0&&(a=gd);const{isTop:u,isBottom:f,isLeft:p,isRight:m}=Qs(e),x={x:0,y:0},j={x:0,y:0},y={height:t.height*a.y,width:t.width*a.x};return!u&&o<=t.top+y.height?(x.y=de.Backward,j.y=s*Math.abs((t.top+y.height-o)/y.height)):!f&&d>=t.bottom-y.height&&(x.y=de.Forward,j.y=s*Math.abs((t.bottom-y.height-d)/y.height)),!m&&c>=t.right-y.width?(x.x=de.Forward,j.x=s*Math.abs((t.right-y.width-c)/y.width)):!p&&l<=t.left+y.width&&(x.x=de.Backward,j.x=s*Math.abs((t.left+y.width-l)/y.width)),{direction:x,speed:j}}function bd(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 Zs(e){return e.reduce((t,r)=>st(t,In(r)),De)}function yd(e){return e.reduce((t,r)=>t+Js(r),0)}function wd(e){return e.reduce((t,r)=>t+Xs(r),0)}function jd(e,t){if(t===void 0&&(t=dt),!e)return;const{top:r,left:s,bottom:a,right:o}=t(e);Gs(e)&&(a<=0||o<=0||r>=window.innerHeight||s>=window.innerWidth)&&e.scrollIntoView({block:"center",inline:"center"})}const Nd=[["x",["left","right"],yd],["y",["top","bottom"],wd]];class er{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=sn(r),a=Zs(s);this.rect={...t},this.width=t.width,this.height=t.height;for(const[o,l,c]of Nd)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 pt{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 Cd(e){const{EventTarget:t}=ye(e);return e instanceof t?e:ct(e)}function Nn(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 Ee;(function(e){e.Click="click",e.DragStart="dragstart",e.Keydown="keydown",e.ContextMenu="contextmenu",e.Resize="resize",e.SelectionChange="selectionchange",e.VisibilityChange="visibilitychange"})(Ee||(Ee={}));function $r(e){e.preventDefault()}function Sd(e){e.stopPropagation()}var X;(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"})(X||(X={}));const ea={start:[X.Space,X.Enter],cancel:[X.Esc],end:[X.Space,X.Enter,X.Tab]},kd=(e,t)=>{let{currentCoordinates:r}=t;switch(e.code){case X.Right:return{...r,x:r.x+25};case X.Left:return{...r,x:r.x-25};case X.Down:return{...r,y:r.y+25};case X.Up:return{...r,y:r.y-25}}};class tr{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 pt(ct(r)),this.windowListeners=new pt(ye(r)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(Ee.Resize,this.handleCancel),this.windowListeners.add(Ee.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(Ee.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:r}=this.props,s=t.node.current;s&&jd(s),r(De)}handleKeyDown(t){if(Zn(t)){const{active:r,context:s,options:a}=this.props,{keyboardCodes:o=ea,coordinateGetter:l=kd,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}:De;this.referenceCoordinates||(this.referenceCoordinates=f);const p=l(t,{active:r,context:s.current,currentCoordinates:f});if(p){const m=gt(p,f),x={x:0,y:0},{scrollableAncestors:j}=s.current;for(const y of j){const g=t.code,{isTop:w,isRight:v,isLeft:h,isBottom:b,maxScroll:N,minScroll:k}=Qs(y),S=bd(y),C={x:Math.min(g===X.Right?S.right-S.width/2:S.right,Math.max(g===X.Right?S.left:S.left+S.width/2,p.x)),y:Math.min(g===X.Down?S.bottom-S.height/2:S.bottom,Math.max(g===X.Down?S.top:S.top+S.height/2,p.y))},D=g===X.Right&&!v||g===X.Left&&!h,R=g===X.Down&&!b||g===X.Up&&!w;if(D&&C.x!==p.x){const E=y.scrollLeft+m.x,V=g===X.Right&&E<=N.x||g===X.Left&&E>=k.x;if(V&&!m.y){y.scrollTo({left:E,behavior:c});return}V?x.x=y.scrollLeft-E:x.x=g===X.Right?y.scrollLeft-N.x:y.scrollLeft-k.x,x.x&&y.scrollBy({left:-x.x,behavior:c});break}else if(R&&C.y!==p.y){const E=y.scrollTop+m.y,V=g===X.Down&&E<=N.y||g===X.Up&&E>=k.y;if(V&&!m.x){y.scrollTo({top:E,behavior:c});return}V?x.y=y.scrollTop-E:x.y=g===X.Down?y.scrollTop-N.y:y.scrollTop-k.y,x.y&&y.scrollBy({top:-x.y,behavior:c});break}}this.handleMove(t,st(gt(p,this.referenceCoordinates),x))}}}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()}}tr.activators=[{eventName:"onKeyDown",handler:(e,t,r)=>{let{keyboardCodes:s=ea,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 Hr(e){return!!(e&&"distance"in e)}function _r(e){return!!(e&&"delay"in e)}class nr{constructor(t,r,s){var a;s===void 0&&(s=Cd(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=ct(l),this.documentListeners=new pt(this.document),this.listeners=new pt(s),this.windowListeners=new pt(ye(l)),this.initialCoordinates=(a=Mn(o))!=null?a:De,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(Ee.Resize,this.handleCancel),this.windowListeners.add(Ee.DragStart,$r),this.windowListeners.add(Ee.VisibilityChange,this.handleCancel),this.windowListeners.add(Ee.ContextMenu,$r),this.documentListeners.add(Ee.Keydown,this.handleKeydown),r){if(s!=null&&s({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(_r(r)){this.timeoutId=setTimeout(this.handleStart,r.delay),this.handlePending(r);return}if(Hr(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(Ee.Click,Sd,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(Ee.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=Mn(t))!=null?r:De,u=gt(a,d);if(!s&&c){if(Hr(c)){if(c.tolerance!=null&&Nn(u,c.tolerance))return this.handleCancel();if(Nn(u,c.distance))return this.handleStart()}if(_r(c)&&Nn(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===X.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const Ed={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class rr extends nr{constructor(t){const{event:r}=t,s=ct(r.target);super(t,Ed,s)}}rr.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 Rd={move:{name:"mousemove"},end:{name:"mouseup"}};var On;(function(e){e[e.RightClick=2]="RightClick"})(On||(On={}));class Td extends nr{constructor(t){super(t,Rd,ct(t.event.target))}}Td.activators=[{eventName:"onMouseDown",handler:(e,t)=>{let{nativeEvent:r}=e,{onActivation:s}=t;return r.button===On.RightClick?!1:(s==null||s({event:r}),!0)}}];const Cn={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class Dd extends nr{constructor(t){super(t,Cn)}static setup(){return window.addEventListener(Cn.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(Cn.move.name,t)};function t(){}}}Dd.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 mt;(function(e){e[e.Pointer=0]="Pointer",e[e.DraggableRect=1]="DraggableRect"})(mt||(mt={}));var Zt;(function(e){e[e.TreeOrder=0]="TreeOrder",e[e.ReversedTreeOrder=1]="ReversedTreeOrder"})(Zt||(Zt={}));function Pd(e){let{acceleration:t,activator:r=mt.Pointer,canScroll:s,draggingRect:a,enabled:o,interval:l=5,order:c=Zt.TreeOrder,pointerCoordinates:d,scrollableAncestors:u,scrollableAncestorRects:f,delta:p,threshold:m}=e;const x=Ld({delta:p,disabled:!o}),[j,y]=Wc(),g=i.useRef({x:0,y:0}),w=i.useRef({x:0,y:0}),v=i.useMemo(()=>{switch(r){case mt.Pointer:return d?{top:d.y,bottom:d.y,left:d.x,right:d.x}:null;case mt.DraggableRect:return a}},[r,a,d]),h=i.useRef(null),b=i.useCallback(()=>{const k=h.current;if(!k)return;const S=g.current.x*w.current.x,C=g.current.y*w.current.y;k.scrollBy(S,C)},[]),N=i.useMemo(()=>c===Zt.TreeOrder?[...u].reverse():u,[c,u]);i.useEffect(()=>{if(!o||!u.length||!v){y();return}for(const k of N){if((s==null?void 0:s(k))===!1)continue;const S=u.indexOf(k),C=f[S];if(!C)continue;const{direction:D,speed:R}=vd(k,C,v,t,m);for(const E of["x","y"])x[E][D[E]]||(R[E]=0,D[E]=0);if(R.x>0||R.y>0){y(),h.current=k,j(b,l),g.current=R,w.current=D;return}}g.current={x:0,y:0},w.current={x:0,y:0},y()},[t,b,s,y,o,l,JSON.stringify(v),JSON.stringify(x),j,u,N,f,JSON.stringify(m)])}const Ad={x:{[de.Backward]:!1,[de.Forward]:!1},y:{[de.Backward]:!1,[de.Forward]:!1}};function Ld(e){let{delta:t,disabled:r}=e;const s=Ln(t);return Ct(a=>{if(r||!s||!a)return Ad;const o={x:Math.sign(t.x-s.x),y:Math.sign(t.y-s.y)};return{x:{[de.Backward]:a.x[de.Backward]||o.x===-1,[de.Forward]:a.x[de.Forward]||o.x===1},y:{[de.Backward]:a.y[de.Backward]||o.y===-1,[de.Forward]:a.y[de.Forward]||o.y===1}}},[r,t,s])}function Md(e,t){const r=t!=null?e.get(t):void 0,s=r?r.node.current:null;return Ct(a=>{var o;return t==null?null:(o=s??a)!=null?o:null},[s,t])}function Id(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 bt;(function(e){e[e.Always=0]="Always",e[e.BeforeDragging=1]="BeforeDragging",e[e.WhileDragging=2]="WhileDragging"})(bt||(bt={}));var Fn;(function(e){e.Optimized="optimized"})(Fn||(Fn={}));const zr=new Map;function Od(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=g(),m=ht(p),x=i.useCallback(function(w){w===void 0&&(w=[]),!m.current&&l(v=>v===null?w:v.concat(w.filter(h=>!v.includes(h))))},[m]),j=i.useRef(null),y=Ct(w=>{if(p&&!r)return zr;if(!w||w===zr||f.current!==e||o!=null){const v=new Map;for(let h of e){if(!h)continue;if(o&&o.length>0&&!o.includes(h.id)&&h.rect.current){v.set(h.id,h.rect.current);continue}const b=h.node.current,N=b?new er(d(b),b):null;h.rect.current=N,N&&v.set(h.id,N)}return v}return w},[e,o,r,p,d]);return i.useEffect(()=>{f.current=e},[e]),i.useEffect(()=>{p||x()},[r,p]),i.useEffect(()=>{o&&o.length>0&&l(null)},[JSON.stringify(o)]),i.useEffect(()=>{p||typeof c!="number"||j.current!==null||(j.current=setTimeout(()=>{x(),j.current=null},c))},[c,p,x,...s]),{droppableRects:y,measureDroppableContainers:x,measuringScheduled:o!=null};function g(){switch(u){case bt.Always:return!1;case bt.BeforeDragging:return r;default:return!r}}}function ta(e,t){return Ct(r=>e?r||(typeof t=="function"?t(e):e):null,[t,e])}function Fd(e,t){return ta(e,t)}function Bd(e){let{callback:t,disabled:r}=e;const s=Qn(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 an(e){let{callback:t,disabled:r}=e;const s=Qn(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 $d(e){return new er(dt(e),e)}function Wr(e,t,r){t===void 0&&(t=$d);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=Bd({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=an({callback:o});return Me(()=>{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 Hd(e){const t=ta(e);return Ys(e,t)}const Vr=[];function _d(e){const t=i.useRef(e),r=Ct(s=>e?s&&s!==Vr&&e&&t.current&&e.parentNode===t.current.parentNode?s:sn(e):Vr,[e]);return i.useEffect(()=>{t.current=e},[e]),r}function zd(e){const[t,r]=i.useState(null),s=i.useRef(e),a=i.useCallback(o=>{const l=jn(o.target);l&&r(c=>c?(c.set(l,In(l)),new Map(c)):null)},[]);return i.useEffect(()=>{const o=s.current;if(e!==o){l(o);const c=e.map(d=>{const u=jn(d);return u?(u.addEventListener("scroll",a,{passive:!0}),[u,In(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=jn(d);u==null||u.removeEventListener("scroll",a)})}},[a,e]),i.useMemo(()=>e.length?t?Array.from(t.values()).reduce((o,l)=>st(o,l),De):Zs(e):De,[e,t])}function Ur(e,t){t===void 0&&(t=[]);const r=i.useRef(null);return i.useEffect(()=>{r.current=null},t),i.useEffect(()=>{const s=e!==De;s&&!r.current&&(r.current=e),!s&&r.current&&(r.current=null)},[e]),r.current?gt(e,r.current):De}function Wd(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 Vd(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 na(e){return i.useMemo(()=>e?md(e):null,[e])}const Kr=[];function Ud(e,t){t===void 0&&(t=dt);const[r]=e,s=na(r?ye(r):null),[a,o]=i.useState(Kr);function l(){o(()=>e.length?e.map(d=>qs(d)?s:new er(t(d),d)):Kr)}const c=an({callback:l});return Me(()=>{c==null||c.disconnect(),l(),e.forEach(d=>c==null?void 0:c.observe(d))},[e]),a}function Kd(e){if(!e)return null;if(e.children.length>1)return e;const t=e.children[0];return Nt(t)?t:e}function Yd(e){let{measure:t}=e;const[r,s]=i.useState(null),a=i.useCallback(u=>{for(const{target:f}of u)if(Nt(f)){s(p=>{const m=t(f);return p?{...p,width:m.width,height:m.height}:m});break}},[t]),o=an({callback:a}),l=i.useCallback(u=>{const f=Kd(u);o==null||o.disconnect(),f&&(o==null||o.observe(f)),s(f?t(f):null)},[t,o]),[c,d]=qt(l);return i.useMemo(()=>({nodeRef:c,rect:r,setRef:d}),[r,c,d])}const Gd=[{sensor:rr,options:{}},{sensor:tr,options:{}}],Jd={current:{}},Wt={draggable:{measure:Br},droppable:{measure:Br,strategy:bt.WhileDragging,frequency:Fn.Optimized},dragOverlay:{measure:dt}};class xt 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 Xd={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new xt,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:Qt},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:Wt,measureDroppableContainers:Qt,windowRect:null,measuringScheduled:!1},qd={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:Qt,draggableNodes:new Map,over:null,measureDroppableContainers:Qt},on=i.createContext(qd),ra=i.createContext(Xd);function Qd(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new xt}}}function Zd(e,t){switch(t.type){case le.DragStart:return{...e,draggable:{...e.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case le.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 le.DragEnd:case le.DragCancel:return{...e,draggable:{...e.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case le.RegisterDroppable:{const{element:r}=t,{id:s}=r,a=new xt(e.droppable.containers);return a.set(s,r),{...e,droppable:{...e.droppable,containers:a}}}case le.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 xt(e.droppable.containers);return l.set(r,{...o,disabled:a}),{...e,droppable:{...e.droppable,containers:l}}}case le.UnregisterDroppable:{const{id:r,key:s}=t,a=e.droppable.containers.get(r);if(!a||s!==a.key)return e;const o=new xt(e.droppable.containers);return o.delete(r),{...e,droppable:{...e.droppable,containers:o}}}default:return e}}function eu(e){let{disabled:t}=e;const{active:r,activatorEvent:s,draggableNodes:a}=i.useContext(on),o=Ln(s),l=Ln(r==null?void 0:r.id);return i.useEffect(()=>{if(!t&&!s&&o&&l!=null){if(!Zn(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=Kc(f);if(p){p.focus();break}}})}},[s,t,a,l,o]),null}function tu(e,t){let{transform:r,...s}=t;return e!=null&&e.length?e.reduce((a,o)=>o({transform:a,...s}),r):r}function nu(e){return i.useMemo(()=>({draggable:{...Wt.draggable,...e==null?void 0:e.draggable},droppable:{...Wt.droppable,...e==null?void 0:e.droppable},dragOverlay:{...Wt.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 ru(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;Me(()=>{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=Ys(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=Gs(u);m&&m.scrollBy({top:p.y,left:p.x})}},[t,l,c,s,r])}const sa=i.createContext({...De,scaleX:1,scaleY:1});var ze;(function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initializing=1]="Initializing",e[e.Initialized=2]="Initialized"})(ze||(ze={}));const su=i.memo(function(t){var r,s,a,o;let{id:l,accessibility:c,autoScroll:d=!0,children:u,sensors:f=Gd,collisionDetection:p=id,measuring:m,modifiers:x,...j}=t;const y=i.useReducer(Zd,void 0,Qd),[g,w]=y,[v,h]=Qc(),[b,N]=i.useState(ze.Uninitialized),k=b===ze.Initialized,{draggable:{active:S,nodes:C,translate:D},droppable:{containers:R}}=g,E=S!=null?C.get(S):null,V=i.useRef({initial:null,translated:null}),F=i.useMemo(()=>{var ce;return S!=null?{id:S,data:(ce=E==null?void 0:E.data)!=null?ce:Jd,rect:V}:null},[S,E]),$=i.useRef(null),[Y,B]=i.useState(null),[T,I]=i.useState(null),A=ht(j,Object.values(j)),O=St("DndDescribedBy",l),Q=i.useMemo(()=>R.getEnabled(),[R]),W=nu(m),{droppableRects:H,measureDroppableContainers:U,measuringScheduled:M}=Od(Q,{dragging:k,dependencies:[D.x,D.y],config:W.droppable}),L=Md(C,S),G=i.useMemo(()=>T?Mn(T):null,[T]),J=un(),ee=Fd(L,W.draggable.measure);ru({activeNode:S!=null?C.get(S):null,config:J.layoutShiftCompensation,initialRect:ee,measure:W.draggable.measure});const _=Wr(L,W.draggable.measure,ee),P=Wr(L?L.parentElement:null),ne=i.useRef({activatorEvent:null,active:null,activeNode:L,collisionRect:null,collisions:null,droppableRects:H,draggableNodes:C,draggingNode:null,draggingNodeRect:null,droppableContainers:R,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),oe=R.getNodeFor((r=ne.current.over)==null?void 0:r.id),re=Yd({measure:W.dragOverlay.measure}),te=(s=re.nodeRef.current)!=null?s:L,q=k?(a=re.rect)!=null?a:_:null,se=!!(re.nodeRef.current&&re.rect),Ve=Hd(se?null:_),Pe=na(te?ye(te):null),he=_d(k?oe??L:null),Be=Ud(he),ue=tu(x,{transform:{x:D.x-Ve.x,y:D.y-Ve.y,scaleX:1,scaleY:1},activatorEvent:T,active:F,activeNodeRect:_,containerNodeRect:P,draggingNodeRect:q,over:ne.current.over,overlayNodeRect:re.rect,scrollableAncestors:he,scrollableAncestorRects:Be,windowRect:Pe}),Qe=G?st(G,D):null,fe=zd(he),Ue=Ur(fe),$e=Ur(fe,[_]),we=st(ue,Ue),K=q?dd(q,ue):null,je=F&&K?p({active:F,collisionRect:K,droppableRects:H,droppableContainers:Q,pointerCoordinates:Qe}):null,Ke=Ks(je,"id"),[Re,Et]=i.useState(null),ln=se?ue:st(ue,$e),Rt=ld(ln,(o=Re==null?void 0:Re.rect)!=null?o:null,_),Ze=i.useRef(null),Tt=i.useCallback((ce,pe)=>{let{sensor:me,options:Ne}=pe;if($.current==null)return;const ge=C.get($.current);if(!ge)return;const xe=ce.nativeEvent,Ce=new me({active:$.current,activeNode:ge,event:xe,options:Ne,context:ne,onAbort(ae){if(!C.get(ae))return;const{onDragAbort:Se}=A.current,Te={id:ae};Se==null||Se(Te),v({type:"onDragAbort",event:Te})},onPending(ae,ie,Se,Te){if(!C.get(ae))return;const{onDragPending:Ge}=A.current,ve={id:ae,constraint:ie,initialCoordinates:Se,offset:Te};Ge==null||Ge(ve),v({type:"onDragPending",event:ve})},onStart(ae){const ie=$.current;if(ie==null)return;const Se=C.get(ie);if(!Se)return;const{onDragStart:Te}=A.current,Ye={activatorEvent:xe,active:{id:ie,data:Se.data,rect:V}};ut.unstable_batchedUpdates(()=>{Te==null||Te(Ye),N(ze.Initializing),w({type:le.DragStart,initialCoordinates:ae,active:ie}),v({type:"onDragStart",event:Ye}),B(Ze.current),I(xe)})},onMove(ae){w({type:le.DragMove,coordinates:ae})},onEnd:He(le.DragEnd),onCancel:He(le.DragCancel)});Ze.current=Ce;function He(ae){return async function(){const{active:Se,collisions:Te,over:Ye,scrollAdjustedTranslate:Ge}=ne.current;let ve=null;if(Se&&Ge){const{cancelDrop:_e}=A.current;ve={activatorEvent:xe,active:Se,collisions:Te,delta:Ge,over:Ye},ae===le.DragEnd&&typeof _e=="function"&&await Promise.resolve(_e(ve))&&(ae=le.DragCancel)}$.current=null,ut.unstable_batchedUpdates(()=>{w({type:ae}),N(ze.Uninitialized),Et(null),B(null),I(null),Ze.current=null;const _e=ae===le.DragEnd?"onDragEnd":"onDragCancel";if(ve){const Je=A.current[_e];Je==null||Je(ve),v({type:_e,event:ve})}})}}},[C]),Dt=i.useCallback((ce,pe)=>(me,Ne)=>{const ge=me.nativeEvent,xe=C.get(Ne);if($.current!==null||!xe||ge.dndKit||ge.defaultPrevented)return;const Ce={active:xe};ce(me,pe.options,Ce)===!0&&(ge.dndKit={capturedBy:pe.sensor},$.current=Ne,Tt(me,pe))},[C,Tt]),Oe=Id(f,Dt);Wd(f),Me(()=>{_&&b===ze.Initializing&&N(ze.Initialized)},[_,b]),i.useEffect(()=>{const{onDragMove:ce}=A.current,{active:pe,activatorEvent:me,collisions:Ne,over:ge}=ne.current;if(!pe||!me)return;const xe={active:pe,activatorEvent:me,collisions:Ne,delta:{x:we.x,y:we.y},over:ge};ut.unstable_batchedUpdates(()=>{ce==null||ce(xe),v({type:"onDragMove",event:xe})})},[we.x,we.y]),i.useEffect(()=>{const{active:ce,activatorEvent:pe,collisions:me,droppableContainers:Ne,scrollAdjustedTranslate:ge}=ne.current;if(!ce||$.current==null||!pe||!ge)return;const{onDragOver:xe}=A.current,Ce=Ne.get(Ke),He=Ce&&Ce.rect.current?{id:Ce.id,rect:Ce.rect.current,data:Ce.data,disabled:Ce.disabled}:null,ae={active:ce,activatorEvent:pe,collisions:me,delta:{x:ge.x,y:ge.y},over:He};ut.unstable_batchedUpdates(()=>{Et(He),xe==null||xe(ae),v({type:"onDragOver",event:ae})})},[Ke]),Me(()=>{ne.current={activatorEvent:T,active:F,activeNode:L,collisionRect:K,collisions:je,droppableRects:H,draggableNodes:C,draggingNode:te,draggingNodeRect:q,droppableContainers:R,over:Re,scrollableAncestors:he,scrollAdjustedTranslate:we},V.current={initial:q,translated:K}},[F,L,je,K,C,te,q,H,R,Re,he,we]),Pd({...J,delta:D,draggingRect:K,pointerCoordinates:Qe,scrollableAncestors:he,scrollableAncestorRects:Be});const cn=i.useMemo(()=>({active:F,activeNode:L,activeNodeRect:_,activatorEvent:T,collisions:je,containerNodeRect:P,dragOverlay:re,draggableNodes:C,droppableContainers:R,droppableRects:H,over:Re,measureDroppableContainers:U,scrollableAncestors:he,scrollableAncestorRects:Be,measuringConfiguration:W,measuringScheduled:M,windowRect:Pe}),[F,L,_,T,je,P,re,C,R,H,Re,U,he,Be,W,M,Pe]),dn=i.useMemo(()=>({activatorEvent:T,activators:Oe,active:F,activeNodeRect:_,ariaDescribedById:{draggable:O},dispatch:w,draggableNodes:C,over:Re,measureDroppableContainers:U}),[T,Oe,F,_,w,O,C,Re,U]);return be.createElement(Ws.Provider,{value:h},be.createElement(on.Provider,{value:dn},be.createElement(ra.Provider,{value:cn},be.createElement(sa.Provider,{value:Rt},u)),be.createElement(eu,{disabled:(c==null?void 0:c.restoreFocus)===!1})),be.createElement(td,{...c,hiddenTextDescribedById:O}));function un(){const ce=(Y==null?void 0:Y.autoScrollEnabled)===!1,pe=typeof d=="object"?d.enabled===!1:d===!1,me=k&&!ce&&!pe;return typeof d=="object"?{...d,enabled:me}:{enabled:me}}}),au=i.createContext(null),Yr="button",ou="Draggable";function iu(e){let{id:t,data:r,disabled:s=!1,attributes:a}=e;const o=St(ou),{activators:l,activatorEvent:c,active:d,activeNodeRect:u,ariaDescribedById:f,draggableNodes:p,over:m}=i.useContext(on),{role:x=Yr,roleDescription:j="draggable",tabIndex:y=0}=a??{},g=(d==null?void 0:d.id)===t,w=i.useContext(g?sa:au),[v,h]=qt(),[b,N]=qt(),k=Vd(l,t),S=ht(r);Me(()=>(p.set(t,{id:t,key:o,node:v,activatorNode:b,data:S}),()=>{const D=p.get(t);D&&D.key===o&&p.delete(t)}),[p,t]);const C=i.useMemo(()=>({role:x,tabIndex:y,"aria-disabled":s,"aria-pressed":g&&x===Yr?!0:void 0,"aria-roledescription":j,"aria-describedby":f.draggable}),[s,x,y,g,j,f.draggable]);return{active:d,activatorEvent:c,activeNodeRect:u,attributes:C,isDragging:g,listeners:s?void 0:k,node:v,over:m,setNodeRef:h,setActivatorNodeRef:N,transform:w}}function lu(){return i.useContext(ra)}const cu="Droppable",du={timeout:25};function uu(e){let{data:t,disabled:r=!1,id:s,resizeObserverConfig:a}=e;const o=St(cu),{active:l,dispatch:c,over:d,measureDroppableContainers:u}=i.useContext(on),f=i.useRef({disabled:r}),p=i.useRef(!1),m=i.useRef(null),x=i.useRef(null),{disabled:j,updateMeasurementsFor:y,timeout:g}={...du,...a},w=ht(y??s),v=i.useCallback(()=>{if(!p.current){p.current=!0;return}x.current!=null&&clearTimeout(x.current),x.current=setTimeout(()=>{u(Array.isArray(w.current)?w.current:[w.current]),x.current=null},g)},[g]),h=an({callback:v,disabled:j||!l}),b=i.useCallback((C,D)=>{h&&(D&&(h.unobserve(D),p.current=!1),C&&h.observe(C))},[h]),[N,k]=qt(b),S=ht(t);return i.useEffect(()=>{!h||!N.current||(h.disconnect(),p.current=!1,h.observe(N.current))},[N,h]),i.useEffect(()=>(c({type:le.RegisterDroppable,element:{id:s,key:o,disabled:r,node:N,rect:m,data:S}}),()=>c({type:le.UnregisterDroppable,key:o,id:s})),[s]),i.useEffect(()=>{r!==f.current.disabled&&(c({type:le.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:N,over:d,setNodeRef:k}}function sr(e,t,r){const s=e.slice();return s.splice(r<0?s.length+r:r,0,s.splice(t,1)[0]),s}function fu(e,t){return e.reduce((r,s,a)=>{const o=t.get(s);return o&&(r[a]=o),r},Array(e.length))}function Ot(e){return e!==null&&e>=0}function pu(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 mu(e){return typeof e=="boolean"?{draggable:e,droppable:e}:e}const aa=e=>{let{rects:t,activeIndex:r,overIndex:s,index:a}=e;const o=sr(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}},Ft={scaleX:1,scaleY:1},xu=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,...Ft}:null}const d=hu(o,a,r);return a>r&&a<=l?{x:0,y:-c.height-d,...Ft}:a<r&&a>=l?{x:0,y:c.height+d,...Ft}:{x:0,y:0,...Ft}};function hu(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 oa="Sortable",ia=be.createContext({activeIndex:-1,containerId:oa,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:aa,disabled:{draggable:!1,droppable:!1}});function gu(e){let{children:t,id:r,items:s,strategy:a=aa,disabled:o=!1}=e;const{active:l,dragOverlay:c,droppableRects:d,over:u,measureDroppableContainers:f}=lu(),p=St(oa,r),m=c.rect!==null,x=i.useMemo(()=>s.map(k=>typeof k=="object"&&"id"in k?k.id:k),[s]),j=l!=null,y=l?x.indexOf(l.id):-1,g=u?x.indexOf(u.id):-1,w=i.useRef(x),v=!pu(x,w.current),h=g!==-1&&y===-1||v,b=mu(o);Me(()=>{v&&j&&f(x)},[v,x,j,f]),i.useEffect(()=>{w.current=x},[x]);const N=i.useMemo(()=>({activeIndex:y,containerId:p,disabled:b,disableTransforms:h,items:x,overIndex:g,useDragOverlay:m,sortedRects:fu(x,d),strategy:a}),[y,p,b.draggable,b.droppable,h,x,g,d,m,a]);return be.createElement(ia.Provider,{value:N},t)}const vu=e=>{let{id:t,items:r,activeIndex:s,overIndex:a}=e;return sr(r,s,a).indexOf(t)},bu=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},yu={duration:200,easing:"ease"},la="transform",wu=vt.Transition.toString({property:la,duration:0,easing:"linear"}),ju={roleDescription:"sortable"};function Nu(e){let{disabled:t,index:r,node:s,rect:a}=e;const[o,l]=i.useState(null),c=i.useRef(r);return Me(()=>{if(!t&&r!==c.current&&s.current){const d=a.current;if(d){const u=dt(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 Cu(e){let{animateLayoutChanges:t=bu,attributes:r,disabled:s,data:a,getNewIndex:o=vu,id:l,strategy:c,resizeObserverConfig:d,transition:u=yu}=e;const{items:f,containerId:p,activeIndex:m,disabled:x,disableTransforms:j,sortedRects:y,overIndex:g,useDragOverlay:w,strategy:v}=i.useContext(ia),h=Su(s,x),b=f.indexOf(l),N=i.useMemo(()=>({sortable:{containerId:p,index:b,items:f},...a}),[p,a,b,f]),k=i.useMemo(()=>f.slice(f.indexOf(l)),[f,l]),{rect:S,node:C,isOver:D,setNodeRef:R}=uu({id:l,data:N,disabled:h.droppable,resizeObserverConfig:{updateMeasurementsFor:k,...d}}),{active:E,activatorEvent:V,activeNodeRect:F,attributes:$,setNodeRef:Y,listeners:B,isDragging:T,over:I,setActivatorNodeRef:A,transform:O}=iu({id:l,data:N,attributes:{...ju,...r},disabled:h.draggable}),Q=zc(R,Y),W=!!E,H=W&&!j&&Ot(m)&&Ot(g),U=!w&&T,M=U&&H?O:null,G=H?M??(c??v)({rects:y,activeNodeRect:F,activeIndex:m,overIndex:g,index:b}):null,J=Ot(m)&&Ot(g)?o({id:l,items:f,activeIndex:m,overIndex:g}):b,ee=E==null?void 0:E.id,_=i.useRef({activeId:ee,items:f,newIndex:J,containerId:p}),P=f!==_.current.items,ne=t({active:E,containerId:p,isDragging:T,isSorting:W,id:l,index:b,items:f,newIndex:_.current.newIndex,previousItems:_.current.items,previousContainerId:_.current.containerId,transition:u,wasDragging:_.current.activeId!=null}),oe=Nu({disabled:!ne,index:b,node:C,rect:S});return i.useEffect(()=>{W&&_.current.newIndex!==J&&(_.current.newIndex=J),p!==_.current.containerId&&(_.current.containerId=p),f!==_.current.items&&(_.current.items=f)},[W,J,p,f]),i.useEffect(()=>{if(ee===_.current.activeId)return;if(ee!=null&&_.current.activeId==null){_.current.activeId=ee;return}const te=setTimeout(()=>{_.current.activeId=ee},50);return()=>clearTimeout(te)},[ee]),{active:E,activeIndex:m,attributes:$,data:N,rect:S,index:b,newIndex:J,items:f,isOver:D,isSorting:W,isDragging:T,listeners:B,node:C,overIndex:g,over:I,setNodeRef:Q,setActivatorNodeRef:A,setDroppableNodeRef:R,setDraggableNodeRef:Y,transform:oe??G,transition:re()};function re(){if(oe||P&&_.current.newIndex===b)return wu;if(!(U&&!Zn(V)||!u)&&(W||ne))return vt.Transition.toString({...u,property:la})}}function Su(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 en(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 ku=[X.Down,X.Right,X.Up,X.Left],Eu=(e,t)=>{let{context:{active:r,collisionRect:s,droppableRects:a,droppableContainers:o,over:l,scrollableAncestors:c}}=t;if(ku.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 X.Down:s.top<m.top&&d.push(p);break;case X.Up:s.top>m.top&&d.push(p);break;case X.Left:s.left>m.left&&d.push(p);break;case X.Right:s.left<m.left&&d.push(p);break}});const u=ad({collisionRect:s,droppableRects:a,droppableContainers:d});let f=Ks(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),x=m?a.get(m.id):null,j=m==null?void 0:m.node.current;if(j&&x&&p&&m){const g=sn(j).some((k,S)=>c[S]!==k),w=ca(p,m),v=Ru(p,m),h=g||!w?{x:0,y:0}:{x:v?s.width-x.width:0,y:v?s.height-x.height:0},b={x:x.left,y:x.top};return h.x&&h.y?b:gt(b,h)}}}};function ca(e,t){return!en(e)||!en(t)?!1:e.data.current.sortable.containerId===t.data.current.sortable.containerId}function Ru(e,t){return!en(e)||!en(t)||!ca(e,t)?!1:e.data.current.sortable.index<t.data.current.sortable.index}function da(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 Tu(){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 Du({slug:e,onClose:t}){return n.jsx("div",{className:"px-3 py-2 border-t border-[var(--border-subtle)]",children:n.jsx(ys,{slashCommand:`/codeyam-edit-plan ${e}`,height:360,onClose:t})})}function Pu({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 Au({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 Lu({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 Mu({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 Iu({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(Mu,{dep:t},t.slug))})]})}function Ou({body:e,providerLabel:t,onEdit:r,onChat:s,dependencies:a}){return n.jsxs("div",{className:"border-t border-[var(--border-subtle)]",children:[a&&a.length>0&&n.jsx(Iu,{dependencies:a}),n.jsx("div",{className:"px-3 py-2 max-h-[40vh] overflow-y-auto",children:n.jsx(ot,{variant:"compact",children:e})}),n.jsxs("div",{className:"flex gap-2 justify-end px-3 py-2 border-t border-[var(--border-subtle)]",children:[n.jsx(Au,{onClick:r}),n.jsx(Lu,{providerLabel:t,onClick:s})]})]})}function Fu({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}=Tu(),{config:p}=yt(),m=Vt(p==null?void 0:p.provider);return i.useEffect(()=>{o(e.title),c(e.body),s("view")},[e.slug]),r==="chat"?n.jsx(Du,{slug:e.slug,onClose:()=>s("view")}):r==="edit"?n.jsx(Pu,{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(Ou,{body:e.body,providerLabel:m,onEdit:()=>s("edit"),onChat:()=>s("chat"),dependencies:t})}const ua="Building is in progress, please wait for it to complete before starting a new build session.";function Bu({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?ua:void 0,className:l+(u?c:""),children:r?"Launching…":"Run"})}function $u({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:x=!1,unsatisfiedDepCount:j=0,unsatisfiedDepTooltip:y,dependencies:g}){const w=v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),r())};return n.jsxs("li",{ref:p,style:m,className:`border border-[var(--border-subtle)] rounded-lg bg-[var(--bg-surface,transparent)] ${x?"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:v=>v.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(Bu,{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}),j>0&&n.jsxs("span",{"data-testid":`plan-dep-chip-${e.slug}`,title:y,className:"text-[10px] uppercase tracking-wide px-1.5 py-0.5 rounded border",style:{borderColor:"var(--accent-warn, #c08a2c)",color:"var(--accent-warn, #c08a2c)"},children:["blocked: depends on ",j," plan",j===1?"":"s"]}),n.jsx("span",{className:"text-[10px] text-[var(--text-dim)] whitespace-nowrap",children:da(e.createdAt)})]}),t&&n.jsx(Fu,{plan:e,dependencies:g})]})}function Hu({plan:e,position:t,expanded:r,onToggle:s,onRun:a,launching:o,blocked:l,onBlockedClick:c,draggable:d,unsatisfiedDepCount:u,unsatisfiedDepTooltip:f,dependencies:p}){const{attributes:m,listeners:x,setNodeRef:j,setActivatorNodeRef:y,transform:g,transition:w,isDragging:v}=Cu({id:e.slug,disabled:!d}),h={transform:vt.Transform.toString(g),transition:w};return n.jsx($u,{plan:e,expanded:r,onToggle:s,onRun:a,launching:o,blocked:l,onBlockedClick:c,position:t,sortableRef:j,sortableStyle:h,isDragging:v,dragHandleRef:d?y:void 0,dragHandleAttributes:d?m:void 0,dragHandleListeners:d?x:void 0,unsatisfiedDepCount:u,unsatisfiedDepTooltip:f,dependencies:p})}function ar({plans:e,loading:t,error:r,onRun:s,launchingSlug:a,launchError:o,blocked:l=!1,onBlockedClick:c,onReorder:d,depAnnotationsBySlug:u,dependenciesBySlug:f}){const[p,m]=i.useState(null),[x,j]=i.useState(null),[y,g]=i.useState(null);i.useEffect(()=>{j(null)},[e]);const w=x??e,v=w.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 (",v,")"]}),o&&n.jsxs("p",{className:"mt-2 text-sm text-[var(--accent-red)]",children:["Failed to launch plan: ",o]}),y&&n.jsxs("p",{className:"mt-2 text-sm text-[var(--accent-red)]",children:["Failed to reorder plans: ",y]}),n.jsx(_u,{plans:w,loading:t,error:r,expandedSlug:p,onToggle:h=>m(b=>b===h?null:h),onRun:s,launchingSlug:a??null,blocked:l,onBlockedClick:c,depAnnotationsBySlug:u,dependenciesBySlug:f,onReorder:d?async h=>{j(h),g(null);try{await d(h.map(b=>b.slug))}catch(b){j(null),g(b instanceof Error?b.message:"Unknown error")}}:void 0})]})}function _u({plans:e,loading:t,error:r,expandedSlug:s,onToggle:a,onRun:o,launchingSlug:l,blocked:c,onBlockedClick:d,onReorder:u,depAnnotationsBySlug:f,dependenciesBySlug:p}){const m=nd(Ir(rr,{activationConstraint:{distance:4}}),Ir(tr,{coordinateGetter:Eu})),x=i.useMemo(()=>e.map(g=>g.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 j=g=>{const{active:w,over:v}=g;if(!v||w.id===v.id||!u)return;const h=e.findIndex(N=>N.slug===w.id),b=e.findIndex(N=>N.slug===v.id);h===-1||b===-1||u(sr(e,h,b))},y=n.jsx("ul",{className:"mt-3 flex flex-col gap-2","data-testid":"plan-list",children:e.map((g,w)=>{const v=f==null?void 0:f[g.slug];return n.jsx(Hu,{plan:g,position:w+1,expanded:s===g.slug,onToggle:()=>a(g.slug),onRun:o,launching:l===g.slug,blocked:c,onBlockedClick:d,draggable:!!u,unsatisfiedDepCount:v==null?void 0:v.count,unsatisfiedDepTooltip:v==null?void 0:v.tooltip,dependencies:p==null?void 0:p[g.slug]},g.slug)})});return u?n.jsx(su,{sensors:m,collisionDetection:sd,onDragEnd:j,children:n.jsx(gu,{items:x,strategy:xu,children:y})}):y}function zu({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:x,onLaunchPlan:j,launchingSlug:y,launchError:g,onReorderPlans:w,isAgentBuilding:v}){const{recoveryFeatureName:h,recoveryStep:b,recoveryMode:N,showTerminal:k,shouldResumeSameProvider:S}=vc({awaitingPlanLaunchChoice:e,configLoading:t,sessionLoading:r,sessionDecision:s,sessionInfo:a,stepState:o});return s==="pending"?n.jsx(gc,{featureName:h,editorStep:b,workflowMode:N,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?n.jsx(Yn,{children:n.jsx(ar,{plans:p,loading:m,error:x,onRun:C=>{var R;const D=((R=p.find(E=>E.slug===C))==null?void 0:R.title)??C;j(C,D)},launchingSlug:y,launchError:g,blocked:v,onReorder:w})}):k?n.jsx(_c,{provider:l,shouldResumeSameProvider:S,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 Wu(e){return e?{step:e.step??0,feature:e.feature??null,startedAt:e.startedAt??"",mode:Ie(e.mode),slug:e.slug??null}:null}const Vu=3e3;function kt(){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=Wu(c),u=JSON.stringify(d);u!==o.current&&(o.current=u,t(d)),s(!1)}).catch(()=>{s(!1)})};return l(),a.current=setInterval(l,Vu),()=>{a.current&&clearInterval(a.current)}},[]),{stepState:e,loading:r}}const ke={hasSession:!1,resumeMode:"fresh",provider:null,feature:null,step:null,mode:null,label:null,sessionId:null,awaitingUserInput:!1,reopenResults:!1,preview:null};function Uu(e){return{hasSession:(e==null?void 0:e.hasSession)??ke.hasSession,resumeMode:(e==null?void 0:e.resumeMode)??ke.resumeMode,provider:(e==null?void 0:e.provider)??ke.provider,feature:(e==null?void 0:e.feature)??ke.feature,step:(e==null?void 0:e.step)??ke.step,mode:(e==null?void 0:e.mode)==null?ke.mode:Ie(e.mode),label:(e==null?void 0:e.label)??ke.label,sessionId:(e==null?void 0:e.sessionId)??ke.sessionId,awaitingUserInput:(e==null?void 0:e.awaitingUserInput)??ke.awaitingUserInput,reopenResults:(e==null?void 0:e.reopenResults)??ke.reopenResults,preview:(e==null?void 0:e.preview)??ke.preview}}function fa(){const[e,t]=i.useState(null),[r,s]=i.useState(!0),a=i.useCallback(async()=>{s(!0);try{const l=await(await fetch("/api/session-info")).json();t(Uu(l))}catch{t(ke)}finally{s(!1)}},[]);return i.useEffect(()=>{a()},[a]),{sessionInfo:e,loading:r,refetch:a}}const Ku=5e3;function Yu(){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,Ku),()=>{a.current&&clearInterval(a.current)}},[]),{prompt:e,loading:r}}function Gu({currentDecision:e,sessionInfo:t,sessionLoading:r}){return r||!t?e:e==="continue"&&t.hasSession?"continue":t.resumeMode==="resume"||t.resumeMode==="handoff"?"pending":"fresh"}function Ju({sessionLoading:e,sessionInfo:t,onSessionDetected:r}){const s=i.useRef(!1),[a,o]=i.useState("no-session");i.useEffect(()=>{o(c=>Gu({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 Xu(){const e=document.activeElement;return e===null||e===document.body||e===document.documentElement||e instanceof HTMLElement&&e.dataset.navTab==="true"}function qu(e,t,r,s=0){return e>=r.left-s&&e<=r.right+s&&t>=r.top-s&&t<=r.bottom+s}function Gr(e){Xt(),e.blur(),window.dispatchEvent(new Event("terminal-focus")),queueMicrotask(()=>{document.activeElement instanceof HTMLIFrameElement&&window.dispatchEvent(new Event("terminal-focus"))})}function Qu(e){const t=i.useRef(!1);i.useEffect(()=>{if(!e)return;function r(){if(!t.current&&Xu()){t.current=!0;try{Xt(),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&&Gr(c)}function o(l){const c=document.activeElement;if(!(c instanceof HTMLIFrameElement))return;const d=c.getBoundingClientRect();qu(l.clientX,l.clientY,d,1)||Gr(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 Zu({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 ef(e){const t=i.useRef(e);i.useEffect(()=>{e&&e!==t.current&&(vs(e),t.current=e)},[e])}function Jr(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 tf({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 nf({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(ot,{variant:"compact",children:e})})}function rf({currentStep:e,isExpanded:t,mode:r,onToggle:s=()=>{},stepNum:a}){const o=a===e,l=a<e,{description:c,label:d}=Ds(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 sf({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);Jr(p,o,i.useCallback(()=>l(!1),[])),Jr(m,u,i.useCallback(()=>f(!1),[]));const x=t&&e>0,j=t||"New Working Session",y=Ie(r),g=Ds(e,y),w=x?g.label:null,v=g.totalSteps,h=g.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:j})]}),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(tf,{displayName:j,hasPrompt:!!a,expanded:u,onToggle:()=>f(b=>!b)})]}),x&&n.jsxs("div",{className:"relative",ref:p,children:[n.jsxs("button",{onClick:()=>l(b=>!b),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:[h," ",e,n.jsxs("span",{style:{color:"var(--text-dim)"},children:[" / ",v]}),": ",w]}),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:v},(b,N)=>N+1).map(b=>{const N=c===b;return n.jsx(rf,{currentStep:e,isExpanded:N,mode:y,onToggle:()=>d(N?null:b),stepNum:b},b)})})]})]}),u&&a&&n.jsx(nf,{prompt:a})]})}function af({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:x,onReorderPlans:j,isAgentBuilding:y}){const{stepState:g}=kt(),{config:w,loading:v}=yt(),{prompt:h}=Yu(),{sessionInfo:b,loading:N}=fa(),{sessionDecision:k,handleContinueSession:S}=Ju({sessionLoading:N,sessionInfo:b,onSessionDetected:r});return Qu(t),Zu({sessionLoading:N,sessionInfo:b,onRestorePreview:c}),ef((g==null?void 0:g.feature)??null),n.jsx(oc,{stepIndicator:n.jsx(sf,{step:(g==null?void 0:g.step)??0,feature:(g==null?void 0:g.feature)??null,mode:(g==null?void 0:g.mode)??"ui",projectTitle:(w==null?void 0:w.projectName)??null,userPrompt:h}),sessionContent:n.jsx(zu,{awaitingPlanLaunchChoice:e,configLoading:v,sessionLoading:N,sessionDecision:k,sessionInfo:b,stepState:g,provider:l,onContinueSession:S,onAgentIdle:s,onAgentActive:a,onUserInput:o,pendingPlans:d,pendingPlansLoading:u,pendingPlansError:f,onLaunchPlan:p,launchingSlug:m,launchError:x,onReorderPlans:j,isAgentBuilding:y})})}function pa({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?Fe(e):"",p=f.startsWith("http"),m=t&&!p?`${f}?cb=${t}`:f,x=()=>{l("success"),d(!0)},j=()=>{l("error"),d(!1)};return i.useEffect(()=>{l("loading"),d(!1);const y=u.current;y!=null&&y.complete&&(y.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:x,onError:j,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 of({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 rt(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]}:rt(e,{defaultSelection:!0,selectedIndex:t.selectedIndex})}const r=Math.min(t.selectedIndex??0,e.length-1);return{selectedIndex:r,scenario:e[r]}}function lf(e){return e==null?"":typeof e=="string"?e:typeof e=="object"&&typeof e.name=="string"?e.name:String(e)}const cf="/api/editor-session-summary",df=3e3;function uf(e=df){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(cf);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 ff({onClose:e,onSelectScenario:t}){var m,x;const{summary:r,loading:s,refreshing:a,refresh:o}=uf(),[l,c]=i.useState(0),d=i.useMemo(()=>r?[...r.application,...r.components]:[],[r]),u=i.useCallback(j=>{d.length!==0&&(document.activeElement instanceof HTMLIFrameElement||Rc()||(j.key==="ArrowRight"?(j.preventDefault(),c(y=>{const g=rt(d,{direction:"next",selectedIndex:y});return g.scenario&&(t==null||t(g.scenario.slug,g.scenario.url)),g.selectedIndex})):j.key==="ArrowLeft"&&(j.preventDefault(),c(y=>{const g=rt(d,{direction:"previous",selectedIndex:y});return g.scenario&&(t==null||t(g.scenario.slug,g.scenario.url)),g.selectedIndex}))))},[d,t]);i.useEffect(()=>(window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)),[u]);const f=i.useRef(!1);if(i.useEffect(()=>{if(f.current||d.length===0)return;f.current=!0;const j=rt(d,{defaultSelection:!0,selectedIndex:l});j.scenario&&(t==null||t(j.scenario.slug,j.scenario.url))},[d,t,l]),s)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(!r)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 p=r.application.length+r.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(of,{refreshing:a,onRefresh:o,onClose:e}),n.jsxs("div",{className:"flex-1 overflow-auto p-4 space-y-4",children:[r.userPrompt&&n.jsx(pf,{text:r.userPrompt}),n.jsx(Bt,{title:"Application",icon:"🌐",count:r.application.length,empty:p===0?"No scenarios in this session":void 0,children:r.application.length>0&&n.jsx(xf,{scenarios:r.application,selectedSlug:(m=d[l])==null?void 0:m.slug,onSelect:(j,y)=>{var w,v;const g=rt(d,{slug:j,selectedIndex:l});g.selectedIndex>=0&&c(g.selectedIndex),t==null||t(((w=g.scenario)==null?void 0:w.slug)??j,((v=g.scenario)==null?void 0:v.url)??y)}})}),n.jsx(Bt,{title:"Components",icon:"🧩",count:r.components.length,children:r.components.length>0&&n.jsx(mf,{scenarios:r.components,selectedSlug:(x=d[l])==null?void 0:x.slug,onSelect:(j,y)=>{var w,v;const g=rt(d,{slug:j,selectedIndex:l});g.selectedIndex>=0&&c(g.selectedIndex),t==null||t(((w=g.scenario)==null?void 0:w.slug)??j,((v=g.scenario)==null?void 0:v.url)??y)}})}),n.jsx(Bt,{title:"Functions",icon:"⚙️",count:r.functions.length,children:r.functions.length>0&&n.jsx(gf,{functions:r.functions})}),n.jsx(Bt,{title:"Modified Files",icon:"📄",count:r.modifiedFiles.length,children:r.modifiedFiles.length>0&&n.jsx(vf,{files:r.modifiedFiles})})]})]})}function pf({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(ot,{variant:"compact",children:e}),a&&n.jsx("button",{onClick:()=>r(!1),className:"text-blue-600 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-blue-600 hover:underline ml-1 text-xs",children:"Read more..."})]})]})}function Bt({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 Bn({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(hf,{scenario:s,isSelected:s.slug===t,onSelect:r},s.slug))})})}function mf({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(Bn,{scenarios:s[o],selectedSlug:t,onSelect:r})]},o))})}function xf({scenarios:e,selectedSlug:t,onSelect:r}){if(!e.some(l=>l.routeName))return n.jsx(Bn,{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(Bn,{scenarios:a[l],selectedSlug:t,onSelect:r})]},l))})}function hf({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(pa,{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 gf({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:lf(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 vf({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(Kn,{status:t.status}),n.jsx("span",{className:"text-xs text-[var(--text-secondary)] font-mono truncate",children:t.path})]},t.path))})}function bf({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 yf({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]),bf({showStepResults:r,showResultsPanel:s,openResults:c,closeResults:d}),{closeResults:d,openResults:c,resultsKey:o,showResultsPanel:s}}function wf(e){return(e==null?void 0:e.mode)==="ui"&&(e==null?void 0:e.slug)==="feature-complete"}function jf({awaitingPlanLaunchChoice:e,buildActivated:t,activeTab:r,onSessionDetected:s,onSelectScenario:a,showResultsCommandKey:o,hideResultsCommandKey:l,onAgentIdle:c,onAgentActive:d,onUserInput:u,notifSettings:f,onSettingsChange:p,provider:m,onRestorePreview:x,pendingPlans:j,pendingPlansLoading:y,pendingPlansError:g,onLaunchPlan:w,launchingSlug:v,launchError:h,onReorderPlans:b,isAgentBuilding:N}){const{stepState:k}=kt(),{closeResults:S,resultsKey:C,showResultsPanel:D}=yf({showResultsCommandKey:o,hideResultsCommandKey:l,showStepResults:wf(k)});return t?n.jsx(ic,{activeTab:r,showResultsPanel:D,buildTab:n.jsx(af,{awaitingPlanLaunchChoice:e,isActive:r==="build",onSessionDetected:s,onAgentIdle:c,onAgentActive:d,onUserInput:u,provider:m,onRestorePreview:x,pendingPlans:j,pendingPlansLoading:y,pendingPlansError:g,onLaunchPlan:w,launchingSlug:v,launchError:h,onReorderPlans:b,isAgentBuilding:N}),resultsPanel:n.jsx(ff,{onClose:S,onSelectScenario:a},C),footer:n.jsx(Rl,{settings:f,onChange:p,agentName:m})}):null}function Nf({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 Cf({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 Xr=["·","✢","✳","✶","✻","✽"],Sf=160;function kf(){const[e,t]=i.useState(0);return i.useEffect(()=>{const r=window.setInterval(()=>t(s=>(s+1)%Xr.length),Sf);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-[#29C0CF] leading-none text-[11px] tabular-nums",children:Xr[e]})}function Ef({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 Rf({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("circle",{cx:"12",cy:"12",r:"3"}),n.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})}function Tf({onNavigateToBuild:e,onDismiss:t}){return i.useEffect(()=>(z("banner-mounted",{}),()=>{z("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 Df=[{key:"home",label:"Home"},{key:"plan",label:"Plan"},{key:"build",label:"Build"},{key:"history",label:"History"}];function qr(){if(typeof document>"u")return;const e=document.activeElement;e instanceof HTMLElement&&e.blur()}function Pf({activeTab:e,onTabChange:t,onSendTranscript:r,buildIdle:s=!1,isAgentBuilding:a=!1,bannerVisible:o=!1,onDismissIdleBanner:l}){const c=o&&e!=="build",d=s,u=a&&!s,f=u?"green":d?"orange":"none",p=i.useRef(f);return i.useEffect(()=>{p.current!==f&&(z("build-tab-dot-change",{from:p.current,to:f}),p.current=f)},[f]),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(Nf,{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:Df.map(m=>n.jsxs(Yt,{href:Kt(m.key),"data-nav-tab":"true",onNavigate:()=>{t(m.key),qr(),m.key==="build"&&We()},className:`px-2.5 py-2.5 text-sm transition-colors cursor-pointer border-b ${e===m.key?"text-[#D7FF63] border-[#D7FF63] font-medium":"text-[#8E8E8E] border-transparent hover:text-white font-light"}`,children:[m.key==="build"&&u&&n.jsx(kf,{}),m.key==="build"&&d&&n.jsx("span",{"data-testid":"nav-build-dot-idle",className:"mr-1 inline-block w-2 h-2 rounded-full bg-[#FF8B43]"}),m.label]},m.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(Ef,{})}),n.jsx(Yt,{href:Kt("settings"),"data-nav-tab":"true",onNavigate:()=>{t("settings"),qr()},className:`p-1.5 rounded-md transition-colors cursor-pointer inline-flex items-center ${e==="settings"?"text-[#D7FF63]":"text-[#8E8E8E] hover:text-white"}`,title:"Settings",children:n.jsx(Rf,{})})]}),c&&n.jsx(Tf,{onNavigateToBuild:()=>t("build"),onDismiss:l??(()=>{})})]})}function Af({appDetailProps:e,appOverviewProps:t,selectedApp:r}){return r?n.jsx(Oi,{app:r,...e}):n.jsx(ac,{...t},"app-overview")}function Lf({activeTab:e,awaitingPlanLaunchChoice:t,buildActivated:r,hideResultsCommandKey:s,onSelectScenario:a,onSessionDetected:o,showResultsCommandKey:l,onAgentIdle:c,onAgentActive:d,onUserInput:u,notifSettings:f,onSettingsChange:p,provider:m,onRestorePreview:x,pendingPlans:j,pendingPlansLoading:y,pendingPlansError:g,onLaunchPlan:w,launchingSlug:v,launchError:h,onReorderPlans:b,isAgentBuilding:N}){return r?n.jsx(jf,{awaitingPlanLaunchChoice:t,buildActivated:r,activeTab:e,onSessionDetected:o,onSelectScenario:a,showResultsCommandKey:l,hideResultsCommandKey:s,onAgentIdle:c,onAgentActive:d,onUserInput:u,notifSettings:f,onSettingsChange:p,provider:m,onRestorePreview:x,pendingPlans:j,pendingPlansLoading:y,pendingPlansError:g,onLaunchPlan:w,launchingSlug:v,launchError:h,onReorderPlans:b,isAgentBuilding:N}):null}function Mf({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)"}})})}function If({isCollapsed:e,leftPane:t,onResizeStart:r,previewPane:s,splitRef:a}){return 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(Mf,{onMouseDown:r})]}),s]})}function ma(){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;(d!==r.current.scenariosVersion||u!==r.current.plansVersion)&&(r.current={scenariosVersion:d,plansVersion:u},t(r.current))}catch{}};a();const o=setInterval(a,500);return()=>{s=!0,clearInterval(o)}},[]),e}function xa(){const[e,t]=i.useState([]),[r,s]=i.useState(!0),[a,o]=i.useState(null),{plansVersion:l}=ma(),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 ha(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 Of(e,t,r){const s=new Map(r.map(o=>[o.slug,o])),a=new Map(t.map(o=>[o.slug,o]));return e.dependsOn.map(o=>{const l=s.get(o),c=a.get(o);return{slug:o,title:(c==null?void 0:c.title)??(l==null?void 0:l.title)??null,satisfied:l!==void 0}})}function ga(e){return e.filter(t=>!t.satisfied)}function va(e){const{plans:t}=ha();return i.useMemo(()=>{const r={},s={};for(const a of e){const o=a.dependsOn??[];if(o.length===0)continue;const l=Of({...a,dependsOn:o},e,t);s[a.slug]=l;const c=ga(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 at={hasActiveSession:!1,isAgentBuilding:!1,stepStateFeature:null};function ba(e){at={...at,...e}}function Ff(){return at}function Bf(){return at.hasActiveSession||at.isAgentBuilding||!!at.stepStateFeature}const $f=500;async function or(){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&&ba({hasActiveSession:!1,isAgentBuilding:!1,stepStateFeature:null}),z("clear-editor-session",{ok:e,...t!==void 0?{status:t}:{},snapshotReset:e})}async function ir(e={}){const t=Ff(),r=e.caller??"unknown",s=e.bypassLiveGuard===!0;if(Bf()&&!s){z("launch-editor-skill",{caller:r,suppressed:!0,snapshot:t,bypassLiveGuard:!1});return}Nc(),z("launch-editor-skill",{caller:r,suppressed:!1,snapshot:t,bypassLiveGuard:s}),e.provider!=="gemini"&&($s(e.renameLabel??"Editor",r,bs),Rn("/clear\r"),await new Promise(a=>setTimeout(()=>{Rn("/codeyam-editor\r"),a()},$f)))}async function Hf(e={}){await or(),await ir(e)}function lr(e){const t=Bo(e),[r,s]=i.useState(t==="build"),[a,o]=i.useState(t==="plan");i.useEffect(()=>{t==="build"&&s(!0),t==="plan"&&o(!0)},[t]);const l=i.useCallback(d=>{window.history.pushState(null,"",Kt(d)),d==="build"&&s(!0),d==="plan"&&o(!0)},[]),c=i.useCallback(()=>{window.history.pushState(null,"",Kt("build")),s(!0)},[]);return{activeTab:t,buildActivated:r,planActivated:a,navigateToTab:l,showBuildTab:c}}function ya(){const{showBuildTab:e}=lr(typeof window>"u"?"/":window.location.pathname),{config:t}=yt(),[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 or()}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)}return e(),await ir({caller:"plan-launcher",renameLabel:d,provider:t==null?void 0:t.provider,bypassLiveGuard:!0}),!0}catch(u){return o(u instanceof Error?u.message:"Failed to launch plan"),!1}finally{s(null)}},[r,e,t==null?void 0:t.provider]);return{launchingSlug:r,error:a,launchPlan:l}}function wa(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])}}function _f(){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:"Claude Code will remember your plans and suggest them once the current building session is over."})]})}function zf({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 Wf({onClose:e}){return n.jsx(ys,{slashCommand:"/codeyam-plan",height:360,onClose:e})}function Vf(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 Uf({journalTimestamp:e}){const{entry:t,loading:r,error:s}=Vf(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(As,{entry:t}):n.jsx("p",{className:"text-sm text-[var(--text-dim)]",children:"No journal entry found for this plan yet."})}function Kf({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:da(e.completedAt)}),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(Uf,{journalTimestamp:e.journalTimestamp})})]})}function Yf({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(Gf,{plans:e,loading:t,error:r,expandedSlug:s,onToggle:l=>a(c=>c===l?null:l)})]})}function Gf({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(Kf,{plan:o,expanded:s===o.slug,onToggle:()=>a(o.slug)},o.slug))})}function Jf({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:ua}),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 Xf({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"})})]})})}function qf({chatOpen:e,onChatOpenChange:t,isActive:r=!0,isAgentBuilding:s=!1,launchingSlug:a,launchError:o,onLaunchPlan:l}={}){const{plans:c,loading:d,error:u,refetch:f}=xa(),{plans:p,loading:m,error:x}=ha(),j=l!==void 0,y=ya(),g=j?a??null:y.launchingSlug,w=j?o??null:y.error,[v,h]=i.useState(!1),[b,N]=i.useState(!1),[k,S]=i.useState(null),C=e!==void 0,D=C?e:v,R=T=>{C||h(T),t==null||t(T)},E=()=>{R(!1),f()},V=()=>{const T=!D;T&&We(),R(T)};i.useEffect(()=>{if(!(!r||!D))return We()},[r,D]);const{annotationsBySlug:F,dependenciesBySlug:$}=va(c),Y=T=>{var O;const I=ga($[T]??[]);if(I.length>0){S(I);return}const A=((O=c.find(Q=>Q.slug===T))==null?void 0:O.title)??T;if(l){l(T,A);return}y.launchPlan(T,A)},{reorderPlans:B}=wa(f);return n.jsxs(Yn,{testId:"plan-tab",children:[n.jsx(_f,{}),n.jsx(zf,{open:D,onToggle:V}),D&&n.jsx(Wf,{onClose:E}),n.jsx(ar,{plans:c,loading:d,error:u,onRun:Y,launchingSlug:g,launchError:w,blocked:s,onBlockedClick:()=>N(!0),onReorder:B,depAnnotationsBySlug:F,dependenciesBySlug:$}),n.jsx(Yf,{plans:p,loading:m,error:x}),b&&n.jsx(Jf,{onClose:()=>N(!1)}),k&&!b&&n.jsx(Xf,{deps:k,onClose:()=>S(null)})]})}function Qf({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(qf,{chatOpen:r,onChatOpenChange:s,isActive:e==="plan",isAgentBuilding:a,launchingSlug:o,launchError:l,onLaunchPlan:c})}):null}function Zf({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 ep({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(Zf,{visible:e===s,children:t[s]},s))})}function tp({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 np({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(ep,{activeTab:e,width:r,children:{home:t,build:null,plan:null,history:a?n.jsx(xl,{}):null,settings:n.jsx(tp,{title:"Settings"})}})})}function rp({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:x,dependenciesBySlug:j}=va(e),y=i.useCallback(b=>{b.key==="Escape"&&(b.preventDefault(),c())},[c]);i.useEffect(()=>(window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)),[y]);const g=p.trim(),w=g.length===0||o||r!==null,v=()=>{w||a(g)},h=b=>{(b.metaKey||b.ctrlKey)&&b.key==="Enter"&&(b.preventDefault(),v())};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(ar,{plans:e,loading:d,error:u,onRun:b=>{var k;const N=((k=e.find(S=>S.slug===b))==null?void 0:k.title)??b;t(b,N)},launchingSlug:r,launchError:s,blocked:f,depAnnotationsBySlug:x,dependenciesBySlug:j})}),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:b=>m(b.target.value),onKeyDown:h,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:v,disabled:w,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, #4a9eff)",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 sp({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 ap({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(sp,{onCreateNewPlan:e,onViewPlans:t})})}function op(e){return!e||!(e instanceof Element)?!1:!!e.closest("[data-terminal-emulator], .xterm")}function ip(e){return!e||!(e instanceof Element)?!1:!!e.closest("[data-post-push-modal]")}function lp({onStartNextFeature:e,onContinueInSession:t,onSendTranscript:r,onSelectPlan:s,pendingPlanCount:a=0}){const o=a>0&&s,l={background:"var(--accent-active)",color:"var(--bg-deep)"},c={background:"transparent",color:"var(--text-secondary)",border:"1px solid var(--border-default)"};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:[o&&n.jsx("button",{onClick:s,className:"w-full px-4 py-2.5 rounded-md text-sm font-medium transition cursor-pointer",style:l,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:o?c:l,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:c,type:"button",children:"Continue in Current Session"}),r&&n.jsx("button",{onClick:r,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:o?"Press Enter to pick a queued plan":"Press Enter to start a new feature with a fresh context"})]})}function cp({onStartNextFeature:e,onContinueInSession:t,onSendTranscript:r,onSelectPlan:s,pendingPlanCount:a=0}){const o=i.useCallback(l=>{if(l.key!=="Enter"||op(l.target))return;const c=l.target===document.body||l.target===document.documentElement||l.target===document;!ip(l.target)&&!c||(l.preventDefault(),a>0&&s?s():e())},[s,e,a]);return i.useEffect(()=>(window.addEventListener("keydown",o),()=>window.removeEventListener("keydown",o)),[o]),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(lp,{onStartNextFeature:e,onContinueInSession:t,onSendTranscript:r,onSelectPlan:s,pendingPlanCount:a})})}function dp({plan:e,onSelect:t,isLaunching:r,isDisabled:s}){var o;const a=((o=e.body.trim().split(`
|
|
17
|
+
`)[0])==null?void 0:o.slice(0,140))??"";return n.jsxs("button",{type:"button",onClick:()=>t(e.slug,e.title),disabled:s||r,className:"w-full text-left px-3 py-2 rounded-md transition cursor-pointer disabled:cursor-not-allowed disabled:opacity-50",style:{background:"transparent",border:"1px solid var(--border-default)",color:"var(--text-primary)"},"data-testid":`select-plan-card-${e.slug}`,children:[n.jsxs("div",{className:"flex items-center justify-between gap-3 mb-1",children:[n.jsx("span",{className:"flex-1 min-w-0 truncate text-sm font-medium",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})]}),a&&n.jsx("p",{className:"text-xs text-[var(--text-muted)] truncate",children:a}),r&&n.jsx("p",{className:"mt-1 text-xs text-[var(--accent-active)]",children:"Launching…"})]})}function up({plans:e,onSelect:t,onCancel:r,launchingSlug:s,error:a}){const o=i.useCallback(l=>{if(l.key==="Escape"){l.preventDefault(),r();return}l.key==="Enter"&&e.length>0&&!s&&(l.preventDefault(),t(e[0].slug,e[0].title))},[s,r,t,e]);return i.useEffect(()=>(window.addEventListener("keydown",o),()=>window.removeEventListener("keydown",o)),[o]),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(l=>n.jsx("li",{children:n.jsx(dp,{plan:l,onSelect:t,isLaunching:s===l.slug,isDisabled:s!==null&&s!==l.slug})},l.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 fp({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,navigateToTab:m,onAgentActive:x,onAgentIdle:j,onUserInput:y,notifSettings:g,onSettingsChange:w,provider:v,onContinueInSession:h,onRestorePreview:b,onResultsScenarioSelect:N,onSessionDetected:k,onStartNextFeature:S,showPostPushModal:C,showResultsCommandKey:D,planChatOpen:R,onPlanChatOpenChange:E,showPlanCompleteModal:V,onCreateNewPlan:F,onViewPlans:$,pendingPlans:Y,onSelectPlan:B,selectPlanOpen:T,onPickPlan:I,onCancelSelectPlan:A,launchingPlanSlug:O,planLaunchError:Q,showBuildLaunchModal:W=!1,onSubmitBuildPrompt:H,submittingBuildPrompt:U=!1,buildPromptError:M=null,onCancelBuildLaunchModal:L,pendingPlansLoading:G,pendingPlansError:J,onReorderPlans:ee}){return n.jsxs("div",{className:"shrink-0 flex flex-col overflow-hidden",style:{width:p,background:"var(--bg-deep)"},children:[n.jsx(Pf,{activeTab:e,onTabChange:m,onSendTranscript:t,buildIdle:l,isAgentBuilding:c,bannerVisible:d,onDismissIdleBanner:u}),n.jsxs("div",{className:"flex-1 min-h-0 overflow-hidden relative",children:[n.jsx(Lf,{awaitingPlanLaunchChoice:s,buildActivated:a,activeTab:e,onSessionDetected:k,onSelectScenario:N,showResultsCommandKey:D,hideResultsCommandKey:f,onAgentIdle:j,onAgentActive:x,onUserInput:y,notifSettings:g,onSettingsChange:w,provider:v,onRestorePreview:b,pendingPlans:Y,pendingPlansLoading:G,pendingPlansError:J,onLaunchPlan:I,launchingSlug:O,launchError:Q,onReorderPlans:ee,isAgentBuilding:c}),n.jsx(Qf,{activeTab:e,planActivated:o,chatOpen:R,onChatOpenChange:E,isAgentBuilding:c,launchingPlanSlug:O,planLaunchError:Q,onLaunchPlan:I}),n.jsx(np,{activeTab:e,appTabContent:r,leftWidth:p}),C&&e==="build"&&!T?n.jsx(cp,{onStartNextFeature:S,onContinueInSession:h,onSendTranscript:t,onSelectPlan:B,pendingPlanCount:Y.length}):null,T&&e==="build"?n.jsx(up,{plans:Y,onSelect:I,onCancel:A,launchingSlug:O,error:Q}):null,W&&e==="build"&&!C&&H&&L?n.jsx(rp,{plans:Y,onPickPlan:I,launchingSlug:O,planError:Q,onSubmitPrompt:H,submittingPrompt:U,promptError:M,onCancel:L,pendingPlansLoading:G,pendingPlansError:J,isAgentBuilding:c}):null,V&&e==="plan"?n.jsx(ap,{onCreateNewPlan:F,onViewPlans:$}):null]})]})}const tn=5173;function cr(e){if(e.startsWith("http"))try{return new URL(e).pathname}catch{return e}return e.split("?")[0]??e}function ja(e){return e?parseInt(e.port||(e.protocol==="https:"?"443":"80"),10):0}function Na(e,{appPort:t,currentPort:r}){return e.startsWith("http")||r===t?e:`http://localhost:${t}${e}`}function pp(e,t,r,s){if(r&&r.length>0)return Na(r,{appPort:s,currentPort:t});const a=`/scenario/${e}`;return t===tn?a:`http://localhost:${tn}${a}`}async function Qr(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 mp(e){try{await fetch("/api/editor-iframe-error",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({error:e})})}catch{}}async function xp(e){try{await fetch("/api/editor-iframe-banner",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({seedError:e})})}catch{}}function hp(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 gp=32;function vp({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:hp(s.width,s.height,t,e,gp);return{containerRef:d,containerSize:s,scale:u}}function bp(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 Zr(){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 yp=50,wp={status:"loading",lastSuccessAt:null,lastErrorAt:null,lastErrorMessage:null,fetchCount:0,errorCount:0};function jp(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 Np(e,t){return{timestamp:t,success:e.ok,statusCode:e.statusCode,durationMs:e.durationMs,error:e.error}}function Cp(e,t){return[t,...e].slice(0,yp)}function Sp(){const[e,t]=i.useState(wp),[r,s]=i.useState([]),a=i.useCallback(l=>{const c=Date.now();s(d=>Cp(d,Np(l,c))),t(d=>jp(d,l,c))},[]),o=i.useCallback(()=>{t(l=>({...l,status:"polling"}))},[]);return{connectionState:e,fetchLog:r,recordFetch:a,markPolling:o}}function kp(){const[e,t]=i.useState(()=>Date.now());return i.useEffect(()=>{const r=setInterval(()=>t(Date.now()),1e3);return()=>clearInterval(r)},[]),e}function Ep(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 Rp({state:e}){const t=kp(),{dotClass:r,label:s,labelClass:a}=Ep(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 ",No(e.lastSuccessAt,t)]})]})}function Tp({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:Dn(e.durationMs)}),e.error&&n.jsx("span",{className:"text-red-500 truncate","data-testid":"connection-log-error",children:e.error})]})}function Dp({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(Tp,{entry:a},a.timestamp))})})]})}function Pp({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 Ap({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(Gn,{title:"Function Coverage",aggregate:t,aggregateTestId:"functions-coverage-aggregate"}),s&&n.jsx(Pp,{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 Lp({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(Gn,{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(Fs,{file:r},r.filePath))})]})]})}function Mp(){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 Ip({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(Is,{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 Op(){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 Fp({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 $t(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 Bp(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 Ht({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 $p({failures:e}){const t=Bp(e);return n.jsxs("div",{className:"space-y-3",children:[t.global.length>0&&n.jsx(Ht,{title:"Global",items:t.global.map($t)}),t.perFile.length>0&&n.jsx(Ht,{title:"Per-file",items:t.perFile.map($t)}),t.perGlossaryEntry.length>0&&n.jsx(Ht,{title:"Per-glossary-entry",items:t.perGlossaryEntry.map($t)}),t.regression.length>0&&n.jsx(Ht,{title:"Regression",items:t.regression.map($t)})]})}function Hp({report:e}){if(!e)return n.jsx(Mp,{});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(Ip,{global:e.global,failureCount:e.failures.length}),e.usedDefaultThresholds&&n.jsx(Op,{}),t?n.jsx(Fp,{ranRunners:e.ranRunners}):n.jsx($p,{failures:e.failures})]})}const _p=new Set([3,4,6]),zp=5e3;function Wp(){const[e,t]=i.useState(null),[r,s]=i.useState(!0),{connectionState:a,fetchLog:o,recordFetch:l,markPolling:c}=Sp(),d=i.useRef(null);if(i.useEffect(()=>{async function m(){const x=await Zr();l(x),x.ok&&x.data&&t(x.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&&_p.has(e.step)&&(d.current=setInterval(async()=>{c();const m=await Zr();l(m),m.ok&&m.data&&t(m.data)},zp)),()=>{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,x)=>m+x.tests.length,0),p=bp(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(Rp,{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(Rs,{children:e.userPrompt})]})]}),n.jsx(tl,{currentStep:u}),n.jsx(nl,{stats:e.testRunnerStats}),n.jsx(Bs,{warnings:e.coverageWarnings??[]}),p&&n.jsx("div",{className:"text-sm text-[var(--text-secondary)] text-center",children:p}),e.narrative&&n.jsx(rl,{narrative:e.narrative}),e.narrative?n.jsx(sl,{narrative:e.narrative}):n.jsx(il,{step:u,fileCount:e.modifiedFiles.length,testCount:f}),n.jsx(Lp,{projectWide:e.projectWideCoverage??null,orphanedFiles:e.orphanedFiles??[]}),n.jsx(Ap,{functions:e.functions,aggregate:e.coverage??null,projectWide:e.projectWideCoverage??null}),n.jsx(Hp,{report:e.coverageThresholds??null}),e.modifiedFiles.length>0&&n.jsx(cl,{files:e.modifiedFiles,defaultCollapsed:e.narrative!==null}),n.jsx(Dp,{state:a,entries:o})]})})}function Vp(){return n.jsx("div",{className:"flex-1 flex flex-col min-w-0 overflow-auto",style:{background:"var(--bg-deep)"},children:n.jsx(Wp,{})})}function Up({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 $n(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 Ca(e){return Jn(e)?e.componentName??$n(e.name).pageName:$n(e.name).pageName}function dr(e){return $n(e.name).stateName}function Kp({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 es({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 Yp({onClick:e,isOpen:t,disabled:r}){return n.jsx("button",{type:"button",onClick:e,disabled:r,"aria-expanded":t,"aria-haspopup":"dialog",className:`flex items-center h-7 px-2 rounded text-[11px] font-mono tracking-wide cursor-pointer transition-colors ${r?"text-gray-500 bg-[#2d2d2d] cursor-not-allowed":t?"text-white bg-[#555]":"text-gray-300 bg-[#3a3a3a] hover:bg-[#444]"}`,title:"Edit scenario data",children:"EDIT DATA"})}function ur(e){return`${e.method} ${e.pathPattern}`}function Gp({slug:e,onApplied:t}){const[r,s]=i.useState({kind:"idle"}),a=i.useCallback(async o=>{s({kind:"submitting"});try{const c=await(await fetch(`/api/scenarios/${encodeURIComponent(e)}/data/describe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:o})})).json();c.success?(t(),s({kind:"applied",message:c.message??"Changes applied. Review the table and click Save."})):s({kind:"error",message:c.error??"AI rewrite failed."})}catch(l){s({kind:"error",message:l instanceof Error?l.message:"Network error"})}},[e,t]);return{status:r,submit:a}}function Jp(e,t){i.useEffect(()=>{function r(a){e.current&&!e.current.contains(a.target)&&t()}function s(a){a.key==="Escape"&&t()}return document.addEventListener("mousedown",r),document.addEventListener("keydown",s),()=>{document.removeEventListener("mousedown",r),document.removeEventListener("keydown",s)}},[e,t])}function Xp({props:e,seedTabs:t,mockEntries:r}){const[s,a]=i.useState(null),[o,l]=i.useState(null),[c,d]=i.useState(null),u=i.useMemo(()=>{const m=[];return e&&Object.keys(e).length>0&&m.push({kind:"props",label:"Props",tabs:[]}),t.length>0&&m.push({kind:"seed",label:"Seed Data",tabs:t.map(x=>({id:x.dataKey,label:x.label}))}),r.length>0&&m.push({kind:"mock",label:"Mock Data",tabs:r.map(x=>({id:ur(x),label:`${x.method} ${x.pathPattern}`}))}),m},[e,t,r]);i.useEffect(()=>{if(s!==null||u.length===0)return;const m=u[0];a(m.kind),m.kind==="seed"&&m.tabs[0]?l(m.tabs[0].id):m.kind==="mock"&&m.tabs[0]&&d(m.tabs[0].id)},[s,u]);const f=u.find(m=>m.kind===s)??null;function p(m){var x,j,y,g;if(a(m),m==="seed"&&!o){const w=(j=(x=u.find(v=>v.kind==="seed"))==null?void 0:x.tabs[0])==null?void 0:j.id;w&&l(w)}if(m==="mock"&&!c){const w=(g=(y=u.find(v=>v.kind==="mock"))==null?void 0:y.tabs[0])==null?void 0:g.id;w&&d(w)}}return{sections:u,activeSection:f,section:s,activeSeedKey:o,activeMockKey:c,selectSection:p,selectSeedKey:l,selectMockKey:d}}function qp(e){const[t,r]=i.useState(null);return i.useEffect(()=>{var l;const s=(l=e.current)==null?void 0:l.closest("[data-preview-pane='true']");if(!s)return;const a=()=>r(s.getBoundingClientRect().width);a();const o=new ResizeObserver(a);return o.observe(s),()=>o.disconnect()},[e]),t}function fr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Qp(e){return Array.isArray(e)&&e.length>0&&e.every(fr)}function Hn(e,t,r){if(fr(e)){for(const[s,a]of Object.entries(e)){const o=t?`${t}.${s}`:s;Hn(a,o,r)}return}if(Qp(e)){e.forEach((s,a)=>Hn(s,`${t}[${a}]`,r));return}r.push({path:t,value:e})}function ts(e){if(!fr(e))return[];const t=[];return Hn(e,"",t),t}function Zp(e){return e===null?"null":e===void 0?"":typeof e=="object"?JSON.stringify(e):String(e)}function em({slug:e,initialProps:t,onCellEdited:r}){const[s,a]=i.useState(()=>ts(t)),[o,l]=i.useState(null),[c,d]=i.useState(""),[u,f]=i.useState(""),p=i.useRef(null);i.useEffect(()=>{a(ts(t)),l(null)},[t]);function m(w){const v=s.find(N=>N.path===w);l(w);const h=v==null?void 0:v.value,b=h==null?"":typeof h=="object"?JSON.stringify(h):String(h);d(b),f(b)}function x(w){if(d(w),p.current&&clearTimeout(p.current),!o)return;const v=o;p.current=setTimeout(()=>{g(v,w)},600)}function j(){o&&(p.current&&clearTimeout(p.current),g(o,c),l(null))}function y(){if(p.current&&clearTimeout(p.current),!!o){if(c!==u){const w=s.map(v=>v.path===o?{...v,value:wr(u)}:v);a(w),fetch(`/api/scenarios/${encodeURIComponent(e)}/data`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:`props.${o}`,value:u})}).then(()=>{Ut(),r&&r()}).catch(()=>{})}l(null)}}async function g(w,v){const h=s.map(b=>b.path===w?{...b,value:wr(v)}:b);a(h);try{await fetch(`/api/scenarios/${encodeURIComponent(e)}/data`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:`props.${w}`,value:v})}),Ut(),r&&r()}catch{}}return{rows:s,editingPath:o,editValue:c,handleEditPath:m,handleEditValueChange:x,handleSave:j,handleCancelEdit:y}}function tm({path:e,value:t,onValueChange:r,onSave:s,onCancel:a}){return n.jsxs("div",{className:"border-t border-[var(--border-default)] bg-[var(--bg-deep)] px-3 py-2",children:[n.jsx("div",{className:"flex items-center gap-2 mb-1.5",children:n.jsxs("span",{className:"text-[10px] text-[var(--text-muted)]",children:["Editing"," ",n.jsx("strong",{className:"text-[var(--text-secondary)] font-mono",children:e})]})}),n.jsx("textarea",{value:t,onChange:o=>r(o.target.value),className:"w-full px-2 py-1.5 text-[11px] bg-[var(--bg-card)] text-[var(--text-primary)] border border-[var(--border-default)] rounded outline-none focus:border-[var(--accent-active)]/50 resize-y min-h-[60px] max-h-[200px] font-mono",autoFocus:!0,rows:t.length>100?4:2,onKeyDown:o=>{o.key==="Escape"&&a(),o.key==="Enter"&&(o.metaKey||o.ctrlKey)&&s()}}),n.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[n.jsx("button",{onClick:s,className:"px-3 py-1 text-[10px] font-medium text-[var(--bg-deep)] bg-[var(--accent-active)] rounded cursor-pointer border-none hover:bg-[var(--accent-active)]/80 transition-colors",children:"Save"}),n.jsx("button",{onClick:a,className:"px-3 py-1 text-[10px] text-[var(--text-muted)] hover:text-[var(--text-primary)] bg-transparent border-none cursor-pointer",children:"Cancel"}),n.jsxs("span",{className:"text-[9px] text-[var(--text-dim)] ml-auto",children:["⌘","+Enter to save, Esc to cancel"]})]})]})}function nm({slug:e,props:t,onCellEdited:r}){const{rows:s,editingPath:a,editValue:o,handleEditPath:l,handleEditValueChange:c,handleSave:d,handleCancelEdit:u}=em({slug:e,initialProps:t,onCellEdited:r});return s.length===0?n.jsx("p",{className:"p-4 text-xs text-[var(--text-dim)] italic",children:"This scenario has no props to edit."}):n.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[n.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:n.jsxs("table",{className:"w-full text-[11px] border-separate border-spacing-0",children:[n.jsx("thead",{className:"bg-[var(--bg-card)] sticky top-0 z-10",children:n.jsxs("tr",{children:[n.jsx("th",{className:"text-left font-medium text-[var(--text-secondary)] px-3 py-2 border-b border-[var(--border-default)] w-1/3",children:"Key"}),n.jsx("th",{className:"text-left font-medium text-[var(--text-secondary)] px-3 py-2 border-b border-[var(--border-default)]",children:"Value"})]})}),n.jsx("tbody",{children:s.map(f=>n.jsxs("tr",{className:"hover:bg-[var(--bg-card)]",children:[n.jsx("td",{className:"px-3 py-1.5 border-b border-[var(--border-subtle)] font-mono text-[var(--text-secondary)] align-top",children:f.path}),n.jsx("td",{className:"px-3 py-1.5 border-b border-[var(--border-subtle)] cursor-text text-[var(--text-primary)] align-top",onClick:()=>l(f.path),children:Zp(f.value)})]},f.path))})]})}),a&&n.jsx(tm,{path:a,value:o,onValueChange:c,onSave:d,onCancel:u})]})}function rm({slug:e,section:t,hasAnything:r,loading:s,seedError:a,mocksError:o,draftError:l,props:c,selectedSeedTab:d,filteredSeedRows:u,selectedMock:f,onSeedCellEdit:p,onMockSave:m}){return n.jsxs("div",{className:"min-h-0 flex-1 flex flex-col bg-[var(--bg-deep)] overflow-hidden",children:[a&&n.jsxs("p",{className:"p-3 text-xs text-red-400",children:["Seed error: ",a]}),o&&n.jsxs("p",{className:"p-3 text-xs text-red-400",children:["Mocks error: ",o]}),l&&n.jsxs("p",{className:"p-3 text-xs text-red-400",children:["Draft error: ",l]}),s&&!r&&n.jsx("p",{className:"p-4 text-xs text-[var(--text-dim)]",children:"Loading scenario data…"}),!s&&!r&&n.jsx("p",{className:"p-4 text-xs text-[var(--text-dim)] italic",children:"This scenario has no data, mocks, or props to edit."}),t==="props"&&n.jsx(nm,{slug:e,props:c,onCellEdited:p}),t==="seed"&&d&&n.jsx(Co,{slug:e,tab:d,initialRows:u,onCellEdited:p}),t==="mock"&&f&&n.jsx("div",{className:"flex-1 min-h-0 overflow-auto p-3",children:f.source==="scenario"||f.source==="default"||f.source==="shared"?n.jsx(So,{entry:f,routeKey:ur(f),scenarioSlug:e,onSave:m}):n.jsx(ko,{entry:f})})]})}function sm({status:e,onSubmit:t}){const[r,s]=i.useState(""),a=e.kind==="submitting";function o(){const l=r.trim();!l||a||(t(l),s(""))}return n.jsxs("div",{className:"shrink-0 border-t border-[var(--border-default)] bg-[var(--bg-deep)] px-4 py-3",children:[n.jsxs("div",{className:"flex items-end gap-2",children:[n.jsx("textarea",{value:r,onChange:l=>s(l.target.value),placeholder:"Describe Changes",rows:2,disabled:a,className:"flex-1 px-3 py-2 text-[12px] bg-[var(--bg-card)] text-[var(--text-primary)] border border-[var(--border-default)] rounded outline-none focus:border-[var(--accent-active)]/50 resize-none min-h-[44px] disabled:opacity-50",onKeyDown:l=>{l.key==="Enter"&&(l.metaKey||l.ctrlKey)&&(l.preventDefault(),o())}}),n.jsx("button",{type:"button",onClick:o,disabled:a||!r.trim(),className:"px-3 py-2 text-[11px] font-medium text-[var(--bg-deep)] bg-[var(--accent-active)] rounded cursor-pointer border-none hover:bg-[var(--accent-active)]/80 disabled:opacity-50 disabled:cursor-not-allowed transition-colors h-fit",children:a?"Applying…":"Submit"})]}),e.kind==="applied"&&n.jsx("p",{className:"text-[10px] text-[var(--accent-active)] mt-1.5",children:e.message}),e.kind==="error"&&n.jsx("p",{className:"text-[10px] text-red-400 mt-1.5",children:e.message})]})}function am({isDirty:e,saving:t,cancelling:r,onSave:s,onCancel:a,onClose:o}){const l=t||r;return n.jsxs(n.Fragment,{children:[e&&n.jsxs(n.Fragment,{children:[n.jsx("button",{type:"button",onClick:s,disabled:l,className:"px-2 py-0.5 text-[10px] font-medium text-[var(--bg-deep)] bg-[var(--accent-active)] rounded cursor-pointer border-none hover:bg-[var(--accent-active)]/80 disabled:opacity-50",children:t?"Saving…":"Save"}),n.jsx("button",{type:"button",onClick:a,disabled:l,className:"px-2 py-0.5 text-[10px] text-[var(--text-muted)] hover:text-[var(--text-primary)] bg-transparent border border-[var(--border-default)] rounded cursor-pointer disabled:opacity-50",children:r?"Cancelling…":"Cancel"})]}),n.jsx("button",{type:"button",onClick:o,"aria-label":"Close",className:"text-[var(--text-muted)] hover:text-[var(--text-primary)] text-sm bg-transparent border-none cursor-pointer px-1 leading-none",children:"✕"})]})}function om({value:e,disabled:t,onChange:r}){return n.jsx("input",{type:"search",value:e,onChange:s=>r(s.target.value),placeholder:"Search…",disabled:t,className:"text-[10px] bg-[var(--bg-card)] text-[var(--text-primary)] border border-[var(--border-default)] rounded px-2 py-0.5 outline-none focus:border-[var(--accent-active)]/50 disabled:opacity-40 w-36"})}function im({sections:e,section:t,activeSection:r,onSelect:s}){return e.length>1?n.jsx("select",{value:t??"",onChange:a=>s(a.target.value),className:"text-[9px] font-semibold tracking-wider uppercase text-[var(--text-primary)] bg-[var(--bg-card)] border border-[var(--border-default)] rounded px-1.5 py-0.5 cursor-pointer outline-none",children:e.map(a=>n.jsx("option",{value:a.kind,children:a.label},a.kind))}):r?n.jsx("span",{className:"text-[9px] font-semibold tracking-wider uppercase text-[var(--text-primary)] px-1.5 py-0.5",children:r.label}):null}function lm({tabs:e,activeId:t,onSelect:r}){return n.jsx("div",{className:"flex items-center gap-0.5 overflow-x-auto min-w-0",children:e.map(s=>{const a=s.id===t;return n.jsx("button",{type:"button",onClick:()=>r(s.id),className:`px-1.5 py-0.5 text-[9px] font-medium tracking-wide uppercase rounded whitespace-nowrap cursor-pointer transition-colors ${a?"text-[var(--accent-active)] bg-[var(--accent-active)]/10":"text-[var(--text-muted)] hover:text-[var(--text-primary)]"}`,children:s.label},s.id)})})}function cm({sections:e,section:t,activeSection:r,activeTabId:s,onSelectSection:a,onSelectTab:o,search:l,searchDisabled:c,onSearchChange:d,isDirty:u,saving:f,cancelling:p,onSave:m,onCancel:x,onClose:j}){return n.jsxs("header",{className:"shrink-0 flex items-center justify-between gap-3 px-3 py-1.5 border-b border-[var(--border-subtle)]",children:[n.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 flex-1",children:[n.jsx(im,{sections:e,section:t,activeSection:r,onSelect:a}),n.jsx("span",{className:"text-[var(--text-dim)] text-[10px]",children:"/"}),n.jsx(lm,{tabs:(r==null?void 0:r.tabs)??[],activeId:s,onSelect:o})]}),n.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[n.jsx(om,{value:l,disabled:c,onChange:d}),n.jsx(am,{isDirty:u,saving:f,cancelling:p,onSave:m,onCancel:x,onClose:j})]})]})}function dm({popoverRef:e,paneWidth:t}){return n.jsx("div",{"aria-hidden":"true",onMouseDown:r=>{const s=e.current;if(!s)return;r.preventDefault();const a=s.getBoundingClientRect(),o=r.clientX,l=r.clientY,c=a.width,d=a.height,u=a.right,f=m=>{const x=m.clientX-o,j=m.clientY-l,y=420,g=280,w=t?Math.max(y,t-16):c+1e3,v=Math.max(y,Math.min(w,c-x)),h=Math.max(g,d+j);s.style.width=`${v}px`,s.style.height=`${h}px`,s.style.right=`${s.parentElement.getBoundingClientRect().right-u}px`},p=()=>{window.removeEventListener("mousemove",f),window.removeEventListener("mouseup",p)};window.addEventListener("mousemove",f),window.addEventListener("mouseup",p)},className:"absolute bottom-0 left-0 w-3 h-3 z-50",style:{cursor:"nesw-resize"}})}function um({slug:e,scenarioName:t,onClose:r}){const s=i.useRef(null),a=Eo({slug:e,onPreviewReload:Ut}),o=qp(s),{data:l,tableTabs:c,props:d,loading:u,error:f}=Ro(e),{entries:p,loading:m,error:x,upsertScoped:j}=ws(e),{sections:y,activeSection:g,section:w,activeSeedKey:v,activeMockKey:h,selectSection:b,selectSeedKey:N,selectMockKey:k}=Xp({props:d,seedTabs:c,mockEntries:p}),[S,C]=i.useState(""),D=w==="seed"?c.find(U=>U.dataKey===v)??null:null,R=w==="mock"?p.find(U=>ur(U)===h)??null:null,E=D&&l?l[D.dataKey]??[]:[],V=i.useMemo(()=>{if(!S.trim())return E;const U=S.toLowerCase();return E.filter(M=>Object.values(M).some(L=>String(L??"").toLowerCase().includes(U)))},[E,S]),F=i.useCallback(()=>{a.markDirty(),Ut()},[a]),$=i.useCallback(async U=>{await j(U),F()},[j,F]),Y=i.useCallback(()=>{a.confirmIfDirty("Discard unsaved changes to this scenario?")&&r()},[a,r]);Jp(s,Y);const B=i.useCallback(async()=>{await a.save(),a.error||r()},[a,r]),T=Gp({slug:e,onApplied:F}),I=w==="seed"?v:w==="mock"?h:null;function A(U){w==="seed"&&N(U),w==="mock"&&k(U)}function O(U){U!==null&&(b(U),C(""))}const Q=t??e,W=y.length>0,H=u||m;return n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"fixed inset-0 z-30 bg-black/30 pointer-events-none","aria-hidden":"true"}),n.jsxs("div",{ref:s,role:"dialog","aria-label":`Edit data for ${Q}`,style:{resize:"both",maxWidth:o?`${Math.max(420,o-16)}px`:"calc(100vw - 2rem)"},className:"absolute right-0 top-full mt-1 z-40 flex flex-col rounded-lg border border-[var(--border-default)] bg-[var(--bg-deep)] shadow-2xl overflow-hidden w-[640px] max-h-[calc(100vh-6rem)] min-w-[420px] min-h-[200px]",children:[n.jsx(cm,{sections:y,section:w,activeSection:g,activeTabId:I,onSelectSection:O,onSelectTab:A,search:S,searchDisabled:w!=="seed",onSearchChange:C,isDirty:a.isDirty,saving:a.saving,cancelling:a.cancelling,onSave:B,onCancel:()=>void a.cancel(),onClose:Y}),n.jsx(rm,{slug:e,section:w,hasAnything:W,loading:H,seedError:f,mocksError:x,draftError:a.error,props:d,selectedSeedTab:D,filteredSeedRows:V,selectedMock:R,onSeedCellEdit:F,onMockSave:$}),n.jsx(sm,{status:T.status,onSubmit:T.submit}),n.jsx(dm,{popoverRef:s,paneWidth:o})]})]})}function fm({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 pm({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 Sa(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 mm(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 ka(e,t){i.useEffect(()=>{const r=a=>{e.current&&!e.current.contains(a.target)&&t()},s=a=>{a.key==="Escape"&&t()};return document.addEventListener("mousedown",r),document.addEventListener("keydown",s),()=>{document.removeEventListener("mousedown",r),document.removeEventListener("keydown",s)}},[e,t])}function xm({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 hm({scenario:e,active:t,onClick:r}){const s=e.screenshotPaths[0],a=dr(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:Fe(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 gm({group:e,currentSlug:t,onSelect:r}){const s=e.scenarios[0]?Ca(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(hm,{scenario:a,active:a.slug===t,onClick:()=>r(a.slug)},a.slug))})]})}function ns({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 vm({scenarioGroups:e,currentSlug:t,onSelect:r,onClose:s}){const[a,o]=i.useState("pages"),[l,c]=i.useState(""),d=i.useRef(null),u=i.useRef(null);i.useEffect(()=>{var g;(g=u.current)==null||g.focus()},[]),ka(d,s);const f=i.useMemo(()=>e.flatMap(g=>g.scenarios),[e]),p=i.useMemo(()=>mm(f,l),[f,l]),m=i.useMemo(()=>p.filter(qe),[p]),x=i.useMemo(()=>p.filter(Jn),[p]),j=a==="pages"?m:x,y=i.useMemo(()=>Sa(j),[j]);return n.jsxs("div",{ref:d,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(ns,{label:"PAGES",active:a==="pages",count:m.length,onClick:()=>o("pages")}),n.jsx(ns,{label:"COMPONENTS",active:a==="components",count:x.length,onClick:()=>o("components")}),n.jsx("div",{className:"flex-1"}),n.jsx("input",{ref:u,value:l,onChange:g=>c(g.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(xm,{tab:a,hasQuery:l.trim().length>0}):y.map(g=>n.jsx(gm,{group:g,currentSlug:t,onSelect:w=>{r(w),s()}},g.route))})]})}function bm(){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 ym(){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 Ea({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 wm({currentScenario:e,isOpen:t,onClick:r}){const s=e?Jn(e):!1,a=(e==null?void 0:e.screenshotPaths[0])??null,o=e?s?e.componentName??e.name:Ca(e)??e.url??e.name:"Select a page";return n.jsxs("button",{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:o,"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:a?n.jsx("img",{src:Fe(a),alt:"",className:"w-full h-full object-cover"}):s?n.jsx(ym,{}):n.jsx(bm,{})}),n.jsx(Ea,{})]}),n.jsx("span",{className:"truncate",children:o})]})}function jm(e,t){const r=e.url??"Uncategorized",s=t.find(a=>a.route===r);return(s==null?void 0:s.scenarios)??[e]}function Nm({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:Fe(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:dr(e)})]})}function Cm({currentScenario:e,scenarioGroups:t,onSelect:r,onCreateNew:s,onClose:a}){const o=i.useRef(null);ka(o,a);const l=i.useMemo(()=>jm(e,t),[e,t]);return n.jsxs("div",{ref:o,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:l.map(c=>n.jsx(Nm,{scenario:c,active:c.slug===e.slug,onClick:()=>{r(c.slug),a()}},c.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 Sm({label:e,disabled:t,isOpen:r,onClick:s}){return n.jsxs("button",{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(Ea,{className:"opacity-70 shrink-0"})]})}function km({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(Cf,{name:e.name})})}function Em({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:x,scenarioGroups:j,onShowScenarioPreview:y,onCreateStateRequest:g}){const[w,v]=i.useState(!1),[h,b]=i.useState(!1),[N,k]=i.useState(!1),S=d&&f?Math.round(f):s,C=d&&p?Math.round(p):a,D=x?dr(x):"No state",R=!x;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:n.jsx(Kp,{isCollapsed:l,onToggle:c})}),n.jsxs("div",{className:"flex items-center gap-2 justify-self-center",children:[n.jsxs("div",{className:"relative flex items-center bg-[#3a3a3a] rounded h-7 px-1 gap-1",children:[n.jsx(wm,{currentScenario:x,isOpen:w,onClick:()=>{v(E=>!E),b(!1),k(!1)}}),w&&n.jsx(vm,{scenarioGroups:j,currentSlug:(x==null?void 0:x.slug)??null,onSelect:y,onClose:()=>v(!1)}),n.jsx("span",{className:"w-px h-5 bg-[#555] mx-1 shrink-0","aria-hidden":"true"}),e.map(E=>n.jsx(km,{viewport:E,isActive:!d&&t===E.name,onSelect:()=>{d&&u(),r(E.name)}},E.name)),n.jsx(fm,{isFilled:d,onToggle:u}),n.jsx(es,{label:"H",value:C,disabled:d,onCommit:E=>m(s,E)}),n.jsx(es,{label:"W",value:S,disabled:d,onCommit:E=>m(E,a)}),n.jsx(pm,{previewUrl:o})]}),n.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[n.jsxs("div",{className:"relative",children:[n.jsx(Sm,{label:D,disabled:R,isOpen:h,onClick:()=>{b(E=>!E),v(!1),k(!1)}}),h&&x&&n.jsx(Cm,{currentScenario:x,scenarioGroups:j,onSelect:y,onCreateNew:g,onClose:()=>b(!1)})]}),n.jsxs("div",{className:"relative",children:[n.jsx(Yp,{isOpen:N,disabled:!x,onClick:()=>{k(E=>!E),v(!1),b(!1)}}),N&&x&&n.jsx(um,{slug:x.slug,scenarioName:x.name,onClose:()=>k(!1)})]})]})]}),n.jsx("div",{"aria-hidden":"true"})]})}function Rm(){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 Tm({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})}function Dm({prompt:e}){return n.jsxs("section",{"aria-label":"What you asked for",style:{border:"1px solid var(--border-subtle)",borderRadius:"8px",padding:"1rem 1.25rem",marginBottom:"1.5rem",background:"var(--bg-elevated)"},children:[n.jsx("div",{style:{fontSize:"0.75rem",fontWeight:600,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.05em",marginBottom:"0.5rem"},children:"What you asked for"}),n.jsx(ot,{children:e})]})}function Pm(){return n.jsxs("footer",{style:{color:"var(--text-muted)",fontSize:"0.8125rem"},children:["Open the ",n.jsx("strong",{children:"Build"})," tab to follow along step by step."]})}function Am(){return n.jsxs("header",{style:{marginBottom:"1.5rem"},children:[n.jsx("h1",{style:{fontSize:"1.5rem",fontWeight:600,color:"var(--text-primary)",margin:"0 0 0.5rem 0"},children:"Setting up your project"}),n.jsx("p",{style:{margin:0,color:"var(--text-muted)",fontSize:"0.875rem"},children:"Hold tight — your app is being built. This usually takes a few minutes."})]})}function Lm(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 Mm={complete:"✓",active:"●",pending:"○"},Im={complete:"var(--accent-green, #16a34a)",active:"var(--accent-blue, #2563eb)",pending:"var(--text-muted)"};function Om({phase:e,status:t,activeStepLabel:r}){const s=t==="pending"?"var(--text-muted)":"var(--text-primary)";return n.jsxs("li",{"data-phase-id":e.phaseId,"data-phase-status":t,style:{display:"flex",alignItems:"flex-start",gap:"0.75rem"},children:[n.jsx("span",{"aria-hidden":"true",style:{width:"1.25rem",flexShrink:0,color:Im[t],fontSize:"1rem",lineHeight:"1.4",textAlign:"center"},children:Mm[t]}),n.jsxs("div",{style:{flex:1,minWidth:0},children:[n.jsx("div",{style:{color:s,fontSize:"0.9375rem",fontWeight:t==="active"?600:400},children:e.phaseLabel}),t==="active"&&r?n.jsxs("div",{style:{marginTop:"0.25rem",color:"var(--text-secondary)",fontSize:"0.8125rem"},children:["Now: ",r]}):null]})]})}function Fm({currentStep:e,mode:t}){const r=el(t),s=Zi(e,t)||null;return n.jsx("section",{"aria-label":"Progress",style:{marginBottom:"1.5rem"},children:n.jsx("ol",{style:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:"0.75rem"},children:r.map(a=>{const o=Lm(a,e);return n.jsx(Om,{phase:a,status:o,activeStepLabel:o==="active"?s:null},a.phaseId)})})})}function Bm(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(`
|
|
18
|
+
`)&&(t=t.slice(0,-1)),t}function $m({prompt:e,currentStep:t,mode:r}){return n.jsxs(n.Fragment,{children:[n.jsx(Am,{}),n.jsx(Dm,{prompt:Bm(e)}),n.jsx(Fm,{currentStep:t,mode:r}),n.jsx(Pm,{})]})}const rs={prompt:null,title:null};function Hm(){const[e,t]=i.useState(rs),[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(rs)}finally{a||s(!1)}})(),()=>{a=!0}},[]),{...e,loading:r}}function _m(){const{prompt:e,title:t,loading:r}=Hm(),{stepState:s}=kt();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?t?n.jsxs(n.Fragment,{children:[n.jsx(Tm,{title:t}),n.jsx(ot,{children:e})]}):n.jsx($m,{prompt:e,currentStep:(s==null?void 0:s.step)??1,mode:(s==null?void 0:s.mode)??"ui"}):n.jsx(Rm,{})})})}function zm({message:e}){return n.jsx("span",{style:{color:"var(--text-dim)"},children:e})}function Wm(e,t,r){const s=[e];return t&&s.push(`reload:${t}`),r&&s.push(`command:${r}`),s.join("::")}function Vm({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 Um=i.forwardRef(function({currentHeight:t,currentWidth:r,isFilled:s,previewUrl:a,scale:o,reloadNonce:l,commandNonce:c,onLoad:d,onError:u},f){if(it())return n.jsx(Vm,{currentWidth:r,currentHeight:t,isFilled:s,scale:o});const p=Wm(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 Km(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 Ym(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 Gm(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?l(f=>f+1):s.current==null&&a.current&&t&&Qr(e,c.current),s.current=e)},[e,t]);const d=i.useCallback(f=>{a.current=!0,f&&(c.current=f),t&&e!=null&&Qr(e,f??c.current)},[e,t]),u=i.useCallback(f=>{t&&mp(f)},[t]);return{reloadNonce:o,handleIframeLoad:d,handleIframeError:u}}const Jm=500,Xm=2e3,qm=1e3,Qm=2;function Zm(){return typeof window>"u"?!1:window.location.pathname.startsWith("/scenario/")?!0:it()}function ex(e){const t=Zm(),[r,s]=i.useState(t?!0:null),[a,o]=i.useState(null),[l,c]=i.useState(0),[d,u]=i.useState(0),f=i.useRef(null),p=i.useRef(null),m=i.useRef(null),x=i.useRef(!1),j=i.useRef(e);i.useEffect(()=>{j.current=e},[e]);const y=i.useCallback(()=>{p.current!=null&&(clearTimeout(p.current),p.current=null)},[]),g=i.useCallback(async()=>{if(x.current)return;const h=j.current;if(!h)return;m.current&&m.current.abort();const b=new AbortController;m.current=b;const N=setTimeout(()=>b.abort(),qm);let k=!1;try{await fetch(h,{mode:"no-cors",cache:"no-store",signal:b.signal}),k=!0}catch{k=!1}finally{clearTimeout(N)}if(!x.current){if(o(Date.now()),k){if(c(0),f.current!==!0){const S=f.current===!1;f.current=!0,s(!0),S&&u(C=>C+1)}}else c(S=>{const C=S+1;return C>=Qm&&f.current!==!1&&(f.current=!1,s(!1)),C});w()}},[]),w=i.useCallback(()=>{if(x.current)return;y();const h=f.current===!0?Xm:Jm;p.current=setTimeout(()=>{p.current=null,g()},h)},[y,g]),v=i.useCallback(()=>{y(),g()},[y,g]);return i.useEffect(()=>{if(!t)return x.current=!1,g(),()=>{x.current=!0,y(),m.current&&(m.current.abort(),m.current=null)}},[g,y,t]),i.useEffect(()=>{t||g()},[e,g,t]),{healthy:r,lastProbeAt:a,failedProbeCount:l,reloadNonce:d,invalidate:v}}const _t={windowMs:1e4,threshold:4,ringBufferSize:16};function tx({pidNonce:e,probeNonce:t,draftNonce:r,windowMs:s=_t.windowMs,threshold:a=_t.threshold}){const[o,l]=i.useState(!1),[c,d]=i.useState([]),[u,f]=i.useState(0),p=i.useRef(!1),m=i.useRef(e),x=i.useRef(t),j=i.useRef(r),y=i.useCallback(w=>{const v=Date.now(),h=v-s;let b=[];d(k=>{const S=k.filter(C=>C.timestampMs>=h);return S.push({reason:w,timestampMs:v}),S.length>_t.ringBufferSize&&S.splice(0,S.length-_t.ringBufferSize),b=S,S});const N=b.filter(k=>k.timestampMs>=h).length;if(!p.current&&N>=a){p.current=!0,l(!0);return}p.current||f(k=>k+1)},[s,a]);i.useEffect(()=>{e!==m.current&&(m.current=e,y("pid"))},[e,y]),i.useEffect(()=>{t!==x.current&&(x.current=t,y("probe"))},[t,y]),i.useEffect(()=>{r!==j.current&&(j.current=r,y("draft"))},[r,y]);const g=i.useCallback(()=>{p.current=!1,l(!1),d([]),f(w=>w+1)},[]);return{tripped:o,recentReloads:c,gatedNonce:u,reset:g}}const ss=20,nx="codeyam-error-capture";function rx(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!==nx)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(x=>x.dedupeKey===u.dedupeKey);if(p>=0){const x=f.slice();return x[p]={...x[p],count:x[p].count+1,timestampMs:u.timestampMs},x}const m=[...f,{...u,count:1}];return m.length>ss?m.slice(m.length-ss):m})}return window.addEventListener("message",o),()=>window.removeEventListener("message",o)},[e]),{errors:r,clear:a}}const Sn=[500,1e3,2e3];async function sx(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 ax(){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 ox(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+Sn.length;let l=null;for(let d=0;d<o;d++){if(a)return;const{status:u}=await sx(e);if(a)return;if(l=u,u===null||u<500){s({status:u,clickThroughBroken:!1,logLines:[],loading:!1});return}d<Sn.length&&await new Promise(f=>setTimeout(f,Sn[d]))}const c=await ax();a||s({status:l,clickThroughBroken:!0,logLines:c,loading:!1})})(),()=>{a=!0}},[e,t]),r}function ix({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(`
|
|
19
|
+
`):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 lx(e){if(e===null||!e.startCommand)return{isRestarting:!1,isFailed:!1,isStarting:!1,isStopped:!1};const t=e.status!=="running"&&e.intendedRunning,r=t&&(e.restartCount??0)>2,s=e.intendedRunning&&e.status!=="running"&&(e.restartCount??0)===0,a=e.status==="stopped"&&!e.intendedRunning;return{isRestarting:t,isFailed:r,isStarting:s,isStopped:a}}function cx(e){const{hasDevServerConfigured:t,probeHealthy:r,backendRunning:s,backendIframeHealthy:a,isStarting:o,isRestarting:l,isFailed:c,isStopped:d,isPrePrototype:u}=e;return!t||r===!0&&(s&&a!==!1)?null:c?"crashed":u?"scaffolding":d?"stopped":l?"restarting":o?"starting":r===!1||a===!1?"reconnecting":r===null?"probing":"reconnecting"}function dx(e){return e===null||e.status!=="running"?!1:e.liveIframeHealthy!==!1}const ux=5,fx=3;function px(e,t){return e===null||e<=0?!1:e<=(t==="backend"?fx:ux)}const as="Setting up your project",os="Preparing your project — the preview will appear once it's ready.",mx={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."},xx={1:"Aligning on the plan with you.",2:"Aligning on the plan with you.",3:"Preparing the project environment."};function hx(e,t){return e===null?{title:as,body:os}:{title:as,body:(t==="backend"?xx:mx)[e]??os}}function gx({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 vx={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},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 bx({variant:e,restartCount:t=0,showRetry:r=!1,onRetry:s,bodyOverride:a}){const{title:o,body:l,spinner:c}=vx[e],d=a??l;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(gx,{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})]}),r&&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:"Retry now"})]})})}function yx(e){return e.slice().reverse().map(t=>{const r=t.filename!=null?`
|
|
20
|
+
at ${t.filename}${t.lineno!=null?`:${t.lineno}`:""}${t.colno!=null?`:${t.colno}`:""}`:"",s=t.stack?`
|
|
21
|
+
${t.stack}`:"",a=t.count>1?` (×${t.count})`:"";return`[${t.type}]${a} ${t.message}${r}${s}`}).join(`
|
|
22
|
+
|
|
23
|
+
`)}function wx(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(", ")}async function jx(e){try{if(typeof navigator<"u"&&navigator.clipboard&&typeof navigator.clipboard.writeText=="function")return await navigator.clipboard.writeText(e),!0}catch{}return!1}function Nx({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 Cx({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 Sx({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 kx({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(Sx,{error:a,expanded:r===a.dedupeKey,onToggle:()=>s(r===a.dedupeKey?null:a.dedupeKey)},a.dedupeKey))})}function Ex({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 Rx=`Fix this error in the live preview. Here is what the captured runtime error reported:
|
|
24
|
+
|
|
25
|
+
`;function Tx({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(()=>yx(t),[t]),p=i.useMemo(()=>wx(r),[r]);if(i.useEffect(()=>{t.length===0&&u(!0)},[t.length]),!e&&t.length===0)return null;const m=s&&!e,x=m&&d&&t.length>0,j=e?`Live Preview paused — ${t.length} error${t.length===1?"":"s"} captured`:`${t.length} runtime error${t.length===1?"":"s"} captured`;async function y(g){const w=await jx(g+f);c(w?"copied":"failed"),setTimeout(()=>c("idle"),1500)}return x?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(Nx,{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(Cx,{headline:j,tripped:e,onClear:m?()=>u(!0):o,closeAriaLabel:m?"Minimize errors":"Dismiss errors"}),n.jsx(kx,{errors:t,emptyHint:e?`Breaker tripped before any runtime error was reported. Reasons in window: ${p}.`:null}),n.jsx(Ex,{canCopy:t.length>0,reasonsSummary:p,copyState:l,onCopy:()=>y(""),onCopyForClaude:()=>y(Rx),onRetry:a})]})})}function Dx(){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 Px({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 Ax({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}=To({writer:s});return n.jsx("button",{type:"button",onClick:()=>{l(e)},disabled:e.length===0,className:a,children:o?r:t})}function Lx(){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 Mx({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(Lx,{}),n.jsx(Ax,{text:e.join(`
|
|
26
|
+
`),label:"Copy logs",writer:t})]})})}function Ix({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(Dx,{}),n.jsx(Px,{logs:e}),n.jsx(Mx,{logs:e})]})}const is=48,Ox=100,Fx=320,Bx=192;function $x({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:Fx,height:Bx,hasViewport:!1};const o=t-is*2,l=e-is*2-Ox,c=Math.min(1,o/s,l/r);return{width:Math.round(s*c),height:Math.round(r*c),hasViewport:!0}}function Hx({containerHeight:e,containerWidth:t,onDismiss:r,scenarioName:s,screenshotPath:a,viewportHeight:o,viewportWidth:l}){const{width:c,height:d,hasViewport:u}=$x({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(pa,{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 _x({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 zx(){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 Wx({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 Vx({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 Ux({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(Vx,{ancestors:e,onOpenInEditor:t})]})}function Kx({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 Yx({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:x,onClose:j}){const y=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(Kx,{propsNames:f}),n.jsx(Ux,{ancestors:u,onOpenInEditor:p}),n.jsx("textarea",{value:o,onChange:g=>l(g.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:x,disabled:y,className:"px-3 py-1.5 rounded text-sm flex-1",style:{background:y?"var(--bg-deep)":"var(--accent-blue)",border:"none",color:y?"var(--text-secondary)":"#000",cursor:y?"not-allowed":"pointer",fontWeight:600},children:c?"Creating...":"Create Fix Plan"}),n.jsx("button",{onClick:j,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 Gx({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 Jx({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}=zx(),m=async()=>{d(!0);try{await a(o,e)}finally{d(!1)}},x=e.componentName??`<${e.element.tag}>`,j=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:y=>y.stopPropagation(),children:[n.jsx(Wx,{tag:e.element.tag,id:e.element.id,className:e.element.className,text:e.element.text,detectionMethod:e.detectionMethod,previewUrl:t}),n.jsx(Yx,{componentDisplay:x,sourceDisplay:j,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(Gx,{error:f,onDismiss:p})]})}function Xx(){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 qx({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(Xx,{})]})}function Qx(){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, #58a6ff)",borderRadius:4,boxSizing:"border-box"},children:n.jsx("div",{style:{position:"absolute",top:0,left:16,padding:"2px 8px",background:"var(--accent-blue, #58a6ff)",color:"#000",fontSize:10,fontWeight:700,fontFamily:"system-ui, -apple-system, sans-serif",borderRadius:"0 0 4px 4px",letterSpacing:.5},children:"INSPECT MODE"})})}function Zx(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 eh({onDismiss:e}){return n.jsx("div",{onClick:e,style:{position:"fixed",inset:0,zIndex:999998,background:"transparent"}})}function th({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 nh({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(th,{match:r,onOpen:t})},`${r.endpoint}${r.jsonPath}${s}`))})}function rh({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:sh(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(nh,{matches:t,onOpen:s})]})}function sh(e,t){return e.length<=t?e:e.slice(0,t-1)+"…"}function ah({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 ls=320,cs=320,oh=8;function ih({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}=Zx(r,{width:c,height:l},{width:ls,maxHeight:cs,gap:oh});return n.jsxs(n.Fragment,{children:[n.jsx(eh,{onDismiss:a}),n.jsxs("div",{style:{position:"fixed",top:d,left:u,width:ls,maxHeight:cs,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(ah,{onDismiss:a}),n.jsx(rh,{clickedText:e,matches:t,corpusEmpty:o,onOpenInPanel:s})]})]})}function lh({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 ds(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 ch(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 x=e.current;x!=null&&x.contentWindow&&x.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(x){!x.data||typeof x.data.type!="string"||(x.data.type==="codeyam:debug:hover"?a(ds(x.data.payload)):x.data.type==="codeyam:debug:selected"&&l(ds(x.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 dh=/^\/api\/mock-panel(\/.*)?$/;function uh(e,t){return e.toUpperCase()!=="GET"?!1:dh.test(t)}function fh(e){return Array.isArray(e)?e.filter(t=>t.consumedThisPageLoad&&!uh(t.method,t.pathPattern)).map(t=>({endpoint:`${t.method} ${t.pathPattern}`,body:t.body})):[]}async function ph(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 mh=12;function xh(e,t,r){if(t.length===0)return[];const s=[];return _n(e,t,r,"$",0,new Set,s),s}function hh(e,t){const r=[];for(const o of e)for(const l of xh(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 _n(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>=mh)&&!o.has(e)){if(o.add(e),Array.isArray(e))for(let d=0;d<e.length;d++)_n(e[d],t,r,`${s}[${d}]`,a+1,o,l);else if(c==="object")for(const[d,u]of Object.entries(e))_n(u,t,r,`${s}.${d}`,a+1,o,l);o.delete(e)}}const gh={backgroundColor:"#1e1e1e",backgroundImage:"conic-gradient(#262626 25%, #1e1e1e 0 50%, #262626 0 75%, #1e1e1e 0)",backgroundSize:"16px 16px"};function vh({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,scale:x,commandNonce:j}){const y=i.useRef(null),g=a??y,w=i.useRef(null),{status:v,restart:h}=Do();Km(v,h);const{isRestarting:b,isFailed:N,isStarting:k,isStopped:S}=lx(v),{stepState:C}=kt(),D=px((C==null?void 0:C.step)??null,(C==null?void 0:C.mode)??"ui"),R=(v==null?void 0:v.liveIframeHealthy)!==void 0,{reloadNonce:E,handleIframeLoad:V,handleIframeError:F}=Gm((v==null?void 0:v.pid)??null,R,v==null?void 0:v.status),{healthy:$,failedProbeCount:Y,reloadNonce:B,invalidate:T}=ex(m),[I,A]=i.useState(0);i.useEffect(()=>Po(()=>{A(fe=>fe+1)}),[]);const O=tx({pidNonce:E,probeNonce:B,draftNonce:I}),Q=O.gatedNonce,{errors:W,clear:H}=rx(w,Q),U=ox(m,Q),M=i.useCallback(()=>{O.reset(),H(),T()},[O,H,T]),L=cx({hasDevServerConfigured:!!(v!=null&&v.startCommand),probeHealthy:$,backendRunning:(v==null?void 0:v.status)==="running",backendIframeHealthy:v==null?void 0:v.liveIframeHealthy,isStarting:k,isRestarting:b,isFailed:N,isStopped:S,isPrePrototype:D}),G=L==="scaffolding"?hx((C==null?void 0:C.step)??null,(C==null?void 0:C.mode)??"ui").body:void 0,J=Y>=10,{isActive:ee,hoveredElement:_,selectedElement:P,activate:ne,deactivate:oe,clearSelection:re}=ch(w),te=i.useCallback(()=>{ee?oe():ne()},[ee,ne,oe]),{entries:q}=ws(p??null),{isActive:se,toggle:Ve}=Ym({activate:ne,deactivate:oe,clearSelection:re},E);i.useEffect(()=>(jr({isActive:se,previewSlug:p??null}),()=>{jr({isActive:!1,previewSlug:null})}),[se,p]),i.useEffect(()=>Ao(()=>{Ve()}),[Ve]);const Pe=se&&P?P.element.text.trim():"",he=i.useMemo(()=>fh(q),[q]),Be=i.useMemo(()=>!se||!Pe?[]:hh(he,Pe),[se,Pe,he]),ue=i.useCallback(async fe=>{re(),oe();try{const $e=await(await fetch("/api/scenarios")).json(),we=Array.isArray($e)?$e.find(K=>K.componentName===fe):null;if(we!=null&&we.slug){const K=ja(window.location),je=`/scenario/${we.slug}`,Ke=K===tn?je:`http://localhost:${tn}${je}`;window.history.pushState(null,"",Ke);return}}catch{}window.history.pushState(null,"","/entities")},[re,oe]),Qe=i.useCallback(async(fe,Ue)=>{try{await ph(fe,Ue,m),re(),oe()}catch($e){console.error("Failed to create debug plan:",$e)}},[m,re,oe]);return n.jsx("div",{ref:g,className:`relative flex-1 flex overflow-hidden ${u?"":"items-center justify-center p-8"}`,style:u?{backgroundColor:"#fff"}:gh,children:m?n.jsxs(n.Fragment,{children:[n.jsx(Um,{ref:w,currentHeight:l,currentWidth:c,isFilled:u,previewUrl:m,scale:x,reloadNonce:Q,onLoad:()=>V(m),onError:F}),n.jsx(lh,{healthy:v==null?void 0:v.liveIframeHealthy,reason:(v==null?void 0:v.iframeLastError)??null}),ee&&n.jsx(qx,{hoveredElement:_}),se&&n.jsx(Qx,{}),P&&!se&&n.jsx(Jx,{element:P,previewUrl:m,onClose:re,onGoToIsolated:ue,onCreatePlan:Qe}),P&&se&&n.jsx(ih,{clickedText:Pe,matches:Be,anchor:P.element.boundingBox,corpusEmpty:he.length===0,onOpenInPanel:fe=>{Lo({routeKey:fe.endpoint,jsonPath:fe.jsonPath}),re()},onDismiss:re}),!t&&n.jsx(_x,{isActive:ee,onToggle:te}),L&&(L==="crashed"?n.jsx(Ix,{logs:(v==null?void 0:v.logs)??[]}):n.jsx(bx,{variant:L,restartCount:(v==null?void 0:v.restartCount)??0,showRetry:J,onRetry:T,bodyOverride:G})),n.jsx(Tx,{tripped:O.tripped,errors:W,recentReloads:O.recentReloads,serverHealthy:dx(v),onRetry:M,onClear:H}),U.clickThroughBroken&&U.status!==null&&n.jsx(ix,{url:m,status:U.status,logLines:U.logLines,onRetry:M}),t&&f&&n.jsx(Hx,{containerHeight:s,containerWidth:o,onDismiss:f,scenarioName:e??null,screenshotPath:r??null,viewportHeight:l,viewportWidth:c})]}):n.jsx(zm,{message:d})})}function bh({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 yh(){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 wh({emptyStateMessage:e,previewSlug:t,previewUrl:r,viewports:s,activeViewport:a,onViewportChange:o,isCollapsed:l,onToggleCollapsed:c,isFilled:d,onToggleFilled:u,currentWidth:f,currentHeight:p,onCustomSizeChange:m,buildingScenarioSlug:x,buildingScreenshotPath:j,buildingScenarioName:y,onDismissBuildingOverlay:g,previewSeeding:w,previewSeedError:v,onRetrySeed:h,currentScenario:b,scenarioGroups:N,onShowScenarioPreview:k,commandNonce:S}){const[C,D]=i.useState(!1),{containerRef:R,containerSize:E,scale:V}=vp({currentHeight:p,currentWidth:f,isFilled:d});i.useEffect(()=>{it()||xp(v??null)},[v]);const F=r?cr(r):"",$=F==="/results"||F.startsWith("/results/");return F==="/plan-preview"?n.jsx(_m,{}):$?n.jsx(Vp,{}):n.jsxs("div",{"data-preview-pane":"true",className:"flex-1 flex flex-col min-w-0",children:[n.jsx(Em,{viewports:s,active:a,onChange:o,currentWidth:f,currentHeight:p,previewUrl:r,isCollapsed:l,onToggleCollapsed:c,isFilled:d,onToggleFilled:u,containerWidth:(E==null?void 0:E.width)??null,containerHeight:(E==null?void 0:E.height)??null,onCustomSizeChange:m,currentScenario:b??null,scenarioGroups:N??[],onShowScenarioPreview:k??(()=>{}),onCreateStateRequest:()=>D(!0)}),v?n.jsx(bh,{error:v,onRetry:h}):null,n.jsxs("div",{className:"relative flex-1 flex flex-col min-h-0",children:[n.jsx(vh,{containerRef:R,containerHeight:E==null?void 0:E.height,containerWidth:E==null?void 0:E.width,currentHeight:p,currentWidth:f,emptyStateMessage:e??"Select a scenario to preview",isFilled:d,previewSlug:t,previewUrl:r,scale:V,buildingScenarioSlug:x,buildingScreenshotPath:j,buildingScenarioName:y,onDismissBuildingOverlay:g,commandNonce:S}),w?n.jsx(yh,{}):null]}),C?n.jsx(Up,{onClose:()=>D(!1)}):null]})}function jh(){const[e,t]=i.useState([]),[r,s]=i.useState(!0),[a,o]=i.useState(null),{scenariosVersion:l}=ma(),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(Hs);t(Sa(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 Nh(){const[e,t]=i.useState([]),[r,s]=i.useState(!0),[a,o]=i.useState(null),l=i.useCallback(async()=>{s(!0),o(null);try{const c=await fetch("/api/app-route-entities");if(!c.ok)throw new Error(`HTTP ${c.status}`);const d=await c.json();t(Array.isArray(d)?d.map(u=>({...u,scenarios:Array.isArray(u==null?void 0:u.scenarios)?u.scenarios.map(Hs):[]})):[])}catch(c){o(c instanceof Error?c.message:"Failed to load app routes"),t([])}finally{s(!1)}},[]);return i.useEffect(()=>{l()},[l]),{routeEntities:e,loading:r,error:a,reload:l}}function us(e){const t=new Map;for(const r of e){const s=Ch(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 Ch(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 Ra(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 Ta(e,t,r){return r==="backend"?[]:e.map(s=>({...s,scenarios:s.scenarios.filter(qe)})).filter(s=>s.scenarios.length>0)}function Da(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 Sh(e){return e.reduce((t,r)=>t+r.scenarios.length,0)}const kh=3e3;function Eh(){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,x]=i.useState(null),[j,y]=i.useState(null),g=i.useRef(null),w=i.useRef(null),v=i.useRef(!1),h=i.useRef(null),b=i.useCallback(async(E=!1)=>{var Y;(Y=g.current)==null||Y.abort();const V=new AbortController;g.current=V;const{signal:F}=V;E&&(v.current=!0,o(!0));const $=!E&&h.current!==null;$||(s(!0),c(null));try{if(!E&&!$)try{const A=await fetch("/api/test-results/summary",{signal:F});if(A.ok){const O=await A.json();O.running?p(O.currentRunner??null):O.stats&&(x(O.stats),y(O.coverage??null))}}catch{}let B,T;if($){B=h.current;const A=await fetch("/api/test-results",{signal:F});if(!A.ok)throw new Error(`test-results: HTTP ${A.status}`);T=await A.json()}else if(E){const A=await fetch("/api/test-results/refresh",{method:"POST",signal:F});if(!A.ok)throw new Error(`test-results: HTTP ${A.status}`);T=await A.json(),B=h.current??[]}else{const[A,O]=await Promise.all([fetch("/api/tests",{signal:F}),fetch("/api/test-results",{signal:F})]);if(!A.ok)throw new Error(`tests: HTTP ${A.status}`);if(!O.ok)throw new Error(`test-results: HTTP ${O.status}`);B=us(await A.json()),T=await O.json(),h.current=B}if(p(T.currentRunner??null),T.running&&v.current){w.current=setTimeout(()=>b(!1),kh);return}const I=v.current;if(v.current=!1,I){const A=await fetch("/api/tests",{signal:F});A.ok&&(B=us(await A.json()),h.current=B)}t(B),u(T.cached??!1),y(T.coverage??null),x(null),s(!1),o(!1)}catch(B){if(B instanceof DOMException&&B.name==="AbortError")return;v.current=!1,c(B instanceof Error?B.message:"Failed to load tests"),s(!1),o(!1)}},[]);i.useEffect(()=>(b(),()=>{var E;(E=g.current)==null||E.abort(),w.current&&clearTimeout(w.current)}),[b]);const{total:N,passed:k,failed:S,ignored:C,discovered:D}=i.useMemo(()=>Da(e),[e]),R=i.useCallback(()=>{v.current||b(!0)},[b]);return{groups:e,loading:r,refreshing:a,error:l,cached:d,currentRunner:f,summaryStats:m,coverage:j,totalTests:N,passedTests:k,failedTests:S,ignoredTests:C,discoveredTests:D,reload:b,refresh:R}}function pr(e,t){return e.filter(r=>r.appDir===t)}function Pa(e,t){return t?e.find(r=>r.route===t)??null:null}function Aa(e,t,r){const s=Ta(e,t,r);return Dh(s)}function Rh(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=>zn(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 Th(e){return(e==null?void 0:e.defaultScenarioSlug)??null}function La(e,t){const r=e.find(s=>s.type==="web");return r?Aa(t,r.dir,r.type):null}function Dh(e){const t=e.flatMap(c=>c.scenarios.filter(d=>qe(d)).map(d=>({route:c.route,scenario:d})));if(t.length===0)return null;const r=t.find(({route:c,scenario:d})=>c==="/"&&zn(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})=>zn(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(qe(d)){o=d.slug,l=c.route.length;break}}return o}function zn(e){return/\bhome\b/i.test(e.name)}function fs(e){return new Set(e.flatMap(t=>t.scenarios.map(r=>r.slug)))}function kn({selectedApp:e,appRouteEntities:t,scenarioGroups:r}){return e?Rh(t)??Aa(r,e.dir,e.type):null}function Ph({apps:e,hasExplicitAppSelection:t,scenarioGroups:r}){return t||e.length===0||r.length===0?null:La(e,r)}function ps(e){return Th(e)}function Ah({apps:e,routeEntities:t,selectedApp:r,appRouteEntities:s}){if(r)return s;const a=e.find(o=>o.type==="web");return a?pr(t,a.dir):[]}function Lh({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 Mh({previewRouteEntities:e,path:t}){var s;const r=cr(t);return((s=Pa(e,r))==null?void 0:s.defaultScenarioSlug)??null}function Ih(e,t,r=""){const s=Cr(r),[a,o]=i.useState(s.selectedAppDir),[l,c]=i.useState(s.selectedEntityHash);i.useEffect(()=>{const w=Cr(r);o(v=>v===w.selectedAppDir?v:w.selectedAppDir),c(v=>v===w.selectedEntityHash?v:w.selectedEntityHash)},[r]);const d=i.useMemo(()=>l?t.find(w=>Tn(w)===l)??null:null,[t,l]),u=i.useMemo(()=>a?e.find(w=>w.dir===a)??null:d?e.find(w=>w.dir===d.appDir)??null:null,[e,a,d]),f=i.useMemo(()=>u?pr(t,u.dir):[],[t,u]),p=i.useMemo(()=>l?d:null,[l,d]);function m(w){if(typeof window>"u")return;const v=`${window.location.pathname}${window.location.search}`;w!==v&&window.history.pushState({},"",w)}function x(w){o(w),c(null),m(Sr(w))}function j(){o(null),c(null),m("/apps")}function y(w){const v=f.find(N=>N.route===w);if(!v)return;const h=Tn(v),b=ks(v);!h||!b||(c(h),m(b))}function g(){c(null),m(a?Sr(a):"/apps")}return{selectedApp:u,appRouteEntities:f,selectedRouteEntity:p,selectApp:x,deselectApp:j,selectRoute:y,deselectRoute:g}}function Oh(e,t,r,s,a=""){const[o,l]=i.useState(null),c=i.useRef(!1),d=i.useRef(!1),{selectedApp:u,appRouteEntities:f,selectedRouteEntity:p,selectApp:m,deselectApp:x,selectRoute:j,deselectRoute:y}=Ih(e,t,a),g=i.useMemo(()=>fs(f),[f]),w=i.useMemo(()=>fs(p?[p]:[]),[p]),v=i.useMemo(()=>kn({selectedApp:u,appRouteEntities:f,scenarioGroups:r}),[f,r,u]),h=i.useMemo(()=>ps(p),[p]),b=i.useMemo(()=>u?Ra(s,u.dir):[],[s,u]);i.useEffect(()=>{if(c.current)return;const R=Ph({apps:e,scenarioGroups:r,hasExplicitAppSelection:!!u});R&&(l(R),c.current=!0)},[e,r,u]),i.useEffect(()=>{if(u){if(d.current){d.current=!1;return}if(p){if(!h||o&&w.has(o))return;l(h);return}v&&(o&&g.has(o)||l(v))}},[v,h,o,u,g,p,w]);function N(R){m(R);const E=e.find(F=>F.dir===R);if(!E)return;const V=kn({selectedApp:E,appRouteEntities:pr(t,E.dir),scenarioGroups:r});l(V)}function k(){x(),l(La(e,r))}function S(R){j(R);const E=ps(Pa(f,R));l(E)}const C=i.useCallback(R=>{d.current=!0,l(R)},[]);function D(){if(y(),!u)return;const R=kn({selectedApp:u,appRouteEntities:f,scenarioGroups:r});R&&l(R)}return{selectedApp:u,appRouteEntities:f,appTestGroups:b,selectedRouteEntity:p,previewSlug:o,setPreviewSlug:l,setPreviewSlugExplicit:C,selectApp:N,deselectApp:k,selectRoute:S,deselectRoute:D}}const Fh=1e3;function Bh(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,Fh)}}return s(),()=>{r=!1}},[])}function $h(){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(()=>Jo(e),[e]);return{graph:e,entityLookup:l,loading:r,error:a}}const Hh=["/apps","/entities","/app","/build","/history","/settings","/plan"];function _h(e){if(!e)return!1;const t=cr(e);return Hh.some(r=>t===r||t.startsWith(`${r}/`))}function zh(e,t){const r=typeof window<"u"?ja(window.location):0;return nn(e)==="component"?pp(e.slug,r,e.url,t):e.url?Na(e.url,{appPort:t,currentPort:r}):""}function Wh(e,t){return e.startsWith("http")?e:e||`http://localhost:${t}/results`}function Vh(e,t){return e.startsWith("http")?e:e||`http://localhost:${t}/plan-preview`}function Ma(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 Uh({directPreviewPath:e,fallbackPreviewPath:t,previewKind:r,selectedScenario:s,port:a}){return r==="blank"?"":e&&(r==="application"||r==="results"||r==="plan-preview")?r==="results"?Wh(e,a):r==="plan-preview"?Vh(e,a):e.startsWith("http")?e:`http://localhost:${a}${e}`:s?zh({slug:s.slug,scenarioType:s.scenarioType,componentName:s.componentName,url:s.url},a):t?t.startsWith("http")?t:`http://localhost:${a}${t}`:""}function Kh(e,t=Date.now()){const r=e.includes("?")?"&":"?";return`${e}${r}_cb=${t}`}function Wn(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 Yh({apps:e,appRouteEntities:t,directPreviewPath:r,fallbackPort:s,previewKind:a,previewSlug:o,routeEntities:l,scenarioGroups:c,selectedApp:d,selectedRouteEntity:u}){const f=Ma(c,o),p=Ah({apps:e,routeEntities:l,selectedApp:d,appRouteEntities:t}),m=Lh({previewRouteEntities:p,selectedRouteEntity:u}),x=e.some(g=>g.type==="web");let j="blank";a==="plan-preview"&&r?j="plan-preview":a==="results"&&r?j="results":a==="application"&&r?j="application":f?j=qe(f)?"application":"component":m&&(j="application");const y=Uh({directPreviewPath:r,fallbackPreviewPath:m,previewKind:j,selectedScenario:f,port:s});return{selectedScenario:f,previewRouteEntities:p,fallbackPreviewPath:m,resolvedPreviewKind:j,basePreviewUrl:y,hasWebApp:x}}function Gh({allowEditorRoutePreview:e,command:t,configLoaded:r,previewRouteEntities:s,scenarioGroups:a,selectedScenario:o}){const l=t.dimension??null,c=!!t.dimension,d=t.commandNonce;if(t.scenarioSlug??t.scenarioId){const y=t.scenarioSlug??t.scenarioId,g=Ma(a,y);return g?{clearCustomSize:c,scenarioSlug:g.slug,type:"show-scenario",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:y,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",x=_h(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(x&&!e)return{clearCustomSize:c,type:r?"ignore":"defer",viewportName:l,commandNonce:d};if(x&&e)return{clearCustomSize:c,path:u,previewKind:"application",previewSlug:null,preserveDirectPreviewPathOnSlugChange:!0,type:"show-path",viewportName:l,commandNonce:d};const j=Mh({previewRouteEntities:s,path:u});return j?{clearCustomSize:c,scenarioSlug:j,type:"show-scenario",viewportName:l,commandNonce:d}:{clearCustomSize:c,path:u,previewKind:"application",previewSlug:!o||!qe(o)?null:void 0,preserveDirectPreviewPathOnSlugChange:!1,type:"show-path",viewportName:l,commandNonce:d}}function Jh(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 Xh=[{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 qh(e,t){const r=Object.entries(e);if(r.length===0)return Xh;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 Qh({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 Zh({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(Fc({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}}function eg({apps:e,appRouteEntities:t,configLoaded:r,defaultScreenSize:s,port:a,projectName:o,previewSlug:l,routeEntities:c,scenarioGroups:d,scenariosLoaded:u,screenSizes:f,selectedApp:p,selectedRouteEntity:m,setPreviewSlug:x}){const[j,y]=i.useState("Desktop"),[g,w]=i.useState(null),[v,h]=i.useState(null),[b,N]=i.useState(null),[k,S]=i.useState(null),[C,D]=i.useState(()=>Date.now()),[R,E]=i.useState(0),V=i.useRef(null),F=i.useRef(!1),$=i.useMemo(()=>qh(f,s),[s,f]),Y=i.useMemo(()=>g!==null&&v!==null?{name:"Custom",width:g,height:v}:$.find(te=>te.name===j)??$[0]??{name:"Desktop",width:1440,height:900},[j,v,g,$]),B=it(),T=o==="CodeYam Editor",{basePreviewUrl:I,fallbackPreviewPath:A,hasWebApp:O,previewRouteEntities:Q,resolvedPreviewKind:W,selectedScenario:H}=i.useMemo(()=>Yh({apps:e,appRouteEntities:t,directPreviewPath:b,fallbackPort:a,previewKind:k,previewSlug:l,routeEntities:c,scenarioGroups:d,selectedApp:p,selectedRouteEntity:m}),[e,t,b,a,k,l,c,d,p,m]),U=i.useMemo(()=>I?Kh(I,C):"",[I,C]),M=i.useCallback(te=>{y(te),w(null),h(null)},[]),L=i.useCallback((te,q)=>{w(te),h(q)},[]),G=i.useCallback(te=>{x(te),N(null),S(null),D(Date.now());const q=Wn(te,d);if(!q)return;const se=Jh(j,g,v,q,$);se!==null&&(y(se),w(null),h(null))},[j,v,g,d,x,$]),J=i.useCallback(te=>{const q=Gh({allowEditorRoutePreview:T,command:te,configLoaded:r,previewRouteEntities:Q,scenarioGroups:d,selectedScenario:H});if(q.viewportName&&y(q.viewportName),q.clearCustomSize&&(w(null),h(null)),q.type==="show-scenario"){G(q.scenarioSlug),E(se=>se+1);return}if(q.type==="defer"){V.current=te;return}if(q.type==="refresh"){D(Date.now()),E(se=>se+1);return}q.type!=="ignore"&&(q.type==="show-path"&&(S(q.previewKind),N(q.path),F.current=q.preserveDirectPreviewPathOnSlugChange,typeof q.previewSlug=="string"?x(q.previewSlug):q.previewSlug===null&&x(null)),D(Date.now()),E(se=>se+1))},[r,T,Q,d,H,x,G]);i.useEffect(()=>{if(!r)return;const te=V.current;te&&(V.current=null,J(te))},[r,J]),i.useEffect(()=>{if(!(!l||b===null)){if(F.current){F.current=!1;return}N(null),S(null),D(Date.now())}},[b,l]);const ee=i.useMemo(()=>W==="results"||W==="plan-preview"?b:W==="application"?b??(H==null?void 0:H.url)??A:null,[b,A,W,H==null?void 0:H.url]),_=i.useCallback(()=>{D(Date.now())},[]);Qh({isInIframe:B,persistedPath:ee,previewKind:W,resolvedViewport:Y,selectedScenario:H?{id:H.id??null,slug:H.slug}:null});const{seeding:P,seedError:ne}=Zh({isInIframe:B,onActivated:_,previewKind:W,scenariosLoaded:u,selectedScenario:H?{slug:H.slug,scenarioType:H.scenarioType,componentName:H.componentName??null}:null}),oe=O?"Select a scenario to preview":"No web app is available for Live Preview.",re=i.useCallback(te=>{N(te),S(te?"application":null),D(Date.now())},[]);return{viewports:$,resolvedViewport:Y,previewUrl:U,emptyStateMessage:oe,handleViewportChange:M,handleCustomSizeChange:L,showScenarioPreview:G,handlePreviewCommand:J,setPreviewPath:re,previewSeeding:P,previewSeedError:ne,commandNonce:R}}function tg(){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 ng(){const[e,t]=i.useState(!1),r=i.useCallback(()=>{t(!0)},[]),s=i.useCallback(()=>{t(!1)},[]);return{showPlanCompleteModal:e,onPlanCompleteCommand:r,dismissPlanCompleteModal:s}}function rg(){const{showBuildTab:e}=lr(typeof window>"u"?"/":window.location.pathname),{config:t}=yt(),[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 or()}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 ir({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 sg({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 ag(e,t,r){return e.map(s=>{const a=Ra(t,s.dir),o=Ta(r,s.dir,s.type),{total:l,passed:c,failed:d,ignored:u,discovered:f}=Da(a),p=Sh(o);return{app:s,tests:{total:l,passed:c,failed:d,ignored:u,discovered:f},scenarios:{total:p,thumbnails:og(o)}}})}function og(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 ig="No app configured yet — pick a tech stack and design system on the left to get started.";function lg({hasNoApps:e,hasStepState:t,defaultMessage:r}){return e&&!t?ig:r}function cg(e,t){return t?{scenarioSlug:e,path:t}:{scenarioSlug:e}}function dg(e){return e.activeTab==="build"&&!e.hasActiveSession&&!e.isAgentBuilding&&!e.showPostPushModal&&e.launchingPlanSlug===null&&!e.submittingBuildPrompt&&!e.stepStateFeature&&e.pendingPlanCount>0&&!e.buildLaunchModalDismissed}const ug=300,ms=150;function fg(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 y;if(!s.current)return;const m=((y=e.current)==null?void 0:y.getBoundingClientRect().left)??0,x=p.clientX-m,j=l();x<ms?r(0):x>j-ms?r(j):r(Math.max(ug,x))},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}}const pg=3e3;function mg({hot:e,isInIframe:t,reload:r=()=>window.location.reload(),sustainedDisconnectMs:s=pg}){return()=>{}}function xg(){i.useEffect(()=>mg({hot:void 0,isInIframe:it()}),[])}function En(e){window.dispatchEvent(new CustomEvent("miniagent-send-input",{detail:e}))}function xs(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 hs=800;async function hg(){En("\x1B"),await xs(hs),En("/clear\r"),await xs(hs),En("/codeyam-plan\r")}function gg(){fetch("/api/clear-build-agent-session",{method:"POST"}).catch(()=>{})}function vg(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){z("favicon-redraw",{idle:e,hasIcon:!1});return}if(t.current||(t.current=s.href),!e){s.href=t.current,z("favicon-restore",{});return}z("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 bg=120*1e3,Ia=1500;class yg{constructor(t,r,s=z){Le(this,"deferred",!1);Le(this,"userActiveSinceLastOutput",!1);Le(this,"lastActivitySource",null);Le(this,"lastActivityAt",null);Le(this,"lastNotificationTime",null);Le(this,"actions");Le(this,"env");Le(this,"now");Le(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<Ia;if(r&&s&&c)return this.userActiveSinceLastOutput=!1,this.log("suppressed-user-active",l),"suppressed";if(a!==null&&a<bg)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 wg(e,t){return new yg({playSound:Ms,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 jg(e,t){return e==="hook-stop"?t.idleOnStop:t.idleOnNotification}const Ng=600*1e3,Cg=3e3;function Sg({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,x]=i.useState(gl),[j,y]=i.useState(!1),g=i.useRef(!1);g.current=j;const w=i.useRef(!1),v=i.useRef(null),h=i.useRef(null),b=i.useRef(null),N=i.useRef(typeof document<"u"&&document.hidden?Date.now():null),k=i.useRef(null),S=i.useRef(s??!1);S.current=s??!1,vg(j),b.current||(b.current=wg(d,h));const C=i.useCallback(T=>{x(T),vl(T)},[]),D=i.useCallback(T=>{v.current!==null&&(clearTimeout(v.current),v.current=null,z("debounce-cancelled",{trigger:T}))},[]),R=i.useCallback(T=>{g.current&&z("idle-cleared",{trigger:T}),y(!1),g.current=!1,k.current=null,h.current&&(h.current.close(),h.current=null)},[]),E=i.useCallback(T=>{var I;if(!jg(T,m)){z("idle-suppressed-by-pref",{source:T});return}z("ws-idle-received",{buildTabActive:u.current,source:T}),(I=f.current)==null||I.call(f),D("re-arm-on-idle"),v.current=setTimeout(()=>{var W;v.current=null;const A=N.current,O=A===null?null:Date.now()-A,Q=A!==null&&Date.now()-A>Ng;z("debounce-resolved",{suppressedForOvernight:Q,msHidden:O,buildTabActive:u.current}),Q||(W=b.current)==null||W.onIdle(m,u.current),y(!0),g.current=!0,k.current=Date.now(),w.current=!1,z("agent-currently-idle-set",{suppressedForOvernight:Q}),u.current&&We()},Ia)},[m,D]),V=i.useCallback(()=>{var T,I,A;(T=p.current)==null||T.call(p),D("agent-active"),(I=b.current)==null||I.onActive(),(A=b.current)==null||A.resetActivityFlag(),g.current&&S.current&&k.current!==null&&Date.now()-k.current>Cg&&R("remote-resume")},[D,R]),F=i.useCallback(()=>{var T,I;D("user-input"),g.current&&((T=b.current)==null||T.onUserEngagement(),(I=b.current)==null||I.reportUserActivity("terminal-input"),w.current=!0,R("user-input"))},[D,R]),$=i.useCallback(T=>{var I;T==="build"&&(D("navigate-build"),g.current&&((I=b.current)==null||I.onUserEngagement(),w.current=!0,R("navigate-build"))),o(T)},[o,D,R]),Y=i.useCallback(()=>{var T;D("dismiss-banner"),(T=b.current)==null||T.onUserEngagement(),w.current=!0,R("dismiss-banner")},[D,R]);i.useEffect(()=>{function T(){var M;g.current&&(w.current||(D("ack-notification"),(M=b.current)==null||M.onUserEngagement(),w.current=!0,z("notification-acknowledged",{trigger:"user-return"})))}function I(M){var L;g.current&&u.current&&document.hasFocus()&&(document.hidden||((L=b.current)==null||L.onUserEngagement(),w.current=!0,R(M)))}function A(M){var L;document.hasFocus()&&T(),(L=b.current)==null||L.reportUserActivity(M)}const O=()=>A("mousemove"),Q=()=>A("mousedown"),W=()=>A("keydown");function H(){document.hidden?N.current===null&&(N.current=Date.now()):(N.current=null,T(),I("tab-visible-on-build"))}function U(){var M;T(),I("window-focus-on-build"),(M=b.current)==null||M.reportUserActivity("focus")}return window.addEventListener("focus",U),document.addEventListener("visibilitychange",H),document.addEventListener("mousemove",O),document.addEventListener("mousedown",Q),document.addEventListener("keydown",W),()=>{D("unmount"),window.removeEventListener("focus",U),document.removeEventListener("visibilitychange",H),document.removeEventListener("mousemove",O),document.removeEventListener("mousedown",Q),document.removeEventListener("keydown",W)}},[D,R]);const B=i.useRef(a??0);return i.useEffect(()=>{var A;const T=a??0;if(T===B.current)return;B.current=T;const I=u.current&&document.hasFocus();z("feature-complete-fast-path",{skipBecauseWatching:I}),!I&&((A=b.current)==null||A.onIdle(m,!1),y(!0),g.current=!0,k.current=Date.now(),w.current=!1)},[a,m]),i.useEffect(()=>{var T,I;if((T=b.current)==null||T.onBuildTabChange(t,m),t)return g.current&&typeof document<"u"&&document.hasFocus()&&!document.hidden&&((I=b.current)==null||I.onUserEngagement(),w.current=!0,R("build-tab-active-on-focus")),We()},[t,m,R]),{buildIdle:j,bannerVisible:j,notifSettings:m,handleSettingsChange:C,handleAgentIdle:E,handleAgentActive:V,handleUserInput:F,handleNavigateToTab:$,dismissIdleBanner:Y}}const kg=1e4;function Eg(e){const{isAgentBuilding:t,submittingBuildPrompt:r,launchingPlanSlug:s,hasActiveSession:a,sessionInfo:o,refetchSessionInfo:l}=e,[c,d]=i.useState(!1),u=i.useRef(!1),f=i.useCallback((p,m)=>{u.current!==p&&(z("build-session-live-change",{from:u.current,to:p,trigger:m}),u.current=p,d(p))},[]);return i.useEffect(()=>{t&&f(!0,"agent-active")},[t,f]),i.useEffect(()=>{r&&f(!0,"launch-prompt")},[r,f]),i.useEffect(()=>{s!==null&&f(!0,"launch-plan")},[s,f]),i.useEffect(()=>{a&&f(!0,"session-detected")},[a,f]),i.useEffect(()=>{o&&!o.hasSession&&f(!1,"session-ended")},[o,f]),i.useEffect(()=>{if(!c)return;const p=setInterval(()=>{l()},kg);return()=>clearInterval(p)},[c,l]),{buildSessionLive:c,transitionBuildSessionLive:f}}function gs(e){const{isAgentBuilding:t,trigger:r,transitionBuildSessionLive:s}=e;if(t){z("build-session-live-suppress-clear",{trigger:r,reason:"agent-still-active"});return}s(!1,r)}function Rg(){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
|
|
27
|
+
|
|
28
|
+
${a.trim()}
|
|
29
|
+
|
|
30
|
+
${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 Tg(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(`
|
|
31
|
+
|
|
32
|
+
`));return`mailto:${r}?subject=${s}&body=${a}`}const Dg=["bug","suggestion","question","praise"];function Pg({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}=Rg(),m=i.useCallback(()=>{p(r)},[p,r]),x=i.useCallback(()=>{navigator.clipboard.writeText("feedback@codeyam.com").then(()=>{c(!0),setTimeout(()=>c(!1),2e3)})},[]),j=i.useCallback(y=>{o(g=>g===y?null:y)},[]);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:Dg.map(y=>{const g=a===y;return n.jsx("button",{type:"button","aria-pressed":g,onClick:()=>j(y),className:"px-2.5 py-1 rounded-full text-xs transition cursor-pointer",style:{background:g?"var(--accent-active)":"transparent",color:g?"var(--bg-deep)":"var(--text-secondary)",border:"1px solid var(--border-default)"},children:y},y)})})]}),n.jsx("textarea",{value:r,onChange:y=>s(y.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:Tg(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:x,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 Ag(){var yr;xg();const e=$o(),{activeTab:t,buildActivated:r,planActivated:s,navigateToTab:a,showBuildTab:o}=lr(e),[l,c]=i.useState(!1),[d,u]=i.useState(!1),[f,p]=i.useState(0),[m,x]=i.useState(0),[j,y]=i.useState(0),{showPostPushModal:g,onFeatureCompleteCommand:w,onAgentIdle:v,onAgentActive:h,dismissModal:b}=tg(),{showPlanCompleteModal:N,onPlanCompleteCommand:k,dismissPlanCompleteModal:S}=ng(),[C,D]=i.useState(!1),[R,E]=i.useState(!1),[V,F]=i.useState(!1),$=i.useCallback(()=>{F(!0)},[]),Y=i.useCallback(()=>{F(!1)},[]),{plans:B,loading:T,error:I,refetch:A}=xa(),{reorderPlans:O}=wa(A),{launchPlan:Q,launchingSlug:W,error:H}=ya(),{launchPrompt:U,launching:M,error:L}=rg(),{sessionInfo:G,refetch:J}=fa(),[ee,_]=i.useState(!1),{stepState:P}=kt(),ne=i.useRef(null),{leftWidth:oe,handleMouseDown:re}=fg(ne),{entityLookup:te}=$h(),{groups:q,loading:se,refreshing:Ve,currentRunner:Pe,coverage:he,refresh:Be}=Eh(),{groups:ue,loading:Qe,reload:fe}=jh(),{routeEntities:Ue,loading:$e,error:we}=Nh(),{config:K,apps:je,loading:Ke}=yt(),Re=i.useMemo(()=>ag(je,q,ue),[je,ue,q]),Et=i.useCallback(()=>{c(Z=>!Z)},[]),ln=i.useCallback(()=>{u(Z=>!Z)},[]),{selectedApp:Rt,appRouteEntities:Ze,appTestGroups:Tt,selectedRouteEntity:Dt,previewSlug:Oe,setPreviewSlugExplicit:cn,selectApp:dn,deselectApp:un,selectRoute:ce,deselectRoute:pe}=Oh(je,Ue,ue,q,e),{viewports:me,resolvedViewport:Ne,previewUrl:ge,emptyStateMessage:xe,handleViewportChange:Ce,handleCustomSizeChange:He,showScenarioPreview:ae,handlePreviewCommand:ie,setPreviewPath:Se,previewSeeding:Te,previewSeedError:Ye,commandNonce:Ge}=eg({apps:je,appRouteEntities:Ze,configLoaded:!Ke,port:(K==null?void 0:K.port)??5173,projectName:(K==null?void 0:K.projectName)??null,routeEntities:Ue,screenSizes:(K==null?void 0:K.screenSizes)??{},defaultScreenSize:(K==null?void 0:K.defaultScreenSize)??null,scenarioGroups:ue,scenariosLoaded:!Qe,selectedApp:Rt,selectedRouteEntity:Dt,previewSlug:Oe,setPreviewSlug:cn}),{isAgentBuilding:ve,isAgentBuildingRef:_e,buildingScenarioSlug:Je,onAgentIdle:mr,onAgentActive:xr,guardScenarioSelect:hr,clearBuildingOverlay:et}=sg({onTransitionToLive:ae}),Pt=(G==null?void 0:G.resumeMode)==="resume"||(G==null?void 0:G.resumeMode)==="handoff",{buildSessionLive:gr,transitionBuildSessionLive:fn}=Eg({isAgentBuilding:ve,submittingBuildPrompt:M,launchingPlanSlug:W,hasActiveSession:Pt,sessionInfo:G,refetchSessionInfo:J});i.useEffect(()=>{ba({hasActiveSession:Pt,isAgentBuilding:ve,stepStateFeature:(P==null?void 0:P.feature)??null})},[Pt,ve,P==null?void 0:P.feature]),i.useEffect(()=>{const Z=K==null?void 0:K.projectName;document.title=typeof Z=="string"&&Z.length>0?`CodeYam: ${Z}`:"CodeYam"},[K==null?void 0:K.projectName]);const Oa=i.useCallback(()=>{v(),mr()},[v,mr]),Fa=i.useCallback(()=>{h(),xr()},[h,xr]),At=(K==null?void 0:K.provider)??Mo,Ba=Vt(At),{buildIdle:$a,bannerVisible:Ha,notifSettings:_a,handleSettingsChange:za,handleAgentIdle:Wa,handleAgentActive:Va,handleUserInput:Ua,handleNavigateToTab:Ka,dismissIdleBanner:Ya}=Sg({agentName:Ba,isBuildTabActive:t==="build",isAgentBuilding:ve,buildSessionLive:gr,featureCompleteKey:j,navigateToTab:a,onAgentIdleImmediate:Oa,onAgentActiveImmediate:Fa}),vr=i.useCallback(Z=>{hr(Z)||ae(Z)},[hr,ae]),tt=i.useMemo(()=>Wn(Je,ue),[Je,ue]),Ga=((yr=tt==null?void 0:tt.screenshotPaths)==null?void 0:yr[0])??null,Ja=(tt==null?void 0:tt.name)??null,Xa=i.useCallback(Z=>{switch(Z.type){case"preview":("scenarioSlug"in Z||"scenarioId"in Z)&&fe(),ie(Z);break;case"showResults":et(),fe(),p(Ae=>Ae+1),(P==null?void 0:P.mode)==="backend"&&ie({path:"/results",dimension:"Desktop"});break;case"hideResults":x(Ae=>Ae+1);break;case"featureComplete":et(),w(),y(Ae=>Ae+1),gs({isAgentBuilding:_e.current,trigger:"feature-complete",transitionBuildSessionLive:fn});break;case"planComplete":k(),gs({isAgentBuilding:_e.current,trigger:"plan-complete",transitionBuildSessionLive:fn});break}},[et,ie,w,k,fe,P,fn]);Bh(Xa);const Lt=(P==null?void 0:P.slug)==="ui-confirm-plan"||(P==null?void 0:P.slug)==="backend-confirm-plan",pn=i.useRef(null);i.useEffect(()=>{if(!P||!Lt){pn.current=null;return}pn.current!==P.step&&(pn.current=P.step,ie({path:"/plan-preview",dimension:"Desktop"}))},[P,Lt,ie]);const mn=i.useRef(null);i.useEffect(()=>{if(!P||P.mode!=="backend"||P.step<2||Lt){mn.current=null;return}mn.current!==P.step&&(mn.current=P.step,ie({path:"/results",dimension:"Desktop"}))},[P,Lt,ie]);const qa=i.useCallback(async()=>{b(),await Hf({provider:At,renameLabel:(P==null?void 0:P.feature)??void 0,caller:"post-push-modal",bypassLiveGuard:!0}),We()},[b,At,P]),Qa=i.useCallback(()=>{b(),We()},[b]),Za=i.useCallback(()=>{hg(),S(),We()},[S]),eo=i.useCallback(()=>{D(!1),gg(),S()},[S]),to=i.useCallback(()=>{E(!0)},[]),no=i.useCallback(()=>{E(!1)},[]),ro=i.useCallback(async(Z,Ae)=>{await Q(Z,Ae)&&(E(!1),_(!0),b(),J())},[Q,b,J]),so=i.useCallback(async Z=>{await U(Z)&&(_(!0),J())},[U,J]),ao=i.useCallback(()=>{_(!0)},[]),br=dg({activeTab:t,hasActiveSession:Pt,isAgentBuilding:ve,showPostPushModal:g,launchingPlanSlug:W,submittingBuildPrompt:M,stepStateFeature:(P==null?void 0:P.feature)??null,pendingPlanCount:B.length,buildLaunchModalDismissed:ee}),oo=br||R;i.useEffect(()=>{t==="build"&&J()},[t,J]);const io=i.useCallback(async(Z,Ae)=>{et(),ie(cg(Z,Ae))},[et,ie]),lo=i.useCallback(Z=>{(Z.scenarioSlug||Z.path)&&ie({...Z.scenarioSlug?{scenarioSlug:Z.scenarioSlug}:{},...Z.path?{path:Z.path}:{},...Z.dimension?{dimension:Z.dimension}:{}})},[ie]),co=n.jsx(Af,{selectedApp:Rt,appDetailProps:{routeEntities:Ze,routesLoading:$e,routesError:we,selectedRouteEntity:Dt,testGroups:Tt,selectedSlug:Oe,entityLookup:te,allScenarios:ue.flatMap(Z=>Z.scenarios),onSelectScenario:vr,onSelectRoute:ce,onBackToRoutes:pe,onBack:un,onScenariosChanged:fe},appOverviewProps:{projectTitle:(K==null?void 0:K.projectName)??"Project",projectDescription:(K==null?void 0:K.projectDescription)??null,stats:Re,coverage:he,onSelectApp:dn,configLoading:Ke,testsLoading:se,testsRefreshing:Ve,onRunTests:Be,currentRunner:Pe,stepState:P,onPreviewUrl:Se,onComplete:()=>a("build"),onOpenBuildTab:()=>a("build")}});return n.jsxs(n.Fragment,{children:[n.jsx(If,{splitRef:ne,isCollapsed:l,onResizeStart:re,leftPane:n.jsx(fp,{activeTab:t,onSendTranscript:$,appTabContent:co,awaitingPlanLaunchChoice:oo,buildActivated:r,planActivated:s,buildIdle:$a,isAgentBuilding:gr,bannerVisible:Ha,onDismissIdleBanner:Ya,hideResultsCommandKey:m,leftWidth:oe,navigateToTab:Ka,onAgentActive:Va,onAgentIdle:Wa,onUserInput:Ua,notifSettings:_a,onSettingsChange:za,provider:At,onRestorePreview:lo,onResultsScenarioSelect:io,onSessionDetected:o,showPostPushModal:g,onStartNextFeature:qa,onContinueInSession:Qa,showResultsCommandKey:f,planChatOpen:C,onPlanChatOpenChange:D,showPlanCompleteModal:N,onCreateNewPlan:Za,onViewPlans:eo,pendingPlans:B,onSelectPlan:to,selectPlanOpen:R,onPickPlan:ro,onCancelSelectPlan:no,launchingPlanSlug:W,planLaunchError:H,showBuildLaunchModal:br,onSubmitBuildPrompt:so,submittingBuildPrompt:M,buildPromptError:L,onCancelBuildLaunchModal:ao,pendingPlansLoading:T,pendingPlansError:I,onReorderPlans:O}),previewPane:n.jsx(wh,{emptyStateMessage:lg({hasNoApps:Re.length===0,hasStepState:!!P,defaultMessage:xe}),previewSlug:Oe,previewUrl:ge,viewports:me,activeViewport:Ne.name,onViewportChange:Ce,isCollapsed:l,onToggleCollapsed:Et,isFilled:d,onToggleFilled:ln,currentWidth:Ne.width,currentHeight:Ne.height,onCustomSizeChange:He,buildingScenarioSlug:Je,buildingScreenshotPath:Ga,buildingScenarioName:Ja,onDismissBuildingOverlay:et,previewSeeding:Te,previewSeedError:Ye,onRetrySeed:()=>{Oe&&ae(Oe)},currentScenario:Wn(Oe,ue),scenarioGroups:ue,onShowScenarioPreview:vr,commandNonce:Ge})}),V?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(Pg,{featureName:(P==null?void 0:P.feature)??null,onClose:Y})}):null]})}const _g=Object.freeze(Object.defineProperty({__proto__:null,EditorShell:Ag},Symbol.toStringTag,{value:"Module"}));export{Lx as $,gi as A,xi as B,Rs as C,fi as D,Ef as E,mi as F,pa as G,bi as H,nh as I,Ti as J,Ri as K,Ei as L,kf as M,Yt as N,Sx as O,Nx as P,kx as Q,gx as R,Hi as S,Bi as T,Ex as U,Cx as V,Tx as W,bx as X,Ix as Y,Px as Z,Dx as _,ai as a,$c as a$,Mx as a0,Ax as a1,Il as a2,Ml as a3,Al as a4,Pl as a5,Dl as a6,Ll as a7,Vo as a8,zo as a9,bm as aA,Ea as aB,ym as aC,Nm as aD,gm as aE,hm as aF,xm as aG,ns as aH,km as aI,tm as aJ,nm as aK,lm as aL,im as aM,om as aN,am as aO,dm as aP,cm as aQ,sm as aR,rm as aS,um as aT,Yp as aU,Sm as aV,Up as aW,Cm as aX,vm as aY,wm as aZ,Em as a_,Ho as aa,Nr as ab,_o as ac,Wl as ad,Fl as ae,Bl as af,$l as ag,zl as ah,Hl as ai,_l as aj,Vl as ak,Ul as al,Lp as am,Pp as an,Fs as ao,Gn as ap,Ap as aq,Bs as ar,jt as as,Ps as at,Dp as au,Tp as av,Rp as aw,Wp as ax,of as ay,ff as az,Sr as b,Ko as b$,Bc as b0,Hc as b1,ap as b2,sp as b3,dp as b4,up as b5,lp as b6,cp as b7,rp as b8,Yn as b9,Kp as bA,Wo as bB,si as bC,Ai as bD,Li as bE,Pi as bF,Zf as bG,rf as bH,sf as bI,vi as bJ,yi as bK,ki as bL,Di as bM,Ni as bN,ji as bO,li as bP,ii as bQ,oi as bR,wi as bS,Ci as bT,Zo as bU,ni as bV,ti as bW,Qo as bX,ei as bY,Ii as bZ,Yo as b_,Uf as ba,Kf as bb,Yf as bc,Hu as bd,ar as be,Xf as bf,Jf as bg,Bu as bh,Ou as bi,Pu as bj,Iu as bk,Du as bl,Fu as bm,Lu as bn,Au as bo,Mu as bp,$u as bq,Wf as br,zf as bs,_f as bt,qf as bu,tp as bv,pm as bw,fm as bx,Ag as by,es as bz,Hg as c,Yx as c$,Mi as c0,ft as c1,ec as c2,wh as c3,lh as c4,Pm as c5,Om as c6,Fm as c7,Dm as c8,Am as c9,As as cA,xl as cB,Kn as cC,tf as cD,Rf as cE,np as cF,Qf as cG,fp as cH,If as cI,Lf as cJ,Af as cK,mc as cL,yn as cM,hc as cN,pc as cO,fc as cP,uc as cQ,Tf as cR,Pf as cS,Cf as cT,Nf as cU,Gx as cV,Xx as cW,Kx as cX,Ux as cY,Vx as cZ,qx as c_,$m as ca,Tm as cb,Rm as cc,_m as cd,Vp as ce,Um as cf,zm as cg,vh as ch,nf as ci,Mf as cj,nt as ck,Zl as cl,ql as cm,Ql as cn,sc as co,cl as cp,il as cq,sl as cr,rl as cs,nl as ct,tl as cu,ep as cv,Tr as cw,El as cx,Rl as cy,fl as cz,Is as d,Wx as d0,Jx as d1,_x as d2,Hx as d3,js as d4,_c as d5,Sc as d6,zu as d7,gc as d8,ic as d9,jf as da,oc as db,af as dc,ac as dd,Oi as de,Uo as df,_g as dg,Fi as e,Es as f,Pg as g,th as h,ah as i,rh as j,eh as k,ih as l,ix as m,Qx as n,Ht as o,Ss as p,$p as q,Fe as r,Fp as s,Op as t,Ip as u,Mp as v,Hp as w,yh as x,bh as y,hi as z};
|