@codeyam-editor/codeyam-editor 0.1.14 → 0.1.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/npm/agent-cli-install.js +102 -0
- package/npm/cloud.js +50 -53
- package/npm/editor.js +23 -0
- package/npm/fleet-add-failure.js +53 -2
- package/npm/fleet-auth.js +17 -1
- package/npm/launch-config.js +20 -3
- package/npm/launcher-boot-log.js +57 -0
- package/npm/operator-host-disk.js +44 -0
- package/npm/scenario-check.js +172 -1
- package/npm/scenario-metrics.js +101 -0
- package/npm/scenario-playwright.js +77 -5
- package/npm/utils.js +140 -21
- package/package.json +5 -5
- package/ui/dist/assets/{ContainerInspector-9w8TlRwl.js → ContainerInspector-Ceop11Fv.js} +1 -1
- package/ui/dist/assets/EditorShell-DjI5cEF_.js +366 -0
- package/ui/dist/assets/ScenarioDataPanel-D-nWT7xD.js +21 -0
- package/ui/dist/assets/{ScenarioDataPanelFullPage-DkysGs6X.js → ScenarioDataPanelFullPage-ZNFZcTQU.js} +1 -1
- package/ui/dist/assets/ScenarioRenderer-BW6QLGFW.js +26 -0
- package/ui/dist/assets/index-B3SMxYUB.css +1 -0
- package/ui/dist/assets/{index-CqKB9WVm.js → index-ClrdYzlw.js} +6 -6
- package/ui/dist/index.html +2 -2
- package/ui/dist/assets/EditorShell-CmEoMxKh.js +0 -366
- package/ui/dist/assets/ScenarioDataPanel-BM7COEfv.js +0 -21
- package/ui/dist/assets/ScenarioRenderer-M3HRiuEn.js +0 -26
- package/ui/dist/assets/index-Bk0fHYF3.css +0 -1
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
import{j as s}from"./markdown-C9tbsVHX.js";import{b as i}from"./react-nrLBr15I.js";import{a as cn,u as ln,d as Kr,C as Re,c as Hr}from"./useServerIdentity-CVuHTzjg.js";import{u as Ur}from"./useEvents-DNb1olaj.js";import{r as Wr,a as Yr}from"./xterm--24IGk-x.js";import{l as G,n as Vr}from"./index-CqKB9WVm.js";const Jr=500,Ie=new Set;let Ee=null,Ue=null;async function ht(){let e;try{const t=await fetch("/api/editor-dev-server");t.ok?e={ok:!0,data:await t.json()}:e={ok:!1,error:`Failed to fetch dev server status: ${t.statusText}`}}catch(t){e={ok:!1,error:t instanceof Error?t.message:String(t)}}if(Ie.size!==0){Ue=e;for(const t of[...Ie])t(e)}}function Xr(e){return Ie.add(e),Ue&&e(Ue),Ee===null&&(Ee=setInterval(()=>{ht()},Jr),ht()),()=>{Ie.delete(e),Ie.size===0&&Ee!==null&&(clearInterval(Ee),Ee=null,Ue=null)}}function qr(){ht()}const un="Connected to the editor server at ";function dn(e){const t=e===null?null:e?"in the cloud container":"on this machine";return t?`, running ${t}.`:"."}function Gr(e,t){return e===null?null:`${un}${e}${dn(t)}`}function Qr({headline:e,explanation:t,nextAction:n,diagnostics:r,connection:a}){const o=[`CodeYam editor — ${e}`,`What happened
|
|
2
|
-
${t}`,`What to do
|
|
3
|
-
${n}`],c=r==null?void 0:r.trim();c&&o.push(`Details
|
|
4
|
-
${c}`);const l=a==null?void 0:a.trim();return l&&o.push(`Connection
|
|
5
|
-
${l}`),o.join(`
|
|
6
|
-
|
|
7
|
-
`)}function mt(e){return typeof e=="string"?e:typeof e=="number"?String(e):Array.isArray(e)?e.map(mt).join(""):""}const Zr={error:{accent:"var(--accent-red, #dc2626)",surface:"var(--bg-base)",label:"Error"},warning:{accent:"var(--accent-amber, #d97706)",surface:"var(--bg-base)",label:"Warning"},blocked:{accent:"var(--accent-primary, #2563eb)",surface:"var(--bg-base)",label:"Blocked"}};function fn({headline:e,palette:t,report:n,copyLabel:r}){return s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide",style:{color:t.accent},children:t.label}),s.jsx("h2",{className:"text-base font-semibold leading-snug",children:e})]}),s.jsx(cn,{variant:"subtle",text:n,label:r,ariaLabel:`Copy this report: ${e}`})]})}const di=Object.freeze(Object.defineProperty({__proto__:null,ErrorNoticeHeader:fn},Symbol.toStringTag,{value:"Module"}));function pn({nextAction:e,palette:t}){return s.jsxs("div",{className:"rounded border-l-2 pl-3",style:{borderLeftColor:t.accent},children:[s.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wide",style:{color:t.accent},children:"What to do"}),s.jsx("div",{style:{color:"var(--text-primary)"},children:e})]})}const fi=Object.freeze(Object.defineProperty({__proto__:null,ErrorNoticeNextAction:pn},Symbol.toStringTag,{value:"Module"}));function hn({diagnostics:e,testId:t}){return s.jsx("pre",{"data-testid":t,className:"m-0 max-h-48 overflow-auto whitespace-pre-wrap rounded px-3 py-2 font-mono text-xs leading-snug",style:{background:"var(--bg-surface)",color:"var(--text-secondary)"},children:e})}const pi=Object.freeze(Object.defineProperty({__proto__:null,ErrorNoticeDiagnostics:hn},Symbol.toStringTag,{value:"Module"}));function mn({actions:e,palette:t,actionFeedback:n}){return e.length===0&&!n?null:s.jsxs(s.Fragment,{children:[e.length>0?s.jsx("div",{className:"flex flex-wrap items-center gap-2",children:e.map(r=>s.jsx("button",{type:"button",onClick:r.onClick,disabled:r.pending,"aria-label":r.ariaLabel,"data-testid":r.testId,className:"rounded px-3 py-1.5 text-sm font-medium disabled:cursor-not-allowed disabled:opacity-70",style:r.variant==="secondary"?{border:"1px solid var(--border-default)",color:"var(--text-primary)"}:{background:t.accent,color:"var(--bg-base)"},children:r.pending?r.pendingLabel??`${r.label}…`:r.label},r.label))}):null,n?s.jsx("div",{className:"text-xs",style:{color:"var(--text-dim)"},children:n}):null]})}const hi=Object.freeze(Object.defineProperty({__proto__:null,ErrorNoticeActions:mn},Symbol.toStringTag,{value:"Module"}));function be({headline:e,explanation:t,nextAction:n,explanationText:r,nextActionText:a,diagnostics:o,severity:c="error",actions:l=[],actionFeedback:d,copyLabel:f="Copy this report",testId:g,className:b}){const{projectDir:u,inContainer:h,loaded:m}=ln(),x=Zr[c],y=m?Gr(u,h):null,p=Qr({headline:e,explanation:r??mt(t),nextAction:a??mt(n),diagnostics:o,connection:y});return s.jsxs("div",{role:"alert","aria-label":e,"data-testid":g,className:b??"flex w-full max-w-2xl flex-col gap-3 rounded-lg border border-l-4 p-5 text-sm shadow-lg",style:{background:x.surface,borderColor:"var(--border-default)",borderLeftColor:x.accent,color:"var(--text-primary)"},children:[s.jsx(fn,{headline:e,palette:x,report:p,copyLabel:f}),s.jsx("p",{style:{color:"var(--text-dim)"},children:t}),s.jsx(pn,{nextAction:n,palette:x}),o?s.jsx(hn,{diagnostics:o,testId:g?`${g}-diagnostics`:void 0}):null,s.jsx(mn,{actions:l,palette:x,actionFeedback:d}),u!==null&&m?s.jsxs("p",{className:"text-xs",style:{color:"var(--text-dim)"},children:[un,s.jsx("code",{children:u}),dn(h)]}):null]})}const mi=Object.freeze(Object.defineProperty({__proto__:null,ErrorNotice:be},Symbol.toStringTag,{value:"Module"}));function bn(){return s.jsx("div",{"data-codeyam-capture-placeholder":"MiniAgentChat",style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",padding:"0 16px",textAlign:"center",color:"#8a8a8a",fontFamily:"'IBM Plex Mono', 'Menlo', 'Monaco', monospace",fontSize:12,lineHeight:1.6},children:"No agent session is started in a captured screenshot."})}const bi=Object.freeze(Object.defineProperty({__proto__:null,CaptureChatPlaceholder:bn},Symbol.toStringTag,{value:"Module"})),Tt="claude";function es(e){return e==="claude"}function ts(e){return e!=="gemini"}function ke(e){switch(e){case"codex":return"Codex";case"gemini":return"Gemini";case"opencode":return"OpenCode";default:return"Claude"}}function gn(e){return e>=500?"transient":"rejected"}function xn({provider:e,onAuthenticated:t}){const[n,r]=i.useState(""),[a,o]=i.useState(!1),[c,l]=i.useState(null),[d,f]=i.useState(!1),g=ke(e),b=i.useCallback(async()=>{if(n.trim()){o(!0),l(null),f(!1);try{const u=await fetch("/api/auth/api-key",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({provider:e,key:n.trim()})});if(!u.ok){if(gn(u.status)==="transient"){f(!0),l(`The editor was briefly unreachable (HTTP ${u.status}). Your key wasn't rejected — try again.`);return}const h=await u.json().catch(()=>({}));l(h.error??`Could not save the key (HTTP ${u.status}).`);return}r(""),t()}catch{f(!0),l("Could not reach the editor to save the key. Try again.")}finally{o(!1)}}},[n,e,t]);return s.jsxs("div",{"data-testid":"api-key-flow",className:"space-y-3",children:[s.jsxs("p",{className:"text-sm text-[#8E8E8E]",children:["Paste your ",g," API key. It is stored locally in",s.jsx("code",{className:"mx-1 text-[#D7FF63]",children:".codeyam/editor.local.json"}),"and never committed."]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"password",value:n,onChange:u=>r(u.target.value),placeholder:`${g} API key`,className:"flex-1 min-w-0 px-2 py-1.5 rounded bg-black border border-[#3A3A3A] text-white text-sm"}),s.jsx("button",{onClick:()=>void b(),disabled:a||!n.trim(),className:"px-3 py-1.5 text-sm rounded-md bg-[#D7FF63] text-black font-medium cursor-pointer disabled:opacity-50",children:a?"Saving…":"Save"})]}),c?s.jsxs("div",{className:"space-y-2",children:[s.jsx("p",{className:"text-sm text-[#FF8B43]",children:c}),d?s.jsx("button",{"data-testid":"api-key-flow-retry",onClick:()=>void b(),disabled:a||!n.trim(),className:"px-3 py-1.5 text-sm rounded-md border border-[#3A3A3A] text-white font-medium cursor-pointer disabled:opacity-50",children:a?"Saving…":"Retry"}):null]}):null]})}const gi=Object.freeze(Object.defineProperty({__proto__:null,ApiKeyFlow:xn,classifyApiKeySaveFailure:gn},Symbol.toStringTag,{value:"Module"}));function ye({onRetry:e,onRecheck:t,rechecking:n,retryLabel:r="Retry",retryTestId:a,recheckTestId:o}){return s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("button",{onClick:e,"data-testid":a,className:"px-3 py-2 text-sm rounded-md bg-[#D7FF63] text-black font-medium cursor-pointer",children:r}),s.jsx("button",{onClick:t,"data-testid":o,disabled:n,className:"px-3 py-2 text-sm rounded-md border border-[#3A3A3A] text-white cursor-pointer disabled:opacity-50",children:n?"Rechecking…":"I already logged in — recheck"})]})}const xi=Object.freeze(Object.defineProperty({__proto__:null,RecoveryActions:ye},Symbol.toStringTag,{value:"Module"}));function yn({timedOut:e,onRetry:t,onRecheck:n,rechecking:r}){return e?s.jsxs("div",{"data-testid":"claude-oauth-install-timeout",className:"space-y-3",children:[s.jsxs("p",{className:"text-sm text-[#FF8B43]",children:["Installing the Claude command-line tool is taking longer than expected. Try again, or install it yourself in a terminal with"," ",s.jsx("code",{className:"text-white",children:"npm install -g @anthropic-ai/claude-code"})," ","and then retry."]}),s.jsx(ye,{onRetry:t,onRecheck:n,rechecking:r,retryTestId:"claude-oauth-install-timeout-retry",recheckTestId:"claude-oauth-install-timeout-recheck"})]}):s.jsx("p",{"data-testid":"claude-oauth-installing",className:"text-sm text-[#8E8E8E]",children:"Installing the Claude command-line tool… this can take a minute."})}const yi=Object.freeze(Object.defineProperty({__proto__:null,ClaudeOAuthInstallProgress:yn},Symbol.toStringTag,{value:"Module"})),Xe=i.createContext({openPicker:()=>{},registerFileSink:()=>{}});function ns({fallbackUpload:e,children:t}){const n=i.useRef(null),r=i.useRef(null),a=i.useCallback(d=>{r.current=d},[]),o=i.useCallback(()=>{var d;(d=n.current)==null||d.click()},[]),c=i.useCallback(async d=>{const f=d.target,g=Array.from(f.files??[]).filter(u=>u.size>0);if(f.value="",g.length===0)return;const b=r.current;b&&await b(g)||e(g)},[e]),l=i.useMemo(()=>({openPicker:o,registerFileSink:a}),[o,a]);return s.jsxs(Xe.Provider,{value:l,children:[t,s.jsx("input",{ref:n,type:"file",multiple:!0,onChange:d=>void c(d),style:{display:"none"},"data-testid":"global-file-picker-input"})]})}function vn(){return i.useContext(Xe)}function rs(e,t){const{registerFileSink:n}=i.useContext(Xe);i.useEffect(()=>{if(t)return n(e),()=>n(null)},[n,e,t])}function wn(){const{registerFileSink:e}=i.useContext(Xe);return{registerFileSink:e}}const vi=Object.freeze(Object.defineProperty({__proto__:null,FilePickerProvider:ns,useFilePicker:vn,useFilePickerChannel:wn,useRegisterFilePickerSink:rs},Symbol.toStringTag,{value:"Module"})),ss={binaryMismatch:!1,configMissingAtLaunch:!1},bt={state:"unknown",provider:Tt,credsPresent:!0,cliInstalled:!0,cliRunnable:null,cliFailure:null,scannedDirs:[],reason:null,source:null,shellShare:null,storeDurability:"unobserved",claudeLaunch:ss,expiresAt:null,probeInFlight:!1,probeAttempts:0,backendFieldAbsent:!1};function as(e){if(e==null)return{...bt,backendFieldAbsent:!0};if(typeof e!="object")return bt;const t=e,n=t.state==="authenticated"||t.state==="needs-login"||t.state==="unknown"?t.state:"unknown",r=t.provider==="claude"||t.provider==="codex"||t.provider==="gemini"||t.provider==="opencode"?t.provider:Tt,a=typeof t.credsPresent=="boolean"?t.credsPresent:!0,o=typeof t.cliInstalled=="boolean"?t.cliInstalled:!0,c=typeof t.cliRunnable=="boolean"?t.cliRunnable:null,l=c===!1&&typeof t.cliFailure=="string"?t.cliFailure:null,d=Array.isArray(t.scannedDirs)?t.scannedDirs.filter(_=>typeof _=="string"):[],f=t.reason==="token-expired"||t.reason==="api-401"||t.reason==="no-credentials"||t.reason==="probe-timeout"||t.reason==="config-corrupt"||t.reason==="cli-not-found"||t.reason==="credentials-not-persisted"||t.reason==="stale-verdict"?t.reason:null,g=typeof t.source=="string"?t.source:null,b=t.shellShare==="available"||t.shellShare==="shared"?t.shellShare:null,u=t.storeDurability==="persisted"||t.storeDurability==="did-not-persist"?t.storeDurability:"unobserved",h=typeof t.claudeLaunch=="object"&&t.claudeLaunch!==null?t.claudeLaunch:{},m={binaryMismatch:h.binaryMismatch===!0,configMissingAtLaunch:h.configMissingAtLaunch===!0},x=typeof t.tokenExpiresAt=="string"?t.tokenExpiresAt:typeof t.expiresAt=="string"?t.expiresAt:null,y=typeof t.probeInFlight=="boolean"?t.probeInFlight:!1,p=typeof t.probeAttempts=="number"&&Number.isFinite(t.probeAttempts)&&t.probeAttempts>=0?t.probeAttempts:0;return{state:n,provider:r,credsPresent:a,cliInstalled:o,cliRunnable:c,cliFailure:l,scannedDirs:d,reason:f,source:g,shellShare:b,storeDurability:u,claudeLaunch:m,expiresAt:x,probeInFlight:y,probeAttempts:p,backendFieldAbsent:!1}}const os=1e3,is=5e3,cs=2e4,ls=6e4;function us(e,t){return e.state==="unknown"||e.probeInFlight?os:e.state==="needs-login"?t<ls?is:cs:null}let Pe=bt,_n=0,Oe=null,Ft=0;const gt=new Set;function xt(e){Pe=e,gt.forEach(t=>t())}function ds(e){return gt.add(e),()=>gt.delete(e)}function fs(){return Pe}function xe(){if(Oe)return Oe;const e=Ft;return Oe=(async()=>{try{const t=await fetch("/api/config");if(!t.ok)return;const n=await t.json();_n=Date.now(),xt(as(n.providerAuth))}catch{}finally{Oe=null}})(),Oe}function ps(e){Date.now()-_n<e/2||xe()}function wi(){window.dispatchEvent(new CustomEvent("agent-auth-resolved"))}function hs(){const e=i.useSyncExternalStore(ds,fs),t=i.useRef(Date.now());i.useEffect(()=>{xe()},[]);const n=us(e,Date.now()-t.current);return i.useEffect(()=>{if(n===null)return;const r=window.setInterval(()=>ps(n),n);return()=>window.clearInterval(r)},[n]),i.useEffect(()=>{const r=()=>{Pe.state!=="authenticated"&&xe()};return window.addEventListener("focus",r),()=>window.removeEventListener("focus",r)},[]),i.useEffect(()=>{const r=()=>{xt({...Pe,state:"needs-login"}),xe()};return window.addEventListener("agent-auth-required",r),()=>window.removeEventListener("agent-auth-required",r)},[]),i.useEffect(()=>{const r=()=>{xt({...Pe,state:"authenticated"}),xe()};return window.addEventListener("agent-auth-resolved",r),()=>window.removeEventListener("agent-auth-resolved",r)},[]),{state:e.state,provider:e.provider,credsPresent:e.credsPresent,cliInstalled:e.cliInstalled,cliRunnable:e.cliRunnable,cliFailure:e.cliFailure,scannedDirs:e.scannedDirs,reason:e.reason,source:e.source,shellShare:e.shellShare,storeDurability:e.storeDurability,claudeLaunch:e.claudeLaunch,expiresAt:e.expiresAt,probeInFlight:e.probeInFlight,probeAttempts:e.probeAttempts,backendFieldAbsent:e.backendFieldAbsent,refresh:xe}}var ms=Wr(),bs=Yr();function gs(e){if(typeof e!="object"||e===null)return null;const{provider:t,stanza:n,file:r,setupCommand:a}=e;return typeof t!="string"||typeof n!="string"||typeof r!="string"||typeof a!="string"?null:{provider:t,stanza:n,file:r,setupCommand:a}}const xs=3e3;function jn(){const[e,t]=i.useState(null),[n,r]=i.useState(!0),[a,o]=i.useState(null),c=i.useRef(null),l=i.useCallback(async()=>{try{const d=await fetch("/api/config");if(!d.ok)throw new Error(`HTTP ${d.status}`);const f=await d.json(),g={projectTitle:f.projectTitle??null,projectDescription:f.projectDescription??null,provider:f.provider??Tt,providerDeclared:f.providerDeclared??!1,port:f.port??3e3,previewOrigin:f.previewOrigin??null,screenSizes:f.screenSizes??{},defaultScreenSize:f.defaultScreenSize??null,apps:f.apps??[],admin:f.admin??!1,mobileTerminalCommands:f.mobileTerminalCommands??[],launcherUrl:f.launcherUrl??null,projectCount:f.projectCount??0,setupBrowserEnabled:f.setupBrowserEnabled??!1,claudePermissionModeAuto:f.claudePermissionModeAuto??!0,previewDedicatedOriginUnavailable:f.previewDedicatedOriginUnavailable??!1,previewDedicatedOriginHint:gs(f.previewDedicatedOriginHint),onManagedFleetVm:f.onManagedFleetVm??!1,previewSessionHandoff:f.previewSessionHandoff??null,previewSessionHandoffProbe:f.previewSessionHandoffProbe??null},b=JSON.stringify(g);b!==c.current&&(c.current=b,t(g)),o(null)}catch(d){o(d instanceof Error?d.message:"Failed to load config")}finally{r(!1)}},[]);return i.useEffect(()=>{l();const d=setInterval(()=>{l()},xs);return()=>clearInterval(d)},[l]),{config:e,apps:(e==null?void 0:e.apps)??[],loading:n,error:a,refetch:l}}const ys="capture-origin-spawn-refused";function Sn(){return typeof window<"u"&&window.__codeyamCapture===!0}function Bt(){return Sn()&&window.__codeyamCaptureLiveSocket!==!0}function vs(e){const t=window.location.protocol==="https:"?"wss:":"ws:",n=new URL(`${t}//${window.location.host}/ws/terminal`);return e!=null&&e.provider&&n.searchParams.set("provider",e.provider),e!=null&&e.mode&&n.searchParams.set("mode",e.mode),e!=null&&e.sessionId&&n.searchParams.set("sessionId",e.sessionId),e!=null&&e.chatKey&&n.searchParams.set("chatKey",e.chatKey),e!=null&&e.launchId&&n.searchParams.set("launchId",e.launchId),e!=null&&e.launch&&n.searchParams.set("launch","1"),e!=null&&e.capture&&n.searchParams.set("capture","1"),e!=null&&e.cols&&e.cols>0&&n.searchParams.set("cols",String(e.cols)),e!=null&&e.rows&&e.rows>0&&n.searchParams.set("rows",String(e.rows)),n.toString()}const ws=20,_s=1;function js(e,t){const n=t===_s?e:e/ws;return Math.trunc(n)||Math.sign(n)}function Ss(){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 ks(e,t,n={}){const r=n.isMac??Ss(),a=n.onError,o=n.onCopy;let c=null;async function l(m){if(!m)return!1;let x=!1;try{x=await Kr(m)}catch(y){return a==null||a(zt("copy",y)),!1}if(x){try{e.clearSelection()}catch{}o==null||o()}else a==null||a(Ns("copy"));return x}async function d(){return e.hasSelection()?l(e.getSelection()):!1}async function f(){try{const m=await navigator.clipboard.readText();m&&e.paste(m)}catch(m){a==null||a(zt("paste",m))}}function g(m){return m.type!=="keydown"?!0:r?(m.metaKey&&!m.ctrlKey&&!m.altKey&&m.key.toLowerCase()==="c"||m.ctrlKey&&!m.metaKey&&!m.altKey&&!m.shiftKey&&m.key.toLowerCase()==="c")&&e.hasSelection()?(d(),!1):!0:(m.ctrlKey&&m.shiftKey&&!m.metaKey&&!m.altKey&&m.key.toLowerCase()==="c"||m.ctrlKey&&!m.shiftKey&&!m.metaKey&&!m.altKey&&m.key.toLowerCase()==="c")&&e.hasSelection()?(d(),!1):!0}e.attachCustomKeyEventHandler(g);function b(){if(!c)return;const{root:m,onDocumentClick:x,onKeyDown:y}=c;document.removeEventListener("mousedown",x,!0),document.removeEventListener("keydown",y,!0),m.remove(),c=null}function u(m,x,y){b();const p=document.createElement("div");p.setAttribute("data-terminal-clipboard-menu","true"),p.style.position="fixed",p.style.left=`${m}px`,p.style.top=`${x}px`,p.style.zIndex="1000",p.style.minWidth="180px",p.style.padding="4px 0",p.style.background="var(--bg-card)",p.style.border="1px solid var(--border-subtle)",p.style.borderRadius="6px",p.style.boxShadow="0 8px 24px rgba(0, 0, 0, 0.35)",p.style.fontSize="12px",p.style.color="var(--text-primary)",p.style.userSelect="none";const _=r?"⌘C":"Ctrl+Shift+C",v=r?"⌘V":"Ctrl+Shift+V",w=st("Copy",_,!y,()=>{l(y),b()}),S=st("Paste",v,!1,()=>{f(),b()}),M=st("Select All","",!1,()=>{try{e.selectAll()}catch{}const j=e.hasSelection()?e.getSelection():"";l(j),b()});p.appendChild(w),p.appendChild(S),p.appendChild(M),document.body.appendChild(p),Cs(p,m,x);const N=j=>{p.contains(j.target)||b()},z=j=>{j.key==="Escape"&&(j.preventDefault(),b())};document.addEventListener("mousedown",N,!0),document.addEventListener("keydown",z,!0),c={root:p,onDocumentClick:N,onKeyDown:z}}function h(m){m.preventDefault();const x=e.hasSelection()?e.getSelection():"";u(m.clientX,m.clientY,x)}return t.addEventListener("contextmenu",h),()=>{t.removeEventListener("contextmenu",h),b(),e.attachCustomKeyEventHandler(()=>!0)}}function st(e,t,n,r){const a=document.createElement("button");a.type="button",a.disabled=n,a.style.display="flex",a.style.justifyContent="space-between",a.style.alignItems="center",a.style.gap="16px",a.style.width="100%",a.style.padding="6px 12px",a.style.border="none",a.style.background="transparent",a.style.textAlign="left",a.style.fontSize="12px",a.style.cursor=n?"default":"pointer",a.style.color=n?"var(--text-dim)":"var(--text-primary)";const o=document.createElement("span");if(o.textContent=e,a.appendChild(o),t){const c=document.createElement("span");c.textContent=t,c.style.color="var(--text-dim)",c.style.fontSize="11px",a.appendChild(c)}return n||(a.addEventListener("mouseenter",()=>{a.style.background="var(--border-subtle)"}),a.addEventListener("mouseleave",()=>{a.style.background="transparent"}),a.addEventListener("click",()=>r())),a}function Cs(e,t,n){const r=typeof window<"u"?window.innerWidth:0,a=typeof window<"u"?window.innerHeight:0;if(!r||!a)return;const o=e.getBoundingClientRect(),c=4;let l=t,d=n;o.width&&t+o.width+c>r&&(l=Math.max(c,r-o.width-c)),o.height&&n+o.height+c>a&&(d=Math.max(c,a-o.height-c)),e.style.left=`${l}px`,e.style.top=`${d}px`}function zt(e,t){const n=t instanceof Error?t.message:String(t);return`Clipboard ${e} failed: ${n}`}function Ns(e){return`Clipboard ${e} blocked by the browser.`}function Ts(e,t,n,r,a,o){const c=e.leftBorderCol+1;if(t===r)return a-n;if(r<t){let f=n-c;f+=1;for(let b=r+1;b<t;b++){const u=o(b);if(u===null)return null;f+=Math.max(1,u-c+1)}const g=o(r);return g===null?null:(f+=Math.max(0,g-a),-f)}const l=o(t);if(l===null)return null;let d=Math.max(0,l-n)+1;for(let f=t+1;f<r;f++){const g=o(f);if(g===null)return null;d+=Math.max(1,g-c+1)}return d+=a-c,d}const ze=new Set(["│","┃","║","|"]);function Es(e,t,n,r){const a=e.baseY,o=(h,m)=>{const x=e.getLine(a+h);if(!x)return null;const y=x.getCell(m);return y?y.getChars():null},c=h=>{let m=-1;for(let y=0;y<n;y++){const p=o(h,y);if(p!==null&&ze.has(p)){m=y;break}}if(m===-1)return null;let x=-1;for(let y=n-1;y>m;y--){const p=o(h,y);if(p!==null&&ze.has(p)){x=y;break}}return x===-1?null:{leftBorderCol:m,rightBorderCol:x}};let l=t,d=c(t);if(!d){const h=c(t-1);if(h)l=t-1,d=h;else{const m=c(t+1);m&&(l=t+1,d=m)}}if(!d)return null;const{leftBorderCol:f,rightBorderCol:g}=d;let b=l;for(let h=l-1;h>=0;h--){const m=o(h,f);if(m===null)break;if(!(m===""||m===" ")){if(!ze.has(m))break;b=h}}let u=l;for(let h=l+1;h<r;h++){const m=o(h,f);if(m===null)break;if(!(m===""||m===" ")){if(!ze.has(m))break;u=h}}return{topRow:b,bottomRow:u,leftBorderCol:f,rightBorderCol:g}}function Os(e,t,n,r){const a=e.getLine(e.baseY+t);if(!a)return null;for(let o=r;o>=n;o--){const c=a.getCell(o);if(!c)continue;const l=c.getChars();if(l!==""&&l!==" ")return o}return n-1}const As=200;function Ms(e){const{click:t,terminal:n,cellSurface:r,debug:a}=e,o=n.buffer.active,c=w=>{a==null||a({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 l=r.getBoundingClientRect();if(l.width===0||l.height===0)return c({targetRow:-1,targetCol:-1,box:null,rejected:"outside-grid",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;const d=t.clientX-l.left,f=t.clientY-l.top;if(d<0||f<0||d>=l.width||f>=l.height)return c({targetRow:-1,targetCol:-1,box:null,rejected:"outside-grid",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;const g=l.width/n.cols,b=l.height/n.rows,u=Math.floor(d/g),h=Math.floor(f/b),m=n.modes.applicationCursorKeysMode,x=m?"\x1BOC":"\x1B[C",y=m?"\x1BOD":"\x1B[D",p=Es(o,o.cursorY,n.cols,n.rows);if(p){if(h<p.topRow||h>p.bottomRow)return c({targetRow:h,targetCol:u,box:p,rejected:"out-of-box",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;if(u<=p.leftBorderCol||u>=p.rightBorderCol)return c({targetRow:h,targetCol:u,box:p,rejected:"border",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;const w=p.leftBorderCol+1,S=p.rightBorderCol-1,M=A=>Os(o,A,w,S),N=o.cursorY<p.topRow||o.cursorY>p.bottomRow,z=N?p.bottomRow:o.cursorY,j=N?S:o.cursorX,I=h!==z;let E=null;if(I&&(E=M(h),E===null))return c({targetRow:h,targetCol:u,originalTargetCol:u,snapped:!1,box:p,rejected:"unreadable-row",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;let F=u,W=!1;if(I&&E!==null){const A=Math.max(w,E);u>A&&(F=A,W=!0)}if(h===z&&F===j)return c({targetRow:h,targetCol:F,originalTargetCol:u,snapped:W,box:p,rejected:"same-cell",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;const L=Ts(p,z,j,h,F,M);if(L===null)return c({targetRow:h,targetCol:F,originalTargetCol:u,snapped:W,box:p,rejected:"unreadable-row",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;if(L===0)return c({targetRow:h,targetCol:F,originalTargetCol:u,snapped:W,box:p,rejected:"same-cell",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;if(Math.abs(L)>As)return c({targetRow:h,targetCol:F,originalTargetCol:u,snapped:W,box:p,rejected:"emit-cap",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;const K=L<0?y.repeat(-L):x.repeat(L);return c({targetRow:h,targetCol:F,originalTargetCol:u,snapped:W,box:p,rejected:null,emittedDirection:L<0?"left":"right",emittedByteCount:K.length,predictedCursorY:h,predictedCursorX:F}),K}if(h!==o.cursorY)return c({targetRow:h,targetCol:u,box:null,rejected:"out-of-box",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;const _=u-o.cursorX;if(_===0)return c({targetRow:h,targetCol:u,box:null,rejected:"same-cell",emittedDirection:null,emittedByteCount:0,predictedCursorY:null,predictedCursorX:null}),null;const v=_<0?y.repeat(-_):x.repeat(_);return c({targetRow:h,targetCol:u,box:null,rejected:null,emittedDirection:_<0?"left":"right",emittedByteCount:v.length,predictedCursorY:h,predictedCursorX:u}),v}const Kt=1;function Is(e,t){const{sendInput:n,pixelThreshold:r=3,timeThresholdMs:a=300,now:o=()=>Date.now(),onVerificationDisable:c}=t,l=e.element;if(!l)return()=>{};const d=l.querySelector(".xterm-screen")??l;let f=null,g=!1,b=null,u=null;const h=typeof e.onRender=="function"?e.onRender.bind(e):null;h&&(u=h(()=>{const y=b;if(!y)return;b=null;const p=e.buffer.active,_=Math.abs(p.cursorY-y.y),v=Math.abs(p.cursorX-y.x);if(_>Kt||v>Kt){g=!0;const w={predicted:y,actual:{y:p.cursorY,x:p.cursorX}};c?c(w):console.warn("[click-cursor] disabled — cursor diverged from prediction",w)}}));function m(y){if(y.button!==0||y.altKey||y.shiftKey||y.metaKey||y.ctrlKey){f=null;return}f={clientX:y.clientX,clientY:y.clientY,at:o()}}function x(y){var z;const p=f;if(f=null,!p)return;const _=y.clientX-p.clientX,v=y.clientY-p.clientY;if(Math.hypot(_,v)>r||o()-p.at>a)return;const w=typeof window<"u"&&((z=window.localStorage)==null?void 0:z.getItem("codeyam.terminalClickDebug"))==="1";if(w)try{const j=e.buffer.active,I=j.cursorY,E={};for(let F=-2;F<=2;F++){const W=I+F,L=j.getLine(j.baseY+W);if(!L)continue;const K=[];for(let A=0;A<e.cols;A++){const Q=L.getCell(A);K.push(Q?Q.getChars():"")}E[`row${W}`]=K.join("|")}console.log("[click-cursor] buffer dump",{cursorY:I,cursorX:j.cursorX,viewportY:j.viewportY,baseY:j.baseY,rows:E})}catch{}let S=null;const M=j=>{S=j,w&&console.log("[click-cursor] result",j)},N=Ms({click:{clientX:y.clientX,clientY:y.clientY},terminal:e,cellSurface:d,debug:M});if(N){if(S){const j=S,I=j.box!==null&&j.targetRow!==j.cursorY;if(I&&g){w&&console.log("[click-cursor] suppressed by verification-disabled");return}I&&j.predictedCursorY!==null&&j.predictedCursorX!==null&&(b={y:j.predictedCursorY,x:j.predictedCursorX})}n(N)}}return d.addEventListener("mousedown",m),d.addEventListener("mouseup",x),()=>{d.removeEventListener("mousedown",m),d.removeEventListener("mouseup",x),u==null||u.dispose()}}function Ps(e){const t=document.activeElement;return!(t instanceof HTMLElement)||!(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement||t.isContentEditable)?!1:!((e==null?void 0:e.contains(t))??!1)}const Ht=20*1024*1024,Rs=3e4,Ds=3e3;function Ls(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{const a=r.result;if(typeof a!="string"){n(new Error("Unexpected FileReader result"));return}const o=a.indexOf(",");t(o===-1?a:a.slice(o+1))},r.onerror=()=>n(r.error??new Error("read failed")),r.readAsDataURL(e)})}function $s(){return typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`drop-${Date.now()}-${Math.random().toString(36).slice(2)}`}function Fs(e){return/^[A-Za-z0-9._/\-]+$/.test(e)?e:`"${e.replace(/(["\\$`])/g,"\\$1")}"`}function kn(e){const t=e==null?void 0:e.items;if(!t)return[];const n=[];for(const r of Array.from(t)){if(r.kind!=="file"||!r.type.startsWith("image/"))continue;const a=r.getAsFile();a&&n.push(a)}return n}function Bs(e){const t=e.items;if(!t||t.length===0||typeof t[0].webkitGetAsEntry!="function")return!1;for(const r of Array.from(t)){const a=r.webkitGetAsEntry();if(a&&a.isDirectory)return!0}return!1}function zs(e,t){function n(r){const a=kn(r.clipboardData);a.length!==0&&(r.preventDefault(),r.stopPropagation(),t(a))}return e.addEventListener("paste",n,!0),()=>e.removeEventListener("paste",n,!0)}function Ks(){window.focus()}function Hs(e,t){Ks(),e==null||e.focus({preventScroll:!0}),t()}function Us({wsRef:e,insertInput:t}){const[n,r]=i.useState(!1),[a,o]=i.useState(null),c=i.useRef(new Map),l=i.useRef(0);i.useEffect(()=>{if(a===null)return;const v=window.setTimeout(()=>o(null),Ds);return()=>window.clearTimeout(v)},[a]);const d=i.useCallback(v=>{o(v)},[]),f=i.useCallback((v,w)=>{const S=c.current.get(v);S&&(c.current.delete(v),S.resolve(w))},[]),g=i.useCallback((v,w)=>{const S=c.current.get(v);S&&(c.current.delete(v),S.reject(w))},[]),b=i.useCallback(v=>{for(const[,w]of c.current)w.reject(v);c.current.clear()},[]),u=i.useCallback(async v=>{if(v.size>Ht)throw new Error(`File too large (max ${Ht/(1024*1024)} MB)`);const w=e.current;if(!w||w.readyState!==WebSocket.OPEN)throw new Error("Not connected — try again in a moment");const S=await Ls(v),M=$s(),N=new Promise((z,j)=>{const I=window.setTimeout(()=>{c.current.delete(M)&&j(new Error("Timed out waiting for save to complete"))},Rs);c.current.set(M,{resolve:E=>{window.clearTimeout(I),z(E)},reject:E=>{window.clearTimeout(I),j(new Error(E))}})});return w.send(JSON.stringify({type:"drop",id:M,name:v.name||"unnamed",mime:v.type||"application/octet-stream",data:S})),N},[e]),h=i.useCallback(async v=>{if(v.length===0)return;const w=[];for(const S of v)try{w.push(await u(S))}catch(M){const N=M instanceof Error?M.message:String(M);d(`Attach failed: ${N}`);return}t(w.map(Fs).join(" ")+" ")},[u,d,t]),m=i.useCallback(v=>{v.dataTransfer.types.includes("Files")&&(v.preventDefault(),l.current+=1,r(!0))},[]),x=i.useCallback(v=>{v.dataTransfer.types.includes("Files")&&v.preventDefault()},[]),y=i.useCallback(v=>{v.dataTransfer.types.includes("Files")&&(l.current=Math.max(0,l.current-1),l.current===0&&r(!1))},[]),p=i.useCallback(async v=>{if(!v.dataTransfer.types.includes("Files"))return;if(v.preventDefault(),l.current=0,r(!1),Bs(v.dataTransfer)){d("Folder drops are not supported — drag individual files instead");return}const w=Array.from(v.dataTransfer.files).filter(S=>S.size>0);await h(w)},[h,d]),_=i.useCallback(async v=>{const w=kn(v.clipboardData);w.length!==0&&(v.preventDefault(),await h(w))},[h]);return{dragActive:n,errorToast:a,dropHandlers:{onDragEnter:m,onDragOver:x,onDragLeave:y,onDrop:p},pasteHandler:_,handleImageFiles:h,resolveDrop:f,rejectDrop:g,cancelAllDrops:b,showError:d}}function Ws(e,t,n=50){const r=i.useRef(t);r.current=t,i.useEffect(()=>{const a=e.current;if(!a)return;let o=null;const c=new ResizeObserver(l=>{o&&clearTimeout(o);const d=l[0];d&&(o=setTimeout(()=>{r.current(d)},n))});return c.observe(a),()=>{o&&clearTimeout(o),c.disconnect()}},[e,n])}function _i({viewportY:e,baseY:t}){return!Number.isFinite(e)||!Number.isFinite(t)?!1:e>=t}function Ys({width:e,height:t,cellWidth:n,cellHeight:r}){return!Number.isFinite(e)||!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(r)||n<=0||r<=0?!1:e>=n&&t>=r}function Vs(e){var t,n,r,a;try{const o=(a=(r=(n=(t=e._core)==null?void 0:t._renderService)==null?void 0:n.dimensions)==null?void 0:r.css)==null?void 0:a.cell;return{cellWidth:(o==null?void 0:o.width)??NaN,cellHeight:(o==null?void 0:o.height)??NaN}}catch{return{cellWidth:NaN,cellHeight:NaN}}}function Js(e,t){const{cellWidth:n,cellHeight:r}=Vs(e);return Ys({width:(t==null?void 0:t.clientWidth)??NaN,height:(t==null?void 0:t.clientHeight)??NaN,cellWidth:n,cellHeight:r})}function Cn(){return s.jsx("div",{"data-testid":"terminal-drop-overlay",style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(30, 30, 30, 0.85)",color:"#D7FF63",fontFamily:"'IBM Plex Mono', monospace",fontSize:14,border:"2px dashed #D7FF63",borderRadius:6,pointerEvents:"none",zIndex:5},children:"Drop file to attach"})}const ji=Object.freeze(Object.defineProperty({__proto__:null,TerminalDropOverlay:Cn},Symbol.toStringTag,{value:"Module"}));function Nn({message:e}){return s.jsx("div",{"data-testid":"terminal-drop-toast",style:{position:"absolute",bottom:12,left:"50%",transform:"translateX(-50%)",background:"#3a1f1f",color:"#ff9494",border:"1px solid #7a3939",borderRadius:4,padding:"6px 12px",fontFamily:"'IBM Plex Mono', monospace",fontSize:12,zIndex:6,pointerEvents:"none"},children:e})}const Si=Object.freeze(Object.defineProperty({__proto__:null,TerminalDropToast:Nn},Symbol.toStringTag,{value:"Module"}));async function Tn(e=1500){try{return(await fetch("/api/health",{signal:AbortSignal.timeout(e)})).ok}catch{return!1}}const En=4e3;async function Xs({attempts:e=3,intervalMs:t=1500,timeoutMs:n=En}={}){for(let r=0;r<e;r++)if(r>0&&t>0&&await new Promise(a=>setTimeout(a,t)),await Tn(n))return!1;return!0}function qs(e,t){let n=!1,r=null;async function a(){if(!n){if(await Tn(En)){n||t();return}n||(r=setTimeout(a,e))}}return r=setTimeout(a,e),()=>{n=!0,r&&(clearTimeout(r),r=null)}}const Gs="The editor server closed the terminal connection with no further detail.";function Qs(e){if(e&&typeof e=="object"&&"message"in e){const t=e.message;if(typeof t=="string"&&t.length>0)return t}return Gs}let On=!1;function at(e){On=e}function Zs(){return On}const ea=800,An="codeyam.miniAgent.deliveredSeed.";function Mn(e,t){try{window.sessionStorage.setItem(An+e,t)}catch{}}function ta(e,t){try{return window.sessionStorage.getItem(An+e)===t}catch{return!1}}const na=5e3,ra="*";function ot(e,t){window.dispatchEvent(new CustomEvent("miniagent-send-input",{detail:{text:e,chatName:t}}))}const We=new Map;function De(e,t){const n=We.get(e);if(!n){let r;try{r=t()}catch(a){return Promise.reject(a)}return r instanceof Promise?Ut(e,r):Promise.resolve()}return Ut(e,n.then(()=>t()))}function Ut(e,t){const n=t.catch(()=>{});return We.set(e,n),n.then(()=>{We.get(e)===n&&We.delete(e)}),t}let je=0,ve=[];function ki(){if(je+=1,je===1&&ve.length>0){const e=ve;ve=[];for(const t of e)t()}}function Ci(){je>0&&(je-=1)}function sa(){return je>0}function aa(e){return je>0?Promise.resolve(!0):new Promise(t=>{let n=!1;const r=()=>{n||(n=!0,t(!0))};ve.push(r),setTimeout(()=>{n||(n=!0,ve=ve.filter(a=>a!==r),t(!1))},e)})}const Ce="build",it="miniagent",Wt=3e3;function Et(e,t=!1){return sa()?e():aa(Wt).then(n=>{if(n)return e();const r=`no terminal-send-input listener attached within ${Wt}ms`;if(t)throw new oa(r);console.warn(`[terminal] dropped programmatic injection: ${r}`)})}class oa extends Error{constructor(t){super(t),this.name="TerminalInputDroppedError"}}function Se(e){window.dispatchEvent(new CustomEvent("terminal-send-input",{detail:e}))}function Ni(e){De(Ce,()=>Et(()=>Se(e)))}function Ti(e){return De(Ce,()=>Et(()=>Se(e),!0))}const we=50;function Ei(e){return De(Ce,()=>Et(()=>new Promise(t=>{Se(e),setTimeout(()=>{Se("\r"),t()},we)}),!0))}function In(e,t=Se,n=Ce){return De(n,()=>new Promise(r=>{t(e),setTimeout(()=>{t("\r"),r()},we)}))}const ia=250,Pn="";function ca(e){return`\x1B[200~${e}\x1B[201~`}function Oi(e,t){const n=t.replace(/[\r\n]+$/,"");if(!e(Pn))return null;e(ca(n));const r=window.setTimeout(()=>e("\r"),ia);return()=>window.clearTimeout(r)}function Rn(e,t,n){return new Promise(r=>{let a=!1;const o=()=>{a||(a=!0,window.removeEventListener(e,c),clearTimeout(l),r())},c=d=>{n&&!n(d)||o()},l=setTimeout(o,t);window.addEventListener(e,c)})}function la(e,t="plan"){return Rn("miniagent-agent-idle",e,n=>{const r=n.detail;return(r==null?void 0:r.chatName)===t})}function ua(e){return Zs()?Promise.resolve():Rn("miniagent-ws-open",e)}async function da(e,t){return ta(t,e)?(G("seed-suppressed-on-reattach",{chatName:t}),!1):(Mn(t,e),await ua(na),await la(ea,t),ot(Pn,t),ot(e,t),await new Promise(n=>setTimeout(n,we)),ot("\r",t),!0)}function Dn(){return s.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…"})}const Ai=Object.freeze(Object.defineProperty({__proto__:null,TerminalConnectingHint:Dn},Symbol.toStringTag,{value:"Module"}));function Ln({attempt:e,maxAttempts:t,pulseKey:n,label:r="Reconnecting…"}){return s.jsx("div",{"data-testid":"terminal-reconnecting-banner",className:"absolute inset-0 flex items-start justify-center pt-3 z-10 bg-black/40",children:s.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:[r," (attempt ",e," of ",t,")"]},n)})}const Mi=Object.freeze(Object.defineProperty({__proto__:null,TerminalReconnectingBanner:Ln},Symbol.toStringTag,{value:"Module"})),fa=350;function Ne(e,t={}){const{minPendingMs:n=fa}=t,[r,a]=i.useState("idle"),[o,c]=i.useState(0),l=i.useRef(!0);i.useEffect(()=>(l.current=!0,()=>{l.current=!1}),[]);const d=i.useCallback(()=>{a("pending"),c(b=>b+1);let f;try{f=Promise.resolve(e())}catch{f=Promise.resolve()}const g=new Promise(b=>setTimeout(b,n));Promise.allSettled([f,g]).then(()=>{l.current&&a("unchanged")})},[e,n]);return{phase:r,attempts:o,retry:d}}function $n({onRefresh:e}){const{phase:t,attempts:n,retry:r}=Ne(e);return s.jsx("div",{"data-testid":"terminal-failed-banner",className:"absolute inset-0 z-10 flex items-start justify-center bg-black/60 p-3",children:s.jsx(be,{severity:"error",testId:"terminal-failed-notice",headline:"The terminal lost its connection",explanation:"The terminal tried to reconnect several times and couldn't get through. Either the editor restarted underneath it, or the connection between your browser and this machine dropped. Your files and your work are untouched — it's only the live terminal view that stopped.",nextAction:"Refresh the page to start a fresh terminal. If this keeps happening, copy this report and send it to whoever set up this machine.",actions:[{label:"Refresh page",onClick:r,pending:t==="pending",pendingLabel:"Refreshing…",testId:"terminal-failed-banner-refresh"}],actionFeedback:t==="unchanged"?s.jsxs("span",{"data-testid":"terminal-failed-banner-unchanged",children:["Tried just now — the terminal still isn’t back",n>1?` (${n} tries)`:"","."]}):null})})}const Ii=Object.freeze(Object.defineProperty({__proto__:null,TerminalFailedBanner:$n},Symbol.toStringTag,{value:"Module"}));function Fn({onReload:e,onDismiss:t}){const{phase:n,attempts:r,retry:a}=Ne(e),o=[{label:"Reload page",onClick:a,pending:n==="pending",pendingLabel:"Checking…",testId:"terminal-server-stopped-banner-reload"}];return t&&o.push({label:"Dismiss — keep trying to reconnect",onClick:t,variant:"secondary",ariaLabel:"Dismiss the lost-contact notice and keep trying to reconnect",testId:"terminal-server-stopped-banner-dismiss"}),s.jsx("div",{"data-testid":"terminal-server-stopped-banner",className:"absolute inset-0 z-10 flex items-start justify-center bg-black/60 p-3",children:s.jsx(be,{severity:"error",testId:"terminal-server-stopped-notice",headline:"Lost contact with the editor",explanation:"This page stopped hearing from the editor. The editor may have been closed, or the connection may just be slow — the agent can still be working behind this notice. Nothing you were working on is lost.",nextAction:"If the editor was closed, start it again — this page comes back by itself once it's reachable, so you don't need to keep clicking. Reload page only checks early. If you can see the agent still working, dismiss this to keep reconnecting.",actions:o,actionFeedback:n==="unchanged"?s.jsxs("span",{"data-testid":"terminal-server-stopped-banner-unchanged",children:["Checked just now — the editor still isn’t answering",r>1?` (${r} tries)`:"","."]}):null})})}const Pi=Object.freeze(Object.defineProperty({__proto__:null,TerminalServerStoppedBanner:Fn},Symbol.toStringTag,{value:"Module"}));function Bn({message:e,onRefresh:t}){return s.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:s.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:[s.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}),s.jsxs("div",{className:"flex items-start gap-2 self-start shrink-0",children:[s.jsx(cn,{variant:"subtle",text:e,label:"Copy",className:"px-2 py-1 rounded bg-white text-amber-900 font-medium cursor-pointer hover:bg-amber-50 disabled:opacity-50 disabled:cursor-not-allowed"}),s.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",children:"Refresh"})]})]})})}const Ri=Object.freeze(Object.defineProperty({__proto__:null,TerminalServerErrorBanner:Bn},Symbol.toStringTag,{value:"Module"}));function zn({onRefresh:e}){const{phase:t,attempts:n,retry:r}=Ne(e);return s.jsx("div",{"data-testid":"terminal-edge-unreachable-banner",className:"absolute inset-0 z-10 flex items-start justify-center bg-black/60 p-3",children:s.jsx(be,{severity:"warning",testId:"terminal-edge-unreachable-notice",headline:"The terminal can't reach this machine",explanation:"The editor itself is loading fine and you're signed in — it's the terminal's own live connection that isn't getting through. Nothing you did caused this, and your work isn't lost.",nextAction:"Try Retry. If it keeps failing, this one isn't yours to fix — copy this report and send it to whoever set up this machine.",actions:[{label:"Retry",onClick:r,pending:t==="pending",pendingLabel:"Reconnecting…",testId:"terminal-edge-unreachable-banner-retry"}],actionFeedback:t==="unchanged"?s.jsxs("span",{"data-testid":"terminal-edge-unreachable-banner-unchanged",children:["Checked just now — still not connecting",n>1?` (${n} tries)`:"","."]}):null,diagnostics:"The editor answers over HTTP and the session is valid, but the terminal's live connection channel does not complete. Typically the network path in front of this machine is not carrying it."})})}const Di=Object.freeze(Object.defineProperty({__proto__:null,TerminalEdgeUnreachableBanner:zn},Symbol.toStringTag,{value:"Module"}));function Kn({canRetry:e=!1,onRefresh:t}){const{phase:n,attempts:r,retry:a}=Ne(t);return s.jsx("div",{"data-testid":"terminal-session-stale-banner",className:"absolute inset-0 z-10 flex items-start justify-center bg-black/60 p-3",children:s.jsx(be,{severity:"warning",testId:"terminal-session-stale-notice",headline:e?"Couldn't get this tab signed back in":"Signing this tab back in",explanation:e?"The editor restarted, which signed this tab out. It tried to sign back in automatically and couldn't.":"The editor restarted, which signed this tab out. It's signing back in and reconnecting the terminal now.",nextAction:e?"Use Retry to try again. If that doesn't take, reload the page — that always gets a fresh session.":"Nothing, unless this sticks around. If the terminal hasn't come back after about ten seconds, reload the page.",actions:e?[{label:"Retry",onClick:a,pending:n==="pending",pendingLabel:"Retrying…",testId:"terminal-session-stale-banner-retry"}]:[],actionFeedback:e&&n==="unchanged"?s.jsxs("span",{"data-testid":"terminal-session-stale-banner-unchanged",children:["Tried just now — still signed out",r>1?` (${r} tries)`:"",". Reloading the page will fix it."]}):null})})}const Li=Object.freeze(Object.defineProperty({__proto__:null,TerminalSessionStaleBanner:Kn},Symbol.toStringTag,{value:"Module"}));function pa(e){if(e.oomSignature)return{headline:"This session was killed because the machine ran out of memory.",body:"The agent did not stop on its own and did not crash — the system killed it to reclaim memory, so nothing it was in the middle of was saved. Free some memory before starting a new session, or the same thing will happen again.",retryLikelyHelps:!1};if(e.externalDeath)return{headline:`This session was stopped from outside the editor (${e.signal??"an external signal"}).`,body:"Something other than the editor ended the agent process. Nothing it was in the middle of was saved. Starting a new session is safe, but if this keeps happening the cause is outside the editor.",retryLikelyHelps:!0};if(e.origin==="broker-initiated")return{headline:"This session was stopped.",body:"The editor ended the agent process — this is what you get after Stop Building, or after a session sits unused long enough to be cleaned up. Start a new session whenever you are ready.",retryLikelyHelps:!0};const t=e.exitCode;return{headline:t===null?"The agent process ended.":`The agent process ended on its own (exit code ${t}).`,body:"The agent was not killed — it exited by itself, so whatever it printed above is the best evidence for why. Starting a new session is safe.",retryLikelyHelps:!0}}function Hn({report:e,onRefresh:t}){const{phase:n,attempts:r,retry:a}=Ne(t),o=pa(e);return s.jsx("div",{"data-testid":"terminal-session-died-banner",className:"absolute inset-0 z-10 flex items-start justify-center bg-black/60 p-3",children:s.jsx(be,{severity:o.retryLikelyHelps?"warning":"error",testId:"terminal-session-died-notice",headline:o.headline,explanation:o.body,nextAction:o.retryLikelyHelps?"Start a new session when you're ready. Reloading the page gets you a clean one.":"Free up memory first — close other work on this machine — then reload the page to start a new session.",actions:[{label:"Reload",onClick:a,pending:n==="pending",pendingLabel:"Reloading…",testId:"terminal-session-died-banner-reload"}],actionFeedback:n==="unchanged"?s.jsxs("span",{"data-testid":"terminal-session-died-banner-unchanged",children:["Tried just now — still no session",r>1?` (${r} tries)`:"","."]}):null})})}const $i=Object.freeze(Object.defineProperty({__proto__:null,TerminalSessionDiedBanner:Hn},Symbol.toStringTag,{value:"Module"}));function Un({status:e,pulseKey:t,onRefresh:n,reconnectingLabel:r,onDismissServerStopped:a}){return e.kind==="open"||e.kind==="ended"?null:e.kind==="connecting"?s.jsx(Dn,{}):e.kind==="reconnecting"?s.jsx(Ln,{attempt:e.attempt,maxAttempts:e.maxAttempts,pulseKey:t,label:r}):e.kind==="server-stopped"?s.jsx(Fn,{onReload:n,onDismiss:a}):e.kind==="server-error"?s.jsx(Bn,{message:e.message,onRefresh:n}):e.kind==="edge-unreachable"?s.jsx(zn,{onRefresh:n}):e.kind==="session-died"?s.jsx(Hn,{report:e.report,onRefresh:n}):e.kind==="session-stale"?s.jsx(Kn,{canRetry:e.canRetry,onRefresh:n}):s.jsx($n,{onRefresh:n})}const Fi=Object.freeze(Object.defineProperty({__proto__:null,TerminalDisconnectOverlay:Un},Symbol.toStringTag,{value:"Module"}));function Wn(){return s.jsx("div",{"data-testid":"mini-agent-launch-retrying",className:"absolute inset-x-0 top-2 z-10 flex justify-center pointer-events-none",children:s.jsx("span",{className:"font-mono text-xs italic text-[var(--text-dim)] bg-black/40 px-2 py-1 rounded",children:"Launch slow — retrying…"})})}const Bi=Object.freeze(Object.defineProperty({__proto__:null,MiniAgentLaunchRetryingHint:Wn},Symbol.toStringTag,{value:"Module"}));function ha(e){if((e==null?void 0:e.kind)==="rejected")return{headline:`The agent didn't recognize ${e.command}`,explanation:`The build agent started, but it doesn't have the ${e.command} command installed, so nothing began. Nothing in your code has been touched.`,nextAction:"Use Retry — it installs the command again and sends it to the agent that is already running. If it is rejected again, copy this report and send it on.",unchangedAfterRetry:`Tried just now — the agent still didn't recognize ${e.command}`};if((e==null?void 0:e.kind)==="unsupported"){const t=ke(e.provider);return{headline:`This chat isn't available with ${t}`,explanation:`This chat runs through the ${e.command} command, and ${t} can't run CodeYam's commands. Nothing was started and nothing in your code has been touched.`,nextAction:"Switch the build agent to Claude, Codex, or OpenCode in settings to use this chat, or continue without it.",unchangedAfterRetry:`Tried just now — ${t} still can't run ${e.command}`}}return{headline:"The build agent didn't start",explanation:"CodeYam opened a shell to start the build agent and it never became ready. This is the agent failing to start, not your project — nothing in your code has been touched.",nextAction:"Use Retry. If it fails again, copy this report and send it on — a shell that will not come up is a setup problem on this machine rather than something to fix in your project.",unchangedAfterRetry:"Tried just now — the agent still didn’t start"}}function Yn({failure:e=null,onRetry:t}){const{phase:n,attempts:r,retry:a}=Ne(t),o=ha(e);return s.jsx("div",{"data-testid":"mini-agent-launch-failed-banner",className:"absolute inset-0 z-10 flex items-start justify-center bg-black/60 p-3",children:s.jsx(be,{severity:"error",testId:"mini-agent-launch-failed-notice",headline:o.headline,explanation:o.explanation,nextAction:o.nextAction,actions:(e==null?void 0:e.kind)==="unsupported"?[]:[{label:"Retry",onClick:a,pending:n==="pending",pendingLabel:"Starting…",testId:"mini-agent-launch-failed-retry"}],actionFeedback:n==="unchanged"?s.jsxs("span",{"data-testid":"mini-agent-launch-failed-unchanged",children:[o.unchangedAfterRetry,r>1?` (${r} tries)`:"","."]}):null})})}const zi=Object.freeze(Object.defineProperty({__proto__:null,MiniAgentLaunchFailed:Yn},Symbol.toStringTag,{value:"Module"}));function Vn({status:e,failure:t=null,onRetry:n}){return e==="retrying"?s.jsx(Wn,{}):e==="failed"?s.jsx(Yn,{failure:t,onRetry:n}):null}const Ki=Object.freeze(Object.defineProperty({__proto__:null,MiniAgentLaunchOverlay:Vn},Symbol.toStringTag,{value:"Module"})),ma=1e3;let yt=0;function Hi(){yt=Date.now()}function vt(){return yt===0?1/0:Date.now()-yt}function Ui(){return vt()<ma}const Jn=5e3,Yt=6e4,ba=50;function Vt(e,t=Jn){return e<t}function ga(e,t=Jn){return Math.max(ba,t-e)}const Ae=new Map;async function xa(e,t,n,r){if(r!=null&&r.aborted)return null;if(!Vt(vt()))return e;const a=Ae.get(t);if(a)return a.label=e,G("dispatch-rename-superseded",{caller:n,label:e}),null;const o={label:e};Ae.set(t,o);let c=0;for(;;){if(r!=null&&r.aborted)return Ae.delete(t),G("dispatch-rename-cancelled",{caller:n,label:o.label,waitedMs:c}),null;const l=vt();if(!Vt(l))break;const d=ga(l);if(c+d>Yt)return Ae.delete(t),G("dispatch-rename-abandoned",{caller:n,label:o.label,msSinceKeystroke:l,waitedMs:c,capMs:Yt}),null;G("dispatch-rename-deferred",{caller:n,label:o.label,msSinceKeystroke:l,retryInMs:d,waitedMs:c}),await new Promise(f=>setTimeout(f,d)),c+=d}return Ae.delete(t),o.label}const ya=40;function va(e){const t=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return t&&t.slice(0,ya).replace(/-+$/,"")||"session"}const ct=3e3;function wa(e){return e==="codex"?"codex":e==="gemini"?"gemini":e==="opencode"?"opencode":"claude"}function Xn(e,t,n,r,a){const o=wa(e),c=r?_a(n,r):o;if(o!=="claude")return c;const l=t?" --permission-mode auto":"",d=a?` --session-id ${Ot(n,a)}`:"";return`${c}${l}${d}`}function _a(e,t){const n=Ot(e,t);return e==="powershell"?`& ${n}`:n}function Ot(e,t){return`'${e==="powershell"?t.replaceAll("'","''"):t.replaceAll("'","'\\''")}'`}function ja(e,t,n=!0,r="posix",a=null,o=null){const c=Ot(r,t);return e==="opencode"?`opencode${n?" --auto":""} --prompt ${c}\r`:`${Xn(e,n,r,a,o)} ${c}\r`}async function Sa(e,t=Se,n=Ce,r="dispatch-rename-launch",a){const o=await xa(va(e),n,r,a);return o===null?!1:(await In(`/rename ${o}`,t,n),!0)}function ka(e,t,n,r=Ce,a){G("dispatch-rename",{phase:"queued",caller:t,label:e,delayMs:ct}),setTimeout(()=>{G("dispatch-rename",{phase:"fired",caller:t,label:e,delayMs:ct}),Sa(e,n,r,t).then(o=>a==null?void 0:a(o?"fired":"superseded"),()=>a==null?void 0:a("failed"))},ct)}const At=".codeyam/tmp/inline-prompt.md";function Ca(e){return e.split(`
|
|
8
|
-
`).map(t=>t.startsWith("'@")?` ${t}`:t).join(`
|
|
9
|
-
`)}function Na(e){return`mkdir -p .codeyam/tmp && cat > ${At} << 'INLINE_PROMPT_EOF'
|
|
10
|
-
${e}
|
|
11
|
-
INLINE_PROMPT_EOF\r`}function Ta(e){return`New-Item -ItemType Directory -Force -Path .codeyam/tmp | Out-Null; @'
|
|
12
|
-
${Ca(e)}
|
|
13
|
-
'@ | Set-Content -LiteralPath ${At} -Encoding utf8\r`}function Ea(e,t,n=!0,r="posix",a=null,o=null){const c=Xn(e,n,r,a,o),l=r==="powershell"?Ta(t):Na(t),d=`${c} "Read the file at '${At}' for your instructions."\r`;return[l,d]}function Oa({attempt:e,sawOutput:t}){return t?e===1?"extend":"ready":e===1?"retry":"fail"}function Aa({idleMs:e,ceilingMs:t}){return new Promise(n=>{let r=null,a=null,o=!1;function c(){o||(o=!0,r!==null&&clearTimeout(r),a!==null&&clearTimeout(a),window.removeEventListener("miniagent-output",d),n())}function l(){r!==null&&clearTimeout(r),r=setTimeout(c,e)}function d(){l()}window.addEventListener("miniagent-output",d),a=setTimeout(c,t),l()})}function Ma(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null))}const Ia=e=>{typeof fetch=="function"&&fetch("/api/launch-trace",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Ma(e)),keepalive:!0}).catch(()=>{})};let Pa=Ia;function Jt(e){Pa(e)}function Ye(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();const e=()=>Math.floor(Math.random()*4294967296).toString(16);return`${e()}-${e()}-${e()}-${e()}`}function Xt(e){return e?e==="initial-design"?"design":e==="design-tweak"?"design-tweak":e==="plan"||e.startsWith("edit-plan-")?"plan":"other":"build"}function qt(e){const t=e==null?void 0:e.trim().split(/\s+/)[0];return t&&/^\/[a-z0-9-]{1,64}$/.test(t)?t:void 0}let wt=null;function Wi(e){wt=e}function Ra(){const e=wt;return wt=null,e}function Yi(e){return e??Ra()??Ye()}function Da(e){return e==="fired"?{event:"rename-fired"}:e==="superseded"?{event:"rename-skipped",reason:"superseded"}:{event:"rename-failed"}}const La=350,$a=4e3,Gt=8e3,Fa=500,Ba=5e3,ie={armed:"mini-agent-launch-armed",fired:"mini-agent-launch-fired",ready:"mini-agent-launch-ready",confirmed:"mini-agent-launch-confirmed",relaunch:"mini-agent-relaunch",failed:"mini-agent-launch-failed",reattached:"mini-agent-launch-reattached"};function za(e){const{provider:t,slashCommand:n,prompt:r,chatName:a,sendInput:o,permissionModeAuto:c=!0,shellDialect:l=null,onLaunchAttempt:d,beforeRelaunch:f}=e,[g,b]=i.useState("idle"),[u,h]=i.useState(null),m=i.useRef("idle"),x=i.useRef(null),y=i.useCallback((C,H=null)=>{m.current=C,x.current=H,b(C),h(H)},[]),p=i.useRef(!1),_=i.useRef(f);i.useEffect(()=>{_.current=f},[f]);const v=i.useRef(o),w=i.useRef(n),S=i.useRef(r),M=i.useRef(a),N=i.useRef(t),z=i.useRef(c),j=i.useRef(l),I=i.useRef(null),E=i.useCallback(C=>{I.current=C},[]),F=i.useRef(null),W=i.useCallback(C=>{F.current=C},[]);i.useEffect(()=>{v.current=o},[o]),i.useEffect(()=>{z.current=c},[c]),i.useEffect(()=>{j.current=l},[l]),i.useEffect(()=>{w.current=n},[n]),i.useEffect(()=>{S.current=r},[r]),i.useEffect(()=>{M.current=a},[a]),i.useEffect(()=>{N.current=t},[t]);const L=i.useRef(d);i.useEffect(()=>{L.current=d},[d]);const K=i.useRef(null),A=i.useRef(null),Q=i.useRef(null),ce=i.useCallback(()=>(K.current??(K.current=Ye()),K.current),[]),V=i.useCallback((C,H={})=>{const B=A.current;B&&Jt({...C,...H,launchId:B,retryOf:Q.current,role:Xt(M.current),command:qt(w.current)})},[]),J=i.useRef(0),re=i.useRef(!1),Z=i.useRef(0),oe=i.useRef(0),Y=i.useRef(0);i.useEffect(()=>{const C=()=>{oe.current+=1};return window.addEventListener("miniagent-output",C),()=>window.removeEventListener("miniagent-output",C)},[]);const q=i.useCallback((C,H)=>{const B=w.current,te=S.current;return De(it,()=>{const de=j.current??"posix";if(B){const $=ja(N.current,B,z.current,de,I.current,F.current),le=lt($);return C(le),new Promise($e=>{setTimeout(()=>{H()&&C("\r"),$e()},we)})}const[ne,pe]=Ea(N.current,te??"",z.current,de,I.current,F.current),fe=lt(ne),se=lt(pe);return C(fe),new Promise($=>{setTimeout(()=>{if(!H())return $();C("\r"),setTimeout(()=>{if(!H())return $();C(se),setTimeout(()=>{H()&&C("\r"),$()},we)},Fa)},we)})})},[]),ee=i.useCallback(C=>{const H=m.current;if(H==="ready"||H==="confirmed"||x.current)return;const B=++J.current;p.current=!0,y("ready"),G(ie.ready,{launchId:A.current,provider:N.current,slashCommand:w.current,reason:C,elapsedMs:Date.now()-Z.current}),setTimeout(()=>{if(J.current!==B)return;y("confirmed");const te=Date.now()-Z.current;V({event:"prompt-accepted",reason:C},{elapsedMs:te}),G(ie.confirmed,{launchId:A.current,provider:N.current,slashCommand:w.current,reason:C,verified:!1,elapsedMs:te})},Ba)},[y,V]),ue=i.useCallback(C=>{var se;const H=++J.current,B=Date.now();Z.current=B,p.current=!1,C==="retry"&&A.current?(Q.current=A.current,A.current=Ye()):(Q.current=null,A.current=K.current??Ye(),K.current=null),(se=L.current)==null||se.call(L,{launchId:A.current,retryOf:Q.current});const te=S.current;Jt({event:"armed",launchId:A.current,retryOf:Q.current,role:Xt(M.current),command:qt(w.current),promptLen:typeof te=="string"?te.length:void 0});const de=w.current;if(de&&!ts(N.current)){y("failed",{kind:"unsupported",command:de.split(/\s+/)[0],provider:N.current}),V({event:"prompt-rejected",reason:"skill-invocation-unsupported"}),G(ie.failed,{launchId:A.current,provider:N.current,slashCommand:de,reason:"skill-invocation-unsupported",elapsedMs:0});return}Y.current=oe.current,y("armed"),G(ie.armed,{launchId:A.current,provider:N.current,slashCommand:w.current,chatName:M.current,hasPrompt:typeof S.current=="string"});function ne(){return J.current===H}function pe($){ne()&&(y($===1?"firing":"retrying"),V({event:"fired"},{attempt:$,elapsedMs:Date.now()-B}),G($===1?ie.fired:ie.relaunch,{launchId:A.current,provider:N.current,slashCommand:w.current,chatName:M.current,attempt:$,elapsedMs:Date.now()-B}),q(v.current,ne).then(()=>{ne()&&(Y.current=oe.current,V({event:"prompt-written",kind:"ui-payload"},{attempt:$,elapsedMs:Date.now()-B}))}),es(N.current)?re.current?V({event:"rename-skipped",reason:"already-scheduled"}):(re.current=!0,V({event:"rename-queued"}),ka(M.current,"mini-agent-chat",le=>v.current(le),it,le=>V(Da(le)))):V({event:"rename-skipped",reason:"provider-unsupported"}),setTimeout(()=>fe($),Gt))}function fe($){if(!ne())return;const le=oe.current>Y.current;switch(Oa({attempt:$,sawOutput:le})){case"retry":pe(2);return;case"extend":G(ie.relaunch,{launchId:A.current,provider:N.current,slashCommand:w.current,attempt:2,sawOutput:!0,resent:!1,elapsedMs:Date.now()-B}),setTimeout(()=>fe(2),Gt);return;case"ready":ee("output-without-banner");return;case"fail":y("failed"),V({event:"prompt-rejected",reason:"banner-timeout"},{attempt:$,elapsedMs:Date.now()-B}),G(ie.failed,{launchId:A.current,provider:N.current,slashCommand:w.current,reason:"banner-timeout",sawOutput:!1,elapsedMs:Date.now()-B})}}Aa({idleMs:La,ceilingMs:$a}).then(()=>{ne()&&pe(1)})},[q,ee,y,V]),T=i.useCallback(async C=>{var B;const H=++J.current;Z.current=Date.now(),y("retrying"),G(ie.relaunch,{launchId:A.current,provider:N.current,slashCommand:C,inAgent:!0}),await((B=_.current)==null?void 0:B.call(_).catch(()=>{})),J.current===H&&(await In(C,te=>v.current(te),it),J.current===H&&ee("relaunch-in-agent"))},[ee,y]),k=i.useCallback(()=>{re.current=!1,ue("arm")},[ue]),X=i.useCallback(()=>{const C=w.current;if(p.current&&C){T(C);return}ue("retry")},[ue,T]),D=i.useCallback(()=>{J.current!==0&&m.current!=="armed"&&ee("banner")},[ee]),ge=i.useCallback(C=>{var te;if(J.current===0)return;const H=m.current;if(H==="confirmed"||H==="idle"||((te=x.current)==null?void 0:te.kind)==="rejected")return;J.current++,p.current=!0,y("failed",{kind:"rejected",command:C});const B=Date.now()-Z.current;V({event:"prompt-rejected",reason:"slash-command-rejected"},{elapsedMs:B}),G(ie.failed,{launchId:A.current,provider:N.current,slashCommand:w.current,reason:"slash-command-rejected",command:C,elapsedMs:B})},[y,V]),nt=i.useCallback(()=>{if(J.current===0)return;J.current++,p.current=!1,y("failed");const C=Date.now()-Z.current;V({event:"prompt-rejected",reason:"startup-failed"},{elapsedMs:C}),G(ie.failed,{launchId:A.current,reason:"startup-failed",elapsedMs:C})},[y,V]),rt=i.useCallback(()=>{J.current++,y("confirmed"),G(ie.reattached,{provider:N.current,chatName:M.current})},[y]);return i.useEffect(()=>()=>{J.current++},[]),{status:g,failure:u,peekLaunchId:ce,arm:k,retry:X,onBannerReady:D,onRejected:ge,onStartupFailed:nt,onReattached:rt,setLaunchProgram:E,setLaunchSessionId:W}}function lt(e){return e.endsWith("\r")?e.slice(0,-1):e}const qe=i.createContext({registerSender:()=>{},setReady:()=>{},sendToAgent:()=>!1,agentReady:!1});function Ka({children:e}){const t=i.useRef(null),[n,r]=i.useState(!1),a=i.useCallback(d=>{t.current=d},[]),o=i.useCallback(d=>{r(d)},[]),c=i.useCallback(d=>{const f=t.current;return f?f(d):!1},[]),l=i.useMemo(()=>({registerSender:a,setReady:o,sendToAgent:c,agentReady:n}),[a,o,c,n]);return s.jsx(qe.Provider,{value:l,children:e})}function Ha(){const{sendToAgent:e,agentReady:t}=i.useContext(qe);return{sendToAgent:e,agentReady:t}}function Ua(e,t){const{registerSender:n,setReady:r}=i.useContext(qe);i.useEffect(()=>(n(e),()=>n(null)),[n,e]),i.useEffect(()=>(r(t),()=>r(!1)),[r,t])}function qn(){const{registerSender:e,setReady:t}=i.useContext(qe);return{registerSender:e,setReady:t}}const Vi=Object.freeze(Object.defineProperty({__proto__:null,AgentInputProvider:Ka,useAgentInput:Ha,useAgentInputChannel:qn,useRegisterAgentInput:Ua},Symbol.toStringTag,{value:"Module"})),_t=new Map,jt=new Set;function Ji(e){return _t.get(e)??null}function Qt(e,t){const n=_t.get(e)??null;if(!(t&&n&&t.length===n.length&&t.every((r,a)=>r===n[a]))&&!(t===null&&n===null)){_t.set(e,t);for(const r of jt)r()}}function Xi(e){return jt.add(e),()=>jt.delete(e)}function Wa(e,t){return i.useCallback(async n=>{var r;return((r=e.current)==null?void 0:r.readyState)!==WebSocket.OPEN?!1:(await t.current.handleImageFiles(n),!0)},[e,t])}function Ya(e){var r;const t=e.buffer.active,n=[];for(let a=0;a<e.rows;a++)n.push(((r=t.getLine(t.baseY+a))==null?void 0:r.translateToString(!0))??"");return n}function Gn({className:e=""}){const{openPicker:t}=vn();return s.jsxs("button",{type:"button",onClick:t,title:"Attach a file","aria-label":"Attach a file","data-testid":"attach-file-button",className:`inline-flex items-center gap-1 text-xs font-medium cursor-pointer bg-transparent border-none text-[var(--text-dim)] hover:text-[var(--text-primary)] transition ${e}`,children:[s.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:s.jsx("path",{d:"m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"})}),"Attach file"]})}const qi=Object.freeze(Object.defineProperty({__proto__:null,AttachFileButton:Gn},Symbol.toStringTag,{value:"Module"})),Ke=15;function ut(e,t,n){if(!Js(e,t))return!1;try{return n.fit(),!0}catch{return!1}}function Qn({chatName:e,prompt:t,slashCommand:n,seedText:r,height:a=400,onClose:o,beforeRelaunch:c,binding:l,onInputChannel:d,onScreen:f}){const g=i.useRef(l);g.current=l;const b=i.useRef(null),u=i.useRef(null),h=i.useRef(null),m=i.useRef(null);i.useRef(t);const{config:x}=jn(),y=(x==null?void 0:x.provider)??"claude",[p,_]=i.useState({kind:"connecting"}),v=i.useRef(null),[w,S]=i.useState(0),[M,N]=i.useState(()=>Bt()),z=i.useCallback(T=>{const k=u.current;(k==null?void 0:k.readyState)===WebSocket.OPEN&&k.send(JSON.stringify({type:"input",data:T}))},[]),j=Us({wsRef:u,insertInput:z}),I=i.useRef(j);I.current=j;const{registerSender:E,setReady:F}=qn(),W=i.useCallback(T=>{var k;return((k=u.current)==null?void 0:k.readyState)===WebSocket.OPEN?(u.current.send(JSON.stringify({type:"input",data:T})),!0):!1},[]),L=p.kind==="open";i.useEffect(()=>(L&&E(W),()=>E(null)),[E,W,L]),i.useEffect(()=>{var T,k;(k=(T=g.current)==null?void 0:T.onSender)==null||k.call(T,L?W:null)},[W,L]),i.useEffect(()=>(F(L),()=>F(!1)),[F,L]);const K=i.useRef(d),A=i.useRef(f);i.useEffect(()=>{K.current=d,A.current=f}),i.useEffect(()=>{var T;if(L)return(T=K.current)==null||T.call(K,W),()=>{var k;return(k=K.current)==null?void 0:k.call(K,null)}},[W,L]);const{registerFileSink:Q}=wn(),ce=Wa(u,I);i.useEffect(()=>(L&&Q(ce),()=>Q(null)),[Q,ce,L]);const V=i.useCallback(()=>{var T;((T=u.current)==null?void 0:T.readyState)===WebSocket.OPEN&&(E(W),F(!0),Q(ce)),Hs(b.current,()=>{var k;return(k=m.current)==null?void 0:k.focus()})},[E,F,W,Q,ce]),{shellDialect:J}=ln(),re=i.useRef(null),Z=i.useCallback(({launchId:T,retryOf:k})=>{re.current=T;const X=u.current;(X==null?void 0:X.readyState)===WebSocket.OPEN&&X.send(JSON.stringify({type:"launch-attempt",launchId:T,retryOf:k}))},[]),oe=za({provider:y,slashCommand:n,prompt:t,chatName:e,sendInput:z,permissionModeAuto:(x==null?void 0:x.claudePermissionModeAuto)??!0,shellDialect:J,onLaunchAttempt:Z,beforeRelaunch:c}),Y=i.useRef(oe);i.useEffect(()=>{Y.current=oe});const q=i.useRef(e);i.useEffect(()=>{q.current=e});const ee=i.useRef(r),ue=i.useRef(n);return i.useEffect(()=>{ee.current=r,ue.current=n}),i.useEffect(()=>{const T=b.current;if(!T||Bt())return;const k=new ms.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}),X=new bs.FitAddon;k.loadAddon(X),k.open(T);const D=ks(k,T,{onError:P=>console.warn("[MiniAgentChat]",P)}),ge=Is(k,{sendInput:P=>{const O=u.current;(O==null?void 0:O.readyState)===WebSocket.OPEN&&O.send(JSON.stringify({type:"input",data:P}))}}),nt=zs(T,P=>{I.current.handleImageFiles(P)}),rt=requestAnimationFrame(()=>{if(!ut(k,T,X))return;fe=!0;const P=u.current;(P==null?void 0:P.readyState)===WebSocket.OPEN&&P.send(JSON.stringify({type:"resize",cols:k.cols,rows:k.rows}))});m.current=k,h.current=X;let C;const H=()=>{C!==void 0&&window.clearTimeout(C),C=window.setTimeout(()=>{var O,U,ae;C=void 0;const P=Ya(k);Qt(q.current,P),(U=(O=g.current)==null?void 0:O.onScreen)==null||U.call(O,P),(ae=A.current)==null||ae.call(A,P)},300)},B={current:"inline"},te={current:null},de={current:!1},ne={current:!1},pe={current:!1};let fe=!1,se=0,$=null;v.current=()=>{$==null||$(),$=null,se=0,le()};function le(){_({kind:"connecting"});const P=vs({mode:B.current,sessionId:te.current??void 0,chatKey:e,launchId:re.current??Y.current.peekLaunchId(),cols:fe?k.cols:void 0,rows:fe?k.rows:void 0,capture:Sn()}),O=new WebSocket(P);O.binaryType="arraybuffer",u.current=O,O.onopen=()=>{se=0,_({kind:"open"}),at(!0),window.dispatchEvent(new CustomEvent("miniagent-ws-open")),O.send(JSON.stringify({type:"resize",cols:k.cols,rows:k.rows}))},O.onmessage=U=>{var ae,Te,Fe,Lt;if(U.data instanceof ArrayBuffer){k.write(new Uint8Array(U.data)),H(),window.dispatchEvent(new CustomEvent("miniagent-output"));return}try{const R=JSON.parse(U.data);if(R.type==="error"&&R.reason===ys){ne.current=!0,N(!0);return}if(R.type==="error"){ne.current=!0,_({kind:"server-error",message:Qs(R)});return}if(R.type==="drop-complete"){I.current.resolveDrop(R.id,R.path);return}if(R.type==="drop-error"){I.current.rejectDrop(R.id,R.message);return}if(R.type==="session-id"){if(typeof R.sessionId=="string"&&((Te=(ae=g.current)==null?void 0:ae.onSessionId)==null||Te.call(ae,R.sessionId)),R.sessionId&&(te.current=R.sessionId,B.current="resume"),R.reattached===!0){de.current=!0,Y.current.onReattached(),(Lt=(Fe=g.current)==null?void 0:Fe.onReattached)==null||Lt.call(Fe,!!ee.current);const Be=ee.current,$t=ue.current;Be&&$t&&!pe.current&&(pe.current=!0,da($t,q.current));return}if(!de.current){de.current=!0,Y.current.setLaunchProgram(typeof R.launchProgram=="string"?R.launchProgram:null),Y.current.setLaunchSessionId(typeof R.launchSessionId=="string"?R.launchSessionId:null),Y.current.arm();const Be=ue.current;ee.current&&Be&&Mn(q.current,Be)}return}if(R.type==="agent-idle"||R.type==="claude-idle"||R.type==="agent-blocked"){window.dispatchEvent(new CustomEvent("miniagent-agent-idle",{detail:{chatName:q.current}}));return}if(R.type==="agent-active"||R.type==="claude-active"){window.dispatchEvent(new CustomEvent("miniagent-agent-active",{detail:{chatName:q.current}}));return}if(R.type==="agent-banner-ready"){Y.current.onBannerReady();return}if(R.type==="launch-rejected"){Y.current.onRejected(String(R.command??""));return}if(R.type==="agent-auth-required"){window.dispatchEvent(new CustomEvent("agent-auth-required"));return}if(R.type==="startup-failed"){Y.current.onStartupFailed();return}}catch{k.write(U.data),H(),window.dispatchEvent(new CustomEvent("miniagent-output"))}},O.onerror=()=>{},O.onclose=async()=>{if(at(!1),I.current.cancelAllDrops("Not connected"),ne.current){_(ae=>ae.kind==="server-error"?ae:{kind:"ended"});return}_({kind:"reconnecting",attempt:Math.min(se+1,Ke),maxAttempts:Ke});const U=await Xs();if(!ne.current){if(U){_({kind:"server-stopped"}),$==null||$(),$=qs(2e3,()=>{ne.current||window.location.reload()});return}if(se<Ke){const ae=se<4?1e3*Math.pow(2,se):1e4;se++,_({kind:"reconnecting",attempt:se,maxAttempts:Ke}),setTimeout(()=>{ne.current||le()},ae)}else _({kind:"failed"})}}}fe=ut(k,T,X),le(),k.onData(P=>{const O=u.current;(O==null?void 0:O.readyState)===WebSocket.OPEN?O.send(JSON.stringify({type:"input",data:P})):S(U=>U+1)});function $e(P){const O=m.current;if(!O)return;const U=P.target;if(U!=null&&U.closest(".xterm-viewport")||O.buffer.active.length<=O.rows)return;const Te=js(P.deltaY,P.deltaMode);Te!==0&&(O.scrollLines(Te),P.preventDefault(),P.stopPropagation())}T.addEventListener("wheel",$e,{passive:!1});function Rt(){var P;Ps(T)||(P=m.current)==null||P.focus()}window.addEventListener("terminal-focus",Rt);function Dt(P){const O=P.detail,U=u.current;((O==null?void 0:O.chatName)===q.current||(O==null?void 0:O.chatName)===ra)&&typeof O.text=="string"&&(U==null?void 0:U.readyState)===WebSocket.OPEN&&U.send(JSON.stringify({type:"input",data:O.text}))}return window.addEventListener("miniagent-send-input",Dt),()=>{var O,U;C!==void 0&&window.clearTimeout(C),Qt(q.current,null),(O=A.current)==null||O.call(A,null),ne.current=!0,at(!1),$==null||$(),$=null,v.current=null,window.removeEventListener("terminal-focus",Rt),window.removeEventListener("miniagent-send-input",Dt),T.removeEventListener("wheel",$e),cancelAnimationFrame(rt),D(),ge(),nt();const P=u.current;(P==null?void 0:P.readyState)===WebSocket.OPEN&&P.close(),(U=m.current)==null||U.dispose(),h.current=null}},[y]),Ws(b,()=>{const T=m.current,k=h.current;if(!T||!k||!ut(T,b.current,k))return;const X=u.current;(X==null?void 0:X.readyState)===WebSocket.OPEN&&X.send(JSON.stringify({type:"resize",cols:T.cols,rows:T.rows}))}),s.jsxs("div",{"data-codeyam-hydrated":"MiniAgentChat",className:"mt-2 border border-[var(--border-subtle)] rounded-lg overflow-hidden",children:[s.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 bg-[var(--bg-card)]",children:[s.jsx("span",{className:"text-xs font-medium text-[var(--accent-active)]",children:ke(y)}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(Gn,{}),o&&s.jsx("button",{onClick:o,className:"text-[var(--text-dim)] hover:text-[var(--text-primary)] text-xs bg-transparent border-none cursor-pointer",children:"Close"})]})]}),s.jsx("div",{ref:b,className:"mini-agent-terminal",tabIndex:-1,onPointerDown:V,onClick:V,onDragEnter:j.dropHandlers.onDragEnter,onDragOver:j.dropHandlers.onDragOver,onDragLeave:j.dropHandlers.onDragLeave,onDrop:j.dropHandlers.onDrop,style:{height:a,background:"#1a1a1a",padding:"6px 10px",position:"relative",overflow:"hidden",outline:"none"},children:M?s.jsx(bn,{}):s.jsxs(s.Fragment,{children:[s.jsx(Un,{status:p,pulseKey:w,onRefresh:()=>window.location.reload(),onDismissServerStopped:()=>{var T;return(T=v.current)==null?void 0:T.call(v)}}),s.jsx(Vn,{status:oe.status,failure:oe.failure,onRetry:oe.retry}),j.dragActive&&s.jsx(Cn,{}),j.errorToast&&s.jsx(Nn,{message:j.errorToast})]})})]})}const Gi=Object.freeze(Object.defineProperty({__proto__:null,MiniAgentChat:Qn},Symbol.toStringTag,{value:"Module"}));function Qi(e,t){switch(e){case"connected":return`${t} is connected.`;case"settling":return`Checking your ${t} sign-in…`;case"signed-in-not-stored":return`Your ${t} sign-in worked, but it wasn't saved on this machine.`;case"needs-login":return`You are not signed into ${t} yet.`}}function Zi(e,t){return e==="did-not-persist"?`The folder ${t} keeps its sign-in in was empty after a restart, so signing in again here would be lost the same way. Somewhere that keeps its files between restarts will hold it.`:`${t} reported a successful sign-in, but nothing was saved where it keeps credentials — so the chat still can't use it.`}function ec(e,t){return e.binaryMismatch?`The chat started a different copy of ${t} than the one you signed in with, so it may ask you to sign in again.`:e.configMissingAtLaunch?`The chat started ${t} before its settings were ready, so it may have shown its own sign-in screen. Reopening the chat should go straight in.`:null}function tc(e){return e!=="connected"&&e!=="signed-in-not-stored"}function nc(e){return e==="needs-login"||e==="signed-in-not-stored"}function Zt(e){return e===null?"Couldn't reach the editor to set that up.":e.ok?"Done. Open a new Shell and `claude` there will use this sign-in.":`Couldn't set that up: ${e.error??"unknown error"}`}const Va=500,Ja=75e3,Xa=3e5,qa=`
|
|
14
|
-
|
|
15
|
-
--- transcript tail ---
|
|
16
|
-
`,Ga=`
|
|
17
|
-
|
|
18
|
-
--- installer output ---
|
|
19
|
-
`;function Zn(e){const t=[{delimiter:qa,label:"Login transcript (what claude actually printed)"},{delimiter:Ga,label:"Installer output (what npm printed)"}];for(const{delimiter:n,label:r}of t){const a=e.indexOf(n);if(a!==-1)return{headline:e.slice(0,a),tail:e.slice(a+n.length),tailLabel:r}}return{headline:e}}function er({onAuthenticated:e}){const[t,n]=i.useState({state:"starting"}),[r,a]=i.useState(""),[o,c]=i.useState(!1),[l,d]=i.useState(!1),[f,g]=i.useState(!1),[b,u]=i.useState(!1),[h,m]=i.useState(!1),x=i.useRef(!1),y=i.useRef(e);y.current=e;const p=i.useCallback(async()=>{try{const j=await fetch("/api/auth/status");if(!j.ok)return;const I=await j.json();n(I),I.state==="authenticated"&&!x.current&&(x.current=!0,y.current())}catch{}},[]),_=i.useCallback(async()=>{x.current=!1,g(!1),u(!1),n({state:"starting"});try{const j=await fetch("/api/auth/start",{method:"POST"});if(j.ok)(await j.json().catch(()=>({}))).installing&&n({state:"installing"});else{const I=await j.json().catch(()=>({}));n({state:"failed",error:I.error??"Could not start the login process."})}}catch{n({state:"failed",error:"Could not start the login process."})}},[]);i.useEffect(()=>{_()},[_]),i.useEffect(()=>{const j=window.setInterval(()=>void p(),Va);return()=>window.clearInterval(j)},[p]);const v=t.state==="installing",w=t.state!=="failed"&&t.state!=="idle"&&t.state!=="authenticated"&&t.state!=="url-ready"&&!v;i.useEffect(()=>{if(!w){g(!1);return}const j=window.setTimeout(()=>g(!0),Ja);return()=>window.clearTimeout(j)},[w]),i.useEffect(()=>{if(!v){u(!1);return}const j=window.setTimeout(()=>u(!0),Xa);return()=>window.clearTimeout(j)},[v]);const S=i.useCallback(async()=>{if(r.trim()){c(!0);try{const j=await fetch("/api/auth/code",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({code:r.trim()})});if(j.ok)a("");else{const I=await j.json().catch(()=>({}));n({state:"failed",error:I.error??"Code not accepted — check the value and try again."})}}catch{n({state:"failed",error:"Could not submit the code."})}finally{c(!1)}}},[r]),M=i.useCallback(async()=>{try{await fetch("/api/auth/cancel",{method:"POST"})}catch{}_()},[_]),N=i.useCallback(async()=>{m(!0);try{await fetch("/api/auth/refresh-cache",{method:"POST"}),e()}catch{}finally{m(!1)}},[e]),z=i.useCallback(()=>{var j;t.url&&((j=navigator.clipboard)==null||j.writeText(t.url),d(!0),window.setTimeout(()=>d(!1),1500))},[t.url]);if(f&&w)return s.jsxs("div",{"data-testid":"claude-oauth-timeout",className:"space-y-3",children:[s.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 ",s.jsx("code",{className:"text-white",children:"claude /login"})," ","directly."]}),s.jsx(ye,{onRetry:()=>void M(),onRecheck:()=>void N(),rechecking:h,retryTestId:"claude-oauth-timeout-retry",recheckTestId:"claude-oauth-timeout-recheck"})]});if(v)return s.jsx(yn,{timedOut:b,onRetry:()=>void M(),onRecheck:()=>void N(),rechecking:h});if(t.state==="failed"){const{headline:j,tail:I,tailLabel:E}=Zn(t.error??"Login failed.");return s.jsxs("div",{"data-testid":"claude-oauth-failed",className:"space-y-3",children:[s.jsx("p",{className:"text-sm text-[#FF8B43]",children:j}),I&&s.jsxs("details",{open:!0,"data-testid":"claude-oauth-failed-transcript",children:[s.jsx("summary",{className:"cursor-pointer text-xs text-[#9CA3AF]",children:E}),s.jsx("pre",{className:"mt-2 max-h-64 overflow-auto whitespace-pre-wrap break-all rounded bg-[#1A1A1A] p-2 font-mono text-[11px] leading-relaxed text-[#9CA3AF]",children:I})]}),s.jsx(ye,{onRetry:()=>void M(),onRecheck:()=>void N(),rechecking:h,retryLabel:"Try again",recheckTestId:"claude-oauth-failed-recheck"})]})}return t.state==="idle"?s.jsxs("div",{"data-testid":"claude-oauth-idle",className:"space-y-3",children:[s.jsx("p",{className:"text-sm text-[#FF8B43]",children:"No login is running — the login process stopped before it could start. Try again, or recheck if you already authenticated elsewhere."}),s.jsx(ye,{onRetry:()=>void M(),onRecheck:()=>void N(),rechecking:h,retryTestId:"claude-oauth-idle-retry",recheckTestId:"claude-oauth-idle-recheck"})]}):t.state==="authenticated"?s.jsx("p",{"data-testid":"claude-oauth-authenticated",className:"text-sm text-[#D7FF63]",children:"Connected. Opening Build…"}):t.state==="url-ready"&&!t.url?s.jsxs("div",{"data-testid":"claude-oauth-url-missing",className:"space-y-3",children:[s.jsx("p",{className:"text-sm text-[#FF8B43]",children:"The login process reported that a link was ready but did not send a usable one. Try again, or recheck if you already authenticated elsewhere."}),s.jsx(ye,{onRetry:()=>void M(),onRecheck:()=>void N(),rechecking:h,retryTestId:"claude-oauth-url-missing-retry",recheckTestId:"claude-oauth-url-missing-recheck"})]}):t.state==="url-ready"&&t.url?s.jsxs("div",{"data-testid":"claude-oauth-url-ready",className:"space-y-3",children:[s.jsx("p",{className:"text-sm text-[#8E8E8E]",children:"Open this URL in your browser, approve access, then paste the code back here:"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("code",{className:"flex-1 min-w-0 truncate px-2 py-1.5 rounded bg-black text-[#D7FF63] text-xs",children:t.url}),s.jsx("button",{onClick:z,className:"px-2 py-1.5 text-xs rounded-md border border-[#3A3A3A] text-white cursor-pointer",children:l?"Copied":"Copy"}),s.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"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:r,onChange:j=>a(j.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"}),s.jsx("button",{onClick:()=>void S(),disabled:o||!r.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"})]})]}):s.jsx("p",{"data-testid":"claude-oauth-starting",className:"text-sm text-[#8E8E8E]",children:"Preparing the login link…"})}const rc=Object.freeze(Object.defineProperty({__proto__:null,ClaudeOAuthFlow:er,splitTranscriptTail:Zn},Symbol.toStringTag,{value:"Module"}));function tr({provider:e,onAuthenticated:t,onClose:n}){const r=ke(e);return s.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)"},onMouseDown:a=>{a.target===a.currentTarget&&n()},children:s.jsxs("div",{className:"w-[32rem] max-w-[90vw] rounded-lg border border-[#3A3A3A] bg-[#1E1E1E] p-6 space-y-4",children:[s.jsxs("div",{className:"flex items-start justify-between",children:[s.jsxs("h2",{className:"text-base font-medium text-white",children:["Connect your ",r," account"]}),s.jsx("button",{onClick:n,"aria-label":"Close",className:"text-[#8E8E8E] hover:text-white cursor-pointer",children:"✕"})]}),e==="claude"?s.jsx(er,{onAuthenticated:t}):s.jsx(xn,{provider:e,onAuthenticated:t})]})})}const sc=Object.freeze(Object.defineProperty({__proto__:null,ProviderAuthModal:tr},Symbol.toStringTag,{value:"Module"}));function Qa(e){const t=new Date(e).getTime()-Date.now(),n=Math.abs(Math.round(t/36e5));if(n<1)return t<0?"just now":"very soon";if(n<48)return t<0?`${n} h ago`:`in ${n} h`;const r=Math.round(n/24);return t<0?`${r} d ago`:`in ${r} d`}function nr({provider:e,credsPresent:t=!0,reason:n=null,expiresAt:r=null,shellShare:a=null,sessionOngoing:o=!1,onAuthenticated:c,onAuthorized:l}){const[d,f]=i.useState(!1),[g,b]=i.useState(!1),u=ke(e),h=i.useCallback(()=>{f(!1),c(),l==null||l()},[c,l]),m=i.useCallback(async()=>{b(!0);try{await fetch("/api/auth/refresh-cache",{method:"POST"}),c()}catch{}finally{b(!1)}},[c]),[x,y]=i.useState(null),p=i.useCallback(async()=>{try{const j=await(await fetch("/api/auth/share-store-with-shell",{method:"POST"})).json();y(Zt(j))}catch{y(Zt(null))}},[]),_=n==="stale-verdict",v=e==="claude"&&!t,w=r?` (token expired ${Qa(r)})`:"",S=v?`${u} credentials file is missing`:_?`Couldn't confirm your ${u} sign-in`:n==="token-expired"?`Your ${u} token has expired`:n==="api-401"?`${u} authentication rejected (401)`:`Connect your ${u} account`,M=o?" Your Build session stays open — you can finish logging in here or directly in the Build terminal.":"",N=v?"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.":_?`The editor couldn't reach ${u} to check, so this is the last answer it had — not a fresh one. If you've already signed in, click Recheck. If not, click Authenticate.${M}`:n==="token-expired"?`Your ${u} token has expired${w} — click Authenticate to refresh it. On a fleet VM the dashboard can copy a fresh token from a donor VM.${M}`:n==="api-401"?`The ${u} server rejected your credentials (401)${w}. This usually means the token was revoked or expired. Click Authenticate to re-connect.${M}`:o?"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 ${u} to unlock the Build tab. On a cloud VM the dashboard usually does this for you; locally you connect once here.`;return s.jsxs("div",{"data-testid":"provider-auth-gate","data-auth-variant":v?"creds-missing":_?"stale-verdict":"needs-login","data-auth-card":!0,className:"m-4 rounded-lg border border-[#D7FF63]/40 bg-[#1E1E1E] p-5 space-y-3",children:[s.jsx("h2",{className:"text-base font-medium text-white",children:S}),s.jsx("p",{className:"text-sm text-[#8E8E8E]",children:N}),s.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[s.jsx("button",{onClick:()=>f(!0),className:_?"order-2 px-3 py-2 text-sm rounded-md border border-[#3A3A3A] text-white cursor-pointer":"px-3 py-2 text-sm rounded-md bg-[#D7FF63] text-black font-medium cursor-pointer",children:"Authenticate"}),s.jsx("button",{onClick:()=>void m(),"data-testid":"provider-auth-gate-recheck",disabled:g,className:_?"order-1 px-3 py-2 text-sm rounded-md bg-[#D7FF63] text-black font-medium cursor-pointer disabled:opacity-50":"px-3 py-2 text-sm rounded-md border border-[#3A3A3A] text-white cursor-pointer disabled:opacity-50",children:g?"Rechecking…":_?"Recheck":"Already logged in? Recheck"})]}),e==="claude"&&a==="available"?s.jsxs("div",{className:"space-y-1",children:[s.jsx("button",{onClick:()=>void p(),"data-testid":"provider-auth-share-with-shell",disabled:x!==null,className:"text-sm text-[#D7FF63] underline cursor-pointer disabled:opacity-50",children:"Also use this sign-in in the Shell"}),x?s.jsx("p",{className:"text-xs text-[#8E8E8E]",children:x}):null]}):null,d?s.jsx(tr,{provider:e,onAuthenticated:h,onClose:()=>f(!1)}):null]})}const ac=Object.freeze(Object.defineProperty({__proto__:null,ProviderAuthenticateCta:nr},Symbol.toStringTag,{value:"Module"}));let dt=!1;function rr(e){const{state:t,provider:n,credsPresent:r,reason:a,expiresAt:o,shellShare:c,refresh:l}=hs(),[d]=i.useState(()=>dt);return i.useEffect(()=>{t==="authenticated"?dt=!0:t==="needs-login"&&(dt=!1)},[t]),t==="needs-login"?s.jsx(nr,{provider:n,credsPresent:r,reason:a,expiresAt:o,shellShare:c,onAuthenticated:()=>void l(),onAuthorized:()=>{}}):t==="authenticated"||d?s.jsx(Qn,{...e}):s.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:[s.jsx("span",{"aria-hidden":"true",className:"h-4 w-4 rounded-full border-2 border-[var(--text-dim)] border-t-transparent animate-spin"}),s.jsx("span",{className:"text-xs text-[var(--text-dim)]",children:"Checking your account…"})]})}const oc=Object.freeze(Object.defineProperty({__proto__:null,GatedAgentChat:rr},Symbol.toStringTag,{value:"Module"})),ft=4e3;function en(e){let t;try{t=JSON.stringify(e,null,2)}catch{t=String(e)}return t.length>ft?`${t.slice(0,ft)}
|
|
20
|
-
… (truncated, ${t.length-ft} more chars)`:t}function Za({slug:e,scenarioName:t,seedTabs:n,mockEntries:r,selectedMock:a,selectedSeedTab:o,selectedSeedRows:c}){const l=[],d=t??e;if(l.push(`# Edit Scenario Data: "${d}"`),l.push(""),l.push(`**Slug**: ${e}`),l.push(`**Scenario file**: .codeyam/scenarios/${e}.json`),l.push(""),l.push("## Scenario overview"),n.length>0){l.push("### Seed & Local tables");for(const f of n){const g=f.category?` (${f.category})`:"";l.push(`- **${f.label}**${g} — dataKey \`${f.dataKey}\``)}l.push("")}if(r.length>0){l.push("### HTTP mocks");const f=new Map;for(const g of r){const b=f.get(g.source)??[];b.push(g),f.set(g.source,b)}for(const[g,b]of f){l.push(`**${g}** (${b.length}):`);for(const u of b)l.push(`- \`${u.method} ${u.pathPattern}\``)}l.push("")}if(a){const f=`${a.method} ${a.pathPattern}`;l.push(`## Currently viewing: mock \`${f}\``),l.push(`- **Source**: ${a.source}`),a.status!==void 0&&l.push(`- **Status**: ${a.status}`);const g=a.headers??{},b=Object.entries(g);if(b.length>0){l.push("- **Headers**:");for(const[u,h]of b)l.push(` - \`${u}: ${h}\``)}a.body!==void 0&&a.body!==null?(l.push("- **Body**:"),l.push("```json"),l.push(en(a.body)),l.push("```")):l.push("- **Body**: (empty)"),l.push("")}else if(o){if(l.push(`## Currently viewing: seed table **${o.label}**`),l.push(`- **dataKey**: \`${o.dataKey}\``),o.category&&l.push(`- **Category**: ${o.category}`),o.description&&l.push(`- **Description**: ${o.description}`),o.schemaFields&&o.schemaFields.length>0){l.push("- **Schema**:");for(const f of o.schemaFields){const g=f.isId?" (PK)":"";l.push(` - \`${f.name}\`: ${f.type}${g}`)}}c&&c.length>0?(l.push(`- **Rows** (${c.length}):`),l.push("```json"),l.push(en(c)),l.push("```")):l.push("- **Rows**: (none yet)"),l.push("")}return l.push("## Your task"),l.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."),l.push(""),l.push("Typical edits:"),l.push('- Tweak an HTTP mock body, status, or headers → update `mocks.http["METHOD /path"]` in the scenario JSON'),l.push("- Add or remove seed rows → update the `seed` section"),l.push("- Adjust `localStorage` values → update the `localStorage` section"),l.push(""),l.push("To save changes:"),l.push("1. Write the updated scenario JSON to `.codeyam/tmp/scenario.json`"),l.push("2. Run: `codeyam-editor editor register @.codeyam/tmp/scenario.json`"),l.push("3. The editor will reload automatically and the panel will reflect the new data."),l.join(`
|
|
21
|
-
`)}const St=new Set;let He=null;const eo=150;function ic(e){return St.add(e),()=>{St.delete(e)}}function _e(){He&&clearTimeout(He),He=setTimeout(()=>{He=null;for(const e of St)e()},eo)}const kt=new Set;function cc(e){for(const t of kt)t(e)}function to(e){return kt.add(e),()=>{kt.delete(e)}}function no({onSelect:e,onFocus:t}){i.useEffect(()=>to(({routeKey:n,jsonPath:r})=>{e(n),t(r)}),[e,t])}async function Ge(e){try{const t=await e.json();if(t.error)return t.error}catch{}return`Request failed (${e.status})`}async function ro(e,t=null){const n=t!=null?`?since_ms=${encodeURIComponent(t)}`:"",a=await(await fetch(`/api/mock-panel/${encodeURIComponent(e)}${n}`)).json();if("error"in a)throw new Error(a.error);return a}async function tn(e,t){const n=`/api/scenarios/${encodeURIComponent(e)}/mocks/${encodeURIComponent(t.routeKey)}`,r=await fetch(n,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:t.status,body:t.body,headers:t.headers})});if(!r.ok)throw new Error(await Ge(r))}async function so(e,t){const n=`/api/scenarios/${encodeURIComponent(e)}/mocks/${encodeURIComponent(t)}`,r=await fetch(n,{method:"DELETE"});if(!r.ok)throw new Error(await Ge(r))}async function ao(e,t){const n=`/api/scenarios/${encodeURIComponent(e)}/mocks/${encodeURIComponent(t)}/passthrough`,r=await fetch(n,{method:"POST"});if(!r.ok)throw new Error(await Ge(r))}function he(e){return e.kind==="shared"?`shared:${e.slug}`:e.kind}async function oo(e){const t=await fetch("/api/mocks/save-scoped",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),n=await t.json();if(!t.ok||"success"in n&&n.success===!1)throw new Error("error"in n?n.error:`Save failed (${t.status})`);return n}async function io(e,t,n){const r=new URLSearchParams({scenarioSlug:e,routeKey:t,scope:he(n)}),a=await fetch(`/api/mocks/save-scope-impact?${r.toString()}`);if(!a.ok)throw new Error(await Ge(a));return(await a.json()).impactedScenarios??[]}function co(){const[e,t]=i.useState(null),[n,r]=i.useState(null),a=i.useRef(null);return i.useEffect(()=>Xr(c=>{if(!c.ok){r(c.error);return}const l=c.data,d=JSON.stringify(l);if(d===a.current){r(null);return}a.current=d,t(l),r(null)}),[]),{status:e,error:n,restart:async()=>{try{const c=await fetch("/api/editor-dev-server",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"restart"})});if(!c.ok)throw new Error(`Failed to restart dev server: ${c.statusText}`);qr()}catch(c){r(c instanceof Error?c.message:String(c))}}}}function lo(e){const[t,n]=i.useState([]),[r,a]=i.useState(null),[o,c]=i.useState(!1),[l,d]=i.useState(null),{events:f}=Ur(),{status:g}=co(),b=(g==null?void 0:g.lastIframeLoadedAtMs)??null,u=i.useCallback(async()=>{if(!e){n([]),a(null);return}c(!0),d(null);try{const p=await ro(e,b);n(p.entries),a(p.defaultSlug)}catch(p){d(p instanceof Error?p.message:"Failed to load mocks")}finally{c(!1)}},[e,b]);i.useEffect(()=>{u()},[u]),i.useEffect(()=>{const p=f[f.length-1];!p||p.type!=="http_request"||u()},[f,u]);const h=i.useCallback(async p=>{e&&(await tn(e,p),await u())},[e,u]),m=i.useCallback(async p=>{e&&(p.scope.kind==="scenario"?await tn(e,{routeKey:p.routeKey,status:p.status,body:p.body,headers:p.headers}):await oo({scenarioSlug:e,routeKey:p.routeKey,scope:p.scope,status:p.status,body:p.body,headers:p.headers}),await u())},[e,u]),x=i.useCallback(async p=>{e&&(await so(e,p),await u())},[e,u]),y=i.useCallback(async p=>{e&&(await ao(e,p),await u())},[e,u]);return{entries:t,defaultSlug:r,loading:o,error:l,refresh:u,upsert:h,upsertScoped:m,remove:x,setPassthrough:y}}function uo(e){const t={};for(const[n,r]of Object.entries(e))if(typeof r=="string")try{const a=JSON.parse(r);Array.isArray(a)?t[n]=a:typeof a=="object"&&a!==null&&(t[n]=[a])}catch{}else Array.isArray(r)&&(t[n]=r);return t}function fo(e,t){return e.length===0||t.length===0?!1:e.filter(r=>t.includes(r)).length>=Math.min(e.length,t.length)*.5}function po(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 ho(e,t){return e.length>0?Object.keys(e[0]):t?t.map(n=>n.name):[]}function mo(e,t,n){const r=new Map((n||[]).map(o=>[o.name,o.type])),a={};for(const o of e)a[o]=r.get(o)||(t.length>0?po(t[0][o]):"text");return a}function bo(e,t){var n;return((n=t==null?void 0:t.find(r=>r.isId))==null?void 0:n.name)||e.find(r=>r==="id")||null}function go(e,t){const{_metadata:n,...r}=t,a=r.localStorage&&typeof r.localStorage=="object"&&!Array.isArray(r.localStorage)?uo(r.localStorage):{},o={};if(r.seed&&typeof r.seed=="object"&&!Array.isArray(r.seed))for(const[u,h]of Object.entries(r.seed))Array.isArray(h)&&(o[u]=h);const c={},l=[],d=new Set,f=new Set,g=new Set;for(const u of e){const h=u.name.charAt(0).toLowerCase()+u.name.slice(1),m=u.fields.map(p=>p.name);let x=null,y=[];for(const p of[u.name,h,`${h}s`])if(p in r&&Array.isArray(r[p])){x=p,y=r[p],f.add(p);break}if(!x){for(const p of[u.name,h,`${h}s`])if(p in o){x=p,y=o[p],g.add(p),p in a&&d.add(p);break}}if(!x){for(const p of[u.name,h,`${h}s`])if(p in a){x=h,y=a[p],d.add(p);break}}if(!x){for(const[p,_]of Object.entries(a))if(!d.has(p)&&_.length>0&&fo(m,Object.keys(_[0]))){x=h,y=_,d.add(p);break}}x||(x=h),c[x]=y,l.push({label:u.name,dataKey:x,category:u.category,description:u.description,schemaFields:u.fields.map(p=>({name:p.name,type:p.type,isId:p.isId??!1}))})}const b=new Set(["name","id","url","dimensions","componentName","scenarioType","pageFilePath","routeName","description","props","env"]);for(const[u,h]of Object.entries(r))u==="_metadata"||u==="localStorage"||u==="seed"||u==="type"||u==="mocks"||b.has(u)||f.has(u)||xo(h)&&(c[u]=h,l.push({label:u,dataKey:u}));for(const[u,h]of Object.entries(o))g.has(u)||(c[u]=h,l.push({label:u,dataKey:u}));for(const[u,h]of Object.entries(a))d.has(u)||(c[u]=h,l.push({label:u,dataKey:u}));return{data:c,tabs:l}}function nn(e){return e==="null"?null:e==="true"?!0:e==="false"?!1:e===""?"":isNaN(Number(e))?e:Number(e)}function xo(e){return Array.isArray(e)&&e.length>0&&typeof e[0]=="object"&&e[0]!==null}function yo(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 vo(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 wo(e,t){const n=new Set;for(const r of t){const a=e[r.dataKey];Array.isArray(a)&&a.length>0&&n.add(r.dataKey)}return n}function _o(e){if(typeof e=="object"&&e!==null&&"shares"in e){const t=e.shares;if(Array.isArray(t))return t.filter(n=>typeof n=="string")}return[]}function jo(e){const[t,n]=i.useState({data:null,tableTabs:[],scenarioOwnedDataKeys:new Set,shares:[],props:null,browserState:null,loading:!0,error:null});return i.useEffect(()=>{n(r=>({...r,loading:!0,error:null})),Promise.all([fetch("/api/data-structure").then(r=>r.json()).catch(()=>[]),fetch(`/api/scenarios/${encodeURIComponent(e)}`).then(r=>{if(!r.ok)throw new Error(`HTTP ${r.status}`);return r.json()})]).then(([r,a])=>{const o=go(Array.isArray(r)?r:[],a);n({data:o.data,tableTabs:o.tabs,scenarioOwnedDataKeys:wo(o.data,o.tabs),shares:_o(a),props:yo(a),browserState:vo(a),loading:!1,error:null})}).catch(r=>n({data:null,tableTabs:[],scenarioOwnedDataKeys:new Set,shares:[],props:null,browserState:null,loading:!1,error:r instanceof Error?r.message:"Failed to load"}))},[e]),t}function Mt(e,t=""){return`/api/scenarios/${encodeURIComponent(e)}/draft${t}`}async function So(e){const t=await fetch(Mt(e,"/status"));if(!t.ok)return{isDirty:!1,diffSummary:null};const n=await t.json();return{isDirty:!!n.isDirty,diffSummary:n.diffSummary??null}}async function ko(e){const t=await fetch(Mt(e,"/commit"),{method:"POST"});if(!t.ok)throw new Error(`Save failed (${t.status})`)}async function Co(e){const t=await fetch(Mt(e),{method:"DELETE"});if(!t.ok)throw new Error(`Cancel failed (${t.status})`)}function No({slug:e,onPreviewReload:t}){const[n,r]=i.useState(!1),[a,o]=i.useState(null),[c,l]=i.useState(!1),[d,f]=i.useState(!1),[g,b]=i.useState(null),u=i.useRef(null),h=i.useCallback(async()=>{if(!e){r(!1),o(null);return}try{const _=await So(e);r(_.isDirty),o(_.diffSummary)}catch{}},[e]);i.useEffect(()=>{h()},[h]),i.useEffect(()=>{if(!n)return;const _=v=>{v.preventDefault(),v.returnValue=""};return window.addEventListener("beforeunload",_),()=>window.removeEventListener("beforeunload",_)},[n]);const m=i.useCallback(()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{h()},100)},[h]),x=i.useCallback(async()=>{if(e){l(!0),b(null);try{await ko(e),r(!1),o(null),t&&t()}catch(_){b(_ instanceof Error?_.message:"Save failed")}finally{l(!1)}}},[e,t]),y=i.useCallback(async()=>{if(e){f(!0),b(null);try{await Co(e),r(!1),o(null),t&&t()}catch(_){b(_ instanceof Error?_.message:"Cancel failed")}finally{f(!1)}}},[e,t]),p=i.useCallback(_=>n?window.confirm(_):!0,[n]);return{isDirty:n,saving:c,cancelling:d,error:g,diffSummary:a,save:x,cancel:y,markDirty:m,confirmIfDirty:p}}const To={scenario:"Scenario",shared:"Shared",default:"Defaults","catalog-only":"Observed only",passthrough:"Passthrough"},Eo={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 sr(e){return To[e]??e}function Oo(e){return Eo[e]??null}function me(e){return`${e.method} ${e.pathPattern}`}const Ao={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 It({source:e}){const t=Oo(e);return s.jsx("span",{className:`px-1.5 py-0.5 rounded border ${Ao[e]}`,title:t??`source: ${e}`,children:sr(e)})}const lc=Object.freeze(Object.defineProperty({__proto__:null,MockSourceBadge:It},Symbol.toStringTag,{value:"Module"}));function ar({label:e,scenarioCount:t,inheritedCount:n,expanded:r,onToggle:a}){const o=n===0;return s.jsxs("h3",{className:"px-3 pb-1 text-[10px] font-semibold uppercase tracking-wider text-[var(--text-dim)]",children:[s.jsx("div",{className:"mb-0.5",children:e}),s.jsxs("div",{className:"flex items-center gap-1 normal-case tracking-normal font-normal",children:[s.jsxs("span",{children:[t," scenario-specific"]}),s.jsx("span",{"aria-hidden":!0,children:"·"}),s.jsxs("button",{type:"button",onClick:a,disabled:o,"aria-expanded":r,className:`inline-flex items-center gap-0.5 ${o?"cursor-default text-[var(--text-dim)]":"cursor-pointer hover:text-[var(--text-primary)]"}`,children:[s.jsx("span",{"aria-hidden":!0,className:"inline-block w-2 text-[9px]",children:o?"":r?"▾":"▸"}),s.jsxs("span",{children:[n," inherited from default"]})]})]})]})}const uc=Object.freeze(Object.defineProperty({__proto__:null,SidebarGroupOverrideHeader:ar},Symbol.toStringTag,{value:"Module"}));function or({children:e}){return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"mx-3 my-1 border-t border-[var(--border-subtle)]"}),s.jsx("div",{className:"px-3 pb-1 text-[9px] uppercase tracking-wider text-[var(--text-dim)]",children:"Inherited from default"}),e]})}const dc=Object.freeze(Object.defineProperty({__proto__:null,SidebarInheritedSection:or},Symbol.toStringTag,{value:"Module"}));function ir({slug:e}){return s.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 fc=Object.freeze(Object.defineProperty({__proto__:null,MockSharedSlugBadge:ir},Symbol.toStringTag,{value:"Module"})),Mo={GET:"text-emerald-400",POST:"text-[#D7FF63]",PUT:"text-amber-400",PATCH:"text-purple-400",DELETE:"text-red-400"};function cr({entry:e,routeKey:t,active:n,onSelect:r}){const a=Mo[e.method]??"text-[var(--text-muted)]";return s.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 ${n?"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:[s.jsx("span",{className:`font-mono text-[9px] font-semibold ${a}`,children:e.method}),s.jsx("span",{className:"truncate flex-1 font-mono",children:e.pathPattern}),e.source==="shared"&&e.sharedSlug&&s.jsx(ir,{slug:e.sharedSlug})]})}const pc=Object.freeze(Object.defineProperty({__proto__:null,SidebarMockEntryRow:cr},Symbol.toStringTag,{value:"Module"})),Io=["scenario","shared","default","catalog-only","passthrough"];function lr({seedTabs:e,mockEntries:t,selection:n,onSelect:r,overrides:a}){const o=new Map;for(const c of t){const l=o.get(c.source)??[];l.push(c),o.set(c.source,l)}return s.jsxs("nav",{className:"w-56 shrink-0 border-r border-[var(--border-subtle)] bg-[var(--bg-deep)] overflow-y-auto",children:[s.jsxs(Ve,{label:"Browser Environment",count:4,emptyHint:"",children:[s.jsx(Me,{label:"Cookies",active:(n==null?void 0:n.kind)==="browser"&&n.tab==="cookies",onSelect:()=>r({kind:"browser",tab:"cookies"})}),s.jsx(Me,{label:"Local Storage",active:(n==null?void 0:n.kind)==="browser"&&n.tab==="localStorage",onSelect:()=>r({kind:"browser",tab:"localStorage"})}),s.jsx(Me,{label:"Session Storage",active:(n==null?void 0:n.kind)==="browser"&&n.tab==="sessionStorage",onSelect:()=>r({kind:"browser",tab:"sessionStorage"})}),s.jsx(Me,{label:"Request Headers",active:(n==null?void 0:n.kind)==="browser"&&n.tab==="headers",onSelect:()=>r({kind:"browser",tab:"headers"})})]}),s.jsx(Ve,{label:"Seed & Local",count:e.length,emptyHint:"No seed or localStorage data",override:a?{scenarioCount:a.scenarioSeedCount,inheritedCount:a.inheritedSeedCount,renderInherited:()=>rn({tabs:a.inheritedSeedTabs,selection:n,onSelect:r})}:void 0,children:rn({tabs:e,selection:n,onSelect:r})}),s.jsx(Ve,{label:"Mock APIs",count:t.length,emptyHint:"No HTTP mocks registered",override:a?{scenarioCount:a.scenarioMockCount,inheritedCount:a.inheritedMockCount,renderInherited:()=>sn({entries:a.inheritedMockEntries,selection:n,onSelect:r})}:void 0,children:sn({entries:t,grouped:o,selection:n,onSelect:r})})]})}function rn({tabs:e,selection:t,onSelect:n}){return e.map(r=>{const a=(t==null?void 0:t.kind)==="seed"&&t.dataKey===r.dataKey;return s.jsxs("button",{onClick:()=>n({kind:"seed",dataKey:r.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 ${a?"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:[s.jsx("span",{className:"truncate flex-1",children:r.label}),r.category&&s.jsx("span",{className:"text-[9px] uppercase tracking-wide text-[var(--text-dim)]",children:r.category==="mock-api"?"API":r.category})]},r.dataKey)})}function Me({label:e,active:t,onSelect:n}){return s.jsxs("button",{onClick:n,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:[s.jsx("span",{className:"truncate flex-1",children:e}),s.jsx("span",{className:"text-[9px] uppercase tracking-wide text-[var(--text-dim)]",children:"ENV"})]})}function sn({entries:e,grouped:t,selection:n,onSelect:r}){const a=t??Po(e);return Io.flatMap(o=>{const c=a.get(o)??[];return c.length===0?[]:[s.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:[sr(o),s.jsx(It,{source:o})]},`hdr-${o}`),...c.map(l=>{const d=me(l),f=(n==null?void 0:n.kind)==="mock"&&n.routeKey===d;return s.jsx(cr,{entry:l,routeKey:d,active:f,onSelect:()=>r({kind:"mock",routeKey:d})},d)})]})}function Po(e){const t=new Map;for(const n of e){const r=t.get(n.source)??[];r.push(n),t.set(n.source,r)}return t}function Ve({label:e,count:t,emptyHint:n,children:r,override:a}){const[o,c]=i.useState(!1);if(a){const{scenarioCount:l,inheritedCount:d,renderInherited:f}=a,g=l+(o?d:0);return s.jsxs("section",{className:"py-2",children:[s.jsx(ar,{label:e,scenarioCount:l,inheritedCount:d,expanded:o,onToggle:()=>c(b=>!b)}),g===0?s.jsx("p",{className:"px-3 py-1 text-[10px] italic text-[var(--text-dim)]",children:n}):s.jsxs("div",{children:[r,o&&d>0&&s.jsx(or,{children:f()})]})]})}return s.jsxs("section",{className:"py-2",children:[s.jsxs("h3",{className:"px-3 pb-1 text-[10px] font-semibold uppercase tracking-wider text-[var(--text-dim)] flex items-center justify-between",children:[s.jsx("span",{children:e}),s.jsx("span",{children:t})]}),t===0?s.jsx("p",{className:"px-3 py-1 text-[10px] italic text-[var(--text-dim)]",children:n}):s.jsx("div",{children:r})]})}const hc=Object.freeze(Object.defineProperty({__proto__:null,BrowserStateButton:Me,ScenarioDataPanelSidebar:lr,SidebarGroup:Ve,routeKeyFor:me},Symbol.toStringTag,{value:"Module"}));function Ro({seedTabs:e,mockEntries:t,initialSection:n,selection:r,setSelection:a}){i.useEffect(()=>{if(r)return;const o=n==="mocks",c=n==="seed";if(o&&t.length>0){a({kind:"mock",routeKey:me(t[0])});return}if(c&&e.length>0){a({kind:"seed",dataKey:e[0].dataKey});return}e.length>0?a({kind:"seed",dataKey:e[0].dataKey}):t.length>0&&a({kind:"mock",routeKey:me(t[0])})},[n,t,e,r,a])}function ur(){return s.jsx("div",{className:"flex h-full items-center justify-center p-6",children:s.jsxs("div",{className:"max-w-xs text-center space-y-2",children:[s.jsx("p",{className:"text-sm text-[var(--text-muted)]",children:"No scenario data yet."}),s.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."})]})})}const mc=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelEmptyState:ur},Symbol.toStringTag,{value:"Module"}));function dr({variant:e,onClose:t}){return e!=="slideOver"?null:s.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"})}const bc=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelCloseButton:dr},Symbol.toStringTag,{value:"Module"}));function fr({variant:e,providerLabel:t,chatOpen:n,onToggleChat:r}){const a=e==="inline",o=a?"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=n?"border-[var(--accent-active)] bg-[var(--accent-active)]/15 text-[var(--accent-active)]":a?"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 s.jsxs("button",{type:"button",onClick:r,className:`${o} ${c}`,title:`Open a chat with ${t} seeded with this scenario's context`,children:[s.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.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 gc=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelEditChatButton:fr},Symbol.toStringTag,{value:"Module"})),Ct=new Set,Nt=new Set;let pr={isActive:!1,previewSlug:null};function Do(){for(const e of Ct)e()}function xc(e){return Ct.add(e),()=>{Ct.delete(e)}}function yc(e){pr=e;for(const t of Nt)t(e)}function Lo(e){return Nt.add(e),()=>{Nt.delete(e)}}function an(){return pr}function $o(){const[e,t]=i.useState(()=>an());return i.useEffect(()=>(t(an()),Lo(t)),[]),e}function hr({panelSlug:e,scenarioState:t}){const n=$o(),{isActive:r,previewSlug:a}=t??n;return a!==e?null:s.jsxs("button",{type:"button","aria-pressed":r,onClick:()=>Do(),title:r?"Exit inspect data source":"Inspect data source — click a value in the live preview to see its mock",className:r?"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:[s.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("circle",{cx:"11",cy:"11",r:"8"}),s.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),r?"Inspecting…":"Inspect data"]})}const vc=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelInspectButton:hr},Symbol.toStringTag,{value:"Module"}));function mr({variant:e,slug:t}){const n=()=>window.open(Vr(t),"_blank");return e==="slideOver"?s.jsx("button",{type:"button",onClick:n,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:s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),s.jsx("polyline",{points:"15 3 21 3 21 9"}),s.jsx("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]})}):e==="inline"?s.jsxs("button",{type:"button",onClick:n,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:[s.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),s.jsx("polyline",{points:"15 3 21 3 21 9"}),s.jsx("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]}),"Open in new tab"]}):null}const wc=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelOpenInNewButton:mr},Symbol.toStringTag,{value:"Module"}));function br(e){if(!e)return"Unsaved changes";const t=[];e.mocks.length>0&&t.push(`${e.mocks.length} mock${e.mocks.length===1?"":"s"}`);const n=e.seed.length;return n>0&&t.push(`${n} seed ${n===1?"table":"tables"}`),t.length>0?`Unsaved changes (${t.join(", ")})`:"Unsaved changes"}function gr({diff:e,saving:t,cancelling:n,error:r,onSave:a,onCancel:o}){return s.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:[s.jsx("span",{className:"text-xs text-amber-300 font-medium",children:br(e)}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&s.jsx(Re,{text:r,className:"text-xs text-red-400"}),s.jsx("button",{type:"button",onClick:o,disabled:n||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:n?"Discarding…":"Cancel"}),s.jsx("button",{type:"button",onClick:a,disabled:n||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"})]})]})}const _c=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDraftBar:gr,summarizeDraftDiff:br},Symbol.toStringTag,{value:"Module"}));function xr({title:e,slug:t,provider:n,chatOpen:r,onToggleChat:a,variant:o,onClose:c,draftDirty:l,draftDiff:d,draftSaving:f,draftCancelling:g,draftError:b,onSave:u,onCancel:h}){const m=ke(n),x=!!l&&!!u&&!!h;return s.jsxs("header",{className:"flex flex-col gap-2 border-b border-[var(--border-subtle)] bg-[var(--bg-deep)] px-4 py-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("div",{className:"min-w-0",children:s.jsxs("h2",{className:"text-sm font-medium text-[var(--text-primary)] truncate",children:["Scenario data: ",e]})}),s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx(fr,{variant:o,providerLabel:m,chatOpen:r,onToggleChat:a}),s.jsx(hr,{panelSlug:t}),s.jsx(mr,{variant:o,slug:t}),c&&s.jsx(dr,{variant:o,onClose:c})]})]}),x&&u&&h&&s.jsx(gr,{diff:d??null,saving:f??!1,cancelling:g??!1,error:b??null,onSave:u,onCancel:h})]})}const jc=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelHeader:xr},Symbol.toStringTag,{value:"Module"}));function Fo(e,t){const[n,r]=i.useState(e.status??200),[a,o]=i.useState(e.body??null),[c,l]=i.useState(()=>Object.entries(e.headers??{}).map(([b,u])=>({name:b,value:u})));i.useEffect(()=>{r(e.status??200),o(e.body??null),l(Object.entries(e.headers??{}).map(([b,u])=>({name:b,value:u})))},[t,e.status,e.body,e.headers]);const d=i.useMemo(()=>e.headers??{},[e.headers]),f=i.useMemo(()=>{if((e.status??200)!==n||JSON.stringify(e.body??null)!==JSON.stringify(a))return!0;const b={};for(const x of c)x.name.trim()&&(b[x.name.trim()]=x.value);const u=d,h=Object.keys(u),m=Object.keys(b);if(h.length!==m.length)return!0;for(const x of m)if(u[x]!==b[x])return!0;return!1},[n,a,c,e.status,e.body,d]);return{status:n,setStatus:r,body:a,setBody:o,headers:c,setHeaders:l,isDirty:f,buildPayload:()=>{const b={};for(const u of c)u.name.trim()&&(b[u.name.trim()]=u.value);return{status:n,body:a,headers:b}}}}function yr({body:e,onBodyChange:t}){const{copied:n,copy:r}=Hr();async function a(){try{const c=await navigator.clipboard.readText(),l=JSON.parse(c);t(l)}catch{}}function o(){r(JSON.stringify(e,null,2))}return s.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[s.jsx("button",{type:"button",onClick:()=>void a(),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"}),s.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:n?"Copied":"Copy"})]})}const Sc=Object.freeze(Object.defineProperty({__proto__:null,JsonBodyActions:yr},Symbol.toStringTag,{value:"Module"}));function Le(e){return JSON.stringify(e)}function vr(e,t){return e?e instanceof Set?e.has(t):e.includes(t):!1}function Bo(e){const t=new Set;function n(r,a){if(r!==null&&typeof r=="object")if(t.add(Le(a)),Array.isArray(r))r.forEach((o,c)=>n(o,[...a,c]));else for(const[o,c]of Object.entries(r))n(c,[...a,o])}return n(e,[]),t}function zo(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 Ko(e){return e===null?"null":typeof e=="string"?`"${e}"`:String(e)}function Ho(e){return e===null?"null":typeof e=="string"?e:String(e)}function Uo(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 Qe(e){return JSON.parse(JSON.stringify(e))}function Wo(e,t,n){if(t.length===0)return n;const r=Qe(e);let a=r;for(let o=0;o<t.length-1;o++)a=a[t[o]];return a[t[t.length-1]]=n,r}function Pt(e,t){if(t.length===0)return e;const n=Qe(e);let r=n;for(let o=0;o<t.length-1;o++)r=r[t[o]];const a=t[t.length-1];return Array.isArray(r)?r.splice(a,1):delete r[a],n}function Yo(e,t){const n=Qe(e);let r=n;for(const a of t)r=r[a];return Array.isArray(r)&&r.push(null),n}function Vo(e,t,n){const r=Qe(e);let a=r;for(const o of t)a=a[o];return a&&typeof a=="object"&&!Array.isArray(a)&&(a[n]=""),r}function Jo(e){if(typeof e!="string"||e.length===0||e!=="$"&&!e.startsWith("$.")&&!e.startsWith("$["))return null;const t=[];let n=e[0]==="$"?1:0;for(;n<e.length;){const r=e[n];if(r==="."){n+=1;const a=n;for(;n<e.length&&e[n]!=="."&&e[n]!=="[";)n+=1;const o=e.slice(a,n);if(o.length===0)return null;t.push(o)}else if(r==="["){const a=e.indexOf("]",n);if(a===-1)return null;const o=e.slice(n+1,a);if(o.length===0)return null;const c=Number(o);if(!Number.isInteger(c)||c<0)return null;t.push(c),n=a+1}else return null}return t}function Xo(e,t){i.useEffect(()=>{if(!e)return;const n=Jo(e);n&&t(r=>{const a=new Set(r);for(let o=0;o<n.length;o++)a.add(Le(n.slice(0,o)));return a})},[e,t])}function Ze({collapsible:e,isOpen:t,onToggle:n,parentKey:r,readOnly:a,onRemove:o,children:c}){return s.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?s.jsx("button",{type:"button",onClick:n,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:s.jsx("span",{className:"text-[10px]",children:t?"▾":"▸"})}):s.jsx("span",{className:"w-4"}),r!==null&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-cyan-300",children:typeof r=="number"?`[${r}]`:r}),s.jsx("span",{className:"text-[var(--text-dim)]",children:":"})]}),s.jsx("div",{className:"flex-1 min-w-0 flex items-center gap-1",children:c}),!a&&o&&s.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:"×"})]})}const kc=Object.freeze(Object.defineProperty({__proto__:null,JsonTreeNodeLine:Ze},Symbol.toStringTag,{value:"Module"}));function wr(e){const{value:t,path:n,parentKey:r,expanded:a,onToggle:o,readOnly:c}=e,l=Le(n),d=vr(a,l),f=t.length>0;return s.jsxs("div",{children:[s.jsxs(Ze,{collapsible:f,isOpen:d,onToggle:()=>o(l),parentKey:r,readOnly:c,onRemove:n.length>0?()=>e.onValueChange(Pt(e.rootValue,n)):null,children:[s.jsx("span",{className:"text-[var(--text-dim)]",children:"["}),!d&&s.jsxs(s.Fragment,{children:[f&&s.jsxs("span",{className:"text-[var(--text-dim)] italic",children:[" ","…",t.length," item",t.length===1?"":"s"," "]}),s.jsx("span",{className:"text-[var(--text-dim)]",children:"]"})]})]}),d&&s.jsxs("div",{className:"ml-4 border-l border-[var(--border-subtle)] pl-2",children:[t.map((g,b)=>i.createElement(et,{...e,key:b,value:g,path:[...n,b],parentKey:b,isLast:b===t.length-1})),!c&&s.jsx("button",{type:"button",onClick:()=>e.onValueChange(Yo(e.rootValue,n)),className:"text-[10px] text-[var(--accent-blue)] hover:underline bg-transparent border-none cursor-pointer py-0.5",children:"+ Add item"})]}),d&&s.jsx("div",{className:"text-[var(--text-dim)]",children:"]"})]})}const Cc=Object.freeze(Object.defineProperty({__proto__:null,JsonTreeArrayNode:wr},Symbol.toStringTag,{value:"Module"}));function _r({onSave:e,onCancel:t}){const[n,r]=i.useState("");return s.jsxs("div",{className:"flex items-center gap-1 py-0.5",children:[s.jsx("span",{className:"text-[var(--text-dim)] text-[10px]",children:"+ key:"}),s.jsx("input",{autoFocus:!0,value:n,onChange:a=>r(a.target.value),onBlur:()=>e(n),onKeyDown:a=>{a.key==="Enter"?(a.preventDefault(),e(n)):a.key==="Escape"&&(a.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]"})]})}const Nc=Object.freeze(Object.defineProperty({__proto__:null,JsonTreeAddKeyInput:_r},Symbol.toStringTag,{value:"Module"}));function jr(e){const{value:t,path:n,parentKey:r,expanded:a,onToggle:o,readOnly:c,addingKeyAtPath:l,onStartAddKey:d,onStopAddKey:f}=e,g=Le(n),b=vr(a,g),u=Object.entries(t),h=u.length>0,m=l===g;return s.jsxs("div",{children:[s.jsxs(Ze,{collapsible:h,isOpen:b,onToggle:()=>o(g),parentKey:r,readOnly:c,onRemove:n.length>0?()=>e.onValueChange(Pt(e.rootValue,n)):null,children:[s.jsx("span",{className:"text-[var(--text-dim)]",children:"{"}),!b&&s.jsxs(s.Fragment,{children:[h&&s.jsxs("span",{className:"text-[var(--text-dim)] italic",children:[" ","…",u.length," key",u.length===1?"":"s"," "]}),s.jsx("span",{className:"text-[var(--text-dim)]",children:"}"})]})]}),b&&s.jsxs("div",{className:"ml-4 border-l border-[var(--border-subtle)] pl-2",children:[u.map(([x,y],p)=>i.createElement(et,{...e,key:x,value:y,path:[...n,x],parentKey:x,isLast:p===u.length-1})),!c&&!m&&s.jsx("button",{type:"button",onClick:()=>d(g),className:"text-[10px] text-[var(--accent-blue)] hover:underline bg-transparent border-none cursor-pointer py-0.5",children:"+ Add key"}),!c&&m&&s.jsx(_r,{onSave:x=>{x.trim()&&e.onValueChange(Vo(e.rootValue,n,x.trim())),f()},onCancel:f})]}),b&&s.jsx("div",{className:"text-[var(--text-dim)]",children:"}"})]})}const Tc=Object.freeze(Object.defineProperty({__proto__:null,JsonTreeObjectNode:jr},Symbol.toStringTag,{value:"Module"}));function Sr({initial:e,onSave:t,onCancel:n}){const[r,a]=i.useState(e);return s.jsx("input",{autoFocus:!0,value:r,onChange:o=>a(o.target.value),onBlur:()=>t(r),onKeyDown:o=>{o.key==="Enter"?(o.preventDefault(),t(r)):o.key==="Escape"&&(o.preventDefault(),n())},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)]"})}const Ec=Object.freeze(Object.defineProperty({__proto__:null,JsonTreePrimitiveEditor:Sr},Symbol.toStringTag,{value:"Module"}));function kr(e){const{value:t,path:n,parentKey:r,readOnly:a,editingPath:o,onStartEdit:c,onStopEdit:l}=e,d=Le(n),f=o===d;return s.jsx(Ze,{collapsible:!1,isOpen:!1,parentKey:r,readOnly:a,onToggle:()=>{},onRemove:n.length>0?()=>e.onValueChange(Pt(e.rootValue,n)):null,children:f?s.jsx(Sr,{initial:Ho(t),onSave:g=>{const b=Uo(g);e.onValueChange(Wo(e.rootValue,n,b)),l()},onCancel:l}):s.jsx("button",{type:"button",onClick:a?void 0:()=>c(d),disabled:a,className:`${a?"":"hover:bg-[var(--bg-card)] cursor-pointer"} bg-transparent border-none px-1 py-0 rounded ${zo(t)} text-left font-mono`,title:a?void 0:"Click to edit",children:Ko(t)})})}const Oc=Object.freeze(Object.defineProperty({__proto__:null,JsonTreePrimitiveNode:kr},Symbol.toStringTag,{value:"Module"}));function et(e){const{value:t}=e;return Array.isArray(t)?s.jsx(wr,{...e,value:t}):t!==null&&typeof t=="object"?s.jsx(jr,{...e,value:t}):s.jsx(kr,{...e})}const Ac=Object.freeze(Object.defineProperty({__proto__:null,JsonTreeNode:et},Symbol.toStringTag,{value:"Module"}));function tt({value:e,onChange:t,readOnly:n=!1,focusJsonPath:r}){const[a,o]=i.useState(()=>Bo(e)),[c,l]=i.useState(null),[d,f]=i.useState(null);Xo(r,o);function g(b){o(u=>{const h=new Set(u);return h.has(b)?h.delete(b):h.add(b),h})}return s.jsx("div",{className:"flex flex-col h-full min-h-0",children:s.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:s.jsx(et,{value:e,path:[],parentKey:null,isLast:!0,readOnly:n,expanded:a,editingPath:c,addingKeyAtPath:d,onToggle:g,onStartEdit:l,onStopEdit:()=>l(null),onStartAddKey:f,onStopAddKey:()=>f(null),onValueChange:t,rootValue:e})})})}const Mc=Object.freeze(Object.defineProperty({__proto__:null,JsonTreeEditor:tt},Symbol.toStringTag,{value:"Module"}));function Cr({headers:e,onChange:t}){function n(o,c){t(e.map((l,d)=>d===o?{...l,...c}:l))}function r(){t([...e,{name:"",value:""}])}function a(o){t(e.filter((c,l)=>l!==o))}return s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("label",{className:"text-xs text-[var(--text-muted)]",children:"Headers"}),s.jsx("button",{type:"button",onClick:r,className:"text-xs text-[var(--accent-blue)] hover:underline bg-transparent border-none cursor-pointer",children:"+ Add"})]}),e.length===0&&s.jsx("p",{className:"text-xs text-[var(--text-dim)] italic",children:"No headers"}),e.map((o,c)=>s.jsxs("div",{className:"flex gap-2",children:[s.jsx("input",{value:o.name,onChange:l=>n(c,{name:l.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"}),s.jsx("input",{value:o.value,onChange:l=>n(c,{value:l.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"}),s.jsx("button",{type:"button",onClick:()=>a(c),className:"px-2 text-xs text-[var(--text-dim)] hover:text-red-400 bg-transparent border-none cursor-pointer",children:"×"})]},c))]})}const Ic=Object.freeze(Object.defineProperty({__proto__:null,MockBodyHeadersEditor:Cr},Symbol.toStringTag,{value:"Module"})),pt=5;function qo(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 n=e.length===1?"scenario":"scenarios",r=e.slice(0,pt).join(", "),a=e.length>pt?`, +${e.length-pt} more`:"";return`Affects ${e.length} ${n}: ${r}${a}`}function Go(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 Qo(e,t){if(e.source==="default"){const n=t.findIndex(r=>r.scope.kind==="default");if(n>=0)return n}if(e.source==="shared"){const n=t.findIndex(r=>r.scope.kind==="shared"&&r.scope.slug===(e.sharedSlug??""));if(n>=0)return n}return 0}function Zo(e,t,n){const[r,a]=i.useState({}),o=n.map(c=>he(c.scope)).join("|");return i.useEffect(()=>{let c=!1;return(async()=>{const d={};for(const f of n)d[he(f.scope)]="loading";a(d);for(const f of n)try{const g=await io(e,t,f.scope);if(c)return;a(b=>({...b,[he(f.scope)]:g}))}catch{if(c)return;a(g=>({...g,[he(f.scope)]:[]}))}})(),()=>{c=!0}},[e,t,o]),r}function Nr({choice:e,selected:t,impactLabel:n,onSelect:r}){return s.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:[s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"radio",name:"save-scope",checked:t,onChange:r}),s.jsx("span",{className:"font-medium text-[var(--text-primary)]",children:e.label})]}),s.jsx("span",{className:"mt-1 pl-6 text-[var(--text-muted)]",children:e.description}),s.jsx("span",{className:"mt-1 pl-6 text-[var(--text-dim)] italic",children:n})]})}const Pc=Object.freeze(Object.defineProperty({__proto__:null,SaveScopeChoiceRow:Nr},Symbol.toStringTag,{value:"Module"}));function Tr({entry:e,scenarioSlug:t,routeKey:n,onCancel:r,onConfirm:a}){const o=Go(e),[c,l]=i.useState(()=>Qo(e,o)),d=Zo(t,n,o),[f,g]=i.useState(!1),[b,u]=i.useState(null),h=async()=>{const m=o[c];if(m){g(!0),u(null);try{await a(m.scope)}catch(x){u(x instanceof Error?x.message:"Save failed")}finally{g(!1)}}};return s.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",onMouseDown:m=>{m.target===m.currentTarget&&r()},children:s.jsxs("div",{className:"w-[28rem] max-w-[90vw] rounded-lg border border-[var(--border-default)] bg-[var(--bg-surface)] p-5 shadow-xl",children:[s.jsx("h2",{id:"save-scope-modal-title",className:"text-sm font-semibold text-[var(--text-primary)]",children:"Where should this save land?"}),s.jsx("p",{className:"mt-1 text-xs text-[var(--text-muted)]",children:n}),s.jsx("div",{className:"mt-4 space-y-2",children:o.map((m,x)=>s.jsx(Nr,{choice:m,selected:c===x,impactLabel:qo(d[he(m.scope)],m.scope),onSelect:()=>l(x)},he(m.scope)))}),b&&s.jsx(Re,{text:b,className:"text-xs text-red-400",rowClassName:"mt-3"}),s.jsxs("div",{className:"mt-5 flex justify-end gap-2",children:[s.jsx("button",{type:"button",onClick:r,disabled:f,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"}),s.jsx("button",{type:"button",onClick:()=>void h(),disabled:f,className:"rounded bg-violet-500 px-3 py-1.5 text-xs font-medium text-white hover:bg-violet-400 disabled:opacity-50",children:f?"Saving…":"Save"})]})]})})}const Rc=Object.freeze(Object.defineProperty({__proto__:null,SaveScopeModal:Tr},Symbol.toStringTag,{value:"Module"}));function Er({entry:e,routeKey:t,scenarioSlug:n,onSave:r,focusJsonPath:a}){const o=Fo(e,t),[c,l]=i.useState(null),[d,f]=i.useState(!1),[g,b]=i.useState(!1);i.useEffect(()=>{l(null),b(!1)},[t]);const u=async m=>{f(!0),l(null);try{const x=o.buildPayload();await r({routeKey:t,...x,scope:m})}catch(x){throw l(x instanceof Error?x.message:"Save failed"),x}finally{f(!1)}},h=async()=>{if(o.isDirty){if(e.source==="scenario"){try{await u({kind:"scenario"})}catch{}return}b(!0)}};return s.jsxs("div",{className:"flex flex-col gap-3 h-full min-h-0",children:[c&&s.jsx(Re,{text:c,className:"text-xs text-red-400"}),s.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[s.jsx("label",{className:"text-xs text-[var(--text-muted)]",children:"Status"}),s.jsx("input",{type:"number",value:o.status,onChange:m=>o.setStatus(Number(m.target.value)),className:"w-20 rounded border border-[var(--border-default)] bg-[var(--bg-surface)] px-2 py-1 text-xs font-mono"}),s.jsx("div",{className:"flex-1"}),s.jsx("button",{type:"button",onClick:()=>void h(),disabled:!o.isDirty||d,className:"rounded bg-violet-500 px-3 py-1 text-xs font-medium text-white hover:bg-violet-400 disabled:opacity-50",children:d?"Saving…":o.isDirty?"Save changes":"Saved"})]}),s.jsx(Cr,{headers:o.headers,onChange:o.setHeaders}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",children:[s.jsxs("div",{className:"flex items-center gap-2 pb-1",children:[s.jsx("label",{className:"text-xs text-[var(--text-muted)]",children:"Body"}),s.jsx(yr,{body:o.body,onBodyChange:o.setBody})]}),s.jsx(tt,{value:o.body,onChange:o.setBody,focusJsonPath:a},t)]}),g&&s.jsx(Tr,{entry:e,scenarioSlug:n,routeKey:t,onCancel:()=>b(!1),onConfirm:async m=>{await u(m),b(!1)}})]})}const Dc=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelMainMockEditable:Er},Symbol.toStringTag,{value:"Module"}));function ei(e,t){if(e==null)return"never";const n=Math.max(0,Math.floor((t-e)/1e3));if(n<60)return`${n}s ago`;const r=Math.floor(n/60);return r<60?`${r}m ago`:`${Math.floor(r/60)}h ago`}const on={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 ti(e){return on[e]??on.GET}function Or({entry:e,scenarioHasDefaultFallback:t,onSave:n,onRemove:r,onPassthrough:a}){const o=`${e.method} ${e.pathPattern}`,c=ti(e.method),l=e.status??e.lastObservedStatus,d=i.useMemo(()=>e.lastObservedMs?ei(e.lastObservedMs,Date.now()):null,[e.lastObservedMs]),f="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 s.jsxs("header",{className:"border-b border-[var(--border-subtle)] bg-[var(--bg-deep)] px-4 py-3 space-y-2 flex-shrink-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:`px-2 py-0.5 rounded border font-mono text-xs ${c}`,children:e.method}),s.jsx("span",{className:"font-mono text-sm text-[var(--text-primary)] break-all",children:e.pathPattern}),s.jsx(It,{source:e.source}),l!==void 0&&s.jsx("span",{className:"px-1.5 py-0.5 rounded border border-[var(--border-default)] text-[var(--text-muted)] font-mono text-xs",children:l}),e.observedCount>0&&s.jsxs("span",{className:"ml-auto text-xs text-[var(--text-dim)]",children:[e.observedCount,"× ",d?`· ${d}`:""]})]}),e.variants.length>1&&s.jsxs("div",{className:"text-[10px] text-[var(--text-dim)] font-mono",children:["variants: ",e.variants.filter(g=>g!==o).join(", ")]}),s.jsxs("div",{className:"flex flex-wrap gap-2 pt-1",children:[e.source==="scenario"&&t&&s.jsx("button",{onClick:()=>void r(o),className:f,title:"Remove this scenario mock and fall back to the default",children:"Revert to default"}),e.source==="scenario"&&s.jsx("button",{onClick:()=>void a(o),className:f,children:"Mark passthrough"}),e.source==="default"&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>void n({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"}),s.jsx("button",{onClick:()=>void a(o),className:f,children:"Mark passthrough"})]}),e.source==="passthrough"&&s.jsx("button",{onClick:()=>void r(o),className:f,children:"Undo passthrough"})]})]})}const Lc=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelMainMockHeader:Or},Symbol.toStringTag,{value:"Module"}));function Ar({entry:e}){const t=Object.entries(e.headers??{}),n=e.body!==void 0&&e.body!==null;return!n&&t.length===0?s.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."}):s.jsxs("div",{className:"space-y-3 h-full min-h-0 flex flex-col",children:[t.length>0&&s.jsxs("section",{className:"space-y-1 flex-shrink-0",children:[s.jsx("h4",{className:"text-xs font-medium uppercase tracking-wide text-[var(--text-dim)]",children:"Headers"}),s.jsx("dl",{className:"text-xs font-mono space-y-0.5",children:t.map(([r,a])=>s.jsxs("div",{className:"flex gap-2",children:[s.jsxs("dt",{className:"text-[var(--text-muted)]",children:[r,":"]}),s.jsx("dd",{className:"text-[var(--text-primary)] break-all",children:a})]},r))})]}),n&&s.jsxs("section",{className:"flex-1 min-h-0 flex flex-col",children:[s.jsx("h4",{className:"text-xs font-medium uppercase tracking-wide text-[var(--text-dim)] pb-1",children:"Body"}),s.jsx(tt,{value:e.body,onChange:()=>{},readOnly:!0},`${e.method} ${e.pathPattern}`)]})]})}const $c=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelMainMockReadOnly:Ar},Symbol.toStringTag,{value:"Module"}));function Mr({entry:e,scenarioSlug:t,scenarioHasDefaultFallback:n,onSave:r,onRemove:a,onPassthrough:o,focusJsonPath:c}){const l=`${e.method} ${e.pathPattern}`,d=e.source==="scenario"||e.source==="default"||e.source==="shared";return s.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[s.jsx(Or,{entry:e,scenarioHasDefaultFallback:n,onSave:r,onRemove:a,onPassthrough:o}),s.jsx("div",{className:"flex-1 min-h-0 overflow-auto p-4",children:d?s.jsx(Er,{entry:e,routeKey:l,scenarioSlug:t,onSave:r,focusJsonPath:c}):s.jsx(Ar,{entry:e})})]})}const Fc=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelMainMock:Mr},Symbol.toStringTag,{value:"Module"}));function ni({slug:e,tab:t,initialRows:n,onCellEdited:r}){const[a,o]=i.useState(n),[c,l]=i.useState(null),[d,f]=i.useState(""),[g,b]=i.useState(""),u=i.useRef(null);i.useEffect(()=>{o(n),l(null)},[t.dataKey,n]);function h(_,v){const w=a[_];l({row:_,col:v});const S=w[v]===null?"":typeof w[v]=="object"?JSON.stringify(w[v]):String(w[v]);f(S),b(S)}function m(_){if(f(_),u.current&&clearTimeout(u.current),!c)return;const v=c;u.current=setTimeout(()=>{p(v.row,v.col,_)},600)}function x(){c&&(u.current&&clearTimeout(u.current),p(c.row,c.col,d),l(null))}function y(){if(u.current&&clearTimeout(u.current),!!c){if(d!==g){const _=[...a];_[c.row]={..._[c.row],[c.col]:nn(g)},o(_),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:g})}).then(()=>{_e(),r&&r()}).catch(()=>{})}l(null)}}async function p(_,v,w){const S=[...a];S[_]={...S[_],[v]:nn(w)},o(S);try{await fetch(`/api/scenarios/${encodeURIComponent(e)}/data`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({table:t.dataKey,rowIndex:_,column:v,value:w})}),_e(),r&&r()}catch{}}return{rows:a,editingCell:c,editValue:d,handleEditCell:h,handleEditValueChange:m,handleSave:x,handleCancelEdit:y}}function Ir({tab:e}){return!e.description&&!e.category?null:s.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&&s.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&&s.jsx("span",{className:"text-[10px] text-[var(--text-dim)]",children:e.description})]})}const Bc=Object.freeze(Object.defineProperty({__proto__:null,DataViewerCategoryBadge:Ir},Symbol.toStringTag,{value:"Module"}));function Pr({editingCell:e,editValue:t,onEditValueChange:n,onSave:r,onCancel:a}){return s.jsxs("div",{className:"border-t border-[var(--border-default)] bg-[var(--bg-deep)] px-3 py-2",children:[s.jsx("div",{className:"flex items-center gap-2 mb-1.5",children:s.jsxs("span",{className:"text-[10px] text-[var(--text-muted)]",children:["Editing"," ",s.jsx("strong",{className:"text-[var(--text-secondary)]",children:e.col})," ","in row ",e.row+1]})}),s.jsx("textarea",{value:t,onChange:o=>n(o.target.value),className:"w-full px-2 py-1.5 text-[11px] bg-[var(--bg-card)] text-[var(--text-primary)] border border-[var(--border-default)] rounded outline-none focus:border-[var(--accent-active)]/50 resize-y min-h-[60px] max-h-[200px] font-mono",autoFocus:!0,rows:t.length>100?4:2,onKeyDown:o=>{o.key==="Escape"&&a(),o.key==="Enter"&&(o.metaKey||o.ctrlKey)&&r()}}),s.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[s.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"}),s.jsx("button",{onClick:a,className:"px-3 py-1 text-[10px] text-[var(--text-muted)] hover:text-[var(--text-primary)] bg-transparent border-none cursor-pointer",children:"Cancel"}),s.jsxs("span",{className:"text-[9px] text-[var(--text-dim)] ml-auto",children:["⌘","+Enter to save, Esc to cancel"]})]})]})}const zc=Object.freeze(Object.defineProperty({__proto__:null,DataViewerCellEditor:Pr},Symbol.toStringTag,{value:"Module"}));function Rr({columns:e,colTypes:t,pkCol:n,rows:r,onEditCell:a}){return e.length===0?s.jsx("div",{className:"px-3 py-4 text-[10px] text-[var(--text-dim)] text-center",children:"No columns defined for this table"}):s.jsx("div",{className:"overflow-x-auto max-h-[300px] overflow-y-auto",children:s.jsxs("table",{className:"w-full text-[10px] border-collapse table-fixed",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"bg-[var(--bg-deep)] sticky top-0 z-10",children:[s.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=>s.jsx(Dr,{name:o,type:t[o],isPk:o===n},o))]})}),s.jsx("tbody",{children:r.map((o,c)=>s.jsx(Lr,{row:o,rowIndex:c,columns:e,pkCol:n,onEditCell:a},c))})]})})}function Dr({name:e,type:t,isPk:n}){return s.jsxs("th",{className:"text-left px-2 py-1.5 border-b border-[var(--border-default)] whitespace-nowrap overflow-hidden",children:[n&&s.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"}),s.jsx("span",{className:"text-[var(--text-secondary)] font-medium",children:e}),s.jsx("span",{className:"text-[var(--text-dim)] font-normal ml-1",children:t})]})}function Lr({row:e,rowIndex:t,columns:n,pkCol:r,onEditCell:a}){return s.jsxs("tr",{className:"border-b border-[var(--border-subtle)] hover:bg-[var(--bg-card)] group/row",children:[s.jsx("td",{className:"text-right text-[var(--text-dim)] px-2 py-1.5 w-8 select-none",children:t+1}),n.map(o=>s.jsx($r,{value:e[o],isPk:o===r,onEdit:()=>a(t,o)},o))]})}function $r({value:e,isPk:t,onEdit:n}){return s.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:[s.jsx("span",{className:"truncate block whitespace-nowrap",children:e===null?s.jsx("span",{className:"text-[var(--text-dim)] italic",children:"null"}):typeof e=="object"?s.jsx("span",{className:"text-[var(--text-dim)]",children:JSON.stringify(e)}):typeof e=="number"?s.jsx("span",{className:"text-amber-400",children:String(e)}):String(e)}),s.jsx("button",{onClick:r=>{r.stopPropagation(),n()},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:s.jsxs("svg",{width:"9",height:"9",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),s.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})})]})}const Kc=Object.freeze(Object.defineProperty({__proto__:null,DataViewerCell:$r,DataViewerColumnHeader:Dr,DataViewerRow:Lr,DataViewerTable:Rr},Symbol.toStringTag,{value:"Module"}));function Fr({slug:e,tab:t,initialRows:n,onCellEdited:r}){const{rows:a,editingCell:o,editValue:c,handleEditCell:l,handleEditValueChange:d,handleSave:f,handleCancelEdit:g}=ni({slug:e,tab:t,initialRows:n,onCellEdited:r}),b=ho(a,t.schemaFields),u=mo(b,a,t.schemaFields),h=bo(b,t.schemaFields);return s.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[s.jsx(Ir,{tab:t}),s.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:s.jsx(Rr,{columns:b,colTypes:u,pkCol:h,rows:a,onEditCell:l})}),o&&s.jsx(Pr,{editingCell:o,editValue:c,onEditValueChange:d,onSave:f,onCancel:g})]})}const Hc=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelMainTable:Fr},Symbol.toStringTag,{value:"Module"}));function ri({slug:e,browserState:t,tab:n,onCellEdited:r}){const a=i.useMemo(()=>{if(!t)return{};switch(n){case"cookies":return t.cookies??{};case"localStorage":return t.localStorage??{};case"sessionStorage":return t.sessionStorage??{};case"headers":return t.requestHeaders??{};default:return{}}},[t,n]),o=i.useCallback(async d=>{const f=n==="headers"?"browserState.requestHeaders":`browserState.${n}`;try{await fetch(`/api/scenarios/${encodeURIComponent(e)}/data`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:f,value:JSON.stringify(d)})}),_e(),r&&r()}catch{}},[e,n,r]),c=i.useMemo(()=>{switch(n){case"cookies":return"Cookies";case"localStorage":return"Local Storage";case"sessionStorage":return"Session Storage";case"headers":return"Request Headers"}},[n]),l=i.useMemo(()=>{switch(n){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."}},[n]);return{value:a,handleChange:o,label:c,description:l}}function Br({slug:e,browserState:t,tab:n,onCellEdited:r}){const{value:a,handleChange:o,label:c,description:l}=ri({slug:e,browserState:t,tab:n,onCellEdited:r});return s.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[s.jsxs("div",{className:"px-4 py-3 border-b border-[var(--border-subtle)]",children:[s.jsx("h2",{className:"text-sm font-semibold text-[var(--text-primary)]",children:c}),s.jsx("p",{className:"text-xs text-[var(--text-dim)] mt-1",children:l})]}),s.jsx("div",{className:"flex-1 min-h-0 p-4 overflow-auto",children:s.jsx(tt,{value:a,onChange:o})})]})}const Uc=Object.freeze(Object.defineProperty({__proto__:null,BrowserStateTab:Br},Symbol.toStringTag,{value:"Module"}));function Je({label:e,active:t,onClick:n}){return s.jsx("button",{type:"button",onClick:n,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})}const Wc=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelMockDataBadge:Je},Symbol.toStringTag,{value:"Module"}));function zr({shares:e,activeBadge:t,onSelect:n}){return s.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:[s.jsx("span",{className:"text-[10px] uppercase tracking-wider text-[var(--text-dim)] font-semibold",children:"Mock Data:"}),s.jsx(Je,{label:"This Page",active:t.kind==="this-page",onClick:()=>n({kind:"this-page"})}),e.map(r=>s.jsx(Je,{label:r,active:t.kind==="share"&&t.slug===r,onClick:()=>n({kind:"share",slug:r})},r)),s.jsx(Je,{label:"Defaults",active:t.kind==="defaults",onClick:()=>n({kind:"defaults"})})]})}const Yc=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanelMockDataStrip:zr},Symbol.toStringTag,{value:"Module"}));function si({slug:e,scenarioName:t,initialSection:n,onClose:r,variant:a="slideOver"}){const{data:o,tableTabs:c,scenarioOwnedDataKeys:l,shares:d,browserState:f,loading:g,error:b}=jo(e),{entries:u,loading:h,error:m,upsertScoped:x,remove:y,setPassthrough:p}=lo(e),{config:_}=jn(),v=(_==null?void 0:_.provider)??"claude",w=No({slug:e,onPreviewReload:_e}),S=i.useCallback(()=>{w.markDirty(),_e()},[w]),M=i.useCallback(async D=>{await x(D),S()},[x,S]),N=i.useCallback(async D=>{await y(D),S()},[y,S]),z=i.useCallback(async D=>{await p(D),S()},[p,S]),j=i.useCallback(()=>{w.markDirty(),_e()},[w]),I=i.useCallback(()=>{r&&w.confirmIfDirty("Discard unsaved changes to this scenario?")&&r()},[r,w]),[E,F]=i.useState(null),[W,L]=i.useState(null),[K,A]=i.useState(!1),Q=i.useCallback(D=>F({kind:"mock",routeKey:D}),[]);no({onSelect:Q,onFocus:L});const[ce,V]=i.useState({kind:"this-page"}),J=g||h,re=i.useMemo(()=>a==="inline"?c.filter(D=>l.has(D.dataKey)):c,[a,c,l]),Z=i.useMemo(()=>{if(a!=="inline")return u;switch(ce.kind){case"this-page":return u.filter(D=>D.consumedThisPageLoad);case"defaults":return u.filter(D=>D.source==="default");case"share":return u.filter(D=>D.source==="shared"&&D.sharedSlug===ce.slug)}},[a,u,ce]);Ro({seedTabs:re,mockEntries:Z,initialSection:n,selection:E,setSelection:F});const oe=i.useMemo(()=>{const D=new Set;for(const ge of u)ge.source==="default"&&D.add(me(ge));return D},[u]),Y=(E==null?void 0:E.kind)==="seed"?re.find(D=>D.dataKey===E.dataKey)??null:null,q=(E==null?void 0:E.kind)==="mock"?Z.find(D=>me(D)===E.routeKey)??null:null,ee=Y&&o?o[Y.dataKey]??[]:[],ue=i.useMemo(()=>Za({slug:e,scenarioName:t,seedTabs:re,mockEntries:Z,selectedMock:q,selectedSeedTab:Y,selectedSeedRows:ee}),[e,t,re,Z,q,Y,ee]),T=t??e,k=re.length>0||Z.length>0,X=s.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[s.jsx(xr,{title:T,slug:e,provider:v,chatOpen:K,onToggleChat:()=>A(D=>!D),variant:a,onClose:r?I: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()}),a==="inline"&&s.jsx(zr,{shares:d,activeBadge:ce,onSelect:V}),K&&s.jsx("div",{className:"flex-shrink-0 border-b border-[var(--border-subtle)] bg-[var(--bg-deep)]",children:s.jsx(rr,{chatName:`edit-data-${e}`,prompt:ue,height:360,onClose:()=>A(!1)})}),s.jsxs("div",{className:"flex flex-1 min-h-0",children:[s.jsx(lr,{seedTabs:re,mockEntries:Z,selection:E,onSelect:F}),s.jsx("main",{className:"flex-1 min-w-0 min-h-0 bg-[var(--bg-deep)] flex flex-col",children:s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col",children:[b&&s.jsx(Re,{text:`Seed error: ${b}`,className:"text-xs text-red-400",rowClassName:"p-4"}),m&&s.jsx(Re,{text:`Mocks error: ${m}`,className:"text-xs text-red-400",rowClassName:"p-4"}),!J&&!k&&s.jsx(ur,{}),Y&&s.jsx(Fr,{slug:e,tab:Y,initialRows:ee,onCellEdited:j}),q&&s.jsx(Mr,{entry:q,scenarioSlug:e,scenarioHasDefaultFallback:oe.has(me(q)),onSave:M,onRemove:N,onPassthrough:z,focusJsonPath:W}),(E==null?void 0:E.kind)==="browser"&&s.jsx(Br,{slug:e,browserState:f,tab:E.tab,onCellEdited:j}),!Y&&!q&&(E==null?void 0:E.kind)!=="browser"&&k&&!J&&s.jsx("p",{className:"p-4 text-xs text-[var(--text-dim)] italic",children:"Select a data source from the left to view it."}),J&&!k&&s.jsx("p",{className:"p-4 text-xs text-[var(--text-dim)]",children:"Loading scenario data…"})]})})]})]});return a==="fullPage"?s.jsx("div",{className:"fixed inset-0 bg-[var(--bg-deep)] text-[var(--text-primary)]",children:X}):a==="inline"?s.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:X}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-40 bg-black/40",onClick:I,"aria-label":"Close scenario data panel"}),s.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:X})]})}const Vc=Object.freeze(Object.defineProperty({__proto__:null,ScenarioDataPanel:si},Symbol.toStringTag,{value:"Module"}));export{cr as $,Ka as A,Ve as B,un as C,Lr as D,mn as E,ns as F,Dr as G,$r as H,Br as I,Me as J,Vn as K,Qn as L,Cr as M,kr as N,Sr as O,jr as P,Ze as Q,ye as R,si as S,Hn as T,et as U,tt as V,wr as W,_r as X,yr as Y,gr as Z,ir as _,It as a,gc as a$,Tr as a0,Nr as a1,lr as a2,zr as a3,Je as a4,mr as a5,Or as a6,Mr as a7,hr as a8,xr as a9,Li as aA,$i as aB,Pi as aC,Ri as aD,Mi as aE,Ii as aF,Di as aG,Si as aH,ji as aI,Fi as aJ,Ai as aK,pc as aL,dc as aM,uc as aN,_c as aO,hc as aP,wc as aQ,Yc as aR,Wc as aS,Hc as aT,$c as aU,Lc as aV,Dc as aW,Fc as aX,vc as aY,jc as aZ,mc as a_,ur as aa,fr as ab,dr as ac,Rr as ad,Pr as ae,Ir as af,or as ag,ar as ah,Fn as ai,$n as aj,Ln as ak,Dn as al,Un as am,Nn as an,Cn as ao,xn as ap,er as aq,tr as ar,rr as as,nr as at,vi as au,Vi as av,xi as aw,yi as ax,rc as ay,gi as az,Gn as b,rs as b$,bc as b0,Vc as b1,Rc as b2,Pc as b3,ac as b4,sc as b5,lc as b6,fc as b7,Ic as b8,Bi as b9,Gr as bA,gn as bB,ke as bC,jn as bD,Ye as bE,Jt as bF,Wi as bG,ec as bH,Qi as bI,Zi as bJ,tc as bK,nc as bL,hs as bM,wi as bN,Ha as bO,ot as bP,Ji as bQ,Xi as bR,Oi as bS,Se as bT,Sa as bU,es as bV,ct as bW,In as bX,Ni as bY,Us as bZ,Wa as b_,Ki as ba,zi as bb,Gi as bc,Oc as bd,Ec as be,Tc as bf,kc as bg,Ac as bh,Mc as bi,Cc as bj,Nc as bk,Sc as bl,oc as bm,fi as bn,di as bo,pi as bp,hi as bq,mi as br,Kc as bs,zc as bt,Bc as bu,bi as bv,Uc as bw,qi as bx,Xr as by,Qr as bz,wn as c,Ws as c0,ms as c1,bs as c2,ks as c3,Is as c4,vs as c5,Sn as c6,Yi as c7,_i as c8,Ya as c9,yc as cA,xc as cB,cc as cC,ua as cD,la as cE,na as cF,Ds as cG,Ht as cH,Ls as cI,Bs as cJ,Fs as cK,Tt as cL,Qs as ca,Es as cb,Xs as cc,qs as cd,ki as ce,Hs as cf,kn as cg,Ps as ch,Ks as ci,Hi as cj,Js as ck,Ci as cl,Rn as cm,ea as cn,Ui as co,aa as cp,Wt as cq,sa as cr,we as cs,Ei as ct,Ti as cu,oa as cv,ra as cw,Ne as cx,co as cy,ic as cz,Fr as d,_e as e,ei as f,Er as g,Ar as h,No as i,jo as j,lo as k,dn as l,bn as m,yn as n,Wn as o,nn as p,Yn as q,me as r,hn as s,pn as t,Ua as u,fn as v,be as w,Kn as x,zn as y,Bn as z};
|