@codeyam-editor/codeyam-editor 0.1.4 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/npm/cloud-branch-switch.js +1 -1
  2. package/npm/cloud.js +1415 -73
  3. package/npm/container.js +3 -0
  4. package/npm/disk-pressure.js +78 -0
  5. package/npm/editor-dev.js +96 -15
  6. package/npm/editor.js +85 -37
  7. package/npm/fleet-auth-health.js +75 -0
  8. package/npm/fleet-auth.js +6 -1
  9. package/npm/fleet-build-data.js +51 -2
  10. package/npm/fleet-cleanup.js +118 -7
  11. package/npm/fleet-destroy-safety.js +55 -0
  12. package/npm/fleet-effect-status.js +33 -32
  13. package/npm/fleet-host.js +74 -0
  14. package/npm/fleet-job-badge.js +1 -1
  15. package/npm/fleet-launchd.js +171 -0
  16. package/npm/fleet-live-status.js +123 -0
  17. package/npm/fleet-plans.js +135 -0
  18. package/npm/fleet-prewarm.js +165 -0
  19. package/npm/fleet-public-url.js +160 -0
  20. package/npm/fleet-queue.js +38 -1
  21. package/npm/fleet-reconcile.js +43 -1
  22. package/npm/fleet-reset.js +298 -13
  23. package/npm/fleet-roster.js +6 -8
  24. package/npm/fleet-self-update.js +142 -0
  25. package/npm/fleet-setup-steps.js +105 -0
  26. package/npm/fleet-sleep-status.js +33 -0
  27. package/npm/fleet-strand.js +150 -0
  28. package/npm/fleet-stuck-status.js +111 -0
  29. package/npm/fleet-vm-access.js +234 -0
  30. package/npm/fleet-vm-readiness.js +104 -0
  31. package/npm/fleet-vm-slugs.js +116 -0
  32. package/npm/google-ingress.js +211 -0
  33. package/npm/ingress-invoke.js +292 -0
  34. package/npm/launch-config.js +204 -3
  35. package/npm/scenario-check.js +603 -32
  36. package/npm/scenario-handlers.js +78 -12
  37. package/npm/scenario-metrics.js +116 -1
  38. package/npm/scenario-mocks.js +20 -0
  39. package/npm/scenario-playwright.js +366 -29
  40. package/npm/script-drift.js +81 -0
  41. package/npm/utils.js +329 -50
  42. package/npm/vm-urls.js +69 -8
  43. package/package.json +5 -5
  44. package/ui/dist/assets/ContainerInspector-D7VZkkaj.js +2 -0
  45. package/ui/dist/assets/EditorShell-DHhIaotd.css +1 -0
  46. package/ui/dist/assets/EditorShell-r-796N_W.js +191 -0
  47. package/ui/dist/assets/{Markdown-BHBqz-Mj.js → Markdown-BoLHHFXH.js} +1 -1
  48. package/ui/dist/assets/ProjectLauncherScreen-Ck-XWkQN.js +1 -0
  49. package/ui/dist/assets/ScenarioDataPanel-B9iDSUpA.js +5 -0
  50. package/ui/dist/assets/ScenarioDataPanelFullPage-CBLTGC4-.js +1 -0
  51. package/ui/dist/assets/ScenarioRenderer-BhLfT-nX.js +21 -0
  52. package/ui/dist/assets/StepsSimulator-BFldWyoX.js +1 -0
  53. package/ui/dist/assets/index-CIXZkwfB.css +1 -0
  54. package/ui/dist/assets/{index-BuK0lizt.js → index-QsOiOG9x.js} +9 -9
  55. package/ui/dist/assets/useEvents-DHkLJZR4.js +1 -0
  56. package/ui/dist/codeyam-mark.svg +4 -0
  57. package/ui/dist/codeyam-wordmark.svg +5 -0
  58. package/ui/dist/index.html +2 -2
  59. package/ui/dist/assets/ContainerInspector-C8EkH4PP.js +0 -2
  60. package/ui/dist/assets/EditorShell-tMMdarZD.js +0 -187
  61. package/ui/dist/assets/ScenarioDataPanel-xWYGZOpo.js +0 -5
  62. package/ui/dist/assets/ScenarioDataPanelFullPage-5G6KuZgw.js +0 -1
  63. package/ui/dist/assets/ScenarioRenderer-CSdhX1Ak.js +0 -1
  64. package/ui/dist/assets/StepsSimulator-CRtmlyNZ.js +0 -1
  65. package/ui/dist/assets/index-BGqairFV.css +0 -1
  66. package/ui/dist/assets/useEvents-DggWrtHe.js +0 -1
@@ -1,5 +0,0 @@
1
- import{j as n}from"./markdown-v0F0UEt3.js";import{b as l}from"./react-CSS0HapR.js";import{u as Je}from"./useEvents-DggWrtHe.js";import{r as We,a as ze}from"./xterm--24IGk-x.js";import{l as F,b as qe}from"./index-BuK0lizt.js";const oe=4e3;function Ne(e){let t;try{t=JSON.stringify(e,null,2)}catch{t=String(e)}return t.length>oe?`${t.slice(0,oe)}
2
- … (truncated, ${t.length-oe} more chars)`:t}function Ge({slug:e,scenarioName:t,seedTabs:r,mockEntries:a,selectedMock:s,selectedSeedTab:o,selectedSeedRows:c}){const i=[],f=t??e;if(i.push(`# Edit Scenario Data: "${f}"`),i.push(""),i.push(`**Slug**: ${e}`),i.push(`**Scenario file**: .codeyam/scenarios/${e}.json`),i.push(""),i.push("## Scenario overview"),r.length>0){i.push("### Seed & Local tables");for(const p of r){const y=p.category?` (${p.category})`:"";i.push(`- **${p.label}**${y} — dataKey \`${p.dataKey}\``)}i.push("")}if(a.length>0){i.push("### HTTP mocks");const p=new Map;for(const y of a){const h=p.get(y.source)??[];h.push(y),p.set(y.source,h)}for(const[y,h]of p){i.push(`**${y}** (${h.length}):`);for(const d of h)i.push(`- \`${d.method} ${d.pathPattern}\``)}i.push("")}if(s){const p=`${s.method} ${s.pathPattern}`;i.push(`## Currently viewing: mock \`${p}\``),i.push(`- **Source**: ${s.source}`),s.status!==void 0&&i.push(`- **Status**: ${s.status}`);const y=s.headers??{},h=Object.entries(y);if(h.length>0){i.push("- **Headers**:");for(const[d,m]of h)i.push(` - \`${d}: ${m}\``)}s.body!==void 0&&s.body!==null?(i.push("- **Body**:"),i.push("```json"),i.push(Ne(s.body)),i.push("```")):i.push("- **Body**: (empty)"),i.push("")}else if(o){if(i.push(`## Currently viewing: seed table **${o.label}**`),i.push(`- **dataKey**: \`${o.dataKey}\``),o.category&&i.push(`- **Category**: ${o.category}`),o.description&&i.push(`- **Description**: ${o.description}`),o.schemaFields&&o.schemaFields.length>0){i.push("- **Schema**:");for(const p of o.schemaFields){const y=p.isId?" (PK)":"";i.push(` - \`${p.name}\`: ${p.type}${y}`)}}c&&c.length>0?(i.push(`- **Rows** (${c.length}):`),i.push("```json"),i.push(Ne(c)),i.push("```")):i.push("- **Rows**: (none yet)"),i.push("")}return i.push("## Your task"),i.push("The user is looking at the Scenario Data Panel and wants your help adjusting its data. Ask what change they'd like to make."),i.push(""),i.push("Typical edits:"),i.push('- Tweak an HTTP mock body, status, or headers → update `mocks.http["METHOD /path"]` in the scenario JSON'),i.push("- Add or remove seed rows → update the `seed` section"),i.push("- Adjust `localStorage` values → update the `localStorage` section"),i.push(""),i.push("To save changes:"),i.push("1. Write the updated scenario JSON to `.codeyam/tmp/scenario.json`"),i.push("2. Run: `codeyam-editor editor register @.codeyam/tmp/scenario.json`"),i.push("3. The editor will reload automatically and the panel will reflect the new data."),i.join(`
3
- `)}const he=new Set;let q=null;const Qe=150;function _n(e){return he.add(e),()=>{he.delete(e)}}function X(){q&&clearTimeout(q),q=setTimeout(()=>{q=null;for(const e of he)e()},Qe)}const me=new Set;function Hn(e){for(const t of me)t(e)}function Ze(e){return me.add(e),()=>{me.delete(e)}}function et({onSelect:e,onFocus:t}){l.useEffect(()=>Ze(({routeKey:r,jsonPath:a})=>{e(r),t(a)}),[e,t])}const ge="claude";function W(e){switch(e){case"codex":return"Codex";case"gemini":return"Gemini";default:return"Claude"}}const tt=3e3;function Ie(){const[e,t]=l.useState(null),[r,a]=l.useState(!0),[s,o]=l.useState(null),c=l.useRef(null),i=l.useCallback(async()=>{try{const f=await fetch("/api/config");if(!f.ok)throw new Error(`HTTP ${f.status}`);const p=await f.json(),y={projectTitle:p.projectTitle??null,projectDescription:p.projectDescription??null,provider:p.provider??ge,port:p.port??3e3,previewOrigin:p.previewOrigin??null,screenSizes:p.screenSizes??{},defaultScreenSize:p.defaultScreenSize??null,apps:p.apps??[]},h=JSON.stringify(y);h!==c.current&&(c.current=h,t(y)),o(null)}catch(f){o(f instanceof Error?f.message:"Failed to load config")}finally{a(!1)}},[]);return l.useEffect(()=>{i();const f=setInterval(()=>{i()},tt);return()=>clearInterval(f)},[i]),{config:e,apps:(e==null?void 0:e.apps)??[],loading:r,error:s,refetch:i}}async function ee(e){try{const t=await e.json();if(t.error)return t.error}catch{}return`Request failed (${e.status})`}async function rt(e,t=null){const r=t!=null?`?since_ms=${encodeURIComponent(t)}`:"",s=await(await fetch(`/api/mock-panel/${encodeURIComponent(e)}${r}`)).json();if("error"in s)throw new Error(s.error);return s}async function Ee(e,t){const r=`/api/scenarios/${encodeURIComponent(e)}/mocks/${encodeURIComponent(t.routeKey)}`,a=await fetch(r,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:t.status,body:t.body,headers:t.headers})});if(!a.ok)throw new Error(await ee(a))}async function nt(e,t){const r=`/api/scenarios/${encodeURIComponent(e)}/mocks/${encodeURIComponent(t)}`,a=await fetch(r,{method:"DELETE"});if(!a.ok)throw new Error(await ee(a))}async function at(e,t){const r=`/api/scenarios/${encodeURIComponent(e)}/mocks/${encodeURIComponent(t)}/passthrough`,a=await fetch(r,{method:"POST"});if(!a.ok)throw new Error(await ee(a))}function _(e){return e.kind==="shared"?`shared:${e.slug}`:e.kind}async function st(e){const t=await fetch("/api/mocks/save-scoped",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),r=await t.json();if(!t.ok||"success"in r&&r.success===!1)throw new Error("error"in r?r.error:`Save failed (${t.status})`);return r}async function ot(e,t,r){const a=new URLSearchParams({scenarioSlug:e,routeKey:t,scope:_(r)}),s=await fetch(`/api/mocks/save-scope-impact?${a.toString()}`);if(!s.ok)throw new Error(await ee(s));return(await s.json()).impactedScenarios??[]}function it(){const[e,t]=l.useState(null),[r,a]=l.useState(null),s=l.useRef(null),o=async()=>{try{const i=await fetch("/api/editor-dev-server");if(!i.ok)throw new Error(`Failed to fetch dev server status: ${i.statusText}`);const f=await i.json(),p=JSON.stringify(f);if(p===s.current){a(null);return}s.current=p,t(f),a(null)}catch(i){a(i instanceof Error?i.message:String(i))}};return l.useEffect(()=>{o();const i=setInterval(o,1e3);return()=>clearInterval(i)},[]),{status:e,error:r,restart:async()=>{try{const i=await fetch("/api/editor-dev-server",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"restart"})});if(!i.ok)throw new Error(`Failed to restart dev server: ${i.statusText}`);o()}catch(i){a(i instanceof Error?i.message:String(i))}}}}function ct(e){const[t,r]=l.useState([]),[a,s]=l.useState(null),[o,c]=l.useState(!1),[i,f]=l.useState(null),{events:p}=Je(),{status:y}=it(),h=(y==null?void 0:y.lastIframeLoadedAtMs)??null,d=l.useCallback(async()=>{if(!e){r([]),s(null);return}c(!0),f(null);try{const u=await rt(e,h);r(u.entries),s(u.defaultSlug)}catch(u){f(u instanceof Error?u.message:"Failed to load mocks")}finally{c(!1)}},[e,h]);l.useEffect(()=>{d()},[d]),l.useEffect(()=>{const u=p[p.length-1];!u||u.type!=="http_request"||d()},[p,d]);const m=l.useCallback(async u=>{e&&(await Ee(e,u),await d())},[e,d]),x=l.useCallback(async u=>{e&&(u.scope.kind==="scenario"?await Ee(e,{routeKey:u.routeKey,status:u.status,body:u.body,headers:u.headers}):await st({scenarioSlug:e,routeKey:u.routeKey,scope:u.scope,status:u.status,body:u.body,headers:u.headers}),await d())},[e,d]),b=l.useCallback(async u=>{e&&(await nt(e,u),await d())},[e,d]),v=l.useCallback(async u=>{e&&(await at(e,u),await d())},[e,d]);return{entries:t,defaultSlug:a,loading:o,error:i,refresh:d,upsert:m,upsertScoped:x,remove:b,setPassthrough:v}}function lt(e){const t={};for(const[r,a]of Object.entries(e))if(typeof a=="string")try{const s=JSON.parse(a);Array.isArray(s)?t[r]=s:typeof s=="object"&&s!==null&&(t[r]=[s])}catch{}else Array.isArray(a)&&(t[r]=a);return t}function dt(e,t){return e.length===0||t.length===0?!1:e.filter(a=>t.includes(a)).length>=Math.min(e.length,t.length)*.5}function ut(e){return e==null?"null":typeof e=="number"?Number.isInteger(e)?"int4":"float":typeof e=="boolean"?"bool":typeof e=="object"?Array.isArray(e)?"array":"json":"text"}function ft(e,t){return e.length>0?Object.keys(e[0]):t?t.map(r=>r.name):[]}function pt(e,t,r){const a=new Map((r||[]).map(o=>[o.name,o.type])),s={};for(const o of e)s[o]=a.get(o)||(t.length>0?ut(t[0][o]):"text");return s}function ht(e,t){var r;return((r=t==null?void 0:t.find(a=>a.isId))==null?void 0:r.name)||e.find(a=>a==="id")||null}function mt(e,t){const{_metadata:r,...a}=t,s=a.localStorage&&typeof a.localStorage=="object"&&!Array.isArray(a.localStorage)?lt(a.localStorage):{},o={};if(a.seed&&typeof a.seed=="object"&&!Array.isArray(a.seed))for(const[d,m]of Object.entries(a.seed))Array.isArray(m)&&(o[d]=m);const c={},i=[],f=new Set,p=new Set,y=new Set;for(const d of e){const m=d.name.charAt(0).toLowerCase()+d.name.slice(1),x=d.fields.map(u=>u.name);let b=null,v=[];for(const u of[d.name,m,`${m}s`])if(u in a&&Array.isArray(a[u])){b=u,v=a[u],p.add(u);break}if(!b){for(const u of[d.name,m,`${m}s`])if(u in o){b=u,v=o[u],y.add(u),u in s&&f.add(u);break}}if(!b){for(const u of[d.name,m,`${m}s`])if(u in s){b=m,v=s[u],f.add(u);break}}if(!b){for(const[u,g]of Object.entries(s))if(!f.has(u)&&g.length>0&&dt(x,Object.keys(g[0]))){b=m,v=g,f.add(u);break}}b||(b=m),c[b]=v,i.push({label:d.name,dataKey:b,category:d.category,description:d.description,schemaFields:d.fields.map(u=>({name:u.name,type:u.type,isId:u.isId??!1}))})}const h=new Set(["name","id","url","dimensions","componentName","scenarioType","pageFilePath","routeName","description","props","env"]);for(const[d,m]of Object.entries(a))d==="_metadata"||d==="localStorage"||d==="seed"||d==="type"||d==="mocks"||h.has(d)||p.has(d)||xt(m)&&(c[d]=m,i.push({label:d,dataKey:d}));for(const[d,m]of Object.entries(o))y.has(d)||(c[d]=m,i.push({label:d,dataKey:d}));for(const[d,m]of Object.entries(s))f.has(d)||(c[d]=m,i.push({label:d,dataKey:d}));return{data:c,tabs:i}}function Te(e){return e==="null"?null:e==="true"?!0:e==="false"?!1:e===""?"":isNaN(Number(e))?e:Number(e)}function xt(e){return Array.isArray(e)&&e.length>0&&typeof e[0]=="object"&&e[0]!==null}function bt(e){if(typeof e!="object"||e===null||!("props"in e))return null;const t=e.props;return typeof t!="object"||t===null||Array.isArray(t)?null:t}function yt(e){if(typeof e!="object"||e===null||!("browserState"in e))return null;const t=e.browserState;return typeof t!="object"||t===null||Array.isArray(t)?null:t}function gt(e,t){const r=new Set;for(const a of t){const s=e[a.dataKey];Array.isArray(s)&&s.length>0&&r.add(a.dataKey)}return r}function vt(e){if(typeof e=="object"&&e!==null&&"shares"in e){const t=e.shares;if(Array.isArray(t))return t.filter(r=>typeof r=="string")}return[]}function wt(e){const[t,r]=l.useState({data:null,tableTabs:[],scenarioOwnedDataKeys:new Set,shares:[],props:null,browserState:null,loading:!0,error:null});return l.useEffect(()=>{r(a=>({...a,loading:!0,error:null})),Promise.all([fetch("/api/data-structure").then(a=>a.json()).catch(()=>[]),fetch(`/api/scenarios/${encodeURIComponent(e)}`).then(a=>{if(!a.ok)throw new Error(`HTTP ${a.status}`);return a.json()})]).then(([a,s])=>{const o=mt(Array.isArray(a)?a:[],s);r({data:o.data,tableTabs:o.tabs,scenarioOwnedDataKeys:gt(o.data,o.tabs),shares:vt(s),props:bt(s),browserState:yt(s),loading:!1,error:null})}).catch(a=>r({data:null,tableTabs:[],scenarioOwnedDataKeys:new Set,shares:[],props:null,browserState:null,loading:!1,error:a instanceof Error?a.message:"Failed to load"}))},[e]),t}function ve(e,t=""){return`/api/scenarios/${encodeURIComponent(e)}/draft${t}`}async function jt(e){const t=await fetch(ve(e,"/status"));if(!t.ok)return{isDirty:!1,diffSummary:null};const r=await t.json();return{isDirty:!!r.isDirty,diffSummary:r.diffSummary??null}}async function kt(e){const t=await fetch(ve(e,"/commit"),{method:"POST"});if(!t.ok)throw new Error(`Save failed (${t.status})`)}async function St(e){const t=await fetch(ve(e),{method:"DELETE"});if(!t.ok)throw new Error(`Cancel failed (${t.status})`)}function Ct({slug:e,onPreviewReload:t}){const[r,a]=l.useState(!1),[s,o]=l.useState(null),[c,i]=l.useState(!1),[f,p]=l.useState(!1),[y,h]=l.useState(null),d=l.useRef(null),m=l.useCallback(async()=>{if(!e){a(!1),o(null);return}try{const g=await jt(e);a(g.isDirty),o(g.diffSummary)}catch{}},[e]);l.useEffect(()=>{m()},[m]),l.useEffect(()=>{if(!r)return;const g=S=>{S.preventDefault(),S.returnValue=""};return window.addEventListener("beforeunload",g),()=>window.removeEventListener("beforeunload",g)},[r]);const x=l.useCallback(()=>{d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{m()},100)},[m]),b=l.useCallback(async()=>{if(e){i(!0),h(null);try{await kt(e),a(!1),o(null),t&&t()}catch(g){h(g instanceof Error?g.message:"Save failed")}finally{i(!1)}}},[e,t]),v=l.useCallback(async()=>{if(e){p(!0),h(null);try{await St(e),a(!1),o(null),t&&t()}catch(g){h(g instanceof Error?g.message:"Cancel failed")}finally{p(!1)}}},[e,t]),u=l.useCallback(g=>r?window.confirm(g):!0,[r]);return{isDirty:r,saving:c,cancelling:f,error:y,diffSummary:s,save:b,cancel:v,markDirty:x,confirmIfDirty:u}}const Nt={scenario:"Scenario",shared:"Shared",default:"Defaults","catalog-only":"Observed only",passthrough:"Passthrough"},Et={scenario:null,shared:null,default:null,"catalog-only":"Observed during live traffic but not mocked yet. Promote it to a scenario mock to capture and edit the response.",passthrough:null};function Le(e){return Nt[e]??e}function Tt(e){return Et[e]??null}const At={scenario:"bg-emerald-500/15 text-emerald-300 border-emerald-500/40",shared:"bg-violet-500/15 text-violet-300 border-violet-500/40",default:"bg-[#D7FF63]/15 text-[#D7FF63] border-[#D7FF63]/40","catalog-only":"bg-slate-500/15 text-slate-300 border-slate-500/40",passthrough:"bg-zinc-500/15 text-zinc-300 border-zinc-500/40"};function Be({source:e}){const t=Tt(e);return n.jsx("span",{className:`px-1.5 py-0.5 rounded border ${At[e]}`,title:t??`source: ${e}`,children:Le(e)})}function Dt({label:e,scenarioCount:t,inheritedCount:r,expanded:a,onToggle:s}){const o=r===0;return n.jsxs("h3",{className:"px-3 pb-1 text-[10px] font-semibold uppercase tracking-wider text-[var(--text-dim)]",children:[n.jsx("div",{className:"mb-0.5",children:e}),n.jsxs("div",{className:"flex items-center gap-1 normal-case tracking-normal font-normal",children:[n.jsxs("span",{children:[t," scenario-specific"]}),n.jsx("span",{"aria-hidden":!0,children:"·"}),n.jsxs("button",{type:"button",onClick:s,disabled:o,"aria-expanded":a,className:`inline-flex items-center gap-0.5 ${o?"cursor-default text-[var(--text-dim)]":"cursor-pointer hover:text-[var(--text-primary)]"}`,children:[n.jsx("span",{"aria-hidden":!0,className:"inline-block w-2 text-[9px]",children:o?"":a?"▾":"▸"}),n.jsxs("span",{children:[r," inherited from default"]})]})]})]})}function Ot({children:e}){return n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"mx-3 my-1 border-t border-[var(--border-subtle)]"}),n.jsx("div",{className:"px-3 pb-1 text-[9px] uppercase tracking-wider text-[var(--text-dim)]",children:"Inherited from default"}),e]})}function Mt({slug:e}){return n.jsx("span",{className:"px-1 py-0.5 rounded border text-[9px] font-mono bg-violet-500/10 text-violet-300 border-violet-500/30",title:`from shared-data set: ${e}`,children:e})}const Rt={GET:"text-emerald-400",POST:"text-[#D7FF63]",PUT:"text-amber-400",PATCH:"text-purple-400",DELETE:"text-red-400"};function Pt({entry:e,routeKey:t,active:r,onSelect:a}){const s=Rt[e.method]??"text-[var(--text-muted)]";return n.jsxs("button",{onClick:a,className:`w-full text-left px-3 py-1.5 text-xs flex items-center gap-2 border-l-2 transition-colors cursor-pointer ${r?"bg-[var(--accent-blue)]/10 border-[var(--accent-blue)] text-[var(--text-primary)]":"border-transparent text-[var(--text-muted)] hover:bg-[var(--bg-card)] hover:text-[var(--text-primary)]"}`,title:t,children:[n.jsx("span",{className:`font-mono text-[9px] font-semibold ${s}`,children:e.method}),n.jsx("span",{className:"truncate flex-1 font-mono",children:e.pathPattern}),e.source==="shared"&&e.sharedSlug&&n.jsx(Mt,{slug:e.sharedSlug})]})}const $t=["scenario","shared","default","catalog-only","passthrough"];function J(e){return`${e.method} ${e.pathPattern}`}function It({seedTabs:e,mockEntries:t,selection:r,onSelect:a,overrides:s}){const o=new Map;for(const c of t){const i=o.get(c.source)??[];i.push(c),o.set(c.source,i)}return n.jsxs("nav",{className:"w-56 shrink-0 border-r border-[var(--border-subtle)] bg-[var(--bg-deep)] overflow-y-auto",children:[n.jsxs(ie,{label:"Browser Environment",count:4,emptyHint:"",children:[n.jsx(G,{label:"Cookies",active:(r==null?void 0:r.kind)==="browser"&&r.tab==="cookies",onSelect:()=>a({kind:"browser",tab:"cookies"})}),n.jsx(G,{label:"Local Storage",active:(r==null?void 0:r.kind)==="browser"&&r.tab==="localStorage",onSelect:()=>a({kind:"browser",tab:"localStorage"})}),n.jsx(G,{label:"Session Storage",active:(r==null?void 0:r.kind)==="browser"&&r.tab==="sessionStorage",onSelect:()=>a({kind:"browser",tab:"sessionStorage"})}),n.jsx(G,{label:"Request Headers",active:(r==null?void 0:r.kind)==="browser"&&r.tab==="headers",onSelect:()=>a({kind:"browser",tab:"headers"})})]}),n.jsx(ie,{label:"Seed & Local",count:e.length,emptyHint:"No seed or localStorage data",override:s?{scenarioCount:s.scenarioSeedCount,inheritedCount:s.inheritedSeedCount,renderInherited:()=>Ae({tabs:s.inheritedSeedTabs,selection:r,onSelect:a})}:void 0,children:Ae({tabs:e,selection:r,onSelect:a})}),n.jsx(ie,{label:"Mock APIs",count:t.length,emptyHint:"No HTTP mocks registered",override:s?{scenarioCount:s.scenarioMockCount,inheritedCount:s.inheritedMockCount,renderInherited:()=>De({entries:s.inheritedMockEntries,selection:r,onSelect:a})}:void 0,children:De({entries:t,grouped:o,selection:r,onSelect:a})})]})}function Ae({tabs:e,selection:t,onSelect:r}){return e.map(a=>{const s=(t==null?void 0:t.kind)==="seed"&&t.dataKey===a.dataKey;return n.jsxs("button",{onClick:()=>r({kind:"seed",dataKey:a.dataKey}),className:`w-full text-left px-3 py-1.5 text-xs flex items-center gap-2 border-l-2 transition-colors cursor-pointer ${s?"bg-[var(--accent-active)]/10 border-[var(--accent-active)] text-[var(--text-primary)]":"border-transparent text-[var(--text-muted)] hover:bg-[var(--bg-card)] hover:text-[var(--text-primary)]"}`,children:[n.jsx("span",{className:"truncate flex-1",children:a.label}),a.category&&n.jsx("span",{className:"text-[9px] uppercase tracking-wide text-[var(--text-dim)]",children:a.category==="mock-api"?"API":a.category})]},a.dataKey)})}function G({label:e,active:t,onSelect:r}){return n.jsxs("button",{onClick:r,className:`w-full text-left px-3 py-1.5 text-xs flex items-center gap-2 border-l-2 transition-colors cursor-pointer ${t?"bg-[var(--accent-active)]/10 border-[var(--accent-active)] text-[var(--text-primary)]":"border-transparent text-[var(--text-muted)] hover:bg-[var(--bg-card)] hover:text-[var(--text-primary)]"}`,children:[n.jsx("span",{className:"truncate flex-1",children:e}),n.jsx("span",{className:"text-[9px] uppercase tracking-wide text-[var(--text-dim)]",children:"ENV"})]})}function De({entries:e,grouped:t,selection:r,onSelect:a}){const s=t??Lt(e);return $t.flatMap(o=>{const c=s.get(o)??[];return c.length===0?[]:[n.jsxs("div",{className:"px-3 pt-2 pb-1 text-[9px] uppercase tracking-wider text-[var(--text-dim)] font-semibold flex items-center gap-1.5",children:[Le(o),n.jsx(Be,{source:o})]},`hdr-${o}`),...c.map(i=>{const f=J(i),p=(r==null?void 0:r.kind)==="mock"&&r.routeKey===f;return n.jsx(Pt,{entry:i,routeKey:f,active:p,onSelect:()=>a({kind:"mock",routeKey:f})},f)})]})}function Lt(e){const t=new Map;for(const r of e){const a=t.get(r.source)??[];a.push(r),t.set(r.source,a)}return t}function ie({label:e,count:t,emptyHint:r,children:a,override:s}){const[o,c]=l.useState(!1);if(s){const{scenarioCount:i,inheritedCount:f,renderInherited:p}=s,y=i+(o?f:0);return n.jsxs("section",{className:"py-2",children:[n.jsx(Dt,{label:e,scenarioCount:i,inheritedCount:f,expanded:o,onToggle:()=>c(h=>!h)}),y===0?n.jsx("p",{className:"px-3 py-1 text-[10px] italic text-[var(--text-dim)]",children:r}):n.jsxs("div",{children:[a,o&&f>0&&n.jsx(Ot,{children:p()})]})]})}return n.jsxs("section",{className:"py-2",children:[n.jsxs("h3",{className:"px-3 pb-1 text-[10px] font-semibold uppercase tracking-wider text-[var(--text-dim)] flex items-center justify-between",children:[n.jsx("span",{children:e}),n.jsx("span",{children:t})]}),t===0?n.jsx("p",{className:"px-3 py-1 text-[10px] italic text-[var(--text-dim)]",children:r}):n.jsx("div",{children:a})]})}function Bt({seedTabs:e,mockEntries:t,initialSection:r,selection:a,setSelection:s}){l.useEffect(()=>{if(a)return;const o=r==="mocks",c=r==="seed";if(o&&t.length>0){s({kind:"mock",routeKey:J(t[0])});return}if(c&&e.length>0){s({kind:"seed",dataKey:e[0].dataKey});return}e.length>0?s({kind:"seed",dataKey:e[0].dataKey}):t.length>0&&s({kind:"mock",routeKey:J(t[0])})},[r,t,e,a,s])}const xe={state:"unknown",provider:ge,credsPresent:!0,reason:null,expiresAt:null,probeInFlight:!1,probeAttempts:0,backendFieldAbsent:!1};function Kt(e){if(e==null)return{...xe,backendFieldAbsent:!0};if(typeof e!="object")return xe;const t=e,r=t.state==="authenticated"||t.state==="needs-login"||t.state==="unknown"?t.state:"unknown",a=t.provider==="claude"||t.provider==="codex"||t.provider==="gemini"?t.provider:ge,s=typeof t.credsPresent=="boolean"?t.credsPresent:!0,o=t.reason==="token-expired"||t.reason==="api-401"||t.reason==="no-credentials"||t.reason==="probe-timeout"?t.reason:null,c=typeof t.tokenExpiresAt=="string"?t.tokenExpiresAt:typeof t.expiresAt=="string"?t.expiresAt:null,i=typeof t.probeInFlight=="boolean"?t.probeInFlight:!1,f=typeof t.probeAttempts=="number"&&Number.isFinite(t.probeAttempts)&&t.probeAttempts>=0?t.probeAttempts:0;return{state:r,provider:a,credsPresent:s,reason:o,expiresAt:c,probeInFlight:i,probeAttempts:f,backendFieldAbsent:!1}}const Ft=1e3;function _t(){const[e,t]=l.useState(xe),r=l.useRef(e.state);r.current=e.state;const a=l.useCallback(async()=>{try{const s=await fetch("/api/config");if(!s.ok)return;const o=await s.json();t(Kt(o.providerAuth))}catch{}},[]);return l.useEffect(()=>{a()},[a]),l.useEffect(()=>{if(e.state!=="unknown")return;const s=window.setInterval(()=>{r.current==="unknown"&&a()},Ft);return()=>window.clearInterval(s)},[e.state,a]),l.useEffect(()=>{const s=()=>{t(o=>({...o,state:"needs-login"})),a()};return window.addEventListener("agent-auth-required",s),()=>window.removeEventListener("agent-auth-required",s)},[a]),l.useEffect(()=>{const s=()=>{t(o=>({...o,state:"authenticated"})),a()};return window.addEventListener("agent-auth-resolved",s),()=>window.removeEventListener("agent-auth-resolved",s)},[a]),{state:e.state,provider:e.provider,credsPresent:e.credsPresent,reason:e.reason,expiresAt:e.expiresAt,probeInFlight:e.probeInFlight,probeAttempts:e.probeAttempts,backendFieldAbsent:e.backendFieldAbsent,refresh:a}}var Ht=We(),Vt=ze();function Yt(e){const t=window.location.protocol==="https:"?"wss:":"ws:",r=new URL(`${t}//${window.location.host}/ws/terminal`);return e!=null&&e.provider&&r.searchParams.set("provider",e.provider),e!=null&&e.mode&&r.searchParams.set("mode",e.mode),e!=null&&e.sessionId&&r.searchParams.set("sessionId",e.sessionId),e!=null&&e.cols&&e.cols>0&&r.searchParams.set("cols",String(e.cols)),e!=null&&e.rows&&e.rows>0&&r.searchParams.set("rows",String(e.rows)),r.toString()}async function Ut(e){try{if(typeof navigator<"u"&&navigator.clipboard&&typeof navigator.clipboard.writeText=="function")return await navigator.clipboard.writeText(e),!0}catch{}return Xt(e)}function Xt(e){var s;if(typeof document>"u"||!document.body)return!1;const t=document.activeElement,r=document.createElement("textarea");r.value=e,r.setAttribute("readonly",""),r.style.position="fixed",r.style.top="0",r.style.left="-9999px",r.style.opacity="0",r.style.pointerEvents="none",document.body.appendChild(r);let a=!1;try{r.focus(),r.select(),a=document.execCommand("copy")}catch{a=!1}finally{r.remove(),(s=t==null?void 0:t.focus)==null||s.call(t)}return a}function Jt(){if(typeof navigator>"u")return!1;const e=navigator.platform??"";return e?/Mac|iPhone|iPad|iPod/i.test(e):/Mac|iPhone|iPad|iPod/i.test(navigator.userAgent??"")}function Wt(e,t,r={}){const a=r.isMac??Jt(),s=r.onError,o=r.onCopy;let c=null;async function i(x){if(!x)return!1;let b=!1;try{b=await Ut(x)}catch(v){return s==null||s(Oe("copy",v)),!1}if(b){try{e.clearSelection()}catch{}o==null||o()}else s==null||s(qt("copy"));return b}async function f(){return e.hasSelection()?i(e.getSelection()):!1}async function p(){try{const x=await navigator.clipboard.readText();x&&e.paste(x)}catch(x){s==null||s(Oe("paste",x))}}function y(x){return x.type!=="keydown"?!0:a?(x.metaKey&&!x.ctrlKey&&!x.altKey&&x.key.toLowerCase()==="c"||x.ctrlKey&&!x.metaKey&&!x.altKey&&!x.shiftKey&&x.key.toLowerCase()==="c")&&e.hasSelection()?(f(),!1):!0:(x.ctrlKey&&x.shiftKey&&!x.metaKey&&!x.altKey&&x.key.toLowerCase()==="c"||x.ctrlKey&&!x.shiftKey&&!x.metaKey&&!x.altKey&&x.key.toLowerCase()==="c")&&e.hasSelection()?(f(),!1):!0}e.attachCustomKeyEventHandler(y);function h(){if(!c)return;const{root:x,onDocumentClick:b,onKeyDown:v}=c;document.removeEventListener("mousedown",b,!0),document.removeEventListener("keydown",v,!0),x.remove(),c=null}function d(x,b,v){h();const u=document.createElement("div");u.setAttribute("data-terminal-clipboard-menu","true"),u.style.position="fixed",u.style.left=`${x}px`,u.style.top=`${b}px`,u.style.zIndex="1000",u.style.minWidth="180px",u.style.padding="4px 0",u.style.background="var(--bg-card)",u.style.border="1px solid var(--border-subtle)",u.style.borderRadius="6px",u.style.boxShadow="0 8px 24px rgba(0, 0, 0, 0.35)",u.style.fontSize="12px",u.style.color="var(--text-primary)",u.style.userSelect="none";const g=a?"⌘C":"Ctrl+Shift+C",S=a?"⌘V":"Ctrl+Shift+V",w=ce("Copy",g,!v,()=>{i(v),h()}),N=ce("Paste",S,!1,()=>{p(),h()}),R=ce("Select All","",!1,()=>{try{e.selectAll()}catch{}const j=e.hasSelection()?e.getSelection():"";i(j),h()});u.appendChild(w),u.appendChild(N),u.appendChild(R),document.body.appendChild(u),zt(u,x,b);const D=j=>{u.contains(j.target)||h()},O=j=>{j.key==="Escape"&&(j.preventDefault(),h())};document.addEventListener("mousedown",D,!0),document.addEventListener("keydown",O,!0),c={root:u,onDocumentClick:D,onKeyDown:O}}function m(x){x.preventDefault();const b=e.hasSelection()?e.getSelection():"";d(x.clientX,x.clientY,b)}return t.addEventListener("contextmenu",m),()=>{t.removeEventListener("contextmenu",m),h(),e.attachCustomKeyEventHandler(()=>!0)}}function ce(e,t,r,a){const s=document.createElement("button");s.type="button",s.disabled=r,s.style.display="flex",s.style.justifyContent="space-between",s.style.alignItems="center",s.style.gap="16px",s.style.width="100%",s.style.padding="6px 12px",s.style.border="none",s.style.background="transparent",s.style.textAlign="left",s.style.fontSize="12px",s.style.cursor=r?"default":"pointer",s.style.color=r?"var(--text-dim)":"var(--text-primary)";const o=document.createElement("span");if(o.textContent=e,s.appendChild(o),t){const c=document.createElement("span");c.textContent=t,c.style.color="var(--text-dim)",c.style.fontSize="11px",s.appendChild(c)}return r||(s.addEventListener("mouseenter",()=>{s.style.background="var(--border-subtle)"}),s.addEventListener("mouseleave",()=>{s.style.background="transparent"}),s.addEventListener("click",()=>a())),s}function zt(e,t,r){const a=typeof window<"u"?window.innerWidth:0,s=typeof window<"u"?window.innerHeight:0;if(!a||!s)return;const o=e.getBoundingClientRect(),c=4;let i=t,f=r;o.width&&t+o.width+c>a&&(i=Math.max(c,a-o.width-c)),o.height&&r+o.height+c>s&&(f=Math.max(c,s-o.height-c)),e.style.left=`${i}px`,e.style.top=`${f}px`}function Oe(e,t){const r=t instanceof Error?t.message:String(t);return`Clipboard ${e} failed: ${r}`}function qt(e){return`Clipboard ${e} blocked by the browser.`}function Gt(e,t,r,a,s,o){const c=e.leftBorderCol+1;if(t===a)return s-r;if(a<t){let p=r-c;p+=1;for(let h=a+1;h<t;h++){const d=o(h);if(d===null)return null;p+=Math.max(1,d-c+1)}const y=o(a);return y===null?null:(p+=Math.max(0,y-s),-p)}const i=o(t);if(i===null)return null;let f=Math.max(0,i-r)+1;for(let p=t+1;p<a;p++){const y=o(p);if(y===null)return null;f+=Math.max(1,y-c+1)}return f+=s-c,f}const Q=new Set(["│","┃","║","|"]);function Qt(e,t,r,a){const s=e.baseY,o=(m,x)=>{const b=e.getLine(s+m);if(!b)return null;const v=b.getCell(x);return v?v.getChars():null},c=m=>{let x=-1;for(let v=0;v<r;v++){const u=o(m,v);if(u!==null&&Q.has(u)){x=v;break}}if(x===-1)return null;let b=-1;for(let v=r-1;v>x;v--){const u=o(m,v);if(u!==null&&Q.has(u)){b=v;break}}return b===-1?null:{leftBorderCol:x,rightBorderCol:b}};let i=t,f=c(t);if(!f){const m=c(t-1);if(m)i=t-1,f=m;else{const x=c(t+1);x&&(i=t+1,f=x)}}if(!f)return null;const{leftBorderCol:p,rightBorderCol:y}=f;let h=i;for(let m=i-1;m>=0;m--){const x=o(m,p);if(x===null)break;if(!(x===""||x===" ")){if(!Q.has(x))break;h=m}}let d=i;for(let m=i+1;m<a;m++){const x=o(m,p);if(x===null)break;if(!(x===""||x===" ")){if(!Q.has(x))break;d=m}}return{topRow:h,bottomRow:d,leftBorderCol:p,rightBorderCol:y}}function Zt(e,t,r,a){const s=e.getLine(e.baseY+t);if(!s)return null;for(let o=a;o>=r;o--){const c=s.getCell(o);if(!c)continue;const i=c.getChars();if(i!==""&&i!==" ")return o}return r-1}const er=200;function tr(e){const{click:t,terminal:r,cellSurface:a,debug:s}=e,o=r.buffer.active,c=w=>{s==null||s({cursorY:o.cursorY,cursorX:o.cursorX,originalTargetCol:w.originalTargetCol??w.targetCol,snapped:w.snapped??!1,...w})};if(o.type==="alternate")return c({targetRow:-1,targetCol:-1,box:null,rejected:"alt-screen",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;if(o.viewportY!==o.baseY)return c({targetRow:-1,targetCol:-1,box:null,rejected:"scrollback",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;const i=a.getBoundingClientRect();if(i.width===0||i.height===0)return c({targetRow:-1,targetCol:-1,box:null,rejected:"outside-grid",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;const f=t.clientX-i.left,p=t.clientY-i.top;if(f<0||p<0||f>=i.width||p>=i.height)return c({targetRow:-1,targetCol:-1,box:null,rejected:"outside-grid",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;const y=i.width/r.cols,h=i.height/r.rows,d=Math.floor(f/y),m=Math.floor(p/h),x=r.modes.applicationCursorKeysMode,b=x?"\x1BOC":"\x1B[C",v=x?"\x1BOD":"\x1B[D",u=Qt(o,o.cursorY,r.cols,r.rows);if(u){if(m<u.topRow||m>u.bottomRow)return c({targetRow:m,targetCol:d,box:u,rejected:"out-of-box",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;if(d<=u.leftBorderCol||d>=u.rightBorderCol)return c({targetRow:m,targetCol:d,box:u,rejected:"border",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;const w=u.leftBorderCol+1,N=u.rightBorderCol-1,R=C=>Zt(o,C,w,N),D=o.cursorY<u.topRow||o.cursorY>u.bottomRow,O=D?u.bottomRow:o.cursorY,j=D?N:o.cursorX,T=m!==O;let k=null;if(T&&(k=R(m),k===null))return c({targetRow:m,targetCol:d,originalTargetCol:d,snapped:!1,box:u,rejected:"unreadable-row",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;let M=d,$=!1;if(T&&k!==null){const C=Math.max(w,k);d>C&&(M=C,$=!0)}if(m===O&&M===j)return c({targetRow:m,targetCol:M,originalTargetCol:d,snapped:$,box:u,rejected:"same-cell",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;const I=Gt(u,O,j,m,M,R);if(I===null)return c({targetRow:m,targetCol:M,originalTargetCol:d,snapped:$,box:u,rejected:"unreadable-row",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;if(I===0)return c({targetRow:m,targetCol:M,originalTargetCol:d,snapped:$,box:u,rejected:"same-cell",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;if(Math.abs(I)>er)return c({targetRow:m,targetCol:M,originalTargetCol:d,snapped:$,box:u,rejected:"emit-cap",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;const B=I<0?v.repeat(-I):b.repeat(I);return c({targetRow:m,targetCol:M,originalTargetCol:d,snapped:$,box:u,rejected:null,emittedDirection:I<0?"left":"right",emittedByteCount:B.length,predictedCursorY:m,predictedCursorX:M}),B}if(m!==o.cursorY)return c({targetRow:m,targetCol:d,box:null,rejected:"out-of-box",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;const g=d-o.cursorX;if(g===0)return c({targetRow:m,targetCol:d,box:null,rejected:"same-cell",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;const S=g<0?v.repeat(-g):b.repeat(g);return c({targetRow:m,targetCol:d,box:null,rejected:null,emittedDirection:g<0?"left":"right",emittedByteCount:S.length,predictedCursorY:m,predictedCursorX:d}),S}const Me=1;function rr(e,t){const{sendInput:r,pixelThreshold:a=3,timeThresholdMs:s=300,now:o=()=>Date.now(),onVerificationDisable:c}=t,i=e.element;if(!i)return()=>{};const f=i.querySelector(".xterm-screen")??i;let p=null,y=!1,h=null,d=null;const m=typeof e.onRender=="function"?e.onRender.bind(e):null;m&&(d=m(()=>{const v=h;if(!v)return;h=null;const u=e.buffer.active,g=Math.abs(u.cursorY-v.y),S=Math.abs(u.cursorX-v.x);if(g>Me||S>Me){y=!0;const w={predicted:v,actual:{y:u.cursorY,x:u.cursorX}};c?c(w):console.warn("[click-cursor] disabled — cursor diverged from prediction",w)}}));function x(v){if(v.button!==0||v.altKey||v.shiftKey||v.metaKey||v.ctrlKey){p=null;return}p={clientX:v.clientX,clientY:v.clientY,at:o()}}function b(v){var O;const u=p;if(p=null,!u)return;const g=v.clientX-u.clientX,S=v.clientY-u.clientY;if(Math.hypot(g,S)>a||o()-u.at>s)return;const w=typeof window<"u"&&((O=window.localStorage)==null?void 0:O.getItem("codeyam.terminalClickDebug"))==="1";if(w)try{const j=e.buffer.active,T=j.cursorY,k={};for(let M=-2;M<=2;M++){const $=T+M,I=j.getLine(j.baseY+$);if(!I)continue;const B=[];for(let C=0;C<e.cols;C++){const E=I.getCell(C);B.push(E?E.getChars():"")}k[`row${$}`]=B.join("|")}console.log("[click-cursor] buffer dump",{cursorY:T,cursorX:j.cursorX,viewportY:j.viewportY,baseY:j.baseY,rows:k})}catch{}let N=null;const R=j=>{N=j,w&&console.log("[click-cursor] result",j)},D=tr({click:{clientX:v.clientX,clientY:v.clientY},terminal:e,cellSurface:f,debug:R});if(D){if(N){const j=N,T=j.box!==null&&j.targetRow!==j.cursorY;if(T&&y){w&&console.log("[click-cursor] suppressed by verification-disabled");return}T&&j.predictedCursorY!==null&&j.predictedCursorX!==null&&(h={y:j.predictedCursorY,x:j.predictedCursorX})}r(D)}}return f.addEventListener("mousedown",x),f.addEventListener("mouseup",b),()=>{f.removeEventListener("mousedown",x),f.removeEventListener("mouseup",b),d==null||d.dispose()}}async function Ke(e=1500){try{return(await fetch("/api/health",{signal:AbortSignal.timeout(e)})).ok}catch{return!1}}function nr(e,t){let r=!1,a=null;async function s(){if(!r){if(await Ke(1500)){r||t();return}r||(a=setTimeout(s,e))}}return a=setTimeout(s,e),()=>{r=!0,a&&(clearTimeout(a),a=null)}}const ar="The editor server closed the terminal connection with no further detail.";function sr(e){if(e&&typeof e=="object"&&"message"in e){const t=e.message;if(typeof t=="string"&&t.length>0)return t}return ar}function or(){return n.jsx("div",{"data-testid":"terminal-connecting-hint",className:"absolute top-2 right-3 text-xs font-mono text-[#aaa] pointer-events-none z-10 select-none",children:"Connecting…"})}function ir({attempt:e,maxAttempts:t,pulseKey:r}){return n.jsx("div",{"data-testid":"terminal-reconnecting-banner",className:"absolute inset-0 flex items-start justify-center pt-3 z-10 bg-black/40",children:n.jsxs("div",{"data-testid":"terminal-reconnecting-banner-label",className:"px-4 py-2 rounded font-mono text-sm shadow terminal-disconnect-pulse bg-amber-500/90 text-black",children:["Reconnecting… (attempt ",e," of ",t,")"]},r)})}function cr({onRefresh:e}){return n.jsx("div",{"data-testid":"terminal-failed-banner",className:"absolute inset-0 flex items-start justify-center pt-3 z-10 bg-black/60",children:n.jsxs("div",{className:"px-4 py-2 rounded font-mono text-sm shadow flex items-center gap-3 terminal-disconnect-pulse bg-red-500/90 text-white",children:[n.jsx("span",{children:"Connection lost. The page must be refreshed to continue."}),n.jsx("button",{type:"button",onClick:e,"data-testid":"terminal-failed-banner-refresh",className:"px-2 py-1 rounded bg-white text-red-700 font-medium cursor-pointer hover:bg-red-50",children:"Refresh page"})]})})}function lr({onReload:e}){return n.jsx("div",{"data-testid":"terminal-server-stopped-banner",className:"absolute inset-0 flex items-start justify-center pt-3 z-10 bg-black/60",children:n.jsxs("div",{className:"px-4 py-2 rounded font-mono text-sm shadow flex items-center gap-3 terminal-disconnect-pulse bg-red-500/90 text-white",children:[n.jsx("span",{children:"Editor stopped — restart it from your terminal to continue."}),n.jsx("button",{type:"button",onClick:e,"data-testid":"terminal-server-stopped-banner-reload",className:"px-2 py-1 rounded bg-white text-red-700 font-medium cursor-pointer hover:bg-red-50",children:"Reload page"})]})})}function dr({message:e,onRefresh:t}){return n.jsx("div",{"data-testid":"terminal-server-error-banner",className:"absolute inset-0 flex items-start justify-center pt-3 z-10 bg-black/60",children:n.jsxs("div",{className:"px-4 py-3 rounded font-mono text-sm shadow flex items-start gap-3 max-w-2xl bg-amber-500/95 text-black border border-amber-700",children:[n.jsx("pre",{"data-testid":"terminal-server-error-banner-message",className:"whitespace-pre-wrap break-words flex-1 m-0 font-mono text-xs leading-snug",children:e}),n.jsx("button",{type:"button",onClick:t,"data-testid":"terminal-server-error-banner-refresh",className:"px-2 py-1 rounded bg-white text-amber-900 font-medium cursor-pointer hover:bg-amber-50 self-start",children:"Refresh"})]})})}function ur({status:e,pulseKey:t,onRefresh:r}){return e.kind==="open"||e.kind==="ended"?null:e.kind==="connecting"?n.jsx(or,{}):e.kind==="reconnecting"?n.jsx(ir,{attempt:e.attempt,maxAttempts:e.maxAttempts,pulseKey:t}):e.kind==="server-stopped"?n.jsx(lr,{onReload:r}):e.kind==="server-error"?n.jsx(dr,{message:e.message,onRefresh:r}):n.jsx(cr,{onRefresh:r})}function fr({status:e,onRetry:t}){return e==="retrying"?n.jsx("div",{"data-testid":"mini-agent-launch-retrying",className:"absolute inset-x-0 top-2 z-10 flex justify-center pointer-events-none",children:n.jsx("span",{className:"font-mono text-xs italic text-[var(--text-dim)] bg-black/40 px-2 py-1 rounded",children:"Launch slow — retrying…"})}):e==="failed"?n.jsx("div",{role:"alert","data-testid":"mini-agent-launch-failed-banner",className:"absolute inset-0 flex items-start justify-center pt-3 z-10 bg-black/60",children:n.jsxs("div",{className:"px-4 py-2 rounded font-mono text-sm shadow flex items-center gap-3 terminal-disconnect-pulse bg-red-500/90 text-white",children:[n.jsx("span",{children:"Couldn't launch the build agent — the shell prompt didn't respond in time."}),n.jsx("button",{type:"button",onClick:t,"data-testid":"mini-agent-launch-failed-retry",className:"px-2 py-1 rounded bg-white text-red-700 font-medium cursor-pointer hover:bg-red-50",children:"Retry"})]})}):null}const pr=40;function hr(e){const t=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return t&&t.slice(0,pr).replace(/-+$/,"")||"session"}function Fe(e){window.dispatchEvent(new CustomEvent("terminal-send-input",{detail:e}))}const Z=50;function mr(e,t=Fe){return new Promise(r=>{t(e),setTimeout(()=>{t("\r"),r()},Z)})}const le=3e3;function _e(e){return e==="gemini"?"gemini":"claude"}function xr(e,t){return`${_e(e)} '${t}'\r`}async function br(e,t=Fe){const r=hr(e);await mr(`/rename ${r}`,t)}function yr(e,t,r){F("dispatch-rename",{phase:"queued",caller:t,label:e,delayMs:le}),setTimeout(()=>{F("dispatch-rename",{phase:"fired",caller:t,label:e,delayMs:le}),br(e,r)},le)}function gr(e,t){const r=_e(e),a=`mkdir -p .codeyam/tmp && cat > .codeyam/tmp/inline-prompt.md << 'INLINE_PROMPT_EOF'
4
- ${t}
5
- INLINE_PROMPT_EOF\r`,s=`${r} "Read the file at '.codeyam/tmp/inline-prompt.md' for your instructions."\r`;return[a,s]}function vr({idleMs:e,ceilingMs:t}){return new Promise(r=>{let a=null,s=null,o=!1;function c(){o||(o=!0,a!==null&&clearTimeout(a),s!==null&&clearTimeout(s),window.removeEventListener("miniagent-output",f),r())}function i(){a!==null&&clearTimeout(a),a=setTimeout(c,e)}function f(){i()}window.addEventListener("miniagent-output",f),s=setTimeout(c,t),i()})}const wr=350,jr=4e3,kr=8e3,Sr=500,U={armed:"mini-agent-launch-armed",fired:"mini-agent-launch-fired",confirmed:"mini-agent-launch-confirmed",relaunch:"mini-agent-relaunch",failed:"mini-agent-launch-failed"};function Cr(e){const{provider:t,slashCommand:r,prompt:a,chatName:s,sendInput:o}=e,[c,i]=l.useState("idle"),f=l.useRef(o),p=l.useRef(r),y=l.useRef(a),h=l.useRef(s),d=l.useRef(t);l.useEffect(()=>{f.current=o},[o]),l.useEffect(()=>{p.current=r},[r]),l.useEffect(()=>{y.current=a},[a]),l.useEffect(()=>{h.current=s},[s]),l.useEffect(()=>{d.current=t},[t]);const m=l.useRef(0),x=l.useRef(!1),b=l.useRef(0),v=l.useCallback((R,D)=>{const O=p.current,j=y.current;if(O){const T=xr(d.current,O),k=de(T);R(k),setTimeout(()=>{D()&&R("\r")},Z)}else{const[T,k]=gr(d.current,j??""),M=de(T),$=de(k);R(M),setTimeout(()=>{D()&&(R("\r"),setTimeout(()=>{D()&&(R($),setTimeout(()=>{D()&&R("\r")},Z))},Sr))},Z)}},[]),u=l.useCallback(()=>{const R=++m.current,D=Date.now();b.current=D,i("armed"),F(U.armed,{provider:d.current,slashCommand:p.current,chatName:h.current,hasPrompt:typeof y.current=="string"});function O(){return m.current===R}function j(T){O()&&(i(T===1?"firing":"retrying"),F(T===1?U.fired:U.relaunch,{provider:d.current,slashCommand:p.current,chatName:h.current,attempt:T,elapsedMs:Date.now()-D}),v(f.current,O),x.current||(x.current=!0,yr(h.current,"mini-agent-chat",k=>f.current(k))),setTimeout(()=>{O()&&(T===1?j(2):(i("failed"),F(U.failed,{provider:d.current,slashCommand:p.current,reason:"banner-timeout",elapsedMs:Date.now()-D})))},kr))}vr({idleMs:wr,ceilingMs:jr}).then(()=>{O()&&j(1)})},[v]),g=l.useCallback(()=>{x.current=!1,u()},[u]),S=l.useCallback(()=>{u()},[u]),w=l.useCallback(()=>{m.current!==0&&(m.current++,i("confirmed"),F(U.confirmed,{elapsedMs:Date.now()-b.current}))},[]),N=l.useCallback(()=>{m.current!==0&&(m.current++,i("failed"),F(U.failed,{reason:"startup-failed",elapsedMs:Date.now()-b.current}))},[]);return l.useEffect(()=>()=>{m.current++},[]),{status:c,arm:g,retry:S,onBannerReady:w,onStartupFailed:N}}function de(e){return e.endsWith("\r")?e.slice(0,-1):e}const Re=15;function Nr({chatName:e,prompt:t,slashCommand:r,height:a=400,onClose:s}){const o=l.useRef(null),c=l.useRef(null),i=l.useRef(null);l.useRef(t);const{config:f}=Ie(),p=(f==null?void 0:f.provider)??"claude",[y,h]=l.useState({kind:"connecting"}),[d,m]=l.useState(0),x=l.useCallback(u=>{const g=c.current;(g==null?void 0:g.readyState)===WebSocket.OPEN&&g.send(JSON.stringify({type:"input",data:u}))},[]),b=Cr({provider:p,slashCommand:r,prompt:t,chatName:e,sendInput:x}),v=l.useRef(b);return l.useEffect(()=>{v.current=b}),l.useEffect(()=>{const u=o.current;if(!u)return;const g=new Ht.Terminal({theme:{background:"#1a1a1a",foreground:"#d4d4d4",cursor:"#d4d4d4",selectionBackground:"#264f78"},fontSize:12,fontFamily:"'IBM Plex Mono', 'Menlo', 'Monaco', monospace",cursorBlink:!0,scrollback:5e3,allowProposedApi:!0}),S=new Vt.FitAddon;g.loadAddon(S),g.open(u);const w=Wt(g,u,{onError:C=>console.warn("[MiniAgentChat]",C)}),N=rr(g,{sendInput:C=>{const E=c.current;(E==null?void 0:E.readyState)===WebSocket.OPEN&&E.send(JSON.stringify({type:"input",data:C}))}});requestAnimationFrame(()=>{try{S.fit()}catch{}}),i.current=g;const R={current:"inline"},D={current:null},O={current:!1},j={current:!1};let T=0,k=null;function M(){h({kind:"connecting"});const C=Yt({mode:R.current,sessionId:D.current??void 0,cols:g.cols,rows:g.rows}),E=new WebSocket(C);E.binaryType="arraybuffer",c.current=E,E.onopen=()=>{T=0,h({kind:"open"}),E.send(JSON.stringify({type:"resize",cols:g.cols,rows:g.rows}))},E.onmessage=P=>{if(P.data instanceof ArrayBuffer){g.write(new Uint8Array(P.data)),window.dispatchEvent(new CustomEvent("miniagent-output"));return}try{const L=JSON.parse(P.data);if(L.type==="error"){j.current=!0,h({kind:"server-error",message:sr(L)});return}if(L.type==="session-id"){L.sessionId&&(D.current=L.sessionId,R.current="resume"),O.current||(O.current=!0,v.current.arm());return}if(L.type==="agent-banner-ready"){v.current.onBannerReady();return}if(L.type==="agent-auth-required"){window.dispatchEvent(new CustomEvent("agent-auth-required"));return}if(L.type==="startup-failed"){v.current.onStartupFailed();return}}catch{g.write(P.data),window.dispatchEvent(new CustomEvent("miniagent-output"))}},E.onerror=()=>{},E.onclose=async()=>{if(j.current){h(L=>L.kind==="server-error"?L:{kind:"ended"});return}const P=await Ke();if(!j.current){if(!P){h({kind:"server-stopped"}),k==null||k(),k=nr(2e3,()=>{j.current||window.location.reload()});return}if(T<Re){const L=T<4?1e3*Math.pow(2,T):1e4;T++,h({kind:"reconnecting",attempt:T,maxAttempts:Re}),setTimeout(()=>{j.current||M()},L)}else h({kind:"failed"})}}}try{S.fit()}catch{}M(),g.onData(C=>{const E=c.current;(E==null?void 0:E.readyState)===WebSocket.OPEN?E.send(JSON.stringify({type:"input",data:C})):m(P=>P+1)});const $=new ResizeObserver(()=>{try{S.fit();const C=c.current;(C==null?void 0:C.readyState)===WebSocket.OPEN&&C.send(JSON.stringify({type:"resize",cols:g.cols,rows:g.rows}))}catch{}});$.observe(u);function I(){var C;(C=i.current)==null||C.focus()}window.addEventListener("terminal-focus",I);function B(C){const E=C.detail,P=c.current;typeof E=="string"&&(P==null?void 0:P.readyState)===WebSocket.OPEN&&P.send(JSON.stringify({type:"input",data:E}))}return window.addEventListener("miniagent-send-input",B),()=>{var E;j.current=!0,k==null||k(),k=null,window.removeEventListener("terminal-focus",I),window.removeEventListener("miniagent-send-input",B),$.disconnect(),w(),N();const C=c.current;(C==null?void 0:C.readyState)===WebSocket.OPEN&&C.close(),(E=i.current)==null||E.dispose()}},[p]),n.jsxs("div",{"data-codeyam-hydrated":"MiniAgentChat",className:"mt-2 border border-[var(--border-subtle)] rounded-lg overflow-hidden",children:[n.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 bg-[var(--bg-card)]",children:[n.jsx("span",{className:"text-xs font-medium text-[var(--accent-active)]",children:W(p)}),s&&n.jsx("button",{onClick:s,className:"text-[var(--text-dim)] hover:text-[var(--text-primary)] text-xs bg-transparent border-none cursor-pointer",children:"Close"})]}),n.jsxs("div",{ref:o,onClick:()=>{var u;return(u=i.current)==null?void 0:u.focus()},style:{height:a,background:"#1a1a1a",padding:"6px 10px",position:"relative",overflow:"hidden"},children:[n.jsx(ur,{status:y,pulseKey:d,onRefresh:()=>window.location.reload()}),n.jsx(fr,{status:b.status,onRetry:b.retry})]})]})}function Er({provider:e,onAuthenticated:t}){const[r,a]=l.useState(""),[s,o]=l.useState(!1),[c,i]=l.useState(null),f=W(e),p=l.useCallback(async()=>{if(r.trim()){o(!0),i(null);try{const y=await fetch("/api/auth/api-key",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({provider:e,key:r.trim()})});if(!y.ok){const h=await y.json().catch(()=>({}));i(h.error??`Could not save the key (HTTP ${y.status}).`);return}a(""),t()}catch{i("Could not reach the editor to save the key.")}finally{o(!1)}}},[r,e,t]);return n.jsxs("div",{"data-testid":"api-key-flow",className:"space-y-3",children:[n.jsxs("p",{className:"text-sm text-[#8E8E8E]",children:["Paste your ",f," API key. It is stored locally in",n.jsx("code",{className:"mx-1 text-[#D7FF63]",children:".codeyam/editor.local.json"}),"and never committed."]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("input",{type:"password",value:r,onChange:y=>a(y.target.value),placeholder:`${f} API key`,className:"flex-1 min-w-0 px-2 py-1.5 rounded bg-black border border-[#3A3A3A] text-white text-sm"}),n.jsx("button",{onClick:()=>void p(),disabled:s||!r.trim(),className:"px-3 py-1.5 text-sm rounded-md bg-[#D7FF63] text-black font-medium cursor-pointer disabled:opacity-50",children:s?"Saving…":"Save"})]}),c?n.jsx("p",{className:"text-sm text-[#FF8B43]",children:c}):null]})}const Tr=500,Ar=2e4;function Dr({onAuthenticated:e}){const[t,r]=l.useState({state:"starting"}),[a,s]=l.useState(""),[o,c]=l.useState(!1),[i,f]=l.useState(!1),[p,y]=l.useState(!1),[h,d]=l.useState(!1),m=l.useRef(!1),x=l.useCallback(async()=>{try{const w=await fetch("/api/auth/status");if(!w.ok)return;const N=await w.json();r(N),N.state==="authenticated"&&!m.current&&(m.current=!0,e())}catch{}},[e]),b=l.useCallback(async()=>{m.current=!1,y(!1),r({state:"starting"});try{await fetch("/api/auth/start",{method:"POST"})}catch{r({state:"failed",error:"Could not start the login process."})}},[]);l.useEffect(()=>{b();const w=window.setInterval(()=>void x(),Tr);return()=>window.clearInterval(w)},[b,x]),l.useEffect(()=>{if(t.state!=="starting"){y(!1);return}const w=window.setTimeout(()=>y(!0),Ar);return()=>window.clearTimeout(w)},[t.state]);const v=l.useCallback(async()=>{if(a.trim()){c(!0);try{const w=await fetch("/api/auth/code",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({code:a.trim()})});if(w.ok)s("");else{const N=await w.json().catch(()=>({}));r({state:"failed",error:N.error??"Code not accepted — check the value and try again."})}}catch{r({state:"failed",error:"Could not submit the code."})}finally{c(!1)}}},[a]),u=l.useCallback(async()=>{try{await fetch("/api/auth/cancel",{method:"POST"})}catch{}b()},[b]),g=l.useCallback(async()=>{d(!0);try{await fetch("/api/auth/refresh-cache",{method:"POST"}),e()}catch{}finally{d(!1)}},[e]),S=l.useCallback(()=>{var w;t.url&&((w=navigator.clipboard)==null||w.writeText(t.url),f(!0),window.setTimeout(()=>f(!1),1500))},[t.url]);return p&&t.state==="starting"?n.jsxs("div",{"data-testid":"claude-oauth-timeout",className:"space-y-3",children:[n.jsxs("p",{className:"text-sm text-[#FF8B43]",children:["Login link preparation timed out — the backend may be wedged. Try again, recheck if you already authenticated elsewhere, or open a terminal and run ",n.jsx("code",{className:"text-white",children:"claude /login"})," ","directly."]}),n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsx("button",{onClick:()=>void u(),"data-testid":"claude-oauth-timeout-retry",className:"px-3 py-2 text-sm rounded-md bg-[#D7FF63] text-black font-medium cursor-pointer",children:"Retry"}),n.jsx("button",{onClick:()=>void g(),"data-testid":"claude-oauth-timeout-recheck",disabled:h,className:"px-3 py-2 text-sm rounded-md border border-[#3A3A3A] text-white cursor-pointer disabled:opacity-50",children:h?"Rechecking…":"I already logged in — recheck"})]})]}):t.state==="failed"?n.jsxs("div",{"data-testid":"claude-oauth-failed",className:"space-y-3",children:[n.jsx("p",{className:"text-sm text-[#FF8B43]",children:t.error??"Login failed."}),n.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[n.jsx("button",{onClick:()=>void u(),className:"px-3 py-2 text-sm rounded-md bg-[#D7FF63] text-black font-medium cursor-pointer",children:"Try again"}),n.jsx("button",{onClick:()=>void g(),"data-testid":"claude-oauth-failed-recheck",disabled:h,className:"px-3 py-2 text-sm rounded-md border border-[#3A3A3A] text-white cursor-pointer disabled:opacity-50",children:h?"Rechecking…":"I already logged in — recheck"})]})]}):t.state==="authenticated"?n.jsx("p",{"data-testid":"claude-oauth-authenticated",className:"text-sm text-[#D7FF63]",children:"Connected. Opening Build…"}):t.state==="url-ready"&&t.url?n.jsxs("div",{"data-testid":"claude-oauth-url-ready",className:"space-y-3",children:[n.jsx("p",{className:"text-sm text-[#8E8E8E]",children:"Open this URL in your browser, approve access, then paste the code back here:"}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("code",{className:"flex-1 min-w-0 truncate px-2 py-1.5 rounded bg-black text-[#D7FF63] text-xs",children:t.url}),n.jsx("button",{onClick:S,className:"px-2 py-1.5 text-xs rounded-md border border-[#3A3A3A] text-white cursor-pointer",children:i?"Copied":"Copy"}),n.jsx("a",{href:t.url,target:"_blank",rel:"noreferrer",className:"px-2 py-1.5 text-xs rounded-md border border-[#3A3A3A] text-white cursor-pointer",children:"Open"})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("input",{type:"text",value:a,onChange:w=>s(w.target.value),placeholder:"Paste the code from the browser here",className:"flex-1 min-w-0 px-2 py-1.5 rounded bg-black border border-[#3A3A3A] text-white text-sm"}),n.jsx("button",{onClick:()=>void v(),disabled:o||!a.trim(),className:"px-3 py-1.5 text-sm rounded-md bg-[#D7FF63] text-black font-medium cursor-pointer disabled:opacity-50",children:o?"Submitting…":"Submit"})]})]}):n.jsx("p",{"data-testid":"claude-oauth-starting",className:"text-sm text-[#8E8E8E]",children:"Preparing the login link…"})}function Or({provider:e,onAuthenticated:t,onClose:r}){const a=W(e);return n.jsx("div",{"data-testid":"provider-auth-modal",className:"fixed inset-0 z-[100] flex items-center justify-center",style:{background:"rgba(30, 30, 30, 0.90)"},children:n.jsxs("div",{className:"w-[32rem] max-w-[90vw] rounded-lg border border-[#3A3A3A] bg-[#1E1E1E] p-6 space-y-4",children:[n.jsxs("div",{className:"flex items-start justify-between",children:[n.jsxs("h2",{className:"text-base font-medium text-white",children:["Connect your ",a," account"]}),n.jsx("button",{onClick:r,"aria-label":"Close",className:"text-[#8E8E8E] hover:text-white cursor-pointer",children:"✕"})]}),e==="claude"?n.jsx(Dr,{onAuthenticated:t}):n.jsx(Er,{provider:e,onAuthenticated:t})]})})}function Mr(e){const t=new Date(e).getTime()-Date.now(),r=Math.abs(Math.round(t/36e5));if(r<1)return t<0?"just now":"very soon";if(r<48)return t<0?`${r} h ago`:`in ${r} h`;const a=Math.round(r/24);return t<0?`${a} d ago`:`in ${a} d`}function Rr({provider:e,credsPresent:t=!0,reason:r=null,expiresAt:a=null,sessionOngoing:s=!1,onAuthenticated:o,onAuthorized:c}){const[i,f]=l.useState(!1),[p,y]=l.useState(!1),h=W(e),d=l.useCallback(()=>{f(!1),o(),c==null||c()},[o,c]),m=l.useCallback(async()=>{y(!0);try{await fetch("/api/auth/refresh-cache",{method:"POST"}),o()}catch{}finally{y(!1)}},[o]),x=e==="claude"&&!t,b=a?` (token expired ${Mr(a)})`:"",v=x?`${h} credentials file is missing`:r==="token-expired"?`Your ${h} token has expired`:r==="api-401"?`${h} authentication rejected (401)`:`Connect your ${h} account`,u=s?" Your Build session stays open — you can finish logging in here or directly in the Build terminal.":"",g=x?"The editor couldn't find ~/.claude/.credentials.json on this machine — likely deleted between editor restarts (operator-side action, a Reconfigure, or a stale image). Re-seed by clicking Authenticate to run OAuth, or — on a fleet VM — copy the file from a donor VM through the dashboard.":r==="token-expired"?`Your ${h} token has expired${b} — click Authenticate to refresh it. On a fleet VM the dashboard can copy a fresh token from a donor VM.${u}`:r==="api-401"?`The ${h} server rejected your credentials (401)${b}. This usually means the token was revoked or expired. Click Authenticate to re-connect.${u}`:s?"You can finish logging in here or directly in the Build terminal — your session stays open either way. On a cloud VM the dashboard usually does this for you; locally you connect once here.":`Authentication used to happen inside the Build terminal. Now it lives here, out of your way. Connect ${h} to unlock the Build tab. On a cloud VM the dashboard usually does this for you; locally you connect once here.`;return n.jsxs("div",{"data-testid":"provider-auth-gate","data-auth-variant":x?"creds-missing":"needs-login","data-auth-card":!0,className:"m-4 rounded-lg border border-[#D7FF63]/40 bg-[#1E1E1E] p-5 space-y-3",children:[n.jsx("h2",{className:"text-base font-medium text-white",children:v}),n.jsx("p",{className:"text-sm text-[#8E8E8E]",children:g}),n.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[n.jsx("button",{onClick:()=>f(!0),className:"px-3 py-2 text-sm rounded-md bg-[#D7FF63] text-black font-medium cursor-pointer",children:"Authenticate"}),n.jsx("button",{onClick:()=>void m(),"data-testid":"provider-auth-gate-recheck",disabled:p,className:"px-3 py-2 text-sm rounded-md border border-[#3A3A3A] text-white cursor-pointer disabled:opacity-50",children:p?"Rechecking…":"Already logged in? Recheck"})]}),i?n.jsx(Or,{provider:e,onAuthenticated:d,onClose:()=>f(!1)}):null]})}let ue=!1;function Pr(e){const{state:t,provider:r,credsPresent:a,reason:s,expiresAt:o,refresh:c}=_t(),[i]=l.useState(()=>ue);return l.useEffect(()=>{t==="authenticated"?ue=!0:t==="needs-login"&&(ue=!1)},[t]),t==="needs-login"?n.jsx(Rr,{provider:r,credsPresent:a,reason:s,expiresAt:o,onAuthenticated:()=>void c(),onAuthorized:()=>{}}):t==="authenticated"||i?n.jsx(Nr,{...e}):n.jsxs("div",{"data-testid":"gated-agent-chat-checking",className:"mt-2 flex items-center gap-3 rounded-lg border border-[var(--border-subtle)] px-3 py-4",children:[n.jsx("span",{"aria-hidden":"true",className:"h-4 w-4 rounded-full border-2 border-[var(--text-dim)] border-t-transparent animate-spin"}),n.jsx("span",{className:"text-xs text-[var(--text-dim)]",children:"Checking your account…"})]})}function $r(){return n.jsx("div",{className:"flex h-full items-center justify-center p-6",children:n.jsxs("div",{className:"max-w-xs text-center space-y-2",children:[n.jsx("p",{className:"text-sm text-[var(--text-muted)]",children:"No scenario data yet."}),n.jsx("p",{className:"text-xs text-[var(--text-dim)]",children:"Seed data and HTTP mocks will appear here as the scenario captures them, or add them with the scenario editor."})]})})}function Ir({variant:e,onClose:t}){return e!=="slideOver"?null:n.jsx("button",{onClick:t,className:"rounded border border-[var(--border-default)] bg-transparent px-2 py-1 text-xs text-[var(--text-muted)] hover:text-[var(--text-primary)] cursor-pointer",children:"Close"})}function Lr({variant:e,providerLabel:t,chatOpen:r,onToggleChat:a}){const s=e==="inline",o=s?"flex items-center gap-1.5 px-3 py-1.5 rounded border text-xs font-medium cursor-pointer transition-colors":"flex items-center gap-1.5 px-2.5 py-1 rounded border text-xs cursor-pointer transition-colors",c=r?"border-[var(--accent-active)] bg-[var(--accent-active)]/15 text-[var(--accent-active)]":s?"border-[var(--accent-active)] bg-[var(--accent-active)] text-black hover:bg-[var(--accent-active)]/90":"border-[var(--border-default)] bg-transparent text-[var(--text-muted)] hover:text-[var(--text-primary)] hover:border-[var(--accent-active)]/40";return n.jsxs("button",{type:"button",onClick:a,className:`${o} ${c}`,title:`Open a chat with ${t} seeded with this scenario's context`,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 ",t]})}const be=new Set,ye=new Set;let He={isActive:!1,previewSlug:null};function Br(){for(const e of be)e()}function Vn(e){return be.add(e),()=>{be.delete(e)}}function Yn(e){He=e;for(const t of ye)t(e)}function Kr(e){return ye.add(e),()=>{ye.delete(e)}}function Pe(){return He}function Fr(){const[e,t]=l.useState(()=>Pe());return l.useEffect(()=>(t(Pe()),Kr(t)),[]),e}function _r({panelSlug:e,scenarioState:t}){const r=Fr(),{isActive:a,previewSlug:s}=t??r;return s!==e?null:n.jsxs("button",{type:"button","aria-pressed":a,onClick:()=>Br(),title:a?"Exit inspect data source":"Inspect data source — click a value in the live preview to see its mock",className:a?"flex items-center gap-1.5 px-2.5 py-1 rounded border text-xs cursor-pointer transition-colors border-[var(--accent-active)] bg-[var(--accent-active)]/15 text-[var(--accent-active)]":"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",children:[n.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("circle",{cx:"11",cy:"11",r:"8"}),n.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),a?"Inspecting…":"Inspect data"]})}function Hr({variant:e,slug:t}){const r=()=>window.open(qe(t),"_blank");return e==="slideOver"?n.jsx("button",{type:"button",onClick:r,className:"p-1.5 rounded text-[var(--text-dim)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-card)] transition-colors cursor-pointer",title:"Open 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"})]})}):e==="inline"?n.jsxs("button",{type:"button",onClick:r,className:"flex items-center gap-1.5 px-2.5 py-1 rounded border border-[var(--border-default)] bg-transparent text-xs text-[var(--text-muted)] hover:text-[var(--text-primary)] hover:border-[var(--accent-active)]/40 transition-colors cursor-pointer",title:"Open the full data editor in a new browser tab",children:[n.jsxs("svg",{width:"12",height:"12",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"})]}),"Open in new tab"]}):null}function Vr(e){if(!e)return"Unsaved changes";const t=[];e.mocks.length>0&&t.push(`${e.mocks.length} mock${e.mocks.length===1?"":"s"}`);const r=e.seed.length;return r>0&&t.push(`${r} seed ${r===1?"table":"tables"}`),t.length>0?`Unsaved changes (${t.join(", ")})`:"Unsaved changes"}function Yr({diff:e,saving:t,cancelling:r,error:a,onSave:s,onCancel:o}){return n.jsxs("div",{className:"flex items-center justify-between gap-2 rounded border border-amber-500/40 bg-amber-500/10 px-2 py-1.5","data-testid":"scenario-draft-bar",children:[n.jsx("span",{className:"text-xs text-amber-300 font-medium",children:Vr(e)}),n.jsxs("div",{className:"flex items-center gap-2",children:[a&&n.jsx("span",{className:"text-xs text-red-400",children:a}),n.jsx("button",{type:"button",onClick:o,disabled:r||t,className:"px-2 py-0.5 text-xs rounded border border-[var(--border-default)] bg-[var(--bg-surface)] text-[var(--text-primary)] hover:bg-[var(--bg-input)] disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer",children:r?"Discarding…":"Cancel"}),n.jsx("button",{type:"button",onClick:s,disabled:r||t,className:"px-3 py-0.5 text-xs rounded border border-[var(--accent-blue)] bg-[var(--accent-blue)]/20 text-[var(--accent-blue)] hover:bg-[var(--accent-blue)]/30 disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer",children:t?"Saving…":"Save"})]})]})}function Ur({title:e,slug:t,provider:r,chatOpen:a,onToggleChat:s,variant:o,onClose:c,draftDirty:i,draftDiff:f,draftSaving:p,draftCancelling:y,draftError:h,onSave:d,onCancel:m}){const x=W(r),b=!!i&&!!d&&!!m;return n.jsxs("header",{className:"flex flex-col gap-2 border-b border-[var(--border-subtle)] bg-[var(--bg-deep)] px-4 py-3",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("div",{className:"min-w-0",children:n.jsxs("h2",{className:"text-sm font-medium text-[var(--text-primary)] truncate",children:["Scenario data: ",e]})}),n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx(Lr,{variant:o,providerLabel:x,chatOpen:a,onToggleChat:s}),n.jsx(_r,{panelSlug:t}),n.jsx(Hr,{variant:o,slug:t}),c&&n.jsx(Ir,{variant:o,onClose:c})]})]}),b&&d&&m&&n.jsx(Yr,{diff:f??null,saving:p??!1,cancelling:y??!1,error:h??null,onSave:d,onCancel:m})]})}function Xr(e,t){const[r,a]=l.useState(e.status??200),[s,o]=l.useState(e.body??null),[c,i]=l.useState(()=>Object.entries(e.headers??{}).map(([h,d])=>({name:h,value:d})));l.useEffect(()=>{a(e.status??200),o(e.body??null),i(Object.entries(e.headers??{}).map(([h,d])=>({name:h,value:d})))},[t,e.status,e.body,e.headers]);const f=l.useMemo(()=>e.headers??{},[e.headers]),p=l.useMemo(()=>{if((e.status??200)!==r||JSON.stringify(e.body??null)!==JSON.stringify(s))return!0;const h={};for(const b of c)b.name.trim()&&(h[b.name.trim()]=b.value);const d=f,m=Object.keys(d),x=Object.keys(h);if(m.length!==x.length)return!0;for(const b of x)if(d[b]!==h[b])return!0;return!1},[r,s,c,e.status,e.body,f]);return{status:r,setStatus:a,body:s,setBody:o,headers:c,setHeaders:i,isDirty:p,buildPayload:()=>{const h={};for(const d of c)d.name.trim()&&(h[d.name.trim()]=d.value);return{status:r,body:s,headers:h}}}}const Jr=e=>navigator.clipboard.writeText(e);function Wr(e={}){const{writer:t=Jr,resetMs:r=2e3}=e,[a,s]=l.useState(!1),o=l.useRef(null),c=l.useCallback(async i=>{await t(i),s(!0),o.current!==null&&clearTimeout(o.current),o.current=setTimeout(()=>{s(!1),o.current=null},r)},[t,r]);return{copied:a,copy:c}}function zr({body:e,onBodyChange:t}){const{copied:r,copy:a}=Wr();async function s(){try{const c=await navigator.clipboard.readText(),i=JSON.parse(c);t(i)}catch{}}function o(){a(JSON.stringify(e,null,2))}return n.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[n.jsx("button",{type:"button",onClick:()=>void s(),className:"text-[10px] px-2 py-0.5 rounded border border-[var(--border-default)] bg-transparent text-[var(--text-muted)] hover:text-[var(--text-primary)] cursor-pointer",children:"Paste"}),n.jsx("button",{type:"button",onClick:o,className:"text-[10px] px-2 py-0.5 rounded border border-[var(--border-default)] bg-transparent text-[var(--text-muted)] hover:text-[var(--text-primary)] cursor-pointer",children:r?"Copied":"Copy"})]})}function z(e){return JSON.stringify(e)}function Ve(e,t){return e?e instanceof Set?e.has(t):e.includes(t):!1}function qr(e){const t=new Set;function r(a,s){if(a!==null&&typeof a=="object")if(t.add(z(s)),Array.isArray(a))a.forEach((o,c)=>r(o,[...s,c]));else for(const[o,c]of Object.entries(a))r(c,[...s,o])}return r(e,[]),t}function Gr(e){return e===null?"text-slate-400 italic":typeof e=="string"?"text-emerald-300":typeof e=="number"?"text-amber-300":typeof e=="boolean"?"text-[#D7FF63]":"text-[var(--text-primary)]"}function Qr(e){return e===null?"null":typeof e=="string"?`"${e}"`:String(e)}function Zr(e){return e===null?"null":typeof e=="string"?e:String(e)}function en(e){const t=e.trim();if(t==="")return"";if(t==="null")return null;if(t==="true")return!0;if(t==="false")return!1;try{return JSON.parse(t)}catch{return e}}function te(e){return JSON.parse(JSON.stringify(e))}function tn(e,t,r){if(t.length===0)return r;const a=te(e);let s=a;for(let o=0;o<t.length-1;o++)s=s[t[o]];return s[t[t.length-1]]=r,a}function we(e,t){if(t.length===0)return e;const r=te(e);let a=r;for(let o=0;o<t.length-1;o++)a=a[t[o]];const s=t[t.length-1];return Array.isArray(a)?a.splice(s,1):delete a[s],r}function rn(e,t){const r=te(e);let a=r;for(const s of t)a=a[s];return Array.isArray(a)&&a.push(null),r}function nn(e,t,r){const a=te(e);let s=a;for(const o of t)s=s[o];return s&&typeof s=="object"&&!Array.isArray(s)&&(s[r]=""),a}function an(e){if(typeof e!="string"||e.length===0||e!=="$"&&!e.startsWith("$.")&&!e.startsWith("$["))return null;const t=[];let r=e[0]==="$"?1:0;for(;r<e.length;){const a=e[r];if(a==="."){r+=1;const s=r;for(;r<e.length&&e[r]!=="."&&e[r]!=="[";)r+=1;const o=e.slice(s,r);if(o.length===0)return null;t.push(o)}else if(a==="["){const s=e.indexOf("]",r);if(s===-1)return null;const o=e.slice(r+1,s);if(o.length===0)return null;const c=Number(o);if(!Number.isInteger(c)||c<0)return null;t.push(c),r=s+1}else return null}return t}function sn(e,t){l.useEffect(()=>{if(!e)return;const r=an(e);r&&t(a=>{const s=new Set(a);for(let o=0;o<r.length;o++)s.add(z(r.slice(0,o)));return s})},[e,t])}function je({collapsible:e,isOpen:t,onToggle:r,parentKey:a,readOnly:s,onRemove:o,children:c}){return n.jsxs("div",{className:"group/row flex items-center gap-1 min-h-[1.5em] hover:bg-[var(--bg-card)]/30 rounded px-1",children:[e?n.jsx("button",{type:"button",onClick:r,className:"w-4 h-4 flex items-center justify-center text-[var(--text-dim)] hover:text-[var(--text-primary)] bg-transparent border-none cursor-pointer p-0","aria-label":t?"Collapse":"Expand",children:n.jsx("span",{className:"text-[10px]",children:t?"▾":"▸"})}):n.jsx("span",{className:"w-4"}),a!==null&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"text-cyan-300",children:typeof a=="number"?`[${a}]`:a}),n.jsx("span",{className:"text-[var(--text-dim)]",children:":"})]}),n.jsx("div",{className:"flex-1 min-w-0 flex items-center gap-1",children:c}),!s&&o&&n.jsx("button",{type:"button",onClick:o,className:"opacity-0 group-hover/row:opacity-100 text-[10px] text-[var(--text-dim)] hover:text-red-400 bg-transparent border-none cursor-pointer px-1",title:"Remove",children:"×"})]})}function on(e){const{value:t,path:r,parentKey:a,expanded:s,onToggle:o,readOnly:c}=e,i=z(r),f=Ve(s,i),p=t.length>0;return n.jsxs("div",{children:[n.jsxs(je,{collapsible:p,isOpen:f,onToggle:()=>o(i),parentKey:a,readOnly:c,onRemove:r.length>0?()=>e.onValueChange(we(e.rootValue,r)):null,children:[n.jsx("span",{className:"text-[var(--text-dim)]",children:"["}),!f&&n.jsxs(n.Fragment,{children:[p&&n.jsxs("span",{className:"text-[var(--text-dim)] italic",children:[" ","…",t.length," item",t.length===1?"":"s"," "]}),n.jsx("span",{className:"text-[var(--text-dim)]",children:"]"})]})]}),f&&n.jsxs("div",{className:"ml-4 border-l border-[var(--border-subtle)] pl-2",children:[t.map((y,h)=>l.createElement(ke,{...e,key:h,value:y,path:[...r,h],parentKey:h,isLast:h===t.length-1})),!c&&n.jsx("button",{type:"button",onClick:()=>e.onValueChange(rn(e.rootValue,r)),className:"text-[10px] text-[var(--accent-blue)] hover:underline bg-transparent border-none cursor-pointer py-0.5",children:"+ Add item"})]}),f&&n.jsx("div",{className:"text-[var(--text-dim)]",children:"]"})]})}function cn({onSave:e,onCancel:t}){const[r,a]=l.useState("");return n.jsxs("div",{className:"flex items-center gap-1 py-0.5",children:[n.jsx("span",{className:"text-[var(--text-dim)] text-[10px]",children:"+ key:"}),n.jsx("input",{autoFocus:!0,value:r,onChange:s=>a(s.target.value),onBlur:()=>e(r),onKeyDown:s=>{s.key==="Enter"?(s.preventDefault(),e(r)):s.key==="Escape"&&(s.preventDefault(),t())},placeholder:"keyName",className:"rounded border border-[var(--accent-active)]/50 bg-[var(--bg-surface)] px-1 py-0 text-xs font-mono text-[var(--text-primary)] min-w-[6rem]"})]})}function ln(e){const{value:t,path:r,parentKey:a,expanded:s,onToggle:o,readOnly:c,addingKeyAtPath:i,onStartAddKey:f,onStopAddKey:p}=e,y=z(r),h=Ve(s,y),d=Object.entries(t),m=d.length>0,x=i===y;return n.jsxs("div",{children:[n.jsxs(je,{collapsible:m,isOpen:h,onToggle:()=>o(y),parentKey:a,readOnly:c,onRemove:r.length>0?()=>e.onValueChange(we(e.rootValue,r)):null,children:[n.jsx("span",{className:"text-[var(--text-dim)]",children:"{"}),!h&&n.jsxs(n.Fragment,{children:[m&&n.jsxs("span",{className:"text-[var(--text-dim)] italic",children:[" ","…",d.length," key",d.length===1?"":"s"," "]}),n.jsx("span",{className:"text-[var(--text-dim)]",children:"}"})]})]}),h&&n.jsxs("div",{className:"ml-4 border-l border-[var(--border-subtle)] pl-2",children:[d.map(([b,v],u)=>l.createElement(ke,{...e,key:b,value:v,path:[...r,b],parentKey:b,isLast:u===d.length-1})),!c&&!x&&n.jsx("button",{type:"button",onClick:()=>f(y),className:"text-[10px] text-[var(--accent-blue)] hover:underline bg-transparent border-none cursor-pointer py-0.5",children:"+ Add key"}),!c&&x&&n.jsx(cn,{onSave:b=>{b.trim()&&e.onValueChange(nn(e.rootValue,r,b.trim())),p()},onCancel:p})]}),h&&n.jsx("div",{className:"text-[var(--text-dim)]",children:"}"})]})}function dn({initial:e,onSave:t,onCancel:r}){const[a,s]=l.useState(e);return n.jsx("input",{autoFocus:!0,value:a,onChange:o=>s(o.target.value),onBlur:()=>t(a),onKeyDown:o=>{o.key==="Enter"?(o.preventDefault(),t(a)):o.key==="Escape"&&(o.preventDefault(),r())},className:"flex-1 min-w-[4rem] rounded border border-[var(--accent-active)]/50 bg-[var(--bg-surface)] px-1 py-0 text-xs font-mono text-[var(--text-primary)]"})}function un(e){const{value:t,path:r,parentKey:a,readOnly:s,editingPath:o,onStartEdit:c,onStopEdit:i}=e,f=z(r),p=o===f;return n.jsx(je,{collapsible:!1,isOpen:!1,parentKey:a,readOnly:s,onToggle:()=>{},onRemove:r.length>0?()=>e.onValueChange(we(e.rootValue,r)):null,children:p?n.jsx(dn,{initial:Zr(t),onSave:y=>{const h=en(y);e.onValueChange(tn(e.rootValue,r,h)),i()},onCancel:i}):n.jsx("button",{type:"button",onClick:s?void 0:()=>c(f),disabled:s,className:`${s?"":"hover:bg-[var(--bg-card)] cursor-pointer"} bg-transparent border-none px-1 py-0 rounded ${Gr(t)} text-left font-mono`,title:s?void 0:"Click to edit",children:Qr(t)})})}function ke(e){const{value:t}=e;return Array.isArray(t)?n.jsx(on,{...e,value:t}):t!==null&&typeof t=="object"?n.jsx(ln,{...e,value:t}):n.jsx(un,{...e})}function Se({value:e,onChange:t,readOnly:r=!1,focusJsonPath:a}){const[s,o]=l.useState(()=>qr(e)),[c,i]=l.useState(null),[f,p]=l.useState(null);sn(a,o);function y(h){o(d=>{const m=new Set(d);return m.has(h)?m.delete(h):m.add(h),m})}return n.jsx("div",{className:"flex flex-col h-full min-h-0",children:n.jsx("div",{className:"flex-1 min-h-0 overflow-auto font-mono text-xs leading-relaxed text-[var(--text-primary)] bg-[var(--bg-input)] border border-[var(--border-default)] rounded p-3",children:n.jsx(ke,{value:e,path:[],parentKey:null,isLast:!0,readOnly:r,expanded:s,editingPath:c,addingKeyAtPath:f,onToggle:y,onStartEdit:i,onStopEdit:()=>i(null),onStartAddKey:p,onStopAddKey:()=>p(null),onValueChange:t,rootValue:e})})})}function fn({headers:e,onChange:t}){function r(o,c){t(e.map((i,f)=>f===o?{...i,...c}:i))}function a(){t([...e,{name:"",value:""}])}function s(o){t(e.filter((c,i)=>i!==o))}return n.jsxs("div",{className:"space-y-1",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("label",{className:"text-xs text-[var(--text-muted)]",children:"Headers"}),n.jsx("button",{type:"button",onClick:a,className:"text-xs text-[var(--accent-blue)] hover:underline bg-transparent border-none cursor-pointer",children:"+ Add"})]}),e.length===0&&n.jsx("p",{className:"text-xs text-[var(--text-dim)] italic",children:"No headers"}),e.map((o,c)=>n.jsxs("div",{className:"flex gap-2",children:[n.jsx("input",{value:o.name,onChange:i=>r(c,{name:i.target.value}),placeholder:"Name",className:"flex-1 rounded border border-[var(--border-default)] bg-[var(--bg-surface)] px-2 py-1 text-xs font-mono"}),n.jsx("input",{value:o.value,onChange:i=>r(c,{value:i.target.value}),placeholder:"Value",className:"flex-1 rounded border border-[var(--border-default)] bg-[var(--bg-surface)] px-2 py-1 text-xs font-mono"}),n.jsx("button",{type:"button",onClick:()=>s(c),className:"px-2 text-xs text-[var(--text-dim)] hover:text-red-400 bg-transparent border-none cursor-pointer",children:"×"})]},c))]})}const fe=5;function pn(e,t){if(e==="loading")return"Computing impact…";if(e==null)return"";if(t.kind==="scenario")return"Affects only this scenario.";if(e.length===0)return"Affects no other scenarios.";const r=e.length===1?"scenario":"scenarios",a=e.slice(0,fe).join(", "),s=e.length>fe?`, +${e.length-fe} more`:"";return`Affects ${e.length} ${r}: ${a}${s}`}function hn(e){const t=[{label:"This scenario only",description:"Write to this scenario's mocks file. The row's source flips to scenario.",scope:{kind:"scenario"}}];return e.source==="shared"&&e.sharedSlug&&t.push({label:`Shared data set "${e.sharedSlug}"`,description:"Write to the shared set this row came from. Affects every scenario opted into it.",scope:{kind:"shared",slug:e.sharedSlug}}),(e.source==="default"||e.source==="shared")&&t.push({label:"Defaults",description:"Write to _default.json. Affects every scenario that falls through to defaults for this route.",scope:{kind:"default"}}),t}function mn(e,t){if(e.source==="default"){const r=t.findIndex(a=>a.scope.kind==="default");if(r>=0)return r}if(e.source==="shared"){const r=t.findIndex(a=>a.scope.kind==="shared"&&a.scope.slug===(e.sharedSlug??""));if(r>=0)return r}return 0}function xn(e,t,r){const[a,s]=l.useState({}),o=r.map(c=>_(c.scope)).join("|");return l.useEffect(()=>{let c=!1;return(async()=>{const f={};for(const p of r)f[_(p.scope)]="loading";s(f);for(const p of r)try{const y=await ot(e,t,p.scope);if(c)return;s(h=>({...h,[_(p.scope)]:y}))}catch{if(c)return;s(y=>({...y,[_(p.scope)]:[]}))}})(),()=>{c=!0}},[e,t,o]),a}function bn({choice:e,selected:t,impactLabel:r,onSelect:a}){return n.jsxs("label",{className:`flex cursor-pointer flex-col rounded border p-3 text-xs transition-colors ${t?"border-violet-500 bg-violet-500/10":"border-[var(--border-subtle)] hover:bg-[var(--bg-elevated)]"}`,children:[n.jsxs("span",{className:"flex items-center gap-2",children:[n.jsx("input",{type:"radio",name:"save-scope",checked:t,onChange:a}),n.jsx("span",{className:"font-medium text-[var(--text-primary)]",children:e.label})]}),n.jsx("span",{className:"mt-1 pl-6 text-[var(--text-muted)]",children:e.description}),n.jsx("span",{className:"mt-1 pl-6 text-[var(--text-dim)] italic",children:r})]})}function yn({entry:e,scenarioSlug:t,routeKey:r,onCancel:a,onConfirm:s}){const o=hn(e),[c,i]=l.useState(()=>mn(e,o)),f=xn(t,r,o),[p,y]=l.useState(!1),[h,d]=l.useState(null),m=async()=>{const x=o[c];if(x){y(!0),d(null);try{await s(x.scope)}catch(b){d(b instanceof Error?b.message:"Save failed")}finally{y(!1)}}};return n.jsx("div",{role:"dialog","aria-modal":"true","aria-labelledby":"save-scope-modal-title",className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",children:n.jsxs("div",{className:"w-[28rem] max-w-[90vw] rounded-lg border border-[var(--border-default)] bg-[var(--bg-surface)] p-5 shadow-xl",children:[n.jsx("h2",{id:"save-scope-modal-title",className:"text-sm font-semibold text-[var(--text-primary)]",children:"Where should this save land?"}),n.jsx("p",{className:"mt-1 text-xs text-[var(--text-muted)]",children:r}),n.jsx("div",{className:"mt-4 space-y-2",children:o.map((x,b)=>n.jsx(bn,{choice:x,selected:c===b,impactLabel:pn(f[_(x.scope)],x.scope),onSelect:()=>i(b)},_(x.scope)))}),h&&n.jsx("p",{className:"mt-3 text-xs text-red-400",role:"alert",children:h}),n.jsxs("div",{className:"mt-5 flex justify-end gap-2",children:[n.jsx("button",{type:"button",onClick:a,disabled:p,className:"rounded border border-[var(--border-default)] px-3 py-1.5 text-xs text-[var(--text-primary)] hover:bg-[var(--bg-elevated)] disabled:opacity-50",children:"Cancel"}),n.jsx("button",{type:"button",onClick:()=>void m(),disabled:p,className:"rounded bg-violet-500 px-3 py-1.5 text-xs font-medium text-white hover:bg-violet-400 disabled:opacity-50",children:p?"Saving…":"Save"})]})]})})}function gn({entry:e,routeKey:t,scenarioSlug:r,onSave:a,focusJsonPath:s}){const o=Xr(e,t),[c,i]=l.useState(null),[f,p]=l.useState(!1),[y,h]=l.useState(!1);l.useEffect(()=>{i(null),h(!1)},[t]);const d=async x=>{p(!0),i(null);try{const b=o.buildPayload();await a({routeKey:t,...b,scope:x})}catch(b){throw i(b instanceof Error?b.message:"Save failed"),b}finally{p(!1)}},m=async()=>{if(o.isDirty){if(e.source==="scenario"){try{await d({kind:"scenario"})}catch{}return}h(!0)}};return n.jsxs("div",{className:"flex flex-col gap-3 h-full min-h-0",children:[c&&n.jsx("p",{className:"text-xs text-red-400",children:c}),n.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[n.jsx("label",{className:"text-xs text-[var(--text-muted)]",children:"Status"}),n.jsx("input",{type:"number",value:o.status,onChange:x=>o.setStatus(Number(x.target.value)),className:"w-20 rounded border border-[var(--border-default)] bg-[var(--bg-surface)] px-2 py-1 text-xs font-mono"}),n.jsx("div",{className:"flex-1"}),n.jsx("button",{type:"button",onClick:()=>void m(),disabled:!o.isDirty||f,className:"rounded bg-violet-500 px-3 py-1 text-xs font-medium text-white hover:bg-violet-400 disabled:opacity-50",children:f?"Saving…":o.isDirty?"Save changes":"Saved"})]}),n.jsx(fn,{headers:o.headers,onChange:o.setHeaders}),n.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",children:[n.jsxs("div",{className:"flex items-center gap-2 pb-1",children:[n.jsx("label",{className:"text-xs text-[var(--text-muted)]",children:"Body"}),n.jsx(zr,{body:o.body,onBodyChange:o.setBody})]}),n.jsx(Se,{value:o.body,onChange:o.setBody,focusJsonPath:s},t)]}),y&&n.jsx(yn,{entry:e,scenarioSlug:r,routeKey:t,onCancel:()=>h(!1),onConfirm:async x=>{await d(x),h(!1)}})]})}function vn(e,t){if(e==null)return"never";const r=Math.max(0,Math.floor((t-e)/1e3));if(r<60)return`${r}s ago`;const a=Math.floor(r/60);return a<60?`${a}m ago`:`${Math.floor(a/60)}h ago`}const $e={GET:"text-emerald-400 border-emerald-400/40",POST:"text-[#D7FF63] border-[#D7FF63]/40",PUT:"text-amber-400 border-amber-400/40",PATCH:"text-purple-400 border-purple-400/40",DELETE:"text-red-400 border-red-400/40"};function wn(e){return $e[e]??$e.GET}function jn({entry:e,scenarioHasDefaultFallback:t,onSave:r,onRemove:a,onPassthrough:s}){const o=`${e.method} ${e.pathPattern}`,c=wn(e.method),i=e.status??e.lastObservedStatus,f=l.useMemo(()=>e.lastObservedMs?vn(e.lastObservedMs,Date.now()):null,[e.lastObservedMs]),p="px-3 py-1 rounded border border-[var(--border-default)] bg-transparent text-[var(--text-muted)] hover:text-[var(--text-primary)] cursor-pointer text-xs";return n.jsxs("header",{className:"border-b border-[var(--border-subtle)] bg-[var(--bg-deep)] px-4 py-3 space-y-2 flex-shrink-0",children:[n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[n.jsx("span",{className:`px-2 py-0.5 rounded border font-mono text-xs ${c}`,children:e.method}),n.jsx("span",{className:"font-mono text-sm text-[var(--text-primary)] break-all",children:e.pathPattern}),n.jsx(Be,{source:e.source}),i!==void 0&&n.jsx("span",{className:"px-1.5 py-0.5 rounded border border-[var(--border-default)] text-[var(--text-muted)] font-mono text-xs",children:i}),e.observedCount>0&&n.jsxs("span",{className:"ml-auto text-xs text-[var(--text-dim)]",children:[e.observedCount,"× ",f?`· ${f}`:""]})]}),e.variants.length>1&&n.jsxs("div",{className:"text-[10px] text-[var(--text-dim)] font-mono",children:["variants: ",e.variants.filter(y=>y!==o).join(", ")]}),n.jsxs("div",{className:"flex flex-wrap gap-2 pt-1",children:[e.source==="scenario"&&t&&n.jsx("button",{onClick:()=>void a(o),className:p,title:"Remove this scenario mock and fall back to the default",children:"Revert to default"}),e.source==="scenario"&&n.jsx("button",{onClick:()=>void s(o),className:p,children:"Mark passthrough"}),e.source==="default"&&n.jsxs(n.Fragment,{children:[n.jsx("button",{onClick:()=>void r({routeKey:o,status:e.status??200,body:e.body,headers:e.headers??{},scope:{kind:"scenario"}}),className:"px-3 py-1 rounded border border-emerald-500/50 bg-emerald-500/10 text-emerald-300 hover:bg-emerald-500/20 cursor-pointer text-xs",title:"Copy default body into this scenario",children:"Promote to scenario"}),n.jsx("button",{onClick:()=>void s(o),className:p,children:"Mark passthrough"})]}),e.source==="passthrough"&&n.jsx("button",{onClick:()=>void a(o),className:p,children:"Undo passthrough"})]})]})}function kn({entry:e}){const t=Object.entries(e.headers??{}),r=e.body!==void 0&&e.body!==null;return!r&&t.length===0?n.jsx("p",{className:"text-xs italic text-[var(--text-dim)]",children:e.source==="catalog-only"?"No mock body yet — this endpoint has only been observed, not mocked. Promote it to a scenario to start editing.":e.source==="passthrough"?"This endpoint passes through to the upstream service.":"No body configured."}):n.jsxs("div",{className:"space-y-3 h-full min-h-0 flex flex-col",children:[t.length>0&&n.jsxs("section",{className:"space-y-1 flex-shrink-0",children:[n.jsx("h4",{className:"text-xs font-medium uppercase tracking-wide text-[var(--text-dim)]",children:"Headers"}),n.jsx("dl",{className:"text-xs font-mono space-y-0.5",children:t.map(([a,s])=>n.jsxs("div",{className:"flex gap-2",children:[n.jsxs("dt",{className:"text-[var(--text-muted)]",children:[a,":"]}),n.jsx("dd",{className:"text-[var(--text-primary)] break-all",children:s})]},a))})]}),r&&n.jsxs("section",{className:"flex-1 min-h-0 flex flex-col",children:[n.jsx("h4",{className:"text-xs font-medium uppercase tracking-wide text-[var(--text-dim)] pb-1",children:"Body"}),n.jsx(Se,{value:e.body,onChange:()=>{},readOnly:!0},`${e.method} ${e.pathPattern}`)]})]})}function Sn({entry:e,scenarioSlug:t,scenarioHasDefaultFallback:r,onSave:a,onRemove:s,onPassthrough:o,focusJsonPath:c}){const i=`${e.method} ${e.pathPattern}`,f=e.source==="scenario"||e.source==="default"||e.source==="shared";return n.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[n.jsx(jn,{entry:e,scenarioHasDefaultFallback:r,onSave:a,onRemove:s,onPassthrough:o}),n.jsx("div",{className:"flex-1 min-h-0 overflow-auto p-4",children:f?n.jsx(gn,{entry:e,routeKey:i,scenarioSlug:t,onSave:a,focusJsonPath:c}):n.jsx(kn,{entry:e})})]})}function Cn({slug:e,tab:t,initialRows:r,onCellEdited:a}){const[s,o]=l.useState(r),[c,i]=l.useState(null),[f,p]=l.useState(""),[y,h]=l.useState(""),d=l.useRef(null);l.useEffect(()=>{o(r),i(null)},[t.dataKey,r]);function m(g,S){const w=s[g];i({row:g,col:S});const N=w[S]===null?"":typeof w[S]=="object"?JSON.stringify(w[S]):String(w[S]);p(N),h(N)}function x(g){if(p(g),d.current&&clearTimeout(d.current),!c)return;const S=c;d.current=setTimeout(()=>{u(S.row,S.col,g)},600)}function b(){c&&(d.current&&clearTimeout(d.current),u(c.row,c.col,f),i(null))}function v(){if(d.current&&clearTimeout(d.current),!!c){if(f!==y){const g=[...s];g[c.row]={...g[c.row],[c.col]:Te(y)},o(g),fetch(`/api/scenarios/${encodeURIComponent(e)}/data`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({table:t.dataKey,rowIndex:c.row,column:c.col,value:y})}).then(()=>{X(),a&&a()}).catch(()=>{})}i(null)}}async function u(g,S,w){const N=[...s];N[g]={...N[g],[S]:Te(w)},o(N);try{await fetch(`/api/scenarios/${encodeURIComponent(e)}/data`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({table:t.dataKey,rowIndex:g,column:S,value:w})}),X(),a&&a()}catch{}}return{rows:s,editingCell:c,editValue:f,handleEditCell:m,handleEditValueChange:x,handleSave:b,handleCancelEdit:v}}function Nn({tab:e}){return!e.description&&!e.category?null:n.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 bg-[var(--bg-deep)] border-b border-[var(--border-subtle)]",children:[e.category&&n.jsx("span",{className:`text-[9px] rounded px-1.5 py-0 border ${e.category==="datastore"?"text-[var(--accent-active)]/80 bg-[var(--accent-active)]/10 border-[var(--accent-active)]/30":e.category==="mock-api"?"text-[#D7FF63]/80 bg-[#D7FF63]/10 border-[#D7FF63]/30":"text-[var(--text-muted)] bg-[var(--bg-surface)]/30 border-[var(--text-dim)]/30"}`,children:e.category==="mock-api"?"API Mock":e.category}),e.description&&n.jsx("span",{className:"text-[10px] text-[var(--text-dim)]",children:e.description})]})}function En({editingCell:e,editValue:t,onEditValueChange:r,onSave:a,onCancel:s}){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)]",children:e.col})," ","in row ",e.row+1]})}),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"&&s(),o.key==="Enter"&&(o.metaKey||o.ctrlKey)&&a()}}),n.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[n.jsx("button",{onClick:a,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:s,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 Tn({columns:e,colTypes:t,pkCol:r,rows:a,onEditCell:s}){return e.length===0?n.jsx("div",{className:"px-3 py-4 text-[10px] text-[var(--text-dim)] text-center",children:"No columns defined for this table"}):n.jsx("div",{className:"overflow-x-auto max-h-[300px] overflow-y-auto",children:n.jsxs("table",{className:"w-full text-[10px] border-collapse table-fixed",children:[n.jsx("thead",{children:n.jsxs("tr",{className:"bg-[var(--bg-deep)] sticky top-0 z-10",children:[n.jsx("th",{className:"text-right text-[var(--text-dim)] font-normal px-2 py-1.5 border-b border-[var(--border-default)] w-8",children:"#"}),e.map(o=>n.jsx(An,{name:o,type:t[o],isPk:o===r},o))]})}),n.jsx("tbody",{children:a.map((o,c)=>n.jsx(Dn,{row:o,rowIndex:c,columns:e,pkCol:r,onEditCell:s},c))})]})})}function An({name:e,type:t,isPk:r}){return n.jsxs("th",{className:"text-left px-2 py-1.5 border-b border-[var(--border-default)] whitespace-nowrap overflow-hidden",children:[r&&n.jsx("span",{className:"inline-block text-[8px] font-bold text-[var(--bg-deep)] bg-[var(--accent-active)] rounded px-1 py-0 mr-1.5 align-middle",children:"PK"}),n.jsx("span",{className:"text-[var(--text-secondary)] font-medium",children:e}),n.jsx("span",{className:"text-[var(--text-dim)] font-normal ml-1",children:t})]})}function Dn({row:e,rowIndex:t,columns:r,pkCol:a,onEditCell:s}){return n.jsxs("tr",{className:"border-b border-[var(--border-subtle)] hover:bg-[var(--bg-card)] group/row",children:[n.jsx("td",{className:"text-right text-[var(--text-dim)] px-2 py-1.5 w-8 select-none",children:t+1}),r.map(o=>n.jsx(On,{value:e[o],isPk:o===a,onEdit:()=>s(t,o)},o))]})}function On({value:e,isPk:t,onEdit:r}){return n.jsxs("td",{className:`px-2 py-1.5 overflow-hidden relative group/cell ${t?"text-[var(--accent-active)] font-medium":"text-[var(--text-secondary)]"}`,title:String(e??""),children:[n.jsx("span",{className:"truncate block whitespace-nowrap",children:e===null?n.jsx("span",{className:"text-[var(--text-dim)] italic",children:"null"}):typeof e=="object"?n.jsx("span",{className:"text-[var(--text-dim)]",children:JSON.stringify(e)}):typeof e=="number"?n.jsx("span",{className:"text-amber-400",children:String(e)}):String(e)}),n.jsx("button",{onClick:a=>{a.stopPropagation(),r()},className:"absolute right-1 top-1/2 -translate-y-1/2 opacity-0 group-hover/cell:opacity-100 text-[var(--text-dim)] hover:text-[var(--text-primary)] bg-[var(--bg-card)] border border-[var(--border-default)] rounded cursor-pointer p-0.5 transition-opacity",title:"Edit",children:n.jsxs("svg",{width:"9",height:"9",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[n.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),n.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})})]})}function Mn({slug:e,tab:t,initialRows:r,onCellEdited:a}){const{rows:s,editingCell:o,editValue:c,handleEditCell:i,handleEditValueChange:f,handleSave:p,handleCancelEdit:y}=Cn({slug:e,tab:t,initialRows:r,onCellEdited:a}),h=ft(s,t.schemaFields),d=pt(h,s,t.schemaFields),m=ht(h,t.schemaFields);return n.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[n.jsx(Nn,{tab:t}),n.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:n.jsx(Tn,{columns:h,colTypes:d,pkCol:m,rows:s,onEditCell:i})}),o&&n.jsx(En,{editingCell:o,editValue:c,onEditValueChange:f,onSave:p,onCancel:y})]})}function Rn({slug:e,browserState:t,tab:r,onCellEdited:a}){const s=l.useMemo(()=>{if(!t)return{};switch(r){case"cookies":return t.cookies??{};case"localStorage":return t.localStorage??{};case"sessionStorage":return t.sessionStorage??{};case"headers":return t.requestHeaders??{};default:return{}}},[t,r]),o=l.useCallback(async f=>{const p=r==="headers"?"browserState.requestHeaders":`browserState.${r}`;try{await fetch(`/api/scenarios/${encodeURIComponent(e)}/data`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:p,value:JSON.stringify(f)})}),X(),a&&a()}catch{}},[e,r,a]),c=l.useMemo(()=>{switch(r){case"cookies":return"Cookies";case"localStorage":return"Local Storage";case"sessionStorage":return"Session Storage";case"headers":return"Request Headers"}},[r]),i=l.useMemo(()=>{switch(r){case"cookies":return"Cookies injected via Set-Cookie headers on the scenario's initial response.";case"localStorage":return"localStorage items set before the app's JavaScript executes.";case"sessionStorage":return"sessionStorage items set before the app's JavaScript executes.";case"headers":return"Custom headers added to every outbound HTTP request from the iframe."}},[r]);return{value:s,handleChange:o,label:c,description:i}}function Pn({slug:e,browserState:t,tab:r,onCellEdited:a}){const{value:s,handleChange:o,label:c,description:i}=Rn({slug:e,browserState:t,tab:r,onCellEdited:a});return n.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[n.jsxs("div",{className:"px-4 py-3 border-b border-[var(--border-subtle)]",children:[n.jsx("h2",{className:"text-sm font-semibold text-[var(--text-primary)]",children:c}),n.jsx("p",{className:"text-xs text-[var(--text-dim)] mt-1",children:i})]}),n.jsx("div",{className:"flex-1 min-h-0 p-4 overflow-auto",children:n.jsx(Se,{value:s,onChange:o})})]})}function pe({label:e,active:t,onClick:r}){return n.jsx("button",{type:"button",onClick:r,className:`px-2 py-0.5 rounded-full border text-[10px] font-mono transition-colors cursor-pointer ${t?"bg-violet-500/25 text-violet-100 border-violet-400/70":"bg-violet-500/10 text-violet-300 border-violet-500/40 hover:bg-violet-500/20"}`,"aria-pressed":t,children:e})}function $n({shares:e,activeBadge:t,onSelect:r}){return n.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap border-b border-[var(--border-subtle)] bg-[var(--bg-deep)] px-4 py-2","data-testid":"scenario-mock-data-strip",children:[n.jsx("span",{className:"text-[10px] uppercase tracking-wider text-[var(--text-dim)] font-semibold",children:"Mock Data:"}),n.jsx(pe,{label:"This Page",active:t.kind==="this-page",onClick:()=>r({kind:"this-page"})}),e.map(a=>n.jsx(pe,{label:a,active:t.kind==="share"&&t.slug===a,onClick:()=>r({kind:"share",slug:a})},a)),n.jsx(pe,{label:"Defaults",active:t.kind==="defaults",onClick:()=>r({kind:"defaults"})})]})}function Un({slug:e,scenarioName:t,initialSection:r,onClose:a,variant:s="slideOver"}){const{data:o,tableTabs:c,scenarioOwnedDataKeys:i,shares:f,browserState:p,loading:y,error:h}=wt(e),{entries:d,loading:m,error:x,upsertScoped:b,remove:v,setPassthrough:u}=ct(e),{config:g}=Ie(),S=(g==null?void 0:g.provider)??"claude",w=Ct({slug:e,onPreviewReload:X}),N=l.useCallback(()=>{w.markDirty(),X()},[w]),R=l.useCallback(async A=>{await b(A),N()},[b,N]),D=l.useCallback(async A=>{await v(A),N()},[v,N]),O=l.useCallback(async A=>{await u(A),N()},[u,N]),j=l.useCallback(()=>{w.markDirty(),X()},[w]),T=l.useCallback(()=>{a&&w.confirmIfDirty("Discard unsaved changes to this scenario?")&&a()},[a,w]),[k,M]=l.useState(null),[$,I]=l.useState(null),[B,C]=l.useState(!1),E=l.useCallback(A=>M({kind:"mock",routeKey:A}),[]);et({onSelect:E,onFocus:I});const[P,L]=l.useState({kind:"this-page"}),re=y||m,H=l.useMemo(()=>s==="inline"?c.filter(A=>i.has(A.dataKey)):c,[s,c,i]),V=l.useMemo(()=>{if(s!=="inline")return d;switch(P.kind){case"this-page":return d.filter(A=>A.consumedThisPageLoad);case"defaults":return d.filter(A=>A.source==="default");case"share":return d.filter(A=>A.source==="shared"&&A.sharedSlug===P.slug)}},[s,d,P]);Bt({seedTabs:H,mockEntries:V,initialSection:r,selection:k,setSelection:M});const Ye=l.useMemo(()=>{const A=new Set;for(const Ce of d)Ce.source==="default"&&A.add(J(Ce));return A},[d]),K=(k==null?void 0:k.kind)==="seed"?H.find(A=>A.dataKey===k.dataKey)??null:null,Y=(k==null?void 0:k.kind)==="mock"?V.find(A=>J(A)===k.routeKey)??null:null,ne=K&&o?o[K.dataKey]??[]:[],Ue=l.useMemo(()=>Ge({slug:e,scenarioName:t,seedTabs:H,mockEntries:V,selectedMock:Y,selectedSeedTab:K,selectedSeedRows:ne}),[e,t,H,V,Y,K,ne]),Xe=t??e,ae=H.length>0||V.length>0,se=n.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[n.jsx(Ur,{title:Xe,slug:e,provider:S,chatOpen:B,onToggleChat:()=>C(A=>!A),variant:s,onClose:a?T:void 0,draftDirty:w.isDirty,draftDiff:w.diffSummary,draftSaving:w.saving,draftCancelling:w.cancelling,draftError:w.error,onSave:()=>void w.save(),onCancel:()=>void w.cancel()}),s==="inline"&&n.jsx($n,{shares:f,activeBadge:P,onSelect:L}),B&&n.jsx("div",{className:"flex-shrink-0 border-b border-[var(--border-subtle)] bg-[var(--bg-deep)]",children:n.jsx(Pr,{chatName:`edit-data-${e}`,prompt:Ue,height:360,onClose:()=>C(!1)})}),n.jsxs("div",{className:"flex flex-1 min-h-0",children:[n.jsx(It,{seedTabs:H,mockEntries:V,selection:k,onSelect:M}),n.jsx("main",{className:"flex-1 min-w-0 min-h-0 bg-[var(--bg-deep)] flex flex-col",children:n.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",children:[h&&n.jsxs("p",{className:"p-4 text-xs text-red-400",children:["Seed error: ",h]}),x&&n.jsxs("p",{className:"p-4 text-xs text-red-400",children:["Mocks error: ",x]}),!re&&!ae&&n.jsx($r,{}),K&&n.jsx(Mn,{slug:e,tab:K,initialRows:ne,onCellEdited:j}),Y&&n.jsx(Sn,{entry:Y,scenarioSlug:e,scenarioHasDefaultFallback:Ye.has(J(Y)),onSave:R,onRemove:D,onPassthrough:O,focusJsonPath:$}),(k==null?void 0:k.kind)==="browser"&&n.jsx(Pn,{slug:e,browserState:p,tab:k.tab,onCellEdited:j}),!K&&!Y&&(k==null?void 0:k.kind)!=="browser"&&ae&&!re&&n.jsx("p",{className:"p-4 text-xs text-[var(--text-dim)] italic",children:"Select a data source from the left to view it."}),re&&!ae&&n.jsx("p",{className:"p-4 text-xs text-[var(--text-dim)]",children:"Loading scenario data…"})]})})]})]});return s==="fullPage"?n.jsx("div",{className:"fixed inset-0 bg-[var(--bg-deep)] text-[var(--text-primary)]",children:se}):s==="inline"?n.jsx("div",{className:"rounded-md border border-[var(--border-subtle)] bg-[var(--bg-deep)] max-h-[min(640px,70vh)] min-h-0 flex flex-col overflow-hidden",children:se}):n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"fixed inset-0 z-40 bg-black/40",onClick:T,"aria-label":"Close scenario data panel"}),n.jsx("aside",{className:"fixed right-0 top-0 z-50 h-full w-full max-w-4xl border-l border-[var(--border-default)] bg-[var(--bg-deep)] shadow-2xl",children:se})]})}export{Rr as $,$n as A,pe as B,Hr as C,jn as D,Sn as E,_r as F,Ur as G,$r as H,Lr as I,un as J,Ir as K,Tn as L,fn as M,En as N,Nn as O,Ot as P,Dt as Q,cr as R,Un as S,lr as T,ir as U,or as V,ur as W,Er as X,Dr as Y,Or as Z,Pr as _,Be as a,Ie as a0,W as a1,Fe as a2,br as a3,le as a4,Ht as a5,Vt as a6,Wt as a7,rr as a8,Yt as a9,sr as aa,Ke as ab,nr as ac,Wr as ad,Z as ae,Ut as af,it as ag,_n as ah,Yn as ai,Vn as aj,Hn as ak,_t as al,ge as am,Mn as b,gn as c,kn as d,X as e,vn as f,wt as g,ct as h,fr as i,Nr as j,dn as k,ln as l,je as m,ke as n,Se as o,Te as p,on as q,cn as r,zr as s,Yr as t,Ct as u,Mt as v,Pt as w,yn as x,bn as y,It as z};
@@ -1 +0,0 @@
1
- import{j as c}from"./markdown-v0F0UEt3.js";import{b as o}from"./react-CSS0HapR.js";import{S as m}from"./ScenarioDataPanel-xWYGZOpo.js";import"./useEvents-DggWrtHe.js";import"./xterm--24IGk-x.js";import"./index-BuK0lizt.js";function S({slug:t}){const[r,i]=o.useState(void 0);return o.useEffect(()=>{let n=!1;return fetch(`/api/scenarios/${encodeURIComponent(t)}`).then(e=>e.ok?e.json():null).then(e=>{if(n||!e)return;const a=typeof e=="object"&&e!==null&&"name"in e?String(e.name):void 0;i(a),a&&(document.title=`${a} · data`)}).catch(()=>{}),()=>{n=!0}},[t]),c.jsx(m,{slug:t,scenarioName:r,variant:"fullPage"})}export{S as ScenarioDataPanelFullPage};
@@ -1 +0,0 @@
1
- import{j as e}from"./markdown-v0F0UEt3.js";import{b as d}from"./react-CSS0HapR.js";import{c as Xe,C as Y,S as X,f as Ze,T as Z,e as et,N as A,b as tt,a as ee,r as at,d as te,R as H,p as st,g as ae,P as rt,h as nt,I as ot,i as it,j as ct,k as lt,l as dt,m as ut,n as xt,o as pt,q as mt,s as ht,E as bt,t as ft,u as vt,v as gt,w as yt,x as jt,y as St,z as Nt,A as wt,B as Ct,D as Pt,F as kt,G as Et,H as Dt,J as Rt,K as Tt,L as Bt,M as Mt,O as Ft,Q as Ot,U as Lt,V as At,W as It,X as Ht,Y as $t,Z as Vt,_ as _t,$ as Kt,a0 as Jt,a1 as Gt,a2 as zt,a3 as Ut,a4 as Wt,a5 as Qt,a6 as qt,a7 as Yt,a8 as Xt,a9 as Zt,aa as ea,ab as ta,ac as aa,ad as sa,ae as ra,af as na,ag as oa,ah as ia,ai as ca,aj as la,ak as da,al as ua,am as xa,an as pa,ao as ma,ap as ha,aq as ba,ar as fa,as as va,at as ga,au as ya,av as ja,aw as Sa,ax as Na,ay as wa,az as Ca,aA as Pa,aB as ka,aC as Ea,aD as Da,aE as Ra,aF as Ta,aG as Ba,aH as Ma,aI as Fa,aJ as Oa,aK as La,aL as Aa,aM as Ia,aN as Ha,aO as $a,aP as Va,aQ as _a,aR as Ka,aS as Ja,aT as Ga,aU as za,aV as Ua,aW as Wa,aX as Qa,aY as qa,aZ as Ya,a_ as Xa,a$ as Za,b0 as es,b1 as ts,b2 as as,b3 as ss,b4 as rs,b5 as ns,b6 as os,b7 as is,b8 as cs,b9 as ls,ba as ds,bb as us,bc as xs,bd as ps,be as ms,bf as hs,bg as bs,bh as fs,bi as vs,bj as gs,bk as ys,bl as js,bm as Ss,bn as Ns,bo as ws,bp as Cs,bq as Ps,br as ks,bs as Es,bt as Ds,bu as Rs,bv as Ts,bw as Bs,bx as Ms,by as Fs,bz as Os,bA as Ls,bB as As,bC as Is,bD as Hs,bE as $s,bF as Vs,bG as _s,bH as Ks,bI as Js,bJ as Gs,bK as zs,bL as Us,bM as Ws,bN as Qs,bO as qs,bP as Ys,bQ as Xs,bR as Zs,bS as er,bT as tr,bU as ar,bV as sr,bW as rr,bX as nr,bY as or,bZ as ir,b_ as cr,b$ as lr,c0 as dr,c1 as ur,c2 as xr,c3 as pr,c4 as mr,c5 as hr,c6 as br,c7 as fr,c8 as vr,c9 as gr,ca as yr,cb as jr,cc as Sr,cd as Nr,ce as wr,cf as Cr,cg as Pr,ch as kr,ci as Er,cj as Dr,ck as Rr,cl as Tr,cm as Br,cn as Mr,co as Fr,cp as G,cq as Or,cr as Lr,cs as Ar,ct as Ir,cu as Hr,cv as $r,cw as Vr,cx as _r,cy as Kr,cz as Jr,cA as Gr,cB as zr,cC as Ur,cD as Wr,cE as Qr,cF as qr,cG as Yr,cH as Xr,cI as Zr,cJ as en,cK as tn,cL as an,cM as sn,cN as rn,cO as nn,cP as on,cQ as cn,cR as ln,cS as dn,cT as un,cU as xn,cV as pn,cW as mn,cX as hn,cY as bn,cZ as fn,c_ as vn,c$ as gn,d0 as yn,d1 as jn,d2 as Sn,d3 as Nn,d4 as wn,d5 as Cn,d6 as Pn,d7 as kn,d8 as En,d9 as Dn,da as Rn,db as Tn,dc as Bn,dd as Mn,de as Fn,df as On,dg as Ln,dh as An,di as In,dj as Hn,dk as $n,dl as Vn,dm as _n,dn as Kn,dp as Jn,dq as Gn,dr as zn,ds as Un,dt as Wn,du as Qn,dv as qn,dw as Yn,dx as Xn,dy as Zn,dz as eo,dA as to,dB as ao,dC as so,dD as ro,dE as no,dF as oo,dG as io,dH as co,dI as lo,dJ as uo,dK as xo,dL as po,dM as mo,dN as ho,dO as bo,dP as fo,dQ as vo,dR as go,dS as yo,dT as jo,dU as So,dV as No,dW as wo,dX as Co,dY as Po,dZ as ko,d_ as Eo}from"./EditorShell-tMMdarZD.js";import{S as Do,a as Ro,b as To,c as Bo}from"./StepsSimulator-CRtmlyNZ.js";import{M as se}from"./Markdown-BHBqz-Mj.js";import{S as Mo,B as R,M as k,a as L,t as C,I as Fo,b as Oo,c as Lo,d as Ao,e as Io,f as Ho,g as $o,h as Vo,i as _o,j as Ko,k as Jo,C as Go,l as zo}from"./ContainerInspector-C8EkH4PP.js";import{S as re,M as ne,f as Uo,a as oe,p as z,e as B,b as ie,c as ce,d as le,u as Wo,g as Qo,h as qo,i as Yo,j as Xo,J as Zo,k as ei,l as ti,m as ai,n as si,o as ri,q as ni,r as oi,s as ii,t as ci,v as li,w as di,x as ui,y as xi,z as pi,A as mi,B as hi,C as bi,D as fi,E as vi,F as gi,G as yi,H as ji,I as Si,K as Ni,L as wi,N as Ci,O as Pi,P as ki,Q as Ei,T as Di,R as Ri,U as Ti,V as Bi,W as Mi,X as Fi,Y as Oi,Z as Li,_ as Ai,$ as Ii}from"./ScenarioDataPanel-xWYGZOpo.js";import{ScenarioDataPanelFullPage as Hi}from"./ScenarioDataPanelFullPage-5G6KuZgw.js";import"./index-BuK0lizt.js";import"./useEvents-DggWrtHe.js";import"./xterm--24IGk-x.js";function de({files:t}){if(t.length===0)return null;const{added:a,modified:s,deleted:r}=Xe(t);return e.jsxs("span",{className:"text-xs text-[var(--text-muted)]",children:[a>0&&e.jsxs("span",{className:"text-[var(--accent-green)]",children:["+",a," "]}),s>0&&e.jsxs("span",{className:"text-[var(--accent-orange)]",children:["~",s," "]}),r>0&&e.jsxs("span",{className:"text-[var(--accent-red)]",children:["-",r," "]}),"file",t.length!==1?"s":""]})}function w({label:t,children:a}){return e.jsxs("div",{className:"mb-2",children:[e.jsx("p",{className:"text-xs font-medium mb-1",style:{color:"var(--text-muted)"},children:t}),e.jsx("div",{className:"mt-0.5",children:a})]})}function ue({files:t}){return t.length===0?null:e.jsx("div",{className:"max-h-32 overflow-y-auto",children:t.map(a=>e.jsxs("p",{className:"font-mono text-xs text-[var(--text-muted)]",children:[e.jsx(xe,{status:a.status})," ",a.path]},a.path))})}function xe({status:t}){const a=t==="added"?"text-[var(--accent-green)]":t==="deleted"?"text-[var(--accent-red)]":"text-[var(--accent-orange)]",s=t==="added"?"+":t==="deleted"?"-":"~";return e.jsx("span",{className:a,children:s})}function pe({entry:t}){return e.jsxs("div",{className:"mt-3 pt-3",style:{borderTop:"1px solid var(--border-default)"},children:[t.userRequest&&e.jsx(w,{label:"Request",children:e.jsx(Y,{children:t.userRequest})}),e.jsx(w,{label:"Description",children:e.jsx(se,{variant:"compact",children:t.description})}),t.scenarioScreenshots.length>0&&e.jsx(w,{label:"Scenarios",children:e.jsx(X,{screenshots:t.scenarioScreenshots})}),t.modifiedFiles.length>0&&e.jsx(w,{label:"Modified Files",children:e.jsx(ue,{files:t.modifiedFiles})}),t.commitSha&&e.jsxs("p",{className:"text-xs",style:{color:"var(--text-dim)"},children:["Commit: ",e.jsx("span",{className:"font-mono",children:t.commitSha.slice(0,7)}),t.commitMessage&&` — ${t.commitMessage}`]})]})}function me({entry:t}){const[a,s]=d.useState(!1);return e.jsxs("div",{className:"rounded-lg border p-4",style:{borderColor:"var(--border-default)",background:"var(--bg-surface)"},children:[e.jsxs("button",{onClick:()=>s(!a),className:"flex w-full items-start gap-3 text-left",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(he,{type:t.type}),e.jsx("h3",{className:"text-sm font-medium",style:{color:"var(--text-secondary)"},children:t.title})]}),e.jsxs("div",{className:"mt-1 flex items-center gap-3",children:[e.jsx("span",{className:"text-xs",style:{color:"var(--text-dim)"},children:Ze(t.timestamp)}),t.testResults&&e.jsx(Z,{total:t.testResults.total,passed:t.testResults.passed,failed:t.testResults.failed}),e.jsx(de,{files:t.modifiedFiles})]})]}),e.jsx("span",{className:"text-xs mt-1",style:{color:"var(--text-dim)"},children:a?"▼":"▶"})]}),a&&e.jsx(pe,{entry:t})]})}function he({type:t}){return e.jsx("span",{className:`text-xs font-medium ${et(t)}`,children:t})}function $i({entries:t,total:a,hasMore:s,loading:r,loadingMore:n,error:o,onLoadMore:i}){if(r)return e.jsx("div",{className:"py-12 text-center text-[var(--text-muted)]",children:"Loading journal..."});if(o)return e.jsxs("div",{className:"py-12 text-center text-[var(--accent-red)]",children:["Failed to load journal: ",o]});if(t.length===0)return e.jsxs("div",{className:"py-12 text-center text-[var(--text-dim)]",children:[e.jsx("p",{children:"No journal entries yet."}),e.jsx("p",{className:"mt-2 text-sm text-[var(--text-dim)]",children:"Journal entries capture what was requested, what changed, and the state of tests and scenarios."})]});const l=Math.max(a,t.length);return e.jsxs("div",{className:"overflow-y-auto px-6 py-4",style:{maxHeight:"calc(100vh - 110px)"},children:[e.jsxs("p",{className:"mb-4 text-sm text-[var(--text-muted)]",children:[t.length," of ",l," journal entr",l===1?"y":"ies"]}),e.jsx("div",{className:"flex flex-col gap-3",children:t.map(c=>e.jsx(me,{entry:c},c.timestamp))}),s?e.jsx("div",{className:"mt-4 flex justify-center",children:e.jsx("button",{type:"button",onClick:i,disabled:n,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:n?"Loading...":"Load older entries"})}):null]})}function Vi({apps:t,selected:a,onChange:s}){return t.length===0?null:e.jsxs("div",{className:"flex gap-1",children:[t.map(r=>e.jsx(A,{href:tt(r.dir),onNavigate:()=>s(r.dir),className:`rounded-md px-3 py-1 text-sm ${a===r.dir?"bg-[var(--bg-input)] text-[var(--text-primary)]":"text-[var(--text-muted)] hover:text-[var(--text-secondary)]"}`,children:r.name},r.dir)),e.jsx(A,{href:"/apps",onNavigate:()=>s(null),className:`rounded-md px-3 py-1 text-sm ${a===null?"bg-[var(--bg-input)] text-[var(--text-primary)]":"text-[var(--text-muted)] hover:text-[var(--text-secondary)]"}`,children:"All"})]})}function _i(){return e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-slate-500 space-y-4 px-10 text-center",children:[e.jsx("div",{className:"text-lg font-medium text-slate-400",children:"Ready to build"}),e.jsx("p",{className:"max-w-md",children:"Your first session will start automatically. You can queue changes or wait for the project to initialize."})]})}function Ki({size:t=16}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("circle",{cx:"12",cy:"12",r:"3"}),e.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"})]})}const Ji={http_request:"#3fb950",db_query:"#D7FF63",process_output:"#6e7681",health_check:"#d29922",hook_execution:"#bc8cff",error:"#f85149",scenario_switch:"#d29922"};function Gi(t){const a=Ji[t.type]??"#6e7681";switch(t.type){case"http_request":{const s=t.status??"";return{label:"HTTP",detail:`${t.method} ${t.url} ${s} ${t.durationMs}ms`,badge:t.mocked?"MOCKED":"LIVE",color:a}}case"db_query":return{label:"DB",detail:`${t.query} (${t.durationMs}ms)`,badge:t.mocked?"MOCKED":"LIVE",color:a};case"process_output":return{label:"Process",detail:`[${t.stream}] ${t.line}`,color:a};case"health_check":return{label:"Health",detail:t.healthy?"healthy":"unhealthy",color:a};case"hook_execution":return{label:"Hook",detail:`${t.hook} exit=${t.exitCode} ${t.durationMs}ms`,color:a};case"error":return{label:"Error",detail:`${t.source}: ${t.message}`,color:a};case"scenario_switch":return{label:"Scenario",detail:`${t.from??"(none)"} → ${t.to}`,color:a}}}function be({event:t}){const{label:a,detail:s,badge:r,color:n}=Gi(t);return e.jsxs("div",{className:"my-1 rounded-md bg-[var(--bg-surface)] px-3 py-2 font-mono text-sm",style:{borderLeft:`3px solid ${n}`},children:[e.jsx("span",{className:"mr-2 font-semibold",children:a}),e.jsx("span",{className:"text-[var(--text-secondary)]",children:s}),r&&e.jsx("span",{className:`ml-2 text-xs ${r==="MOCKED"?"text-[var(--accent-green)]":"text-[var(--text-muted)]"}`,children:r})]})}function zi({events:t}){return t.length===0?e.jsx("div",{className:"py-12 text-center text-[var(--text-dim)]",children:"Waiting for events..."}):e.jsx("div",{className:"overflow-y-auto px-6 py-2",style:{maxHeight:"calc(100vh - 110px)"},children:t.map(a=>e.jsx(be,{event:a},a.id))})}function fe({passed:t,failed:a,total:s}){return a>0?e.jsxs("span",{className:"rounded bg-[var(--accent-red)]/20 px-2 py-0.5 text-xs text-[var(--accent-red)]",children:[a," failed"]}):t===s&&s>0?e.jsxs("span",{className:"rounded bg-[var(--accent-green)]/20 px-2 py-0.5 text-xs text-[var(--accent-green)]",children:[t," passed"]}):e.jsxs("span",{className:"text-xs text-[var(--text-dim)]",children:["(",s,")"]})}function ve({group:t}){const[a,s]=d.useState(!0),r=t.tests.filter(i=>i.status==="passed").length,n=t.tests.filter(i=>i.status==="failed").length,o=t.tests.length;return e.jsxs("div",{className:"mb-4",children:[e.jsxs("button",{onClick:()=>s(!a),className:"flex w-full items-center gap-2 text-left text-sm font-medium text-[var(--text-secondary)] hover:text-[var(--text-primary)]",children:[e.jsx("span",{className:"text-[var(--text-dim)]",children:a?"▼":"▶"}),e.jsx("span",{children:t.feature}),e.jsx(fe,{passed:r,failed:n,total:o})]}),a&&e.jsx("div",{className:"ml-5 mt-1 border-l border-[var(--border-default)] pl-3",children:t.tests.map((i,l)=>e.jsx(ee,{test:i},l))})]})}function Ui({filters:t,active:a,onChange:s}){return e.jsx("div",{className:"flex gap-2 border-b px-6 py-3",style:{borderColor:"var(--border-default)"},children:t.map(r=>e.jsx("button",{onClick:()=>s(r),className:"rounded-md border px-3 py-1 text-sm",style:r===a?{borderColor:"var(--accent-active)",background:"var(--accent-active)",color:"var(--bg-nav)"}:{borderColor:"var(--border-default)",background:"var(--bg-surface)",color:"var(--text-secondary)"},children:r},r))})}function ge({scenario:t,onPreview:a}){const s=t.screenshotPaths.length>0,[r,n]=d.useState(!1),o=s&&!r;return e.jsxs("div",{className:`rounded-lg border border-[var(--border-default)] bg-[var(--bg-surface)] p-3 ${a?"cursor-pointer hover:border-[var(--border-subtle)]":""}`,onClick:a,children:[o?e.jsx("img",{src:at(t.screenshotPaths[0],t.screenshotCapturedAtMs),alt:t.name,className:"mb-2 w-full rounded border border-[var(--border-default)]",onError:()=>n(!0)}):e.jsx("div",{className:"mb-2 flex h-32 items-center justify-center rounded border border-dashed border-[var(--border-default)] text-sm text-[var(--text-dim)]",children:"No screenshot"}),e.jsx("p",{className:"text-sm font-medium text-[var(--text-secondary)]",children:t.name}),e.jsxs("div",{className:"mt-1 flex gap-1",children:[t.hasMocks&&e.jsx("span",{className:"rounded bg-[var(--accent-blue)]/20 px-1.5 py-0.5 text-xs text-[var(--accent-blue)]",children:"mocks"}),t.hasSeed&&e.jsx("span",{className:"rounded bg-[var(--accent-purple)]/20 px-1.5 py-0.5 text-xs text-[var(--accent-purple)]",children:"seed"}),t.dimensions.map(i=>e.jsx("span",{className:"rounded bg-[var(--bg-input)] px-1.5 py-0.5 text-xs text-[var(--text-muted)]",children:i},i))]})]})}function ye({group:t,onPreviewScenario:a}){const[s,r]=d.useState(!0);return e.jsxs("div",{className:"mb-6",children:[e.jsxs("button",{onClick:()=>r(!s),className:"flex w-full items-center gap-2 text-left text-sm font-medium text-[var(--text-secondary)] hover:text-[var(--text-primary)]",children:[e.jsx("span",{className:"text-[var(--text-dim)]",children:s?"▼":"▶"}),e.jsx("span",{className:"font-mono",children:t.route}),e.jsxs("span",{className:"text-[var(--text-dim)]",children:["(",t.scenarios.length,")"]})]}),s&&e.jsx("div",{className:"mt-2 grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3",children:t.scenarios.map(n=>e.jsx(ge,{scenario:n,onPreview:a?()=>a(n.slug):void 0},n.slug))})]})}function je({fileName:t,dirPath:a}){return e.jsxs("div",{className:"flex items-center gap-3 rounded-md px-3 py-2 text-left bg-[var(--bg-card)] border border-[var(--border-subtle)] hover:border-[var(--border-default)] transition",children:[e.jsx("span",{className:"text-xs text-[var(--text-secondary)]",children:t}),e.jsxs("span",{className:"font-mono text-[10px] text-[var(--text-dim)]",children:[a,"/"]})]})}function Wi({slug:t,name:a,url:s,componentName:r,props:n,mocks:o,seed:i,localStorage:l,dimensions:c}){const[u,m]=d.useState(!1),b=Object.keys((o==null?void 0:o.http)??{}).length,x=Object.keys((o==null?void 0:o.db)??{}).length,f=Object.keys(l??{});return e.jsxs("div",{className:"space-y-3 text-sm",children:[e.jsx("h3",{className:"font-medium text-[var(--text-secondary)]",children:a}),s&&e.jsx(w,{label:"URL",children:e.jsx("span",{className:"font-mono text-xs text-[var(--text-muted)]",children:s})}),r&&e.jsx(w,{label:"Component",children:e.jsx("span",{className:"font-mono text-xs text-[var(--accent-blue)]",children:r})}),n&&e.jsx(w,{label:"Props",children:e.jsx("pre",{className:"max-h-32 overflow-auto rounded bg-[var(--bg-input)] p-2 font-mono text-xs text-[var(--text-muted)]",children:JSON.stringify(n,null,2)})}),b>0&&e.jsxs(w,{label:"Mocks",children:[t?e.jsxs("button",{type:"button",onClick:()=>m(!0),className:"text-xs text-[var(--accent-blue)] hover:underline bg-transparent border-none cursor-pointer p-0",children:[b," HTTP mock",b!==1?"s":""," →"]}):e.jsxs("span",{className:"text-xs text-[var(--text-muted)]",children:[b," HTTP mock",b!==1?"s":""]}),x>0&&e.jsxs("span",{className:"ml-2 text-xs text-[var(--text-muted)]",children:[x," DB mock",x!==1?"s":""]})]}),i&&e.jsx(w,{label:"Seed",children:i.command&&e.jsx("span",{className:"font-mono text-xs text-[var(--text-muted)]",children:i.command})}),f.length>0&&e.jsx(w,{label:"localStorage",children:f.map(v=>e.jsxs("p",{className:"font-mono text-xs text-[var(--text-muted)]",children:[v,": ",l[v]]},v))}),c.length>0&&e.jsx(w,{label:"Dimensions",children:e.jsx("div",{className:"flex gap-1",children:c.map(v=>e.jsx("span",{className:"rounded bg-[var(--bg-input)] px-1.5 py-0.5 text-xs text-[var(--text-muted)]",children:v},v))})}),u&&t&&e.jsx(re,{slug:t,scenarioName:a,initialSection:"mocks",onClose:()=>m(!1)})]})}function Se({value:t,onChange:a=()=>{},parseError:s,onParseError:r=()=>{}}){return d.useEffect(()=>{if(t.trim()===""){r(null);return}try{JSON.parse(t),r(null)}catch(n){r(n instanceof Error?n.message:"Invalid JSON")}},[t,r]),e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-xs text-[var(--text-muted)]",children:"Body (JSON)"}),e.jsx("textarea",{value:t,onChange:n=>a(n.target.value),rows:8,spellCheck:!1,className:`w-full rounded border bg-[var(--bg-surface)] px-2 py-1 text-xs font-mono resize-y ${s?"border-red-500":"border-[var(--border-default)]"}`}),s&&e.jsx("p",{className:"text-xs text-red-400 font-mono",children:s})]})}function Ne({initialStatus:t,initialBody:a,initialHeaders:s,onSave:r,onCancel:n}){const o=d.useMemo(()=>{if(a==null)return"";try{return JSON.stringify(a,null,2)}catch{return""}},[a]),[i,l]=d.useState(t),[c,u]=d.useState(o),[m,b]=d.useState(null),[x,f]=d.useState(()=>Object.entries(s).map(([p,g])=>({name:p,value:g}))),[v,y]=d.useState(!0),j=m!==null||v;function h(){const p=c.trim()===""?null:JSON.parse(c),g={};for(const N of x)N.name.trim()&&(g[N.name.trim()]=N.value);r({status:i,body:p,headers:g})}return e.jsxs("div",{className:"mt-2 border border-[var(--border-subtle)] rounded bg-[var(--bg-input)] p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("label",{className:"text-xs text-[var(--text-muted)]",children:"Status"}),e.jsx("input",{type:"number",value:i,onChange:p=>{y(!1),l(Number(p.target.value))},className:"w-20 rounded border border-[var(--border-default)] bg-[var(--bg-surface)] px-2 py-1 text-xs font-mono"})]}),e.jsx(ne,{headers:x,onChange:p=>{y(!1),f(p)}}),e.jsx(Se,{value:c,parseError:m,onChange:p=>{y(!1),u(p)},onParseError:b}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx("button",{type:"button",onClick:n,className:"px-3 py-1 text-xs rounded border border-[var(--border-default)] bg-transparent text-[var(--text-muted)] hover:text-[var(--text-primary)] cursor-pointer",children:"Cancel"}),e.jsx("button",{type:"button",onClick:h,disabled:j,className:"px-3 py-1 text-xs rounded border border-[var(--accent-blue)] bg-[var(--accent-blue)]/10 text-[var(--accent-blue)] hover:bg-[var(--accent-blue)]/20 disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer",children:"Save"})]})]})}function we({entry:t,scenarioHasDefaultFallback:a,editing:s,onToggleEdit:r,onPromoteDefaultToScenario:n,onRemove:o,onPassthrough:i,onCaptureLive:l}){const[c,u]=d.useState(!1),[m,b]=d.useState(null);async function x(){u(!0),b(null);try{await l()}catch(v){b(v instanceof Error?v.message:"Capture failed")}finally{u(!1)}}const f="px-2 py-0.5 rounded border border-[var(--border-default)] bg-transparent text-[var(--text-muted)] hover:text-[var(--text-primary)] cursor-pointer text-[10px]";return e.jsxs("div",{className:"flex flex-wrap gap-1 pt-1",children:[t.source==="scenario"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:r,className:f,children:s?"Close":"Edit"}),a&&e.jsx("button",{onClick:o,className:f,title:"Revert to default",children:"Revert to default"}),e.jsx("button",{onClick:i,className:f,children:"Mark passthrough"})]}),t.source==="default"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:n,className:"px-2 py-0.5 rounded border border-emerald-500/50 bg-emerald-500/10 text-emerald-300 hover:bg-emerald-500/20 cursor-pointer text-[10px]",title:"Copy default body into this scenario",children:"Promote to scenario"}),e.jsx("button",{onClick:i,className:f,children:"Mark passthrough"})]}),t.source==="catalog-only"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:x,disabled:c,className:"px-2 py-0.5 rounded border border-[#D7FF63]/50 bg-[#D7FF63]/10 text-[#D7FF63] hover:bg-[#D7FF63]/20 disabled:opacity-50 disabled:cursor-wait cursor-pointer text-[10px]",title:"Write last-observed body as this scenario's mock",children:c?"Capturing…":"Capture from live"}),m&&e.jsx("span",{className:"text-red-400 text-[10px]",children:m})]}),t.source==="passthrough"&&e.jsx("button",{onClick:o,className:f,children:"Undo passthrough"})]})}const U={GET:"text-emerald-400 border-emerald-400/40",POST:"text-[#D7FF63] border-[#D7FF63]/40",PUT:"text-amber-400 border-amber-400/40",PATCH:"text-purple-400 border-purple-400/40",DELETE:"text-red-400 border-red-400/40"};function Ce({entry:t}){const a=U[t.method]??U.GET,s=t.status??t.lastObservedStatus,r=t.lastObservedMs?Uo(t.lastObservedMs,Date.now()):null;return e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:`px-1.5 py-0.5 rounded border font-mono ${a}`,children:t.method}),e.jsx("span",{className:"font-mono text-[var(--text-primary)] break-all",children:t.pathPattern}),e.jsx(oe,{source:t.source}),s!==void 0&&e.jsx("span",{className:"px-1.5 py-0.5 rounded border border-[var(--border-default)] text-[var(--text-muted)] font-mono",children:s}),t.observedCount>0&&e.jsxs("span",{className:"ml-auto text-[var(--text-dim)]",children:[t.observedCount,"× ",r?`· ${r}`:""]})]})}function Pe({entry:t,scenarioHasDefaultFallback:a,onSave:s,onRemove:r,onPassthrough:n,onCaptureLive:o}){const[i,l]=d.useState(!1),c=`${t.method} ${t.pathPattern}`;return e.jsxs("div",{className:"border border-[var(--border-subtle)] rounded p-2 text-xs space-y-1",children:[e.jsx(Ce,{entry:t}),t.variants.length>1&&e.jsxs("div",{className:"text-[10px] text-[var(--text-dim)] font-mono",children:["variants: ",t.variants.filter(u=>u!==c).join(", ")]}),e.jsx(we,{entry:t,scenarioHasDefaultFallback:a,editing:i,onToggleEdit:()=>l(u=>!u),onPromoteDefaultToScenario:()=>s({routeKey:c,status:t.status??200,body:t.body,headers:t.headers??{}}),onRemove:()=>r(c),onPassthrough:()=>n(c),onCaptureLive:()=>o(t.method,t.pathPattern)}),i&&e.jsx(Ne,{initialStatus:t.status??200,initialBody:t.body,initialHeaders:t.headers??{},onCancel:()=>l(!1),onSave:async u=>{await s({routeKey:c,...u}),l(!1)}})]})}const T=async()=>{};function Qi({label:t,entries:a,defaultEndpointKeys:s=[],onSave:r=T,onRemove:n=T,onPassthrough:o=T,onCaptureLive:i=T}){if(a.length===0)return null;const l=s instanceof Set?s:new Set(s);return e.jsxs("section",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-[10px] font-semibold uppercase tracking-wide text-[var(--text-dim)]",children:[t," (",a.length,")"]}),e.jsx("div",{className:"space-y-2",children:a.map(c=>e.jsx(Pe,{entry:c,scenarioHasDefaultFallback:l.has(`${c.method} ${c.pathPattern}`),onSave:r,onRemove:n,onPassthrough:o,onCaptureLive:i},`${c.method} ${c.pathPattern}`))})]})}function qi({scenarioName:t,defaultSlug:a,onClose:s}){return e.jsxs("header",{className:"sticky top-0 z-10 flex items-center justify-between gap-2 border-b border-[var(--border-subtle)] bg-[var(--bg-deep)] px-4 py-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-sm font-medium text-[var(--text-primary)]",children:["Mocks for ",t]}),a&&e.jsxs("p",{className:"text-xs text-[var(--text-dim)]",children:["Defaults inherited from ",e.jsx("span",{className:"font-mono",children:a})]})]}),e.jsx("button",{onClick:s,className:"rounded border border-[var(--border-default)] bg-transparent px-2 py-1 text-xs text-[var(--text-muted)] hover:text-[var(--text-primary)] cursor-pointer",children:"Close"})]})}function Yi({total:t,passed:a,failed:s,discovered:r}){if(t===0&&(r??0)>0)return e.jsxs("span",{className:"text-[var(--text-dim)]",children:[r," ",r===1?"test":"tests"," (not run)"]});if(t===0)return e.jsx("span",{className:"text-[var(--text-dim)]",children:"No tests"});const n=(r??t)>t?(r??t)-t:0;return n>0?e.jsxs("span",{children:[e.jsxs("span",{className:"text-[var(--accent-green)]",children:[a," passed"]}),s>0&&e.jsxs("span",{className:"text-[var(--accent-red)]",children:[" · ",s," failed"]}),e.jsxs("span",{className:"text-[var(--text-dim)]",children:[" · ",n," not run"]})]}):s>0?e.jsxs("span",{className:"text-[var(--accent-red)]",children:[a,"/",t," passed"]}):e.jsxs("span",{className:"text-[var(--accent-green)]",children:[a,"/",t," passed"]})}function Xi({groups:t,loading:a,error:s,totalScenarios:r,onPreviewScenario:n}){return a?e.jsx("div",{className:"py-12 text-center text-[var(--text-muted)]",children:"Loading scenarios..."}):s?e.jsxs("div",{className:"py-12 text-center text-[var(--accent-red)]",children:["Failed to load scenarios: ",s]}):t.length===0?e.jsxs("div",{className:"py-12 text-center text-[var(--text-dim)]",children:[e.jsx("p",{children:"No scenarios defined yet."}),e.jsx("p",{className:"mt-2 text-sm text-[var(--text-dim)]",children:"Create scenario JSON files in .codeyam/scenarios/"})]}):e.jsxs("div",{className:"overflow-y-auto px-6 py-4",style:{maxHeight:"calc(100vh - 110px)"},children:[e.jsxs("p",{className:"mb-4 text-sm text-[var(--text-muted)]",children:[r," scenarios across ",t.length," routes"]}),t.map(o=>e.jsx(ye,{group:o,onPreviewScenario:n},o.route))]})}function Zi({groups:t,loading:a,error:s,cached:r,totalTests:n,passedTests:o,coverage:i,onRefresh:l}){return a?e.jsx("div",{className:"py-12 text-center text-[var(--text-muted)]",children:"Loading tests..."}):s?e.jsxs("div",{className:"py-12 text-center text-[var(--accent-red)]",children:["Failed to load tests: ",s]}):t.length===0?e.jsx("div",{className:"py-12 text-center text-[var(--text-dim)]",children:"No tests found"}):e.jsxs("div",{className:"overflow-y-auto px-6 py-4",style:{maxHeight:"calc(100vh - 110px)"},children:[e.jsxs("div",{className:"mb-4 flex items-center gap-3 text-sm text-[var(--text-muted)]",children:[e.jsxs("span",{children:[o,"/",n," passed across ",t.length," features"]}),e.jsx(te,{coverage:i,testId:"tests-view-coverage",className:"rounded bg-[var(--bg-input)] px-2 py-0.5 text-xs font-medium text-[var(--text-secondary)]"}),r&&e.jsx("span",{className:"rounded bg-[var(--bg-input)] px-2 py-0.5 text-xs text-[var(--text-muted)]",children:"cached"}),e.jsx("button",{onClick:l,disabled:a,className:"rounded bg-[var(--bg-input)] px-2 py-0.5 text-xs text-[var(--text-muted)] hover:bg-[var(--bg-surface)] hover:text-[var(--text-secondary)] disabled:opacity-50",children:a?"Running...":"Run Tests"})]}),t.map(c=>e.jsx(ve,{group:c},c.feature))]})}function ec({onClick:t,isOpen:a,disabled:s}){return e.jsx("button",{type:"button",onClick:t,disabled:s,"aria-expanded":a,"aria-haspopup":"dialog",className:`flex items-center h-7 px-2 rounded text-[11px] font-mono tracking-wide cursor-pointer transition-colors ${s?"text-gray-500 bg-[#2d2d2d] cursor-not-allowed":a?"text-white bg-[#555]":"text-gray-300 bg-[#3a3a3a] hover:bg-[#444]"}`,title:"Edit scenario data",children:"EDIT DATA"})}function $(t){return`${t.method} ${t.pathPattern}`}function tc({slug:t,onApplied:a}){const[s,r]=d.useState({kind:"idle"}),n=d.useCallback(async o=>{r({kind:"submitting"});try{const l=await(await fetch(`/api/scenarios/${encodeURIComponent(t)}/data/describe`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:o})})).json();l.success?(a(),r({kind:"applied",message:l.message??"Changes applied. Review the table and click Save."})):r({kind:"error",message:l.error??"AI rewrite failed."})}catch(i){r({kind:"error",message:i instanceof Error?i.message:"Network error"})}},[t,a]);return{status:s,submit:n}}function ac(t,a){d.useEffect(()=>{function s(n){t.current&&!t.current.contains(n.target)&&a()}function r(n){n.key==="Escape"&&a()}return document.addEventListener("mousedown",s),document.addEventListener("keydown",r),()=>{document.removeEventListener("mousedown",s),document.removeEventListener("keydown",r)}},[t,a])}function sc({props:t,seedTabs:a,mockEntries:s}){const[r,n]=d.useState(null),[o,i]=d.useState(null),[l,c]=d.useState(null),u=d.useMemo(()=>{const x=[];return t&&Object.keys(t).length>0&&x.push({kind:"props",label:"Props",tabs:[]}),a.length>0&&x.push({kind:"seed",label:"Seed Data",tabs:a.map(f=>({id:f.dataKey,label:f.label}))}),s.length>0&&x.push({kind:"mock",label:"Mock Data",tabs:s.map(f=>({id:$(f),label:`${f.method} ${f.pathPattern}`}))}),x},[t,a,s]);d.useEffect(()=>{if(r!==null||u.length===0)return;const x=u[0];n(x.kind),x.kind==="seed"&&x.tabs[0]?i(x.tabs[0].id):x.kind==="mock"&&x.tabs[0]&&c(x.tabs[0].id)},[r,u]);const m=u.find(x=>x.kind===r)??null;function b(x){var f,v,y,j;if(n(x),x==="seed"&&!o){const h=(v=(f=u.find(p=>p.kind==="seed"))==null?void 0:f.tabs[0])==null?void 0:v.id;h&&i(h)}if(x==="mock"&&!l){const h=(j=(y=u.find(p=>p.kind==="mock"))==null?void 0:y.tabs[0])==null?void 0:j.id;h&&c(h)}}return{sections:u,activeSection:m,section:r,activeSeedKey:o,activeMockKey:l,selectSection:b,selectSeedKey:i,selectMockKey:c}}function rc(t){const[a,s]=d.useState(null);return d.useEffect(()=>{var i;const r=(i=t.current)==null?void 0:i.closest("[data-preview-pane='true']");if(!r)return;const n=()=>s(r.getBoundingClientRect().width);n();const o=new ResizeObserver(n);return o.observe(r),()=>o.disconnect()},[t]),a}function V(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function nc(t){return Array.isArray(t)&&t.length>0&&t.every(V)}function I(t,a,s){if(V(t)){for(const[r,n]of Object.entries(t)){const o=a?`${a}.${r}`:r;I(n,o,s)}return}if(nc(t)){t.forEach((r,n)=>I(r,`${a}[${n}]`,s));return}s.push({path:a,value:t})}function W(t){if(!V(t))return[];const a=[];return I(t,"",a),a}function oc(t){return t===null?"null":t===void 0?"":typeof t=="object"?JSON.stringify(t):String(t)}function ic({slug:t,initialProps:a,onCellEdited:s}){const[r,n]=d.useState(()=>W(a)),[o,i]=d.useState(null),[l,c]=d.useState(""),[u,m]=d.useState(""),b=d.useRef(null);d.useEffect(()=>{n(W(a)),i(null)},[a]);function x(h){const p=r.find(M=>M.path===h);i(h);const g=p==null?void 0:p.value,N=g==null?"":typeof g=="object"?JSON.stringify(g):String(g);c(N),m(N)}function f(h){if(c(h),b.current&&clearTimeout(b.current),!o)return;const p=o;b.current=setTimeout(()=>{j(p,h)},600)}function v(){o&&(b.current&&clearTimeout(b.current),j(o,l),i(null))}function y(){if(b.current&&clearTimeout(b.current),!!o){if(l!==u){const h=r.map(p=>p.path===o?{...p,value:z(u)}:p);n(h),fetch(`/api/scenarios/${encodeURIComponent(t)}/data`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:`props.${o}`,value:u})}).then(()=>{B(),s&&s()}).catch(()=>{})}i(null)}}async function j(h,p){const g=r.map(N=>N.path===h?{...N,value:z(p)}:N);n(g);try{await fetch(`/api/scenarios/${encodeURIComponent(t)}/data`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:`props.${h}`,value:p})}),B(),s&&s()}catch{}}return{rows:r,editingPath:o,editValue:l,handleEditPath:x,handleEditValueChange:f,handleSave:v,handleCancelEdit:y}}function ke({path:t,value:a,onValueChange:s,onSave:r,onCancel:n}){return e.jsxs("div",{className:"border-t border-[var(--border-default)] bg-[var(--bg-deep)] px-3 py-2",children:[e.jsx("div",{className:"flex items-center gap-2 mb-1.5",children:e.jsxs("span",{className:"text-[10px] text-[var(--text-muted)]",children:["Editing"," ",e.jsx("strong",{className:"text-[var(--text-secondary)] font-mono",children:t})]})}),e.jsx("textarea",{value:a,onChange:o=>s(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:a.length>100?4:2,onKeyDown:o=>{o.key==="Escape"&&n(),o.key==="Enter"&&(o.metaKey||o.ctrlKey)&&r()}}),e.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[e.jsx("button",{onClick:r,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"}),e.jsx("button",{onClick:n,className:"px-3 py-1 text-[10px] text-[var(--text-muted)] hover:text-[var(--text-primary)] bg-transparent border-none cursor-pointer",children:"Cancel"}),e.jsxs("span",{className:"text-[9px] text-[var(--text-dim)] ml-auto",children:["⌘","+Enter to save, Esc to cancel"]})]})]})}function Ee({slug:t,props:a,onCellEdited:s}){const{rows:r,editingPath:n,editValue:o,handleEditPath:i,handleEditValueChange:l,handleSave:c,handleCancelEdit:u}=ic({slug:t,initialProps:a,onCellEdited:s});return r.length===0?e.jsx("p",{className:"p-4 text-xs text-[var(--text-dim)] italic",children:"This scenario has no props to edit."}):e.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[e.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:e.jsxs("table",{className:"w-full text-[11px] border-separate border-spacing-0",children:[e.jsx("thead",{className:"bg-[var(--bg-card)] sticky top-0 z-10",children:e.jsxs("tr",{children:[e.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"}),e.jsx("th",{className:"text-left font-medium text-[var(--text-secondary)] px-3 py-2 border-b border-[var(--border-default)]",children:"Value"})]})}),e.jsx("tbody",{children:r.map(m=>e.jsxs("tr",{className:"hover:bg-[var(--bg-card)]",children:[e.jsx("td",{className:"px-3 py-1.5 border-b border-[var(--border-subtle)] font-mono text-[var(--text-secondary)] align-top",children:m.path}),e.jsx("td",{className:"px-3 py-1.5 border-b border-[var(--border-subtle)] cursor-text text-[var(--text-primary)] align-top",onClick:()=>i(m.path),children:oc(m.value)})]},m.path))})]})}),n&&e.jsx(ke,{path:n,value:o,onValueChange:l,onSave:c,onCancel:u})]})}function De({slug:t,section:a,hasAnything:s,loading:r,seedError:n,mocksError:o,draftError:i,props:l,selectedSeedTab:c,filteredSeedRows:u,selectedMock:m,onSeedCellEdit:b,onMockSave:x}){return e.jsxs("div",{className:"min-h-0 flex-1 flex flex-col bg-[var(--bg-deep)] overflow-hidden",children:[n&&e.jsxs("p",{className:"p-3 text-xs text-red-400",children:["Seed error: ",n]}),o&&e.jsxs("p",{className:"p-3 text-xs text-red-400",children:["Mocks error: ",o]}),i&&e.jsxs("p",{className:"p-3 text-xs text-red-400",children:["Draft error: ",i]}),r&&!s&&e.jsx("p",{className:"p-4 text-xs text-[var(--text-dim)]",children:"Loading scenario data…"}),!r&&!s&&e.jsx("p",{className:"p-4 text-xs text-[var(--text-dim)] italic",children:"This scenario has no data, mocks, or props to edit."}),a==="props"&&e.jsx(Ee,{slug:t,props:l,onCellEdited:b}),a==="seed"&&c&&e.jsx(ie,{slug:t,tab:c,initialRows:u,onCellEdited:b}),a==="mock"&&m&&e.jsx("div",{className:"flex-1 min-h-0 overflow-auto p-3",children:m.source==="scenario"||m.source==="default"||m.source==="shared"?e.jsx(ce,{entry:m,routeKey:$(m),scenarioSlug:t,onSave:x}):e.jsx(le,{entry:m})})]})}function Re({status:t,onSubmit:a}){const[s,r]=d.useState(""),n=t.kind==="submitting";function o(){const i=s.trim();!i||n||(a(i),r(""))}return e.jsxs("div",{className:"shrink-0 border-t border-[var(--border-default)] bg-[var(--bg-deep)] px-4 py-3",children:[e.jsxs("div",{className:"flex items-end gap-2",children:[e.jsx("textarea",{value:s,onChange:i=>r(i.target.value),placeholder:"Describe Changes",rows:2,disabled:n,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:i=>{i.key==="Enter"&&(i.metaKey||i.ctrlKey)&&(i.preventDefault(),o())}}),e.jsx("button",{type:"button",onClick:o,disabled:n||!s.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:n?"Applying…":"Submit"})]}),t.kind==="applied"&&e.jsx("p",{className:"text-[10px] text-[var(--accent-active)] mt-1.5",children:t.message}),t.kind==="error"&&e.jsx("p",{className:"text-[10px] text-red-400 mt-1.5",children:t.message})]})}function Te({isDirty:t,saving:a,cancelling:s,onSave:r,onCancel:n,onClose:o}){const i=a||s;return e.jsxs(e.Fragment,{children:[t&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:r,disabled:i,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:a?"Saving…":"Save"}),e.jsx("button",{type:"button",onClick:n,disabled:i,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:s?"Cancelling…":"Cancel"})]}),e.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 Be({value:t,disabled:a,onChange:s}){return e.jsx("input",{type:"search",value:t,onChange:r=>s(r.target.value),placeholder:"Search…",disabled:a,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 Me({sections:t,section:a,activeSection:s,onSelect:r}){return t.length>1?e.jsx("select",{value:a??"",onChange:n=>r(n.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:t.map(n=>e.jsx("option",{value:n.kind,children:n.label},n.kind))}):s?e.jsx("span",{className:"text-[9px] font-semibold tracking-wider uppercase text-[var(--text-primary)] px-1.5 py-0.5",children:s.label}):null}function Fe({tabs:t,activeId:a,onSelect:s}){return e.jsx("div",{className:"flex items-center gap-0.5 overflow-x-auto min-w-0",children:t.map(r=>{const n=r.id===a;return e.jsx("button",{type:"button",onClick:()=>s(r.id),className:`px-1.5 py-0.5 text-[9px] font-medium tracking-wide uppercase rounded whitespace-nowrap cursor-pointer transition-colors ${n?"text-[var(--accent-active)] bg-[var(--accent-active)]/10":"text-[var(--text-muted)] hover:text-[var(--text-primary)]"}`,children:r.label},r.id)})})}function Oe({sections:t,section:a,activeSection:s,activeTabId:r,onSelectSection:n,onSelectTab:o,search:i,searchDisabled:l,onSearchChange:c,isDirty:u,saving:m,cancelling:b,onSave:x,onCancel:f,onClose:v}){return e.jsxs("header",{className:"shrink-0 flex items-center justify-between gap-3 px-3 py-1.5 border-b border-[var(--border-subtle)]",children:[e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 flex-1",children:[e.jsx(Me,{sections:t,section:a,activeSection:s,onSelect:n}),e.jsx("span",{className:"text-[var(--text-dim)] text-[10px]",children:"/"}),e.jsx(Fe,{tabs:(s==null?void 0:s.tabs)??[],activeId:r,onSelect:o})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[e.jsx(Be,{value:i,disabled:l,onChange:c}),e.jsx(Te,{isDirty:u,saving:m,cancelling:b,onSave:x,onCancel:f,onClose:v})]})]})}function Le({popoverRef:t,paneWidth:a}){return e.jsx("div",{"aria-hidden":"true",onMouseDown:s=>{const r=t.current;if(!r)return;s.preventDefault();const n=r.getBoundingClientRect(),o=s.clientX,i=s.clientY,l=n.width,c=n.height,u=n.right,m=x=>{const f=x.clientX-o,v=x.clientY-i,y=420,j=280,h=a?Math.max(y,a-16):l+1e3,p=Math.max(y,Math.min(h,l-f)),g=Math.max(j,c+v);r.style.width=`${p}px`,r.style.height=`${g}px`,r.style.right=`${r.parentElement.getBoundingClientRect().right-u}px`},b=()=>{window.removeEventListener("mousemove",m),window.removeEventListener("mouseup",b)};window.addEventListener("mousemove",m),window.addEventListener("mouseup",b)},className:"absolute bottom-0 left-0 w-3 h-3 z-50",style:{cursor:"nesw-resize"}})}function cc({slug:t,scenarioName:a,onClose:s}){const r=d.useRef(null),n=Wo({slug:t,onPreviewReload:B}),o=rc(r),{data:i,tableTabs:l,props:c,loading:u,error:m}=Qo(t),{entries:b,loading:x,error:f,upsertScoped:v}=qo(t),{sections:y,activeSection:j,section:h,activeSeedKey:p,activeMockKey:g,selectSection:N,selectSeedKey:M,selectMockKey:He}=sc({props:c,seedTabs:l,mockEntries:b}),[E,_]=d.useState(""),F=h==="seed"?l.find(S=>S.dataKey===p)??null:null,$e=h==="mock"?b.find(S=>$(S)===g)??null:null,O=F&&i?i[F.dataKey]??[]:[],Ve=d.useMemo(()=>{if(!E.trim())return O;const S=E.toLowerCase();return O.filter(qe=>Object.values(qe).some(Ye=>String(Ye??"").toLowerCase().includes(S)))},[O,E]),D=d.useCallback(()=>{n.markDirty(),B()},[n]),_e=d.useCallback(async S=>{await v(S),D()},[v,D]),K=d.useCallback(()=>{n.confirmIfDirty("Discard unsaved changes to this scenario?")&&s()},[n,s]);ac(r,K);const Ke=d.useCallback(async()=>{await n.save(),n.error||s()},[n,s]),J=tc({slug:t,onApplied:D}),Je=h==="seed"?p:h==="mock"?g:null;function Ge(S){h==="seed"&&M(S),h==="mock"&&He(S)}function ze(S){S!==null&&(N(S),_(""))}const Ue=a??t,We=y.length>0,Qe=u||x;return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed inset-0 z-30 bg-black/30 pointer-events-none","aria-hidden":"true"}),e.jsxs("div",{ref:r,role:"dialog","aria-label":`Edit data for ${Ue}`,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:[e.jsx(Oe,{sections:y,section:h,activeSection:j,activeTabId:Je,onSelectSection:ze,onSelectTab:Ge,search:E,searchDisabled:h!=="seed",onSearchChange:_,isDirty:n.isDirty,saving:n.saving,cancelling:n.cancelling,onSave:Ke,onCancel:()=>void n.cancel(),onClose:K}),e.jsx(De,{slug:t,section:h,hasAnything:We,loading:Qe,seedError:m,mocksError:f,draftError:n.error,props:c,selectedSeedTab:F,filteredSeedRows:Ve,selectedMock:$e,onSeedCellEdit:D,onMockSave:_e}),e.jsx(Re,{status:J.status,onSubmit:J.submit}),e.jsx(Le,{popoverRef:r,paneWidth:o})]})]})}function lc({tabs:t,active:a,onChange:s}){return e.jsx("div",{className:"flex gap-0",children:t.map(r=>e.jsx("button",{onClick:()=>s(r.key),className:`px-3 py-2 text-sm transition-colors border-b-2 ${a===r.key?"font-medium":"border-transparent hover:text-[var(--text-primary)]"}`,style:a===r.key?{color:"var(--accent-active)",borderBottomColor:"var(--accent-active)"}:{color:"var(--text-muted)"},children:r.label},r.key))})}function dc({restartCount:t}){return e.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:e.jsxs("div",{className:"flex flex-col items-center space-y-4 text-center max-w-md p-6",children:[e.jsx(H,{restartCount:t}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 dark:text-gray-100",children:"Dev Server Restarting"}),e.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400",children:"The Live Preview server crashed unexpectedly. CodeYam is automatically recovering it..."})]}),t>2&&e.jsx("div",{className:"pt-2",children:e.jsx("p",{className:"text-xs text-amber-600 dark:text-amber-400 font-medium",children:"Recovery is taking longer than usual..."})})]})})}function uc(){return e.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:e.jsxs("div",{className:"flex flex-col items-center space-y-4 text-center max-w-md p-6",children:[e.jsx(H,{restartCount:0}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 dark:text-gray-100",children:"Starting Dev Server"}),e.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400",children:"Waiting for the development server to start..."})]})]})})}function xc(){return e.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:e.jsxs("div",{className:"flex flex-col items-center space-y-4 text-center max-w-md p-6",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-gray-200 dark:bg-gray-700 flex items-center justify-center",children:e.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:[e.jsx("rect",{x:"6",y:"5",width:"4",height:"14",rx:"1"}),e.jsx("rect",{x:"14",y:"5",width:"4",height:"14",rx:"1"})]})}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 dark:text-gray-100",children:"Dev Server Not Running"}),e.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400",children:"Starting automatically…"})]})]})})}function pc({title:t,count:a,children:s}){return e.jsxs("div",{className:"mt-5",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between gap-4",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.18em] text-[var(--text-dim)]",children:t}),e.jsxs("p",{className:"text-xs text-[var(--text-dim)]",children:[a," total"]})]}),s]})}function Ae(){return e.jsx("div",{className:"rounded-xl border border-dashed border-[var(--border-default)] px-4 py-5 text-sm text-[var(--text-dim)]",children:"No direct imports were found for this route file."})}function mc({directImports:t}){return t.length===0?e.jsx(Ae,{}):e.jsx("div",{className:"grid grid-cols-1 gap-1",children:t.map(a=>{const{fileName:s,dirPath:r}=st(a);return e.jsx(je,{fileName:s,dirPath:r},a)})})}function hc({routeEntity:t}){return e.jsxs("div",{className:"rounded-xl border border-[var(--border-default)] bg-[var(--bg-elevated)] px-4 py-4",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.18em] text-[var(--text-dim)]",children:"Route"}),e.jsx("p",{className:"mt-2 text-lg font-semibold text-[var(--text-primary)]",children:t.displayName}),e.jsx("p",{className:"mt-1 font-mono text-xs text-[var(--accent-blue)]",children:t.route}),t.pageFilePath?e.jsx("p",{className:"mt-3 text-sm text-[var(--text-muted)]",children:t.pageFilePath}):e.jsx("p",{className:"mt-3 text-sm text-[var(--text-dim)]",children:"No source file is linked to this route yet."})]})}function bc({tabs:t,activeTable:a,onSelectTable:s,onClose:r}){return e.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1.5 bg-[var(--bg-card)] border-b border-[var(--border-default)] flex-wrap",children:[t.map(n=>e.jsx(fc,{tab:n,isActive:a===n.dataKey,onClick:()=>s(n.dataKey)},n.dataKey)),e.jsx("div",{className:"flex-1"}),e.jsx("button",{onClick:r,className:"w-5 h-5 flex items-center justify-center text-[var(--text-dim)] hover:text-[var(--text-primary)] bg-[var(--bg-input)] hover:bg-[var(--border-default)] rounded-full border-none cursor-pointer text-xs transition-colors",title:"Close",children:"×"})]})}function fc({tab:t,isActive:a,onClick:s}){const r=t.category==="datastore"?a?"text-[var(--accent-active)] bg-[var(--accent-active)]/15 border-[var(--accent-active)]/40":"text-[var(--accent-active)]/60 bg-transparent border-transparent hover:text-[var(--accent-active)]/80":t.category==="mock-api"?a?"text-[#D7FF63] bg-[#D7FF63]/15 border-[#D7FF63]/40":"text-[#D7FF63]/60 bg-transparent border-transparent hover:text-[#D7FF63]/80":a?"text-[var(--text-primary)] bg-[var(--border-default)] border-[var(--border-default)]":"text-[var(--text-dim)] bg-transparent border-transparent hover:text-[var(--text-secondary)]";return e.jsx("button",{onClick:s,className:`px-2.5 py-0.5 text-[10px] font-semibold uppercase tracking-wider rounded cursor-pointer border transition-colors ${r}`,children:t.label})}function vc({featureName:t,onClose:a}){return e.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center",style:{background:"rgba(30, 30, 30, 0.90)"},children:e.jsx(ae,{featureName:t,onClose:a})})}function Q(){return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16,padding:16,background:"#0d1117",color:"#c9d1d9",fontFamily:"'SF Mono', Menlo, monospace",fontSize:13},children:[e.jsx(Mo,{title:"Section Header Example"}),e.jsxs("div",{style:{display:"flex",gap:8},children:[e.jsx(R,{color:"#238636",children:"ACTIVE"}),e.jsx(R,{color:"#d29922",children:"WARNING"}),e.jsx(R,{color:"#da3633",children:"ERROR"}),e.jsx(R,{color:"#D7FF63",children:"INFO"})]}),e.jsxs("div",{style:{display:"flex",gap:12},children:[e.jsx(k,{method:"GET"}),e.jsx(k,{method:"POST"}),e.jsx(k,{method:"PUT"}),e.jsx(k,{method:"DELETE"}),e.jsx(k,{method:"PATCH"})]}),e.jsx(L,{color:"#238636",children:"Success status message"}),e.jsx(L,{color:"#d29922",children:"Warning status message"}),e.jsx(L,{color:"#8b949e",children:"Neutral status message"})]})}const gc=[{type:"http_request",id:"evt-1",timestampMs:Date.now(),method:"GET",url:"/api/tasks",status:200,durationMs:2,mocked:!0},{type:"http_request",id:"evt-2",timestampMs:Date.now(),method:"POST",url:"/api/users/register",status:201,durationMs:145,mocked:!1}];function q({events:t}){const a=t??gc;return e.jsx("div",{style:{background:"#0d1117",padding:16},children:e.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:12,fontFamily:"'SF Mono', Menlo, monospace",color:"#c9d1d9"},children:[e.jsx("thead",{children:e.jsxs("tr",{style:{borderBottom:"1px solid #30363d"},children:[e.jsx("th",{style:C,children:"Time"}),e.jsx("th",{style:C,children:"Method"}),e.jsx("th",{style:{...C,textAlign:"left"},children:"URL"}),e.jsx("th",{style:C,children:"Status"}),e.jsx("th",{style:C,children:"Duration"}),e.jsx("th",{style:C,children:"Source"})]})}),e.jsx("tbody",{children:a.map(s=>e.jsx(Fo,{event:s},s.id))})]})})}function yc(){return e.jsx("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-0",style:{background:"repeating-linear-gradient(45deg, transparent 0 24px, rgba(255,255,255,0.025) 24px 48px)"}})}function Ie({error:t}){return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-[var(--bg-deep)] text-[var(--accent-red)]",children:e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-lg",children:"Seed Error"}),e.jsx("p",{className:"mt-2 text-sm",children:t}),e.jsx("p",{className:"mt-2 text-xs text-[var(--text-muted)]",children:"The database state shown may not match this scenario."})]})})}const jc={DesignAssetDropLabel:Eo,PendingFileCard:ko,PendingFileList:Po,SaveUploadsButton:Co,UploadErrorMessage:wo,UploadSuccessMessage:No,ProviderAuthGate:So,ProviderAuthenticateCta:Ii,GatedAgentChat:Ai,ProviderAuthModal:Li,ClaudeOAuthFlow:Oi,ApiKeyFlow:Fi,AppCard:jo,AppDetail:yo,AppOverview:go,BuildTab:vo,BuildTabLayout:fo,BuildTabPane:bo,BuildTabPaneLayout:ho,BuildTabRecoveryPanel:mo,BuildTabSessionContent:po,BuildTabStartupError:xo,BuildTabReadyToBuildPlaceholder:_i,BuildTabTerminalSession:uo,AppSelector:Vi,AppTypeBadge:lo,BreadcrumbNav:co,EntityBreadcrumb:io,BuildingPreviewOverlay:oo,ConnectionBadge:zo,DebugModeButton:no,DebugModal:ro,DebugModalElementPreview:so,DebugModalInfoPanel:ao,DebugOverlay:to,DebugAncestryList:eo,DebugAncestrySection:Zn,DebugPropsChips:Xn,DebugFreezePill:Yn,OpenInEditorErrorToast:qn,CyLogo:Qn,DeviceIcon:Wn,EditorNavBar:Un,IdleBanner:zn,EditorSessionRecoveryActionButton:Gn,EditorSessionRecoveryDialog:Jn,EditorSessionRecoveryHeader:Kn,EditorSessionRecovery:_n,EditorSessionRecoverySummaryRow:Vn,EditorSessionRecoverySummary:$n,EditorShellHomeTabContent:Hn,EditorShellBuildLayer:In,EditorShellLayout:An,EditorShellLeftPane:Ln,EditorShellPlanLayer:On,EditorShellPreviewPane:G,EditorShellTabLayer:Fn,MobilePaneSwitcher:Mn,GearIcon:Ki,EventCard:be,EventStream:zi,EntryTypeBadge:he,CollapsibleMarkdown:Y,FeatureNameButton:Bn,FeatureGroupView:ve,FileChangeSummary:de,FileStatusIndicator:xe,FileStatusIndicatorStandalone:Tn,HistoryTab:Rn,HistoryEntryCard:Dn,CommitOnlyHistoryRow:En,NotificationSettingsPopover:kn,NotificationSettingsControls:Pn,NotificationSetupBanner:Cn,DebugNotificationsButton:wn,IdleTriggerCheckbox:Nn,JournalEntryCard:me,JournalEntryDetails:pe,JournalView:$i,LabeledSection:w,FilterBar:Ui,LeftPanel:Sn,ModifiedFilesList:ue,NavLink:A,Markdown:se,NewProjectQuestionnaire:jn,NewProjectQuestionnaireInner:yn,DesignFileUploadStep:gn,QuestionnaireDesignApproachStep:vn,QuestionnaireNotificationsStep:fn,QuestionnaireDesignChatStep:bn,QuestionnaireDesignChatLaunchPanel:hn,MockupArchivedRoundView:mn,MockupCard:pn,MockupLintBadge:xn,MockupCardPreviewSlot:un,MockupCardFeedback:dn,MockupFeedbackCommentBox:ln,MockupFeedbackRatingSlider:cn,MockupGridInfoBanner:on,MockupGridIterateButton:nn,MockupPlaceholderCard:rn,MockupRoundPager:sn,DesignExplorationView:an,QuestionnaireIntroBanner:tn,QuestionnaireDeviceSelector:en,QuestionnaireNavButtons:Zr,QuestionnaireOptionCard:Xr,PanelDivider:Yr,PromptDropdownPanel:qr,PreviewCanvas:Qr,PreviewEmptyState:Wr,PreviewFrame:Ur,BackendResultsPanelView:zr,PlanPreviewPanelView:Gr,PlanPreviewEmptyState:Jr,PlanPreviewHeader:Kr,ProjectSetupPreviewView:_r,ProjectSetupPreviewPane:Vr,StartBuildingConfirmModal:$r,ProjectSetupHeader:Hr,ProjectSetupDescriptionCard:Ir,ProjectSetupProgressList:Ar,ProjectSetupProgressRow:Lr,LiveIframeHealthPill:Or,PreviewPanel:G,BuildLogsModal:Fr,SimulatorLauncherControls:Mr,SimulatorPreviewFrame:Br,NoBootedSimulatorPlaceholder:Tr,QuestionnaireStepNav:Rr,QuestionnaireStepPanel:Dr,AppDetailContent:Er,AppDetailContentError:kr,AppDetailContentLoading:Pr,AppDetailHeader:Cr,AppDetailProjectBand:wr,AppCapabilitiesPanel:Nr,AppStackPanel:Sr,AppStackPanelSummary:jr,AppStackPanelBody:yr,AppStackCapabilitiesSlot:gr,CapabilityRow:vr,AppTestSummary:fr,LayoutChainCard:br,LayoutChainSection:hr,RouteDependencyCard:mr,RouteDependencyCardHeader:pr,RouteDependencyEmptyState:xr,RouteDependencyList:ur,RouteDependencyScenarioStrip:dr,RouteEntityDetail:lr,RouteEntityDetailContent:cr,RouteFunctionCard:ir,RouteFunctionEmptyState:or,RouteFunctionList:nr,RouteEntityDetailHeader:rr,RouteEntityTabs:sr,RouteGroupView:ye,RouteImportRow:je,RouteList:ar,RouteListCardThumbnail:tr,RouteScenarioList:er,ScenarioCard:ge,ScenarioRow:Zs,ScenarioDetailPanel:Wi,MockBodyEditor:Ne,MockBodyHeadersEditor:ne,MockBodyJsonTextarea:Se,MockPanelGroup:Qi,MockPanelHeader:qi,MockPanelRow:Pe,MockPanelRowActions:we,MockPanelRowHeader:Ce,MockSourceBadge:oe,ScenarioThumbnailGrid:X,StatusBadge:fe,StepIndicatorBar:Xs,StepIndicatorDropdownItem:Ys,TabPane:qs,TestItem:ee,TestGroupHeader:Qs,TestGroupList:Ws,TestGroupRow:Us,TestResultsBadge:Z,TestSummary:Yi,TestStatusIcon:zs,ThumbnailStrip:Gs,CollapseToggleButton:Js,DimensionInput:Ks,EditorShell:_s,EntityDetail:Vs,EntityDetailContent:$s,EntityDetailHeader:Hs,EntityRefCard:Is,EntityRefList:As,FillPreviewButton:Ls,OpenInNewTabButton:Os,PlaceholderPane:Fs,PlanTab:Ms,PlanTabHeader:Bs,PlanNextChangeButton:Ts,PlanAuthoringChat:Rs,PlanSubTabs:Ds,DescribePane:Es,PrototypePane:ks,PrototypeAgentChat:Ps,StartPrototypingButton:Cs,FinishAndFormalizeButton:ws,PrototypeBuildingInProgressBanner:Ns,PlanChatLaunchCaption:Ss,PlanExpandedHeader:js,PlanRow:ys,PlanRowClaimBadge:gs,PlanRowDependencyEntry:vs,PlanRowEditButton:fs,PlanRowEditChatButton:bs,PlanRowExpandedBody:hs,PlanRowExpandedChat:ms,PlanRowExpandedDependencies:ps,PlanRowExpandedEdit:xs,PlanRowExpandedView:us,PlanRunButton:ds,PlanRunBlockedModal:ls,PlanRunForeignClaimModal:cs,PlanRunDependenciesModal:is,QueuedChangesSection:os,InFlightSection:ns,InFlightPlanRow:rs,CommitQueueSection:ss,CommitQueueRow:as,CommitQueuePriorityChip:ts,CommitQueueReleaseButton:es,CommitQueueRowIdentity:Za,SortablePlanRow:Xa,RecentPlansSection:Ya,CompletedPlanRow:qa,CompletedPlanExpandedBody:Qa,TabScrollPanel:Wa,BuildLaunchModal:Ua,PostPushTransition:za,PostPushTransitionDialog:Ga,SelectPlanModal:Ja,PlanCompleteDialog:Ka,PlanCompleteTransition:_a,ScenarioRenderer:Dc,ScenariosView:Xi,TerminalEmulator:Va,RawTerminalModal:$a,RawTerminalEmulator:Ha,TerminalDropOverlay:Ia,TerminalDropToast:Aa,TerminalDisconnectOverlay:Mi,TerminalConnectingHint:Bi,TerminalReconnectingBanner:Ti,TerminalFailedBanner:Ri,TerminalServerStoppedBanner:Di,TestsView:Zi,NavigationBar:La,PagePill:Oa,PagePickerDropdown:Fa,StatesDropdown:Ma,CreateStatePlaceholderModal:Ba,StatesPillButton:Ta,EditDataButton:ec,EditDataPopover:cc,EditDataPopoverBody:De,EditDataPopoverDescribeInput:Re,EditDataPopoverHeader:Oe,EditDataPopoverResizeHandleLeft:Le,EditDataPopoverSaveCancelClose:Te,EditDataPopoverSearchInput:Be,EditDataPopoverSectionSelector:Me,EditDataPopoverTabStrip:Fe,ScenarioDataPanelMainProps:Ee,ScenarioDataPanelPropsEditor:ke,ViewportPresetButton:Ra,PagePickerTabButton:Da,PagePickerEmptyMessage:Ea,PagePickerScenarioThumbnail:ka,PagePickerRouteSection:Pa,StatesDropdownRow:Ca,ComponentGlyph:wa,DropdownChevron:Na,PageGlyph:Sa,ViewTabs:lc,SessionResultsPanel:ja,SessionResultsPanelHeader:ya,BackendResultsPage:ga,BackendResultsHeader:va,BackendConnectionStatusBadge:fa,BehaviorGallery:ba,BehaviorGroup:ha,BehaviorItem:ma,BehaviorGalleryEmptyState:pa,NarrativeTestStatusIcon:xa,CoverageBadge:te,CoverageBar:ua,CoverageWarningsBanner:da,CoverageSectionHeader:la,OrphanedFileRow:ca,CoverageDetailsModal:ia,CoverageFileDrilldown:oa,CoverageDetailsEntriesSection:na,CoverageDetailsEntryRow:ra,CoverageDetailsOrphanedSection:sa,CoverageDetailsDirectoriesSection:aa,CoverageDetailsDirectoryGroup:ta,CoverageDetailsDirectoryFileRow:ea,CoverageLineRow:Zt,AppCardFooter:Xt,RunTestsButton:Yt,TestBar:qt,AppCardHeader:Qt,AppCardScenarioStrip:Wt,AppOverviewEmptyState:Ut,AppOverviewEmptyStateBuildingPanel:zt,AppOverviewEmptyStateNoAppPanel:Gt,OpenBuildTabButton:Jt,AppOverviewGrid:Kt,AppOverviewHeader:_t,CopyButton:Vt,CrashLogFooter:$t,CrashLogFooterMessage:Ht,CrashLogHeader:It,CrashLogViewer:At,DevServerCrashLog:Lt,DevServerRestartingOverlay:dc,DevServerStartingOverlay:uc,DevServerStoppedOverlay:xc,PreviewUnhealthyOverlay:Ot,PreviewErrorOverlay:Ft,PreviewErrorOverlayHeader:Mt,PreviewErrorOverlayFooter:Bt,PreviewErrorList:Tt,PreviewErrorRow:Rt,PreviewErrorBadge:Dt,BuildSpinner:Et,BuildShaBadge:kt,RestartSpinner:H,RouteEntitySection:pc,RouteImportEmptyState:Ae,RouteImportList:mc,RouteListCard:Pt,RouteListEmptyState:Ct,RouteListSectionHeader:wt,RouteScenarioEmptyState:Nt,RouteSummaryCard:hc,SafeScreenshot:St,ScenarioRowMeta:jt,ScenarioRowOverrideBadge:yt,ScenarioRowThumbnail:gt,SidebarGroupOverrideHeader:Ei,SidebarInheritedSection:ki,DataViewerCategoryBadge:Pi,DataViewerCellEditor:Ci,DataViewerTabBar:bc,DataViewerTable:wi,ScenarioDataPanel:re,ScenarioDataPanelCloseButton:Ni,ScenarioDataPanelEditChatButton:Si,ScenarioDataPanelEmptyState:ji,ScenarioDataPanelFullPage:Hi,ScenarioDataPanelHeader:yi,ScenarioDataPanelInspectButton:gi,ScenarioDataPanelMainMock:vi,ScenarioDataPanelMainMockEditable:ce,ScenarioDataPanelMainMockHeader:fi,ScenarioDataPanelMainMockReadOnly:le,ScenarioDataPanelMainTable:ie,ScenarioDataPanelOpenInNewButton:bi,ScenarioDataPanelMockDataBadge:hi,ScenarioDataPanelMockDataStrip:mi,ScenarioDataPanelSidebar:pi,SaveScopeChoiceRow:xi,SaveScopeModal:ui,SidebarMockEntryRow:di,MockSharedSlugBadge:li,ScenarioDraftBar:ci,JsonBodyActions:ii,JsonTreeAddKeyInput:oi,JsonTreeArrayNode:ni,JsonTreeEditor:ri,JsonTreeNode:si,JsonTreeNodeLine:ai,JsonTreeObjectNode:ti,JsonTreePrimitiveEditor:ei,JsonTreePrimitiveNode:Zo,ScenarioRenameForm:vt,ScenarioRowActions:ft,MiniAgentChat:Xo,MiniAgentLaunchOverlay:Yo,EnvelopeIcon:bt,SendTranscriptModal:ae,SendTranscriptOverlay:vc,ContainerInspector:Go,InspectorScenarioSection:Jo,InspectorRouteTable:Ko,InspectorTrafficSection:_o,InspectorExplainerSection:Vo,InspectorExplainerResult:$o,InspectorPrimitivesShowcase:Q,InspectorTrafficRowShowcase:q,InspectorTrafficDetail:Ho,InspectorTrafficFilterBar:Io,InspectorTrafficTable:Ao,InspectorTrafficUrlChips:Lo,InspectorUrlGlossary:Oo,InspectorPrimitives:Q,InspectorTrafficRow:q,StepsSimulator:Bo,StepsSimulatorStepList:To,StepsSimulatorVariableControl:Ro,StepsSimulatorInstructionsPanel:Do,SeedErrorBanner:ht,SeedLoadingOverlay:mt,StaleDbStripeOverlay:yc,ScenarioSeedErrorView:Ie,InspectModeRibbon:pt,IframeClickThroughErrorCard:xt,InspectResultCard:ut,InspectResultCardBackdrop:dt,InspectResultCardBody:lt,InspectResultCardHeader:ct,InspectResultCardMatchButton:it,InspectResultCardMatchList:ot,SkeletonBar:nt,PreviewWaitingPlaceholder:rt};function Sc(t){const a={};for(const[s,r]of Object.entries(t))a[s]=P(r);return a}const Nc=new Set(["div","span","p","strong","em","code","pre","h1","h2","h3","h4","h5","h6","ul","ol","li","a","br","hr","img","section","header","footer","nav","article","button"]);function P(t){if(t==="__noop__")return()=>{};if(t==null||typeof t!="object")return t;if(Array.isArray(t))return t.map(P);if(t.__type==="noop")return()=>{};if(t.__type==="undefined")return;if(t.__type==="Ref")return{current:null};if(t.__type==="Date"&&typeof t.value=="string")return new Date(t.value);if(t.__type==="Set"&&Array.isArray(t.values))return new Set(t.values.map(P));if(t.__type==="ReactNode"){if(typeof t.text=="string")return t.text;if(typeof t.element=="string"){if(!Nc.has(t.element))return null;const s=t.children!=null?P(t.children):void 0;return d.createElement(t.element,t.props||null,s)}}if(t.__type==="Map"&&typeof t.entries=="object"&&t.entries!==null){const s=new Map;for(const[r,n]of Object.entries(t.entries))s.set(r,P(n));return s}const a={};for(const[s,r]of Object.entries(t))a[s]=P(r);return a}function wc(t){if(!t||typeof t!="object")return!1;const a=t,s=a.http?Object.keys(a.http).length:0,r=a.db?Object.keys(a.db).length:0;return s>0||r>0}const Cc=new Set(["EditorShell"]);function Pc(t){return t?jc[t]??null:null}function kc(t){const[a,s]=d.useState({Component:null,props:{},name:"",loading:!0,error:null,needsRouter:!1,displayHints:null,seed:null,scenarioType:null,hasMocks:!1,url:null});return d.useEffect(()=>{let r=!1;return s(n=>({...n,loading:!0,error:null})),fetch(`/api/scenarios/${encodeURIComponent(t)}`).then(n=>n.json()).then(n=>{if(r)return;if(n.error){s({Component:null,props:{},name:"",loading:!1,error:n.error,needsRouter:!1,displayHints:null,seed:null,scenarioType:null,hasMocks:!1,url:null});return}const o=Pc(n.componentName),i=n.scenarioType==="application"||n.scenarioType==="component"?n.scenarioType:null,l=n.seed??null,c=wc(n.mocks),u=typeof n.url=="string"?n.url:null;if(!o&&n.componentName){s({Component:null,props:{},name:n.name??"",loading:!1,error:`Component "${n.componentName}" not found in registry`,needsRouter:!1,displayHints:null,seed:l,scenarioType:i,hasMocks:c,url:u});return}s({Component:o,props:Sc(n.props??{}),name:n.name??"",loading:!1,error:null,needsRouter:Cc.has(n.componentName??""),displayHints:n.displayHints??null,seed:l,scenarioType:i,hasMocks:c,url:u})}).catch(n=>{r||s({Component:null,props:{},name:"",loading:!1,error:n.message,needsRouter:!1,displayHints:null,seed:null,scenarioType:null,hasMocks:!1,url:null})}),()=>{r=!0}},[t]),a}function Ec({name:t,url:a}){return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-[var(--bg-deep)] text-[var(--text-muted)]",children:e.jsxs("div",{className:"max-w-md text-center",children:[e.jsx("p",{className:"text-lg",children:t}),e.jsx("p",{className:"mt-2 text-sm",children:"This is an application scenario — it renders on its own app route, not the component preview path."}),a?e.jsxs("p",{className:"mt-3 text-sm",children:["Open it at"," ",e.jsx("a",{href:a,className:"underline text-[var(--accent-blue,#6ab0ff)]",children:a})," ","(its seed and mocks are already active)."]}):e.jsx("p",{className:"mt-3 text-sm",children:"Activate the scenario, then navigate the preview to its app route to see it."})]})})}function Dc({slug:t}){const{Component:a,props:s,name:r,loading:n,error:o,needsRouter:i,displayHints:l,seed:c,scenarioType:u,hasMocks:m,url:b}=kc(t),[x,f]=d.useState(!1),[v,y]=d.useState(null);if(d.useEffect(()=>{if(n)return;let h=!1;return f(!1),y(null),u==="component"&&c==null&&!m?(f(!0),()=>{h=!0}):(fetch("/api/editor-activate-scenario",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({slug:t})}).then(async p=>{const g=await p.json().catch(()=>null);h||(g&&(g.seedError||g.success===!1)&&(c!=null?y(g.seedError||g.error||"scenario activation failed"):console.warn("[scenario] activation returned failure for no-seed scenario; ignoring",g)),f(!0))}).catch(p=>{h||(c!=null?y(p instanceof Error?p.message:String(p)):console.warn("[scenario] activation request failed for no-seed scenario; ignoring",p),f(!0))}),()=>{h=!0,fetch("/api/editor-deactivate-scenario",{method:"POST"}).catch(()=>{})})},[t,n,c,u,m]),n||!x)return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-[var(--bg-deep)] text-[var(--text-muted)]",children:"Loading scenario..."});if(v)return e.jsx(Ie,{error:v});if(o)return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-[var(--bg-deep)] text-[var(--accent-red)]",children:e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-lg",children:"Scenario Error"}),e.jsx("p",{className:"mt-2 text-sm",children:o})]})});if(!a)return u==="application"?e.jsx(Ec,{name:r,url:b}):e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-[var(--bg-deep)] text-[var(--text-muted)]",children:e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-lg",children:r}),e.jsx("p",{className:"mt-2 text-sm",children:"No component specified for this scenario"})]})});const j=e.jsx(a,{...s});return i?j:e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-[var(--bg-deep)] p-4",children:e.jsx("div",{className:"w-full",style:l!=null&&l.maxWidth?{maxWidth:l.maxWidth}:void 0,children:j})})}export{Dc as ScenarioRenderer};
@@ -1 +0,0 @@
1
- import{j as e}from"./markdown-v0F0UEt3.js";import{b as d}from"./react-CSS0HapR.js";import{M as I}from"./Markdown-BHBqz-Mj.js";function E({workflow:n,selectedSlug:r,onSelectSlug:t}){return e.jsx("div",{style:{padding:"4px 8px 16px",flex:1},children:n.steps.map(o=>o.kind==="slug"?e.jsx(k,{position:o.position,slug:o.slug,label:o.label,description:o.description,isSelected:r===o.slug,onSelect:()=>t(o.slug)},`slug-${o.position}-${o.slug}`):e.jsx(D,{position:o.position,ifKey:o.ifKey,arms:o.arms,selectedSlug:r,onSelectSlug:t},`branch-${o.position}`))})}function k({position:n,slug:r,label:t,description:o,isSelected:s,onSelect:i,indent:l=0,branchHint:a}){return e.jsxs("button",{onClick:i,style:{display:"flex",alignItems:"flex-start",gap:8,padding:"7px 8px",paddingLeft:8+l,borderRadius:4,border:"none",cursor:"pointer",textAlign:"left",fontSize:13,width:"100%",background:s?"var(--bg-input)":"transparent",color:s?"var(--accent-active)":"var(--text-secondary)",fontWeight:s?600:400},children:[e.jsx("span",{style:{width:22,textAlign:"right",color:"var(--text-muted)",fontSize:11,fontFamily:"'IBM Plex Mono', monospace",flexShrink:0,paddingTop:1},children:n}),e.jsxs("span",{style:{flex:1,display:"flex",flexDirection:"column"},children:[e.jsxs("span",{children:[t,a&&e.jsx("span",{style:{marginLeft:6,fontSize:10,color:"var(--text-dim)",fontFamily:"'IBM Plex Mono', monospace"},children:a})]}),e.jsx("span",{style:{fontSize:11,color:o?"var(--text-muted)":"var(--accent-error, #d44)",marginTop:2,fontWeight:400},children:o??"(missing description)"}),e.jsx("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:1,fontFamily:"'IBM Plex Mono', monospace"},children:r})]})]})}function D({position:n,ifKey:r,arms:t,selectedSlug:o,onSelectSlug:s}){return e.jsxs("div",{children:[e.jsxs("div",{style:{padding:"4px 8px",fontSize:11,color:"var(--text-dim)",fontStyle:"italic"},children:["Branch on ",e.jsx("code",{children:r})," (position ",n,")"]}),t.map(i=>e.jsx(k,{position:n,slug:i.slug,label:i.label,description:i.description,isSelected:o===i.slug,onSelect:()=>s(i.slug),indent:20,branchHint:`(${i.outcome})`},`${n}-${i.slug}`))]})}const F=["provider","feature","dimension","screenSizes","hasProject","isResuming","designSystem","stack","needsScaffold","projectDescription","startCommand","hasGlossary","hasUserPrompt","selectedPlan","needsInitialStartingSurface","port","controlPort"],L={provider:"Provider",feature:"Feature Name",dimension:"Dimension",screenSizes:"Screen Sizes",hasProject:"Has Project",isResuming:"Is Resuming",designSystem:"Design System",stack:"Stack Config",needsScaffold:"Needs Scaffold",projectDescription:"Project Description",startCommand:"Start Command",hasGlossary:"Has Glossary",hasUserPrompt:"Has User Prompt",selectedPlan:"Selected Plan",needsInitialStartingSurface:"Needs Initial Starting Surface",port:"Port",controlPort:"Control Port"};function V({visibleVariables:n,vars:r,onVarChange:t}){return n.length===0?e.jsx("div",{style:{padding:"12px 20px",borderBottom:"1px solid var(--border-default)",fontSize:12,color:"var(--text-muted)",fontStyle:"italic"},children:"This step has no input variables — its rendered output is the same in every context."}):e.jsx("div",{style:{padding:"12px 20px",borderBottom:"1px solid var(--border-default)",display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(220px, 1fr))",gap:12},children:n.filter(o=>F.includes(o)).map(o=>e.jsx(A,{fieldKey:o,value:r[o],onChange:s=>t(o,s)},o))})}function A({fieldKey:n,value:r,onChange:t}){const o=L[n],s=typeof r=="boolean",i=typeof r=="number",l=Array.isArray(r);return e.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:4,fontSize:11,color:"var(--text-muted)"},children:[e.jsx("span",{children:o}),s?e.jsx("input",{type:"checkbox",checked:r,onChange:a=>t(a.target.checked),style:{alignSelf:"flex-start"}}):i?e.jsx("input",{type:"number",value:r,onChange:a=>t(Number(a.target.value)),style:y()}):l?e.jsx("input",{type:"text",value:r.join(", "),onChange:a=>t(a.target.value.split(",").map(f=>f.trim()).filter(Boolean)),placeholder:"comma-separated",style:y()}):e.jsx("input",{type:"text",value:typeof r=="string"?r:"",onChange:a=>t(a.target.value||null),placeholder:"(unset)",style:y()})]})}function y(){return{background:"var(--bg-input)",border:"1px solid var(--border-default)",borderRadius:3,padding:"4px 6px",fontSize:12,color:"var(--text-primary)",fontFamily:"'IBM Plex Mono', monospace"}}function W({rendered:n,renderError:r,renderLoading:t,selectedSlug:o,selectedDescription:s,visibleVariables:i,vars:l,onVarChange:a}){return e.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden"},children:[e.jsx(T,{rendered:n,selectedSlug:o,selectedDescription:s}),e.jsx(V,{visibleVariables:i,vars:l,onVarChange:a}),e.jsx($,{rendered:n,renderError:r,renderLoading:t})]})}function T({rendered:n,selectedSlug:r,selectedDescription:t}){return e.jsxs("div",{style:{padding:"16px 20px 12px",borderBottom:"1px solid var(--border-default)"},children:[e.jsx("div",{style:{fontSize:11,color:"var(--text-dim)",fontFamily:"'IBM Plex Mono', monospace",marginBottom:4},children:r??"no step selected"}),e.jsx("h2",{style:{fontSize:18,fontWeight:600,color:"var(--text-primary)",margin:0},children:(n==null?void 0:n.label)??"—"}),e.jsx("p",{style:{fontSize:13,color:t?"var(--text-muted)":"var(--accent-error, #d44)",margin:"6px 0 0"},children:t??"(missing description)"})]})}function $({rendered:n,renderError:r,renderLoading:t}){return e.jsx("div",{style:{flex:1,overflow:"auto",padding:"16px 20px"},children:r?e.jsx(S,{message:r,kind:"render"}):n?e.jsx("div",{style:{opacity:t?.6:1},children:e.jsx(I,{children:n.instructions})}):e.jsx("div",{style:{color:"var(--text-muted)",fontSize:13},children:t?"Rendering…":"Select a step."})})}function N(){return{provider:"claude",port:3e3,controlPort:14199,dimension:"Desktop",screenSizes:["Desktop"],hasProject:!1,isResuming:!1,needsScaffold:!1,startCommand:"npm run dev",hasGlossary:!1,hasUserPrompt:!1,selectedPlan:null,needsInitialStartingSurface:!1}}function _(){const[n,r]=d.useState("ui"),[t,o]=d.useState(null),[s,i]=d.useState(null),[l,a]=d.useState(null),[f,P]=d.useState(N),[w,g]=d.useState(null),[B,m]=d.useState(null),[z,b]=d.useState(!1),v=d.useCallback(async x=>{i(null),o(null),g(null),m(null),a(null);try{const u=await(await fetch(`/api/workflow?mode=${x}`)).json();if("error"in u){i(u.error);return}o(u);const p=H(u);a(p)}catch(c){i(c instanceof Error?c.message:String(c))}},[]);d.useEffect(()=>{v(n)},[n,v]);const j=d.useCallback(async(x,c,u)=>{b(!0),m(null);try{const h=await(await fetch("/api/workflow/render",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({slug:x,mode:c,vars:u})})).json();if("error"in h){g(null),m(h.error);return}g(h)}catch(p){g(null),m(p instanceof Error?p.message:String(p))}finally{b(!1)}},[]);d.useEffect(()=>{l&&j(l,n,f)},[l,n,f,j]);const C=l?O(t,l):null,M=t&&l?U(t,l):[],R=t?[...M,...t.globalVariables??[]]:[];return e.jsxs("div",{style:{display:"flex",height:"100vh",background:"var(--bg-deep)",color:"var(--text-secondary)",fontFamily:"'IBM Plex Sans', system-ui, sans-serif"},children:[e.jsx(G,{mode:n,workflow:t,loadError:s,selectedSlug:l,onModeChange:r,onSelectSlug:a}),e.jsx(W,{rendered:w,renderError:B,renderLoading:z,selectedSlug:l,selectedDescription:C,visibleVariables:R,vars:f,onVarChange:(x,c)=>P(u=>({...u,[x]:c}))})]})}function H(n){for(const r of n.steps){if(r.kind==="slug")return r.slug;if(r.kind==="branch"&&r.arms.length>0)return r.arms[0].slug}return null}function O(n,r){if(!n)return null;for(const t of n.steps){if(t.kind==="slug"&&t.slug===r)return t.description;if(t.kind==="branch"){const o=t.arms.find(s=>s.slug===r);if(o)return o.description}}return null}function U(n,r){for(const t of n.steps){if(t.kind==="slug"&&t.slug===r)return t.variables??[];if(t.kind==="branch"){const o=t.arms.find(s=>s.slug===r);if(o)return o.variables??[]}}return[]}function G({mode:n,workflow:r,loadError:t,selectedSlug:o,onModeChange:s,onSelectSlug:i}){return e.jsxs("div",{style:{width:360,minWidth:360,borderRight:"1px solid var(--border-default)",display:"flex",flexDirection:"column",overflow:"auto"},children:[e.jsx(K,{}),e.jsx(J,{mode:n,onChange:s}),t?e.jsx(S,{message:t,kind:"load"}):r?e.jsx(E,{workflow:r,selectedSlug:o,onSelectSlug:i}):e.jsx("div",{style:{padding:16,color:"var(--text-muted)"},children:"Loading…"})]})}function K(){return e.jsxs("div",{style:{padding:"16px 16px 12px",borderBottom:"1px solid var(--border-default)"},children:[e.jsx("h1",{style:{fontSize:16,fontWeight:600,color:"var(--text-primary)",margin:0},children:"Workflow Viewer"}),e.jsx("p",{style:{fontSize:12,color:"var(--text-muted)",margin:"4px 0 0"},children:"Live data from the server. Click a step to see its instructions and edit variables to see how the rendered text changes."})]})}function J({mode:n,onChange:r}){return e.jsx("div",{style:{padding:"12px 16px 8px"},children:e.jsx("div",{style:{display:"flex",gap:4},children:["ui","backend"].map(t=>e.jsx("button",{onClick:()=>r(t),style:{padding:"5px 12px",borderRadius:4,border:"none",cursor:"pointer",fontSize:12,fontWeight:500,flex:1,background:n===t?"var(--accent-active)":"var(--bg-input)",color:n===t?"#000":"var(--text-secondary)"},children:t==="ui"?"UI":"Backend"},t))})})}function S({message:n,kind:r}){return e.jsxs("div",{style:{margin:16,padding:12,borderRadius:4,background:"rgba(220, 60, 60, 0.1)",border:"1px solid rgba(220, 60, 60, 0.3)",color:"#f99",fontSize:12,fontFamily:"'IBM Plex Mono', monospace",whiteSpace:"pre-wrap"},children:[e.jsx("div",{style:{fontWeight:600,marginBottom:4},children:r==="load"?"Failed to load workflow":"Failed to render step"}),n]})}const X=Object.freeze(Object.defineProperty({__proto__:null,ErrorBanner:S,StepsSimulator:_},Symbol.toStringTag,{value:"Module"}));export{W as S,V as a,E as b,_ as c,X as d};