@oscharko-dev/keiko 0.2.0 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -9
- package/dist/ui/csp-hashes.json +12 -12
- package/dist/ui/static/404.html +1 -1
- package/dist/ui/static/__next.__PAGE__.txt +2 -2
- package/dist/ui/static/__next._full.txt +2 -2
- package/dist/ui/static/__next._head.txt +1 -1
- package/dist/ui/static/__next._index.txt +1 -1
- package/dist/ui/static/__next._tree.txt +1 -1
- package/dist/ui/static/_next/static/chunks/{3u1-caup3g2wd.js → 14pxq1l54d91b.js} +1 -1
- package/dist/ui/static/_not-found/__next._full.txt +1 -1
- package/dist/ui/static/_not-found/__next._head.txt +1 -1
- package/dist/ui/static/_not-found/__next._index.txt +1 -1
- package/dist/ui/static/_not-found/__next._not-found.__PAGE__.txt +1 -1
- package/dist/ui/static/_not-found/__next._not-found.txt +1 -1
- package/dist/ui/static/_not-found/__next._tree.txt +1 -1
- package/dist/ui/static/_not-found.html +1 -1
- package/dist/ui/static/_not-found.txt +1 -1
- package/dist/ui/static/index.html +1 -1
- package/dist/ui/static/index.txt +2 -2
- package/dist/ui/static/launch/__next._full.txt +2 -2
- package/dist/ui/static/launch/__next._head.txt +1 -1
- package/dist/ui/static/launch/__next._index.txt +1 -1
- package/dist/ui/static/launch/__next._tree.txt +1 -1
- package/dist/ui/static/launch/__next.launch.__PAGE__.txt +2 -2
- package/dist/ui/static/launch/__next.launch.txt +1 -1
- package/dist/ui/static/launch.html +1 -1
- package/dist/ui/static/launch.txt +2 -2
- package/dist/ui/static/local-knowledge/__next._full.txt +2 -2
- package/dist/ui/static/local-knowledge/__next._head.txt +1 -1
- package/dist/ui/static/local-knowledge/__next._index.txt +1 -1
- package/dist/ui/static/local-knowledge/__next._tree.txt +1 -1
- package/dist/ui/static/local-knowledge/__next.local-knowledge.__PAGE__.txt +2 -2
- package/dist/ui/static/local-knowledge/__next.local-knowledge.txt +1 -1
- package/dist/ui/static/local-knowledge/capsule/__next._full.txt +1 -1
- package/dist/ui/static/local-knowledge/capsule/__next._head.txt +1 -1
- package/dist/ui/static/local-knowledge/capsule/__next._index.txt +1 -1
- package/dist/ui/static/local-knowledge/capsule/__next._tree.txt +1 -1
- package/dist/ui/static/local-knowledge/capsule/__next.local-knowledge.capsule.__PAGE__.txt +1 -1
- package/dist/ui/static/local-knowledge/capsule/__next.local-knowledge.capsule.txt +1 -1
- package/dist/ui/static/local-knowledge/capsule/__next.local-knowledge.txt +1 -1
- package/dist/ui/static/local-knowledge/capsule.html +1 -1
- package/dist/ui/static/local-knowledge/capsule.txt +1 -1
- package/dist/ui/static/local-knowledge.html +1 -1
- package/dist/ui/static/local-knowledge.txt +2 -2
- package/dist/ui/static/memoriaviva/__next._full.txt +1 -1
- package/dist/ui/static/memoriaviva/__next._head.txt +1 -1
- package/dist/ui/static/memoriaviva/__next._index.txt +1 -1
- package/dist/ui/static/memoriaviva/__next._tree.txt +1 -1
- package/dist/ui/static/memoriaviva/__next.memoriaviva.__PAGE__.txt +1 -1
- package/dist/ui/static/memoriaviva/__next.memoriaviva.txt +1 -1
- package/dist/ui/static/memoriaviva/consolidation/__next._full.txt +1 -1
- package/dist/ui/static/memoriaviva/consolidation/__next._head.txt +1 -1
- package/dist/ui/static/memoriaviva/consolidation/__next._index.txt +1 -1
- package/dist/ui/static/memoriaviva/consolidation/__next._tree.txt +1 -1
- package/dist/ui/static/memoriaviva/consolidation/__next.memoriaviva.consolidation.__PAGE__.txt +1 -1
- package/dist/ui/static/memoriaviva/consolidation/__next.memoriaviva.consolidation.txt +1 -1
- package/dist/ui/static/memoriaviva/consolidation/__next.memoriaviva.txt +1 -1
- package/dist/ui/static/memoriaviva/consolidation.html +1 -1
- package/dist/ui/static/memoriaviva/consolidation.txt +1 -1
- package/dist/ui/static/memoriaviva/detail/__next._full.txt +1 -1
- package/dist/ui/static/memoriaviva/detail/__next._head.txt +1 -1
- package/dist/ui/static/memoriaviva/detail/__next._index.txt +1 -1
- package/dist/ui/static/memoriaviva/detail/__next._tree.txt +1 -1
- package/dist/ui/static/memoriaviva/detail/__next.memoriaviva.detail.__PAGE__.txt +1 -1
- package/dist/ui/static/memoriaviva/detail/__next.memoriaviva.detail.txt +1 -1
- package/dist/ui/static/memoriaviva/detail/__next.memoriaviva.txt +1 -1
- package/dist/ui/static/memoriaviva/detail.html +1 -1
- package/dist/ui/static/memoriaviva/detail.txt +1 -1
- package/dist/ui/static/memoriaviva/review-queue/__next._full.txt +1 -1
- package/dist/ui/static/memoriaviva/review-queue/__next._head.txt +1 -1
- package/dist/ui/static/memoriaviva/review-queue/__next._index.txt +1 -1
- package/dist/ui/static/memoriaviva/review-queue/__next._tree.txt +1 -1
- package/dist/ui/static/memoriaviva/review-queue/__next.memoriaviva.review-queue.__PAGE__.txt +1 -1
- package/dist/ui/static/memoriaviva/review-queue/__next.memoriaviva.review-queue.txt +1 -1
- package/dist/ui/static/memoriaviva/review-queue/__next.memoriaviva.txt +1 -1
- package/dist/ui/static/memoriaviva/review-queue.html +1 -1
- package/dist/ui/static/memoriaviva/review-queue.txt +1 -1
- package/dist/ui/static/memoriaviva.html +1 -1
- package/dist/ui/static/memoriaviva.txt +1 -1
- package/node_modules/@oscharko-dev/keiko-cli/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-cli/package.json +14 -15
- package/node_modules/@oscharko-dev/keiko-contracts/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-contracts/dist/index.d.ts +1 -1
- package/node_modules/@oscharko-dev/keiko-contracts/dist/index.js +1 -1
- package/node_modules/@oscharko-dev/keiko-contracts/package.json +1 -2
- package/node_modules/@oscharko-dev/keiko-evaluations/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-evaluations/package.json +9 -10
- package/node_modules/@oscharko-dev/keiko-evidence/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-evidence/package.json +4 -5
- package/node_modules/@oscharko-dev/keiko-harness/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-harness/package.json +6 -7
- package/node_modules/@oscharko-dev/keiko-local-knowledge/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-local-knowledge/dist/capsule-lifecycle.d.ts +1 -0
- package/node_modules/@oscharko-dev/keiko-local-knowledge/dist/capsule-lifecycle.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-local-knowledge/dist/capsule-lifecycle.js +42 -0
- package/node_modules/@oscharko-dev/keiko-local-knowledge/dist/index.d.ts +1 -1
- package/node_modules/@oscharko-dev/keiko-local-knowledge/dist/index.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-local-knowledge/dist/index.js +1 -1
- package/node_modules/@oscharko-dev/keiko-local-knowledge/dist/indexing/embedding-batcher.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-local-knowledge/dist/indexing/embedding-batcher.js +9 -6
- package/node_modules/@oscharko-dev/keiko-local-knowledge/package.json +5 -6
- package/node_modules/@oscharko-dev/keiko-memory-capture/package.json +3 -4
- package/node_modules/@oscharko-dev/keiko-memory-consolidation/package.json +3 -4
- package/node_modules/@oscharko-dev/keiko-memory-governance/package.json +3 -4
- package/node_modules/@oscharko-dev/keiko-memory-retrieval/package.json +3 -4
- package/node_modules/@oscharko-dev/keiko-memory-vault/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-memory-vault/package.json +3 -4
- package/node_modules/@oscharko-dev/keiko-model-gateway/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-model-gateway/dist/embedding.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-model-gateway/dist/embedding.js +3 -2
- package/node_modules/@oscharko-dev/keiko-model-gateway/package.json +3 -4
- package/node_modules/@oscharko-dev/keiko-quality-intelligence/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-quality-intelligence/package.json +3 -4
- package/node_modules/@oscharko-dev/keiko-sandbox/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-sandbox/package.json +2 -3
- package/node_modules/@oscharko-dev/keiko-sdk/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-sdk/package.json +9 -10
- package/node_modules/@oscharko-dev/keiko-security/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-security/package.json +2 -3
- package/node_modules/@oscharko-dev/keiko-server/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/deps.d.ts +9 -2
- package/node_modules/@oscharko-dev/keiko-server/dist/deps.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/gateway-setup.d.ts +3 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/gateway-setup.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/gateway-setup.js +201 -43
- package/node_modules/@oscharko-dev/keiko-server/dist/local-knowledge-handlers.d.ts +3 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/local-knowledge-handlers.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/local-knowledge-handlers.js +90 -23
- package/node_modules/@oscharko-dev/keiko-server/dist/memory-embedding.d.ts.map +1 -1
- package/node_modules/@oscharko-dev/keiko-server/dist/memory-embedding.js +23 -25
- package/node_modules/@oscharko-dev/keiko-server/package.json +19 -20
- package/node_modules/@oscharko-dev/keiko-tools/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-tools/package.json +5 -6
- package/node_modules/@oscharko-dev/keiko-verification/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-verification/package.json +5 -6
- package/node_modules/@oscharko-dev/keiko-workflows/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-workflows/package.json +10 -11
- package/node_modules/@oscharko-dev/keiko-workspace/dist/.tsbuildinfo +1 -1
- package/node_modules/@oscharko-dev/keiko-workspace/package.json +3 -4
- package/package.json +29 -26
- /package/dist/ui/static/_next/static/{sze4uuTupXYIdcMx_go4e → WDuCK49c2RLzsJ_YkfsbT}/_buildManifest.js +0 -0
- /package/dist/ui/static/_next/static/{sze4uuTupXYIdcMx_go4e → WDuCK49c2RLzsJ_YkfsbT}/_clientMiddlewareManifest.js +0 -0
- /package/dist/ui/static/_next/static/{sze4uuTupXYIdcMx_go4e → WDuCK49c2RLzsJ_YkfsbT}/_ssgManifest.js +0 -0
|
@@ -92,7 +92,7 @@ void main(){
|
|
|
92
92
|
|
|
93
93
|
${s}`:`${s}
|
|
94
94
|
|
|
95
|
-
Click once to arm removal.`,"aria-label":r?`Confirm removal of connection: ${t.label}. Activate again to remove.`:l?`${t.label} — ${m} data exchange in progress. Activate to remove connection.`:`Remove connection: ${t.label}`,children:[(0,n.jsx)(j.Icons.git,{size:11})," ",(0,n.jsx)("span",{children:r?"Remove?":t.label}),l&&!r?(0,n.jsx)("span",{className:"conn-flow-tag","aria-hidden":"true",children:"heavy"===m?"⇶":"→"}):null]},t.c.id)})})]})}let eC=["n","s","e","w","ne","nw","se","sw"],eI=["t","r","b","l"];function eE({icon:e,label:t}){let a=j.Icons[e];return(0,n.jsxs)("div",{className:"too-small",children:[(0,n.jsx)("div",{className:"ts-ico",children:(0,n.jsx)(a,{size:28})}),(0,n.jsxs)("div",{className:"ts-title",children:["Too small to show ",t]}),(0,n.jsx)("div",{className:"ts-sub",children:"Enlarge the window or zoom its content out"}),(0,n.jsx)("div",{className:"ts-arrow","aria-hidden":"true",children:(0,n.jsx)("svg",{width:"22",height:"22",viewBox:"0 0 22 22",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("path",{d:"M8 8l8 8M16 11v5h-5"})})})]})}function eR({win:e,top:t,connState:l,view:i,api:r,wsRef:s}){var o;let c=E[e.type],d=void 0!==(o=e.type)&&((R[o]??[]).length>0||Object.values(R).some(e=>e.includes(o))),u=j.Icons[c.icon],[p,m]=(0,a.useState)(!1),h=(0,a.useRef)(null),f=(0,a.useRef)(null),g=e.zoom??1,v="chat"===e.type||"agents"===e.type||"quality"===e.type||"editor"===e.type,b="agents"===e.type||"quality"===e.type||"editor"===e.type,x="quality"===e.type||"editor"===e.type,y=v?r.linkedFilesRoot(e.id):null,w=b?r.linkedFilesContext(e.id)?.activeFilePath:void 0,k="quality"===e.type?r.linkedAllFilesRoots(e.id):null!==y?[y]:[],N=x?r.linkedConnectorCapsuleIds(e.id):[],S=x?r.linkedConnectorCapsuleSetIds(e.id):[],C="quality"===e.type?r.linkedFigmaSnapshotRunIds(e.id):[],I="quality"===e.type?r.linkedFigmaSnapshotSources?.(e.id):void 0,$="quality"===e.type?r.linkedImageSources?.(e.id):void 0,A=e.w/g,T=e.h/g,P=(0,a.useCallback)(t=>{r.update(e.id,{cfg:{...e.cfg,...t}})},[r,e.cfg,e.id]),M=(0,a.useCallback)((e,t)=>r.add(e,t),[r]),{mode:D,node:q}=function(e,t,a,l,i,r,s,o,c,d,u,p,m,h,f){let g=E[t];if("chat"===t){let t=a<520,n=a<430;return{mode:n?"mini":"full",node:g.render(i,{windowId:e,mini:n,minimalChat:a<360||l<320,compact:a<640,controlsNarrow:t,barCompact:a<520,workflowCompact:t,linkedRoot:r,linkedFilePath:s,linkedRoots:o,linkedCapsuleIds:c,linkedCapsuleSetIds:d,linkedFigmaSnapshotRunIds:u,linkedFigmaSnapshotSources:p,linkedImageSources:m,updateCfg:h,openWindow:f})}}return a<g.tiny.w||l<g.tiny.h?{mode:"tiny",node:(0,n.jsx)(eE,{icon:g.icon,label:g.title})}:{mode:"full",node:g.render(i,{windowId:e,linkedRoot:r,linkedFilePath:s,linkedRoots:o,linkedCapsuleIds:c,linkedCapsuleSetIds:d,linkedFigmaSnapshotRunIds:u,linkedFigmaSnapshotSources:p,linkedImageSources:m,updateCfg:h,openWindow:f})}}(e.id,e.type,A,T,e.cfg,y,w,k,N,S,C,I,$,P,M),F=(0,a.useCallback)(t=>r.update(e.id,{zoom:Math.max(.5,Math.min(2,Math.round(10*t)/10))}),[r,e.id]);(0,a.useEffect)(()=>{var t,n;if(t=e.type,n=e.cfg,"figmaView"!==t||"string"!=typeof n.selectedScreenIdsJson||!(n.selectedScreenIdsJson.length>0)||e.max||"full"!==D)return;let a=h.current;if(null===a)return;let l=null,i=()=>{l=null;let t=a.scrollHeight-a.clientHeight;if(t<=8)return;let n=Math.ceil(e.h+t);n<=e.h+8||r.update(e.id,{h:n})},s=()=>{null===l&&(l="function"==typeof window.requestAnimationFrame?window.requestAnimationFrame(i):window.setTimeout(i,0))};s();let o="u">typeof ResizeObserver?new ResizeObserver(s):null;o?.observe(a);let c=a.firstElementChild;return null!==c&&o?.observe(c),()=>{null!==l&&("function"==typeof window.cancelAnimationFrame?window.cancelAnimationFrame(l):window.clearTimeout(l)),o?.disconnect()}},[r,D,e.cfg,e.h,e.id,e.max,e.type]),(0,a.useEffect)(()=>()=>{f.current?.(),f.current=null},[]);let O=(0,a.useCallback)(t=>{t instanceof Element&&null!==t.closest("button,input,textarea,select,a[href],summary,[contenteditable='true'],[contenteditable=''],[role='button'],[role='checkbox'],[role='link'],[role='menuitem'],[role='option'],[role='radio'],[role='switch'],[role='tab']")?window.setTimeout(()=>r.focus(e.id),0):r.focus(e.id)},[r,e.id]),z=(0,a.useCallback)(t=>{var n,a,o,c;let d,u,p,h,f;if(!(B(c=t)||1===c.button)||"valid"===l)return;t.preventDefault(),O(t.target);let g=s.current;if(null===g)return;let v=(n=g.getBoundingClientRect(),{z:d=i.zoom,vpx0:-i.x/d,vpy0:-i.y/d,vpw:n.width/d,vph:n.height/d,toWX:e=>(e-n.left-i.x)/d,toWY:e=>(e-n.top-i.y)/d}),b=e.max,x=b?e.prev?.w??480:e.w,y=b?e.prev?.h??360:e.h,w=b?x/2:v.toWX(t.clientX)-e.x,j=b?18:v.toWY(t.clientY)-e.y;b&&r.update(e.id,{max:!1,w:x,h:y}),m(!0),a={winId:e.id,offX:w,offY:j,W:x},o=()=>m(!1),u=30/v.z,p=e=>{let t,n,l,i,s=v.toWX(e.clientX),o=v.toWY(e.clientY),c=s-a.offX,d=o-a.offY;c=Math.max(v.vpx0-(a.W-120),Math.min(v.vpx0+v.vpw-120,c)),d=Math.max(v.vpy0,Math.min(v.vpy0+v.vph-38,d)),r.setSnap((t=s-v.vpx0<u,n=v.vpx0+v.vpw-s<u,l=o-v.vpy0<u,i=v.vpy0+v.vph-o<u,l&&t?"tl":l&&n?"tr":i&&t?"bl":i&&n?"br":t?"left":n?"right":l?"maxi":null)),r.update(a.winId,{x:c,y:d})},h=()=>{window.removeEventListener("pointermove",p),window.removeEventListener("pointerup",h),window.removeEventListener("pointercancel",h),r.commitSnap(a.winId),f(),o?.()},f=Y(),window.addEventListener("pointermove",p),window.addEventListener("pointerup",h),window.addEventListener("pointercancel",h)},[r,e.id,e.x,e.y,e.w,e.h,e.max,e.prev,i,s,l,O]),K=(0,a.useCallback)(t=>n=>{if(!B(n))return;n.preventDefault(),n.stopPropagation(),f.current?.(),f.current=null,r.focus(e.id);let a={x:e.x,y:e.y,w:e.w,h:e.h},l=a,s=n.clientX,o=n.clientY,c=i.zoom,d=document.body.style.cursor,u=!0,p=()=>{u&&(u=!1,window.removeEventListener("pointermove",h),window.removeEventListener("pointerup",m),window.removeEventListener("pointercancel",m),window.removeEventListener("blur",m),document.body.style.cursor=d,f.current===p&&(f.current=null))},m=()=>{p()},h=n=>{var i;if(!u)return;if(0===n.buttons)return void p();let d=function(e,t,n,a,l){let{x:i,y:r,w:s,h:o}=e;t.includes("e")&&(s=e.w+n),t.includes("s")&&(o=e.h+a),t.includes("w")&&(s=e.w-n,i=e.x+n),t.includes("n")&&(o=e.h-a,r=e.y+a);let c=E[l].min,d=c.w>0?c.w:240,u=c.h>0?c.h:150;return s<d&&(t.includes("w")&&(i-=d-s),s=d),o<u&&(t.includes("n")&&(r-=u-o),o=u),{x:i,y:r,w:s,h:o}}(a,t,(n.clientX-s)/c,(n.clientY-o)/c,e.type);((i=l).x!==d.x||i.y!==d.y||i.w!==d.w||i.h!==d.h)&&(l=d,r.update(e.id,{...d,max:!1}))};document.body.style.cursor="n"===t||"s"===t?"ns-resize":"e"===t||"w"===t?"ew-resize":"ne"===t||"sw"===t?"nesw-resize":"nwse-resize",window.addEventListener("pointermove",h),window.addEventListener("pointerup",m),window.addEventListener("pointercancel",m),window.addEventListener("blur",m),f.current=p},[r,e.id,e.x,e.y,e.w,e.h,e.type,i.zoom]),_=(0,a.useCallback)((t,n)=>{let a=t.getBoundingClientRect();r.startConnect(e.id,{clientX:"clientX"in n?n.clientX:a.left+a.width/2,clientY:"clientY"in n?n.clientY:a.top+a.height/2,preventDefault:()=>n.preventDefault(),stopPropagation:()=>n.stopPropagation()})},[r,e.id]),U=(0,a.useCallback)(e=>{B(e)&&(e.preventDefault(),e.stopPropagation(),_(e.currentTarget,e))},[_]),W=(0,a.useCallback)(t=>{if("Enter"===t.key||" "===t.key||"Spacebar"===t.key){if("valid"===l)return void r.confirmConnect(e.id,{preventDefault:()=>t.preventDefault(),stopPropagation:()=>t.stopPropagation()});t.preventDefault(),t.stopPropagation(),_(t.currentTarget,t)}},[_,l,r,e.id]),V=(0,a.useCallback)(()=>{r.close(e.id),requestAnimationFrame(()=>{let e=document.querySelector('.window[data-top="true"]')??document.querySelector(".ws-fab");e?.focus({preventScroll:!0})})},[r,e.id]),H=(0,a.useCallback)(()=>{r.minimize(e.id),requestAnimationFrame(()=>{let e=document.querySelector('.window[data-top="true"]')??document.querySelector(".ws-fab");e?.focus({preventScroll:!0})})},[r,e.id]),G="full"===D?L(e.type,e.cfg):null,J="full"===D&&A>=340,X="tiny"===D?{}:{zoom:g},Q={left:e.x,top:e.y,width:e.w,height:e.h,zIndex:e.z};return(0,n.jsxs)("section",{className:"window","aria-label":null!==G?`${c.title} — ${G}`:c.title,"aria-roledescription":"window","data-top":t?"true":"false","data-max":e.max?"true":"false","data-conn":l??void 0,"data-dragging":p?"true":void 0,"data-window-id":e.id,style:Q,tabIndex:-1,onPointerDown:t=>{"valid"===l&&r.confirmConnect(e.id,t),O(t.target)},onFocusCapture:()=>{t||window.setTimeout(()=>r.focus(e.id),0)},children:[(0,n.jsxs)("header",{className:"win-head",onPointerDown:z,onDoubleClick:t=>{(function(e){let t=e.target;if(t instanceof Element&&null!==t.closest("button,[role='button']"))return!1;let n=e.currentTarget.getBoundingClientRect(),a=Math.min(210,n.width/2);return e.clientX<n.right-a})(t)&&r.maximize(e.id)},children:[(0,n.jsx)("span",{className:"win-ico",style:{color:!0===c.accent?"var(--accent)":"var(--fg-muted)"},children:(0,n.jsx)(u,{size:14})}),(0,n.jsx)("span",{className:"win-title",children:c.title}),null!==G?(0,n.jsx)("span",{className:"win-sub mono",title:G,children:(0,n.jsx)("span",{className:"win-sub-text",children:G})}):null,(0,n.jsx)("span",{className:"spacer"}),J?(0,n.jsxs)("div",{className:"win-zoom",children:[(0,n.jsx)("button",{type:"button",className:"win-zbtn ui-tip","data-tip":"Zoom content out","aria-label":`Zoom ${c.title} content out`,disabled:g<=.5,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation()},onClick:()=>F(g-.1),children:(0,n.jsx)(j.Icons.zoomOut,{size:13})}),(0,n.jsxs)("button",{type:"button",className:"win-zpct ui-tip","data-tip":"Reset content zoom to 100%","aria-label":`${String(Math.round(100*g))}% — reset ${c.title} content zoom`,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation()},onClick:()=>r.update(e.id,{zoom:1}),children:[Math.round(100*g),"%"]}),(0,n.jsx)("button",{type:"button",className:"win-zbtn ui-tip","data-tip":"Zoom content in","aria-label":`Zoom ${c.title} content in`,disabled:g>=2,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation()},onClick:()=>F(g+.1),children:(0,n.jsx)(j.Icons.zoomIn,{size:13})})]}):null,(0,n.jsxs)("div",{className:"win-traffic",role:"group","aria-label":`${c.title} window controls`,children:[(0,n.jsx)("button",{type:"button",className:"win-traffic-btn win-traffic-minimize ui-tip","data-tip":"Minimize","aria-label":`Minimize ${c.title} window`,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation()},onClick:H,children:(0,n.jsx)(j.Icons.minimize,{size:17})}),(0,n.jsx)("button",{type:"button",className:"win-traffic-btn win-traffic-maximize ui-tip","data-tip":e.max?"Restore":"Full screen","aria-label":e.max?`Restore ${c.title} window`:`Full screen ${c.title} window`,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation()},onClick:()=>r.maximize(e.id),children:e.max?(0,n.jsx)(j.Icons.restore,{size:17}):(0,n.jsx)(j.Icons.maximize,{size:17})}),(0,n.jsx)("button",{type:"button",className:"win-traffic-btn win-traffic-close ui-tip","data-tip":"Close","aria-label":`Close ${c.title} window`,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation()},onClick:V,children:(0,n.jsx)(j.Icons.close,{size:17})})]})]}),(0,n.jsx)("div",{ref:h,className:"win-body","data-mode":D,style:X,children:q}),e.max?null:eC.map(e=>(0,n.jsx)("div",{className:`wz wz-${e}`,onPointerDown:K(e)},e)),!e.max&&d?eI.map(e=>(0,n.jsx)("button",{type:"button",className:`win-port wp-${e}`,title:"Click to connect to another window","aria-label":`Connect ${c.title} from ${"t"===e?"top":"r"===e?"right":"b"===e?"bottom":"left"} edge`,onPointerDown:U,onKeyDown:W},`p${e}`)):null]})}let e$=[/\bsk-[A-Za-z0-9_-]{20,}\b/,/\bAKIA[0-9A-Z]{16}\b/,/\bgh[pousr]_[A-Za-z0-9]{36,}\b/,/\bxox[abporsu]-[A-Za-z0-9-]{10,}\b/,/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/,/-----BEGIN [A-Z ]*PRIVATE KEY-----/],eA=/\b(?:\d[ -]?){13,19}\b/g;e.i(47167);let eT={chat:{lifecycle:["draft","streaming","final","archived"],trustBoundary:["ui","model","evidence"],authority:"user-confirm",persistence:"durable.ui"},chatHistory:{lifecycle:["live","archived"],trustBoundary:["ui"],authority:"user-confirm",persistence:"durable.ui"},memoria:{lifecycle:["live","needs-review","archived"],trustBoundary:["ui","memory"],authority:"user-confirm",persistence:"memory-reference"},files:{lifecycle:["connecting","connected","degraded","disconnected","error"],trustBoundary:["ui","fs"],authority:"user",persistence:"fs-reference"},connector:{lifecycle:["connecting","connected","degraded","disconnected","error"],trustBoundary:["ui","fs"],authority:"user",persistence:"fs-reference"},localKnowledge:{lifecycle:["idle","connecting","connected","degraded","disconnected","error"],trustBoundary:["ui","fs","model"],authority:"user-confirm",persistence:"durable.ui"},editor:{lifecycle:["viewing","editing","unsaved","saved","error"],trustBoundary:["ui","fs"],authority:"user",persistence:"fs-reference"},browser:{lifecycle:["idle","live","error"],trustBoundary:["ui","network"],authority:"user-confirm",persistence:"transient"},terminal:{lifecycle:["idle","running","blocked","cancelled","error"],trustBoundary:["ui","tool"],authority:"user-confirm",persistence:"transient"},review:{lifecycle:["proposed","needs-review","applied","reverted","archived"],trustBoundary:["ui","evidence"],authority:"user-confirm",persistence:"evidence-reference"},agents:{lifecycle:["proposed","running","blocked","needs-review","verified","cancelled"],trustBoundary:["ui","model","tool","evidence"],authority:"user-confirm",persistence:"durable.ui"},integ:{lifecycle:["idle","connecting","connected","degraded","disconnected","error"],trustBoundary:["ui","network"],authority:"user-confirm",persistence:"durable.config"},keiko:{lifecycle:["live"],trustBoundary:["ui","memory"],authority:"user",persistence:"memory-reference"},settings:{lifecycle:["viewing","editing","saved"],trustBoundary:["ui"],authority:"user",persistence:"durable.config"},project:{lifecycle:["none","connecting","connected","disconnected"],trustBoundary:["ui","fs"],authority:"user",persistence:"durable.config"},search:{lifecycle:["idle","searching","results","error"],trustBoundary:["ui","fs"],authority:"read-only",persistence:"transient"},plugins:{lifecycle:["idle","installed","disabled","enabled"],trustBoundary:["ui"],authority:"user",persistence:"durable.config"},automations:{lifecycle:["idle","enabled","disabled"],trustBoundary:["ui"],authority:"user",persistence:"durable.config"},mobile:{lifecycle:["paired","unpaired","error"],trustBoundary:["ui","network"],authority:"user-confirm",persistence:"durable.config"},inspector:{lifecycle:["empty","focused"],trustBoundary:["ui"],authority:"ui-only",persistence:"transient"},activity:{lifecycle:["live","archived"],trustBoundary:["ui"],authority:"read-only",persistence:"transient"},notifications:{lifecycle:["unread","read","dismissed"],trustBoundary:["ui"],authority:"ui-only",persistence:"transient"},resources:{lifecycle:["live"],trustBoundary:["ui"],authority:"read-only",persistence:"transient"},quality:{lifecycle:["idle","running","results","error"],trustBoundary:["ui","model","evidence"],authority:"user-confirm",persistence:"evidence-reference"},promptEnhancer:{lifecycle:["idle","running","results","error"],trustBoundary:["ui","model","evidence"],authority:"user-confirm",persistence:"transient"},qiRun:{lifecycle:["running","final","needs-review","verified","failed","cancelled"],trustBoundary:["ui","model","evidence"],authority:"user-confirm",persistence:"evidence-reference"},relationships:{lifecycle:["idle","live","degraded","blocked","error"],trustBoundary:["ui","evidence"],authority:"user-confirm",persistence:"durable.ui"},figma:{lifecycle:["idle","running","results","error"],trustBoundary:["ui","evidence","network"],authority:"user-confirm",persistence:"evidence-reference"},figmaView:{lifecycle:["idle","results","error"],trustBoundary:["ui","evidence"],authority:"user-confirm",persistence:"evidence-reference"},figmaJson:{lifecycle:["idle","results","error"],trustBoundary:["ui","evidence"],authority:"user-confirm",persistence:"evidence-reference"},figmaImage:{lifecycle:["idle","results","error"],trustBoundary:["ui","evidence","model"],authority:"user-confirm",persistence:"evidence-reference"}},eL=["apikey","accesskey","clientsecret","credential","password","privatekey","secret","token"],eP=["api_key=","apikey=","client_secret=","clientsecret=","credential=","authorization:","password=","secret=","token="],eM=[".env",".env.local",".env.development",".env.test",".env.production"],eD={chat:["chatId"],editor:["openFiles","layoutJson"],files:["activeFilePath","activeDirectoryPath","resolvedRoot"],figma:["snapshotRunId","selectedScreenIdsJson","selectedScreenName"],figmaView:["snapshotRunId","selectedScreenIdsJson","selectedScreenName"],figmaJson:["snapshotRunId","screenId","selectedScreenIdsJson","selectedScreenName"],figmaImage:["snapshotRunId","screenId","selectedScreenName","imageSrc"]};function eq(e){return"number"==typeof e&&Number.isFinite(e)}function eF(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function eO(e){let t=e.trim();if(0===t.length)return!1;let n=t.toLowerCase();return function(e){for(let t of e$)if(t.test(e))return!0;for(let t of e.matchAll(eA)){let e=t[0].replaceAll(/[ -]/g,"");if(e.length>=13&&e.length<=19&&function(e){let t=0,n=!1;for(let a=e.length-1;a>=0;a-=1){let l=Number(e[a]);n&&(l*=2)>9&&(l-=9),t+=l,n=!n}return t%10==0}(e))return!0}return!1}(t)||function(e){let t="bearer ",n=e.toLowerCase().indexOf(t);if(-1===n)return!1;let a=0;for(let l=n+t.length;l<e.length&&0!==(e[l]??"").trim().length;l+=1)a+=1;return a>=8}(t)||function(e){if(!e.includes("://"))return!1;try{let t=new URL(e);return t.username.length>0||t.password.length>0}catch{return!1}}(t)||eP.some(e=>n.includes(e))||function(e){let t=e.toLowerCase().replaceAll("\\","/").split("/");for(let e=0;e<t.length;e+=1){let n=t[e]??"",a=t[e+1]??"";if(eM.includes(n)||".npmrc"===n||"credentials.json"===n||".aws"===n&&"credentials"===a||".ssh"===n&&a.startsWith("id_"))return!0}return!1}(t)}function ez(e){if(0===e.length||e.length>256||e.startsWith(".")||e.trim()!==e||eO(e))return!1;for(let t of e)if(!function(e){let t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||46===t||95===t||45===t}(t))return!1;return!0}function eK(e){if(0===e.length||e.length>256||e.trim()!==e||eO(e))return!1;for(let t of e){let e=t.charCodeAt(0),n=e>=48&&e<=57,a=e>=65&&e<=90,l=e>=97&&e<=122,i=46===e||58===e||95===e||45===e;if(!n&&!a&&!l&&!i)return!1}return!0}function eB(e){if(!Array.isArray(e)||0===e.length)return;let t=[];for(let n of e){if("string"!=typeof n)return;let e=n.trim().replace(/\\/gu,"/").replace(/^\/+/u,"");if(!(0===e.length||e.length>512||eO(e)||t.includes(e))&&(t.push(e),t.length>=64))break}return t.length>0?t:void 0}function e_(e){let t=[];for(let n of e){let e=function(e){var t;if(!eF(e)||!("string"==typeof(t=e.type)&&t in E))return null;let n=e.type;if("transient"===eT[n].persistence||"string"!=typeof e.id||!eq(e.x)||!eq(e.y)||!eq(e.w)||!eq(e.h)||!eq(e.z)||"boolean"!=typeof e.max)return null;let a={id:e.id,type:n,x:e.x,y:e.y,w:e.w,h:e.h,z:e.z,cfg:function(e,t){if(!eF(t)||"durable.config"===eT[e].persistence)return{};let n=new Set([...(E[e].config??[]).map(e=>e.key),...eD[e]??[]]),a={};for(let[l,i]of Object.entries(t)){if(!n.has(l))continue;let t=function(e,t,n){let a;if("editor"===e&&"openFiles"===t)return eB(n);if("editor"===e&&"layoutJson"===t)return function(e){let t;if("string"!=typeof e||0===e.length)return;try{t=JSON.parse(e)}catch{return}if("object"!=typeof t||null===t||Array.isArray(t))return;let n=t;if(2===n.schemaVersion||2===n.version){let e=eF(n.panes)?n.panes:{},t={};for(let[n,a]of Object.entries(e)){if(!eF(a))continue;let e="string"==typeof a.activeFile?a.activeFile.trim():"",l=eB(a.openFiles),i=eB(a.tabOrder)??l;if(void 0===l&&0===e.length)continue;let r=l??eB([e]);void 0!==r&&(t[n.slice(0,48)]={id:n.slice(0,48),activeFile:e.length>0?e.replace(/\\/gu,"/").replace(/^\/+/u,""):r[0],openFiles:r,tabOrder:i??r})}let a=new Set(Object.keys(t)),l=e=>{if(!eF(e))return null;if("pane"===e.type&&"string"==typeof e.paneId&&a.has(e.paneId))return{type:"pane",paneId:e.paneId};if("split"===e.type){let t=l(e.first),n=l(e.second);if(null===t||null===n)return null;let a="number"==typeof e.ratio&&Number.isFinite(e.ratio)?Math.min(85,Math.max(15,Math.round(e.ratio))):50;return{type:"split",id:"string"==typeof e.id?e.id.slice(0,48):"split-1",direction:"column"===e.direction?"column":"row",ratio:a,first:t,second:n}}return null},i=l(n.tree),r=Object.keys(t)[0];if(null===i||void 0===r)return;let s="string"==typeof n.activePaneId&&a.has(n.activePaneId)?n.activePaneId:r,o="number"==typeof n.sidebarWidth&&Number.isFinite(n.sidebarWidth)?Math.min(440,Math.max(180,Math.round(n.sidebarWidth))):260;return JSON.stringify({schemaVersion:2,root:"string"==typeof n.root?n.root:"",activePaneId:s,tree:i,panes:t,sidebarWidth:o,sidebarCollapsed:!0===n.sidebarCollapsed})}let a=Array.isArray(n.panes)?n.panes.slice(0,2):[],l=[];for(let[e,t]of a.entries()){if("object"!=typeof t||null===t||Array.isArray(t))return;let n="string"==typeof t.file?t.file.trim():"",a=eB(t.openFiles);if(n.length>512||eO(n))continue;let i=a??(n.length>0?eB([n]):void 0);void 0!==i&&l.push({id:"string"==typeof t.id&&t.id.trim().length>0?t.id.trim().slice(0,32):`pane-${e+1}`,file:n.length>0?n.replace(/\\/gu,"/").replace(/^\/+/u,""):i[0],openFiles:i})}if(0===l.length)return;let i="column"===n.direction?"column":"row",r="number"==typeof n.splitRatio&&Number.isFinite(n.splitRatio)?Math.min(75,Math.max(25,Math.round(n.splitRatio))):50,s="number"==typeof n.sidebarWidth&&Number.isFinite(n.sidebarWidth)?Math.min(440,Math.max(180,Math.round(n.sidebarWidth))):260,o="string"==typeof n.activePaneId&&l.some(e=>e.id===n.activePaneId)?n.activePaneId:l[0].id;return JSON.stringify({version:1,panes:l,activePaneId:o,direction:i,splitRatio:r,sidebarWidth:s,sidebarCollapsed:!0===n.sidebarCollapsed})}(n);if("figma"===e||"figmaView"===e||"figmaJson"===e||"figmaImage"===e)return function(e,t){if("string"==typeof t){if("snapshotRunId"===e)return ez(t)?t:void 0;if("screenId"===e)return eK(t)?t:void 0;if("imageSrc"===e)return/^\/api\/figma\/snapshots\/[^/?#]+\/screens\/\d+\/image$/u.test(t)?t:void 0;if("selectedScreenIdsJson"===e){let e;try{e=JSON.parse(t)}catch{return}if(!Array.isArray(e)||0===e.length||e.length>16)return;let n=[];for(let t of e){if("string"!=typeof t)return;let e=t.trim();if(!eK(e))return;n.push(e)}return JSON.stringify(n)}if("selectedScreenName"===e){if(t.length>256||eO(t))return;return t}}}(t,n);if("string"!=typeof n&&"number"!=typeof n&&"boolean"!=typeof n||(a=function(e){let t="";for(let n of e.toLowerCase())(n>="a"&&n<="z"||n>="0"&&n<="9")&&(t+=n);return t}(t),eL.some(e=>a.includes(e))))return;if("string"!=typeof n)return n;let l=eT[e].persistence;return"evidence-reference"===l?ez(n)?n:void 0:eO(n)?"durable.ui"===l?"[REDACTED]":void 0:n}(e,l,i);void 0!==t&&(a[l]=t)}return a}(n,e.cfg),max:e.max},l=function(e){if(eF(e)&&eq(e.x)&&eq(e.y)&&eq(e.w)&&eq(e.h))return{x:e.x,y:e.y,w:e.w,h:e.h}}(e.prev);return{...a,...!0===e.minimized?{minimized:!0}:{},...void 0!==l?{prev:l}:{},...eq(e.zoom)?{zoom:e.zoom}:{}}}(n);null!==e&&t.push("figma"!==e.type||void 0===function(e){let t=e.selectedScreenIdsJson;if("string"==typeof t)try{let e=JSON.parse(t);if(!Array.isArray(e))return;let n=e[0];return"string"==typeof n&&n.length>0?n:void 0}catch{return}}(e.cfg)?e:{...e,type:"figmaView",cfg:{...e.cfg}})}let n=t.filter(e=>"figma"===e.type);if(n.length<=1)return t;let a=n.reduce((e,t)=>t.z>e.z?t:e);return t.filter(e=>"figma"!==e.type||e.id===a.id)}function eU(e,t){let n=new Set(t.map(e=>e.id)),a=[];for(let t of e){if("string"!=typeof t.id||"string"!=typeof t.a||"string"!=typeof t.b||!n.has(t.a)||!n.has(t.b))continue;let e="string"==typeof t.boundRoot&&t.boundRoot.length>0,l="workspace-root"===t.boundScopeKind||"directory"===t.boundScopeKind||"files"===t.boundScopeKind,i="string"==typeof t.boundRelativePath&&t.boundRelativePath.length>0,r="string"==typeof t.boundChatWindowId&&t.boundChatWindowId.length>0&&n.has(t.boundChatWindowId),s=("capsule"===t.boundConnectorKind||"capsule-set"===t.boundConnectorKind)&&"string"==typeof t.boundConnectorId&&t.boundConnectorId.length>0;a.push({id:t.id,a:t.a,b:t.b,...r?{boundChatWindowId:t.boundChatWindowId}:{},...e?{boundRoot:t.boundRoot}:{},...l?{boundScopeKind:t.boundScopeKind}:{},...i?{boundRelativePath:t.boundRelativePath}:{},...s?{boundConnectorKind:t.boundConnectorKind,boundConnectorId:t.boundConnectorId}:{}})}return a}function eW(e,t,n,a,l){return{x:e.x+Math.max(16,Math.min(l+26*a,e.w-t-16)),y:e.y+Math.max(16,Math.min(l+26*a,e.h-n-16))}}function eV(e){let{prev:t,...n}=e;return n}function eH(e,t,n){return e.some(e=>e.a===t&&e.b===n||e.a===n&&e.b===t)}function eY(e,t){return e?.type==="chat"?e.id:t?.type==="chat"?t.id:null}function eG(e){return e.length>0&&(e.startsWith("/")||/^[A-Za-z]:[/\\]/u.test(e))}function eJ(e){return/^[A-Za-z]:[/\\]?$/u.test(e)?e.replace(/\\/gu,"/"):e.replace(/\\/gu,"/").replace(/\/+$/u,"")}function eX(e){if("files"!==e.type)return null;let t=e.cfg.resolvedRoot,n=e.cfg.root,a="string"==typeof t&&t.length>0?t:"string"==typeof n&&n.length>0?n:null;return null!==a&&eG(a)?a:null}function eQ(e){return e.replace(/\\/gu,"/").replace(/^\/+/u,"").replace(/\/+$/u,"")}function eZ(e,t){return void 0!==e.root&&void 0!==t.root&&eJ(e.root)===eJ(t.root)&&e.kind===t.kind&&e.relativePaths.length===t.relativePaths.length&&e.relativePaths.every((e,n)=>eQ(e)===eQ(t.relativePaths[n]??""))}function e0(e,t,n){let a="files"===e.type?e:"files"===t.type?t:null,l="chat"===e.type?e:"chat"===t.type?t:null;if(null===a||null===l)return null;let i=eX(a);if(null===i)return null;let r=a.cfg.activeFilePath;if("string"==typeof r&&r.length>0)return{kind:"files",relativePaths:[eQ(r)],root:eJ(i),connectedAtMs:n};let s=a.cfg.activeDirectoryPath;return"string"==typeof s&&s.length>0?{kind:"directory",relativePaths:[eQ(s)],root:eJ(i),connectedAtMs:n}:{kind:"workspace-root",relativePaths:[],root:eJ(i),connectedAtMs:n}}function e1(e){if("string"!=typeof e.boundRoot||0===e.boundRoot.length)return null;let t=Date.now();return"directory"===e.boundScopeKind?"string"!=typeof e.boundRelativePath||0===e.boundRelativePath.length?null:{kind:"directory",relativePaths:[eQ(e.boundRelativePath)],root:eJ(e.boundRoot),connectedAtMs:t}:"files"===e.boundScopeKind?"string"!=typeof e.boundRelativePath||0===e.boundRelativePath.length?null:{kind:"files",relativePaths:[eQ(e.boundRelativePath)],root:eJ(e.boundRoot),connectedAtMs:t}:{kind:"workspace-root",relativePaths:[],root:eJ(e.boundRoot),connectedAtMs:t}}function e2(e){return Math.max(e.maxConnectedSources,e.maxLocalKnowledgeSources)}function e4(e,t){return e.filter(e=>!eZ(e,t))}function e3(e){return e.connectedScopes??(void 0!==e.connectedScope?[e.connectedScope]:[])}function e6(e){return e.localKnowledgeScopes??(void 0!==e.localKnowledgeScope?[e.localKnowledgeScope]:[])}function e5(e){return"capsule"===e.kind?`capsule:${e.capsuleId}`:`set:${e.capsuleSetId}`}function e8(e){return"string"!=typeof e.boundConnectorId||0===e.boundConnectorId.length?null:"capsule"===e.boundConnectorKind?{kind:"capsule",capsuleId:e.boundConnectorId,connectedAtMs:0}:"capsule-set"===e.boundConnectorKind?{kind:"capsule-set",capsuleSetId:e.boundConnectorId,connectedAtMs:0}:null}function e7(e,t){let n="connector"===e.type?e:"connector"===t.type?t:null,a="chat"===e.type?e:"chat"===t.type?t:null;if(null===n||null===a)return null;let l=n.cfg.selectedKind,i=n.cfg.selectedId;if("string"!=typeof l||"string"!=typeof i)return null;let r=i.trim();return 0===r.length?null:"capsule"===l?{kind:"capsule",capsuleId:r,connectedAtMs:Date.now()}:"capsule-set"===l?{kind:"capsule-set",capsuleSetId:r,connectedAtMs:Date.now()}:null}let e9="keiko.workspace.v4",te="keiko.conns.v1",tt="keiko.view";function tn(){try{let e=window.localStorage.getItem(tt);if(null===e)return{zoom:1,x:0,y:0};let t=JSON.parse(e);if("object"==typeof t&&null!==t&&"zoom"in t&&"number"==typeof t.zoom)return{zoom:t.zoom,x:"number"==typeof t.x?t.x:0,y:"number"==typeof t.y?t.y:0}}catch{}return{zoom:1,x:0,y:0}}function ta(e){return Math.max(.3,Math.min(2.5,e))}function tl(e){return Math.max(.5,Math.min(2,Math.round(10*e)/10))}function ti(e){let t=null;for(let n=0;n<e.length;n++){let a=e[n];if(!0!==a.minimized){if(null===t){t=a;continue}a.z>t.z&&(t=a)}}return t}function tr(e,t){try{window.localStorage.setItem(e,JSON.stringify(t))}catch{}}function ts(e){let t=e.deltaMode===WheelEvent.DOM_DELTA_LINE?16:2===e.deltaMode?800:1;return{x:e.deltaX*t,y:e.deltaY*t}}let to={Equal:"=",NumpadAdd:"+",Minus:"-",NumpadSubtract:"-",Digit0:"0",Numpad0:"0"},tc="application/x-keiko-local-knowledge-connector",td="keiko:local-knowledge-connector-drop";function tu(e){if(!Array.from(e.types).includes(tc))return null;try{let t=JSON.parse(e.getData(tc));if("object"!=typeof t||null===t||"capsule"!==t.kind||"string"!=typeof t.id||0===t.id.trim().length)return null;let n="string"==typeof t.label?t.label.trim():"",a="string"==typeof t.lifecycleState?t.lifecycleState.trim():"";return{kind:"capsule",id:t.id.trim(),...n.length>0?{label:n}:{},...a.length>0?{lifecycleState:a}:{}}}catch{return null}}let tp="application/x-keiko-figma-view",tm="keiko:figma-view-drop";function th(e){return"string"==typeof e&&e.trim().length>0?e.trim():null}function tf(e){if(!Array.from(e.types).includes(tp))return null;try{let t=JSON.parse(e.getData(tp));if("object"!=typeof t||null===t)return null;let n=th(t.snapshotRunId),a=th(t.screenId),l=th(t.name);if(null===n||null===a||null===l)return null;return{snapshotRunId:n,screenId:a,name:l}}catch{return null}}let tg="application/x-keiko-figma-json",tv="keiko:figma-json-drop";function tb(e){return"string"==typeof e&&e.trim().length>0?e.trim():null}function tx(e){if(!Array.from(e.types).includes(tg))return null;try{let t=JSON.parse(e.getData(tg));if("object"!=typeof t||null===t)return null;let n=tb(t.snapshotRunId),a=tb(t.screenId),l=tb(t.name);if(null===n||null===a||null===l)return null;let i=tb(t.sourceWindowId);return{snapshotRunId:n,screenId:a,name:l,...null!==i?{sourceWindowId:i}:{}}}catch{return null}}let ty="application/x-keiko-figma-image",tw="keiko:figma-image-drop";function tj(e){return"string"==typeof e&&e.trim().length>0?e.trim():null}function tk(e){if(!Array.from(e.types).includes(ty))return null;try{let t=JSON.parse(e.getData(ty));if("object"!=typeof t||null===t)return null;let n=tj(t.snapshotRunId),a=tj(t.screenId),l=tj(t.name),i=tj(t.imageSrc);if(null===n||null===a||null===l||null===i||!/^\/api\/figma\/snapshots\/[^/?#]+\/screens\/\d+\/image$/u.test(i))return null;let r=tj(t.sourceWindowId);return{snapshotRunId:n,screenId:a,name:l,imageSrc:i,...null!==r?{sourceWindowId:r}:{}}}catch{return null}}let tN={w:260,h:220},tS={w:360,h:360},tC={w:520,h:540},tI={w:560,h:420};function tE({clientX:e,clientY:t,rect:n,view:a,size:l=tN}){return{x:Math.round((e-n.left-a.x)/a.zoom-l.w/2),y:Math.round((t-n.top-a.y)/a.zoom-28)}}function tR(e,t){let n=e+t;return e<1&&n>1||e>1&&n<1?1:n}function t$(e,t,n){t.preventDefault();let a=t.currentTarget;a.setPointerCapture?.(t.pointerId);let l=t.clientX,i=t.clientY,r=Y();n(!0);let s=t=>{e(t.clientX-l,t.clientY-i),l=t.clientX,i=t.clientY},o=()=>{window.removeEventListener("pointermove",s),window.removeEventListener("pointerup",o),window.removeEventListener("pointercancel",o),n(!1),a.hasPointerCapture?.(t.pointerId)===!0&&a.releasePointerCapture?.(t.pointerId),r()};window.addEventListener("pointermove",s),window.addEventListener("pointerup",o),window.addEventListener("pointercancel",o)}function tA({wins:e,connecting:t,conns:l}){let[i,r]=(0,a.useState)(""),s=(0,a.useRef)(null),o=(0,a.useRef)(l.length);return(0,a.useEffect)(()=>{let n=s.current;s.current=t;let a=o.current;if(o.current=l.length,null===n&&null!==t){let n=e?.find(e=>e.id===t.from),a=void 0!==n?E[n.type].title:"window";r(`Connecting from ${a} — select a highlighted window, press Escape to cancel`);return}if(null!==n&&null===t)if(l.length>a){let t=l[l.length-1],n=void 0!==t?e?.find(e=>e.id===t.a):void 0,a=void 0!==t?e?.find(e=>e.id===t.b):void 0;r(void 0!==n&&void 0!==a?`Connected: ${A(n,a)}`:"Connected")}else r("Connection cancelled")},[t,l,e]),(0,n.jsx)("div",{className:"sr-only","aria-live":"polite",children:i})}function tT({ws:e,wsRef:t,openPalette:l,palette:i}){let{wins:r,view:s,snapPrev:o,conns:c,connecting:d,api:u}=e,[p,m]=(0,a.useState)(!1),[h,f]=(0,a.useState)(!1),g=(0,a.useRef)(!1),v=(0,a.useMemo)(()=>null===r?null:r.filter(e=>!0!==e.minimized),[r]),b=function(e){if(null===e||0===e.length)return null;let t=null;for(let n=0;n<e.length;n++){let a=e[n];if(!0!==a.minimized){if(null===t){t=a;continue}a.z>t.z&&(t=a)}}return t}(v),x=null!==d&&null!==v?v.find(e=>e.id===d.from)??null:null;(0,a.useEffect)(()=>{let e=e=>{g.current=e,f(e)},t=t=>{var n;!("Space"!==t.code||(n=t.target)instanceof Element&&null!==n.closest("input,textarea,select,button,a[href],summary,[contenteditable='true'],[contenteditable=''],[role='button'],[role='checkbox'],[role='dialog'],[role='link'],[role='menuitem'],[role='option'],[role='radio'],[role='switch'],[role='tab']"))&&(t.preventDefault(),g.current||e(!0))},n=t=>{"Space"===t.code&&e(!1)},a=()=>{e(!1)};return window.addEventListener("keydown",t),window.addEventListener("keyup",n),window.addEventListener("blur",a),()=>{window.removeEventListener("keydown",t),window.removeEventListener("keyup",n),window.removeEventListener("blur",a)}},[]);let y=(0,a.useMemo)(()=>({backgroundSize:`${String(22*s.zoom)}px ${String(22*s.zoom)}px`,backgroundPosition:`${String(s.x)}px ${String(s.y)}px`}),[s]),w=(0,a.useMemo)(()=>({transform:`translate(${String(s.x/s.zoom)}px, ${String(s.y/s.zoom)}px)`,transformOrigin:"0 0",zoom:s.zoom}),[s]),k=(0,a.useCallback)((e,t,n,a)=>{let l=u.add("connector",{presentation:"node",selectedKind:e.kind,selectedId:e.id,...void 0!==e.label?{selectedLabel:e.label}:{},...void 0!==e.lifecycleState?{selectedState:e.lifecycleState}:{}});null!==l&&u.update(l,{...tE({clientX:t,clientY:n,rect:a,view:s}),...tN})},[u,s]),N=(0,a.useCallback)((e,t,n,a)=>{let l=u.add("figmaView",{snapshotRunId:e.snapshotRunId,selectedScreenIdsJson:JSON.stringify([e.screenId]),selectedScreenName:e.name});null!==l&&u.update(l,{...tE({clientX:t,clientY:n,rect:a,view:s,size:tS}),...tS})},[u,s]),S=(0,a.useCallback)(e=>{if(null===r)return[];let t=new Map(r.map(e=>[e.id,e])),n=[];for(let a of c){let l=a.a===e?a.b:a.b===e?a.a:null;if(null===l)continue;let i=t.get(l);i?.type==="quality"&&n.push({connId:a.id,qualityId:i.id})}return n},[c,r]),C=(0,a.useCallback)((e,t,n,a)=>{let l=u.add("figmaJson",{snapshotRunId:e.snapshotRunId,screenId:e.screenId,selectedScreenIdsJson:JSON.stringify([e.screenId]),selectedScreenName:e.name});if(null===l||(u.update(l,{...tE({clientX:t,clientY:n,rect:a,view:s,size:tC}),...tC}),void 0===e.sourceWindowId))return;let i=S(e.sourceWindowId);if(0!==i.length){for(let e of i)u.removeConn(e.connId);window.setTimeout(()=>{for(let e of i)u.connect(l,e.qualityId)},0)}},[u,S,s]),I=(0,a.useCallback)((e,t,n,a)=>{let l=u.add("figmaImage",{snapshotRunId:e.snapshotRunId,screenId:e.screenId,selectedScreenName:e.name,imageSrc:e.imageSrc});if(null===l||(u.update(l,{...tE({clientX:t,clientY:n,rect:a,view:s,size:tI}),...tI}),void 0===e.sourceWindowId))return;let i=S(e.sourceWindowId);if(0!==i.length){for(let e of i)u.removeConn(e.connId);window.setTimeout(()=>{for(let e of i)u.connect(l,e.qualityId)},0)}},[u,S,s]);(0,a.useEffect)(()=>{let e=e=>{if(!(e instanceof CustomEvent)||!function(e){if("object"!=typeof e||null===e)return!1;let t=e.payload;return"number"==typeof e.clientX&&"number"==typeof e.clientY&&"object"==typeof t&&null!==t&&"capsule"===t.kind&&"string"==typeof t.id}(e.detail))return;let n=t.current?.getBoundingClientRect();if(void 0===n)return;let{clientX:a,clientY:l,payload:i}=e.detail;a<n.left||a>n.right||l<n.top||l>n.bottom||k(i,a,l,n)};return window.addEventListener(td,e),()=>{window.removeEventListener(td,e)}},[k,t]),(0,a.useEffect)(()=>{let e=e=>{if(!(e instanceof CustomEvent)||!function(e){if("object"!=typeof e||null===e)return!1;let t=e.payload;return"number"==typeof e.clientX&&"number"==typeof e.clientY&&"object"==typeof t&&null!==t&&"string"==typeof t.snapshotRunId&&"string"==typeof t.screenId&&"string"==typeof t.name}(e.detail))return;let n=t.current?.getBoundingClientRect();if(void 0===n)return;let{clientX:a,clientY:l,payload:i}=e.detail;a<n.left||a>n.right||l<n.top||l>n.bottom||N(i,a,l,n)};return window.addEventListener(tm,e),()=>{window.removeEventListener(tm,e)}},[N,t]),(0,a.useEffect)(()=>{let e=e=>{if(!(e instanceof CustomEvent)||!function(e){if("object"!=typeof e||null===e)return!1;let t=e.payload;return"number"==typeof e.clientX&&"number"==typeof e.clientY&&"object"==typeof t&&null!==t&&"string"==typeof t.snapshotRunId&&"string"==typeof t.screenId&&"string"==typeof t.name&&(void 0===t.sourceWindowId||"string"==typeof t.sourceWindowId)}(e.detail))return;let n=t.current?.getBoundingClientRect();if(void 0===n)return;let{clientX:a,clientY:l,payload:i}=e.detail;a<n.left||a>n.right||l<n.top||l>n.bottom||C(i,a,l,n)};return window.addEventListener(tv,e),()=>{window.removeEventListener(tv,e)}},[C,t]),(0,a.useEffect)(()=>{let e=e=>{if(!(e instanceof CustomEvent)||!function(e){if("object"!=typeof e||null===e)return!1;let t=e.payload;return"number"==typeof e.clientX&&"number"==typeof e.clientY&&"object"==typeof t&&null!==t&&"string"==typeof t.snapshotRunId&&"string"==typeof t.screenId&&"string"==typeof t.name&&"string"==typeof t.imageSrc&&(void 0===t.sourceWindowId||"string"==typeof t.sourceWindowId)}(e.detail))return;let n=t.current?.getBoundingClientRect();if(void 0===n)return;let{clientX:a,clientY:l,payload:i}=e.detail;a<n.left||a>n.right||l<n.top||l>n.bottom||I(i,a,l,n)};return window.addEventListener(tw,e),()=>{window.removeEventListener(tw,e)}},[I,t]);let E=null!==r&&0===r.length,R=r?.some(e=>e.max)??!1;return(0,n.jsxs)("main",{className:"workspace",ref:t,"aria-label":"Workspace surface",tabIndex:0,"data-window-maxed":R?"true":void 0,"data-canvas-overlays-hidden":R?"true":"false","data-connecting":null!==d?"true":void 0,"data-panning":p?"true":void 0,"data-hand-tool":h?"true":void 0,onPointerDownCapture:e=>{var t;if(U())return;if(g.current&&B(e)&&null===d&&!((t=e.target)instanceof Element&&null!==t.closest("input, textarea, select, [contenteditable='true'], [contenteditable='']"))&&!_(e.target)){t$(u.panBy,e,m),e.stopPropagation();return}if(0!==e.button||null===d||null===x||null===v)return;let n=function(e){if(!(e instanceof Element))return;let t=e.closest(".window[data-window-id]");return t?.dataset.windowId}(e.target);if(void 0===n||n===x.id)return;let a=v.find(e=>e.id===n);void 0!==a&&$(x.type,a.type)&&u.confirmConnect(a.id,e)},onPointerDown:e=>{if(!(U()||_(e.target))){var t;if(null!==d){B(e)&&u.cancelConnect();return}(B(t=e)||1===t.button)&&t$(u.panBy,e,m)}},onKeyDown:e=>{if(e.target!==e.currentTarget)return;let t=e.shiftKey?192:48;switch(e.key){case"ArrowLeft":u.panBy(t,0);break;case"ArrowRight":u.panBy(-t,0);break;case"ArrowUp":u.panBy(0,t);break;case"ArrowDown":u.panBy(0,-t);break;default:return}e.preventDefault()},onDragOver:e=>{(null!==tu(e.dataTransfer)||null!==tf(e.dataTransfer)||null!==tx(e.dataTransfer)||null!==tk(e.dataTransfer))&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")},onDrop:e=>{let t=tu(e.dataTransfer),n=tf(e.dataTransfer),a=tx(e.dataTransfer),l=tk(e.dataTransfer);if(null===t&&null===n&&null===a&&null===l)return;e.preventDefault(),e.stopPropagation();let i=e.currentTarget.getBoundingClientRect();null!==t?k(t,e.clientX,e.clientY,i):null!==n?N(n,e.clientX,e.clientY,i):null!==a?C(a,e.clientX,e.clientY,i):null!==l&&I(l,e.clientX,e.clientY,i)},children:[(0,n.jsx)(ew,{}),(0,n.jsx)("div",{className:"ws-grid",style:y,"aria-hidden":"true"}),(0,n.jsx)(tA,{wins:v,connecting:d,conns:c}),null!==d?(0,n.jsx)("div",{className:"ws-connect-hint","aria-hidden":"true",children:"Click a highlighted window to connect — Esc to cancel"}):null,E?(0,n.jsx)("div",{className:"ws-empty",children:(0,n.jsx)(K,{onNewWindow:l})}):null,(0,n.jsxs)("div",{className:"ws-scene",style:w,children:[null!==o?(0,n.jsx)("div",{className:"snap-ghost",style:{left:o.x,top:o.y,width:o.w,height:o.h}}):null,null!==v?(0,n.jsx)(eS,{wins:v,conns:c,connecting:d,api:u}):null,null!==v?v.map(e=>(0,n.jsx)(eR,{win:e,top:null!==b&&e.id===b.id,connState:null===x?null:e.id===x.id?"source":$(x.type,e.type)?"valid":"invalid",view:s,api:u,wsRef:t},e.id)):null]}),(0,n.jsxs)("div",{className:"ws-zoom",children:[(0,n.jsx)("button",{type:"button",className:"ws-zoom-btn ui-tip cmp-tip-start",onClick:()=>u.zoomTo(tR(s.zoom,-.2)),disabled:s.zoom<=.3,"aria-label":"Zoom out","data-tip":"Zoom out",children:(0,n.jsx)(j.Icons.zoomOut,{size:15})}),(0,n.jsx)("button",{type:"button",className:"ws-zoom-btn ui-tip cmp-tip-start",onClick:u.fitView,disabled:null===v||0===v.length,"aria-label":"Fit workspace to windows","data-tip":"Fit workspace to windows",children:(0,n.jsx)(j.Icons.expand,{size:15})}),(0,n.jsxs)("button",{type:"button",className:"ws-zoom-pct mono ui-tip",onClick:u.resetView,"aria-label":`${String(Math.round(100*s.zoom))}% — reset`,"data-tip":"Reset",children:[Math.round(100*s.zoom),"%"]}),(0,n.jsx)("button",{type:"button",className:"ws-zoom-btn ui-tip cmp-tip-end",onClick:()=>u.zoomTo(tR(s.zoom,.2)),disabled:s.zoom>=2.5,"aria-label":"Zoom in","data-tip":"Zoom in",children:(0,n.jsx)(j.Icons.zoomIn,{size:15})})]}),(0,n.jsx)("button",{type:"button",className:"ws-fab ui-tip cmp-tip-end",onPointerDown:e=>e.stopPropagation(),onClick:l,"aria-label":"New window","data-tip":"New window",children:(0,n.jsx)(j.Icons.add,{size:20})}),R?null:i??null]})}function tL({commands:e,onClose:t}){let[l,i]=(0,a.useState)(""),[r,s]=(0,a.useState)(0),o=(0,a.useRef)(null),c=(0,a.useRef)(null),d=(0,a.useRef)(null);(0,a.useEffect)(()=>(c.current=document.activeElement,()=>{c.current?.focus?.()}),[]),(0,a.useEffect)(()=>{o.current?.focus()},[]);let u=(0,a.useMemo)(()=>{let t=l.toLowerCase();return e.filter(e=>`${e.label} ${e.group??""}`.toLowerCase().includes(t))},[e,l]);(0,a.useEffect)(()=>{s(0)},[l]),(0,a.useEffect)(()=>{document.getElementById(`cmdk-row-${String(r)}`)?.scrollIntoView?.({block:"nearest"})},[r,u]);let p=e=>{void 0!==e&&(e.run(),t())};return(0,n.jsx)("div",{className:"cmdk-overlay",onPointerDown:t,children:(0,n.jsxs)("div",{ref:d,className:"cmdk",role:"dialog","aria-modal":"true","aria-labelledby":"cmdk-title","aria-describedby":"cmdk-desc",tabIndex:-1,onPointerDown:e=>e.stopPropagation(),onKeyDown:e=>{if("Tab"===e.key){let t=Array.from(d.current?.querySelectorAll("button:not([disabled]),input:not([disabled]),[tabindex]:not([tabindex='-1'])")??[]);if(t.length>0){let n=t[0],a=t[t.length-1];if(e.shiftKey&&document.activeElement===n){e.preventDefault(),a.focus();return}if(!e.shiftKey&&document.activeElement===a){e.preventDefault(),n.focus();return}}}if("ArrowDown"===e.key){e.preventDefault(),s(e=>Math.min(u.length-1,e+1));return}if("ArrowUp"===e.key){e.preventDefault(),s(e=>Math.max(0,e-1));return}if("Enter"===e.key){e.preventDefault(),p(u[r]);return}"Escape"===e.key&&t()},children:[(0,n.jsx)("h2",{id:"cmdk-title",className:"sr-only",children:"Command palette"}),(0,n.jsx)("p",{id:"cmdk-desc",className:"sr-only",children:"Search commands and press Enter to run the selected action."}),(0,n.jsxs)("div",{className:"cmdk-input",children:[(0,n.jsx)(j.Icons.search,{size:16}),(0,n.jsx)("input",{ref:o,role:"combobox","aria-expanded":"true","aria-controls":"cmdk-list","aria-activedescendant":u.length>0?`cmdk-row-${String(r)}`:void 0,"aria-label":"Command query",placeholder:"Type a command…",value:l,onChange:e=>i(e.target.value)}),(0,n.jsx)("span",{className:"kbd",children:"esc"})]}),(0,n.jsx)("div",{className:"sr-only",role:"status",children:0===u.length?"No matching commands":`${String(u.length)} command${1===u.length?"":"s"}`}),(0,n.jsxs)("div",{id:"cmdk-list",role:"listbox",className:"cmdk-list",children:[0===u.length&&(0,n.jsx)("div",{className:"cmdk-empty",children:"No matching commands"}),u.map((e,t)=>{var a;let l;return(0,n.jsxs)("div",{role:"option",id:`cmdk-row-${String(t)}`,"aria-selected":t===r,className:"cmdk-row","data-sel":t===r,tabIndex:-1,onMouseEnter:()=>s(t),onClick:()=>p(e),children:[(0,n.jsx)("span",{className:"cmdk-ico",children:(a=e.icon,l=j.Icons[a]??j.Icons.spark,(0,n.jsx)(l,{size:16}))}),(0,n.jsx)("span",{className:"cmdk-label",children:e.label}),(0,n.jsx)("span",{className:"spacer"}),void 0!==e.shortcut&&(0,n.jsx)("span",{className:"kbd",children:e.shortcut}),void 0!==e.group&&(0,n.jsx)("span",{className:"cmdk-group mono",children:e.group})]},e.id)})]})]})})}var tP=e.i(74080);function tM(e){return Array.from(new Set(e.split(/[\n,]/u).map(e=>e.trim()).filter(e=>e.length>0)))}function tD({onCancel:e,preserveExisting:t=!1,storedApiKeyHeaderName:l,storedModels:i=[]}){let r=(0,a.useRef)(null),s=(0,a.useRef)(null),o=(0,a.useRef)(null),c=(0,a.useRef)(null),d=(0,a.useRef)(void 0),[u,p]=(0,a.useState)(""),[m,h]=(0,a.useState)(""),[f,g]=(0,a.useState)(""),[v,b]=(0,a.useState)(""),[x,y]=(0,a.useState)(""),[k,N]=(0,a.useState)(""),[S,C]=(0,a.useState)(!1),[I,E]=(0,a.useState)(),[R,$]=(0,a.useState)(),[A,T]=(0,a.useState)();async function L(e){if(e.preventDefault(),!S){var n;C(!0),E(void 0),$(void 0),T(void 0),r.current?.focus();try{let e=tM(v);if(function(e){try{return new URL(e.trim()).hostname.endsWith(".services.ai.azure.com")}catch{return!1}}(u)&&0===e.length){E("Azure AI Foundry requires deployment names. Paste the names from the Deployments tab."),C(!1);return}let a=tM(x),l=!t||""!==u.trim()||""!==m.trim()||""!==f.trim()||e.length>0||a.length>0,i=""!==k.trim(),r=await (0,w.setupGateway)({baseUrl:""===u.trim()?void 0:u.trim(),apiKey:""===m.trim()?void 0:m.trim(),apiKeyHeaderName:""===f.trim()?void 0:f.trim(),deploymentNames:e,preserveExisting:t,...0===a.length?{}:{imageInputModelIds:a},...""===k.trim()?{}:{figmaAccessToken:k.trim()}}),s=r.testedModelIds.length,o=(n=r.skippedModelIds??[],0===n.length?"":` Could not verify deployment${1===n.length?"":"s"}: ${n.join(", ")}.`);C(!1),i&&!l?T("Verified Figma access token. Reloading Keiko…"):i?T(`Verified ${String(s)} workflow chat model${1===s?"":"s"} and Figma access token. Reloading Keiko…${o}`):T(`Verified ${String(s)} workflow chat model${1===s?"":"s"}. Reloading Keiko…${o}`),d.current=window.setTimeout(()=>window.location.reload(),0===(r.skippedModelIds??[]).length?800:1800)}catch(t){let e=t instanceof w.ApiError?{message:t.message,code:t.code}:t instanceof Error?{message:t.message}:{message:"The gateway could not be configured."};E(e.message),$(e.code),C(!1)}}}(0,a.useEffect)(()=>{let e=document.documentElement,n=Number(e.dataset.keikoModalOpenCount??"0");e.dataset.keikoModalOpenCount=String(n+1),e.setAttribute("data-keiko-modal-open","true");let a=Number(e.dataset.keikoGatewaySetupOpenCount??"0");return e.dataset.keikoGatewaySetupOpenCount=String(a+1),e.setAttribute("data-keiko-gateway-setup-open","true"),c.current=document.activeElement,t?o.current?.focus():s.current?.focus(),()=>{void 0!==d.current&&window.clearTimeout(d.current);let t=Math.max(0,Number(e.dataset.keikoModalOpenCount??"1")-1);0===t?(delete e.dataset.keikoModalOpenCount,e.removeAttribute("data-keiko-modal-open")):e.dataset.keikoModalOpenCount=String(t);let n=Math.max(0,Number(e.dataset.keikoGatewaySetupOpenCount??"1")-1);0===n?(delete e.dataset.keikoGatewaySetupOpenCount,e.removeAttribute("data-keiko-gateway-setup-open")):e.dataset.keikoGatewaySetupOpenCount=String(n),c.current?.focus?.()}},[t]),(0,a.useEffect)(()=>{let t=r.current;if(null===t)return;let n=n=>{if("Escape"===n.key){if(S||void 0!==A||void 0===e)return;n.preventDefault(),e();return}if("Tab"!==n.key)return;let a=Array.from(t.querySelectorAll("button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),summary,[tabindex]:not([tabindex='-1'])"));if(0===a.length)return;let l=a[0],i=a[a.length-1];n.shiftKey&&document.activeElement===l?(n.preventDefault(),i.focus()):n.shiftKey||document.activeElement!==i||(n.preventDefault(),l.focus())};return t.addEventListener("keydown",n),()=>t.removeEventListener("keydown",n)},[S,e,A]),(0,a.useEffect)(()=>{void 0===I||S||(t&&""===u.trim()&&""===m.trim()?o.current?.focus():s.current?.focus())},[m,u,S,I,t]);let P=tM(v),M=tM(x),D=!t,q=""!==u.trim()||""!==m.trim()||""!==f.trim()||P.length>0||M.length>0,F=""!==k.trim(),O=!S&&void 0===A&&(D?""!==u.trim()&&""!==m.trim():q||F),z=i.map(e=>e.id),K=z.slice(0,6),B=Math.max(0,z.length-K.length),_=(0,n.jsxs)("div",{className:"gw-grid",children:[(0,n.jsxs)("label",{className:"gw-field gw-span-2",children:[(0,n.jsxs)("span",{children:["Base URL ",t?(0,n.jsx)("span",{className:"dlg-opt",children:"leave blank to keep"}):null]}),(0,n.jsx)("input",{className:"gw-input mono",value:u,placeholder:t?"Only enter a value to replace the stored gateway URL":"https://llm-gateway.example.com/v1",autoComplete:"off",disabled:S||void 0!==A,ref:s,onChange:e=>p(e.target.value)})]}),(0,n.jsxs)("label",{className:"gw-field",children:[(0,n.jsxs)("span",{children:["API token ",t?(0,n.jsx)("span",{className:"dlg-opt",children:"leave blank to keep"}):null]}),(0,n.jsx)("input",{className:"gw-input mono",type:"password",value:m,placeholder:t?"Only enter a value to replace the stored token":"Paste your API token",autoComplete:"off",disabled:S||void 0!==A,onChange:e=>h(e.target.value)})]}),(0,n.jsxs)("label",{className:"gw-field",children:[(0,n.jsxs)("span",{children:["API key header ",(0,n.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,n.jsx)("input",{className:"gw-input mono",value:f,placeholder:t?"Leave blank to keep stored header":"Authorization",autoComplete:"off",disabled:S||void 0!==A,onChange:e=>g(e.target.value)})]}),(0,n.jsxs)("label",{className:"gw-field",children:[(0,n.jsx)("span",{children:"Deployment names for Azure"}),(0,n.jsx)("textarea",{className:"gw-input gw-textarea mono",value:v,placeholder:"Paste deployment names, one per line",autoComplete:"off",disabled:S||void 0!==A,onChange:e=>b(e.target.value)})]}),(0,n.jsxs)("label",{className:"gw-field",children:[(0,n.jsxs)("span",{children:["Image-input models ",(0,n.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,n.jsx)("textarea",{className:"gw-input gw-textarea mono",value:x,placeholder:"Paste image-capable model names, one per line",autoComplete:"off",disabled:S||void 0!==A,onChange:e=>y(e.target.value)})]})]}),U=(0,n.jsx)("div",{className:"gw-setup-backdrop",role:"presentation",children:(0,n.jsx)("div",{ref:r,className:"gw-setup",role:"dialog","aria-modal":"true","aria-labelledby":"gw-setup-title","aria-describedby":"gw-setup-desc",tabIndex:-1,children:(0,n.jsxs)("form",{className:"gw-form",onSubmit:e=>void L(e),children:[(0,n.jsxs)("div",{className:"gw-head",children:[(0,n.jsxs)("div",{className:"gw-setup-badge",children:[(0,n.jsx)(j.Icons.cube,{size:18}),t?"Credential update":"Model gateway setup"]}),(0,n.jsx)("h1",{id:"gw-setup-title",children:t?"Update Keiko credentials":"Connect Keiko to your internal LLMs"}),(0,n.jsx)("p",{id:"gw-setup-desc",children:t?"Leave stored gateway fields blank to keep the current value. Keiko never returns existing secrets to the browser.":"Keiko needs the internal gateway URL and API token before chat and agent workflows can run. The token is tested once and stored only on this machine."})]}),(0,n.jsxs)("section",{className:"gw-section","aria-labelledby":"gw-model-section-title",children:[(0,n.jsx)("div",{className:"gw-section-head",children:(0,n.jsxs)("div",{children:[(0,n.jsx)("h2",{id:"gw-model-section-title",children:"Model gateway"}),(0,n.jsx)("p",{children:t?"Blank gateway fields keep the stored value.":"Base URL and API token are required."})]})}),t?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"gw-current","aria-label":"Stored model gateway credentials",children:[(0,n.jsxs)("div",{className:"gw-current-row",children:[(0,n.jsx)("span",{children:"Gateway URL"}),(0,n.jsx)("strong",{children:"Stored"})]}),(0,n.jsxs)("div",{className:"gw-current-row",children:[(0,n.jsx)("span",{children:"API token"}),(0,n.jsx)("strong",{className:"mono",children:"••••••••••••"})]}),(0,n.jsxs)("div",{className:"gw-current-row",children:[(0,n.jsx)("span",{children:"API key header"}),(0,n.jsx)("strong",{className:"mono",children:l??"authorization"})]}),(0,n.jsxs)("div",{className:"gw-current-models",children:[(0,n.jsx)("span",{children:"Configured models"}),(0,n.jsxs)("div",{className:"gw-model-chips",children:[0===K.length?(0,n.jsx)("strong",{children:"Stored"}):K.map(e=>(0,n.jsx)("strong",{className:"mono",children:e},e)),B>0?(0,n.jsxs)("strong",{children:["+",B.toString()]}):null]})]})]}),(0,n.jsxs)("details",{className:"gw-replace",children:[(0,n.jsx)("summary",{children:"Replace model gateway settings"}),_]})]}):_]}),(0,n.jsxs)("section",{className:"gw-section","aria-labelledby":"gw-figma-section-title",children:[(0,n.jsx)("div",{className:"gw-section-head",children:(0,n.jsxs)("div",{children:[(0,n.jsx)("h2",{id:"gw-figma-section-title",children:"Figma Snapshot"}),(0,n.jsx)("p",{children:"Optional connector credential."})]})}),(0,n.jsxs)("label",{className:"gw-field",children:[(0,n.jsxs)("span",{children:["Figma access token ",(0,n.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,n.jsx)("input",{className:"gw-input mono",type:"password",value:k,placeholder:t?"Stored Figma token is kept when blank":"Paste a read-only Figma PAT when needed",autoComplete:"off",disabled:S||void 0!==A,ref:o,onChange:e=>N(e.target.value)})]})]}),(0,n.jsx)("div",{className:"gw-note",children:"Stored secrets stay local and are never returned to the browser. Supported API-key headers: Authorization, X-Litellm-Key, X-Api-Key, api-key."}),void 0!==I?(0,n.jsxs)("div",{className:"gw-error",role:"alert",children:[I,void 0!==R?(0,n.jsx)("div",{className:"gw-error-code mono",children:R}):null]}):null,void 0!==A?(0,n.jsx)("div",{className:"gw-success",role:"status",children:A}):null,S?(0,n.jsx)("div",{className:"gw-pending",role:"status",children:"Testing credentials…"}):null,(0,n.jsx)("span",{id:"gw-submit-requirements",className:"visually-hidden",children:t?"Enter at least one field to update. Blank stored gateway fields keep their current value.":"Base URL and API token are required. The Figma access token is optional."}),(0,n.jsxs)("div",{className:"gw-actions",children:[void 0!==e?(0,n.jsx)("button",{className:"gw-cancel",type:"button",disabled:S||void 0!==A,onClick:e,children:"Cancel"}):null,(0,n.jsx)("button",{className:"gw-submit",type:"submit",disabled:!O,"aria-busy":S,"aria-describedby":"gw-submit-requirements",children:S?"Testing credentials…":"Test & save"})]})]})})});return"u"<typeof document?U:(0,tP.createPortal)(U,document.body)}function tq(e){return e.findIndex(e=>!0!==e.disabled)}function tF(e,t,n){if(0===e.length)return -1;let a=t;for(let t=0;t<e.length;t+=1)if(a=(a+n+e.length)%e.length,e[a]?.disabled!==!0)return a;return -1}function tO({active:e,index:t,onCommit:l,onOptionKeyDown:i,option:r,setOptionRef:s}){let o=(0,a.useRef)(null),c=(0,a.useRef)(null),d=(0,a.useRef)(null),[u,p]=(0,a.useState)(null),m=()=>{null!==d.current&&(clearTimeout(d.current),d.current=null),p(null)},h=()=>{null!==d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{let e=c.current,t=o.current;if(null===e||null===t||e.scrollWidth<=e.clientWidth)return;let n=t.getBoundingClientRect(),a=Math.min(520,window.innerWidth-32),l=n.right+8+a<=window.innerWidth-16?"top-left":"top-right";p({left:"top-left"===l?n.right+8:n.left-8,placement:l,top:n.top-6})},1500)};return(0,a.useEffect)(()=>m,[]),(0,n.jsxs)("button",{ref:e=>{o.current=e,s(t,e)},"aria-selected":e,className:`ksel-option${e?" ksel-option-active":""}`,"data-disabled":!0===r.disabled?"true":void 0,disabled:r.disabled,onBlur:m,onClick:()=>l(r),onFocus:h,onKeyDown:e=>i(e,t),onPointerEnter:h,onPointerLeave:m,role:"option",type:"button",children:[(0,n.jsxs)("span",{className:"ksel-option-copy",children:[(0,n.jsx)("span",{className:"ksel-option-label",ref:c,children:r.label}),void 0!==r.description?(0,n.jsx)("span",{className:"ksel-option-desc",children:r.description}):null]}),void 0!==r.badge?(0,n.jsx)("span",{className:"ksel-option-badge",children:r.badge}):null,null!==u?(0,tP.createPortal)((0,n.jsx)("div",{className:"ksel-overflow-tooltip","data-placement":u.placement,role:"tooltip",style:{left:`${u.left.toString()}px`,top:`${u.top.toString()}px`},children:r.label}),document.body):null]})}function tz({value:e,sections:t,onValueChange:l,disabled:i=!1,placeholder:r="Select an option",ariaLabel:s,ariaDescribedBy:o,ariaLabelledBy:c,triggerClassName:d,menuClassName:u,menuTitle:p,menuCountLabel:m,showMenuHeader:h=!0,leadingVisual:f,mono:g=!1,showChevron:v=!0,menuMinWidth:b,attached:x=!0,triggerStyle:y,autoFocus:w=!1}){let j=(0,a.useRef)(null),k=(0,a.useRef)(null),N=(0,a.useRef)([]),S=(0,a.useId)(),[C,I]=(0,a.useState)(!1),[E,R]=(0,a.useState)(-1),[$,A]=(0,a.useState)(null),[T,L]=(0,a.useState)(!1),P=(0,a.useMemo)(()=>t.flatMap((e,t)=>e.options.map((n,a)=>({...n,key:`${e.label??"section"}-${t.toString()}-${n.value}-${a.toString()}`,sectionLabel:e.label}))),[t]),M=P.findIndex(t=>t.value===e),D=-1===M?null:P[M],q=D?.label??r,F=D?.description??null,O=()=>{I(!1),R(-1)},z=e=>{if(i||0===P.length)return;let t=void 0!==e&&P[e]?.disabled!==!0?e:M>=0&&P[M]?.disabled!==!0?M:tq(P);I(!0),R(t)};function K(e){e.disabled||(l(e.value),O(),j.current?.focus())}function B(e,t){if("Escape"===e.key){e.preventDefault(),O(),j.current?.focus();return}if("Tab"===e.key)return void O();if("ArrowDown"===e.key){e.preventDefault(),R(tF(P,t,1));return}if("ArrowUp"===e.key){e.preventDefault(),R(tF(P,t,-1));return}if("Home"===e.key){e.preventDefault(),R(tq(P));return}if("End"===e.key){e.preventDefault(),R(tF(P,0,-1));return}if("Enter"===e.key||" "===e.key){e.preventDefault();let n=P[t];void 0!==n&&K(n)}}(0,a.useEffect)(()=>{if(!C)return;let e=e=>{let t=e.target;null!==j.current&&t instanceof Node&&j.current.contains(t)||null!==k.current&&t instanceof Node&&k.current.contains(t)||O()},t=()=>O();return window.addEventListener("pointerdown",e,!0),window.addEventListener("blur",t),()=>{window.removeEventListener("pointerdown",e,!0),window.removeEventListener("blur",t)}},[C]),(0,a.useLayoutEffect)(()=>{if(!C||null===j.current)return;let e=()=>{let e=j.current?.getBoundingClientRect();if(void 0===e)return;let t=Math.min(void 0!==b&&e.width<Math.min(b,96)?b:e.width,window.innerWidth-32),n=x&&1>Math.abs(t-e.width),a=n?-1:6,l=window.innerHeight-e.bottom-16,i=e.top-16,r=l<Math.max(96,2*e.height)&&i>l;L(r);let s=r?i:l,o=50*!!h+2,c=Math.max(e.height,Math.min(Math.max(e.height,s-o),380)),d=c+o,u=window.getComputedStyle(j.current);A({left:Math.min(Math.max(16,e.left),window.innerWidth-t-16),width:t,top:r?Math.max(16,e.top-d-a):Math.min(e.bottom+a,window.innerHeight-16-d),optionHeight:Math.max(28,Math.min(e.height,30)),maxHeight:c,openUp:r,attached:n,fontFamily:u.fontFamily,fontSize:u.fontSize,fontWeight:u.fontWeight,letterSpacing:u.letterSpacing,lineHeight:u.lineHeight})};return e(),window.addEventListener("resize",e),window.addEventListener("scroll",e,!0),()=>{window.removeEventListener("resize",e),window.removeEventListener("scroll",e,!0)}},[C,x,b,h]),(0,a.useLayoutEffect)(()=>{if(!C||null===$||!$.openUp||null===j.current||null===k.current)return;let e=j.current.getBoundingClientRect(),t=k.current.getBoundingClientRect();if(t.height<=0)return;let n=$.attached?-1:6,a=Math.max(16,e.top-t.height-n);.5>Math.abs(a-$.top)||A(e=>null===e?e:{...e,top:a})},[C,$]),(0,a.useEffect)(()=>{C&&!(E<0)&&(N.current[E]?.focus(),N.current[E]?.scrollIntoView({block:"nearest"}))},[C,E]),(0,a.useEffect)(()=>{if(!C)return;let e=e=>{if("Escape"===e.key){O(),j.current?.focus();return}if(1===e.key.length&&!e.metaKey&&!e.ctrlKey&&!e.altKey){var t;if((t=e.target)instanceof HTMLElement&&("INPUT"===t.tagName||"TEXTAREA"===t.tagName||"SELECT"===t.tagName||t.isContentEditable))return;let n=e.key.toLowerCase(),a=E>=0?E:M>=0?M:0;for(let e=1;e<=P.length;e+=1){let t=(a+e)%P.length,l=P[t];if(void 0!==l&&!0!==l.disabled&&l.label.toLowerCase().startsWith(n)){R(t);break}}}};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[C,E,P,M]);let _=["ksel-trigger",g?"mono":"",d??"",C?"ksel-trigger-open":"",C&&$?.attached===!0?T?"ksel-trigger-open-up":"ksel-trigger-open-down":"",i?"ksel-trigger-disabled":""].filter(e=>e.length>0).join(" "),U=C&&null!==$?(0,tP.createPortal)((0,n.jsxs)("div",{ref:k,className:["ksel-menu",$.attached?"ksel-menu-attached":"",$.openUp?"ksel-menu-open-up":"ksel-menu-open-down",u??""].filter(e=>e.length>0).join(" "),style:{left:`${$.left.toString()}px`,top:`${$.top.toString()}px`,width:`${$.width.toString()}px`,"--ksel-option-height":`${$.optionHeight.toString()}px`,fontFamily:$.fontFamily,fontSize:$.fontSize,fontWeight:$.fontWeight,letterSpacing:$.letterSpacing,lineHeight:$.lineHeight},children:[h?(0,n.jsxs)("div",{className:"ksel-menu-head",children:[(0,n.jsx)("div",{className:"ksel-menu-title",children:p??s??r}),(0,n.jsx)("div",{className:"ksel-menu-note",children:m??`${P.length.toString()} options`})]}):null,(0,n.jsx)("div",{className:"ksel-menu-scroll",role:"listbox",id:S,style:{maxHeight:`${$.maxHeight.toString()}px`},children:t.map((e,t)=>(0,n.jsxs)("div",{className:"ksel-section",children:[void 0!==e.label?(0,n.jsx)("div",{className:"ksel-section-label",children:e.label}):null,e.options.map(t=>{let a=P.findIndex(n=>n.value===t.value&&n.sectionLabel===e.label),l=a===M,i=P[a];return void 0===i?null:(0,n.jsx)(tO,{active:l,index:a,onCommit:K,onOptionKeyDown:B,option:i,setOptionRef:(e,t)=>{N.current[e]=t}},`${e.label??"section"}-${t.value}`)})]},`${e.label??"section"}-${t.toString()}`))})]}),document.body):null;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("button",{ref:j,"aria-controls":S,"aria-describedby":o,"aria-expanded":C,"aria-haspopup":"listbox","aria-label":s,"aria-labelledby":c,autoFocus:w,className:_,disabled:i,onClick:()=>{C?O():z()},onKeyDown:function(e){if(!i){if("ArrowDown"===e.key||"ArrowUp"===e.key){e.preventDefault(),z(M>=0?M:tq(P));return}("Enter"===e.key||" "===e.key)&&(e.preventDefault(),C?O():z())}},role:"combobox",style:y,type:"button",children:[void 0!==f?(0,n.jsx)("span",{className:"ksel-trigger-leading",children:f}):null,(0,n.jsxs)("span",{className:"ksel-trigger-copy",children:[(0,n.jsx)("span",{className:"ksel-trigger-label",children:q}),null!==F?(0,n.jsx)("span",{className:"ksel-trigger-desc",children:F}):null]}),v?(0,n.jsx)("span",{"aria-hidden":"true",className:`ksel-trigger-caret${C?" ksel-trigger-caret-open":""}`,children:(0,n.jsx)("svg",{fill:"none",height:"12",viewBox:"0 0 12 12",width:"12",children:(0,n.jsx)("path",{d:"M2.25 4.5 6 8.25 9.75 4.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.5"})})}):null]}),U]})}let tK=[["ask","Ask every action"],["full","Full access"]];function tB({cfg:e,set:t}){let a=!1!==e.keikoMode,l="full"===e.access?"full":"ask",i=a?"No rights by default. You approve while manual; Keiko governs per policy when autonomous.":"full"===l?"Legacy: agent acts without prompts.":"Legacy: you approve each privileged action.";return(0,n.jsxs)("div",{className:"permctl",children:[(0,n.jsxs)("button",{type:"button",className:"perm-toggle","data-on":a,"aria-pressed":a,onClick:()=>t("keikoMode",!a),children:[(0,n.jsx)("img",{className:"perm-orca",src:"/assets/keiko-logo.svg",alt:""}),(0,n.jsxs)("span",{className:"perm-tt",children:[(0,n.jsx)("span",{className:"perm-name",children:"Keiko-Mode"}),(0,n.jsx)("span",{className:"perm-desc",children:"Zero standing rights · Keiko governs"})]}),(0,n.jsx)("span",{className:"perm-sw"+(a?" on":""),children:(0,n.jsx)("span",{})})]}),!a&&(0,n.jsx)("div",{className:"perm-legacy",children:tK.map(([e,a])=>(0,n.jsx)("button",{type:"button",className:"perm-opt","data-on":l===e,"aria-pressed":l===e,onClick:()=>t("access",e),children:a},e))}),(0,n.jsx)("div",{className:"perm-note",children:i})]})}function t_(e){return"chat"===e.kind&&e.toolCalling&&e.structuredOutput}function tU(e){if(e instanceof w.ApiError){if("BAD_ROOT"===e.code)return"Enter an absolute folder path.";if("DENIED"===e.code)return"That location is excluded."}return e instanceof Error?e.message:"Unable to read directories."}function tW({value:e,projectId:t,selectProjectRoot:l=!1,onSelect:i,onClose:r}){let[s,o]=(0,a.useState)(null),[c,d]=(0,a.useState)(e),[u,p]=(0,a.useState)(!1),[m,h]=(0,a.useState)(null),f=t??e.trim(),g=(0,a.useCallback)(async e=>{if(0===f.length){o(null),h("Enter an absolute folder path.");return}p(!0),h(null);try{let t=await (0,w.fetchFilesDirectories)(f,e);o(t),d(t.path)}catch(e){h(tU(e))}finally{p(!1)}},[f]);return(0,a.useEffect)(()=>{g(e.length>0?e:void 0)},[]),(0,n.jsxs)("div",{className:"dir-picker",role:"group","aria-label":"Directory picker",children:[(0,n.jsxs)("div",{className:"dir-top",children:[(0,n.jsx)("input",{className:"dlg-input mono dir-path",value:c,"aria-label":"Folder path",placeholder:"/absolute/folder/path",onChange:e=>d(e.target.value),onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),e.stopPropagation(),g(c))}}),(0,n.jsx)("button",{type:"button",className:"dlg-btn dir-go",onClick:()=>void g(c),children:"Go"})]}),null!==s?(0,n.jsx)("div",{className:"dir-roots",children:s.roots.map(e=>(0,n.jsx)("button",{type:"button",className:"dir-chip",onClick:()=>void g(e.path),children:e.label},`${e.label}:${e.path}`))}):null,(0,n.jsxs)("div",{className:"dir-list",children:[s?.parent!==null&&s?.parent!==void 0?(0,n.jsxs)("button",{type:"button",className:"dir-row",onClick:()=>void g(s.parent??void 0),children:[(0,n.jsx)(j.Icons.back,{size:14}),(0,n.jsx)("span",{children:"Parent directory"})]}):null,s?.entries.map(e=>(0,n.jsxs)("button",{type:"button",className:"dir-row",onClick:()=>void g(e.path),children:[(0,n.jsx)(j.Icons.folder,{size:14}),(0,n.jsx)("span",{children:e.name})]},e.path)),u?(0,n.jsx)("div",{className:"dir-note",role:"status",children:"Loading directories…"}):null,u||null===s||0!==s.entries.length?null:(0,n.jsx)("div",{className:"dir-note",children:"No child directories."}),null!==m?(0,n.jsx)("div",{className:"dir-error",role:"alert",children:m}):null]}),(0,n.jsxs)("div",{className:"dir-actions",children:[(0,n.jsx)("button",{type:"button",className:"dlg-btn",onClick:r,children:"Close"}),(0,n.jsx)("button",{type:"button",className:"dlg-btn dlg-primary",onClick:()=>{null!==s&&(i(l?s.roots[0]?.path??s.path:s.path),r())},disabled:null===s,children:"Use directory"})]})]})}let tV=[{id:"unit-test-generation",label:"Unit Test Agent",scope:"Source file"},{id:"bug-investigation",label:"Bugfix Agent",scope:"Bug report"}];function tH(e){return e.filter(e=>e.available).map(e=>e.path)}function tY(e){return e.split(/[\n,]/u).map(e=>e.trim()).filter(e=>e.length>0)}function tG(e){let t=tJ(e.trim()).replace(/\/+$/u,""),n=t.lastIndexOf("/");return n>0?t.slice(0,n):""}function tJ(e){return e.replaceAll("\\","/")}function tX(e,t){let n=tJ(t.trim());if(0===n.length)return"";let a=tJ(e.trim()).replace(/\/+$/u,"");if(0===a.length)return n;if(n===a)return".";let l=`${a}/`;return n.startsWith(l)?n.slice(l.length):n}function tQ({root:e,value:t,onSelect:l,onClose:i}){let r=tX(e,t),[s,o]=(0,a.useState)(tG(r)),[c,d]=(0,a.useState)(r),[u,p]=(0,a.useState)([]),[m,h]=(0,a.useState)(!1),[f,g]=(0,a.useState)(!1),[v,b]=(0,a.useState)(null);(0,a.useEffect)(()=>{if(0===e.trim().length){p([]),h(!1),g(!1),b("Select a repository first.");return}let t=!1;return g(!0),b(null),(0,w.fetchFilesTree)(e.trim(),s).then(e=>{t||(p(e.entries),h(e.truncated))}).catch(e=>{t||(p([]),h(!1),b(tU(e)))}).finally(()=>{t||g(!1)}),()=>{t=!0}},[s,e]);let x=u.filter(e=>"directory"===e.kind),y=u.filter(e=>"directory"!==e.kind);return(0,n.jsxs)("div",{className:"file-picker",role:"group","aria-label":"File picker",children:[(0,n.jsx)("div",{className:"file-picker-head",children:(0,n.jsx)("span",{className:"file-picker-path mono",children:0===s.length?"Repository root":s})}),(0,n.jsxs)("div",{className:"dir-list file-picker-list",children:[s.length>0?(0,n.jsxs)("button",{type:"button",className:"dir-row",onClick:()=>o(tG(s)),children:[(0,n.jsx)(j.Icons.back,{size:14}),(0,n.jsx)("span",{children:"Parent folder"})]}):null,x.map(e=>(0,n.jsxs)("button",{type:"button",className:"dir-row file-picker-row",disabled:!e.readable,onClick:()=>o(e.path),title:e.path,children:[(0,n.jsx)(j.Icons.folder,{size:14}),(0,n.jsx)("span",{children:e.name})]},e.path)),y.map(e=>(0,n.jsxs)("button",{type:"button",className:"dir-row file-picker-row","data-selected":c===e.path?"true":void 0,disabled:!e.readable,"aria-pressed":c===e.path,onClick:()=>d(e.path),title:e.path,children:[(0,n.jsx)(j.Icons.file,{size:14}),(0,n.jsx)("span",{children:e.name}),(0,n.jsx)("span",{className:"file-picker-meta mono",children:function(e){if(!Number.isFinite(e)||e<=0)return"0 B";let t=["B","KB","MB","GB"],n=e,a=0;for(;n>=1024&&a<t.length-1;)n/=1024,a+=1;let l=0===a?n.toFixed(0):n.toFixed(n>=10?1:2);return`${l} ${t[a]}`}(e.sizeBytes)})]},e.path)),f?(0,n.jsx)("div",{className:"dir-note",role:"status",children:"Loading files…"}):null,f||null!==v||0!==u.length?null:(0,n.jsx)("div",{className:"dir-note",children:"No files in this folder."}),m?(0,n.jsxs)("div",{className:"dir-note file-picker-warning",role:"status",children:["Showing only the first ",u.length.toString()," entries."]}):null,null!==v?(0,n.jsx)("div",{className:"dir-error",role:"alert",children:v}):null]}),(0,n.jsxs)("div",{className:"dir-actions",children:[(0,n.jsx)("button",{type:"button",className:"dlg-btn",onClick:i,children:"Close"}),(0,n.jsx)("button",{type:"button",className:"dlg-btn dlg-primary",onClick:()=>{0!==c.trim().length&&(l(tX(e,c)),i())},disabled:0===c.trim().length,children:"Use file"})]})]})}function tZ({filesContext:e,firstRef:t,directoryField:l,setDirectoryField:i,setDialogError:r,onConfirm:s}){let[o,c]=(0,a.useState)("unit-test-generation"),[d,u]=(0,a.useState)(e?.root??""),[p,m]=(0,a.useState)(""),[h,f]=(0,a.useState)([]),[g,v]=(0,a.useState)([]),[b,x]=(0,a.useState)(()=>{var t,n;let a;return t=e?.root??"",{verifyTargetFiles:a=null===(n=e?.activeFilePath??null)?"":tX(t,n),explainFilePath:a,explainQuestion:"",unitFilePath:a,bugDescription:"",bugFailingOutput:"",bugStackTrace:"",bugTargetFiles:a}}),[y,k]=(0,a.useState)(!0),[N,S]=(0,a.useState)(!1),[C,I]=(0,a.useState)(!1),E=d.trim(),R=null!==e&&e.root===E&&void 0!==e.activeFilePath?e.activeFilePath:null,$=E.length>0&&g.includes(E),A=0===E.length?"Repository is required.":0===p.length?"No compatible model is available.":"explain-plan"===o&&0===b.explainFilePath.trim().length?"Explain plan requires a file path.":"unit-test-generation"===o&&0===b.unitFilePath.trim().length?"Unit Test Agent requires a source file.":"bug-investigation"===o&&0===b.bugDescription.trim().length?"Bugfix Agent requires an observed behavior.":null,T=null===A&&$&&!C&&!y,L=tV.find(e=>e.id===o)??tV[0],P="unit-test-generation"===o?"Start Unit Test Agent":"Start Bugfix Agent";(0,a.useEffect)(()=>{let e=!1;return k(!0),r(null),Promise.all([(0,w.fetchModels)(),(0,w.fetchProjects)()]).then(([t,n])=>{if(e)return;let a=t.models.filter(t_);f(a),m(e=>e||(a[0]?.id??"")),v(tH(n.projects))}).catch(t=>{e||r(tU(t))}).finally(()=>{e||k(!1)}),()=>{e=!0}},[r]);let M=e=>{x(t=>({...t,...e}))};(0,a.useEffect)(()=>{if(null===R)return;let e=tX(E,R);x(t=>{let n={};return 0===t.verifyTargetFiles.trim().length&&(n.verifyTargetFiles=e),0===t.explainFilePath.trim().length&&(n.explainFilePath=e),0===t.unitFilePath.trim().length&&(n.unitFilePath=e),0===t.bugTargetFiles.trim().length&&(n.bugTargetFiles=e),0===Object.keys(n).length?t:{...t,...n}})},[R,E]);let D=async()=>{v(tH((await (0,w.fetchProjects)()).projects))},q=async()=>{if(0!==E.length){S(!0),r(null);try{await (0,w.createProject)({path:E}),await D()}catch(e){r(tU(e))}finally{S(!1)}}},F=async()=>{if(!T)return void r(A??"Repository is not registered.");I(!0),r(null);let t=function(e,t,n,a){if("verify"===e){let e=tY(a.verifyTargetFiles).map(e=>tX(t,e));return{taskType:"verify",modelId:n,input:{workspaceRoot:t,...e.length>0?{targetFiles:e}:{}}}}return"explain-plan"===e?{taskType:"explain-plan",modelId:n,input:{workspaceRoot:t,filePath:tX(t,a.explainFilePath),...a.explainQuestion.trim().length>0?{question:a.explainQuestion.trim()}:{}}}:"unit-test-generation"===e?{workflowId:"unit-test-generation",modelId:n,input:{workspaceRoot:t,target:{kind:"file",filePath:tX(t,a.unitFilePath)}}}:{workflowId:"bug-investigation",modelId:n,input:{workspaceRoot:t,report:{...a.bugDescription.trim().length>0?{description:a.bugDescription.trim()}:{},...a.bugFailingOutput.trim().length>0?{failingOutput:a.bugFailingOutput.trim()}:{},...a.bugStackTrace.trim().length>0?{stackTrace:a.bugStackTrace.trim()}:{},...tY(a.bugTargetFiles).length>0?{targetFiles:tY(a.bugTargetFiles).map(e=>tX(t,e))}:{}}}}}(o,E,p,b);try{let n=await (0,w.startRun)(t);s({workflow:o,model:p,runId:n.runId,fingerprint:n.fingerprint,workspaceRoot:E,inputJson:JSON.stringify(t.input),...null!==e&&e.root===E?{__connectFilesId:e.id}:{}})}catch(e){e instanceof w.ApiError&&"WORKSPACE_NOT_REGISTERED"===e.code?(await D().catch(()=>void 0),r("Repository is not registered.")):r(tU(e))}finally{I(!1)}};return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"dlg-agent-grid",children:[(0,n.jsxs)("div",{className:"dlg-field",children:[(0,n.jsx)("span",{className:"dlg-label",children:"Agent"}),(0,n.jsx)("span",{className:"dlg-selwrap",children:(0,n.jsx)(tz,{triggerClassName:"dlg-input",value:o,ariaLabel:"Agent",autoFocus:!0,menuTitle:"Agent",menuCountLabel:`${tV.length.toString()} agents`,sections:[{options:tV.map(e=>({value:e.id,label:e.label}))}],onValueChange:e=>{let t=tV.find(t=>t.id===e);void 0!==t&&c(t.id)}})})]}),(0,n.jsxs)("div",{className:"dlg-field",children:[(0,n.jsx)("span",{className:"dlg-label",children:"Model"}),(0,n.jsx)("span",{className:"dlg-selwrap",children:(0,n.jsx)(tz,{triggerClassName:"dlg-input mono",value:p,ariaLabel:"Model",disabled:0===h.length,menuTitle:"Model",mono:!0,sections:[{options:h.map(e=>({value:e.id,label:e.id}))}],onValueChange:m})})]})]}),(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsx)("span",{className:"dlg-label",children:"Repository"}),(0,n.jsxs)("span",{className:"dlg-dirwrap",children:[(0,n.jsx)("input",{className:"dlg-input mono",value:d,placeholder:"/absolute/repository/path",onClick:()=>i("agentWorkspace"),onChange:e=>u(e.target.value)}),(0,n.jsx)("button",{type:"button",className:"dlg-btn dlg-dirbtn",onClick:()=>i("agentWorkspace"),children:"Browse"})]}),"agentWorkspace"===l?(0,n.jsx)(tW,{value:d,projectId:$?E:void 0,onSelect:u,onClose:()=>i(null)}):null]}),E.length>0&&!$?(0,n.jsxs)("div",{className:"dlg-agent-warning",children:[(0,n.jsx)("span",{children:"Repository is not registered."}),(0,n.jsx)("button",{type:"button",className:"dlg-btn",disabled:N,onClick:()=>void q(),children:N?"Registering…":"Register repository"})]}):null,null!==R?(0,n.jsxs)("button",{type:"button",className:"dlg-current-file",onClick:()=>{if(null===R)return;let e=tX(E,R);"unit-test-generation"===o?M({unitFilePath:e}):M({bugTargetFiles:e})},title:R,children:[(0,n.jsx)(j.Icons.files,{size:13})," Use current file ",(0,n.jsx)("span",{className:"mono",children:R})]}):null,(0,n.jsxs)("div",{className:"dlg-agent-task",children:[(0,n.jsxs)("div",{className:"dlg-agent-task-head",children:[(0,n.jsx)("span",{className:"dlg-agent-task-title",children:L.label}),(0,n.jsx)("span",{className:"dlg-agent-task-scope",children:L.scope})]}),"unit-test-generation"===o?(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsx)("span",{className:"dlg-label",children:"Source file"}),(0,n.jsxs)("span",{className:"dlg-dirwrap",children:[(0,n.jsx)("input",{className:"dlg-input mono",placeholder:"src/file.ts",value:b.unitFilePath,onChange:e=>M({unitFilePath:e.target.value}),onBlur:e=>M({unitFilePath:tX(E,e.target.value)})}),(0,n.jsx)("button",{type:"button",className:"dlg-btn dlg-dirbtn","aria-label":"Browse source file",onClick:()=>i("unitSourceFile"),children:"Browse"})]}),"unitSourceFile"===l?(0,n.jsx)(tQ,{root:E,value:b.unitFilePath,onSelect:e=>M({unitFilePath:e}),onClose:()=>i(null)}):null]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsx)("span",{className:"dlg-label",children:"Observed behavior"}),(0,n.jsx)("textarea",{className:"dlg-input dlg-textarea",rows:2,placeholder:"Describe the observed bug.",value:b.bugDescription,onChange:e=>M({bugDescription:e.target.value})})]}),(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsxs)("span",{className:"dlg-label",children:["Failing output ",(0,n.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,n.jsx)("textarea",{className:"dlg-input dlg-textarea mono",rows:2,value:b.bugFailingOutput,onChange:e=>M({bugFailingOutput:e.target.value})})]}),(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsxs)("span",{className:"dlg-label",children:["Stack trace ",(0,n.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,n.jsx)("textarea",{className:"dlg-input dlg-textarea mono",rows:2,value:b.bugStackTrace,onChange:e=>M({bugStackTrace:e.target.value})})]}),(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsxs)("span",{className:"dlg-label",children:["Related files ",(0,n.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,n.jsx)("textarea",{className:"dlg-input dlg-textarea mono",rows:2,placeholder:"src/file.ts, src/other.ts",value:b.bugTargetFiles,onChange:e=>M({bugTargetFiles:e.target.value}),onBlur:e=>M({bugTargetFiles:tY(e.target.value).map(e=>tX(E,e)).join(", ")})})]})]})]}),(0,n.jsxs)("div",{className:"dlg-agent-actions",children:[(0,n.jsx)("button",{type:"button",className:"dlg-btn dlg-primary",disabled:!T,"aria-busy":C,"aria-describedby":T||C?void 0:"agent-start-validation",onClick:()=>void F(),children:C?"Starting…":P}),y?(0,n.jsx)("span",{id:"agent-start-validation",className:"dlg-note",role:"status",children:"Loading models and projects…"}):null,y||null===A?null:(0,n.jsx)("span",{id:"agent-start-validation",className:"dlg-note",role:"status",children:A})]})]})}function t0({type:e,types:t,filesContext:l=null,onConfirm:i,onClose:r}){let s=t[e],o=s.config??[],[c,d]=(0,a.useState)(()=>(function(e){let t={};for(let n of e)t[n.key]=n.def??"";return t})(o)),[u,p]=(0,a.useState)(!1),[m,h]=(0,a.useState)(null),[f,g]=(0,a.useState)(null),v=(0,a.useRef)(null),b=(0,a.useRef)(null),x=(0,a.useRef)(null);(0,a.useEffect)(()=>(x.current=document.activeElement,()=>{let e=x.current;null!==e&&e.isConnected?e.focus():requestAnimationFrame(()=>{(document.querySelector('.window[data-top="true"]')??document.querySelector(".ws-fab")??document.body).focus({preventScroll:!0})})}),[]),(0,a.useEffect)(()=>{let e=requestAnimationFrame(()=>{p(!0),(v.current??b.current)?.focus()});return()=>cancelAnimationFrame(e)},[]),(0,a.useEffect)(()=>{let e=e=>{"Escape"===e.key&&r()};return window.addEventListener("keydown",e),()=>{window.removeEventListener("keydown",e)}},[r]),(0,a.useEffect)(()=>{if("files"!==e&&"editor"!==e)return;let t=!1,n=c.root;if("string"!=typeof n||!(n.length>0))return h(null),(0,w.fetchProjects)().then(e=>{let n=tH(e.projects)[0];t||void 0===n||d(e=>({...e,root:n}))}).catch(e=>{t||h(tU(e))}),()=>{t=!0}},[c.root,e]);let y=(e,t)=>d(n=>({...n,[e]:t})),k=()=>{"agents"!==e&&i(c)},N=j.Icons[s.icon],S=s.cta??`Open ${s.title}`;return(0,n.jsx)("div",{className:"dlg-overlay"+(u?" in":""),onPointerDown:r,children:(0,n.jsxs)("div",{ref:b,className:"agents"===e?"dlg dlg-agents":"dlg",role:"dialog","aria-modal":"true","aria-labelledby":"new-window-title","aria-describedby":"new-window-desc",tabIndex:-1,onPointerDown:e=>e.stopPropagation(),onKeyDown:e=>{let t,n;if("Escape"===e.key)return void r();if("Enter"===e.key&&(e.metaKey||e.ctrlKey))return void k();if("Enter"===e.key){let t=e.target instanceof HTMLElement?e.target.tagName:"";("INPUT"===t||"SELECT"===t)&&(e.preventDefault(),k());return}if("Tab"!==e.key)return;let a=(t=e.currentTarget.querySelectorAll("button,input,select,textarea"),n=[],t.forEach(e=>{e.hasAttribute("disabled")||(null!==e.offsetParent||"BUTTON"===e.tagName)&&n.push(e)}),n);if(0===a.length)return;let l=a[0],i=a[a.length-1];e.shiftKey&&document.activeElement===l?(e.preventDefault(),i.focus()):e.shiftKey||document.activeElement!==i||(e.preventDefault(),l.focus())},children:[(0,n.jsxs)("div",{className:"dlg-head",children:[(0,n.jsx)("span",{className:"dlg-ico",children:(0,n.jsx)(N,{size:20})}),(0,n.jsxs)("div",{className:"dlg-htext",children:[(0,n.jsxs)("span",{id:"new-window-title",className:"dlg-title",children:["New ",s.title," window"]}),(0,n.jsx)("span",{id:"new-window-desc",className:"dlg-sub",children:s.desc})]}),(0,n.jsx)("span",{className:"spacer"}),(0,n.jsx)("button",{type:"button",className:"palette-x",onClick:r,"aria-label":"Cancel",title:"Cancel",children:(0,n.jsx)(j.Icons.close,{size:16})})]}),(0,n.jsxs)("div",{className:"dlg-body",children:["agents"===e?(0,n.jsx)(tZ,{filesContext:l,firstRef:e=>{v.current=e},directoryField:f,setDirectoryField:g,setDialogError:h,onConfirm:i}):0===o.length&&(0,n.jsxs)("div",{className:"dlg-empty",children:["Add a new ",s.title," window to your workspace."]}),"agents"!==e&&o.map((e,t)=>(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsxs)("span",{className:"dlg-label",children:[e.label,!0===e.optional&&(0,n.jsx)("span",{className:"dlg-opt",children:"optional"})]}),function(e,t,a,l,i){if("perm"===e.type)return(0,n.jsx)(tB,{cfg:t,set:a});let r=t[e.key],s="string"==typeof r?r:void 0===r?"":String(r);if("select"===e.type){let t=e.options??[];return(0,n.jsx)("span",{className:"dlg-selwrap",children:(0,n.jsx)(tz,{triggerClassName:"dlg-input mono",value:s,disabled:0===t.length,autoFocus:null!==l,menuTitle:e.label,mono:!0,sections:[{options:t.map(t=>({value:t,label:`${e.prefix??""}${t}`}))}],onValueChange:t=>a(e.key,t)})})}return"textarea"===e.type?(0,n.jsx)("textarea",{ref:l??void 0,className:"dlg-input dlg-textarea",rows:3,placeholder:e.placeholder??"",value:s,onChange:t=>a(e.key,t.target.value)}):"directory"===e.type?(0,n.jsxs)("span",{className:"dlg-dirwrap",children:[(0,n.jsx)("input",{ref:l??void 0,className:"dlg-input mono",placeholder:e.placeholder??e.label,value:s,onClick:()=>i(e.key),onChange:t=>a(e.key,t.target.value)}),(0,n.jsx)("button",{type:"button",className:"dlg-btn dlg-dirbtn",onClick:()=>i(e.key),children:"Browse"})]}):(0,n.jsx)("input",{ref:l??void 0,className:"dlg-input mono",placeholder:e.placeholder??e.label,value:s,onChange:t=>a(e.key,t.target.value)})}(e,c,y,0===t?e=>{v.current=e}:null,g),"directory"===e.type&&f===e.key?(0,n.jsx)(tW,{value:"string"==typeof c[e.key]?c[e.key]:"",selectProjectRoot:"root"===e.key,onSelect:t=>y(e.key,t),onClose:()=>g(null)}):null]},e.key)),null!==m?(0,n.jsx)("div",{className:"dlg-error",role:"alert",children:m}):null]}),(0,n.jsxs)("div",{className:"dlg-foot",children:[(0,n.jsx)("button",{type:"button",className:"dlg-btn",onClick:r,children:"Cancel"}),"agents"!==e?(0,n.jsx)("button",{type:"button",className:"dlg-btn dlg-primary",onClick:k,children:S}):null]})]})})}function t1({types:e,order:t,onAdd:l,onClose:i}){let r=t.length<=4?2:3,s=(0,a.useRef)(null),o=(0,a.useRef)(null),[c,d]=(0,a.useState)(0);return(0,a.useEffect)(()=>{o.current=document.activeElement;let e=s.current?.querySelector(".pal-card");return e?.focus(),()=>{let e=document.activeElement;(null===e||e===document.body)&&o.current?.focus?.()}},[]),(0,a.useEffect)(()=>{let e=e=>{null!==s.current&&e.target instanceof Node&&!s.current.contains(e.target)&&i()};return document.addEventListener("pointerdown",e),()=>{document.removeEventListener("pointerdown",e)}},[i]),(0,n.jsxs)("div",{ref:s,className:"palette",role:"dialog","aria-labelledby":"palette-title","aria-describedby":"palette-desc",tabIndex:-1,onPointerDown:e=>e.stopPropagation(),onKeyDown:e=>{if("Escape"===e.key){e.preventDefault(),i();return}if(!(e.target instanceof HTMLElement)||!e.target.classList.contains("pal-card"))return;let t=Array.from(s.current?.querySelectorAll(".pal-card")??[]),n=function(e,t,n,a){let l;if(0===n)return null;if("Home"===e)return 0;if("End"===e)return n-1;if("ArrowRight"===e)l=1;else if("ArrowLeft"===e)l=-1;else if("ArrowDown"===e)l=a;else{if("ArrowUp"!==e)return null;l=-a}return Math.max(0,Math.min(n-1,t+l))}(e.key,t.indexOf(e.target),t.length,r);null!==n&&(e.preventDefault(),d(n),t[n]?.focus())},onBlur:e=>{e.relatedTarget instanceof Node&&s.current?.contains(e.relatedTarget)!==!0&&i()},"data-columns":r,children:[(0,n.jsxs)("div",{className:"palette-head",children:[(0,n.jsx)("span",{className:"palette-badge",children:(0,n.jsx)(j.Icons.add,{size:17})}),(0,n.jsxs)("div",{className:"palette-htext",children:[(0,n.jsx)("span",{id:"palette-title",className:"palette-title",children:"New window"}),(0,n.jsx)("span",{id:"palette-desc",className:"palette-sub",children:"Pick a card to add to your workspace"})]}),(0,n.jsx)("span",{className:"spacer"}),(0,n.jsx)("button",{type:"button",className:"palette-x",onClick:i,"aria-label":"Close",title:"Close",children:(0,n.jsx)(j.Icons.close,{size:16})})]}),(0,n.jsx)("div",{className:"palette-grid",children:t.map((t,a)=>{let i=e[t],r=j.Icons[i.icon];return(0,n.jsxs)("button",{type:"button",className:"pal-card pal-main",tabIndex:a===c?0:-1,onFocus:()=>d(a),onClick:()=>l(t),children:[(0,n.jsx)("span",{className:"pal-ico",children:(0,n.jsx)(r,{size:18})}),(0,n.jsx)("span",{className:"pal-name",children:i.title}),(0,n.jsx)("span",{className:"pal-desc",children:i.desc}),(0,n.jsx)("span",{className:"pal-add","aria-hidden":"true",children:(0,n.jsx)(j.Icons.plus,{size:15})})]},t)})})]})}async function t2(e){try{let t=await e.json();return{code:t.error.code,message:t.error.message}}catch{return{code:"INTERNAL",message:`HTTP ${e.status.toString()}`}}}async function t4(e,t){let n,a,l=(t?.method??"GET").toUpperCase(),i=t?.body,r=await fetch(e,{...t,headers:(n={Accept:"application/json"},((a="GET"!==l&&"HEAD"!==l)||null!=i)&&(n["Content-Type"]="application/json"),a&&(n["X-Keiko-CSRF"]="1"),n)});if(!r.ok){let{code:e,message:t}=await t2(r);throw new w.ApiError(e,t,r.status)}return r.json()}async function t3(e={},t=t4){let n=new URLSearchParams;void 0!==e.scope&&e.scope.length>0&&n.set("scope",e.scope.join(",")),void 0!==e.type&&e.type.length>0&&n.set("type",e.type.join(",")),void 0!==e.status&&e.status.length>0&&n.set("status",e.status.join(",")),void 0!==e.sensitivity&&e.sensitivity.length>0&&n.set("sensitivity",e.sensitivity.join(",")),void 0!==e.limit&&n.set("limit",e.limit.toString()),void 0!==e.offset&&n.set("offset",e.offset.toString());let a=n.toString();return t(`/api/memory${a.length>0?`?${a}`:""}`)}async function t6(e=t4){return e("/api/memory/review-queue")}async function t5(e,t=t4){return t("/api/memory/consolidation/jobs",{method:"POST",body:JSON.stringify({settings:e})})}async function t8(e,t=t4){return t(`/api/memory/consolidation/jobs/${encodeURIComponent(e)}`)}async function t7(e,t=t4){return t(`/api/memory/consolidation/jobs/${encodeURIComponent(e)}/cancel`,{method:"POST",body:"{}"})}async function t9(e,t=t4){return t(`/api/memory/${encodeURIComponent(e)}`)}async function ne(e,t,n=t4){return n(`/api/memory/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})}async function nt(e,t=t4){return t(`/api/memory/${encodeURIComponent(e)}/pin`,{method:"POST",body:"{}"})}async function nn(e,t=t4){return t(`/api/memory/${encodeURIComponent(e)}/unpin`,{method:"POST",body:"{}"})}async function na(e,t,n=t4){return n(`/api/memory/${encodeURIComponent(e)}/archive`,{method:"POST",body:JSON.stringify({...void 0!==t?{reason:t}:{}})})}async function nl(e,t,n=t4){return n(`/api/memory/${encodeURIComponent(e)}/forget`,{method:"POST",body:JSON.stringify({acknowledged:!0,...void 0!==t?{reason:t}:{}})})}async function ni(e,t,n=t4){return n(`/api/memory/${encodeURIComponent(e)}`,{method:"DELETE",body:JSON.stringify({acknowledged:!0,...void 0!==t?{reason:t}:{}})})}async function nr(e,t,n=t4){return n(`/api/memory/${encodeURIComponent(e)}/correct`,{method:"POST",body:JSON.stringify({body:t})})}async function ns(e,t=t4){return t(`/api/memory/proposals/${encodeURIComponent(e)}/accept`,{method:"POST",body:"{}"})}async function no(e,t,n=t4){return n(`/api/memory/proposals/${encodeURIComponent(e)}/reject`,{method:"POST",body:JSON.stringify({...void 0!==t?{reason:t}:{}})})}let nc=[{workflowId:"unit-test-generation",label:"Generate unit tests",description:"Drafts a reviewable unit-test patch for a target file. Dry-run only from chat — apply from the workflow view.",prompt:"Target file (workspace-relative)",placeholder:"src/example.ts",buildInput:(e,t)=>({workspaceRoot:e,target:{kind:"file",filePath:t.trim()}})},{workflowId:"bug-investigation",label:"Investigate bug",description:"Investigates a reported issue and proposes a root-cause hypothesis. Dry-run only from chat.",prompt:"Describe the bug",placeholder:"The login button does nothing when the form is empty…",buildInput:(e,t)=>({workspaceRoot:e,report:{description:t.trim()}})}];function nd(e){return nc.find(t=>t.workflowId===e)}let nu=new Set(["completed","dry-run","fix-applied","fix-proposed","investigation-only"]);function np(e){return e.length>200?e.slice(0,200):e}function nm(e){if(null!==e&&"object"==typeof e)return e}function nh(){return"Investigation complete; root cause documented."}function nf(e){let t=e.workflowId;return"unit-test-generation"===t||"unit-tests"===t?"unit-tests":"bug-investigation"===t?"bug":"verify"===e.taskType?"verify":"explain-plan"===e.taskType?"explain":"other"}function ng(e){return void 0===e||!Number.isFinite(e)||e<=0?0:Math.floor(e)}function nv(e){return"u">typeof TextEncoder?new TextEncoder().encode(e).length:e.length}function nb(e){let t=ng(e.modelContextWindow),n=ng(e.modelMaxOutputTokens),a=Math.max(0,t-n),l=nv(e.userDraftText),i=function(e){let t=0;for(let n of e)t+=nv(n.role),t+=nv(n.content);return t}(e.conversationHistory),r=function(e){if(void 0===e)return 0;let t=0;for(let n of e)t+=ng(n.extractedBytes);return t}(e.documentContext),s=ng(e.repoContextPackBytes),o=ng(e.knowledgeCapsuleBytes),c=ng(e.memoryContextBytes),d=l+i+r+s+o+c,u=Math.ceil(d/4),p=function(e,t){if(t<=0)return"exceeded";let n=e/t;return n>.95?"exceeded":n>.75?"high":n>.5?"moderate":"low"}(u,a);return{approximateBytes:d,approximateTokens:u,contextWindowTokens:t,reservedOutputTokens:n,availableInputTokens:a,pressure:p,breakdown:{draftBytes:l,historyBytes:i,documentBytes:r,repoContextBytes:s,knowledgeBytes:o,memoryBytes:c}}}function nx(e){return"chat"===e.kind}let ny={embedding:"embedding-only","ocr-vision":"ocr-vision-only"},nw=[/\bsk-[A-Za-z0-9_-]{12,}\b/g,/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}\b/gi,/\bgho_[A-Za-z0-9_]{12,}\b/g,/\bghp_[A-Za-z0-9_]{12,}\b/g],nj=/\s+\(([A-Z][A-Z0-9_/-]{2,})\)\s*$/;function nk(e){let t=e;for(let e of nw)t=t.replace(e,"[REDACTED]");return t.replace(/\bBearer\s+\[REDACTED\]/gi,"[REDACTED]")}function nN(e,t){return"BAD_REQUEST"===t&&e.toLowerCase().includes("too broad")&&e.toLowerCase().includes("connected")}function nS(e){return"CLARIFICATION_NEEDED"===e}function nC(e,t,n){return"GATEWAY_TIMEOUT"===t&&(0===e.length||e===t)?"The model gateway timed out before the model returned a response.":e.length>0?e:n}function nI(e,t){return nS(t)?"Keiko braucht mehr Kontext":nN(e,t)?"Narrow the connected-source question":"GATEWAY_TIMEOUT"===t?"Model gateway timed out":"PAYLOAD_TOO_LARGE"===t?"Request is too large":"NO_MODEL"===t?"No model is available":void 0!==t?"Request failed":"Something went wrong"}function nE(e,t){return nS(t)?"Nenne eine konkrete Datei, einen Identifier, eine Fehlermeldung oder eine exakte Phrase.":nN(e,t)?"Ask about a specific file, folder, symbol, identifier, or exact phrase. For broad questions over large project folders, narrow the Files scope first.":"GATEWAY_TIMEOUT"===t?"Retry the request. If it repeats, choose a smaller prompt or another configured model, then check the gateway base URL, proxy, and model deployment availability in Settings.":"PAYLOAD_TOO_LARGE"===t?"Reduce the selected scope or remove large attachments before retrying.":void 0}function nR(e,t){if(e instanceof w.ApiError){let n=nC(nk(e.message.trim()),e.code,t);return`${n} (${e.code})`}return e instanceof Error&&e.message.trim().length>0?nk(e.message.trim()):t}let n$="\n…[truncated]",nA=["text/"],nT=new Set(["application/json","application/x-yaml","application/yaml"]),nL=new TextEncoder;function nP(e){return nL.encode(e).length}function nM(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t>=0?e.slice(t+1):e}let nD=`${String(256)} KB`;function nq(e){return`"${e}" won't be sent — the ${nD} attachment limit was already used by earlier files.`}async function nF(e,t){var n,a;let l,i,r,s,o;if(e.remainingAggregate<=0)return nq(nM(t.name));try{l=await t.file.text()}catch{return n=nM(t.name),`Couldn't read "${n}" — it will be skipped. Your message will be sent without it.`}let c=Math.min(65536,Math.max(e.remainingAggregate-nP(n$),0));if(c<=0)return nq(nM(t.name));let{entry:d,consumed:u}=(r=(i=nP(a=l)>c)?function(e,t){if(t<=0)return"";if(nP(e)<=t)return e;let n=0,a="";for(let l of e){let e=n+nP(l);if(e>t)break;n=e,a+=l}return a}(a,c):a,s=nP(r),o=i?nP(n$):0,{entry:{id:t.id,displayName:nM(t.name),mimeType:t.mimeType,sizeBytes:t.sizeBytes,extractedBytes:s,truncated:i,truncationMarker:i?n$:void 0,text:r},consumed:s+o});if(0===d.text.length)return 0===l.length?void 0:nq(nM(t.name));e.entries.push(d),e.remainingAggregate-=u}async function nO(e){let t=e.filter(e=>{var t;return t=e.mimeType,!!nA.some(e=>t.startsWith(e))||nT.has(t)}),n=t.slice(0,16),a={entries:[],remainingAggregate:262144},l=[];for(let e of n){let t=await nF(a,e);void 0!==t&&l.push(t)}for(let e of t.slice(16)){var i;l.push((i=nM(e.name),`"${i}" won't be sent — only the first ${String(16)} documents are included.`))}return{entries:a.entries,failures:l}}let nz=["text/"],nK=new Set(["application/pdf","application/json","application/x-yaml","application/yaml"]),nB="New chat",n_="keiko:chat-upsert",nU="keiko:chat-delete",nW=["completed","failed","cancelled"];function nV(e){return"idle"!==e&&!nW.includes(e)}let nH="The conversation context exceeded the model's window. Clear history or pick a larger-context model.",nY="The model request completed, but the provider did not return any answer text. Retry once; if it happens again, check the selected model deployment in Settings.",nG=new Set(["CONVERSATION_OVERSIZED_CONTEXT","GATEWAY_CONTEXT_OVERFLOW"]),nJ=["context length","context_length_exceeded","max_tokens","too many tokens"],nX=["empty assistant response","empty grounded answer","without assistant content"];function nQ(e){return void 0!==e&&e.contextWindowTokens>0&&"exceeded"===e.pressure}function nZ(e){let t;return function(e){if(e instanceof w.ApiError&&nG.has(e.code))return!0;let t=e instanceof Error?e.message.toLowerCase():"";return 0!==t.length&&nJ.some(e=>t.includes(e))}(e)?nH:0!==(t=e instanceof Error?e.message.toLowerCase():"").length&&nX.some(e=>t.includes(e))?e instanceof w.ApiError?`${nY} (${e.code})`:nY:nR(e,"Something went wrong. Try again.")}function n0(e){return[...e].sort((e,t)=>t.updatedAt-e.updatedAt)}function n1(e){window.dispatchEvent(new CustomEvent(n_,{detail:e}))}function n2(e){return e.find(nx)?.id}function n4(e,t){return void 0!==e&&t.some(t=>t.id===e&&nx(t))?e:n2(t)}function n3(e){return void 0!==e.connectedScope||void 0!==e.connectedScopes&&e.connectedScopes.length>0||void 0!==e.localKnowledgeScope||void 0!==e.localKnowledgeScopes&&e.localKnowledgeScopes.length>0}let n6={projects:[],chats:[],messages:[],models:[],activeProject:void 0,activeChat:void 0,selectedModel:void 0};function n5(e,t){if(0===t.length)return Array.from(e);let n=new Map(t.map(e=>[e.id,e])),a=e.map(e=>n.get(e.id)??e),l=new Set(e.map(e=>e.id));for(let e of t)l.has(e.id)||a.push(e);return a}async function n8(e){let t=(await (0,w.fetchModels)()).models.filter(nx),n=n2(t),a=[...(await (0,w.fetchProjects)().catch(()=>({projects:[]}))).projects].sort((e,t)=>e.favorite!==t.favorite?e.favorite?-1:1:e.lastOpenedAt!==t.lastOpenedAt?t.lastOpenedAt-e.lastOpenedAt:e.path.localeCompare(t.path)),l=a.find(e=>e.available)??a[0];if(void 0!==l){let e=n0((await (0,w.fetchChats)(l.path).catch(()=>({chats:[]}))).chats),n=e[0];if(void 0!==n){let i=await (0,w.fetchChatMessages)(n.id,l.path),r=n4(n.selectedModel,t);return{models:t,selectedModel:r,projects:Array.from(a),activeProject:l,chats:e,activeChat:n,messages:Array.from(i.messages)}}}if(void 0===n||!e)return{models:t,selectedModel:n,projects:Array.from(a),activeProject:l,chats:[],activeChat:void 0,messages:[]};let i={modelId:n,title:nB};l?.available===!0&&(i.projectPath=l.path);let r=await (0,w.createDesktopChat)(i);return n1(r.chat),{models:t,selectedModel:r.chat.selectedModel,projects:Array.from(r.projects),activeProject:r.project,chats:n0(r.chats),activeChat:r.chat,messages:Array.from(r.messages)}}function n7(e={}){let t=e.autoCreate??!0,[n,l]=(0,a.useState)(n6),[i,r]=(0,a.useState)(""),[s,o]=(0,a.useState)(!0),[c,d]=(0,a.useState)("idle"),u=nV(c),p=(0,a.useRef)("idle"),m=(0,a.useRef)(null),[h,f]=(0,a.useState)(),[g,v]=(0,a.useState)(),[b,x]=(0,a.useState)(),[y,j]=(0,a.useState)(!0),[k,N]=(0,a.useState)(1200),S=(0,a.useRef)(!0),C=(0,a.useRef)(void 0),I=(0,a.useRef)(new Set),E=(0,a.useRef)(0),R=(0,a.useRef)([]),[$,A]=(0,a.useState)([]),[T,L]=(0,a.useState)([]),P=(0,a.useCallback)(async e=>{var t;let a;if(0===e.size)return{ok:!1,reason:"empty"};if(e.size>8388608)return{ok:!1,reason:"oversized"};let l=(t=e.type).startsWith("image/")?"image":nz.some(e=>t.startsWith(e))||nK.has(t)?"document":"unsupported-type";if("unsupported-type"===l)return{ok:!1,reason:"unsupported-type"};let i=n.models.find(e=>e.id===n.selectedModel);if(void 0!==i&&("image"===l&&!i.supportsImageInput||"document"===l&&!i.supportsDocumentInput))return{ok:!1,reason:"text-only-model"};if("image"===l)try{a=await new Promise((t,n)=>{let a=new FileReader;a.onload=()=>t(a.result),a.onerror=()=>n(Error("FileReader error")),a.readAsDataURL(e)})}catch{return{ok:!1,reason:"unsupported-type"}}let r={id:crypto.randomUUID(),kind:l,name:e.name,mimeType:e.type,sizeBytes:e.size,previewDataUrl:a,file:e};return A(e=>[...e,r]),{ok:!0}},[n.models,n.selectedModel]),M=(0,a.useCallback)(e=>{A(t=>t.filter(t=>t.id!==e))},[]),D=(0,a.useCallback)(()=>{A([])},[]),q=(0,a.useCallback)(async()=>{let e=$.filter(e=>"document"===e.kind&&void 0!==e.file).map(e=>({id:e.id,name:e.name,mimeType:e.mimeType,sizeBytes:e.sizeBytes,file:e.file}));if(0===e.length)return{entries:[],disclosures:[]};let{entries:t,failures:n}=await nO(e);n.length>0&&f(n.join(" "));let a=t.map(e=>({id:e.id,displayName:e.displayName,truncated:e.truncated}));return{entries:t,disclosures:a}},[$]),F=(0,a.useCallback)(()=>{x(void 0)},[]),O=(0,a.useCallback)((e,t)=>({enabled:y,budgetTokens:k,context:{userId:"local-operator",workspaceId:t.path,projectId:t.path,conversationId:e.id}}),[k,y]),z=(0,a.useCallback)(async e=>{await ns(e),x(t=>void 0===t?t:{...t,actions:t.actions.filter(t=>"candidate"!==t.kind||t.proposalId!==e)})},[]),K=(0,a.useCallback)(async e=>{await no(e),x(t=>void 0===t?t:{...t,actions:t.actions.filter(t=>"candidate"!==t.kind||t.proposalId!==e)})},[]),B=(0,a.useCallback)(async e=>{await nl(e,"user-initiated forget from Conversation Center"),x(t=>void 0===t?t:{...t,actions:t.actions.filter(t=>"forget"!==t.kind||t.memoryId!==e)})},[]),_=(0,a.useCallback)(e=>{p.current=e,d(e)},[]),U=(0,a.useCallback)(async(e,t,n,a)=>{let i=n.runId;if(void 0===i)return void I.current.delete(a);let r={...void 0===n.workflowId?{}:{workflowId:n.workflowId},...void 0===n.taskType?{}:{taskType:n.taskType}};try{for(let a=0;a<120;a+=1){let s;if(!S.current||C.current!==e.id)return;try{let e=await (0,w.fetchRunReport)(i),t=function(e,t){let n=nm(e);if(void 0===n)return{kind:"unknown"};let a=function(e){let t=e.status;if("string"==typeof t)return t}(n),l=nf(t);return"running"===a?{kind:"running"}:"cancelled"===a?{kind:"terminal",summary:{workflowStatus:"cancelled",shortResult:"Run cancelled."}}:"failed"===a||"rejected"===a?{kind:"terminal",summary:{workflowStatus:"failed",shortResult:np(function(e){let t,n,a=(t=nm(e.failure),n=t?.message,"string"==typeof n&&n.length>0?n:void 0);return void 0!==a?np(`Run failed: ${a}.`):"Run failed."}(n))}}:void 0!==a&&nu.has(a)?{kind:"terminal",summary:{workflowStatus:"completed",shortResult:np(function(e,t){if("unit-tests"===t)return function(e){let t,n=e.addedTestFiles;if(Array.isArray(n)){let e=0,a=!1;for(let t of n){let n=nm(t),l=n?.estimatedTestCount;"number"==typeof l&&Number.isFinite(l)&&(e+=l,a=!0)}a&&(t=e)}let a=Array.isArray(n)?n.length:0;return a>0&&void 0!==t?`Generated ${String(a)} test files; ${String(t)} tests proposed.`:a>0?`Generated ${String(a)} test files.`:"Completed."}(e);if("bug"===t)return nh();if("verify"===t){let t,n;return t=nm(e.verificationSummary),n=t?.results,Array.isArray(n)&&n.length>0?`Verification passed: ${String(n.length)} classifications.`:"Verification passed."}if("explain"===t){let t=e.dryRunPreview;if("string"==typeof t&&t.length>0){let e=t.split("\n").filter(e=>e.trim().length>0);if(e.length>0)return`Plan generated; ${String(e.length)} steps.`}return"Plan generated."}return"Completed."}(n,l))}}:{kind:"unknown"}}(e.report,r);"terminal"===t.kind&&(s=t.summary)}catch(e){if(!(e instanceof w.ApiError)||404!==e.status)return;try{let e=await (0,w.fetchEvidenceManifest)(i),t=function(e,t){let n=nm(e),a=void 0===n?void 0:nm(n.run),l=void 0===a?void 0:a.outcome,i=nf(t);return"cancelled"===l?{workflowStatus:"cancelled",shortResult:"Run cancelled."}:"failed"===l||"limit-exceeded"===l?{workflowStatus:"failed",shortResult:"Run failed."}:"completed"===l?{workflowStatus:"completed",shortResult:np("bug"===i?nh():"verify"===i?"Verification passed.":"explain"===i?"Plan generated.":"unit-tests"===i?"Generated tests.":"Completed.")}:{workflowStatus:"completed",shortResult:"Completed."}}(e.manifest,r);s={workflowStatus:"failed"===t.workflowStatus||"cancelled"===t.workflowStatus?t.workflowStatus:"completed",shortResult:t.shortResult}}catch{}}if(void 0!==s){let a=await (0,w.patchChatMessage)(n.id,e.id,t,s);if(!S.current||C.current!==e.id)return;l(t=>t.activeChat?.id!==e.id?t:{...t,messages:t.messages.map(e=>e.id===n.id?a.message:e)});return}a<119&&await new Promise(e=>{globalThis.setTimeout(e,1e3)})}}finally{I.current.delete(a)}},[]);(0,a.useEffect)(()=>{C.current=n.activeChat?.id},[n.activeChat?.id]),(0,a.useEffect)(()=>{R.current=n.models},[n.models]),(0,a.useEffect)(()=>{let e=!1;return async function(){o(!0),f(void 0);try{let n=await n8(t);e||l(e=>({...e,...n}))}catch(t){e||f(nZ(t))}finally{e||o(!1)}}(),()=>{e=!0}},[t]),(0,a.useEffect)(()=>{let e=e=>{let t=e.detail;"object"==typeof t&&null!==t&&"string"==typeof t.id&&"string"==typeof t.projectPath&&"string"==typeof t.title&&"string"==typeof t.selectedModel&&l(e=>({...e,chats:n0([t,...e.chats.filter(e=>e.id!==t.id)]),activeChat:e.activeChat?.id===t.id?t:e.activeChat,selectedModel:e.activeChat?.id===t.id?n4(t.selectedModel,e.models):e.selectedModel}))},t=e=>{let t=e.detail;"object"==typeof t&&null!==t&&"string"==typeof t.chatId&&l(e=>({...e,chats:e.chats.filter(e=>e.id!==t.chatId),activeChat:e.activeChat?.id===t.chatId?void 0:e.activeChat,messages:e.activeChat?.id===t.chatId?[]:e.messages}))};return window.addEventListener(n_,e),window.addEventListener(nU,t),()=>{window.removeEventListener(n_,e),window.removeEventListener(nU,t)}},[]),(0,a.useEffect)(()=>(S.current=!0,()=>{S.current=!1,m.current?.abort()}),[]),(0,a.useEffect)(()=>{let e=n.activeChat,t=n.activeProject;if(void 0!==e&&void 0!==t)for(let a of n.messages){if("system"!==a.role||"string"!=typeof a.runId||void 0!==a.workflowStatus&&"pending"!==a.workflowStatus&&"running"!==a.workflowStatus)continue;let n=a.runId;if(void 0===n)continue;let l=`${a.id}:${n}`;I.current.has(l)||(I.current.add(l),U(e,t.path,a,l))}},[n.activeChat,n.activeProject,n.messages,U]);let W=(0,a.useCallback)(e=>{let t;f(void 0),l(n=>(t={selectedModel:n.selectedModel,activeChat:n.activeChat,chats:n.chats},{...n,selectedModel:e,activeChat:void 0===n.activeChat?n.activeChat:{...n.activeChat,selectedModel:e},chats:n.chats.map(t=>void 0!==n.activeChat&&t.id===n.activeChat.id?{...t,selectedModel:e}:t)})),A(t=>t.filter(t=>{let n;return void 0===(n=R.current.find(t=>t.id===e))||("image"===t.kind?n.supportsImageInput:n.supportsDocumentInput)}));let n=C.current;if(void 0===n)return;let a=E.current+1;E.current=a,(0,w.updateChat)(n,{selectedModel:e}).then(e=>{E.current!==a||C.current===e.chat.id&&(n1(e.chat),l(t=>({...t,selectedModel:e.chat.selectedModel,activeChat:t.activeChat?.id===e.chat.id?e.chat:t.activeChat,chats:t.chats.map(t=>t.id===e.chat.id?e.chat:t)})))}).catch(e=>{if(E.current===a&&C.current===n&&(f(nZ(e)),void 0!==t)){let e=t;l(t=>({...t,selectedModel:t.activeChat?.id===n?e.selectedModel:t.selectedModel,activeChat:t.activeChat?.id===n?e.activeChat:t.activeChat,chats:t.chats.map(t=>{if(t.id!==n)return t;let a=e.chats.find(e=>e.id===n);return void 0!==a?{...t,selectedModel:a.selectedModel}:t})}))}})},[]),V=(0,a.useCallback)(async(e,t)=>{let a=n4(n.selectedModel,n.models);if(void 0===a)return void f("No conversation-eligible model is configured. Connect a gateway in Settings.");f(void 0);try{let i=t?.trim(),r={modelId:a,title:void 0!==i&&i.length>0?i:nB},s=e?.path??n.activeProject?.path;void 0!==s&&(r.projectPath=s);let o=await (0,w.createDesktopChat)(r);return C.current=o.chat.id,n1(o.chat),l({projects:Array.from(o.projects),chats:n0(o.chats),messages:Array.from(o.messages),models:n.models,activeProject:o.project,activeChat:o.chat,selectedModel:o.chat.selectedModel}),o.chat}catch(e){f(nZ(e));return}},[n.selectedModel,n.activeProject,n.models]),H=(0,a.useCallback)(async e=>{f(void 0),l(t=>({...t,activeProject:e}));try{let t=await (0,w.fetchChats)(e.path),a=n0(t.chats),i=a[0];if(void 0===i)return void await V(e);let r=await (0,w.fetchChatMessages)(i.id,e.path);C.current=i.id;let s=n4(i.selectedModel,n.models);l(e=>({...e,chats:a,activeChat:i,selectedModel:s,messages:Array.from(r.messages)})),x(void 0)}catch(e){f(nZ(e))}},[V,n.models]),Y=(0,a.useCallback)(async e=>{f(void 0),m.current?.abort(),m.current=null,C.current=e.id,v(void 0),x(void 0),L([]);try{let t=await (0,w.fetchChatMessages)(e.id,e.projectPath),a=n4(e.selectedModel,n.models);l(n=>{let l=n.projects.find(t=>t.path===e.projectPath);return{...n,activeProject:l,activeChat:e,selectedModel:a,messages:Array.from(t.messages)}})}catch(e){f(nZ(e))}},[n.models]),G=(0,a.useCallback)(async e=>{let t=e.trim();if(0!==t.length){f(void 0);try{let e=await (0,w.createProject)({path:t}),n=await (0,w.fetchProjects)();l(e=>({...e,projects:Array.from(n.projects)})),await V(e.project)}catch(e){f(nZ(e))}}},[V]),J=(0,a.useCallback)(e=>{l(t=>({...t,messages:t.messages.filter(t=>t.id!==e)}))},[]),X=(0,a.useCallback)((e,t,n)=>{let a=!1;return{onToken:t=>{a||(_("streaming"),a=!0),l(n=>({...n,messages:n.messages.map(n=>n.id===e?{...n,content:n.content+t}:n)}))},onDone:a=>{l(n=>({...n,activeChat:a.chat,chats:n0([a.chat,...n.chats.filter(e=>e.id!==a.chat.id)]),messages:[...n.messages.filter(n=>n.id!==t&&n.id!==e),...Array.from(a.messages)]})),n1(a.chat),void 0!==a.memory&&x(a.memory),n("completed")},onError:({code:t,message:a})=>{f(nZ(new w.ApiError(t,a,0))),J(e),n("failed")},onCancelled:()=>{J(e),n("cancelled")}}},[J,_]),Q=(0,a.useCallback)((e,t,n,a,i,r,s)=>{let o=`stream-${String(Date.now())}`;l(t=>({...t,messages:[...t.messages,{id:o,chatId:e.id,role:"assistant",content:"",timestamp:Date.now(),runId:void 0,workflowId:void 0,workflowStatus:void 0,shortResult:void 0,taskType:void 0}]}));let c={chatId:e.id,projectPath:t.path,content:n,modelId:i,memory:O(e,t),...s.length>0?{documentContext:s}:{}};return new Promise((e,t)=>{let n=X(o,a,e);(0,w.sendDesktopChatStream)(c,r,n).catch(n=>{J(o),n instanceof w.StreamingUnavailableError?t(n):n instanceof DOMException&&"AbortError"===n.name?e("cancelled"):(f(nZ(n)),l(e=>({...e,messages:e.messages.filter(e=>e.id!==a)})),e("failed"))})})},[O,X,J]),Z=(0,a.useCallback)(async(e,t,n,a,i,r,s)=>{try{_("contacting");let o=await (0,w.sendDesktopChat)({chatId:e.id,projectPath:t.path,content:n,modelId:i,memory:O(e,t),...s.length>0?{documentContext:s}:{}},r);if(r.aborted)return"cancelled";return l(e=>({...e,activeChat:o.chat,chats:n0([o.chat,...e.chats.filter(e=>e.id!==o.chat.id)]),messages:[...e.messages.filter(e=>e.id!==a),...Array.from(o.messages)]})),n1(o.chat),x(o.memory),"completed"}catch(n){if(n instanceof DOMException&&"AbortError"===n.name)return"cancelled";f(nZ(n));try{let n=await (0,w.fetchChatMessages)(e.id,t.path);l(e=>({...e,messages:Array.from(n.messages)}))}catch{l(e=>({...e,messages:e.messages.filter(e=>e.id!==a)}))}return"failed"}},[O,_]),ee=(0,a.useCallback)(async(e,t,a,l,i,r,s)=>{if(n.models.find(e=>e.id===i)?.streaming!==!0)return Z(e,t,a,l,i,r,s);_("contacting");try{return await Q(e,t,a,l,i,r,s)}catch(e){if(!(e instanceof w.StreamingUnavailableError))throw e}return Z(e,t,a,l,i,r,s)},[n.models,Z,Q,_]),et=(0,a.useCallback)(async(e,t,n,a,i,r)=>{v(void 0);try{_("contacting");let t=await (0,w.askGrounded)({chatId:e.id,content:n,modelId:i},r);if(C.current!==e.id)return"completed";if(r.aborted)return"cancelled";v(t),x(void 0);let[a,s]=await Promise.all([(0,w.fetchChatMessages)(e.id,e.projectPath),(0,w.fetchChats)(e.projectPath)]),o=s.chats.find(t=>t.id===e.id);return l(e=>({...e,messages:Array.from(a.messages),chats:n0(s.chats),activeChat:o??e.activeChat})),void 0!==o&&n1(o),"completed"}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)return"cancelled";return f(nZ(e)),l(e=>({...e,messages:e.messages.filter(e=>e.id!==a)})),"failed"}},[_]),en=(0,a.useCallback)(()=>{nV(p.current)&&(m.current?.abort(),m.current=null,_("cancelled"))},[_]),ea=(0,a.useCallback)(async()=>{if(nV(p.current))return;let e=i.trim(),t=n.activeChat,a=n.activeProject,s=n4(n.selectedModel,n.models);if(0===e.length||void 0===t||void 0===a||void 0===s)return;if(nQ(nb({modelContextWindow:n.models.find(e=>e.id===s)?.contextWindow??0,modelMaxOutputTokens:n.models.find(e=>e.id===s)?.maxOutputTokens??0,userDraftText:e,conversationHistory:n.messages.filter(e=>"user"===e.role||"assistant"===e.role).map(e=>({role:e.role,content:e.content}))})))return void f(nH);if(n3(t)&&$.length>0)return void f("Attachments are not supported for grounded chats. Remove the attachment or switch to a non-grounded chat.");let o={id:`local-${String(Date.now())}`,chatId:t.id,role:"user",content:e,timestamp:Date.now(),runId:void 0,workflowId:void 0,workflowStatus:void 0,shortResult:void 0,taskType:void 0};_("queued"),r(""),f(void 0),l(e=>({...e,messages:[...e.messages,o]}));let c=new AbortController;m.current=c,x(void 0);try{let n=n3(t),{entries:l,disclosures:i}=n?{entries:[],disclosures:[]}:await q(),r=n?await et(t,a,e,o.id,s,c.signal):await ee(t,a,e,o.id,s,c.signal,l);"cancelled"===p.current||_(r),"completed"===r&&(D(),L(i))}finally{m.current=null}},[i,n.activeChat,n.activeProject,n.selectedModel,n.models,n.messages,$,et,ee,q,D,_]),el=(0,a.useCallback)(()=>{v(void 0),x(void 0),l(e=>({...e,messages:[]}))},[]),ei=(0,a.useMemo)(()=>{let e=n.models.find(e=>e.id===n.selectedModel);if(void 0===e)return;let t=n.messages.filter(e=>"user"===e.role||"assistant"===e.role).map(e=>({role:e.role,content:e.content})),a=0,l=0;void 0!==g&&(("connected-context"===g.groundingKind||"hybrid"===g.groundingKind)&&(a=("hybrid"===g.groundingKind?g.contextPack.folder:g.contextPack).usage.excerptBytes),("local-knowledge"===g.groundingKind||"hybrid"===g.groundingKind)&&(l=4*("hybrid"===g.groundingKind?g.contextPack.knowledge:g.contextPack).referenceBudget));let r=y&&void 0!==b&&b.context.enabled?b.context.text.length:0;return nb({modelContextWindow:e.contextWindow,modelMaxOutputTokens:e.maxOutputTokens,userDraftText:i,conversationHistory:t,repoContextPackBytes:a,knowledgeCapsuleBytes:l,memoryContextBytes:r})},[n.models,n.selectedModel,n.messages,i,g,b,y]),er=(0,a.useCallback)(async e=>{if(nV(p.current))return{ok:!1,reason:"request-failed",message:"A request is already in flight."};let t=e.text.trim();if(0===t.length)return{ok:!1,reason:"missing-input"};let a=n.activeChat,i=n.activeProject;if(void 0===a||void 0===i)return{ok:!1,reason:"missing-chat"};let r=n.models.find(t=>t.id===e.modelId);if(void 0===r||!t_(r))return{ok:!1,reason:"not-workflow-eligible"};let s=nd(e.workflowId);if(void 0===s)return{ok:!1,reason:"unknown-workflow"};let o=Date.now(),c=s.buildInput(i.path,t);try{let n=await (0,w.startChatRun)({chatId:a.id,projectPath:i.path,run:{workflowId:e.workflowId,input:c,modelId:e.modelId},user:{content:t,timestamp:o},summary:{content:`Launched: ${s.label}`,timestamp:o+1}});return l(e=>({...e,messages:n5(e.messages,n.messages)})),{ok:!0,runId:n.run.runId}}catch(t){let e=nZ(t);return f(e),{ok:!1,reason:"request-failed",message:e}}},[n.activeChat,n.activeProject,n.models]),es=(0,a.useCallback)(async e=>{if(nV(p.current))return{ok:!1,reason:"request-failed",message:"A request is already in flight."};if(void 0===n.activeChat)return{ok:!1,reason:"missing-chat"};if(0===e.modelId.trim().length)return{ok:!1,reason:"missing-model"};try{let t=await (0,w.startGroundedWorkflowHandoff)({assistantMessageId:e.assistantMessageId,chatId:n.activeChat.id,modelId:e.modelId,workflowKind:e.workflowKind,input:e.input,editablePaths:e.editablePaths,...void 0===e.expectedChecks?{}:{expectedChecks:e.expectedChecks},...void 0===e.unknowns?{}:{unknowns:e.unknowns},requestedAtMs:Date.now()});return l(e=>({...e,messages:n5(e.messages,t.messages)})),{ok:!0,runId:t.run.runId}}catch(t){let e=nZ(t);return f(e),{ok:!1,reason:"request-failed",message:e}}},[n.activeChat]),eo=(0,a.useCallback)(e=>{n1(e),l(t=>({...t,chats:t.chats.map(t=>t.id===e.id?e:t),activeChat:t.activeChat?.id===e.id?e:t.activeChat}))},[]),ec=(0,a.useCallback)(()=>{f(void 0)},[]);return{projects:n.projects,chats:n.chats,messages:n.messages,models:n.models,activeProject:n.activeProject,activeChat:n.activeChat,selectedModel:n.selectedModel,noEligibleModels:!s&&void 0===n4(n.selectedModel,n.models),draft:i,loading:s,sending:u,sendStatus:c,error:h,clearError:ec,setDraft:r,setSelectedModel:W,openNewChat:V,openProject:H,openChat:Y,addProject:G,sendMessage:ea,cancelSend:en,replaceChat:eo,latestGrounded:g,cancelGrounded:en,pendingAttachments:$,addPendingAttachment:P,removePendingAttachment:M,clearPendingAttachments:D,lastSentDocuments:T,budget:ei,memoryEnabled:y,setMemoryEnabled:j,memoryBudgetTokens:k,setMemoryBudgetTokens:N,latestMemory:b,clearLatestMemory:F,acceptMemoryCandidate:z,rejectMemoryCandidate:K,forgetMemoryAction:B,clearHistory:el,launchWorkflowFromConversation:er,launchGroundedWorkflowHandoff:es}}let n9="keiko.theme",ae="dark";var at=e.i(26428);let an=["agent","capsule","capsule-set","chat","connector","data-source","evidence-run","mcp-tool","memory","patch-proposal","skill","tool","workflow-run","workspace-path"],aa=["capsule","capsule-set","chat","evidence-run","memory","patch-proposal","tool","workflow-run","workspace-path"],al=["reads-context","proposes-patch","uses-tool","starts-workflow","produces-evidence","references-document","depends-on"],ai=["draft","active","archived","superseded","revoked","blocked","stale"],ar={"reads-context":{id:"reads-context",displayName:"reads context",semantics:"A consumer endpoint reads the contextual content of the target at a specific point in time.",validSourceKinds:["workflow-run","chat"],validTargetKinds:["memory","capsule","capsule-set","evidence-run","workspace-path","connector","data-source"],cardinality:"N:N",direction:"directed",lifecycle:{creatable:!0,immutable:!0,reconnectable:!1,deletable:!1,archivable:!0},auditEventOnMutation:!0,evidenceRelevance:"reference",ownerPackage:"@oscharko-dev/keiko-workflows",trustBoundary:"per-endpoint"},"proposes-patch":{id:"proposes-patch",displayName:"proposes patch",semantics:"A workflow run proposes a patch against one or more workspace paths. The relationship records the proposal; diff content stays in the harness PatchProposedEvent.",validSourceKinds:["workflow-run"],validTargetKinds:["workspace-path","patch-proposal"],cardinality:"1:N",direction:"directed",lifecycle:{creatable:!0,immutable:!0,reconnectable:!1,deletable:!0,archivable:!0},auditEventOnMutation:!0,evidenceRelevance:"reference",ownerPackage:"@oscharko-dev/keiko-workflows",trustBoundary:"fs"},"uses-tool":{id:"uses-tool",displayName:"uses tool",semantics:"A workflow run uses a registered tool. Per-call arguments and results remain in the harness ToolCallRequest / ToolCallResult envelopes.",validSourceKinds:["workflow-run"],validTargetKinds:["tool","mcp-tool"],cardinality:"N:N",direction:"directed",lifecycle:{creatable:!0,immutable:!0,reconnectable:!1,deletable:!1,archivable:!0},auditEventOnMutation:!0,evidenceRelevance:"reference",ownerPackage:"@oscharko-dev/keiko-workflows",trustBoundary:"tool"},"starts-workflow":{id:"starts-workflow",displayName:"starts workflow",semantics:"A chat or a parent workflow run initiates a workflow run. The relationship records the origin; run identity belongs to the workflow ledger.",validSourceKinds:["chat","workflow-run"],validTargetKinds:["workflow-run"],cardinality:"1:N",direction:"directed",lifecycle:{creatable:!0,immutable:!0,reconnectable:!1,deletable:!1,archivable:!0},auditEventOnMutation:!0,evidenceRelevance:"reference",ownerPackage:"@oscharko-dev/keiko-workflows",trustBoundary:"per-endpoint"},"produces-evidence":{id:"produces-evidence",displayName:"produces evidence",semantics:"A workflow run produces exactly one durable evidence-run record. If a run produces no evidence, no relationship is recorded.",validSourceKinds:["workflow-run"],validTargetKinds:["evidence-run"],cardinality:"1:1",direction:"directed",lifecycle:{creatable:!0,immutable:!0,reconnectable:!1,deletable:!1,archivable:!0},auditEventOnMutation:!0,evidenceRelevance:"produces",ownerPackage:"@oscharko-dev/keiko-evidence",trustBoundary:"evidence"},"references-document":{id:"references-document",displayName:"references document",semantics:"A chat or workflow run holds a structural pointer to a document (workspace file or local-knowledge capsule). Distinct from reads-context: a reference is structural, a read is an event.",validSourceKinds:["chat","workflow-run"],validTargetKinds:["workspace-path","capsule","capsule-set"],cardinality:"N:N",direction:"directed",lifecycle:{creatable:!0,immutable:!1,reconnectable:!0,deletable:!0,archivable:!0},auditEventOnMutation:!0,evidenceRelevance:"reference",ownerPackage:"@oscharko-dev/keiko-workflows",trustBoundary:"per-endpoint"},"depends-on":{id:"depends-on",displayName:"depends on",semantics:"A capsule, capsule-set, workflow run, or memory depends on another. Used by impact analysis (#542). Self-loops and direct two-edge cycles are forbidden at validation time; transitive cycle detection is deferred to impact traversal.",validSourceKinds:["capsule","capsule-set","workflow-run","memory"],validTargetKinds:["capsule","capsule-set","workflow-run","memory","evidence-run","workspace-path"],cardinality:"N:N",direction:"directed",lifecycle:{creatable:!0,immutable:!1,reconnectable:!0,deletable:!0,archivable:!0},auditEventOnMutation:!0,evidenceRelevance:"reference",ownerPackage:"@oscharko-dev/keiko-contracts",trustBoundary:"per-endpoint"}},as=["prompt","documentcontent","filecontent","toolstdout","toolstderr","secret","credential","apikey","password","token"],ao="Unable to reach the local backend. Check that the Keiko server is running (keiko ui).";class ac extends Error{code;status;reasons;constructor(e,t,n,a=[]){super(t),this.name="RelationshipApiError",this.code=e,this.status=n,this.reasons=a}}async function ad(e){let t;try{t=await e.json()}catch{throw new ac("relationship/parse-error","Response is not valid JSON.",e.status)}if(!e.ok){let n=t,a=n.error??n,l="string"==typeof a.code?a.code:"relationship/unknown-error",i="string"==typeof a.message?a.message:"An unknown error occurred.",r=Array.isArray(n.reasons)?n.reasons:[];throw new ac(l,i,e.status,r)}return t}function au(e){let t={"Content-Type":"application/json","X-Keiko-CSRF":"1"};return void 0!==e.idempotencyKey&&(t["Idempotency-Key"]=e.idempotencyKey),void 0!==e.ifMatch&&(t["If-Match"]=e.ifMatch),t}async function ap(e){let t={schemaVersion:"1",proposal:{type:e.type,source:{kind:e.source.kind,id:e.source.id},target:{kind:e.target.kind,id:e.target.id},...void 0!==e.summary?{summary:e.summary}:{}}},n=await fetch("/api/relationships/validate",{method:"POST",headers:au({}),body:JSON.stringify(t)});return{decision:(await ad(n)).decision}}async function am(e,t){let n={schemaVersion:"1",proposal:{type:e.type,source:{kind:e.source.kind,id:e.source.id},target:{kind:e.target.kind,id:e.target.id},...void 0!==e.summary?{summary:e.summary}:{}}},a=await fetch("/api/relationships",{method:"POST",headers:au({idempotencyKey:t}),body:JSON.stringify(n)}),l=await ad(a);return{relationship:l.relationship,etag:l.etag}}async function ah(e){let t=new URLSearchParams;void 0!==e.lifecycle&&t.set("lifecycle",e.lifecycle),void 0!==e.type&&t.set("type",e.type),void 0!==e.sourceKind&&t.set("sourceKind",e.sourceKind),void 0!==e.targetKind&&t.set("targetKind",e.targetKind),void 0!==e.sourceId&&t.set("sourceId",e.sourceId),void 0!==e.targetId&&t.set("targetId",e.targetId),void 0!==e.limit&&t.set("limit",String(e.limit)),void 0!==e.cursor&&t.set("cursor",e.cursor);let n=await fetch(`/api/relationships?${t.toString()}`),a=await ad(n);return{entries:a.entries,truncated:a.truncated,nextCursor:a.nextCursor}}async function af(e){let t=await fetch(`/api/relationships/${encodeURIComponent(e)}`);return(await ad(t)).relationship}async function ag(e,t,n,a){let l=await fetch(`/api/relationships/${encodeURIComponent(e)}`,{method:"PATCH",headers:au({idempotencyKey:a,ifMatch:n}),body:JSON.stringify({schemaVersion:"1",...t})}),i=await ad(l);return{relationship:i.relationship,etag:i.etag}}async function av(e,t,n){let a=await fetch(`/api/relationships/${encodeURIComponent(e)}`,{method:"DELETE",headers:au({idempotencyKey:n,ifMatch:t})});return(await ad(a)).relationship}async function ab(e,t={}){let n=new URLSearchParams;void 0!==t.direction&&n.set("direction",t.direction),void 0!==t.maxDepth&&n.set("maxDepth",String(t.maxDepth)),void 0!==t.maxNodes&&n.set("maxNodes",String(t.maxNodes)),void 0!==t.maxRelationships&&n.set("maxRelationships",String(t.maxRelationships));let a=await fetch(`/api/relationships/${encodeURIComponent(e)}/dependencies?${n.toString()}`);return(await ad(a)).report}async function ax(e){return ad(await fetch(`/api/relationships/${encodeURIComponent(e)}/explain`))}async function ay(){return ad(await fetch("/api/relationships/health"))}let aw=[{key:"t",mod:["cmd"]},{key:"t",mod:["ctrl"]},{key:"r",mod:["cmd"]},{key:"r",mod:["ctrl"]},{key:"n",mod:["cmd","shift"]},{key:"n",mod:["ctrl","shift"]},{key:"w",mod:["cmd"]},{key:"w",mod:["ctrl"]}];function aj(e){switch(e.kind){case"ui.window.move":return"Move window";case"ui.window.resize":return"Resize window";case"ui.window.zorder":return"Reorder window";case"ui.window.close":return"Close window";case"ui.window.open":return"Open window";case"ui.workspace.pan":return"Pan workspace";case"ui.workspace.zoom":return"Zoom workspace";case"ui.workspace.fit":return"Fit workspace to view";case"ui.panel.toggle":return`Toggle ${e.panel} panel`;case"ui.selection.change":return"Change selection";case"ui.tab.switch":return"Switch tab"}}function ak(e){let t=[...e.mod].sort();return`${t.join("+")}|${e.key.toLowerCase()}`}let aN={undoStack:[],redoStack:[]};class aS extends Error{conflicts;constructor(e){super(`Workspace keyboard shortcut conflicts detected: ${e.map(e=>`${ak(e.chord)} (${e.commandIds.join(", ")})`).join("; ")}`),this.name="WorkspaceShortcutConflictError",this.conflicts=e}}class aC extends Error{reserved;constructor(e){super(`Workspace keyboard shortcut bindings refused: ${e.map(e=>`${e.commandId} → ${ak(e.chord)}`).join("; ")} are browser-reserved`),this.name="WorkspaceShortcutReservedError",this.reserved=e}}let aI=[{commandId:"undo",chord:{key:"z",mod:["cmd"]}},{commandId:"redo",chord:{key:"z",mod:["cmd","shift"]}},{commandId:"focus-status",chord:{key:"s",mod:["alt"]}}];var aE=e.i(57688);let aR="cmp-budget-exceeded-alert",a$={low:"Low",moderate:"Moderate",high:"High",exceeded:"Exceeded"},aA={low:"cmp-budget-badge cmp-budget-badge-low",moderate:"cmp-budget-badge cmp-budget-badge-moderate",high:"cmp-budget-badge cmp-budget-badge-high",exceeded:"cmp-budget-badge cmp-budget-badge-exceeded"},aT="Token counts are approximate. Actual model usage may vary.";function aL(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:e.toString()}function aP({budget:e,onClearHistory:t,disabled:l,compact:i=!1}){let[r,s]=(0,a.useState)(!1),[o,c]=(0,a.useState)(!1),d=(0,a.useRef)(null),u=(0,a.useRef)(null);if((0,a.useEffect)(()=>{r&&d.current?.focus()},[r]),void 0===e)return null;let p=e.contextWindowTokens>0,m=aL(e.approximateTokens),h=aL(e.contextWindowTokens),f=e.pressure,g=p&&"exceeded"===f;return(0,n.jsxs)("div",{className:"cmp-budget","data-pressure":p?f:"unknown",children:[(0,n.jsxs)("div",{className:"cmp-budget-row",children:[(0,n.jsx)("span",{className:"cmp-budget-count",children:p?i?`Context: ${m} / ${h}`:`Approximate context: ${m} / ${h} tokens`:i?`Context: ${m}`:`Approximate context: ${m} tokens`}),p?(0,n.jsx)("span",{className:aA[f],"aria-label":`Context pressure: ${a$[f]}`,children:a$[f]}):null,(0,n.jsx)("span",{className:"cmp-budget-info",role:"img",tabIndex:0,"aria-label":aT,"data-tip":aT,children:"i"}),r?(0,n.jsxs)("span",{className:"cmp-budget-confirm",children:[(0,n.jsx)("span",{className:"cmp-budget-confirm-label",id:"cmp-budget-confirm-label",children:"Clear history?"}),(0,n.jsx)("button",{type:"button",ref:d,className:"cmp-budget-clear","aria-describedby":"cmp-budget-confirm-label",onClick:function(){t(),s(!1),c(!0),requestAnimationFrame(()=>u.current?.focus())},children:"Clear"}),(0,n.jsx)("button",{type:"button",className:"cmp-budget-clear",onClick:function(){s(!1),requestAnimationFrame(()=>u.current?.focus())},children:"Cancel"})]}):(0,n.jsx)("button",{type:"button",ref:u,className:"cmp-budget-clear","aria-label":"Clear conversation history for next prompt",onClick:()=>{c(!1),s(!0)},disabled:!0===l,children:i?"Clear":"Clear history"}),o?(0,n.jsx)("span",{role:"status",className:"cmp-budget-cleared",children:"History cleared for the next prompt — messages remain saved."}):null]}),g?(0,n.jsx)("div",{id:aR,role:"alert",className:"cmp-budget-alert gw-error",children:"Context exceeds the selected model's window. Clear history or pick a model with a larger context."}):null]})}function aM({notice:e,className:t="ui-error-notice",id:l,onDismiss:i}){let r=`${e.title}
|
|
95
|
+
Click once to arm removal.`,"aria-label":r?`Confirm removal of connection: ${t.label}. Activate again to remove.`:l?`${t.label} — ${m} data exchange in progress. Activate to remove connection.`:`Remove connection: ${t.label}`,children:[(0,n.jsx)(j.Icons.git,{size:11})," ",(0,n.jsx)("span",{children:r?"Remove?":t.label}),l&&!r?(0,n.jsx)("span",{className:"conn-flow-tag","aria-hidden":"true",children:"heavy"===m?"⇶":"→"}):null]},t.c.id)})})]})}let eC=["n","s","e","w","ne","nw","se","sw"],eI=["t","r","b","l"];function eE({icon:e,label:t}){let a=j.Icons[e];return(0,n.jsxs)("div",{className:"too-small",children:[(0,n.jsx)("div",{className:"ts-ico",children:(0,n.jsx)(a,{size:28})}),(0,n.jsxs)("div",{className:"ts-title",children:["Too small to show ",t]}),(0,n.jsx)("div",{className:"ts-sub",children:"Enlarge the window or zoom its content out"}),(0,n.jsx)("div",{className:"ts-arrow","aria-hidden":"true",children:(0,n.jsx)("svg",{width:"22",height:"22",viewBox:"0 0 22 22",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("path",{d:"M8 8l8 8M16 11v5h-5"})})})]})}function eR({win:e,top:t,connState:l,view:i,api:r,wsRef:s}){var o;let c=E[e.type],d=void 0!==(o=e.type)&&((R[o]??[]).length>0||Object.values(R).some(e=>e.includes(o))),u=j.Icons[c.icon],[p,m]=(0,a.useState)(!1),h=(0,a.useRef)(null),f=(0,a.useRef)(null),g=e.zoom??1,v="chat"===e.type||"agents"===e.type||"quality"===e.type||"editor"===e.type,b="agents"===e.type||"quality"===e.type||"editor"===e.type,x="quality"===e.type||"editor"===e.type,y=v?r.linkedFilesRoot(e.id):null,w=b?r.linkedFilesContext(e.id)?.activeFilePath:void 0,k="quality"===e.type?r.linkedAllFilesRoots(e.id):null!==y?[y]:[],N=x?r.linkedConnectorCapsuleIds(e.id):[],S=x?r.linkedConnectorCapsuleSetIds(e.id):[],C="quality"===e.type?r.linkedFigmaSnapshotRunIds(e.id):[],I="quality"===e.type?r.linkedFigmaSnapshotSources?.(e.id):void 0,$="quality"===e.type?r.linkedImageSources?.(e.id):void 0,A=e.w/g,T=e.h/g,P=(0,a.useCallback)(t=>{r.update(e.id,{cfg:{...e.cfg,...t}})},[r,e.cfg,e.id]),M=(0,a.useCallback)((e,t)=>r.add(e,t),[r]),{mode:D,node:q}=function(e,t,a,l,i,r,s,o,c,d,u,p,m,h,f){let g=E[t];if("chat"===t){let t=a<520,n=a<430;return{mode:n?"mini":"full",node:g.render(i,{windowId:e,mini:n,minimalChat:a<360||l<320,compact:a<640,controlsNarrow:t,barCompact:a<520,workflowCompact:t,linkedRoot:r,linkedFilePath:s,linkedRoots:o,linkedCapsuleIds:c,linkedCapsuleSetIds:d,linkedFigmaSnapshotRunIds:u,linkedFigmaSnapshotSources:p,linkedImageSources:m,updateCfg:h,openWindow:f})}}return a<g.tiny.w||l<g.tiny.h?{mode:"tiny",node:(0,n.jsx)(eE,{icon:g.icon,label:g.title})}:{mode:"full",node:g.render(i,{windowId:e,linkedRoot:r,linkedFilePath:s,linkedRoots:o,linkedCapsuleIds:c,linkedCapsuleSetIds:d,linkedFigmaSnapshotRunIds:u,linkedFigmaSnapshotSources:p,linkedImageSources:m,updateCfg:h,openWindow:f})}}(e.id,e.type,A,T,e.cfg,y,w,k,N,S,C,I,$,P,M),F=(0,a.useCallback)(t=>r.update(e.id,{zoom:Math.max(.5,Math.min(2,Math.round(10*t)/10))}),[r,e.id]);(0,a.useEffect)(()=>{var t,n;if(t=e.type,n=e.cfg,"figmaView"!==t||"string"!=typeof n.selectedScreenIdsJson||!(n.selectedScreenIdsJson.length>0)||e.max||"full"!==D)return;let a=h.current;if(null===a)return;let l=null,i=()=>{l=null;let t=a.scrollHeight-a.clientHeight;if(t<=8)return;let n=Math.ceil(e.h+t);n<=e.h+8||r.update(e.id,{h:n})},s=()=>{null===l&&(l="function"==typeof window.requestAnimationFrame?window.requestAnimationFrame(i):window.setTimeout(i,0))};s();let o="u">typeof ResizeObserver?new ResizeObserver(s):null;o?.observe(a);let c=a.firstElementChild;return null!==c&&o?.observe(c),()=>{null!==l&&("function"==typeof window.cancelAnimationFrame?window.cancelAnimationFrame(l):window.clearTimeout(l)),o?.disconnect()}},[r,D,e.cfg,e.h,e.id,e.max,e.type]),(0,a.useEffect)(()=>()=>{f.current?.(),f.current=null},[]);let O=(0,a.useCallback)(t=>{t instanceof Element&&null!==t.closest("button,input,textarea,select,a[href],summary,[contenteditable='true'],[contenteditable=''],[role='button'],[role='checkbox'],[role='link'],[role='menuitem'],[role='option'],[role='radio'],[role='switch'],[role='tab']")?window.setTimeout(()=>r.focus(e.id),0):r.focus(e.id)},[r,e.id]),z=(0,a.useCallback)(t=>{var n,a,o,c;let d,u,p,h,f;if(!(B(c=t)||1===c.button)||"valid"===l)return;t.preventDefault(),O(t.target);let g=s.current;if(null===g)return;let v=(n=g.getBoundingClientRect(),{z:d=i.zoom,vpx0:-i.x/d,vpy0:-i.y/d,vpw:n.width/d,vph:n.height/d,toWX:e=>(e-n.left-i.x)/d,toWY:e=>(e-n.top-i.y)/d}),b=e.max,x=b?e.prev?.w??480:e.w,y=b?e.prev?.h??360:e.h,w=b?x/2:v.toWX(t.clientX)-e.x,j=b?18:v.toWY(t.clientY)-e.y;b&&r.update(e.id,{max:!1,w:x,h:y}),m(!0),a={winId:e.id,offX:w,offY:j,W:x},o=()=>m(!1),u=30/v.z,p=e=>{let t,n,l,i,s=v.toWX(e.clientX),o=v.toWY(e.clientY),c=s-a.offX,d=o-a.offY;c=Math.max(v.vpx0-(a.W-120),Math.min(v.vpx0+v.vpw-120,c)),d=Math.max(v.vpy0,Math.min(v.vpy0+v.vph-38,d)),r.setSnap((t=s-v.vpx0<u,n=v.vpx0+v.vpw-s<u,l=o-v.vpy0<u,i=v.vpy0+v.vph-o<u,l&&t?"tl":l&&n?"tr":i&&t?"bl":i&&n?"br":t?"left":n?"right":l?"maxi":null)),r.update(a.winId,{x:c,y:d})},h=()=>{window.removeEventListener("pointermove",p),window.removeEventListener("pointerup",h),window.removeEventListener("pointercancel",h),r.commitSnap(a.winId),f(),o?.()},f=Y(),window.addEventListener("pointermove",p),window.addEventListener("pointerup",h),window.addEventListener("pointercancel",h)},[r,e.id,e.x,e.y,e.w,e.h,e.max,e.prev,i,s,l,O]),K=(0,a.useCallback)(t=>n=>{if(!B(n))return;n.preventDefault(),n.stopPropagation(),f.current?.(),f.current=null,r.focus(e.id);let a={x:e.x,y:e.y,w:e.w,h:e.h},l=a,s=n.clientX,o=n.clientY,c=i.zoom,d=document.body.style.cursor,u=!0,p=()=>{u&&(u=!1,window.removeEventListener("pointermove",h),window.removeEventListener("pointerup",m),window.removeEventListener("pointercancel",m),window.removeEventListener("blur",m),document.body.style.cursor=d,f.current===p&&(f.current=null))},m=()=>{p()},h=n=>{var i;if(!u)return;if(0===n.buttons)return void p();let d=function(e,t,n,a,l){let{x:i,y:r,w:s,h:o}=e;t.includes("e")&&(s=e.w+n),t.includes("s")&&(o=e.h+a),t.includes("w")&&(s=e.w-n,i=e.x+n),t.includes("n")&&(o=e.h-a,r=e.y+a);let c=E[l].min,d=c.w>0?c.w:240,u=c.h>0?c.h:150;return s<d&&(t.includes("w")&&(i-=d-s),s=d),o<u&&(t.includes("n")&&(r-=u-o),o=u),{x:i,y:r,w:s,h:o}}(a,t,(n.clientX-s)/c,(n.clientY-o)/c,e.type);((i=l).x!==d.x||i.y!==d.y||i.w!==d.w||i.h!==d.h)&&(l=d,r.update(e.id,{...d,max:!1}))};document.body.style.cursor="n"===t||"s"===t?"ns-resize":"e"===t||"w"===t?"ew-resize":"ne"===t||"sw"===t?"nesw-resize":"nwse-resize",window.addEventListener("pointermove",h),window.addEventListener("pointerup",m),window.addEventListener("pointercancel",m),window.addEventListener("blur",m),f.current=p},[r,e.id,e.x,e.y,e.w,e.h,e.type,i.zoom]),_=(0,a.useCallback)((t,n)=>{let a=t.getBoundingClientRect();r.startConnect(e.id,{clientX:"clientX"in n?n.clientX:a.left+a.width/2,clientY:"clientY"in n?n.clientY:a.top+a.height/2,preventDefault:()=>n.preventDefault(),stopPropagation:()=>n.stopPropagation()})},[r,e.id]),U=(0,a.useCallback)(e=>{B(e)&&(e.preventDefault(),e.stopPropagation(),_(e.currentTarget,e))},[_]),W=(0,a.useCallback)(t=>{if("Enter"===t.key||" "===t.key||"Spacebar"===t.key){if("valid"===l)return void r.confirmConnect(e.id,{preventDefault:()=>t.preventDefault(),stopPropagation:()=>t.stopPropagation()});t.preventDefault(),t.stopPropagation(),_(t.currentTarget,t)}},[_,l,r,e.id]),V=(0,a.useCallback)(()=>{r.close(e.id),requestAnimationFrame(()=>{let e=document.querySelector('.window[data-top="true"]')??document.querySelector(".ws-fab");e?.focus({preventScroll:!0})})},[r,e.id]),H=(0,a.useCallback)(()=>{r.minimize(e.id),requestAnimationFrame(()=>{let e=document.querySelector('.window[data-top="true"]')??document.querySelector(".ws-fab");e?.focus({preventScroll:!0})})},[r,e.id]),G="full"===D?L(e.type,e.cfg):null,J="full"===D&&A>=340,X="tiny"===D?{}:{zoom:g},Q={left:e.x,top:e.y,width:e.w,height:e.h,zIndex:e.z};return(0,n.jsxs)("section",{className:"window","aria-label":null!==G?`${c.title} — ${G}`:c.title,"aria-roledescription":"window","data-top":t?"true":"false","data-max":e.max?"true":"false","data-conn":l??void 0,"data-dragging":p?"true":void 0,"data-window-id":e.id,style:Q,tabIndex:-1,onPointerDown:t=>{"valid"===l&&r.confirmConnect(e.id,t),O(t.target)},onFocusCapture:()=>{t||window.setTimeout(()=>r.focus(e.id),0)},children:[(0,n.jsxs)("header",{className:"win-head",onPointerDown:z,onDoubleClick:t=>{(function(e){let t=e.target;if(t instanceof Element&&null!==t.closest("button,[role='button']"))return!1;let n=e.currentTarget.getBoundingClientRect(),a=Math.min(210,n.width/2);return e.clientX<n.right-a})(t)&&r.maximize(e.id)},children:[(0,n.jsx)("span",{className:"win-ico",style:{color:!0===c.accent?"var(--accent)":"var(--fg-muted)"},children:(0,n.jsx)(u,{size:14})}),(0,n.jsx)("span",{className:"win-title",children:c.title}),null!==G?(0,n.jsx)("span",{className:"win-sub mono",title:G,children:(0,n.jsx)("span",{className:"win-sub-text",children:G})}):null,(0,n.jsx)("span",{className:"spacer"}),J?(0,n.jsxs)("div",{className:"win-zoom",children:[(0,n.jsx)("button",{type:"button",className:"win-zbtn ui-tip","data-tip":"Zoom content out","aria-label":`Zoom ${c.title} content out`,disabled:g<=.5,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation()},onClick:()=>F(g-.1),children:(0,n.jsx)(j.Icons.zoomOut,{size:13})}),(0,n.jsxs)("button",{type:"button",className:"win-zpct ui-tip","data-tip":"Reset content zoom to 100%","aria-label":`${String(Math.round(100*g))}% — reset ${c.title} content zoom`,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation()},onClick:()=>r.update(e.id,{zoom:1}),children:[Math.round(100*g),"%"]}),(0,n.jsx)("button",{type:"button",className:"win-zbtn ui-tip","data-tip":"Zoom content in","aria-label":`Zoom ${c.title} content in`,disabled:g>=2,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation()},onClick:()=>F(g+.1),children:(0,n.jsx)(j.Icons.zoomIn,{size:13})})]}):null,(0,n.jsxs)("div",{className:"win-traffic",role:"group","aria-label":`${c.title} window controls`,children:[(0,n.jsx)("button",{type:"button",className:"win-traffic-btn win-traffic-minimize ui-tip","data-tip":"Minimize","aria-label":`Minimize ${c.title} window`,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation()},onClick:H,children:(0,n.jsx)(j.Icons.minimize,{size:17})}),(0,n.jsx)("button",{type:"button",className:"win-traffic-btn win-traffic-maximize ui-tip","data-tip":e.max?"Restore":"Full screen","aria-label":e.max?`Restore ${c.title} window`:`Full screen ${c.title} window`,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation()},onClick:()=>r.maximize(e.id),children:e.max?(0,n.jsx)(j.Icons.restore,{size:17}):(0,n.jsx)(j.Icons.maximize,{size:17})}),(0,n.jsx)("button",{type:"button",className:"win-traffic-btn win-traffic-close ui-tip","data-tip":"Close","aria-label":`Close ${c.title} window`,onPointerDown:e=>e.stopPropagation(),onDoubleClick:e=>{e.stopPropagation()},onClick:V,children:(0,n.jsx)(j.Icons.close,{size:17})})]})]}),(0,n.jsx)("div",{ref:h,className:"win-body","data-mode":D,style:X,children:q}),e.max?null:eC.map(e=>(0,n.jsx)("div",{className:`wz wz-${e}`,onPointerDown:K(e)},e)),!e.max&&d?eI.map(e=>(0,n.jsx)("button",{type:"button",className:`win-port wp-${e}`,title:"Click to connect to another window","aria-label":`Connect ${c.title} from ${"t"===e?"top":"r"===e?"right":"b"===e?"bottom":"left"} edge`,onPointerDown:U,onKeyDown:W},`p${e}`)):null]})}let e$=[/\bsk-[A-Za-z0-9_-]{20,}\b/,/\bAKIA[0-9A-Z]{16}\b/,/\bgh[pousr]_[A-Za-z0-9]{36,}\b/,/\bxox[abporsu]-[A-Za-z0-9-]{10,}\b/,/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/,/-----BEGIN [A-Z ]*PRIVATE KEY-----/],eA=/\b(?:\d[ -]?){13,19}\b/g;e.i(47167);let eT={chat:{lifecycle:["draft","streaming","final","archived"],trustBoundary:["ui","model","evidence"],authority:"user-confirm",persistence:"durable.ui"},chatHistory:{lifecycle:["live","archived"],trustBoundary:["ui"],authority:"user-confirm",persistence:"durable.ui"},memoria:{lifecycle:["live","needs-review","archived"],trustBoundary:["ui","memory"],authority:"user-confirm",persistence:"memory-reference"},files:{lifecycle:["connecting","connected","degraded","disconnected","error"],trustBoundary:["ui","fs"],authority:"user",persistence:"fs-reference"},connector:{lifecycle:["connecting","connected","degraded","disconnected","error"],trustBoundary:["ui","fs"],authority:"user",persistence:"fs-reference"},localKnowledge:{lifecycle:["idle","connecting","connected","degraded","disconnected","error"],trustBoundary:["ui","fs","model"],authority:"user-confirm",persistence:"durable.ui"},editor:{lifecycle:["viewing","editing","unsaved","saved","error"],trustBoundary:["ui","fs"],authority:"user",persistence:"fs-reference"},browser:{lifecycle:["idle","live","error"],trustBoundary:["ui","network"],authority:"user-confirm",persistence:"transient"},terminal:{lifecycle:["idle","running","blocked","cancelled","error"],trustBoundary:["ui","tool"],authority:"user-confirm",persistence:"transient"},review:{lifecycle:["proposed","needs-review","applied","reverted","archived"],trustBoundary:["ui","evidence"],authority:"user-confirm",persistence:"evidence-reference"},agents:{lifecycle:["proposed","running","blocked","needs-review","verified","cancelled"],trustBoundary:["ui","model","tool","evidence"],authority:"user-confirm",persistence:"durable.ui"},integ:{lifecycle:["idle","connecting","connected","degraded","disconnected","error"],trustBoundary:["ui","network"],authority:"user-confirm",persistence:"durable.config"},keiko:{lifecycle:["live"],trustBoundary:["ui","memory"],authority:"user",persistence:"memory-reference"},settings:{lifecycle:["viewing","editing","saved"],trustBoundary:["ui"],authority:"user",persistence:"durable.config"},project:{lifecycle:["none","connecting","connected","disconnected"],trustBoundary:["ui","fs"],authority:"user",persistence:"durable.config"},search:{lifecycle:["idle","searching","results","error"],trustBoundary:["ui","fs"],authority:"read-only",persistence:"transient"},plugins:{lifecycle:["idle","installed","disabled","enabled"],trustBoundary:["ui"],authority:"user",persistence:"durable.config"},automations:{lifecycle:["idle","enabled","disabled"],trustBoundary:["ui"],authority:"user",persistence:"durable.config"},mobile:{lifecycle:["paired","unpaired","error"],trustBoundary:["ui","network"],authority:"user-confirm",persistence:"durable.config"},inspector:{lifecycle:["empty","focused"],trustBoundary:["ui"],authority:"ui-only",persistence:"transient"},activity:{lifecycle:["live","archived"],trustBoundary:["ui"],authority:"read-only",persistence:"transient"},notifications:{lifecycle:["unread","read","dismissed"],trustBoundary:["ui"],authority:"ui-only",persistence:"transient"},resources:{lifecycle:["live"],trustBoundary:["ui"],authority:"read-only",persistence:"transient"},quality:{lifecycle:["idle","running","results","error"],trustBoundary:["ui","model","evidence"],authority:"user-confirm",persistence:"evidence-reference"},promptEnhancer:{lifecycle:["idle","running","results","error"],trustBoundary:["ui","model","evidence"],authority:"user-confirm",persistence:"transient"},qiRun:{lifecycle:["running","final","needs-review","verified","failed","cancelled"],trustBoundary:["ui","model","evidence"],authority:"user-confirm",persistence:"evidence-reference"},relationships:{lifecycle:["idle","live","degraded","blocked","error"],trustBoundary:["ui","evidence"],authority:"user-confirm",persistence:"durable.ui"},figma:{lifecycle:["idle","running","results","error"],trustBoundary:["ui","evidence","network"],authority:"user-confirm",persistence:"evidence-reference"},figmaView:{lifecycle:["idle","results","error"],trustBoundary:["ui","evidence"],authority:"user-confirm",persistence:"evidence-reference"},figmaJson:{lifecycle:["idle","results","error"],trustBoundary:["ui","evidence"],authority:"user-confirm",persistence:"evidence-reference"},figmaImage:{lifecycle:["idle","results","error"],trustBoundary:["ui","evidence","model"],authority:"user-confirm",persistence:"evidence-reference"}},eL=["apikey","accesskey","clientsecret","credential","password","privatekey","secret","token"],eP=["api_key=","apikey=","client_secret=","clientsecret=","credential=","authorization:","password=","secret=","token="],eM=[".env",".env.local",".env.development",".env.test",".env.production"],eD={chat:["chatId"],editor:["openFiles","layoutJson"],files:["activeFilePath","activeDirectoryPath","resolvedRoot"],figma:["snapshotRunId","selectedScreenIdsJson","selectedScreenName"],figmaView:["snapshotRunId","selectedScreenIdsJson","selectedScreenName"],figmaJson:["snapshotRunId","screenId","selectedScreenIdsJson","selectedScreenName"],figmaImage:["snapshotRunId","screenId","selectedScreenName","imageSrc"]};function eq(e){return"number"==typeof e&&Number.isFinite(e)}function eF(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function eO(e){let t=e.trim();if(0===t.length)return!1;let n=t.toLowerCase();return function(e){for(let t of e$)if(t.test(e))return!0;for(let t of e.matchAll(eA)){let e=t[0].replaceAll(/[ -]/g,"");if(e.length>=13&&e.length<=19&&function(e){let t=0,n=!1;for(let a=e.length-1;a>=0;a-=1){let l=Number(e[a]);n&&(l*=2)>9&&(l-=9),t+=l,n=!n}return t%10==0}(e))return!0}return!1}(t)||function(e){let t="bearer ",n=e.toLowerCase().indexOf(t);if(-1===n)return!1;let a=0;for(let l=n+t.length;l<e.length&&0!==(e[l]??"").trim().length;l+=1)a+=1;return a>=8}(t)||function(e){if(!e.includes("://"))return!1;try{let t=new URL(e);return t.username.length>0||t.password.length>0}catch{return!1}}(t)||eP.some(e=>n.includes(e))||function(e){let t=e.toLowerCase().replaceAll("\\","/").split("/");for(let e=0;e<t.length;e+=1){let n=t[e]??"",a=t[e+1]??"";if(eM.includes(n)||".npmrc"===n||"credentials.json"===n||".aws"===n&&"credentials"===a||".ssh"===n&&a.startsWith("id_"))return!0}return!1}(t)}function ez(e){if(0===e.length||e.length>256||e.startsWith(".")||e.trim()!==e||eO(e))return!1;for(let t of e)if(!function(e){let t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||46===t||95===t||45===t}(t))return!1;return!0}function eK(e){if(0===e.length||e.length>256||e.trim()!==e||eO(e))return!1;for(let t of e){let e=t.charCodeAt(0),n=e>=48&&e<=57,a=e>=65&&e<=90,l=e>=97&&e<=122,i=46===e||58===e||95===e||45===e;if(!n&&!a&&!l&&!i)return!1}return!0}function eB(e){if(!Array.isArray(e)||0===e.length)return;let t=[];for(let n of e){if("string"!=typeof n)return;let e=n.trim().replace(/\\/gu,"/").replace(/^\/+/u,"");if(!(0===e.length||e.length>512||eO(e)||t.includes(e))&&(t.push(e),t.length>=64))break}return t.length>0?t:void 0}function e_(e){let t=[];for(let n of e){let e=function(e){var t;if(!eF(e)||!("string"==typeof(t=e.type)&&t in E))return null;let n=e.type;if("transient"===eT[n].persistence||"string"!=typeof e.id||!eq(e.x)||!eq(e.y)||!eq(e.w)||!eq(e.h)||!eq(e.z)||"boolean"!=typeof e.max)return null;let a={id:e.id,type:n,x:e.x,y:e.y,w:e.w,h:e.h,z:e.z,cfg:function(e,t){if(!eF(t)||"durable.config"===eT[e].persistence)return{};let n=new Set([...(E[e].config??[]).map(e=>e.key),...eD[e]??[]]),a={};for(let[l,i]of Object.entries(t)){if(!n.has(l))continue;let t=function(e,t,n){let a;if("editor"===e&&"openFiles"===t)return eB(n);if("editor"===e&&"layoutJson"===t)return function(e){let t;if("string"!=typeof e||0===e.length)return;try{t=JSON.parse(e)}catch{return}if("object"!=typeof t||null===t||Array.isArray(t))return;let n=t;if(2===n.schemaVersion||2===n.version){let e=eF(n.panes)?n.panes:{},t={};for(let[n,a]of Object.entries(e)){if(!eF(a))continue;let e="string"==typeof a.activeFile?a.activeFile.trim():"",l=eB(a.openFiles),i=eB(a.tabOrder)??l;if(void 0===l&&0===e.length)continue;let r=l??eB([e]);void 0!==r&&(t[n.slice(0,48)]={id:n.slice(0,48),activeFile:e.length>0?e.replace(/\\/gu,"/").replace(/^\/+/u,""):r[0],openFiles:r,tabOrder:i??r})}let a=new Set(Object.keys(t)),l=e=>{if(!eF(e))return null;if("pane"===e.type&&"string"==typeof e.paneId&&a.has(e.paneId))return{type:"pane",paneId:e.paneId};if("split"===e.type){let t=l(e.first),n=l(e.second);if(null===t||null===n)return null;let a="number"==typeof e.ratio&&Number.isFinite(e.ratio)?Math.min(85,Math.max(15,Math.round(e.ratio))):50;return{type:"split",id:"string"==typeof e.id?e.id.slice(0,48):"split-1",direction:"column"===e.direction?"column":"row",ratio:a,first:t,second:n}}return null},i=l(n.tree),r=Object.keys(t)[0];if(null===i||void 0===r)return;let s="string"==typeof n.activePaneId&&a.has(n.activePaneId)?n.activePaneId:r,o="number"==typeof n.sidebarWidth&&Number.isFinite(n.sidebarWidth)?Math.min(440,Math.max(180,Math.round(n.sidebarWidth))):260;return JSON.stringify({schemaVersion:2,root:"string"==typeof n.root?n.root:"",activePaneId:s,tree:i,panes:t,sidebarWidth:o,sidebarCollapsed:!0===n.sidebarCollapsed})}let a=Array.isArray(n.panes)?n.panes.slice(0,2):[],l=[];for(let[e,t]of a.entries()){if("object"!=typeof t||null===t||Array.isArray(t))return;let n="string"==typeof t.file?t.file.trim():"",a=eB(t.openFiles);if(n.length>512||eO(n))continue;let i=a??(n.length>0?eB([n]):void 0);void 0!==i&&l.push({id:"string"==typeof t.id&&t.id.trim().length>0?t.id.trim().slice(0,32):`pane-${e+1}`,file:n.length>0?n.replace(/\\/gu,"/").replace(/^\/+/u,""):i[0],openFiles:i})}if(0===l.length)return;let i="column"===n.direction?"column":"row",r="number"==typeof n.splitRatio&&Number.isFinite(n.splitRatio)?Math.min(75,Math.max(25,Math.round(n.splitRatio))):50,s="number"==typeof n.sidebarWidth&&Number.isFinite(n.sidebarWidth)?Math.min(440,Math.max(180,Math.round(n.sidebarWidth))):260,o="string"==typeof n.activePaneId&&l.some(e=>e.id===n.activePaneId)?n.activePaneId:l[0].id;return JSON.stringify({version:1,panes:l,activePaneId:o,direction:i,splitRatio:r,sidebarWidth:s,sidebarCollapsed:!0===n.sidebarCollapsed})}(n);if("figma"===e||"figmaView"===e||"figmaJson"===e||"figmaImage"===e)return function(e,t){if("string"==typeof t){if("snapshotRunId"===e)return ez(t)?t:void 0;if("screenId"===e)return eK(t)?t:void 0;if("imageSrc"===e)return/^\/api\/figma\/snapshots\/[^/?#]+\/screens\/\d+\/image$/u.test(t)?t:void 0;if("selectedScreenIdsJson"===e){let e;try{e=JSON.parse(t)}catch{return}if(!Array.isArray(e)||0===e.length||e.length>16)return;let n=[];for(let t of e){if("string"!=typeof t)return;let e=t.trim();if(!eK(e))return;n.push(e)}return JSON.stringify(n)}if("selectedScreenName"===e){if(t.length>256||eO(t))return;return t}}}(t,n);if("string"!=typeof n&&"number"!=typeof n&&"boolean"!=typeof n||(a=function(e){let t="";for(let n of e.toLowerCase())(n>="a"&&n<="z"||n>="0"&&n<="9")&&(t+=n);return t}(t),eL.some(e=>a.includes(e))))return;if("string"!=typeof n)return n;let l=eT[e].persistence;return"evidence-reference"===l?ez(n)?n:void 0:eO(n)?"durable.ui"===l?"[REDACTED]":void 0:n}(e,l,i);void 0!==t&&(a[l]=t)}return a}(n,e.cfg),max:e.max},l=function(e){if(eF(e)&&eq(e.x)&&eq(e.y)&&eq(e.w)&&eq(e.h))return{x:e.x,y:e.y,w:e.w,h:e.h}}(e.prev);return{...a,...!0===e.minimized?{minimized:!0}:{},...void 0!==l?{prev:l}:{},...eq(e.zoom)?{zoom:e.zoom}:{}}}(n);null!==e&&t.push("figma"!==e.type||void 0===function(e){let t=e.selectedScreenIdsJson;if("string"==typeof t)try{let e=JSON.parse(t);if(!Array.isArray(e))return;let n=e[0];return"string"==typeof n&&n.length>0?n:void 0}catch{return}}(e.cfg)?e:{...e,type:"figmaView",cfg:{...e.cfg}})}let n=t.filter(e=>"figma"===e.type);if(n.length<=1)return t;let a=n.reduce((e,t)=>t.z>e.z?t:e);return t.filter(e=>"figma"!==e.type||e.id===a.id)}function eU(e,t){let n=new Set(t.map(e=>e.id)),a=[];for(let t of e){if("string"!=typeof t.id||"string"!=typeof t.a||"string"!=typeof t.b||!n.has(t.a)||!n.has(t.b))continue;let e="string"==typeof t.boundRoot&&t.boundRoot.length>0,l="workspace-root"===t.boundScopeKind||"directory"===t.boundScopeKind||"files"===t.boundScopeKind,i="string"==typeof t.boundRelativePath&&t.boundRelativePath.length>0,r="string"==typeof t.boundChatWindowId&&t.boundChatWindowId.length>0&&n.has(t.boundChatWindowId),s=("capsule"===t.boundConnectorKind||"capsule-set"===t.boundConnectorKind)&&"string"==typeof t.boundConnectorId&&t.boundConnectorId.length>0;a.push({id:t.id,a:t.a,b:t.b,...r?{boundChatWindowId:t.boundChatWindowId}:{},...e?{boundRoot:t.boundRoot}:{},...l?{boundScopeKind:t.boundScopeKind}:{},...i?{boundRelativePath:t.boundRelativePath}:{},...s?{boundConnectorKind:t.boundConnectorKind,boundConnectorId:t.boundConnectorId}:{}})}return a}function eW(e,t,n,a,l){return{x:e.x+Math.max(16,Math.min(l+26*a,e.w-t-16)),y:e.y+Math.max(16,Math.min(l+26*a,e.h-n-16))}}function eV(e){let{prev:t,...n}=e;return n}function eH(e,t,n){return e.some(e=>e.a===t&&e.b===n||e.a===n&&e.b===t)}function eY(e,t){return e?.type==="chat"?e.id:t?.type==="chat"?t.id:null}function eG(e){return e.length>0&&(e.startsWith("/")||/^[A-Za-z]:[/\\]/u.test(e))}function eJ(e){return/^[A-Za-z]:[/\\]?$/u.test(e)?e.replace(/\\/gu,"/"):e.replace(/\\/gu,"/").replace(/\/+$/u,"")}function eX(e){if("files"!==e.type)return null;let t=e.cfg.resolvedRoot,n=e.cfg.root,a="string"==typeof t&&t.length>0?t:"string"==typeof n&&n.length>0?n:null;return null!==a&&eG(a)?a:null}function eQ(e){return e.replace(/\\/gu,"/").replace(/^\/+/u,"").replace(/\/+$/u,"")}function eZ(e,t){return void 0!==e.root&&void 0!==t.root&&eJ(e.root)===eJ(t.root)&&e.kind===t.kind&&e.relativePaths.length===t.relativePaths.length&&e.relativePaths.every((e,n)=>eQ(e)===eQ(t.relativePaths[n]??""))}function e0(e,t,n){let a="files"===e.type?e:"files"===t.type?t:null,l="chat"===e.type?e:"chat"===t.type?t:null;if(null===a||null===l)return null;let i=eX(a);if(null===i)return null;let r=a.cfg.activeFilePath;if("string"==typeof r&&r.length>0)return{kind:"files",relativePaths:[eQ(r)],root:eJ(i),connectedAtMs:n};let s=a.cfg.activeDirectoryPath;return"string"==typeof s&&s.length>0?{kind:"directory",relativePaths:[eQ(s)],root:eJ(i),connectedAtMs:n}:{kind:"workspace-root",relativePaths:[],root:eJ(i),connectedAtMs:n}}function e1(e){if("string"!=typeof e.boundRoot||0===e.boundRoot.length)return null;let t=Date.now();return"directory"===e.boundScopeKind?"string"!=typeof e.boundRelativePath||0===e.boundRelativePath.length?null:{kind:"directory",relativePaths:[eQ(e.boundRelativePath)],root:eJ(e.boundRoot),connectedAtMs:t}:"files"===e.boundScopeKind?"string"!=typeof e.boundRelativePath||0===e.boundRelativePath.length?null:{kind:"files",relativePaths:[eQ(e.boundRelativePath)],root:eJ(e.boundRoot),connectedAtMs:t}:{kind:"workspace-root",relativePaths:[],root:eJ(e.boundRoot),connectedAtMs:t}}function e2(e){return Math.max(e.maxConnectedSources,e.maxLocalKnowledgeSources)}function e4(e,t){return e.filter(e=>!eZ(e,t))}function e3(e){return e.connectedScopes??(void 0!==e.connectedScope?[e.connectedScope]:[])}function e6(e){return e.localKnowledgeScopes??(void 0!==e.localKnowledgeScope?[e.localKnowledgeScope]:[])}function e5(e){return"capsule"===e.kind?`capsule:${e.capsuleId}`:`set:${e.capsuleSetId}`}function e8(e){return"string"!=typeof e.boundConnectorId||0===e.boundConnectorId.length?null:"capsule"===e.boundConnectorKind?{kind:"capsule",capsuleId:e.boundConnectorId,connectedAtMs:0}:"capsule-set"===e.boundConnectorKind?{kind:"capsule-set",capsuleSetId:e.boundConnectorId,connectedAtMs:0}:null}function e7(e,t){let n="connector"===e.type?e:"connector"===t.type?t:null,a="chat"===e.type?e:"chat"===t.type?t:null;if(null===n||null===a)return null;let l=n.cfg.selectedKind,i=n.cfg.selectedId;if("string"!=typeof l||"string"!=typeof i)return null;let r=i.trim();return 0===r.length?null:"capsule"===l?{kind:"capsule",capsuleId:r,connectedAtMs:Date.now()}:"capsule-set"===l?{kind:"capsule-set",capsuleSetId:r,connectedAtMs:Date.now()}:null}let e9="keiko.workspace.v4",te="keiko.conns.v1",tt="keiko.view";function tn(){try{let e=window.localStorage.getItem(tt);if(null===e)return{zoom:1,x:0,y:0};let t=JSON.parse(e);if("object"==typeof t&&null!==t&&"zoom"in t&&"number"==typeof t.zoom)return{zoom:t.zoom,x:"number"==typeof t.x?t.x:0,y:"number"==typeof t.y?t.y:0}}catch{}return{zoom:1,x:0,y:0}}function ta(e){return Math.max(.3,Math.min(2.5,e))}function tl(e){return Math.max(.5,Math.min(2,Math.round(10*e)/10))}function ti(e){let t=null;for(let n=0;n<e.length;n++){let a=e[n];if(!0!==a.minimized){if(null===t){t=a;continue}a.z>t.z&&(t=a)}}return t}function tr(e,t){try{window.localStorage.setItem(e,JSON.stringify(t))}catch{}}function ts(e){let t=e.deltaMode===WheelEvent.DOM_DELTA_LINE?16:2===e.deltaMode?800:1;return{x:e.deltaX*t,y:e.deltaY*t}}let to={Equal:"=",NumpadAdd:"+",Minus:"-",NumpadSubtract:"-",Digit0:"0",Numpad0:"0"},tc="application/x-keiko-local-knowledge-connector",td="keiko:local-knowledge-connector-drop";function tu(e){if(!Array.from(e.types).includes(tc))return null;try{let t=JSON.parse(e.getData(tc));if("object"!=typeof t||null===t||"capsule"!==t.kind||"string"!=typeof t.id||0===t.id.trim().length)return null;let n="string"==typeof t.label?t.label.trim():"",a="string"==typeof t.lifecycleState?t.lifecycleState.trim():"";return{kind:"capsule",id:t.id.trim(),...n.length>0?{label:n}:{},...a.length>0?{lifecycleState:a}:{}}}catch{return null}}let tp="application/x-keiko-figma-view",tm="keiko:figma-view-drop";function th(e){return"string"==typeof e&&e.trim().length>0?e.trim():null}function tf(e){if(!Array.from(e.types).includes(tp))return null;try{let t=JSON.parse(e.getData(tp));if("object"!=typeof t||null===t)return null;let n=th(t.snapshotRunId),a=th(t.screenId),l=th(t.name);if(null===n||null===a||null===l)return null;return{snapshotRunId:n,screenId:a,name:l}}catch{return null}}let tg="application/x-keiko-figma-json",tv="keiko:figma-json-drop";function tb(e){return"string"==typeof e&&e.trim().length>0?e.trim():null}function tx(e){if(!Array.from(e.types).includes(tg))return null;try{let t=JSON.parse(e.getData(tg));if("object"!=typeof t||null===t)return null;let n=tb(t.snapshotRunId),a=tb(t.screenId),l=tb(t.name);if(null===n||null===a||null===l)return null;let i=tb(t.sourceWindowId);return{snapshotRunId:n,screenId:a,name:l,...null!==i?{sourceWindowId:i}:{}}}catch{return null}}let ty="application/x-keiko-figma-image",tw="keiko:figma-image-drop";function tj(e){return"string"==typeof e&&e.trim().length>0?e.trim():null}function tk(e){if(!Array.from(e.types).includes(ty))return null;try{let t=JSON.parse(e.getData(ty));if("object"!=typeof t||null===t)return null;let n=tj(t.snapshotRunId),a=tj(t.screenId),l=tj(t.name),i=tj(t.imageSrc);if(null===n||null===a||null===l||null===i||!/^\/api\/figma\/snapshots\/[^/?#]+\/screens\/\d+\/image$/u.test(i))return null;let r=tj(t.sourceWindowId);return{snapshotRunId:n,screenId:a,name:l,imageSrc:i,...null!==r?{sourceWindowId:r}:{}}}catch{return null}}let tN={w:260,h:220},tS={w:360,h:360},tC={w:520,h:540},tI={w:560,h:420};function tE({clientX:e,clientY:t,rect:n,view:a,size:l=tN}){return{x:Math.round((e-n.left-a.x)/a.zoom-l.w/2),y:Math.round((t-n.top-a.y)/a.zoom-28)}}function tR(e,t){let n=e+t;return e<1&&n>1||e>1&&n<1?1:n}function t$(e,t,n){t.preventDefault();let a=t.currentTarget;a.setPointerCapture?.(t.pointerId);let l=t.clientX,i=t.clientY,r=Y();n(!0);let s=t=>{e(t.clientX-l,t.clientY-i),l=t.clientX,i=t.clientY},o=()=>{window.removeEventListener("pointermove",s),window.removeEventListener("pointerup",o),window.removeEventListener("pointercancel",o),n(!1),a.hasPointerCapture?.(t.pointerId)===!0&&a.releasePointerCapture?.(t.pointerId),r()};window.addEventListener("pointermove",s),window.addEventListener("pointerup",o),window.addEventListener("pointercancel",o)}function tA({wins:e,connecting:t,conns:l}){let[i,r]=(0,a.useState)(""),s=(0,a.useRef)(null),o=(0,a.useRef)(l.length);return(0,a.useEffect)(()=>{let n=s.current;s.current=t;let a=o.current;if(o.current=l.length,null===n&&null!==t){let n=e?.find(e=>e.id===t.from),a=void 0!==n?E[n.type].title:"window";r(`Connecting from ${a} — select a highlighted window, press Escape to cancel`);return}if(null!==n&&null===t)if(l.length>a){let t=l[l.length-1],n=void 0!==t?e?.find(e=>e.id===t.a):void 0,a=void 0!==t?e?.find(e=>e.id===t.b):void 0;r(void 0!==n&&void 0!==a?`Connected: ${A(n,a)}`:"Connected")}else r("Connection cancelled")},[t,l,e]),(0,n.jsx)("div",{className:"sr-only","aria-live":"polite",children:i})}function tT({ws:e,wsRef:t,openPalette:l,palette:i}){let{wins:r,view:s,snapPrev:o,conns:c,connecting:d,api:u}=e,[p,m]=(0,a.useState)(!1),[h,f]=(0,a.useState)(!1),g=(0,a.useRef)(!1),v=(0,a.useMemo)(()=>null===r?null:r.filter(e=>!0!==e.minimized),[r]),b=function(e){if(null===e||0===e.length)return null;let t=null;for(let n=0;n<e.length;n++){let a=e[n];if(!0!==a.minimized){if(null===t){t=a;continue}a.z>t.z&&(t=a)}}return t}(v),x=null!==d&&null!==v?v.find(e=>e.id===d.from)??null:null;(0,a.useEffect)(()=>{let e=e=>{g.current=e,f(e)},t=t=>{var n;!("Space"!==t.code||(n=t.target)instanceof Element&&null!==n.closest("input,textarea,select,button,a[href],summary,[contenteditable='true'],[contenteditable=''],[role='button'],[role='checkbox'],[role='dialog'],[role='link'],[role='menuitem'],[role='option'],[role='radio'],[role='switch'],[role='tab']"))&&(t.preventDefault(),g.current||e(!0))},n=t=>{"Space"===t.code&&e(!1)},a=()=>{e(!1)};return window.addEventListener("keydown",t),window.addEventListener("keyup",n),window.addEventListener("blur",a),()=>{window.removeEventListener("keydown",t),window.removeEventListener("keyup",n),window.removeEventListener("blur",a)}},[]);let y=(0,a.useMemo)(()=>({backgroundSize:`${String(22*s.zoom)}px ${String(22*s.zoom)}px`,backgroundPosition:`${String(s.x)}px ${String(s.y)}px`}),[s]),w=(0,a.useMemo)(()=>({transform:`translate(${String(s.x/s.zoom)}px, ${String(s.y/s.zoom)}px)`,transformOrigin:"0 0",zoom:s.zoom}),[s]),k=(0,a.useCallback)((e,t,n,a)=>{let l=u.add("connector",{presentation:"node",selectedKind:e.kind,selectedId:e.id,...void 0!==e.label?{selectedLabel:e.label}:{},...void 0!==e.lifecycleState?{selectedState:e.lifecycleState}:{}});null!==l&&u.update(l,{...tE({clientX:t,clientY:n,rect:a,view:s}),...tN})},[u,s]),N=(0,a.useCallback)((e,t,n,a)=>{let l=u.add("figmaView",{snapshotRunId:e.snapshotRunId,selectedScreenIdsJson:JSON.stringify([e.screenId]),selectedScreenName:e.name});null!==l&&u.update(l,{...tE({clientX:t,clientY:n,rect:a,view:s,size:tS}),...tS})},[u,s]),S=(0,a.useCallback)(e=>{if(null===r)return[];let t=new Map(r.map(e=>[e.id,e])),n=[];for(let a of c){let l=a.a===e?a.b:a.b===e?a.a:null;if(null===l)continue;let i=t.get(l);i?.type==="quality"&&n.push({connId:a.id,qualityId:i.id})}return n},[c,r]),C=(0,a.useCallback)((e,t,n,a)=>{let l=u.add("figmaJson",{snapshotRunId:e.snapshotRunId,screenId:e.screenId,selectedScreenIdsJson:JSON.stringify([e.screenId]),selectedScreenName:e.name});if(null===l||(u.update(l,{...tE({clientX:t,clientY:n,rect:a,view:s,size:tC}),...tC}),void 0===e.sourceWindowId))return;let i=S(e.sourceWindowId);if(0!==i.length){for(let e of i)u.removeConn(e.connId);window.setTimeout(()=>{for(let e of i)u.connect(l,e.qualityId)},0)}},[u,S,s]),I=(0,a.useCallback)((e,t,n,a)=>{let l=u.add("figmaImage",{snapshotRunId:e.snapshotRunId,screenId:e.screenId,selectedScreenName:e.name,imageSrc:e.imageSrc});if(null===l||(u.update(l,{...tE({clientX:t,clientY:n,rect:a,view:s,size:tI}),...tI}),void 0===e.sourceWindowId))return;let i=S(e.sourceWindowId);if(0!==i.length){for(let e of i)u.removeConn(e.connId);window.setTimeout(()=>{for(let e of i)u.connect(l,e.qualityId)},0)}},[u,S,s]);(0,a.useEffect)(()=>{let e=e=>{if(!(e instanceof CustomEvent)||!function(e){if("object"!=typeof e||null===e)return!1;let t=e.payload;return"number"==typeof e.clientX&&"number"==typeof e.clientY&&"object"==typeof t&&null!==t&&"capsule"===t.kind&&"string"==typeof t.id}(e.detail))return;let n=t.current?.getBoundingClientRect();if(void 0===n)return;let{clientX:a,clientY:l,payload:i}=e.detail;a<n.left||a>n.right||l<n.top||l>n.bottom||k(i,a,l,n)};return window.addEventListener(td,e),()=>{window.removeEventListener(td,e)}},[k,t]),(0,a.useEffect)(()=>{let e=e=>{if(!(e instanceof CustomEvent)||!function(e){if("object"!=typeof e||null===e)return!1;let t=e.payload;return"number"==typeof e.clientX&&"number"==typeof e.clientY&&"object"==typeof t&&null!==t&&"string"==typeof t.snapshotRunId&&"string"==typeof t.screenId&&"string"==typeof t.name}(e.detail))return;let n=t.current?.getBoundingClientRect();if(void 0===n)return;let{clientX:a,clientY:l,payload:i}=e.detail;a<n.left||a>n.right||l<n.top||l>n.bottom||N(i,a,l,n)};return window.addEventListener(tm,e),()=>{window.removeEventListener(tm,e)}},[N,t]),(0,a.useEffect)(()=>{let e=e=>{if(!(e instanceof CustomEvent)||!function(e){if("object"!=typeof e||null===e)return!1;let t=e.payload;return"number"==typeof e.clientX&&"number"==typeof e.clientY&&"object"==typeof t&&null!==t&&"string"==typeof t.snapshotRunId&&"string"==typeof t.screenId&&"string"==typeof t.name&&(void 0===t.sourceWindowId||"string"==typeof t.sourceWindowId)}(e.detail))return;let n=t.current?.getBoundingClientRect();if(void 0===n)return;let{clientX:a,clientY:l,payload:i}=e.detail;a<n.left||a>n.right||l<n.top||l>n.bottom||C(i,a,l,n)};return window.addEventListener(tv,e),()=>{window.removeEventListener(tv,e)}},[C,t]),(0,a.useEffect)(()=>{let e=e=>{if(!(e instanceof CustomEvent)||!function(e){if("object"!=typeof e||null===e)return!1;let t=e.payload;return"number"==typeof e.clientX&&"number"==typeof e.clientY&&"object"==typeof t&&null!==t&&"string"==typeof t.snapshotRunId&&"string"==typeof t.screenId&&"string"==typeof t.name&&"string"==typeof t.imageSrc&&(void 0===t.sourceWindowId||"string"==typeof t.sourceWindowId)}(e.detail))return;let n=t.current?.getBoundingClientRect();if(void 0===n)return;let{clientX:a,clientY:l,payload:i}=e.detail;a<n.left||a>n.right||l<n.top||l>n.bottom||I(i,a,l,n)};return window.addEventListener(tw,e),()=>{window.removeEventListener(tw,e)}},[I,t]);let E=null!==r&&0===r.length,R=r?.some(e=>e.max)??!1;return(0,n.jsxs)("main",{className:"workspace",ref:t,"aria-label":"Workspace surface",tabIndex:0,"data-window-maxed":R?"true":void 0,"data-canvas-overlays-hidden":R?"true":"false","data-connecting":null!==d?"true":void 0,"data-panning":p?"true":void 0,"data-hand-tool":h?"true":void 0,onPointerDownCapture:e=>{var t;if(U())return;if(g.current&&B(e)&&null===d&&!((t=e.target)instanceof Element&&null!==t.closest("input, textarea, select, [contenteditable='true'], [contenteditable='']"))&&!_(e.target)){t$(u.panBy,e,m),e.stopPropagation();return}if(0!==e.button||null===d||null===x||null===v)return;let n=function(e){if(!(e instanceof Element))return;let t=e.closest(".window[data-window-id]");return t?.dataset.windowId}(e.target);if(void 0===n||n===x.id)return;let a=v.find(e=>e.id===n);void 0!==a&&$(x.type,a.type)&&u.confirmConnect(a.id,e)},onPointerDown:e=>{if(!(U()||_(e.target))){var t;if(null!==d){B(e)&&u.cancelConnect();return}(B(t=e)||1===t.button)&&t$(u.panBy,e,m)}},onKeyDown:e=>{if(e.target!==e.currentTarget)return;let t=e.shiftKey?192:48;switch(e.key){case"ArrowLeft":u.panBy(t,0);break;case"ArrowRight":u.panBy(-t,0);break;case"ArrowUp":u.panBy(0,t);break;case"ArrowDown":u.panBy(0,-t);break;default:return}e.preventDefault()},onDragOver:e=>{(null!==tu(e.dataTransfer)||null!==tf(e.dataTransfer)||null!==tx(e.dataTransfer)||null!==tk(e.dataTransfer))&&(e.preventDefault(),e.dataTransfer.dropEffect="copy")},onDrop:e=>{let t=tu(e.dataTransfer),n=tf(e.dataTransfer),a=tx(e.dataTransfer),l=tk(e.dataTransfer);if(null===t&&null===n&&null===a&&null===l)return;e.preventDefault(),e.stopPropagation();let i=e.currentTarget.getBoundingClientRect();null!==t?k(t,e.clientX,e.clientY,i):null!==n?N(n,e.clientX,e.clientY,i):null!==a?C(a,e.clientX,e.clientY,i):null!==l&&I(l,e.clientX,e.clientY,i)},children:[(0,n.jsx)(ew,{}),(0,n.jsx)("div",{className:"ws-grid",style:y,"aria-hidden":"true"}),(0,n.jsx)(tA,{wins:v,connecting:d,conns:c}),null!==d?(0,n.jsx)("div",{className:"ws-connect-hint","aria-hidden":"true",children:"Click a highlighted window to connect — Esc to cancel"}):null,E?(0,n.jsx)("div",{className:"ws-empty",children:(0,n.jsx)(K,{onNewWindow:l})}):null,(0,n.jsxs)("div",{className:"ws-scene",style:w,children:[null!==o?(0,n.jsx)("div",{className:"snap-ghost",style:{left:o.x,top:o.y,width:o.w,height:o.h}}):null,null!==v?(0,n.jsx)(eS,{wins:v,conns:c,connecting:d,api:u}):null,null!==v?v.map(e=>(0,n.jsx)(eR,{win:e,top:null!==b&&e.id===b.id,connState:null===x?null:e.id===x.id?"source":$(x.type,e.type)?"valid":"invalid",view:s,api:u,wsRef:t},e.id)):null]}),(0,n.jsxs)("div",{className:"ws-zoom",children:[(0,n.jsx)("button",{type:"button",className:"ws-zoom-btn ui-tip cmp-tip-start",onClick:()=>u.zoomTo(tR(s.zoom,-.2)),disabled:s.zoom<=.3,"aria-label":"Zoom out","data-tip":"Zoom out",children:(0,n.jsx)(j.Icons.zoomOut,{size:15})}),(0,n.jsx)("button",{type:"button",className:"ws-zoom-btn ui-tip cmp-tip-start",onClick:u.fitView,disabled:null===v||0===v.length,"aria-label":"Fit workspace to windows","data-tip":"Fit workspace to windows",children:(0,n.jsx)(j.Icons.expand,{size:15})}),(0,n.jsxs)("button",{type:"button",className:"ws-zoom-pct mono ui-tip",onClick:u.resetView,"aria-label":`${String(Math.round(100*s.zoom))}% — reset`,"data-tip":"Reset",children:[Math.round(100*s.zoom),"%"]}),(0,n.jsx)("button",{type:"button",className:"ws-zoom-btn ui-tip cmp-tip-end",onClick:()=>u.zoomTo(tR(s.zoom,.2)),disabled:s.zoom>=2.5,"aria-label":"Zoom in","data-tip":"Zoom in",children:(0,n.jsx)(j.Icons.zoomIn,{size:15})})]}),(0,n.jsx)("button",{type:"button",className:"ws-fab ui-tip cmp-tip-end",onPointerDown:e=>e.stopPropagation(),onClick:l,"aria-label":"New window","data-tip":"New window",children:(0,n.jsx)(j.Icons.add,{size:20})}),R?null:i??null]})}function tL({commands:e,onClose:t}){let[l,i]=(0,a.useState)(""),[r,s]=(0,a.useState)(0),o=(0,a.useRef)(null),c=(0,a.useRef)(null),d=(0,a.useRef)(null);(0,a.useEffect)(()=>(c.current=document.activeElement,()=>{c.current?.focus?.()}),[]),(0,a.useEffect)(()=>{o.current?.focus()},[]);let u=(0,a.useMemo)(()=>{let t=l.toLowerCase();return e.filter(e=>`${e.label} ${e.group??""}`.toLowerCase().includes(t))},[e,l]);(0,a.useEffect)(()=>{s(0)},[l]),(0,a.useEffect)(()=>{document.getElementById(`cmdk-row-${String(r)}`)?.scrollIntoView?.({block:"nearest"})},[r,u]);let p=e=>{void 0!==e&&(e.run(),t())};return(0,n.jsx)("div",{className:"cmdk-overlay",onPointerDown:t,children:(0,n.jsxs)("div",{ref:d,className:"cmdk",role:"dialog","aria-modal":"true","aria-labelledby":"cmdk-title","aria-describedby":"cmdk-desc",tabIndex:-1,onPointerDown:e=>e.stopPropagation(),onKeyDown:e=>{if("Tab"===e.key){let t=Array.from(d.current?.querySelectorAll("button:not([disabled]),input:not([disabled]),[tabindex]:not([tabindex='-1'])")??[]);if(t.length>0){let n=t[0],a=t[t.length-1];if(e.shiftKey&&document.activeElement===n){e.preventDefault(),a.focus();return}if(!e.shiftKey&&document.activeElement===a){e.preventDefault(),n.focus();return}}}if("ArrowDown"===e.key){e.preventDefault(),s(e=>Math.min(u.length-1,e+1));return}if("ArrowUp"===e.key){e.preventDefault(),s(e=>Math.max(0,e-1));return}if("Enter"===e.key){e.preventDefault(),p(u[r]);return}"Escape"===e.key&&t()},children:[(0,n.jsx)("h2",{id:"cmdk-title",className:"sr-only",children:"Command palette"}),(0,n.jsx)("p",{id:"cmdk-desc",className:"sr-only",children:"Search commands and press Enter to run the selected action."}),(0,n.jsxs)("div",{className:"cmdk-input",children:[(0,n.jsx)(j.Icons.search,{size:16}),(0,n.jsx)("input",{ref:o,role:"combobox","aria-expanded":"true","aria-controls":"cmdk-list","aria-activedescendant":u.length>0?`cmdk-row-${String(r)}`:void 0,"aria-label":"Command query",placeholder:"Type a command…",value:l,onChange:e=>i(e.target.value)}),(0,n.jsx)("span",{className:"kbd",children:"esc"})]}),(0,n.jsx)("div",{className:"sr-only",role:"status",children:0===u.length?"No matching commands":`${String(u.length)} command${1===u.length?"":"s"}`}),(0,n.jsxs)("div",{id:"cmdk-list",role:"listbox",className:"cmdk-list",children:[0===u.length&&(0,n.jsx)("div",{className:"cmdk-empty",children:"No matching commands"}),u.map((e,t)=>{var a;let l;return(0,n.jsxs)("div",{role:"option",id:`cmdk-row-${String(t)}`,"aria-selected":t===r,className:"cmdk-row","data-sel":t===r,tabIndex:-1,onMouseEnter:()=>s(t),onClick:()=>p(e),children:[(0,n.jsx)("span",{className:"cmdk-ico",children:(a=e.icon,l=j.Icons[a]??j.Icons.spark,(0,n.jsx)(l,{size:16}))}),(0,n.jsx)("span",{className:"cmdk-label",children:e.label}),(0,n.jsx)("span",{className:"spacer"}),void 0!==e.shortcut&&(0,n.jsx)("span",{className:"kbd",children:e.shortcut}),void 0!==e.group&&(0,n.jsx)("span",{className:"cmdk-group mono",children:e.group})]},e.id)})]})]})})}var tP=e.i(74080);function tM(e){return Array.from(new Set(e.split(/[\n,]/u).map(e=>e.trim()).filter(e=>e.length>0)))}function tD({onCancel:e,preserveExisting:t=!1,storedApiKeyHeaderName:l,storedModels:i=[]}){let r=(0,a.useRef)(null),s=(0,a.useRef)(null),o=(0,a.useRef)(null),c=(0,a.useRef)(null),d=(0,a.useRef)(void 0),[u,p]=(0,a.useState)(""),[m,h]=(0,a.useState)(""),[f,g]=(0,a.useState)(""),[v,b]=(0,a.useState)(""),[x,y]=(0,a.useState)(""),[k,N]=(0,a.useState)(""),[S,C]=(0,a.useState)(""),[I,E]=(0,a.useState)(!1),[R,$]=(0,a.useState)(),[A,T]=(0,a.useState)(),[L,P]=(0,a.useState)();async function M(e){if(e.preventDefault(),!I){var n;E(!0),$(void 0),T(void 0),P(void 0),r.current?.focus();try{let e,a=tM(x);if(function(e){try{return new URL(e.trim()).hostname.endsWith(".services.ai.azure.com")}catch{return!1}}(u)&&0===a.length){$("Azure AI Foundry requires deployment names. Paste the names from the Deployments tab."),E(!1);return}try{e=function(e){let t=e.trim();if(""===t)return;let n=Number(t);if(!Number.isInteger(n)||n<=0)throw Error("Request timeout must be a positive integer in milliseconds.");return n}(v)}catch(e){$(e instanceof Error?e.message:"Request timeout is invalid."),E(!1);return}let l=tM(k),i=!t||""!==u.trim()||""!==m.trim()||""!==f.trim()||a.length>0||l.length>0,r=i||void 0!==e,s=""!==S.trim(),o=await (0,w.setupGateway)({baseUrl:""===u.trim()?void 0:u.trim(),apiKey:""===m.trim()?void 0:m.trim(),apiKeyHeaderName:""===f.trim()?void 0:f.trim(),...void 0===e?{}:{timeoutMs:e},deploymentNames:a,preserveExisting:t,...0===l.length?{}:{imageInputModelIds:l},...""===S.trim()?{}:{figmaAccessToken:S.trim()}}),c=o.testedModelIds.length,p=(n=o.skippedModelIds??[],0===n.length?"":` Could not verify deployment${1===n.length?"":"s"}: ${n.join(", ")}.`);E(!1),s&&!r?P("Verified Figma access token. Reloading Keiko…"):s&&!i?P("Updated model gateway settings and verified Figma access token. Reloading Keiko…"):s||i?s?P(`Verified ${String(c)} workflow chat model${1===c?"":"s"} and Figma access token. Reloading Keiko…${p}`):P(`Verified ${String(c)} workflow chat model${1===c?"":"s"}. Reloading Keiko…${p}`):P("Updated model gateway settings. Reloading Keiko…"),d.current=window.setTimeout(()=>window.location.reload(),0===(o.skippedModelIds??[]).length?800:1800)}catch(t){let e=t instanceof w.ApiError?{message:t.message,code:t.code}:t instanceof Error?{message:t.message}:{message:"The gateway could not be configured."};$(e.message),T(e.code),E(!1)}}}(0,a.useEffect)(()=>{let e=document.documentElement,n=Number(e.dataset.keikoModalOpenCount??"0");e.dataset.keikoModalOpenCount=String(n+1),e.setAttribute("data-keiko-modal-open","true");let a=Number(e.dataset.keikoGatewaySetupOpenCount??"0");return e.dataset.keikoGatewaySetupOpenCount=String(a+1),e.setAttribute("data-keiko-gateway-setup-open","true"),c.current=document.activeElement,t?o.current?.focus():s.current?.focus(),()=>{void 0!==d.current&&window.clearTimeout(d.current);let t=Math.max(0,Number(e.dataset.keikoModalOpenCount??"1")-1);0===t?(delete e.dataset.keikoModalOpenCount,e.removeAttribute("data-keiko-modal-open")):e.dataset.keikoModalOpenCount=String(t);let n=Math.max(0,Number(e.dataset.keikoGatewaySetupOpenCount??"1")-1);0===n?(delete e.dataset.keikoGatewaySetupOpenCount,e.removeAttribute("data-keiko-gateway-setup-open")):e.dataset.keikoGatewaySetupOpenCount=String(n),c.current?.focus?.()}},[t]),(0,a.useEffect)(()=>{let t=r.current;if(null===t)return;let n=n=>{if("Escape"===n.key){if(I||void 0!==L||void 0===e)return;n.preventDefault(),e();return}if("Tab"!==n.key)return;let a=Array.from(t.querySelectorAll("button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),summary,[tabindex]:not([tabindex='-1'])"));if(0===a.length)return;let l=a[0],i=a[a.length-1];n.shiftKey&&document.activeElement===l?(n.preventDefault(),i.focus()):n.shiftKey||document.activeElement!==i||(n.preventDefault(),l.focus())};return t.addEventListener("keydown",n),()=>t.removeEventListener("keydown",n)},[I,e,L]),(0,a.useEffect)(()=>{void 0===R||I||(t&&""===u.trim()&&""===m.trim()?o.current?.focus():s.current?.focus())},[m,u,I,R,t]);let D=tM(x),q=tM(k),F=!t,O=""!==u.trim()||""!==m.trim()||""!==f.trim()||""!==v.trim()||D.length>0||q.length>0,z=""!==S.trim(),K=!I&&void 0===L&&(F?""!==u.trim()&&""!==m.trim():O||z),B=i.map(e=>e.id),_=B.slice(0,6),U=Math.max(0,B.length-_.length),W=(0,n.jsxs)("div",{className:"gw-grid",children:[(0,n.jsxs)("label",{className:"gw-field gw-span-2",children:[(0,n.jsxs)("span",{children:["Base URL ",t?(0,n.jsx)("span",{className:"dlg-opt",children:"leave blank to keep"}):null]}),(0,n.jsx)("input",{className:"gw-input mono",value:u,placeholder:t?"Only enter a value to replace the stored gateway URL":"https://llm-gateway.example.com/v1",autoComplete:"off",disabled:I||void 0!==L,ref:s,onChange:e=>p(e.target.value)})]}),(0,n.jsxs)("label",{className:"gw-field",children:[(0,n.jsxs)("span",{children:["API token ",t?(0,n.jsx)("span",{className:"dlg-opt",children:"leave blank to keep"}):null]}),(0,n.jsx)("input",{className:"gw-input mono",type:"password",value:m,placeholder:t?"Only enter a value to replace the stored token":"Paste your API token",autoComplete:"off",disabled:I||void 0!==L,onChange:e=>h(e.target.value)})]}),(0,n.jsxs)("label",{className:"gw-field",children:[(0,n.jsxs)("span",{children:["API key header ",(0,n.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,n.jsx)("input",{className:"gw-input mono",value:f,placeholder:t?"Leave blank to keep stored header":"Authorization",autoComplete:"off",disabled:I||void 0!==L,onChange:e=>g(e.target.value)})]}),(0,n.jsxs)("label",{className:"gw-field",children:[(0,n.jsxs)("span",{children:["Request timeout (ms) ",(0,n.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,n.jsx)("input",{className:"gw-input mono",inputMode:"numeric",value:v,placeholder:t?"Leave blank to keep stored timeout":"30000",autoComplete:"off",disabled:I||void 0!==L,onChange:e=>b(e.target.value)})]}),(0,n.jsxs)("label",{className:"gw-field",children:[(0,n.jsx)("span",{children:"Deployment names for Azure"}),(0,n.jsx)("textarea",{className:"gw-input gw-textarea mono",value:x,placeholder:"Paste deployment names, one per line",autoComplete:"off",disabled:I||void 0!==L,onChange:e=>y(e.target.value)})]}),(0,n.jsxs)("label",{className:"gw-field",children:[(0,n.jsxs)("span",{children:["Image-input models ",(0,n.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,n.jsx)("textarea",{className:"gw-input gw-textarea mono",value:k,placeholder:"Paste image-capable model names, one per line",autoComplete:"off",disabled:I||void 0!==L,onChange:e=>N(e.target.value)})]})]}),V=(0,n.jsx)("div",{className:"gw-setup-backdrop",role:"presentation",children:(0,n.jsx)("div",{ref:r,className:"gw-setup",role:"dialog","aria-modal":"true","aria-labelledby":"gw-setup-title","aria-describedby":"gw-setup-desc",tabIndex:-1,children:(0,n.jsxs)("form",{className:"gw-form",onSubmit:e=>void M(e),children:[(0,n.jsxs)("div",{className:"gw-head",children:[(0,n.jsxs)("div",{className:"gw-setup-badge",children:[(0,n.jsx)(j.Icons.cube,{size:18}),t?"Credential update":"Model gateway setup"]}),(0,n.jsx)("h1",{id:"gw-setup-title",children:t?"Update Keiko credentials":"Connect Keiko to your internal LLMs"}),(0,n.jsx)("p",{id:"gw-setup-desc",children:t?"Leave stored gateway fields blank to keep the current value. Keiko never returns existing secrets to the browser.":"Keiko needs the internal gateway URL and API token before chat and agent workflows can run. The token is tested once and stored only on this machine."})]}),(0,n.jsxs)("section",{className:"gw-section","aria-labelledby":"gw-model-section-title",children:[(0,n.jsx)("div",{className:"gw-section-head",children:(0,n.jsxs)("div",{children:[(0,n.jsx)("h2",{id:"gw-model-section-title",children:"Model gateway"}),(0,n.jsx)("p",{children:t?"Blank gateway fields keep the stored value.":"Base URL and API token are required."})]})}),t?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"gw-current","aria-label":"Stored model gateway credentials",children:[(0,n.jsxs)("div",{className:"gw-current-row",children:[(0,n.jsx)("span",{children:"Gateway URL"}),(0,n.jsx)("strong",{children:"Stored"})]}),(0,n.jsxs)("div",{className:"gw-current-row",children:[(0,n.jsx)("span",{children:"API token"}),(0,n.jsx)("strong",{className:"mono",children:"••••••••••••"})]}),(0,n.jsxs)("div",{className:"gw-current-row",children:[(0,n.jsx)("span",{children:"API key header"}),(0,n.jsx)("strong",{className:"mono",children:l??"authorization"})]}),(0,n.jsxs)("div",{className:"gw-current-models",children:[(0,n.jsx)("span",{children:"Configured models"}),(0,n.jsxs)("div",{className:"gw-model-chips",children:[0===_.length?(0,n.jsx)("strong",{children:"Stored"}):_.map(e=>(0,n.jsx)("strong",{className:"mono",children:e},e)),U>0?(0,n.jsxs)("strong",{children:["+",U.toString()]}):null]})]})]}),(0,n.jsxs)("details",{className:"gw-replace",children:[(0,n.jsx)("summary",{children:"Replace model gateway settings"}),W]})]}):W]}),(0,n.jsxs)("section",{className:"gw-section","aria-labelledby":"gw-figma-section-title",children:[(0,n.jsx)("div",{className:"gw-section-head",children:(0,n.jsxs)("div",{children:[(0,n.jsx)("h2",{id:"gw-figma-section-title",children:"Figma Snapshot"}),(0,n.jsx)("p",{children:"Optional connector credential."})]})}),(0,n.jsxs)("label",{className:"gw-field",children:[(0,n.jsxs)("span",{children:["Figma access token ",(0,n.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,n.jsx)("input",{className:"gw-input mono",type:"password",value:S,placeholder:t?"Stored Figma token is kept when blank":"Paste a read-only Figma PAT when needed",autoComplete:"off",disabled:I||void 0!==L,ref:o,onChange:e=>C(e.target.value)})]})]}),(0,n.jsx)("div",{className:"gw-note",children:"Stored secrets stay local and are never returned to the browser. Supported API-key headers: Authorization, X-Litellm-Key, X-Api-Key, api-key."}),void 0!==R?(0,n.jsxs)("div",{className:"gw-error",role:"alert",children:[R,void 0!==A?(0,n.jsx)("div",{className:"gw-error-code mono",children:A}):null]}):null,void 0!==L?(0,n.jsx)("div",{className:"gw-success",role:"status",children:L}):null,I?(0,n.jsx)("div",{className:"gw-pending",role:"status",children:"Testing credentials…"}):null,(0,n.jsx)("span",{id:"gw-submit-requirements",className:"visually-hidden",children:t?"Enter at least one field to update. Blank stored gateway fields keep their current value.":"Base URL and API token are required. The Figma access token is optional."}),(0,n.jsxs)("div",{className:"gw-actions",children:[void 0!==e?(0,n.jsx)("button",{className:"gw-cancel",type:"button",disabled:I||void 0!==L,onClick:e,children:"Cancel"}):null,(0,n.jsx)("button",{className:"gw-submit",type:"submit",disabled:!K,"aria-busy":I,"aria-describedby":"gw-submit-requirements",children:I?"Testing credentials…":"Test & save"})]})]})})});return"u"<typeof document?V:(0,tP.createPortal)(V,document.body)}function tq(e){return e.findIndex(e=>!0!==e.disabled)}function tF(e,t,n){if(0===e.length)return -1;let a=t;for(let t=0;t<e.length;t+=1)if(a=(a+n+e.length)%e.length,e[a]?.disabled!==!0)return a;return -1}function tO({active:e,index:t,onCommit:l,onOptionKeyDown:i,option:r,setOptionRef:s}){let o=(0,a.useRef)(null),c=(0,a.useRef)(null),d=(0,a.useRef)(null),[u,p]=(0,a.useState)(null),m=()=>{null!==d.current&&(clearTimeout(d.current),d.current=null),p(null)},h=()=>{null!==d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{let e=c.current,t=o.current;if(null===e||null===t||e.scrollWidth<=e.clientWidth)return;let n=t.getBoundingClientRect(),a=Math.min(520,window.innerWidth-32),l=n.right+8+a<=window.innerWidth-16?"top-left":"top-right";p({left:"top-left"===l?n.right+8:n.left-8,placement:l,top:n.top-6})},1500)};return(0,a.useEffect)(()=>m,[]),(0,n.jsxs)("button",{ref:e=>{o.current=e,s(t,e)},"aria-selected":e,className:`ksel-option${e?" ksel-option-active":""}`,"data-disabled":!0===r.disabled?"true":void 0,disabled:r.disabled,onBlur:m,onClick:()=>l(r),onFocus:h,onKeyDown:e=>i(e,t),onPointerEnter:h,onPointerLeave:m,role:"option",type:"button",children:[(0,n.jsxs)("span",{className:"ksel-option-copy",children:[(0,n.jsx)("span",{className:"ksel-option-label",ref:c,children:r.label}),void 0!==r.description?(0,n.jsx)("span",{className:"ksel-option-desc",children:r.description}):null]}),void 0!==r.badge?(0,n.jsx)("span",{className:"ksel-option-badge",children:r.badge}):null,null!==u?(0,tP.createPortal)((0,n.jsx)("div",{className:"ksel-overflow-tooltip","data-placement":u.placement,role:"tooltip",style:{left:`${u.left.toString()}px`,top:`${u.top.toString()}px`},children:r.label}),document.body):null]})}function tz({value:e,sections:t,onValueChange:l,disabled:i=!1,placeholder:r="Select an option",ariaLabel:s,ariaDescribedBy:o,ariaLabelledBy:c,triggerClassName:d,menuClassName:u,menuTitle:p,menuCountLabel:m,showMenuHeader:h=!0,leadingVisual:f,mono:g=!1,showChevron:v=!0,menuMinWidth:b,attached:x=!0,triggerStyle:y,autoFocus:w=!1}){let j=(0,a.useRef)(null),k=(0,a.useRef)(null),N=(0,a.useRef)([]),S=(0,a.useId)(),[C,I]=(0,a.useState)(!1),[E,R]=(0,a.useState)(-1),[$,A]=(0,a.useState)(null),[T,L]=(0,a.useState)(!1),P=(0,a.useMemo)(()=>t.flatMap((e,t)=>e.options.map((n,a)=>({...n,key:`${e.label??"section"}-${t.toString()}-${n.value}-${a.toString()}`,sectionLabel:e.label}))),[t]),M=P.findIndex(t=>t.value===e),D=-1===M?null:P[M],q=D?.label??r,F=D?.description??null,O=()=>{I(!1),R(-1)},z=e=>{if(i||0===P.length)return;let t=void 0!==e&&P[e]?.disabled!==!0?e:M>=0&&P[M]?.disabled!==!0?M:tq(P);I(!0),R(t)};function K(e){e.disabled||(l(e.value),O(),j.current?.focus())}function B(e,t){if("Escape"===e.key){e.preventDefault(),O(),j.current?.focus();return}if("Tab"===e.key)return void O();if("ArrowDown"===e.key){e.preventDefault(),R(tF(P,t,1));return}if("ArrowUp"===e.key){e.preventDefault(),R(tF(P,t,-1));return}if("Home"===e.key){e.preventDefault(),R(tq(P));return}if("End"===e.key){e.preventDefault(),R(tF(P,0,-1));return}if("Enter"===e.key||" "===e.key){e.preventDefault();let n=P[t];void 0!==n&&K(n)}}(0,a.useEffect)(()=>{if(!C)return;let e=e=>{let t=e.target;null!==j.current&&t instanceof Node&&j.current.contains(t)||null!==k.current&&t instanceof Node&&k.current.contains(t)||O()},t=()=>O();return window.addEventListener("pointerdown",e,!0),window.addEventListener("blur",t),()=>{window.removeEventListener("pointerdown",e,!0),window.removeEventListener("blur",t)}},[C]),(0,a.useLayoutEffect)(()=>{if(!C||null===j.current)return;let e=()=>{let e=j.current?.getBoundingClientRect();if(void 0===e)return;let t=Math.min(void 0!==b&&e.width<Math.min(b,96)?b:e.width,window.innerWidth-32),n=x&&1>Math.abs(t-e.width),a=n?-1:6,l=window.innerHeight-e.bottom-16,i=e.top-16,r=l<Math.max(96,2*e.height)&&i>l;L(r);let s=r?i:l,o=50*!!h+2,c=Math.max(e.height,Math.min(Math.max(e.height,s-o),380)),d=c+o,u=window.getComputedStyle(j.current);A({left:Math.min(Math.max(16,e.left),window.innerWidth-t-16),width:t,top:r?Math.max(16,e.top-d-a):Math.min(e.bottom+a,window.innerHeight-16-d),optionHeight:Math.max(28,Math.min(e.height,30)),maxHeight:c,openUp:r,attached:n,fontFamily:u.fontFamily,fontSize:u.fontSize,fontWeight:u.fontWeight,letterSpacing:u.letterSpacing,lineHeight:u.lineHeight})};return e(),window.addEventListener("resize",e),window.addEventListener("scroll",e,!0),()=>{window.removeEventListener("resize",e),window.removeEventListener("scroll",e,!0)}},[C,x,b,h]),(0,a.useLayoutEffect)(()=>{if(!C||null===$||!$.openUp||null===j.current||null===k.current)return;let e=j.current.getBoundingClientRect(),t=k.current.getBoundingClientRect();if(t.height<=0)return;let n=$.attached?-1:6,a=Math.max(16,e.top-t.height-n);.5>Math.abs(a-$.top)||A(e=>null===e?e:{...e,top:a})},[C,$]),(0,a.useEffect)(()=>{C&&!(E<0)&&(N.current[E]?.focus(),N.current[E]?.scrollIntoView({block:"nearest"}))},[C,E]),(0,a.useEffect)(()=>{if(!C)return;let e=e=>{if("Escape"===e.key){O(),j.current?.focus();return}if(1===e.key.length&&!e.metaKey&&!e.ctrlKey&&!e.altKey){var t;if((t=e.target)instanceof HTMLElement&&("INPUT"===t.tagName||"TEXTAREA"===t.tagName||"SELECT"===t.tagName||t.isContentEditable))return;let n=e.key.toLowerCase(),a=E>=0?E:M>=0?M:0;for(let e=1;e<=P.length;e+=1){let t=(a+e)%P.length,l=P[t];if(void 0!==l&&!0!==l.disabled&&l.label.toLowerCase().startsWith(n)){R(t);break}}}};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[C,E,P,M]);let _=["ksel-trigger",g?"mono":"",d??"",C?"ksel-trigger-open":"",C&&$?.attached===!0?T?"ksel-trigger-open-up":"ksel-trigger-open-down":"",i?"ksel-trigger-disabled":""].filter(e=>e.length>0).join(" "),U=C&&null!==$?(0,tP.createPortal)((0,n.jsxs)("div",{ref:k,className:["ksel-menu",$.attached?"ksel-menu-attached":"",$.openUp?"ksel-menu-open-up":"ksel-menu-open-down",u??""].filter(e=>e.length>0).join(" "),style:{left:`${$.left.toString()}px`,top:`${$.top.toString()}px`,width:`${$.width.toString()}px`,"--ksel-option-height":`${$.optionHeight.toString()}px`,fontFamily:$.fontFamily,fontSize:$.fontSize,fontWeight:$.fontWeight,letterSpacing:$.letterSpacing,lineHeight:$.lineHeight},children:[h?(0,n.jsxs)("div",{className:"ksel-menu-head",children:[(0,n.jsx)("div",{className:"ksel-menu-title",children:p??s??r}),(0,n.jsx)("div",{className:"ksel-menu-note",children:m??`${P.length.toString()} options`})]}):null,(0,n.jsx)("div",{className:"ksel-menu-scroll",role:"listbox",id:S,style:{maxHeight:`${$.maxHeight.toString()}px`},children:t.map((e,t)=>(0,n.jsxs)("div",{className:"ksel-section",children:[void 0!==e.label?(0,n.jsx)("div",{className:"ksel-section-label",children:e.label}):null,e.options.map(t=>{let a=P.findIndex(n=>n.value===t.value&&n.sectionLabel===e.label),l=a===M,i=P[a];return void 0===i?null:(0,n.jsx)(tO,{active:l,index:a,onCommit:K,onOptionKeyDown:B,option:i,setOptionRef:(e,t)=>{N.current[e]=t}},`${e.label??"section"}-${t.value}`)})]},`${e.label??"section"}-${t.toString()}`))})]}),document.body):null;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("button",{ref:j,"aria-controls":S,"aria-describedby":o,"aria-expanded":C,"aria-haspopup":"listbox","aria-label":s,"aria-labelledby":c,autoFocus:w,className:_,disabled:i,onClick:()=>{C?O():z()},onKeyDown:function(e){if(!i){if("ArrowDown"===e.key||"ArrowUp"===e.key){e.preventDefault(),z(M>=0?M:tq(P));return}("Enter"===e.key||" "===e.key)&&(e.preventDefault(),C?O():z())}},role:"combobox",style:y,type:"button",children:[void 0!==f?(0,n.jsx)("span",{className:"ksel-trigger-leading",children:f}):null,(0,n.jsxs)("span",{className:"ksel-trigger-copy",children:[(0,n.jsx)("span",{className:"ksel-trigger-label",children:q}),null!==F?(0,n.jsx)("span",{className:"ksel-trigger-desc",children:F}):null]}),v?(0,n.jsx)("span",{"aria-hidden":"true",className:`ksel-trigger-caret${C?" ksel-trigger-caret-open":""}`,children:(0,n.jsx)("svg",{fill:"none",height:"12",viewBox:"0 0 12 12",width:"12",children:(0,n.jsx)("path",{d:"M2.25 4.5 6 8.25 9.75 4.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.5"})})}):null]}),U]})}let tK=[["ask","Ask every action"],["full","Full access"]];function tB({cfg:e,set:t}){let a=!1!==e.keikoMode,l="full"===e.access?"full":"ask",i=a?"No rights by default. You approve while manual; Keiko governs per policy when autonomous.":"full"===l?"Legacy: agent acts without prompts.":"Legacy: you approve each privileged action.";return(0,n.jsxs)("div",{className:"permctl",children:[(0,n.jsxs)("button",{type:"button",className:"perm-toggle","data-on":a,"aria-pressed":a,onClick:()=>t("keikoMode",!a),children:[(0,n.jsx)("img",{className:"perm-orca",src:"/assets/keiko-logo.svg",alt:""}),(0,n.jsxs)("span",{className:"perm-tt",children:[(0,n.jsx)("span",{className:"perm-name",children:"Keiko-Mode"}),(0,n.jsx)("span",{className:"perm-desc",children:"Zero standing rights · Keiko governs"})]}),(0,n.jsx)("span",{className:"perm-sw"+(a?" on":""),children:(0,n.jsx)("span",{})})]}),!a&&(0,n.jsx)("div",{className:"perm-legacy",children:tK.map(([e,a])=>(0,n.jsx)("button",{type:"button",className:"perm-opt","data-on":l===e,"aria-pressed":l===e,onClick:()=>t("access",e),children:a},e))}),(0,n.jsx)("div",{className:"perm-note",children:i})]})}function t_(e){return"chat"===e.kind&&e.toolCalling&&e.structuredOutput}function tU(e){if(e instanceof w.ApiError){if("BAD_ROOT"===e.code)return"Enter an absolute folder path.";if("DENIED"===e.code)return"That location is excluded."}return e instanceof Error?e.message:"Unable to read directories."}function tW({value:e,projectId:t,selectProjectRoot:l=!1,onSelect:i,onClose:r}){let[s,o]=(0,a.useState)(null),[c,d]=(0,a.useState)(e),[u,p]=(0,a.useState)(!1),[m,h]=(0,a.useState)(null),f=t??e.trim(),g=(0,a.useCallback)(async e=>{if(0===f.length){o(null),h("Enter an absolute folder path.");return}p(!0),h(null);try{let t=await (0,w.fetchFilesDirectories)(f,e);o(t),d(t.path)}catch(e){h(tU(e))}finally{p(!1)}},[f]);return(0,a.useEffect)(()=>{g(e.length>0?e:void 0)},[]),(0,n.jsxs)("div",{className:"dir-picker",role:"group","aria-label":"Directory picker",children:[(0,n.jsxs)("div",{className:"dir-top",children:[(0,n.jsx)("input",{className:"dlg-input mono dir-path",value:c,"aria-label":"Folder path",placeholder:"/absolute/folder/path",onChange:e=>d(e.target.value),onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),e.stopPropagation(),g(c))}}),(0,n.jsx)("button",{type:"button",className:"dlg-btn dir-go",onClick:()=>void g(c),children:"Go"})]}),null!==s?(0,n.jsx)("div",{className:"dir-roots",children:s.roots.map(e=>(0,n.jsx)("button",{type:"button",className:"dir-chip",onClick:()=>void g(e.path),children:e.label},`${e.label}:${e.path}`))}):null,(0,n.jsxs)("div",{className:"dir-list",children:[s?.parent!==null&&s?.parent!==void 0?(0,n.jsxs)("button",{type:"button",className:"dir-row",onClick:()=>void g(s.parent??void 0),children:[(0,n.jsx)(j.Icons.back,{size:14}),(0,n.jsx)("span",{children:"Parent directory"})]}):null,s?.entries.map(e=>(0,n.jsxs)("button",{type:"button",className:"dir-row",onClick:()=>void g(e.path),children:[(0,n.jsx)(j.Icons.folder,{size:14}),(0,n.jsx)("span",{children:e.name})]},e.path)),u?(0,n.jsx)("div",{className:"dir-note",role:"status",children:"Loading directories…"}):null,u||null===s||0!==s.entries.length?null:(0,n.jsx)("div",{className:"dir-note",children:"No child directories."}),null!==m?(0,n.jsx)("div",{className:"dir-error",role:"alert",children:m}):null]}),(0,n.jsxs)("div",{className:"dir-actions",children:[(0,n.jsx)("button",{type:"button",className:"dlg-btn",onClick:r,children:"Close"}),(0,n.jsx)("button",{type:"button",className:"dlg-btn dlg-primary",onClick:()=>{null!==s&&(i(l?s.roots[0]?.path??s.path:s.path),r())},disabled:null===s,children:"Use directory"})]})]})}let tV=[{id:"unit-test-generation",label:"Unit Test Agent",scope:"Source file"},{id:"bug-investigation",label:"Bugfix Agent",scope:"Bug report"}];function tH(e){return e.filter(e=>e.available).map(e=>e.path)}function tY(e){return e.split(/[\n,]/u).map(e=>e.trim()).filter(e=>e.length>0)}function tG(e){let t=tJ(e.trim()).replace(/\/+$/u,""),n=t.lastIndexOf("/");return n>0?t.slice(0,n):""}function tJ(e){return e.replaceAll("\\","/")}function tX(e,t){let n=tJ(t.trim());if(0===n.length)return"";let a=tJ(e.trim()).replace(/\/+$/u,"");if(0===a.length)return n;if(n===a)return".";let l=`${a}/`;return n.startsWith(l)?n.slice(l.length):n}function tQ({root:e,value:t,onSelect:l,onClose:i}){let r=tX(e,t),[s,o]=(0,a.useState)(tG(r)),[c,d]=(0,a.useState)(r),[u,p]=(0,a.useState)([]),[m,h]=(0,a.useState)(!1),[f,g]=(0,a.useState)(!1),[v,b]=(0,a.useState)(null);(0,a.useEffect)(()=>{if(0===e.trim().length){p([]),h(!1),g(!1),b("Select a repository first.");return}let t=!1;return g(!0),b(null),(0,w.fetchFilesTree)(e.trim(),s).then(e=>{t||(p(e.entries),h(e.truncated))}).catch(e=>{t||(p([]),h(!1),b(tU(e)))}).finally(()=>{t||g(!1)}),()=>{t=!0}},[s,e]);let x=u.filter(e=>"directory"===e.kind),y=u.filter(e=>"directory"!==e.kind);return(0,n.jsxs)("div",{className:"file-picker",role:"group","aria-label":"File picker",children:[(0,n.jsx)("div",{className:"file-picker-head",children:(0,n.jsx)("span",{className:"file-picker-path mono",children:0===s.length?"Repository root":s})}),(0,n.jsxs)("div",{className:"dir-list file-picker-list",children:[s.length>0?(0,n.jsxs)("button",{type:"button",className:"dir-row",onClick:()=>o(tG(s)),children:[(0,n.jsx)(j.Icons.back,{size:14}),(0,n.jsx)("span",{children:"Parent folder"})]}):null,x.map(e=>(0,n.jsxs)("button",{type:"button",className:"dir-row file-picker-row",disabled:!e.readable,onClick:()=>o(e.path),title:e.path,children:[(0,n.jsx)(j.Icons.folder,{size:14}),(0,n.jsx)("span",{children:e.name})]},e.path)),y.map(e=>(0,n.jsxs)("button",{type:"button",className:"dir-row file-picker-row","data-selected":c===e.path?"true":void 0,disabled:!e.readable,"aria-pressed":c===e.path,onClick:()=>d(e.path),title:e.path,children:[(0,n.jsx)(j.Icons.file,{size:14}),(0,n.jsx)("span",{children:e.name}),(0,n.jsx)("span",{className:"file-picker-meta mono",children:function(e){if(!Number.isFinite(e)||e<=0)return"0 B";let t=["B","KB","MB","GB"],n=e,a=0;for(;n>=1024&&a<t.length-1;)n/=1024,a+=1;let l=0===a?n.toFixed(0):n.toFixed(n>=10?1:2);return`${l} ${t[a]}`}(e.sizeBytes)})]},e.path)),f?(0,n.jsx)("div",{className:"dir-note",role:"status",children:"Loading files…"}):null,f||null!==v||0!==u.length?null:(0,n.jsx)("div",{className:"dir-note",children:"No files in this folder."}),m?(0,n.jsxs)("div",{className:"dir-note file-picker-warning",role:"status",children:["Showing only the first ",u.length.toString()," entries."]}):null,null!==v?(0,n.jsx)("div",{className:"dir-error",role:"alert",children:v}):null]}),(0,n.jsxs)("div",{className:"dir-actions",children:[(0,n.jsx)("button",{type:"button",className:"dlg-btn",onClick:i,children:"Close"}),(0,n.jsx)("button",{type:"button",className:"dlg-btn dlg-primary",onClick:()=>{0!==c.trim().length&&(l(tX(e,c)),i())},disabled:0===c.trim().length,children:"Use file"})]})]})}function tZ({filesContext:e,firstRef:t,directoryField:l,setDirectoryField:i,setDialogError:r,onConfirm:s}){let[o,c]=(0,a.useState)("unit-test-generation"),[d,u]=(0,a.useState)(e?.root??""),[p,m]=(0,a.useState)(""),[h,f]=(0,a.useState)([]),[g,v]=(0,a.useState)([]),[b,x]=(0,a.useState)(()=>{var t,n;let a;return t=e?.root??"",{verifyTargetFiles:a=null===(n=e?.activeFilePath??null)?"":tX(t,n),explainFilePath:a,explainQuestion:"",unitFilePath:a,bugDescription:"",bugFailingOutput:"",bugStackTrace:"",bugTargetFiles:a}}),[y,k]=(0,a.useState)(!0),[N,S]=(0,a.useState)(!1),[C,I]=(0,a.useState)(!1),E=d.trim(),R=null!==e&&e.root===E&&void 0!==e.activeFilePath?e.activeFilePath:null,$=E.length>0&&g.includes(E),A=0===E.length?"Repository is required.":0===p.length?"No compatible model is available.":"explain-plan"===o&&0===b.explainFilePath.trim().length?"Explain plan requires a file path.":"unit-test-generation"===o&&0===b.unitFilePath.trim().length?"Unit Test Agent requires a source file.":"bug-investigation"===o&&0===b.bugDescription.trim().length?"Bugfix Agent requires an observed behavior.":null,T=null===A&&$&&!C&&!y,L=tV.find(e=>e.id===o)??tV[0],P="unit-test-generation"===o?"Start Unit Test Agent":"Start Bugfix Agent";(0,a.useEffect)(()=>{let e=!1;return k(!0),r(null),Promise.all([(0,w.fetchModels)(),(0,w.fetchProjects)()]).then(([t,n])=>{if(e)return;let a=t.models.filter(t_);f(a),m(e=>e||(a[0]?.id??"")),v(tH(n.projects))}).catch(t=>{e||r(tU(t))}).finally(()=>{e||k(!1)}),()=>{e=!0}},[r]);let M=e=>{x(t=>({...t,...e}))};(0,a.useEffect)(()=>{if(null===R)return;let e=tX(E,R);x(t=>{let n={};return 0===t.verifyTargetFiles.trim().length&&(n.verifyTargetFiles=e),0===t.explainFilePath.trim().length&&(n.explainFilePath=e),0===t.unitFilePath.trim().length&&(n.unitFilePath=e),0===t.bugTargetFiles.trim().length&&(n.bugTargetFiles=e),0===Object.keys(n).length?t:{...t,...n}})},[R,E]);let D=async()=>{v(tH((await (0,w.fetchProjects)()).projects))},q=async()=>{if(0!==E.length){S(!0),r(null);try{await (0,w.createProject)({path:E}),await D()}catch(e){r(tU(e))}finally{S(!1)}}},F=async()=>{if(!T)return void r(A??"Repository is not registered.");I(!0),r(null);let t=function(e,t,n,a){if("verify"===e){let e=tY(a.verifyTargetFiles).map(e=>tX(t,e));return{taskType:"verify",modelId:n,input:{workspaceRoot:t,...e.length>0?{targetFiles:e}:{}}}}return"explain-plan"===e?{taskType:"explain-plan",modelId:n,input:{workspaceRoot:t,filePath:tX(t,a.explainFilePath),...a.explainQuestion.trim().length>0?{question:a.explainQuestion.trim()}:{}}}:"unit-test-generation"===e?{workflowId:"unit-test-generation",modelId:n,input:{workspaceRoot:t,target:{kind:"file",filePath:tX(t,a.unitFilePath)}}}:{workflowId:"bug-investigation",modelId:n,input:{workspaceRoot:t,report:{...a.bugDescription.trim().length>0?{description:a.bugDescription.trim()}:{},...a.bugFailingOutput.trim().length>0?{failingOutput:a.bugFailingOutput.trim()}:{},...a.bugStackTrace.trim().length>0?{stackTrace:a.bugStackTrace.trim()}:{},...tY(a.bugTargetFiles).length>0?{targetFiles:tY(a.bugTargetFiles).map(e=>tX(t,e))}:{}}}}}(o,E,p,b);try{let n=await (0,w.startRun)(t);s({workflow:o,model:p,runId:n.runId,fingerprint:n.fingerprint,workspaceRoot:E,inputJson:JSON.stringify(t.input),...null!==e&&e.root===E?{__connectFilesId:e.id}:{}})}catch(e){e instanceof w.ApiError&&"WORKSPACE_NOT_REGISTERED"===e.code?(await D().catch(()=>void 0),r("Repository is not registered.")):r(tU(e))}finally{I(!1)}};return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"dlg-agent-grid",children:[(0,n.jsxs)("div",{className:"dlg-field",children:[(0,n.jsx)("span",{className:"dlg-label",children:"Agent"}),(0,n.jsx)("span",{className:"dlg-selwrap",children:(0,n.jsx)(tz,{triggerClassName:"dlg-input",value:o,ariaLabel:"Agent",autoFocus:!0,menuTitle:"Agent",menuCountLabel:`${tV.length.toString()} agents`,sections:[{options:tV.map(e=>({value:e.id,label:e.label}))}],onValueChange:e=>{let t=tV.find(t=>t.id===e);void 0!==t&&c(t.id)}})})]}),(0,n.jsxs)("div",{className:"dlg-field",children:[(0,n.jsx)("span",{className:"dlg-label",children:"Model"}),(0,n.jsx)("span",{className:"dlg-selwrap",children:(0,n.jsx)(tz,{triggerClassName:"dlg-input mono",value:p,ariaLabel:"Model",disabled:0===h.length,menuTitle:"Model",mono:!0,sections:[{options:h.map(e=>({value:e.id,label:e.id}))}],onValueChange:m})})]})]}),(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsx)("span",{className:"dlg-label",children:"Repository"}),(0,n.jsxs)("span",{className:"dlg-dirwrap",children:[(0,n.jsx)("input",{className:"dlg-input mono",value:d,placeholder:"/absolute/repository/path",onClick:()=>i("agentWorkspace"),onChange:e=>u(e.target.value)}),(0,n.jsx)("button",{type:"button",className:"dlg-btn dlg-dirbtn",onClick:()=>i("agentWorkspace"),children:"Browse"})]}),"agentWorkspace"===l?(0,n.jsx)(tW,{value:d,projectId:$?E:void 0,onSelect:u,onClose:()=>i(null)}):null]}),E.length>0&&!$?(0,n.jsxs)("div",{className:"dlg-agent-warning",children:[(0,n.jsx)("span",{children:"Repository is not registered."}),(0,n.jsx)("button",{type:"button",className:"dlg-btn",disabled:N,onClick:()=>void q(),children:N?"Registering…":"Register repository"})]}):null,null!==R?(0,n.jsxs)("button",{type:"button",className:"dlg-current-file",onClick:()=>{if(null===R)return;let e=tX(E,R);"unit-test-generation"===o?M({unitFilePath:e}):M({bugTargetFiles:e})},title:R,children:[(0,n.jsx)(j.Icons.files,{size:13})," Use current file ",(0,n.jsx)("span",{className:"mono",children:R})]}):null,(0,n.jsxs)("div",{className:"dlg-agent-task",children:[(0,n.jsxs)("div",{className:"dlg-agent-task-head",children:[(0,n.jsx)("span",{className:"dlg-agent-task-title",children:L.label}),(0,n.jsx)("span",{className:"dlg-agent-task-scope",children:L.scope})]}),"unit-test-generation"===o?(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsx)("span",{className:"dlg-label",children:"Source file"}),(0,n.jsxs)("span",{className:"dlg-dirwrap",children:[(0,n.jsx)("input",{className:"dlg-input mono",placeholder:"src/file.ts",value:b.unitFilePath,onChange:e=>M({unitFilePath:e.target.value}),onBlur:e=>M({unitFilePath:tX(E,e.target.value)})}),(0,n.jsx)("button",{type:"button",className:"dlg-btn dlg-dirbtn","aria-label":"Browse source file",onClick:()=>i("unitSourceFile"),children:"Browse"})]}),"unitSourceFile"===l?(0,n.jsx)(tQ,{root:E,value:b.unitFilePath,onSelect:e=>M({unitFilePath:e}),onClose:()=>i(null)}):null]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsx)("span",{className:"dlg-label",children:"Observed behavior"}),(0,n.jsx)("textarea",{className:"dlg-input dlg-textarea",rows:2,placeholder:"Describe the observed bug.",value:b.bugDescription,onChange:e=>M({bugDescription:e.target.value})})]}),(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsxs)("span",{className:"dlg-label",children:["Failing output ",(0,n.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,n.jsx)("textarea",{className:"dlg-input dlg-textarea mono",rows:2,value:b.bugFailingOutput,onChange:e=>M({bugFailingOutput:e.target.value})})]}),(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsxs)("span",{className:"dlg-label",children:["Stack trace ",(0,n.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,n.jsx)("textarea",{className:"dlg-input dlg-textarea mono",rows:2,value:b.bugStackTrace,onChange:e=>M({bugStackTrace:e.target.value})})]}),(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsxs)("span",{className:"dlg-label",children:["Related files ",(0,n.jsx)("span",{className:"dlg-opt",children:"optional"})]}),(0,n.jsx)("textarea",{className:"dlg-input dlg-textarea mono",rows:2,placeholder:"src/file.ts, src/other.ts",value:b.bugTargetFiles,onChange:e=>M({bugTargetFiles:e.target.value}),onBlur:e=>M({bugTargetFiles:tY(e.target.value).map(e=>tX(E,e)).join(", ")})})]})]})]}),(0,n.jsxs)("div",{className:"dlg-agent-actions",children:[(0,n.jsx)("button",{type:"button",className:"dlg-btn dlg-primary",disabled:!T,"aria-busy":C,"aria-describedby":T||C?void 0:"agent-start-validation",onClick:()=>void F(),children:C?"Starting…":P}),y?(0,n.jsx)("span",{id:"agent-start-validation",className:"dlg-note",role:"status",children:"Loading models and projects…"}):null,y||null===A?null:(0,n.jsx)("span",{id:"agent-start-validation",className:"dlg-note",role:"status",children:A})]})]})}function t0({type:e,types:t,filesContext:l=null,onConfirm:i,onClose:r}){let s=t[e],o=s.config??[],[c,d]=(0,a.useState)(()=>(function(e){let t={};for(let n of e)t[n.key]=n.def??"";return t})(o)),[u,p]=(0,a.useState)(!1),[m,h]=(0,a.useState)(null),[f,g]=(0,a.useState)(null),v=(0,a.useRef)(null),b=(0,a.useRef)(null),x=(0,a.useRef)(null);(0,a.useEffect)(()=>(x.current=document.activeElement,()=>{let e=x.current;null!==e&&e.isConnected?e.focus():requestAnimationFrame(()=>{(document.querySelector('.window[data-top="true"]')??document.querySelector(".ws-fab")??document.body).focus({preventScroll:!0})})}),[]),(0,a.useEffect)(()=>{let e=requestAnimationFrame(()=>{p(!0),(v.current??b.current)?.focus()});return()=>cancelAnimationFrame(e)},[]),(0,a.useEffect)(()=>{let e=e=>{"Escape"===e.key&&r()};return window.addEventListener("keydown",e),()=>{window.removeEventListener("keydown",e)}},[r]),(0,a.useEffect)(()=>{if("files"!==e&&"editor"!==e)return;let t=!1,n=c.root;if("string"!=typeof n||!(n.length>0))return h(null),(0,w.fetchProjects)().then(e=>{let n=tH(e.projects)[0];t||void 0===n||d(e=>({...e,root:n}))}).catch(e=>{t||h(tU(e))}),()=>{t=!0}},[c.root,e]);let y=(e,t)=>d(n=>({...n,[e]:t})),k=()=>{"agents"!==e&&i(c)},N=j.Icons[s.icon],S=s.cta??`Open ${s.title}`;return(0,n.jsx)("div",{className:"dlg-overlay"+(u?" in":""),onPointerDown:r,children:(0,n.jsxs)("div",{ref:b,className:"agents"===e?"dlg dlg-agents":"dlg",role:"dialog","aria-modal":"true","aria-labelledby":"new-window-title","aria-describedby":"new-window-desc",tabIndex:-1,onPointerDown:e=>e.stopPropagation(),onKeyDown:e=>{let t,n;if("Escape"===e.key)return void r();if("Enter"===e.key&&(e.metaKey||e.ctrlKey))return void k();if("Enter"===e.key){let t=e.target instanceof HTMLElement?e.target.tagName:"";("INPUT"===t||"SELECT"===t)&&(e.preventDefault(),k());return}if("Tab"!==e.key)return;let a=(t=e.currentTarget.querySelectorAll("button,input,select,textarea"),n=[],t.forEach(e=>{e.hasAttribute("disabled")||(null!==e.offsetParent||"BUTTON"===e.tagName)&&n.push(e)}),n);if(0===a.length)return;let l=a[0],i=a[a.length-1];e.shiftKey&&document.activeElement===l?(e.preventDefault(),i.focus()):e.shiftKey||document.activeElement!==i||(e.preventDefault(),l.focus())},children:[(0,n.jsxs)("div",{className:"dlg-head",children:[(0,n.jsx)("span",{className:"dlg-ico",children:(0,n.jsx)(N,{size:20})}),(0,n.jsxs)("div",{className:"dlg-htext",children:[(0,n.jsxs)("span",{id:"new-window-title",className:"dlg-title",children:["New ",s.title," window"]}),(0,n.jsx)("span",{id:"new-window-desc",className:"dlg-sub",children:s.desc})]}),(0,n.jsx)("span",{className:"spacer"}),(0,n.jsx)("button",{type:"button",className:"palette-x",onClick:r,"aria-label":"Cancel",title:"Cancel",children:(0,n.jsx)(j.Icons.close,{size:16})})]}),(0,n.jsxs)("div",{className:"dlg-body",children:["agents"===e?(0,n.jsx)(tZ,{filesContext:l,firstRef:e=>{v.current=e},directoryField:f,setDirectoryField:g,setDialogError:h,onConfirm:i}):0===o.length&&(0,n.jsxs)("div",{className:"dlg-empty",children:["Add a new ",s.title," window to your workspace."]}),"agents"!==e&&o.map((e,t)=>(0,n.jsxs)("label",{className:"dlg-field",children:[(0,n.jsxs)("span",{className:"dlg-label",children:[e.label,!0===e.optional&&(0,n.jsx)("span",{className:"dlg-opt",children:"optional"})]}),function(e,t,a,l,i){if("perm"===e.type)return(0,n.jsx)(tB,{cfg:t,set:a});let r=t[e.key],s="string"==typeof r?r:void 0===r?"":String(r);if("select"===e.type){let t=e.options??[];return(0,n.jsx)("span",{className:"dlg-selwrap",children:(0,n.jsx)(tz,{triggerClassName:"dlg-input mono",value:s,disabled:0===t.length,autoFocus:null!==l,menuTitle:e.label,mono:!0,sections:[{options:t.map(t=>({value:t,label:`${e.prefix??""}${t}`}))}],onValueChange:t=>a(e.key,t)})})}return"textarea"===e.type?(0,n.jsx)("textarea",{ref:l??void 0,className:"dlg-input dlg-textarea",rows:3,placeholder:e.placeholder??"",value:s,onChange:t=>a(e.key,t.target.value)}):"directory"===e.type?(0,n.jsxs)("span",{className:"dlg-dirwrap",children:[(0,n.jsx)("input",{ref:l??void 0,className:"dlg-input mono",placeholder:e.placeholder??e.label,value:s,onClick:()=>i(e.key),onChange:t=>a(e.key,t.target.value)}),(0,n.jsx)("button",{type:"button",className:"dlg-btn dlg-dirbtn",onClick:()=>i(e.key),children:"Browse"})]}):(0,n.jsx)("input",{ref:l??void 0,className:"dlg-input mono",placeholder:e.placeholder??e.label,value:s,onChange:t=>a(e.key,t.target.value)})}(e,c,y,0===t?e=>{v.current=e}:null,g),"directory"===e.type&&f===e.key?(0,n.jsx)(tW,{value:"string"==typeof c[e.key]?c[e.key]:"",selectProjectRoot:"root"===e.key,onSelect:t=>y(e.key,t),onClose:()=>g(null)}):null]},e.key)),null!==m?(0,n.jsx)("div",{className:"dlg-error",role:"alert",children:m}):null]}),(0,n.jsxs)("div",{className:"dlg-foot",children:[(0,n.jsx)("button",{type:"button",className:"dlg-btn",onClick:r,children:"Cancel"}),"agents"!==e?(0,n.jsx)("button",{type:"button",className:"dlg-btn dlg-primary",onClick:k,children:S}):null]})]})})}function t1({types:e,order:t,onAdd:l,onClose:i}){let r=t.length<=4?2:3,s=(0,a.useRef)(null),o=(0,a.useRef)(null),[c,d]=(0,a.useState)(0);return(0,a.useEffect)(()=>{o.current=document.activeElement;let e=s.current?.querySelector(".pal-card");return e?.focus(),()=>{let e=document.activeElement;(null===e||e===document.body)&&o.current?.focus?.()}},[]),(0,a.useEffect)(()=>{let e=e=>{null!==s.current&&e.target instanceof Node&&!s.current.contains(e.target)&&i()};return document.addEventListener("pointerdown",e),()=>{document.removeEventListener("pointerdown",e)}},[i]),(0,n.jsxs)("div",{ref:s,className:"palette",role:"dialog","aria-labelledby":"palette-title","aria-describedby":"palette-desc",tabIndex:-1,onPointerDown:e=>e.stopPropagation(),onKeyDown:e=>{if("Escape"===e.key){e.preventDefault(),i();return}if(!(e.target instanceof HTMLElement)||!e.target.classList.contains("pal-card"))return;let t=Array.from(s.current?.querySelectorAll(".pal-card")??[]),n=function(e,t,n,a){let l;if(0===n)return null;if("Home"===e)return 0;if("End"===e)return n-1;if("ArrowRight"===e)l=1;else if("ArrowLeft"===e)l=-1;else if("ArrowDown"===e)l=a;else{if("ArrowUp"!==e)return null;l=-a}return Math.max(0,Math.min(n-1,t+l))}(e.key,t.indexOf(e.target),t.length,r);null!==n&&(e.preventDefault(),d(n),t[n]?.focus())},onBlur:e=>{e.relatedTarget instanceof Node&&s.current?.contains(e.relatedTarget)!==!0&&i()},"data-columns":r,children:[(0,n.jsxs)("div",{className:"palette-head",children:[(0,n.jsx)("span",{className:"palette-badge",children:(0,n.jsx)(j.Icons.add,{size:17})}),(0,n.jsxs)("div",{className:"palette-htext",children:[(0,n.jsx)("span",{id:"palette-title",className:"palette-title",children:"New window"}),(0,n.jsx)("span",{id:"palette-desc",className:"palette-sub",children:"Pick a card to add to your workspace"})]}),(0,n.jsx)("span",{className:"spacer"}),(0,n.jsx)("button",{type:"button",className:"palette-x",onClick:i,"aria-label":"Close",title:"Close",children:(0,n.jsx)(j.Icons.close,{size:16})})]}),(0,n.jsx)("div",{className:"palette-grid",children:t.map((t,a)=>{let i=e[t],r=j.Icons[i.icon];return(0,n.jsxs)("button",{type:"button",className:"pal-card pal-main",tabIndex:a===c?0:-1,onFocus:()=>d(a),onClick:()=>l(t),children:[(0,n.jsx)("span",{className:"pal-ico",children:(0,n.jsx)(r,{size:18})}),(0,n.jsx)("span",{className:"pal-name",children:i.title}),(0,n.jsx)("span",{className:"pal-desc",children:i.desc}),(0,n.jsx)("span",{className:"pal-add","aria-hidden":"true",children:(0,n.jsx)(j.Icons.plus,{size:15})})]},t)})})]})}async function t2(e){try{let t=await e.json();return{code:t.error.code,message:t.error.message}}catch{return{code:"INTERNAL",message:`HTTP ${e.status.toString()}`}}}async function t4(e,t){let n,a,l=(t?.method??"GET").toUpperCase(),i=t?.body,r=await fetch(e,{...t,headers:(n={Accept:"application/json"},((a="GET"!==l&&"HEAD"!==l)||null!=i)&&(n["Content-Type"]="application/json"),a&&(n["X-Keiko-CSRF"]="1"),n)});if(!r.ok){let{code:e,message:t}=await t2(r);throw new w.ApiError(e,t,r.status)}return r.json()}async function t3(e={},t=t4){let n=new URLSearchParams;void 0!==e.scope&&e.scope.length>0&&n.set("scope",e.scope.join(",")),void 0!==e.type&&e.type.length>0&&n.set("type",e.type.join(",")),void 0!==e.status&&e.status.length>0&&n.set("status",e.status.join(",")),void 0!==e.sensitivity&&e.sensitivity.length>0&&n.set("sensitivity",e.sensitivity.join(",")),void 0!==e.limit&&n.set("limit",e.limit.toString()),void 0!==e.offset&&n.set("offset",e.offset.toString());let a=n.toString();return t(`/api/memory${a.length>0?`?${a}`:""}`)}async function t6(e=t4){return e("/api/memory/review-queue")}async function t5(e,t=t4){return t("/api/memory/consolidation/jobs",{method:"POST",body:JSON.stringify({settings:e})})}async function t8(e,t=t4){return t(`/api/memory/consolidation/jobs/${encodeURIComponent(e)}`)}async function t7(e,t=t4){return t(`/api/memory/consolidation/jobs/${encodeURIComponent(e)}/cancel`,{method:"POST",body:"{}"})}async function t9(e,t=t4){return t(`/api/memory/${encodeURIComponent(e)}`)}async function ne(e,t,n=t4){return n(`/api/memory/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})}async function nt(e,t=t4){return t(`/api/memory/${encodeURIComponent(e)}/pin`,{method:"POST",body:"{}"})}async function nn(e,t=t4){return t(`/api/memory/${encodeURIComponent(e)}/unpin`,{method:"POST",body:"{}"})}async function na(e,t,n=t4){return n(`/api/memory/${encodeURIComponent(e)}/archive`,{method:"POST",body:JSON.stringify({...void 0!==t?{reason:t}:{}})})}async function nl(e,t,n=t4){return n(`/api/memory/${encodeURIComponent(e)}/forget`,{method:"POST",body:JSON.stringify({acknowledged:!0,...void 0!==t?{reason:t}:{}})})}async function ni(e,t,n=t4){return n(`/api/memory/${encodeURIComponent(e)}`,{method:"DELETE",body:JSON.stringify({acknowledged:!0,...void 0!==t?{reason:t}:{}})})}async function nr(e,t,n=t4){return n(`/api/memory/${encodeURIComponent(e)}/correct`,{method:"POST",body:JSON.stringify({body:t})})}async function ns(e,t=t4){return t(`/api/memory/proposals/${encodeURIComponent(e)}/accept`,{method:"POST",body:"{}"})}async function no(e,t,n=t4){return n(`/api/memory/proposals/${encodeURIComponent(e)}/reject`,{method:"POST",body:JSON.stringify({...void 0!==t?{reason:t}:{}})})}let nc=[{workflowId:"unit-test-generation",label:"Generate unit tests",description:"Drafts a reviewable unit-test patch for a target file. Dry-run only from chat — apply from the workflow view.",prompt:"Target file (workspace-relative)",placeholder:"src/example.ts",buildInput:(e,t)=>({workspaceRoot:e,target:{kind:"file",filePath:t.trim()}})},{workflowId:"bug-investigation",label:"Investigate bug",description:"Investigates a reported issue and proposes a root-cause hypothesis. Dry-run only from chat.",prompt:"Describe the bug",placeholder:"The login button does nothing when the form is empty…",buildInput:(e,t)=>({workspaceRoot:e,report:{description:t.trim()}})}];function nd(e){return nc.find(t=>t.workflowId===e)}let nu=new Set(["completed","dry-run","fix-applied","fix-proposed","investigation-only"]);function np(e){return e.length>200?e.slice(0,200):e}function nm(e){if(null!==e&&"object"==typeof e)return e}function nh(){return"Investigation complete; root cause documented."}function nf(e){let t=e.workflowId;return"unit-test-generation"===t||"unit-tests"===t?"unit-tests":"bug-investigation"===t?"bug":"verify"===e.taskType?"verify":"explain-plan"===e.taskType?"explain":"other"}function ng(e){return void 0===e||!Number.isFinite(e)||e<=0?0:Math.floor(e)}function nv(e){return"u">typeof TextEncoder?new TextEncoder().encode(e).length:e.length}function nb(e){let t=ng(e.modelContextWindow),n=ng(e.modelMaxOutputTokens),a=Math.max(0,t-n),l=nv(e.userDraftText),i=function(e){let t=0;for(let n of e)t+=nv(n.role),t+=nv(n.content);return t}(e.conversationHistory),r=function(e){if(void 0===e)return 0;let t=0;for(let n of e)t+=ng(n.extractedBytes);return t}(e.documentContext),s=ng(e.repoContextPackBytes),o=ng(e.knowledgeCapsuleBytes),c=ng(e.memoryContextBytes),d=l+i+r+s+o+c,u=Math.ceil(d/4),p=function(e,t){if(t<=0)return"exceeded";let n=e/t;return n>.95?"exceeded":n>.75?"high":n>.5?"moderate":"low"}(u,a);return{approximateBytes:d,approximateTokens:u,contextWindowTokens:t,reservedOutputTokens:n,availableInputTokens:a,pressure:p,breakdown:{draftBytes:l,historyBytes:i,documentBytes:r,repoContextBytes:s,knowledgeBytes:o,memoryBytes:c}}}function nx(e){return"chat"===e.kind}let ny={embedding:"embedding-only","ocr-vision":"ocr-vision-only"},nw=[/\bsk-[A-Za-z0-9_-]{12,}\b/g,/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}\b/gi,/\bgho_[A-Za-z0-9_]{12,}\b/g,/\bghp_[A-Za-z0-9_]{12,}\b/g],nj=/\s+\(([A-Z][A-Z0-9_/-]{2,})\)\s*$/;function nk(e){let t=e;for(let e of nw)t=t.replace(e,"[REDACTED]");return t.replace(/\bBearer\s+\[REDACTED\]/gi,"[REDACTED]")}function nN(e,t){return"BAD_REQUEST"===t&&e.toLowerCase().includes("too broad")&&e.toLowerCase().includes("connected")}function nS(e){return"CLARIFICATION_NEEDED"===e}function nC(e,t,n){return"GATEWAY_TIMEOUT"===t&&(0===e.length||e===t)?"The model gateway timed out before the model returned a response.":e.length>0?e:n}function nI(e,t){return nS(t)?"Keiko braucht mehr Kontext":nN(e,t)?"Narrow the connected-source question":"GATEWAY_TIMEOUT"===t?"Model gateway timed out":"PAYLOAD_TOO_LARGE"===t?"Request is too large":"NO_MODEL"===t?"No model is available":void 0!==t?"Request failed":"Something went wrong"}function nE(e,t){return nS(t)?"Nenne eine konkrete Datei, einen Identifier, eine Fehlermeldung oder eine exakte Phrase.":nN(e,t)?"Ask about a specific file, folder, symbol, identifier, or exact phrase. For broad questions over large project folders, narrow the Files scope first.":"GATEWAY_TIMEOUT"===t?"Retry the request. If it repeats, choose a smaller prompt or another configured model, then check the gateway base URL, proxy, and model deployment availability in Settings.":"PAYLOAD_TOO_LARGE"===t?"Reduce the selected scope or remove large attachments before retrying.":void 0}function nR(e,t){if(e instanceof w.ApiError){let n=nC(nk(e.message.trim()),e.code,t);return`${n} (${e.code})`}return e instanceof Error&&e.message.trim().length>0?nk(e.message.trim()):t}let n$="\n…[truncated]",nA=["text/"],nT=new Set(["application/json","application/x-yaml","application/yaml"]),nL=new TextEncoder;function nP(e){return nL.encode(e).length}function nM(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t>=0?e.slice(t+1):e}let nD=`${String(256)} KB`;function nq(e){return`"${e}" won't be sent — the ${nD} attachment limit was already used by earlier files.`}async function nF(e,t){var n,a;let l,i,r,s,o;if(e.remainingAggregate<=0)return nq(nM(t.name));try{l=await t.file.text()}catch{return n=nM(t.name),`Couldn't read "${n}" — it will be skipped. Your message will be sent without it.`}let c=Math.min(65536,Math.max(e.remainingAggregate-nP(n$),0));if(c<=0)return nq(nM(t.name));let{entry:d,consumed:u}=(r=(i=nP(a=l)>c)?function(e,t){if(t<=0)return"";if(nP(e)<=t)return e;let n=0,a="";for(let l of e){let e=n+nP(l);if(e>t)break;n=e,a+=l}return a}(a,c):a,s=nP(r),o=i?nP(n$):0,{entry:{id:t.id,displayName:nM(t.name),mimeType:t.mimeType,sizeBytes:t.sizeBytes,extractedBytes:s,truncated:i,truncationMarker:i?n$:void 0,text:r},consumed:s+o});if(0===d.text.length)return 0===l.length?void 0:nq(nM(t.name));e.entries.push(d),e.remainingAggregate-=u}async function nO(e){let t=e.filter(e=>{var t;return t=e.mimeType,!!nA.some(e=>t.startsWith(e))||nT.has(t)}),n=t.slice(0,16),a={entries:[],remainingAggregate:262144},l=[];for(let e of n){let t=await nF(a,e);void 0!==t&&l.push(t)}for(let e of t.slice(16)){var i;l.push((i=nM(e.name),`"${i}" won't be sent — only the first ${String(16)} documents are included.`))}return{entries:a.entries,failures:l}}let nz=["text/"],nK=new Set(["application/pdf","application/json","application/x-yaml","application/yaml"]),nB="New chat",n_="keiko:chat-upsert",nU="keiko:chat-delete",nW=["completed","failed","cancelled"];function nV(e){return"idle"!==e&&!nW.includes(e)}let nH="The conversation context exceeded the model's window. Clear history or pick a larger-context model.",nY="The model request completed, but the provider did not return any answer text. Retry once; if it happens again, check the selected model deployment in Settings.",nG=new Set(["CONVERSATION_OVERSIZED_CONTEXT","GATEWAY_CONTEXT_OVERFLOW"]),nJ=["context length","context_length_exceeded","max_tokens","too many tokens"],nX=["empty assistant response","empty grounded answer","without assistant content"];function nQ(e){return void 0!==e&&e.contextWindowTokens>0&&"exceeded"===e.pressure}function nZ(e){let t;return function(e){if(e instanceof w.ApiError&&nG.has(e.code))return!0;let t=e instanceof Error?e.message.toLowerCase():"";return 0!==t.length&&nJ.some(e=>t.includes(e))}(e)?nH:0!==(t=e instanceof Error?e.message.toLowerCase():"").length&&nX.some(e=>t.includes(e))?e instanceof w.ApiError?`${nY} (${e.code})`:nY:nR(e,"Something went wrong. Try again.")}function n0(e){return[...e].sort((e,t)=>t.updatedAt-e.updatedAt)}function n1(e){window.dispatchEvent(new CustomEvent(n_,{detail:e}))}function n2(e){return e.find(nx)?.id}function n4(e,t){return void 0!==e&&t.some(t=>t.id===e&&nx(t))?e:n2(t)}function n3(e){return void 0!==e.connectedScope||void 0!==e.connectedScopes&&e.connectedScopes.length>0||void 0!==e.localKnowledgeScope||void 0!==e.localKnowledgeScopes&&e.localKnowledgeScopes.length>0}let n6={projects:[],chats:[],messages:[],models:[],activeProject:void 0,activeChat:void 0,selectedModel:void 0};function n5(e,t){if(0===t.length)return Array.from(e);let n=new Map(t.map(e=>[e.id,e])),a=e.map(e=>n.get(e.id)??e),l=new Set(e.map(e=>e.id));for(let e of t)l.has(e.id)||a.push(e);return a}async function n8(e){let t=(await (0,w.fetchModels)()).models.filter(nx),n=n2(t),a=[...(await (0,w.fetchProjects)().catch(()=>({projects:[]}))).projects].sort((e,t)=>e.favorite!==t.favorite?e.favorite?-1:1:e.lastOpenedAt!==t.lastOpenedAt?t.lastOpenedAt-e.lastOpenedAt:e.path.localeCompare(t.path)),l=a.find(e=>e.available)??a[0];if(void 0!==l){let e=n0((await (0,w.fetchChats)(l.path).catch(()=>({chats:[]}))).chats),n=e[0];if(void 0!==n){let i=await (0,w.fetchChatMessages)(n.id,l.path),r=n4(n.selectedModel,t);return{models:t,selectedModel:r,projects:Array.from(a),activeProject:l,chats:e,activeChat:n,messages:Array.from(i.messages)}}}if(void 0===n||!e)return{models:t,selectedModel:n,projects:Array.from(a),activeProject:l,chats:[],activeChat:void 0,messages:[]};let i={modelId:n,title:nB};l?.available===!0&&(i.projectPath=l.path);let r=await (0,w.createDesktopChat)(i);return n1(r.chat),{models:t,selectedModel:r.chat.selectedModel,projects:Array.from(r.projects),activeProject:r.project,chats:n0(r.chats),activeChat:r.chat,messages:Array.from(r.messages)}}function n7(e={}){let t=e.autoCreate??!0,[n,l]=(0,a.useState)(n6),[i,r]=(0,a.useState)(""),[s,o]=(0,a.useState)(!0),[c,d]=(0,a.useState)("idle"),u=nV(c),p=(0,a.useRef)("idle"),m=(0,a.useRef)(null),[h,f]=(0,a.useState)(),[g,v]=(0,a.useState)(),[b,x]=(0,a.useState)(),[y,j]=(0,a.useState)(!0),[k,N]=(0,a.useState)(1200),S=(0,a.useRef)(!0),C=(0,a.useRef)(void 0),I=(0,a.useRef)(new Set),E=(0,a.useRef)(0),R=(0,a.useRef)([]),[$,A]=(0,a.useState)([]),[T,L]=(0,a.useState)([]),P=(0,a.useCallback)(async e=>{var t;let a;if(0===e.size)return{ok:!1,reason:"empty"};if(e.size>8388608)return{ok:!1,reason:"oversized"};let l=(t=e.type).startsWith("image/")?"image":nz.some(e=>t.startsWith(e))||nK.has(t)?"document":"unsupported-type";if("unsupported-type"===l)return{ok:!1,reason:"unsupported-type"};let i=n.models.find(e=>e.id===n.selectedModel);if(void 0!==i&&("image"===l&&!i.supportsImageInput||"document"===l&&!i.supportsDocumentInput))return{ok:!1,reason:"text-only-model"};if("image"===l)try{a=await new Promise((t,n)=>{let a=new FileReader;a.onload=()=>t(a.result),a.onerror=()=>n(Error("FileReader error")),a.readAsDataURL(e)})}catch{return{ok:!1,reason:"unsupported-type"}}let r={id:crypto.randomUUID(),kind:l,name:e.name,mimeType:e.type,sizeBytes:e.size,previewDataUrl:a,file:e};return A(e=>[...e,r]),{ok:!0}},[n.models,n.selectedModel]),M=(0,a.useCallback)(e=>{A(t=>t.filter(t=>t.id!==e))},[]),D=(0,a.useCallback)(()=>{A([])},[]),q=(0,a.useCallback)(async()=>{let e=$.filter(e=>"document"===e.kind&&void 0!==e.file).map(e=>({id:e.id,name:e.name,mimeType:e.mimeType,sizeBytes:e.sizeBytes,file:e.file}));if(0===e.length)return{entries:[],disclosures:[]};let{entries:t,failures:n}=await nO(e);n.length>0&&f(n.join(" "));let a=t.map(e=>({id:e.id,displayName:e.displayName,truncated:e.truncated}));return{entries:t,disclosures:a}},[$]),F=(0,a.useCallback)(()=>{x(void 0)},[]),O=(0,a.useCallback)((e,t)=>({enabled:y,budgetTokens:k,context:{userId:"local-operator",workspaceId:t.path,projectId:t.path,conversationId:e.id}}),[k,y]),z=(0,a.useCallback)(async e=>{await ns(e),x(t=>void 0===t?t:{...t,actions:t.actions.filter(t=>"candidate"!==t.kind||t.proposalId!==e)})},[]),K=(0,a.useCallback)(async e=>{await no(e),x(t=>void 0===t?t:{...t,actions:t.actions.filter(t=>"candidate"!==t.kind||t.proposalId!==e)})},[]),B=(0,a.useCallback)(async e=>{await nl(e,"user-initiated forget from Conversation Center"),x(t=>void 0===t?t:{...t,actions:t.actions.filter(t=>"forget"!==t.kind||t.memoryId!==e)})},[]),_=(0,a.useCallback)(e=>{p.current=e,d(e)},[]),U=(0,a.useCallback)(async(e,t,n,a)=>{let i=n.runId;if(void 0===i)return void I.current.delete(a);let r={...void 0===n.workflowId?{}:{workflowId:n.workflowId},...void 0===n.taskType?{}:{taskType:n.taskType}};try{for(let a=0;a<120;a+=1){let s;if(!S.current||C.current!==e.id)return;try{let e=await (0,w.fetchRunReport)(i),t=function(e,t){let n=nm(e);if(void 0===n)return{kind:"unknown"};let a=function(e){let t=e.status;if("string"==typeof t)return t}(n),l=nf(t);return"running"===a?{kind:"running"}:"cancelled"===a?{kind:"terminal",summary:{workflowStatus:"cancelled",shortResult:"Run cancelled."}}:"failed"===a||"rejected"===a?{kind:"terminal",summary:{workflowStatus:"failed",shortResult:np(function(e){let t,n,a=(t=nm(e.failure),n=t?.message,"string"==typeof n&&n.length>0?n:void 0);return void 0!==a?np(`Run failed: ${a}.`):"Run failed."}(n))}}:void 0!==a&&nu.has(a)?{kind:"terminal",summary:{workflowStatus:"completed",shortResult:np(function(e,t){if("unit-tests"===t)return function(e){let t,n=e.addedTestFiles;if(Array.isArray(n)){let e=0,a=!1;for(let t of n){let n=nm(t),l=n?.estimatedTestCount;"number"==typeof l&&Number.isFinite(l)&&(e+=l,a=!0)}a&&(t=e)}let a=Array.isArray(n)?n.length:0;return a>0&&void 0!==t?`Generated ${String(a)} test files; ${String(t)} tests proposed.`:a>0?`Generated ${String(a)} test files.`:"Completed."}(e);if("bug"===t)return nh();if("verify"===t){let t,n;return t=nm(e.verificationSummary),n=t?.results,Array.isArray(n)&&n.length>0?`Verification passed: ${String(n.length)} classifications.`:"Verification passed."}if("explain"===t){let t=e.dryRunPreview;if("string"==typeof t&&t.length>0){let e=t.split("\n").filter(e=>e.trim().length>0);if(e.length>0)return`Plan generated; ${String(e.length)} steps.`}return"Plan generated."}return"Completed."}(n,l))}}:{kind:"unknown"}}(e.report,r);"terminal"===t.kind&&(s=t.summary)}catch(e){if(!(e instanceof w.ApiError)||404!==e.status)return;try{let e=await (0,w.fetchEvidenceManifest)(i),t=function(e,t){let n=nm(e),a=void 0===n?void 0:nm(n.run),l=void 0===a?void 0:a.outcome,i=nf(t);return"cancelled"===l?{workflowStatus:"cancelled",shortResult:"Run cancelled."}:"failed"===l||"limit-exceeded"===l?{workflowStatus:"failed",shortResult:"Run failed."}:"completed"===l?{workflowStatus:"completed",shortResult:np("bug"===i?nh():"verify"===i?"Verification passed.":"explain"===i?"Plan generated.":"unit-tests"===i?"Generated tests.":"Completed.")}:{workflowStatus:"completed",shortResult:"Completed."}}(e.manifest,r);s={workflowStatus:"failed"===t.workflowStatus||"cancelled"===t.workflowStatus?t.workflowStatus:"completed",shortResult:t.shortResult}}catch{}}if(void 0!==s){let a=await (0,w.patchChatMessage)(n.id,e.id,t,s);if(!S.current||C.current!==e.id)return;l(t=>t.activeChat?.id!==e.id?t:{...t,messages:t.messages.map(e=>e.id===n.id?a.message:e)});return}a<119&&await new Promise(e=>{globalThis.setTimeout(e,1e3)})}}finally{I.current.delete(a)}},[]);(0,a.useEffect)(()=>{C.current=n.activeChat?.id},[n.activeChat?.id]),(0,a.useEffect)(()=>{R.current=n.models},[n.models]),(0,a.useEffect)(()=>{let e=!1;return async function(){o(!0),f(void 0);try{let n=await n8(t);e||l(e=>({...e,...n}))}catch(t){e||f(nZ(t))}finally{e||o(!1)}}(),()=>{e=!0}},[t]),(0,a.useEffect)(()=>{let e=e=>{let t=e.detail;"object"==typeof t&&null!==t&&"string"==typeof t.id&&"string"==typeof t.projectPath&&"string"==typeof t.title&&"string"==typeof t.selectedModel&&l(e=>({...e,chats:n0([t,...e.chats.filter(e=>e.id!==t.id)]),activeChat:e.activeChat?.id===t.id?t:e.activeChat,selectedModel:e.activeChat?.id===t.id?n4(t.selectedModel,e.models):e.selectedModel}))},t=e=>{let t=e.detail;"object"==typeof t&&null!==t&&"string"==typeof t.chatId&&l(e=>({...e,chats:e.chats.filter(e=>e.id!==t.chatId),activeChat:e.activeChat?.id===t.chatId?void 0:e.activeChat,messages:e.activeChat?.id===t.chatId?[]:e.messages}))};return window.addEventListener(n_,e),window.addEventListener(nU,t),()=>{window.removeEventListener(n_,e),window.removeEventListener(nU,t)}},[]),(0,a.useEffect)(()=>(S.current=!0,()=>{S.current=!1,m.current?.abort()}),[]),(0,a.useEffect)(()=>{let e=n.activeChat,t=n.activeProject;if(void 0!==e&&void 0!==t)for(let a of n.messages){if("system"!==a.role||"string"!=typeof a.runId||void 0!==a.workflowStatus&&"pending"!==a.workflowStatus&&"running"!==a.workflowStatus)continue;let n=a.runId;if(void 0===n)continue;let l=`${a.id}:${n}`;I.current.has(l)||(I.current.add(l),U(e,t.path,a,l))}},[n.activeChat,n.activeProject,n.messages,U]);let W=(0,a.useCallback)(e=>{let t;f(void 0),l(n=>(t={selectedModel:n.selectedModel,activeChat:n.activeChat,chats:n.chats},{...n,selectedModel:e,activeChat:void 0===n.activeChat?n.activeChat:{...n.activeChat,selectedModel:e},chats:n.chats.map(t=>void 0!==n.activeChat&&t.id===n.activeChat.id?{...t,selectedModel:e}:t)})),A(t=>t.filter(t=>{let n;return void 0===(n=R.current.find(t=>t.id===e))||("image"===t.kind?n.supportsImageInput:n.supportsDocumentInput)}));let n=C.current;if(void 0===n)return;let a=E.current+1;E.current=a,(0,w.updateChat)(n,{selectedModel:e}).then(e=>{E.current!==a||C.current===e.chat.id&&(n1(e.chat),l(t=>({...t,selectedModel:e.chat.selectedModel,activeChat:t.activeChat?.id===e.chat.id?e.chat:t.activeChat,chats:t.chats.map(t=>t.id===e.chat.id?e.chat:t)})))}).catch(e=>{if(E.current===a&&C.current===n&&(f(nZ(e)),void 0!==t)){let e=t;l(t=>({...t,selectedModel:t.activeChat?.id===n?e.selectedModel:t.selectedModel,activeChat:t.activeChat?.id===n?e.activeChat:t.activeChat,chats:t.chats.map(t=>{if(t.id!==n)return t;let a=e.chats.find(e=>e.id===n);return void 0!==a?{...t,selectedModel:a.selectedModel}:t})}))}})},[]),V=(0,a.useCallback)(async(e,t)=>{let a=n4(n.selectedModel,n.models);if(void 0===a)return void f("No conversation-eligible model is configured. Connect a gateway in Settings.");f(void 0);try{let i=t?.trim(),r={modelId:a,title:void 0!==i&&i.length>0?i:nB},s=e?.path??n.activeProject?.path;void 0!==s&&(r.projectPath=s);let o=await (0,w.createDesktopChat)(r);return C.current=o.chat.id,n1(o.chat),l({projects:Array.from(o.projects),chats:n0(o.chats),messages:Array.from(o.messages),models:n.models,activeProject:o.project,activeChat:o.chat,selectedModel:o.chat.selectedModel}),o.chat}catch(e){f(nZ(e));return}},[n.selectedModel,n.activeProject,n.models]),H=(0,a.useCallback)(async e=>{f(void 0),l(t=>({...t,activeProject:e}));try{let t=await (0,w.fetchChats)(e.path),a=n0(t.chats),i=a[0];if(void 0===i)return void await V(e);let r=await (0,w.fetchChatMessages)(i.id,e.path);C.current=i.id;let s=n4(i.selectedModel,n.models);l(e=>({...e,chats:a,activeChat:i,selectedModel:s,messages:Array.from(r.messages)})),x(void 0)}catch(e){f(nZ(e))}},[V,n.models]),Y=(0,a.useCallback)(async e=>{f(void 0),m.current?.abort(),m.current=null,C.current=e.id,v(void 0),x(void 0),L([]);try{let t=await (0,w.fetchChatMessages)(e.id,e.projectPath),a=n4(e.selectedModel,n.models);l(n=>{let l=n.projects.find(t=>t.path===e.projectPath);return{...n,activeProject:l,activeChat:e,selectedModel:a,messages:Array.from(t.messages)}})}catch(e){f(nZ(e))}},[n.models]),G=(0,a.useCallback)(async e=>{let t=e.trim();if(0!==t.length){f(void 0);try{let e=await (0,w.createProject)({path:t}),n=await (0,w.fetchProjects)();l(e=>({...e,projects:Array.from(n.projects)})),await V(e.project)}catch(e){f(nZ(e))}}},[V]),J=(0,a.useCallback)(e=>{l(t=>({...t,messages:t.messages.filter(t=>t.id!==e)}))},[]),X=(0,a.useCallback)((e,t,n)=>{let a=!1;return{onToken:t=>{a||(_("streaming"),a=!0),l(n=>({...n,messages:n.messages.map(n=>n.id===e?{...n,content:n.content+t}:n)}))},onDone:a=>{l(n=>({...n,activeChat:a.chat,chats:n0([a.chat,...n.chats.filter(e=>e.id!==a.chat.id)]),messages:[...n.messages.filter(n=>n.id!==t&&n.id!==e),...Array.from(a.messages)]})),n1(a.chat),void 0!==a.memory&&x(a.memory),n("completed")},onError:({code:t,message:a})=>{f(nZ(new w.ApiError(t,a,0))),J(e),n("failed")},onCancelled:()=>{J(e),n("cancelled")}}},[J,_]),Q=(0,a.useCallback)((e,t,n,a,i,r,s)=>{let o=`stream-${String(Date.now())}`;l(t=>({...t,messages:[...t.messages,{id:o,chatId:e.id,role:"assistant",content:"",timestamp:Date.now(),runId:void 0,workflowId:void 0,workflowStatus:void 0,shortResult:void 0,taskType:void 0}]}));let c={chatId:e.id,projectPath:t.path,content:n,modelId:i,memory:O(e,t),...s.length>0?{documentContext:s}:{}};return new Promise((e,t)=>{let n=X(o,a,e);(0,w.sendDesktopChatStream)(c,r,n).catch(n=>{J(o),n instanceof w.StreamingUnavailableError?t(n):n instanceof DOMException&&"AbortError"===n.name?e("cancelled"):(f(nZ(n)),l(e=>({...e,messages:e.messages.filter(e=>e.id!==a)})),e("failed"))})})},[O,X,J]),Z=(0,a.useCallback)(async(e,t,n,a,i,r,s)=>{try{_("contacting");let o=await (0,w.sendDesktopChat)({chatId:e.id,projectPath:t.path,content:n,modelId:i,memory:O(e,t),...s.length>0?{documentContext:s}:{}},r);if(r.aborted)return"cancelled";return l(e=>({...e,activeChat:o.chat,chats:n0([o.chat,...e.chats.filter(e=>e.id!==o.chat.id)]),messages:[...e.messages.filter(e=>e.id!==a),...Array.from(o.messages)]})),n1(o.chat),x(o.memory),"completed"}catch(n){if(n instanceof DOMException&&"AbortError"===n.name)return"cancelled";f(nZ(n));try{let n=await (0,w.fetchChatMessages)(e.id,t.path);l(e=>({...e,messages:Array.from(n.messages)}))}catch{l(e=>({...e,messages:e.messages.filter(e=>e.id!==a)}))}return"failed"}},[O,_]),ee=(0,a.useCallback)(async(e,t,a,l,i,r,s)=>{if(n.models.find(e=>e.id===i)?.streaming!==!0)return Z(e,t,a,l,i,r,s);_("contacting");try{return await Q(e,t,a,l,i,r,s)}catch(e){if(!(e instanceof w.StreamingUnavailableError))throw e}return Z(e,t,a,l,i,r,s)},[n.models,Z,Q,_]),et=(0,a.useCallback)(async(e,t,n,a,i,r)=>{v(void 0);try{_("contacting");let t=await (0,w.askGrounded)({chatId:e.id,content:n,modelId:i},r);if(C.current!==e.id)return"completed";if(r.aborted)return"cancelled";v(t),x(void 0);let[a,s]=await Promise.all([(0,w.fetchChatMessages)(e.id,e.projectPath),(0,w.fetchChats)(e.projectPath)]),o=s.chats.find(t=>t.id===e.id);return l(e=>({...e,messages:Array.from(a.messages),chats:n0(s.chats),activeChat:o??e.activeChat})),void 0!==o&&n1(o),"completed"}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)return"cancelled";return f(nZ(e)),l(e=>({...e,messages:e.messages.filter(e=>e.id!==a)})),"failed"}},[_]),en=(0,a.useCallback)(()=>{nV(p.current)&&(m.current?.abort(),m.current=null,_("cancelled"))},[_]),ea=(0,a.useCallback)(async()=>{if(nV(p.current))return;let e=i.trim(),t=n.activeChat,a=n.activeProject,s=n4(n.selectedModel,n.models);if(0===e.length||void 0===t||void 0===a||void 0===s)return;if(nQ(nb({modelContextWindow:n.models.find(e=>e.id===s)?.contextWindow??0,modelMaxOutputTokens:n.models.find(e=>e.id===s)?.maxOutputTokens??0,userDraftText:e,conversationHistory:n.messages.filter(e=>"user"===e.role||"assistant"===e.role).map(e=>({role:e.role,content:e.content}))})))return void f(nH);if(n3(t)&&$.length>0)return void f("Attachments are not supported for grounded chats. Remove the attachment or switch to a non-grounded chat.");let o={id:`local-${String(Date.now())}`,chatId:t.id,role:"user",content:e,timestamp:Date.now(),runId:void 0,workflowId:void 0,workflowStatus:void 0,shortResult:void 0,taskType:void 0};_("queued"),r(""),f(void 0),l(e=>({...e,messages:[...e.messages,o]}));let c=new AbortController;m.current=c,x(void 0);try{let n=n3(t),{entries:l,disclosures:i}=n?{entries:[],disclosures:[]}:await q(),r=n?await et(t,a,e,o.id,s,c.signal):await ee(t,a,e,o.id,s,c.signal,l);"cancelled"===p.current||_(r),"completed"===r&&(D(),L(i))}finally{m.current=null}},[i,n.activeChat,n.activeProject,n.selectedModel,n.models,n.messages,$,et,ee,q,D,_]),el=(0,a.useCallback)(()=>{v(void 0),x(void 0),l(e=>({...e,messages:[]}))},[]),ei=(0,a.useMemo)(()=>{let e=n.models.find(e=>e.id===n.selectedModel);if(void 0===e)return;let t=n.messages.filter(e=>"user"===e.role||"assistant"===e.role).map(e=>({role:e.role,content:e.content})),a=0,l=0;void 0!==g&&(("connected-context"===g.groundingKind||"hybrid"===g.groundingKind)&&(a=("hybrid"===g.groundingKind?g.contextPack.folder:g.contextPack).usage.excerptBytes),("local-knowledge"===g.groundingKind||"hybrid"===g.groundingKind)&&(l=4*("hybrid"===g.groundingKind?g.contextPack.knowledge:g.contextPack).referenceBudget));let r=y&&void 0!==b&&b.context.enabled?b.context.text.length:0;return nb({modelContextWindow:e.contextWindow,modelMaxOutputTokens:e.maxOutputTokens,userDraftText:i,conversationHistory:t,repoContextPackBytes:a,knowledgeCapsuleBytes:l,memoryContextBytes:r})},[n.models,n.selectedModel,n.messages,i,g,b,y]),er=(0,a.useCallback)(async e=>{if(nV(p.current))return{ok:!1,reason:"request-failed",message:"A request is already in flight."};let t=e.text.trim();if(0===t.length)return{ok:!1,reason:"missing-input"};let a=n.activeChat,i=n.activeProject;if(void 0===a||void 0===i)return{ok:!1,reason:"missing-chat"};let r=n.models.find(t=>t.id===e.modelId);if(void 0===r||!t_(r))return{ok:!1,reason:"not-workflow-eligible"};let s=nd(e.workflowId);if(void 0===s)return{ok:!1,reason:"unknown-workflow"};let o=Date.now(),c=s.buildInput(i.path,t);try{let n=await (0,w.startChatRun)({chatId:a.id,projectPath:i.path,run:{workflowId:e.workflowId,input:c,modelId:e.modelId},user:{content:t,timestamp:o},summary:{content:`Launched: ${s.label}`,timestamp:o+1}});return l(e=>({...e,messages:n5(e.messages,n.messages)})),{ok:!0,runId:n.run.runId}}catch(t){let e=nZ(t);return f(e),{ok:!1,reason:"request-failed",message:e}}},[n.activeChat,n.activeProject,n.models]),es=(0,a.useCallback)(async e=>{if(nV(p.current))return{ok:!1,reason:"request-failed",message:"A request is already in flight."};if(void 0===n.activeChat)return{ok:!1,reason:"missing-chat"};if(0===e.modelId.trim().length)return{ok:!1,reason:"missing-model"};try{let t=await (0,w.startGroundedWorkflowHandoff)({assistantMessageId:e.assistantMessageId,chatId:n.activeChat.id,modelId:e.modelId,workflowKind:e.workflowKind,input:e.input,editablePaths:e.editablePaths,...void 0===e.expectedChecks?{}:{expectedChecks:e.expectedChecks},...void 0===e.unknowns?{}:{unknowns:e.unknowns},requestedAtMs:Date.now()});return l(e=>({...e,messages:n5(e.messages,t.messages)})),{ok:!0,runId:t.run.runId}}catch(t){let e=nZ(t);return f(e),{ok:!1,reason:"request-failed",message:e}}},[n.activeChat]),eo=(0,a.useCallback)(e=>{n1(e),l(t=>({...t,chats:t.chats.map(t=>t.id===e.id?e:t),activeChat:t.activeChat?.id===e.id?e:t.activeChat}))},[]),ec=(0,a.useCallback)(()=>{f(void 0)},[]);return{projects:n.projects,chats:n.chats,messages:n.messages,models:n.models,activeProject:n.activeProject,activeChat:n.activeChat,selectedModel:n.selectedModel,noEligibleModels:!s&&void 0===n4(n.selectedModel,n.models),draft:i,loading:s,sending:u,sendStatus:c,error:h,clearError:ec,setDraft:r,setSelectedModel:W,openNewChat:V,openProject:H,openChat:Y,addProject:G,sendMessage:ea,cancelSend:en,replaceChat:eo,latestGrounded:g,cancelGrounded:en,pendingAttachments:$,addPendingAttachment:P,removePendingAttachment:M,clearPendingAttachments:D,lastSentDocuments:T,budget:ei,memoryEnabled:y,setMemoryEnabled:j,memoryBudgetTokens:k,setMemoryBudgetTokens:N,latestMemory:b,clearLatestMemory:F,acceptMemoryCandidate:z,rejectMemoryCandidate:K,forgetMemoryAction:B,clearHistory:el,launchWorkflowFromConversation:er,launchGroundedWorkflowHandoff:es}}let n9="keiko.theme",ae="dark";var at=e.i(26428);let an=["agent","capsule","capsule-set","chat","connector","data-source","evidence-run","mcp-tool","memory","patch-proposal","skill","tool","workflow-run","workspace-path"],aa=["capsule","capsule-set","chat","evidence-run","memory","patch-proposal","tool","workflow-run","workspace-path"],al=["reads-context","proposes-patch","uses-tool","starts-workflow","produces-evidence","references-document","depends-on"],ai=["draft","active","archived","superseded","revoked","blocked","stale"],ar={"reads-context":{id:"reads-context",displayName:"reads context",semantics:"A consumer endpoint reads the contextual content of the target at a specific point in time.",validSourceKinds:["workflow-run","chat"],validTargetKinds:["memory","capsule","capsule-set","evidence-run","workspace-path","connector","data-source"],cardinality:"N:N",direction:"directed",lifecycle:{creatable:!0,immutable:!0,reconnectable:!1,deletable:!1,archivable:!0},auditEventOnMutation:!0,evidenceRelevance:"reference",ownerPackage:"@oscharko-dev/keiko-workflows",trustBoundary:"per-endpoint"},"proposes-patch":{id:"proposes-patch",displayName:"proposes patch",semantics:"A workflow run proposes a patch against one or more workspace paths. The relationship records the proposal; diff content stays in the harness PatchProposedEvent.",validSourceKinds:["workflow-run"],validTargetKinds:["workspace-path","patch-proposal"],cardinality:"1:N",direction:"directed",lifecycle:{creatable:!0,immutable:!0,reconnectable:!1,deletable:!0,archivable:!0},auditEventOnMutation:!0,evidenceRelevance:"reference",ownerPackage:"@oscharko-dev/keiko-workflows",trustBoundary:"fs"},"uses-tool":{id:"uses-tool",displayName:"uses tool",semantics:"A workflow run uses a registered tool. Per-call arguments and results remain in the harness ToolCallRequest / ToolCallResult envelopes.",validSourceKinds:["workflow-run"],validTargetKinds:["tool","mcp-tool"],cardinality:"N:N",direction:"directed",lifecycle:{creatable:!0,immutable:!0,reconnectable:!1,deletable:!1,archivable:!0},auditEventOnMutation:!0,evidenceRelevance:"reference",ownerPackage:"@oscharko-dev/keiko-workflows",trustBoundary:"tool"},"starts-workflow":{id:"starts-workflow",displayName:"starts workflow",semantics:"A chat or a parent workflow run initiates a workflow run. The relationship records the origin; run identity belongs to the workflow ledger.",validSourceKinds:["chat","workflow-run"],validTargetKinds:["workflow-run"],cardinality:"1:N",direction:"directed",lifecycle:{creatable:!0,immutable:!0,reconnectable:!1,deletable:!1,archivable:!0},auditEventOnMutation:!0,evidenceRelevance:"reference",ownerPackage:"@oscharko-dev/keiko-workflows",trustBoundary:"per-endpoint"},"produces-evidence":{id:"produces-evidence",displayName:"produces evidence",semantics:"A workflow run produces exactly one durable evidence-run record. If a run produces no evidence, no relationship is recorded.",validSourceKinds:["workflow-run"],validTargetKinds:["evidence-run"],cardinality:"1:1",direction:"directed",lifecycle:{creatable:!0,immutable:!0,reconnectable:!1,deletable:!1,archivable:!0},auditEventOnMutation:!0,evidenceRelevance:"produces",ownerPackage:"@oscharko-dev/keiko-evidence",trustBoundary:"evidence"},"references-document":{id:"references-document",displayName:"references document",semantics:"A chat or workflow run holds a structural pointer to a document (workspace file or local-knowledge capsule). Distinct from reads-context: a reference is structural, a read is an event.",validSourceKinds:["chat","workflow-run"],validTargetKinds:["workspace-path","capsule","capsule-set"],cardinality:"N:N",direction:"directed",lifecycle:{creatable:!0,immutable:!1,reconnectable:!0,deletable:!0,archivable:!0},auditEventOnMutation:!0,evidenceRelevance:"reference",ownerPackage:"@oscharko-dev/keiko-workflows",trustBoundary:"per-endpoint"},"depends-on":{id:"depends-on",displayName:"depends on",semantics:"A capsule, capsule-set, workflow run, or memory depends on another. Used by impact analysis (#542). Self-loops and direct two-edge cycles are forbidden at validation time; transitive cycle detection is deferred to impact traversal.",validSourceKinds:["capsule","capsule-set","workflow-run","memory"],validTargetKinds:["capsule","capsule-set","workflow-run","memory","evidence-run","workspace-path"],cardinality:"N:N",direction:"directed",lifecycle:{creatable:!0,immutable:!1,reconnectable:!0,deletable:!0,archivable:!0},auditEventOnMutation:!0,evidenceRelevance:"reference",ownerPackage:"@oscharko-dev/keiko-contracts",trustBoundary:"per-endpoint"}},as=["prompt","documentcontent","filecontent","toolstdout","toolstderr","secret","credential","apikey","password","token"],ao="Unable to reach the local backend. Check that the Keiko server is running (keiko ui).";class ac extends Error{code;status;reasons;constructor(e,t,n,a=[]){super(t),this.name="RelationshipApiError",this.code=e,this.status=n,this.reasons=a}}async function ad(e){let t;try{t=await e.json()}catch{throw new ac("relationship/parse-error","Response is not valid JSON.",e.status)}if(!e.ok){let n=t,a=n.error??n,l="string"==typeof a.code?a.code:"relationship/unknown-error",i="string"==typeof a.message?a.message:"An unknown error occurred.",r=Array.isArray(n.reasons)?n.reasons:[];throw new ac(l,i,e.status,r)}return t}function au(e){let t={"Content-Type":"application/json","X-Keiko-CSRF":"1"};return void 0!==e.idempotencyKey&&(t["Idempotency-Key"]=e.idempotencyKey),void 0!==e.ifMatch&&(t["If-Match"]=e.ifMatch),t}async function ap(e){let t={schemaVersion:"1",proposal:{type:e.type,source:{kind:e.source.kind,id:e.source.id},target:{kind:e.target.kind,id:e.target.id},...void 0!==e.summary?{summary:e.summary}:{}}},n=await fetch("/api/relationships/validate",{method:"POST",headers:au({}),body:JSON.stringify(t)});return{decision:(await ad(n)).decision}}async function am(e,t){let n={schemaVersion:"1",proposal:{type:e.type,source:{kind:e.source.kind,id:e.source.id},target:{kind:e.target.kind,id:e.target.id},...void 0!==e.summary?{summary:e.summary}:{}}},a=await fetch("/api/relationships",{method:"POST",headers:au({idempotencyKey:t}),body:JSON.stringify(n)}),l=await ad(a);return{relationship:l.relationship,etag:l.etag}}async function ah(e){let t=new URLSearchParams;void 0!==e.lifecycle&&t.set("lifecycle",e.lifecycle),void 0!==e.type&&t.set("type",e.type),void 0!==e.sourceKind&&t.set("sourceKind",e.sourceKind),void 0!==e.targetKind&&t.set("targetKind",e.targetKind),void 0!==e.sourceId&&t.set("sourceId",e.sourceId),void 0!==e.targetId&&t.set("targetId",e.targetId),void 0!==e.limit&&t.set("limit",String(e.limit)),void 0!==e.cursor&&t.set("cursor",e.cursor);let n=await fetch(`/api/relationships?${t.toString()}`),a=await ad(n);return{entries:a.entries,truncated:a.truncated,nextCursor:a.nextCursor}}async function af(e){let t=await fetch(`/api/relationships/${encodeURIComponent(e)}`);return(await ad(t)).relationship}async function ag(e,t,n,a){let l=await fetch(`/api/relationships/${encodeURIComponent(e)}`,{method:"PATCH",headers:au({idempotencyKey:a,ifMatch:n}),body:JSON.stringify({schemaVersion:"1",...t})}),i=await ad(l);return{relationship:i.relationship,etag:i.etag}}async function av(e,t,n){let a=await fetch(`/api/relationships/${encodeURIComponent(e)}`,{method:"DELETE",headers:au({idempotencyKey:n,ifMatch:t})});return(await ad(a)).relationship}async function ab(e,t={}){let n=new URLSearchParams;void 0!==t.direction&&n.set("direction",t.direction),void 0!==t.maxDepth&&n.set("maxDepth",String(t.maxDepth)),void 0!==t.maxNodes&&n.set("maxNodes",String(t.maxNodes)),void 0!==t.maxRelationships&&n.set("maxRelationships",String(t.maxRelationships));let a=await fetch(`/api/relationships/${encodeURIComponent(e)}/dependencies?${n.toString()}`);return(await ad(a)).report}async function ax(e){return ad(await fetch(`/api/relationships/${encodeURIComponent(e)}/explain`))}async function ay(){return ad(await fetch("/api/relationships/health"))}let aw=[{key:"t",mod:["cmd"]},{key:"t",mod:["ctrl"]},{key:"r",mod:["cmd"]},{key:"r",mod:["ctrl"]},{key:"n",mod:["cmd","shift"]},{key:"n",mod:["ctrl","shift"]},{key:"w",mod:["cmd"]},{key:"w",mod:["ctrl"]}];function aj(e){switch(e.kind){case"ui.window.move":return"Move window";case"ui.window.resize":return"Resize window";case"ui.window.zorder":return"Reorder window";case"ui.window.close":return"Close window";case"ui.window.open":return"Open window";case"ui.workspace.pan":return"Pan workspace";case"ui.workspace.zoom":return"Zoom workspace";case"ui.workspace.fit":return"Fit workspace to view";case"ui.panel.toggle":return`Toggle ${e.panel} panel`;case"ui.selection.change":return"Change selection";case"ui.tab.switch":return"Switch tab"}}function ak(e){let t=[...e.mod].sort();return`${t.join("+")}|${e.key.toLowerCase()}`}let aN={undoStack:[],redoStack:[]};class aS extends Error{conflicts;constructor(e){super(`Workspace keyboard shortcut conflicts detected: ${e.map(e=>`${ak(e.chord)} (${e.commandIds.join(", ")})`).join("; ")}`),this.name="WorkspaceShortcutConflictError",this.conflicts=e}}class aC extends Error{reserved;constructor(e){super(`Workspace keyboard shortcut bindings refused: ${e.map(e=>`${e.commandId} → ${ak(e.chord)}`).join("; ")} are browser-reserved`),this.name="WorkspaceShortcutReservedError",this.reserved=e}}let aI=[{commandId:"undo",chord:{key:"z",mod:["cmd"]}},{commandId:"redo",chord:{key:"z",mod:["cmd","shift"]}},{commandId:"focus-status",chord:{key:"s",mod:["alt"]}}];var aE=e.i(57688);let aR="cmp-budget-exceeded-alert",a$={low:"Low",moderate:"Moderate",high:"High",exceeded:"Exceeded"},aA={low:"cmp-budget-badge cmp-budget-badge-low",moderate:"cmp-budget-badge cmp-budget-badge-moderate",high:"cmp-budget-badge cmp-budget-badge-high",exceeded:"cmp-budget-badge cmp-budget-badge-exceeded"},aT="Token counts are approximate. Actual model usage may vary.";function aL(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:e.toString()}function aP({budget:e,onClearHistory:t,disabled:l,compact:i=!1}){let[r,s]=(0,a.useState)(!1),[o,c]=(0,a.useState)(!1),d=(0,a.useRef)(null),u=(0,a.useRef)(null);if((0,a.useEffect)(()=>{r&&d.current?.focus()},[r]),void 0===e)return null;let p=e.contextWindowTokens>0,m=aL(e.approximateTokens),h=aL(e.contextWindowTokens),f=e.pressure,g=p&&"exceeded"===f;return(0,n.jsxs)("div",{className:"cmp-budget","data-pressure":p?f:"unknown",children:[(0,n.jsxs)("div",{className:"cmp-budget-row",children:[(0,n.jsx)("span",{className:"cmp-budget-count",children:p?i?`Context: ${m} / ${h}`:`Approximate context: ${m} / ${h} tokens`:i?`Context: ${m}`:`Approximate context: ${m} tokens`}),p?(0,n.jsx)("span",{className:aA[f],"aria-label":`Context pressure: ${a$[f]}`,children:a$[f]}):null,(0,n.jsx)("span",{className:"cmp-budget-info",role:"img",tabIndex:0,"aria-label":aT,"data-tip":aT,children:"i"}),r?(0,n.jsxs)("span",{className:"cmp-budget-confirm",children:[(0,n.jsx)("span",{className:"cmp-budget-confirm-label",id:"cmp-budget-confirm-label",children:"Clear history?"}),(0,n.jsx)("button",{type:"button",ref:d,className:"cmp-budget-clear","aria-describedby":"cmp-budget-confirm-label",onClick:function(){t(),s(!1),c(!0),requestAnimationFrame(()=>u.current?.focus())},children:"Clear"}),(0,n.jsx)("button",{type:"button",className:"cmp-budget-clear",onClick:function(){s(!1),requestAnimationFrame(()=>u.current?.focus())},children:"Cancel"})]}):(0,n.jsx)("button",{type:"button",ref:u,className:"cmp-budget-clear","aria-label":"Clear conversation history for next prompt",onClick:()=>{c(!1),s(!0)},disabled:!0===l,children:i?"Clear":"Clear history"}),o?(0,n.jsx)("span",{role:"status",className:"cmp-budget-cleared",children:"History cleared for the next prompt — messages remain saved."}):null]}),g?(0,n.jsx)("div",{id:aR,role:"alert",className:"cmp-budget-alert gw-error",children:"Context exceeds the selected model's window. Clear history or pick a model with a larger context."}):null]})}function aM({notice:e,className:t="ui-error-notice",id:l,onDismiss:i}){let r=`${e.title}
|
|
96
96
|
${e.message}
|
|
97
97
|
${e.code??""}
|
|
98
98
|
${e.remediation??""}`,[s,o]=(0,a.useState)();return s===r?null:(0,n.jsxs)("div",{id:l,className:t,role:"alert","aria-live":"assertive",children:[(0,n.jsxs)("div",{className:"ui-error-notice-title-row",children:[(0,n.jsx)("div",{className:"ui-error-notice-title",children:e.title}),(0,n.jsx)("button",{type:"button",className:"ui-error-notice-close","aria-label":"Dismiss error",title:"Dismiss error",onClick:()=>{o(r),i?.()},children:(0,n.jsx)(j.Icons.close,{size:14})})]}),(0,n.jsx)("div",{className:"ui-error-notice-message",children:e.message}),void 0!==e.remediation?(0,n.jsx)("div",{className:"ui-error-notice-remediation",children:e.remediation}):null,void 0!==e.code?(0,n.jsx)("div",{className:"ui-error-notice-code mono",children:e.code}):null]})}function aD({error:e,fallback:t,className:a,id:l,onDismiss:i}){return(0,n.jsx)(aM,{id:l,className:a,notice:function(e,t){var n;let a;if(e instanceof w.ApiError){let n=nC(nk(e.message.trim()),e.code,t);return{title:nI(n,e.code),message:n,code:e.code,remediation:nE(n,e.code)}}let l=(n=nk(("string"==typeof e?e.trim():e instanceof Error?e.message.trim():"")||t),null===(a=nj.exec(n))?{message:n,code:void 0}:{message:n.slice(0,a.index).trim(),code:a[1]});return{title:nI(l.message,l.code),message:l.message,code:l.code,remediation:nE(l.message,l.code)}}(e,t),onDismiss:i})}var aq=e.i(83449);function aF(e){return Number.isFinite(e)?String(e):"—"}function aO(e,t){return Number.isFinite(e)?t(e):"—"}function az(e){return e.toLocaleString("en-US")}function aK(e){return e.replaceAll("-"," ")}function aB({label:e,value:t}){return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("dt",{className:"grounded-context-pack-dt",children:e}),(0,n.jsx)("dd",{className:"grounded-context-pack-dd",children:t})]})}function a_({contextPack:e}){let{usage:t,budget:a}=e,l=function(e){if("workspace-root"===e.scopeKind)return"workspace root";let t=e.scopeId.slice(-8);return`${aK(e.scopeKind)} (${t})`}(e),i="files"===e.scopeKind?`Scope: ${String(e.fileCount)} file${1===e.fileCount?"":"s"} in ${l}`:`Scope: ${l}`;return(0,n.jsxs)("section",{className:"grounded-context-pack","aria-label":"Context inspection summary",children:[(0,n.jsx)("div",{className:"grounded-context-pack-headline",children:i}),(0,n.jsxs)("dl",{className:"grounded-context-pack-dl",children:[(0,n.jsx)(aB,{label:"Searched",value:`${String(t.searchCalls)} / ${aF(a.searchCallsMax)} searches`}),(0,n.jsx)(aB,{label:"Read",value:`${String(t.filesRead)} / ${aF(a.filesReadMax)} files`}),(0,n.jsx)(aB,{label:"Bytes",value:`${(0,aq.formatBytes)(t.excerptBytes)} / ${aO(a.excerptBytesMax,aq.formatBytes)}`}),(0,n.jsx)(aB,{label:"Input",value:`${az(t.modelInputTokens)} / ${aO(a.modelInputTokensMax,az)} tokens`}),(0,n.jsx)(aB,{label:"Output",value:`${az(t.modelOutputTokens)} / ${aO(a.modelOutputTokensMax,az)} tokens`}),(0,n.jsx)(aB,{label:"Rerank",value:`${String(t.rerankCalls)} / ${aF(a.rerankCallsMax)} calls`}),(0,n.jsx)(aB,{label:"Time",value:`${(0,aq.formatMs)(e.elapsedMs)} / ${aO(a.elapsedMsMax,aq.formatMs)}`}),(0,n.jsx)(aB,{label:"Query",value:aK(e.queryKind)})]})]})}function aU({score:e}){return(0,n.jsxs)("span",{className:"grounded-citation-score",children:[(0,n.jsx)("span",{className:"sr-only",children:"relevance "}),e.toFixed(2)]})}function aW({citation:e}){let t=e.documentFormat?.toUpperCase();return(0,n.jsxs)("span",{className:"grounded-citation",title:function(e){let t=`relevance ${e.score.toFixed(2)}`,n=void 0===e.documentFormat?"Evidence citation":`${e.documentFormat.toUpperCase()} document evidence (extracted text)`;if(void 0===e.lineRange)return`${n} in ${e.scopePath} — ${t}`;let a=void 0===e.documentFormat?`at lines ${String(e.lineRange.startLine)}-${String(e.lineRange.endLine)}`:`at extracted span ${String(e.lineRange.startLine)}-${String(e.lineRange.endLine)}`;return`${n} in ${e.scopePath} ${a} — ${t}`}(e),children:[void 0===t?null:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"grounded-citation-doc-badge",children:t}),(0,n.jsx)("span",{className:"sr-only",children:" document evidence extracted text "})]}),(0,n.jsx)("span",{className:"grounded-citation-range",children:void 0===e.lineRange?e.scopePath:`${e.scopePath}:${String(e.lineRange.startLine)}-${String(e.lineRange.endLine)}`}),(0,n.jsx)(aU,{score:e.score})]})}function aV(e){let t=new Set,n=[];for(let a of e)t.has(a.stableId)||(t.add(a.stableId),n.push(a));return n}function aH({total:e,expanded:t,onToggle:a}){return e<=8?null:(0,n.jsx)("button",{type:"button",className:"grounded-citations-more","aria-expanded":t,onClick:a,children:t?"Show fewer sources":`Show all ${String(e)} sources`})}function aY({citations:e}){let[t,l]=(0,a.useState)(!1);if(0===e.length)return null;let i=aV([...e].sort((e,t)=>t.score-e.score)),r=t?i:i.slice(0,8);return(0,n.jsxs)("div",{className:"grounded-citations-wrap",children:[(0,n.jsx)("span",{className:"grounded-citations-label",children:"Evidence"}),(0,n.jsx)("ul",{className:"grounded-citations","aria-label":"Evidence citations",children:r.map(e=>(0,n.jsx)("li",{className:"grounded-citations-item",children:(0,n.jsx)(aW,{citation:e})},e.stableId))}),(0,n.jsx)(aH,{total:i.length,expanded:t,onToggle:()=>{l(e=>!e)}})]})}function aG({citations:e}){let[t,l]=(0,a.useState)(!1);if(0===e.length)return null;let i=aV([...e].sort((e,t)=>t.score-e.score)),r=t?i:i.slice(0,8);return(0,n.jsxs)("div",{className:"grounded-citations-wrap",children:[(0,n.jsx)("span",{className:"grounded-citations-label",children:"Knowledge citations"}),(0,n.jsx)("ul",{className:"grounded-citations","aria-label":"Knowledge citations",children:r.map(e=>(0,n.jsx)("li",{className:"grounded-citations-item",children:(0,n.jsxs)("span",{className:"grounded-citation",title:void 0===e.source?`${e.label} — relevance ${e.score.toFixed(2)}`:`${e.source} \xb7 ${e.label} — relevance ${e.score.toFixed(2)}`,children:[(0,n.jsx)("span",{children:void 0===e.source?`${e.marker} ${e.label}`:`${e.marker} ${e.source} \xb7 ${e.label}`}),(0,n.jsx)(aU,{score:e.score})]})},e.stableId))}),(0,n.jsx)(aH,{total:i.length,expanded:t,onToggle:()=>{l(e=>!e)}})]})}function aJ({markers:e}){if(0===e.length)return null;let t=Array.from(new Set(e.map(e=>aK(e.kind)))).join(", ");return(0,n.jsxs)("div",{className:"grounded-uncertainty",role:"note",children:[(0,n.jsx)("div",{children:`Uncertainty (${String(e.length)} markers — ${t})`}),(0,n.jsx)("ul",{className:"grounded-uncertainty-list",children:e.map((e,t)=>(0,n.jsx)("li",{children:`${aK(e.kind)}: ${e.claim}`},`${e.kind}-${String(t)}`))})]})}function aX({omittedCount:e,omittedCounts:t}){if(e<=0)return null;let a=Object.entries(t).filter(([,e])=>e>0).sort(([e],[t])=>e<t?-1:+(e>t)).map(([e,t])=>`${aK(e)}: ${String(t)}`).join(", "),l=a.length>0?` (${a})`:"";return(0,n.jsx)("div",{className:"grounded-meta",children:`Not used: ${String(e)} excerpt${1===e?"":"s"}${l}`})}let aQ=[{reason:"size-exceeded",label:"larger than 2 MB"},{reason:"binary",label:"binary or an unsupported format"},{reason:"tool-unavailable",label:"unreadable"},{reason:"unsupported-format",label:"an unsupported document format"},{reason:"no-text-layer",label:"a scanned document with no text layer"},{reason:"malformed-document",label:"a malformed document"},{reason:"encrypted-document",label:"a password-protected document"}];function aZ({omittedCounts:e}){let t=aQ.map(({reason:t,label:n})=>({label:n,count:e[t]})).filter(e=>e.count>0),a=t.reduce((e,t)=>e+t.count,0);if(a<=0)return null;let l=t.map(e=>`${String(e.count)} ${e.label}`).join(", "),i=e.binary>0||e["unsupported-format"]>0||e["no-text-layer"]>0||e["malformed-document"]>0||e["encrypted-document"]>0;return(0,n.jsxs)("div",{className:"grounded-coverage-notice",role:"note",children:[(0,n.jsx)("span",{className:"grounded-coverage-notice-title",children:"Partial coverage"}),(0,n.jsx)("span",{children:`This answer reflects only the searchable files in the connected scope — ${String(a)} ${1===a?"file":"files"} ${1===a?"was":"were"} not searched (${l}). It does not cover the entire folder.`}),i?(0,n.jsx)("span",{children:"Repository Search reads text, code, and small DOCX, XLSX, and text-layer PDF documents. Larger, scanned, encrypted, or other document formats remain available through Local Knowledge."}):null]})}function a0({runId:e,runIds:t}){let a=Array.from(new Set([...void 0===e?[]:[e],...t??[]]));return 0===a.length?null:(0,n.jsx)("div",{className:"grounded-meta",children:a.map((e,t)=>(0,n.jsxs)("a",{className:"sm-link",href:`/api/evidence/${encodeURIComponent(e)}`,target:"_blank",rel:"noopener noreferrer",children:[1===a.length?"View connected-context audit evidence":`View connected-context audit evidence ${String(t+1)}`," ",(0,n.jsx)("span",{className:"sr-only",children:"(opens in new tab)"})]},e))})}function a1({contextPack:e}){return(0,n.jsxs)("section",{className:"grounded-context-pack","aria-label":"Knowledge scope summary",children:[(0,n.jsx)("div",{className:"grounded-context-pack-headline",children:`Knowledge scope: ${e.scopeLabel}`}),(0,n.jsxs)("dl",{className:"grounded-context-pack-dl",children:[(0,n.jsx)(aB,{label:"Mode",value:aK(e.scopeKind)}),(0,n.jsx)(aB,{label:"Capsules",value:String(e.capsuleCount)}),(0,n.jsx)(aB,{label:"Sources",value:String(e.sourceCount)}),(0,n.jsx)(aB,{label:"Citations",value:String(e.citationCount)}),(0,n.jsx)(aB,{label:"Context budget",value:`${String(e.referencesUsed)} / ${String(e.referenceBudget)} references`})]})]})}function a2({contextPack:e}){return(0,n.jsxs)("section",{className:"grounded-context-pack","aria-label":"Hybrid source summary",children:[(0,n.jsx)("div",{className:"grounded-context-pack-headline",children:`Hybrid: ${String(e.folderSourceCount)} folder source${1===e.folderSourceCount?"":"s"} + ${String(e.connectorSourceCount)} connector source${1===e.connectorSourceCount?"":"s"}`}),(0,n.jsx)(a_,{contextPack:e.folder}),(0,n.jsx)(a1,{contextPack:e.knowledge})]})}function a4({answer:e,busy:t}){return void 0===e?t?(0,n.jsx)("div",{className:"grounded-meta",role:"status","aria-live":"polite","aria-busy":"true",children:"Searching connected sources and asking Keiko…"}):null:"local-knowledge"===e.groundingKind?(0,n.jsxs)("div",{className:"grounded-answer",children:[(0,n.jsx)(aG,{citations:e.citations}),(0,n.jsx)(aJ,{markers:e.uncertainty}),(0,n.jsx)(a1,{contextPack:e.contextPack})]}):"hybrid"===e.groundingKind?(0,n.jsxs)("div",{className:"grounded-answer",children:[(0,n.jsx)(aZ,{omittedCounts:e.contextPack.folder.omittedCounts}),(0,n.jsx)(aY,{citations:e.citations}),(0,n.jsx)(aG,{citations:e.knowledgeCitations}),(0,n.jsx)(aJ,{markers:e.uncertainty}),(0,n.jsx)(aX,{omittedCount:e.omittedCount,omittedCounts:e.contextPack.folder.omittedCounts}),(0,n.jsx)(a0,{runId:e.evidenceRunId,runIds:e.evidenceRunIds}),(0,n.jsx)(a2,{contextPack:e.contextPack})]}):(0,n.jsxs)("div",{className:"grounded-answer",children:[(0,n.jsx)(aZ,{omittedCounts:e.contextPack.omittedCounts}),(0,n.jsx)(aY,{citations:e.citations}),(0,n.jsx)(aJ,{markers:e.uncertainty}),(0,n.jsx)(aX,{omittedCount:e.omittedCount,omittedCounts:e.contextPack.omittedCounts}),(0,n.jsx)(a0,{runId:e.evidenceRunId,runIds:e.evidenceRunIds}),(0,n.jsx)(a_,{contextPack:e.contextPack})]})}function a3({label:e,disabled:t=!1,onStepUp:a,onStepDown:l}){let i=`Increase ${e}`,r=`Decrease ${e}`;return(0,n.jsxs)("span",{className:"number-control-stepper",children:[(0,n.jsx)("button",{type:"button",className:"number-control-stepper-button number-control-stepper-up","aria-label":i,disabled:t,onPointerDown:e=>{e.preventDefault()},onClick:e=>{e.stopPropagation(),a()}}),(0,n.jsx)("button",{type:"button",className:"number-control-stepper-button number-control-stepper-down","aria-label":r,disabled:t,onPointerDown:e=>{e.preventDefault()},onClick:e=>{e.stopPropagation(),l()}})]})}var a6=a;let a5=["<script","</script","<iframe","</iframe","<object","</object","<embed","</embed","<style","</style","<svg","</svg","<form","</form","<meta","<link","<base"],a8=[" ","\n"," ","'",'"'];function a7(e){let t=function(e){let t=e.toLowerCase().replaceAll("\0",""),n="";for(let e=0;e<t.length;e++){let a=t[e]??"";if("<"===a){for(n+="<";e+1<t.length&&(" "===t[e+1]||" "===t[e+1]||"\n"===t[e+1]||"\r"===t[e+1]);)e++;continue}n+=a}return n}(e);for(let e of a5)if(t.includes(e))return!0;let n=0;for(;n<t.length-4;){let e=t[n];if(a8.includes(e)&&"o"===t[n+1]&&"n"===t[n+2]){let e=n+3;for(;e<t.length&&/[a-z]/.test(t[e]??"");)e++;if(e<t.length&&"="===t[e])return!0}n++}return!1}function a9(e,t,n,a){a>n&&e.push({kind:"text",text:t.slice(n,a)})}function le(e){return void 0!==e&&/[A-Za-z0-9]/.test(e)}let lt=new Set([" "," ","\n","<",">",'"']),ln=new Set([".",",",")","]","!","?"]);function la(e,t=0){if(t>=16)return e.length>0?[{kind:"text",text:e}]:[];let n=[],a=0,l=0;for(;a<e.length;){let i=function(e,t,n,a){if("`"!==t[n])return -1;let l=t.indexOf("`",n+1);return -1===l?-1:(a9(e,t,a,n),e.push({kind:"inline-code",text:t.slice(n+1,l)}),l+1)}(n,e,a,l);if(-1!==i||-1!==(i=function(e,t,n,a,l){let i=t[n],r=t[n+1];if(n+1>=t.length||("*"!==i||"*"!==r)&&("_"!==i||"_"!==r))return -1;let s=t.indexOf(i+r,n+2);if(-1===s)return -1;a9(e,t,a,n);let o=t.slice(n+2,s);return e.push({kind:"strong",children:la(o,l+1)}),s+2}(n,e,a,l,t))||-1!==(i=function(e,t,n,a,l){let i=t[n];if("*"!==i&&"_"!==i||"_"===i&&le(t[n-1])&&le(t[n+1])||t[n+1]===i||n>0&&t[n-1]===i)return -1;let r=function(e,t,n){for(let a=n;a<e.length;a++)if(e[a]===t&&e[a-1]!==t&&(a+1>=e.length||e[a+1]!==t))return a;return -1}(t,i,n+1);return -1===r||"_"===i&&le(t[r-1])&&le(t[r+1])?-1:(a9(e,t,a,n),e.push({kind:"em",children:la(t.slice(n+1,r),l+1)}),r+1)}(n,e,a,l,t))||-1!==(i=function(e,t,n,a){let l;if("["!==t[n])return -1;let i=t.indexOf("]",n+1);if(-1===i||"("!==t[i+1])return -1;let r=t.indexOf(")",i+2);if(-1===r)return -1;let s=t.slice(n+1,i),o=t.slice(i+2,r);return a9(e,t,a,n),((l=o.trim().toLowerCase()).startsWith("http://")||l.startsWith("https://"))&&!a7(s)&&!a7(o)?e.push({kind:"link",text:s,href:o}):e.push({kind:"text",text:`[${s}](${o})`}),r+1}(n,e,a,l))||-1!==(i=function(e,t,n,a){if("h"!==t[n])return -1;let l="https://"===t.slice(n,n+8),i="http://"===t.slice(n,n+7);if(!l&&!i)return -1;let r=function(e,t){let n=t;for(;n<e.length&&!lt.has(e[n]??"");)n++;for(;n>t&&ln.has(e[n-1]??"");)n--;return n}(t,n);if(r-n<=(l?8:7))return -1;let s=t.slice(n,r);return a9(e,t,a,n),e.push({kind:"link",text:s,href:s}),r}(n,e,a,l))){l=i,a=i;continue}a++}return a9(n,e,l,e.length),n}function ll(e){let t=e.trim(),n=t.startsWith(":"),a=t.endsWith(":");return n&&a?"center":a?"right":n?"left":void 0}function li(e){let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|")}function lr(e){let t=/^( *)([*+\-]) (.*)$/.exec(e);return t?{match:!0,indent:t[1]?.length??0,text:t[3]??""}:{match:!1}}function ls(e){let t=/^( *)\d+\. (.*)$/.exec(e);return t?{match:!0,indent:t[1]?.length??0,text:t[2]??""}:{match:!1}}function lo(e){return e.includes("|")}function lc(e){let t=e.trim();return/^(-{3,}|\*{3,}|_{3,})$/.test(t)}function ld(e,t){let n=[],a=t?ls:lr;for(;e.i<e.lines.length;){let t=e.lines[e.i]??"",l=a(t);if(l.match)n.push({text:l.text,indent:l.indent}),e.i++;else if(""===t.trim())break;else break}return function e(t,n,a){let l=n?"ol":"ul",i=[],r=0;for(;r<t.length;){let l=t[r];if(void 0===l){r++;continue}let s=l.indent,o=[];for(r++;r<t.length;){let e=t[r];if(void 0===e||e.indent<=s)break;o.push(e),r++}let c=[...la(l.text)];o.length>0&&a<16?c.push(e(o,n,a+1)):o.length>0&&c.push({kind:"text",text:o.map(e=>e.text).join("\n")}),i.push({kind:"li",children:c})}return{kind:l,children:i}}(n,t,e.depth)}function lu({text:e}){let[t,a]=(0,a6.useState)(!1),[l,i]=(0,a6.useState)(""),r=(0,a6.useCallback)(()=>{"u"<typeof navigator||navigator.clipboard?.writeText===void 0?i("Copy unavailable: the clipboard requires a secure (HTTPS) connection."):navigator.clipboard.writeText(e).then(()=>{a(!0),i("Code copied"),setTimeout(()=>{a(!1),i("")},1500)},()=>{})},[e]);return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",className:"sm-code-copy","aria-label":t?"Copied":"Copy code block",title:t?"Copied":"Copy code block","data-copied":t?"true":"false",onClick:r,children:t?"Copied":"Copy"}),(0,n.jsx)("span",{role:"status",className:"sr-only",children:l})]})}let lp={1:"h3",2:"h4",3:"h5",4:"h6",5:"h6",6:"h6"},lm={1:"sm-h sm-h1",2:"sm-h sm-h2",3:"sm-h sm-h3",4:"sm-h sm-h4",5:"sm-h sm-h5",6:"sm-h sm-h6"};function lh(e,t){return void 0===e.children?null:e.children.map((e,n)=>lf(e,t+"-"+String(n)))}function lf(e,t){let a=function(e,t){switch(e.kind){case"paragraph":return(0,n.jsx)("p",{className:"sm-p",children:lh(e,t)},t);case"heading":{let a=e.level??1,l=lp[a],i=lm[a];return(0,n.jsx)(l,{className:i,children:lh(e,t)},t)}case"blockquote":return(0,n.jsx)("blockquote",{className:"sm-blockquote",children:lh(e,t)},t);case"hr":return(0,n.jsx)("hr",{className:"sm-hr"},t);case"code-block":{let a=e.language,l=e.text??"",i=void 0!==a?`lang-${a}`:void 0;return(0,n.jsxs)("div",{className:"sm-code-block-frame",children:[(0,n.jsxs)("div",{className:"sm-code-block-header",children:[(0,n.jsx)("span",{className:"sm-code-lang",children:a??"text"}),(0,n.jsx)(lu,{text:l})]}),(0,n.jsx)("pre",{className:"sm-pre",children:(0,n.jsx)("code",{className:i,children:l})})]},t)}default:return null}}(e,t);if(null!==a)return a;let l=function(e,t){switch(e.kind){case"ul":return(0,n.jsx)("ul",{className:"sm-ul",children:lh(e,t)},t);case"ol":return(0,n.jsx)("ol",{className:"sm-ol",children:lh(e,t)},t);case"li":return(0,n.jsx)("li",{className:"sm-li",children:lh(e,t)},t);default:return null}}(e,t);if(null!==l)return l;let i=function(e,t){let a=void 0!==e.align?{textAlign:e.align}:void 0;switch(e.kind){case"table":return(0,n.jsx)("div",{className:"sm-table-wrapper",children:(0,n.jsx)("table",{className:"sm-table",children:lh(e,t)})},t);case"thead":return(0,n.jsx)("thead",{children:lh(e,t)},t);case"tbody":return(0,n.jsx)("tbody",{children:lh(e,t)},t);case"tr":return(0,n.jsx)("tr",{children:lh(e,t)},t);case"th":return(0,n.jsx)("th",{style:a,children:lh(e,t)},t);case"td":return(0,n.jsx)("td",{style:a,children:lh(e,t)},t);default:return null}}(e,t);if(null!==i)return i;let r=function(e,t){switch(e.kind){case"text":return(0,n.jsx)("span",{children:e.text},t);case"inline-code":return(0,n.jsx)("code",{className:"sm-inline-code",children:e.text},t);case"link":return(0,n.jsxs)("a",{href:e.href,className:"sm-link",rel:"noopener noreferrer",target:"_blank",children:[e.text,(0,n.jsx)("span",{className:"sr-only",children:" (opens in new tab)"})]},t);case"strong":return(0,n.jsx)("strong",{children:lh(e,t)},t);case"em":return(0,n.jsx)("em",{children:lh(e,t)},t);default:return null}}(e,t);return null!==r?r:null}function lg({source:e}){let t=function e(t,n){let a=[],l={lines:t.split("\n"),i:0,depth:n};for(;l.i<l.lines.length;)!function(t,n){let a=t.lines[t.i]??"";if(""===a.trim())return t.i++;if(function(e,t,n){let a=/^(`{3,}|~{3,})(\S*)/.exec(t.trim());if(null===a)return!1;let l=a[1]??"```",i=a[2],r=void 0!==i&&i.length>0?i:void 0;return n.push(function(e,t,n){let a=[];for(e.i++;e.i<e.lines.length;){let n=e.lines[e.i]??"",l=/^(`{3,}|~{3,})\s*$/.exec(n.trim());if(null!==l){let n=l[1]??"";if(n.startsWith(t[0]??"")&&n.length>=t.length){e.i++;break}}a.push(n),e.i++}let l={kind:"code-block",text:a.join("\n")};return void 0!==n?{...l,language:n}:l}(e,l,r)),!0}(t,a,n)||function(e,t,n){let a=/^(#{1,6}) (.+)$/.exec(t.trim());if(null===a)return!1;let l=Math.min((a[1]??"").length,6),i=a[2]??"";return n.push({kind:"heading",level:l,children:la(i)}),e.i++,!0}(t,a,n))return;if(lc(a)){n.push({kind:"hr"}),t.i++;return}if(a.trimStart().startsWith("> ")||">"===a.trim())return n.push(function(t){let n=[];for(;t.i<t.lines.length;){let e=t.lines[t.i]??"";if(e.trimStart().startsWith("> ")||">"===e.trim())n.push(e.replace(/^( *)> ?/,"")),t.i++;else break}let a=n.join("\n");return t.depth>=16?{kind:"blockquote",children:[{kind:"paragraph",children:[{kind:"text",text:a}]}]}:{kind:"blockquote",children:[...e(a,t.depth+1)]}}(t));if(lo(a.trim())&&function(e){if(0===e.length)return!1;for(let t of e){let e=t.trim().replace(/^:/,"").replace(/:$/,"");if(!/^-+$/.test(e))return!1}return!0}(li(t.lines[t.i+1]??""))&&(n.push(function(e,t){let n,a;e.i++;let l=e.lines[e.i]??"",i=[];for(e.i++;e.i<e.lines.length;){let t=e.lines[e.i]??"";if(""===t.trim()||!lo(t.trim()))break;i.push(t),e.i++}return n=li(t),a=li(l).map(ll),{kind:"table",children:[{kind:"thead",children:[{kind:"tr",children:n.map((e,t)=>{var n;let l;return n=a[t],l={kind:"th",children:la(e.trim())},void 0!==n?{...l,align:n}:l})}]},{kind:"tbody",children:i.map(e=>({kind:"tr",children:li(e).map((e,t)=>{var n;let l;return n=a[t],l={kind:"td",children:la(e.trim())},void 0!==n?{...l,align:n}:l})}))}]}}(t,a)),1)||(lr(a).match?(n.push(ld(t,!1)),!0):!!ls(a).match&&(n.push(ld(t,!0)),!0)))return;let l=function(e){let t=[];for(;e.i<e.lines.length;){let n=e.lines[e.i]??"";if(function(e){let t=e.trim();return!!(""===t||/^#{1,6} /.test(t)||e.trimStart().startsWith("> ")||/^(`{3,}|~{3,})/.test(t))||!!lr(e).match||!!ls(e).match||lc(e)}(n))break;t.push(n),e.i++}return 0===t.length?null:{kind:"paragraph",children:la(t.join(" "))}}(t);null!==l&&n.push(l)}(l,a);return a}(e,0);return(0,n.jsx)("div",{className:"sm-root",children:t.map((e,t)=>lf(e,String(t)))})}class lv extends a6.Component{state={failed:!1};static getDerivedStateFromError(){return{failed:!0}}render(){return this.state.failed?(0,n.jsx)("div",{className:"sm-root sm-fallback","data-markdown-fallback":"true",children:this.props.source}):(0,n.jsx)(lg,{source:this.props.source})}}function lb({attachment:e,onRemove:t}){var a;let l=`Remove attachment ${e.name}`,i=function(e,t=32){if(e.length<=t)return e;let n=e.lastIndexOf(".");if(n>0&&e.length-n<=8){let a=e.slice(n);return`${e.slice(0,t-a.length-1)}…${a}`}return`${e.slice(0,t-1)}…`}(e.name);return(0,n.jsxs)("div",{className:"attach-chip",role:"listitem",children:["image"===e.kind&&void 0!==e.previewDataUrl?(0,n.jsx)("img",{src:e.previewDataUrl,alt:"",className:"attach-chip-thumb",width:40,height:40}):(0,n.jsx)("span",{className:"attach-chip-icon","aria-hidden":"true",children:(0,n.jsx)(j.Icons.file,{size:16})}),(0,n.jsx)("span",{className:"attach-chip-name",title:e.name,children:i}),(0,n.jsx)("span",{className:"attach-chip-size",children:(a=e.sizeBytes)<1024?`${String(a)} B`:a<1048576?`${(a/1024).toFixed(1)} KB`:`${(a/1048576).toFixed(1)} MiB`}),(0,n.jsx)("button",{type:"button",className:"attach-chip-remove","aria-label":l,onClick:()=>t(e.id),children:(0,n.jsx)(j.Icons.close,{size:12})})]})}function lx({attachments:e,onRemove:t}){return 0===e.length?null:(0,n.jsx)("div",{className:"attach-strip",role:"list","aria-label":"Pending attachments",children:e.map(e=>(0,n.jsx)(lb,{attachment:e,onRemove:t},e.id))})}function ly({enabled:e,onFiles:t}){let[l,i]=(0,a.useState)(!1),[r,s]=(0,a.useState)(!1);(0,a.useEffect)(()=>{if(!e)return;let t=0,n=e=>{Array.from(e.dataTransfer?.types??[]).includes("Files")&&(t+=1,s(!0))},a=()=>{0===(t=Math.max(0,t-1))&&s(!1)},l=()=>{t=0,s(!1)};return window.addEventListener("dragenter",n),window.addEventListener("dragleave",a),window.addEventListener("drop",l),window.addEventListener("dragend",l),()=>{window.removeEventListener("dragenter",n),window.removeEventListener("dragleave",a),window.removeEventListener("drop",l),window.removeEventListener("dragend",l)}},[e]);let o=(0,a.useCallback)(t=>{e&&(t.preventDefault(),i(!0))},[e]),c=(0,a.useCallback)(()=>{i(!1)},[]),d=(0,a.useCallback)(n=>{if(n.preventDefault(),i(!1),!e)return;let a=Array.from(n.dataTransfer.files);a.length>0&&t(a)},[e,t]);return e?(0,n.jsx)("div",{className:"attach-drop-zone","data-dragover":l?"true":void 0,"data-active":r?"true":"false","aria-hidden":"true",onDragOver:o,onDragLeave:c,onDrop:d,children:(0,n.jsx)("span",{className:"attach-drop-hint",children:"Drop files here to attach"})}):null}let lw="cmp-attach-disabled-hint";function lj({model:e,onFiles:t,anyModelSupportsAttachments:l=!0}){let i=(0,a.useRef)(null),r=void 0!==e&&(e.supportsImageInput||e.supportsDocumentInput),s=function(e){if(void 0===e)return"";let t=[];return e.supportsImageInput&&t.push("image/*"),e.supportsDocumentInput&&t.push(".pdf,.txt,.md,.csv,.json,.yaml,.yml"),t.join(",")}(e),o=(0,a.useCallback)(()=>{r&&i.current?.click()},[r]),c=(0,a.useCallback)(()=>{let e=Array.from(i.current?.files??[]);e.length>0&&(t(e),null!==i.current&&(i.current.value=""))},[t]);return(0,n.jsxs)(n.Fragment,{children:[r?null:(0,n.jsx)("span",{id:lw,className:"sr-only",children:l?"The selected model does not support image or document input. Choose a different model to attach files.":"The selected model does not support image or document input. No configured model currently supports attachments."}),(0,n.jsx)("input",{ref:i,type:"file",multiple:!0,accept:s,className:"sr-only",tabIndex:-1,"aria-hidden":"true",onChange:c}),(0,n.jsx)("button",{type:"button",className:"cmp-icon cmp-tip-start","aria-label":"Attach file","aria-disabled":r?void 0:"true","aria-describedby":r?void 0:lw,"data-tip":r?"Attach file":"Attachments not supported",onClick:o,children:(0,n.jsx)(j.Icons.files,{size:16})})]})}function lk({reason:e,mimeType:t}){return void 0===e?null:(0,n.jsx)("div",{role:"alert",className:"attach-rejection-alert",children:function(e,t){switch(e){case"text-only-model":return"The selected model can't accept this attachment type. Choose a model that supports images or documents.";case"unsupported-type":return`Unsupported file type${void 0!==t&&t.length>0?`: ${t}`:""}. Supported types: images (image/*), PDF, plain text, markdown, JSON, YAML.`;case"oversized":return"File is larger than the 8 MiB limit. Choose a smaller file or summarize the content as text.";case"empty":return"Empty file. Add a file with content to attach."}}(e,t)})}function lN({documents:e}){if(0===e.length)return null;let t=e.some(e=>e.truncated);return(0,n.jsxs)("div",{role:"note",className:"sent-docs-note","aria-label":"Documents included as context",children:[(0,n.jsx)("span",{className:"sent-docs-note-label",children:1===e.length?"Document included as context:":"Documents included as context:"}),(0,n.jsx)("ul",{className:"sent-docs-note-list",children:e.map(e=>(0,n.jsxs)("li",{className:"sent-docs-note-item",children:[e.displayName,e.truncated?(0,n.jsx)("span",{className:"sent-docs-note-trunc",children:" (truncated)"}):null]},e.id))}),t?(0,n.jsx)("span",{className:"sent-docs-note-hint",children:"Some document text was truncated to fit the context limit."}):null]})}function lS({selectedModel:e,compact:t=!1,launch:l}){let[i,r]=(0,a.useState)(!1),s=(0,a.useRef)(null);return void 0!==e&&t_(e)?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("button",{ref:s,type:"button",className:`cmp-mode${t?" cmp-mode-compact":" cmp-pill-standard"} ui-tip`,"aria-label":"Launch workflow","aria-haspopup":"dialog","data-tip":t?"Launch workflow":void 0,onClick:()=>r(!0),children:[(0,n.jsx)(j.Icons.spark,{size:t?16:14,style:{color:"var(--accent)"}}),t?(0,n.jsx)("span",{className:"sr-only",children:"Launch workflow"}):"Launch workflow",t?null:(0,n.jsx)(j.Icons.chevron,{size:12})]}),i?(0,n.jsx)(lI,{modelId:e.id,launch:l,onClose:()=>{r(!1),s.current?.focus()}}):null]}):null}function lC(e){return Array.from(e.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'))}function lI({modelId:e,launch:t,onClose:l}){let i=(0,a.useId)(),r=(0,a.useId)(),[s,o]=(0,a.useState)(),[c,d]=(0,a.useState)(""),[u,p]=(0,a.useState)(!1),[m,h]=(0,a.useState)(),f=(0,a.useRef)(null),g=void 0===s?void 0:nd(s);async function v(){if(void 0===g||0===c.trim().length)return;p(!0),h(void 0);let n=await t({workflowId:g.workflowId,modelId:e,text:c});(p(!1),n.ok)?l():h(function(e){if(void 0!==e.message&&e.message.length>0)return e.message;switch(e.reason){case"not-workflow-eligible":return"The selected model does not support workflow runs. Pick a model with tool calling and structured output.";case"unknown-workflow":return"That workflow is no longer available.";case"missing-chat":return"Open or create a chat first, then launch the workflow.";case"missing-input":return"Provide an input before launching the workflow.";case"request-failed":return"Could not launch the workflow. Try again, or check the gateway logs.";default:return"Could not launch the workflow."}}(n))}(0,a.useEffect)(()=>{f.current?.focus()},[s]),(0,a.useEffect)(()=>{function e(e){if("Escape"===e.key)return void l();if("Tab"!==e.key)return;let t=f.current;if(null===t)return;let n=lC(t);if(0===n.length){e.preventDefault(),t.focus();return}let a=n[0],i=n[n.length-1],r=document.activeElement;e.shiftKey&&(r===a||r===t)?(e.preventDefault(),i?.focus()):e.shiftKey||r!==i||(e.preventDefault(),a?.focus())}return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[l]);let b=(0,n.jsx)("div",{ref:f,role:"dialog","aria-modal":"true","aria-labelledby":i,tabIndex:-1,className:"wf-dialog-overlay",children:(0,n.jsxs)("div",{className:"wf-dialog",children:[(0,n.jsx)("h2",{id:i,className:"wf-dialog-title",children:"Launch workflow"}),void 0===g?(0,n.jsx)("ul",{className:"wf-dialog-list","aria-label":"Available workflows",children:nc.map(e=>(0,n.jsx)("li",{children:(0,n.jsxs)("button",{type:"button",className:"wf-dialog-choice",onClick:()=>o(e.workflowId),children:[(0,n.jsx)("span",{className:"wf-dialog-choice-label",children:e.label}),(0,n.jsx)("span",{className:"wf-dialog-choice-desc",children:e.description})]})},e.workflowId))}):(0,n.jsxs)("div",{className:"wf-dialog-form",children:[(0,n.jsx)("p",{className:"wf-dialog-form-desc",children:g.description}),(0,n.jsx)("label",{className:"wf-dialog-field",htmlFor:r,children:g.prompt}),(0,n.jsx)("textarea",{id:r,className:"wf-dialog-input mono",rows:3,placeholder:g.placeholder,value:c,onChange:e=>d(e.target.value)}),void 0!==m?(0,n.jsx)("div",{role:"alert",className:"wf-dialog-error",children:m}):null,(0,n.jsxs)("div",{className:"wf-dialog-actions",children:[(0,n.jsx)("button",{type:"button",className:"wf-dialog-cancel",onClick:()=>o(void 0),children:"Back"}),(0,n.jsx)("button",{type:"button",className:"wf-dialog-launch",disabled:u||0===c.trim().length,onClick:()=>{v()},children:u?"Launching…":"Launch"})]})]}),(0,n.jsx)("button",{type:"button",className:"wf-dialog-close","aria-label":"Close launch workflow",onClick:l,children:(0,n.jsx)(j.Icons.close,{size:14})})]})});return"u"<typeof document?b:(0,tP.createPortal)(b,document.body)}let lE=[{workflowKind:"unit-test-generation",label:"Generate unit tests",description:"Use the grounded evidence as read-only context and propose in-scope test changes."},{workflowKind:"bug-investigation",label:"Investigate bug",description:"Investigate a bug against the grounded evidence and keep writes inside approved paths."},{workflowKind:"verification",label:"Run verification",description:"Run verification against the grounded workspace context without granting write access."}],lR=["verify","lint","typecheck","tests","manual"];function l$(e){return e.split(/\r?\n|,/).map(e=>e.trim()).filter(e=>e.length>0)}function lA({answer:e,modelId:t,busy:l,launch:i}){let[r,s]=(0,a.useState)(!1),o=(0,a.useRef)(null),c=(0,a.useId)();if(void 0===e||"connected-context"!==e.groundingKind||void 0===t||e.citations.some(e=>void 0!==e.source))return null;let d=!0===l;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("button",{ref:o,type:"button",className:"cmp-mode ui-tip","data-tip":"Launch grounded workflow","aria-haspopup":"dialog","aria-disabled":d||void 0,"aria-describedby":d?c:void 0,onClick:()=>{d||s(!0)},children:[(0,n.jsx)(j.Icons.spark,{size:14,style:{color:"var(--accent)"}})," Launch grounded workflow",(0,n.jsx)(j.Icons.chevron,{size:12})]}),d?(0,n.jsx)("span",{className:"sr-only",id:c,children:"A run is in progress. Wait for it to complete before launching another grounded workflow."}):null,r?(0,n.jsx)(lT,{answer:e,modelId:t,launch:i,onClose:()=>{s(!1),o.current?.focus()}}):null]})}function lT({answer:e,modelId:t,launch:l,onClose:i}){let r=(0,a.useId)(),s=(0,a.useRef)(null),[o,c]=(0,a.useState)(),[d,u]=(0,a.useState)("file"),[p,m]=(0,a.useState)(""),[h,f]=(0,a.useState)(""),[g,v]=(0,a.useState)(""),[b,x]=(0,a.useState)(""),[y,w]=(0,a.useState)(""),[k,N]=(0,a.useState)(""),[S,C]=(0,a.useState)([]),[I,E]=(0,a.useState)(!1),[R,$]=(0,a.useState)();async function A(){if(void 0===o)return;let n=function(e,t,n,a,l,i){if("unit-test-generation"===e){if("changedFiles"===t){let e=l$(n);return 0===e.length?{ok:!1,message:"Provide at least one changed file."}:{ok:!0,input:{target:{kind:"changedFiles",filePaths:e}}}}let e=n.trim();return 0===e.length?{ok:!1,message:"module"===t?"Provide a module directory.":"Provide a target file."}:"module"===t?{ok:!0,input:{target:{kind:"module",moduleDir:e}}}:{ok:!0,input:{target:{kind:"file",filePath:e}}}}if("bug-investigation"===e){let e=l$(l),t=a.trim();return 0===t.length&&0===e.length?{ok:!1,message:"Provide at least a bug description or one suspected target file."}:{ok:!0,input:{report:{...0===t.length?{}:{description:t},...0===e.length?{}:{targetFiles:e}}}}}let r=l$(i);return{ok:!0,input:0===r.length?{}:{targetFiles:r}}}(o,d,p,h,g,b);if(!n.ok)return void $(n.message);if(0===S.length)return void $("Select at least one expected check.");E(!0),$(void 0);let a=await l({assistantMessageId:e.assistantMessageId,modelId:t,workflowKind:o,input:n.input,editablePaths:l$(y),expectedChecks:S,unknowns:l$(k)});(E(!1),a.ok)?i():$(function(e){if(e.ok)return"";if(void 0!==e.message&&e.message.length>0)return e.message;switch(e.reason){case"missing-chat":return"Open a chat with the grounded answer you want to hand off.";case"missing-model":return"Pick a model before launching the grounded workflow.";default:return"Could not launch the grounded workflow."}}(a))}(0,a.useEffect)(()=>{s.current?.focus()},[o]),(0,a.useEffect)(()=>{void 0!==o&&C("unit-test-generation"===o?["tests"]:["verify"])},[o]),(0,a.useEffect)(()=>{function e(e){if("Escape"===e.key)return void i();if("Tab"!==e.key)return;let t=s.current;if(null===t)return;let n=lC(t);if(0===n.length){e.preventDefault(),t.focus();return}let a=n[0],l=n[n.length-1],r=document.activeElement;e.shiftKey&&(r===a||r===t)?(e.preventDefault(),l?.focus()):e.shiftKey||r!==l||(e.preventDefault(),a?.focus())}return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[i]);let T=lE.find(e=>e.workflowKind===o),L=(0,n.jsx)("div",{ref:s,role:"dialog","aria-modal":"true","aria-labelledby":r,tabIndex:-1,className:"wf-dialog-overlay",children:(0,n.jsxs)("div",{className:"wf-dialog",children:[(0,n.jsx)("h2",{id:r,className:"wf-dialog-title",children:"Grounded workflow handoff"}),void 0===T?(0,n.jsx)("ul",{className:"wf-dialog-list","aria-label":"Available grounded workflows",children:lE.map(e=>(0,n.jsx)("li",{children:(0,n.jsxs)("button",{type:"button",className:"wf-dialog-choice",onClick:()=>c(e.workflowKind),children:[(0,n.jsx)("span",{className:"wf-dialog-choice-label",children:e.label}),(0,n.jsx)("span",{className:"wf-dialog-choice-desc",children:e.description})]})},e.workflowKind))}):(0,n.jsxs)("div",{className:"wf-dialog-form",children:[(0,n.jsx)("p",{className:"wf-dialog-form-desc",children:T.description}),"unit-test-generation"===o?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"wf-dialog-field",children:[(0,n.jsx)("span",{children:"Target mode"}),(0,n.jsx)(tz,{triggerClassName:"wf-dialog-input mono",value:d,ariaLabel:"Target mode",menuTitle:"Target mode",mono:!0,sections:[{options:[{value:"file",label:"File"},{value:"module",label:"Module"},{value:"changedFiles",label:"Changed files"}]}],onValueChange:e=>u(e)})]}),(0,n.jsxs)("label",{className:"wf-dialog-field",children:["module"===d?"Module directory":"changedFiles"===d?"Changed files (one per line)":"Target file",(0,n.jsx)("textarea",{className:"wf-dialog-input mono",rows:"changedFiles"===d?3:2,value:p,onChange:e=>m(e.target.value),placeholder:"module"===d?"src/components":"changedFiles"===d?"src/a.ts\nsrc/b.ts":"src/example.ts"})]})]}):null,"bug-investigation"===o?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("label",{className:"wf-dialog-field",children:["Bug description",(0,n.jsx)("textarea",{className:"wf-dialog-input mono",rows:3,value:h,onChange:e=>f(e.target.value),placeholder:"Describe the failing behavior or regression."})]}),(0,n.jsxs)("label",{className:"wf-dialog-field",children:["Suspected target files (one per line)",(0,n.jsx)("textarea",{className:"wf-dialog-input mono",rows:2,value:g,onChange:e=>v(e.target.value),placeholder:"src/app.ts\\nsrc/lib/foo.ts"})]})]}):null,"verification"===o?(0,n.jsxs)("label",{className:"wf-dialog-field",children:["Target files (optional, one per line)",(0,n.jsx)("textarea",{className:"wf-dialog-input mono",rows:2,value:b,onChange:e=>x(e.target.value),placeholder:"src/app.ts\\nsrc/lib/foo.ts"})]}):null,(0,n.jsxs)("label",{className:"wf-dialog-field",children:["Editable paths (explicit, workspace-relative, one per line)",(0,n.jsx)("textarea",{className:"wf-dialog-input mono",rows:3,value:y,onChange:e=>w(e.target.value),placeholder:"src/example.test.ts"})]}),(0,n.jsxs)("fieldset",{className:"wf-dialog-field",style:{border:0,padding:0,margin:0},children:[(0,n.jsx)("legend",{children:"Expected checks"}),(0,n.jsx)("div",{className:"wf-dialog-form",style:{gap:8},children:lR.map(e=>(0,n.jsxs)("label",{className:"c-check",children:[(0,n.jsx)("input",{type:"checkbox",checked:S.includes(e),onChange:()=>{C(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])}}),(0,n.jsx)("span",{className:"bx","aria-hidden":"true",children:(0,n.jsx)("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:3,strokeLinecap:"round",strokeLinejoin:"round",children:(0,n.jsx)("path",{d:"M5 12.5 L10 17.5 L19 6.5"})})}),(0,n.jsx)("span",{children:e})]},e))})]}),(0,n.jsxs)("label",{className:"wf-dialog-field",children:["Unknowns (optional, one per line)",(0,n.jsx)("textarea",{className:"wf-dialog-input mono",rows:2,value:k,onChange:e=>N(e.target.value),placeholder:"Need confirmation on public API behavior"})]}),void 0!==R?(0,n.jsx)("div",{role:"alert",className:"wf-dialog-error",children:R}):null,(0,n.jsxs)("div",{className:"wf-dialog-actions",children:[(0,n.jsx)("button",{type:"button",className:"wf-dialog-cancel",onClick:()=>c(void 0),children:"Back"}),(0,n.jsx)("button",{type:"button",className:"wf-dialog-launch",disabled:I,onClick:()=>{A()},children:I?"Launching…":"Launch"})]})]}),(0,n.jsx)("button",{type:"button",className:"wf-dialog-close","aria-label":"Close grounded workflow handoff",onClick:i,children:(0,n.jsx)(j.Icons.close,{size:14})})]})});return"u"<typeof document?L:(0,tP.createPortal)(L,document.body)}function lL(e){return"system"===e.role&&"string"==typeof e.runId}function lP({message:e,onOpenResult:t}){let l=e.workflowStatus??"queued",i=e.workflowId??e.taskType??"workflow",r=void 0===e.runId?"":e.runId.slice(0,8),s=void 0===e.runId?void 0:`/api/evidence/${encodeURIComponent(e.runId)}`,[o,c]=(0,a.useState)(""),d=(0,a.useRef)(l);return(0,a.useEffect)(()=>{d.current!==l&&(d.current=l,c(`Workflow ${i}: ${l}`))},[l,i]),(0,n.jsxs)("article",{className:"run-summary-card","data-testid":"run-summary-card","data-status":l,"aria-label":`Workflow run ${i} — ${l}`,children:[(0,n.jsxs)("header",{className:"run-summary-card-head",children:[(0,n.jsx)(j.Icons.spark,{size:14,style:{color:"var(--accent)"}}),(0,n.jsx)("span",{className:"run-summary-card-workflow mono",children:i}),(0,n.jsx)("span",{className:"run-summary-card-status","data-status":l,children:l})]}),(0,n.jsxs)("div",{className:"run-summary-card-body",children:[(0,n.jsx)("p",{className:"run-summary-card-line",children:e.content}),void 0!==e.shortResult&&e.shortResult.length>0?(0,n.jsx)("p",{className:"run-summary-card-result",children:e.shortResult}):null,void 0!==e.runId?(0,n.jsxs)("p",{className:"run-summary-card-meta mono",children:["run"," ",(0,n.jsx)("span",{className:"run-summary-card-runshort","data-runid":e.runId,title:e.runId,children:r})]}):null,void 0!==e.runId?(0,n.jsxs)("div",{className:"run-summary-card-actions","aria-label":"Workflow result actions",children:[void 0!==t?(0,n.jsx)("button",{type:"button",className:"run-summary-card-action",onClick:()=>t(e),children:"Open result"}):null,void 0!==s?(0,n.jsx)("a",{className:"run-summary-card-action run-summary-card-action-secondary",href:s,target:"_blank",rel:"noreferrer",children:"Evidence"}):null]}):null]}),(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite","data-testid":"run-summary-card-sr",children:o})]})}function lM({on:e,onChange:t,label:a}){return(0,n.jsx)("button",{type:"button",role:"switch","aria-checked":e,"aria-label":a,className:`auto-toggle${e?" on":""}`,onClick:()=>{t(!e)},children:(0,n.jsx)("span",{})})}var lD=e.i(61593);let lq="cmp-no-model-alert",lF="cmp-send-hint",lO="cmp-loading-status",lz="Ask Keiko...",lK=/\s*[[【[]\d+[\]】]]/g;function lB({content:e}){let[t,l]=(0,a.useState)(!1),[i,r]=(0,a.useState)(""),s=(0,a.useCallback)(()=>{"u"<typeof navigator||navigator.clipboard?.writeText===void 0?r("Copy unavailable: the clipboard requires a secure (HTTPS) connection."):navigator.clipboard.writeText(e.replace(lK,"")).then(()=>{l(!0),r("Message copied"),setTimeout(()=>{l(!1),r("")},1500)},()=>{})},[e]);return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",className:"chat-msg-copy ui-tip","aria-label":t?"Copied":"Copy message","data-tip":t?"Copied":"Copy message","data-copied":t?"true":"false",onClick:s,children:t?"Copied":"Copy"}),(0,n.jsx)("span",{role:"status",className:"sr-only",children:i})]})}function l_({message:e,onOpenRunResult:t,streaming:a=!1}){let l,i;if(lL(e))return(0,n.jsx)(lP,{message:e,onOpenResult:t});let r="user"===e.role;return(0,n.jsx)("article",{className:"chat-msg","data-role":e.role,children:(0,n.jsxs)("div",{className:"chat-msg-bubble",children:[r?(0,n.jsx)("div",{className:"chat-msg-role",children:"You"}):(0,n.jsx)(lU,{}),r?e.content:(0,n.jsx)(lv,{source:e.content}),a&&!r?(0,n.jsx)("span",{className:"ai-stream-cursor","aria-hidden":"true"}):null,(0,n.jsxs)("div",{className:"chat-msg-foot",children:[(0,n.jsx)("div",{className:"chat-msg-time",title:new Date(e.timestamp).toLocaleString(),children:(i=(l=new Date(e.timestamp)).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),l.toDateString()===new Date().toDateString()?i:`${l.toLocaleDateString([],{month:"short",day:"numeric"})}, ${i}`)}),r?null:(0,n.jsx)(lB,{content:e.content})]})]})})}function lU({pulsing:e=!1}){return(0,n.jsx)("div",{className:"chat-msg-brand","data-pulsing":e?"true":"false",role:"img","aria-label":"Keiko logo",children:(0,n.jsx)(aE.default,{src:"/assets/keiko-logo.svg",width:22,height:22,alt:"","aria-hidden":"true"})})}function lW(){return(0,n.jsx)("article",{className:"chat-msg","data-role":"assistant",children:(0,n.jsxs)("div",{className:"chat-msg-bubble",children:[(0,n.jsx)(lU,{pulsing:!0}),(0,n.jsxs)("span",{className:"chat-typing",role:"img","aria-label":"Keiko is responding",children:[(0,n.jsx)("i",{}),(0,n.jsx)("i",{}),(0,n.jsx)("i",{})]})]})})}function lV({session:e,ready:t,selectedModelCapability:a,onAttachFiles:l,compact:i=!1,controlsNarrow:r=!1,barCompact:s=!1,workflowCompact:o=!1,budgetExceeded:c}){let{models:d,selectedModel:u,setSelectedModel:p,draft:m,noEligibleModels:h,loading:f,sending:g,cancelSend:v,launchWorkflowFromConversation:b}=e,x=h||c||!t,y=0===m.trim().length,w=h?lq:void 0,k=h?lq:c?aR:f?lO:y?lF:void 0,N=f||h?"":u??"",S=f?"Loading models…":h?"No conversation-eligible model":"Change model";return(0,n.jsxs)("div",{className:`cmp-bar${s?" cmp-bar-compact":""}`,children:[(0,n.jsxs)("div",{className:"cmp-bar-main",children:[(0,n.jsx)(lj,{model:a,onFiles:l,anyModelSupportsAttachments:d.some(e=>e.supportsImageInput||e.supportsDocumentInput)}),(0,n.jsx)(lS,{selectedModel:a,compact:o,launch:b}),(0,n.jsx)("div",{className:`cmp-model mono ui-tip${r?" cmp-model-compact":" cmp-pill-standard"}`,"data-tip":r?S:void 0,children:(0,n.jsx)(tz,{triggerClassName:"cmp-model-select",value:N,ariaLabel:"Models",ariaDescribedBy:w,disabled:f,placeholder:f?"Loading models…":h?"No conversation-eligible model":"Models",leadingVisual:(0,n.jsx)(j.Icons.cube,{size:r?16:13,style:{color:"var(--accent)"}}),menuTitle:"Models",menuClassName:"cmp-model-menu",menuMinWidth:r?118:280,mono:!0,sections:[{options:f?[{value:"",label:"Loading models…",disabled:!0}]:h?[{value:"",label:"No conversation-eligible model",disabled:!0}]:d.filter(e=>"chat"===e.kind).map(e=>({value:e.id,label:e.id}))}],onValueChange:e=>{h||f||p(e)}})}),null]}),k===lF?(0,n.jsx)("span",{id:lF,className:"sr-only",children:"Type a message to send"}):null,g?(0,n.jsx)("button",{type:"button",className:"cmp-send cmp-send-cancel cmp-tip-end","data-on":!0,"aria-label":"Cancel response","data-tip":"Cancel response",onClick:v,children:(0,n.jsx)(j.Icons.close,{size:16})}):(0,n.jsx)("button",{type:x?"button":"submit",className:"cmp-send cmp-tip-end","data-on":!x,"data-tip":h?"No model available":c?"Context too large":f?"Connecting to gateway":"Send message","aria-disabled":x,"aria-describedby":k,"aria-label":"Send message",children:(0,n.jsx)(j.Icons.arrowUp,{size:16})})]})}function lH(){return(0,n.jsx)("div",{id:lq,role:"alert",className:"gw-error cmp-no-model",children:"No conversation-eligible model is configured. Connect a gateway in Settings to enable chat."})}function lY(){return(0,n.jsxs)("div",{id:lO,role:"status",className:"cmp-loading-status",children:[(0,n.jsx)("span",{className:"cmp-loading-dot","aria-hidden":"true"}),"Connecting to your gateway…"]})}function lG({status:e}){let t=function(e){switch(e){case"idle":case"completed":case"failed":return"";case"queued":return"Submitting your message…";case"contacting":return"Contacting model…";case"streaming":return"Receiving response…";case"cancelled":return"Response cancelled."}}(e);return(0,n.jsx)("div",{role:"status","aria-live":"polite","data-send-status":e,className:"cmp-send-status",children:0===t.length?null:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"cmp-loading-dot","aria-hidden":"true"}),t]})})}function lJ({session:e,ready:t,placeholder:l,minimal:i=!1,compact:r=!1,controlsNarrow:s=!1,barCompact:o=!1,workflowCompact:c=!1}){let{draft:d,loading:u,sending:p,sendStatus:m,setDraft:h,sendMessage:f,models:g,selectedModel:v,pendingAttachments:b,addPendingAttachment:x,removePendingAttachment:y,budget:w,clearHistory:j}=e,k=nQ(w),N=(0,a.useRef)(null);(0,a.useEffect)(()=>{let e=N.current;null!==e&&(e.style.height="auto",e.style.height=`${String(Math.min(e.scrollHeight,220))}px`)},[d]);let[S,C]=(0,a.useState)(),[I,E]=(0,a.useState)(),R=g.find(e=>e.id===v),$=void 0!==R&&(R.supportsImageInput||R.supportsDocumentInput),A=(0,a.useCallback)(async e=>{let t,n;for(let a of e){let e=await x(a);e.ok||void 0!==t||(t=e.reason,n=a.type)}C(t),E(n)},[x]);return(0,n.jsxs)("div",{className:`cmp-box${r?" cmp-box-compact":""}`,children:[(0,n.jsxs)("div",{className:"cmp-input-stack",children:[(0,n.jsx)(ly,{enabled:$,onFiles:A}),(0,n.jsx)("textarea",{className:"cmp-input",ref:N,rows:2,value:d,"aria-label":"Chat message",placeholder:l,onChange:e=>h(e.target.value),onKeyDown:e=>{!e.nativeEvent.isComposing&&("Enter"!==e.key||e.shiftKey||(e.preventDefault(),f()))}}),(0,n.jsx)(lx,{attachments:b,onRemove:y}),(0,n.jsx)(lk,{reason:S,mimeType:I}),(0,n.jsx)(lG,{status:m})]}),(0,n.jsxs)("div",{className:"cmp-footer-row",children:[i?null:(0,n.jsx)(aP,{budget:w,onClearHistory:j,disabled:p||u,compact:r}),(0,n.jsx)(lV,{session:e,ready:t,selectedModelCapability:R,onAttachFiles:A,compact:r,controlsNarrow:s,barCompact:o,workflowCompact:c,budgetExceeded:k})]})]})}function lX({minimal:e=!1}){return e?(0,n.jsx)("div",{className:"chatw-empty chatw-empty-minimal",role:"note","aria-label":"Conversation ready",children:(0,n.jsx)("h2",{className:"chatw-empty-headline",children:"How can I help you today?"})}):(0,n.jsx)("div",{className:"chatw-empty",children:(0,n.jsx)("h2",{className:"chatw-empty-headline",children:"How can I help you today?"})})}function lQ(){return(0,n.jsxs)("div",{className:"chatw-empty-no-chat",children:[(0,n.jsx)("div",{className:"chatw-empty-no-chat-icon","aria-hidden":"true",children:(0,n.jsx)(j.Icons.spark,{size:20})}),(0,n.jsx)("p",{className:"chatw-empty-no-chat-label",children:"Pick or start a chat"}),(0,n.jsx)("p",{className:"chatw-empty-no-chat-hint",children:"Select a conversation from the project sidebar, or create a new one to get started."})]})}function lZ(e){return(void 0!==e.connectedScopes?e.connectedScopes.length:+(void 0!==e.connectedScope))+(void 0!==e.localKnowledgeScopes?e.localKnowledgeScopes.length:+(void 0!==e.localKnowledgeScope))}function l0(e){if(lZ(e)>1)return"multi";let t=e.localKnowledgeScopes?.[0]??e.localKnowledgeScope;return t?.kind==="capsule"?`capsule:${t.capsuleId}`:t?.kind==="capsule-set"?`capsule-set:${t.capsuleSetId}`:l2(e)?"files":"none"}function l1(e){return void 0!==e.localKnowledgeScopes?e.localKnowledgeScopes:void 0!==e.localKnowledgeScope?[e.localKnowledgeScope]:[]}function l2(e){return void 0!==e&&(void 0!==e.connectedScope||void 0!==e.connectedScopes&&e.connectedScopes.length>0)}function l4(e){return l2(e)||void 0!==e&&(void 0!==e.localKnowledgeScope||void 0!==e.localKnowledgeScopes&&e.localKnowledgeScopes.length>0)}function l3(e){return nR(e,"Unable to update knowledge scope.")}function l6({chat:e,onChatChanged:t,catalog:l,connected:i}){let{capsules:r,capsuleSets:s,loadError:o}=l,[c,d]=(0,a.useState)(!1),[u,p]=(0,a.useState)(null);async function m(n){d(!0),p(null);try{if("none"===n){let n=lZ(e);if(n>0&&!window.confirm(`This will disconnect ${String(n)} grounding ${1===n?"source":"sources"}. Continue?`))return;let a=await (0,w.updateChat)(e.id,{connectedScopes:null,localKnowledgeScopes:null});t(a.chat);return}if("files"===n){let n=await (0,w.updateChat)(e.id,{localKnowledgeScopes:null});t(n.chat);return}if(n.startsWith("capsule-set:")){let a={kind:"capsule-set",capsuleSetId:n.slice(12),connectedAtMs:Date.now()},l=l1(e),i=l.some(e=>"capsule-set"===e.kind&&e.capsuleSetId===a.capsuleSetId)?l:[...l,a],r=await (0,w.updateChat)(e.id,{localKnowledgeScopes:i});t(r.chat);return}if(n.startsWith("capsule:")){let a={kind:"capsule",capsuleId:n.slice(8),connectedAtMs:Date.now()},l=l1(e),i=l.some(e=>"capsule"===e.kind&&e.capsuleId===a.capsuleId)?l:[...l,a],r=await (0,w.updateChat)(e.id,{localKnowledgeScopes:i});t(r.chat)}}catch(e){p(l3(e))}finally{d(!1)}}let h=l0(e),f=function(e,t){let n=t.map(e=>({value:`capsule:${e.id}`,label:`Knowledge capsule: ${e.displayName}`})),a=l0(e);if(!a.startsWith("capsule:")||n.some(e=>e.value===a))return n;let l=a.slice(8);return[...n,{value:a,label:`Knowledge capsule: ${l} (unavailable)`}]}(e,r),g=function(e,t){let n=t.map(e=>({value:`capsule-set:${e.id}`,label:`Capsule set: ${e.displayName}`})),a=l0(e);if(!a.startsWith("capsule-set:")||n.some(e=>e.value===a))return n;let l=a.slice(12);return[...n,{value:a,label:`Capsule set: ${l} (unavailable)`}]}(e,s),v=u??o;return(0,n.jsxs)("div",{className:"scope-grounding","data-connected":i?"true":"false",children:[(0,n.jsx)("span",{className:"scope-grounding-label mono",children:"Grounding"}),(0,n.jsx)(tz,{triggerClassName:"scope-grounding-select",value:h,disabled:c,ariaLabel:"Grounding mode",menuTitle:"Strategy",sections:[{options:[{value:"none",label:"Model only"},{value:"files",label:"Live Files context",disabled:!l2(e)},..."multi"===h?[{value:"multi",label:"Multiple sources",disabled:!0}]:[],...f.map(e=>({value:e.value,label:e.label})),...g.map(e=>({value:e.value,label:e.label}))]}],onValueChange:e=>{m(e)}}),null!==v?(0,n.jsx)("span",{role:"alert",className:"scope-connect-error",children:v}):null]})}function l5({chat:e,onChatChanged:t}){let l=function(){let[e,t]=(0,a.useState)([]),[n,l]=(0,a.useState)([]),[i,r]=(0,a.useState)(null);return(0,a.useEffect)(()=>{let e=!1;return async function(){try{let[n,a]=await Promise.allSettled([(0,lD.fetchCapsules)(),(0,lD.fetchCapsuleSets)()]);if("fulfilled"!==n.status)throw n.reason;if(e)return;t(n.value.capsules.filter(e=>"ready"===e.lifecycleState)),"fulfilled"===a.status?l(a.value.capsuleSets):(l([]),r(l3(a.reason)))}catch(t){e||r(l3(t))}}(),()=>{e=!0}},[]),{capsules:e,capsuleSets:n,loadError:i}}(),i=l4(e);return(0,n.jsx)("div",{className:"chat-scope-header","data-grounded":i?"true":"false",children:(0,n.jsx)(l6,{chat:e,onChatChanged:t,catalog:l,connected:i})})}function l8({chat:e,answer:t,busy:a,selectedModelId:l,launchGroundedWorkflowHandoff:i}){return void 0!==e&&l4(e)&&(void 0!==t||a)?(0,n.jsxs)("div",{className:"chatw-grounded",children:[(0,n.jsx)(a4,{answer:t,busy:a}),(0,n.jsx)(lA,{answer:t,modelId:l,busy:a,launch:i})]}):null}function l7({action:e,acceptCandidate:t,rejectCandidate:l,forgetMemoryAction:i,onActionSettled:r}){let[s,o]=(0,a.useState)(!1),[c,d]=(0,a.useState)(),[u,p]=(0,a.useState)(!1),m=(0,a.useCallback)((e,t,n)=>{s||(o(!0),d(void 0),e().then(()=>{r(t)}).catch(e=>{d(e instanceof Error?e.message:n)}).finally(()=>o(!1)))},[s,r]);if("candidate"===e.kind)return(0,n.jsxs)("article",{className:"chat-memory-action",children:[(0,n.jsxs)("div",{className:"chat-memory-action-head",children:[(0,n.jsx)("strong",{children:e.scopeLabel}),(0,n.jsx)("span",{children:e.requiresApproval?"Approval required":"Proposed memory"})]}),(0,n.jsx)("p",{children:e.body}),(0,n.jsxs)("div",{className:"chat-memory-action-buttons",children:[(0,n.jsx)("button",{type:"button","aria-disabled":s,"aria-busy":s,onClick:()=>{m(()=>t(e.proposalId),"MemoriaViva proposal accepted.","Unable to accept memory.")},children:"Accept"}),(0,n.jsx)("button",{type:"button","aria-disabled":s,"aria-busy":s,onClick:()=>{m(()=>l(e.proposalId),"MemoriaViva proposal rejected.","Unable to reject memory.")},children:"Reject"})]}),void 0!==c?(0,n.jsx)(aD,{error:c,fallback:"Unable to update memory.",onDismiss:()=>d(void 0)}):null]});if("update"===e.kind)return(0,n.jsxs)("article",{className:"chat-memory-action",children:[(0,n.jsxs)("div",{className:"chat-memory-action-head",children:[(0,n.jsx)("strong",{children:"MemoriaViva update detected"}),(0,n.jsx)("span",{children:e.memoryId})]}),(0,n.jsx)("p",{children:void 0!==e.bodyPatch?`Suggested update: ${e.bodyPatch}`:"Suggested update."})]});if("forget"===e.kind){let t=()=>{m(()=>i(e.memoryId).then(()=>p(!1)),"MemoriaViva forget action completed.","Unable to forget memory.")};return(0,n.jsxs)("article",{className:"chat-memory-action",children:[(0,n.jsxs)("div",{className:"chat-memory-action-head",children:[(0,n.jsx)("strong",{children:"MemoriaViva forget detected"}),(0,n.jsx)("span",{children:e.requiresConfirmation?"Confirmation required":e.memoryId})]}),(0,n.jsx)("p",{children:`Matched memory ${e.memoryId} for a forget operation.`}),(0,n.jsx)("div",{className:"chat-memory-action-buttons",children:e.requiresConfirmation?u?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button","aria-disabled":s,"aria-busy":s,onClick:t,children:"Forget permanently"}),(0,n.jsx)("button",{type:"button","aria-disabled":s,"aria-busy":s,onClick:()=>{s||(d(void 0),p(!1))},children:"Cancel"})]}):(0,n.jsx)("button",{type:"button","aria-disabled":s,"aria-busy":s,onClick:()=>{s||(d(void 0),p(!0))},children:"Review forget"}):(0,n.jsx)("button",{type:"button","aria-disabled":s,"aria-busy":s,onClick:t,children:"Forget"})}),void 0!==c?(0,n.jsx)(aD,{error:c,fallback:"Unable to update memory.",onDismiss:()=>d(void 0)}):null]})}return"rejected"===e.kind?(0,n.jsxs)("article",{className:"chat-memory-action",children:[(0,n.jsx)("div",{className:"chat-memory-action-head",children:(0,n.jsx)("strong",{children:"Memory proposal declined"})}),(0,n.jsx)("p",{children:""!==e.reason?e.reason:"No reason provided"})]}):(0,n.jsx)("article",{className:"chat-memory-action",children:(0,n.jsx)("div",{className:"chat-memory-action-head",children:(0,n.jsx)("strong",{children:"MemoriaViva action not created"})})})}function l9({memoryEnabled:e,setMemoryEnabled:t,memoryBudgetTokens:l,setMemoryBudgetTokens:i,latestMemory:r,acceptCandidate:s,rejectCandidate:o,forgetMemoryAction:c,compact:d=!1}){let[u,p]=(0,a.useState)(!1),[m,h]=(0,a.useState)(""),f=(0,a.useId)(),g=`${f}-chat-memory-disclosure`,v=(0,a.useRef)(null),b=(0,a.useCallback)(e=>{h(e),v.current?.focus()},[]),x=r?.context.memories.length??0,y=x>0?`${String(x)} memories included`:"No memories included",w=e=>{i(Math.max(0,l+e))},k=(0,n.jsxs)("label",{className:"chat-memory-budget",children:[(0,n.jsx)("span",{children:"Budget (tokens)"}),(0,n.jsxs)("span",{className:"number-control number-control-pill",children:[(0,n.jsx)("input",{type:"number",className:"number-control-input",min:0,step:100,value:l,onChange:e=>i(Math.max(0,Number(e.target.value)||0)),onWheel:e=>{0===e.deltaY||(e.preventDefault(),w(100*(e.deltaY<0?1:-1)))}}),(0,n.jsx)(a3,{label:"memory budget",onStepUp:()=>w(100),onStepDown:()=>w(-100)})]})]});return(0,n.jsxs)("section",{className:"chat-memory-panel","aria-label":"Conversation memory",children:[(0,n.jsxs)("div",{className:"chat-memory-panel-head",children:[(0,n.jsxs)("div",{className:"chat-memory-toggle",children:[(0,n.jsx)(lM,{on:e,onChange:t,label:"Enable MemoriaViva for the next request"}),(0,n.jsxs)("span",{children:["MemoriaViva ",e?"on":"off"]})]}),d?null:k,(0,n.jsx)("button",{ref:v,type:"button",className:`chip${d?" chip-icon chat-memory-disclosure-toggle ui-tip cmp-tip-end":""}`,"aria-expanded":u,"aria-controls":g,"aria-label":y,"data-tip":d?y:void 0,onClick:()=>p(e=>!e),children:d?(0,n.jsx)(j.Icons.brainSlash,{size:16,style:{color:"var(--accent)"}}):y})]}),u?(0,n.jsxs)("div",{id:g,className:"chat-memory-disclosure",children:[(0,n.jsx)("p",{className:"chat-memory-summary",children:void 0===r?"MemoriaViva disclosure appears after the next response.":r.context.enabled?`Used ${String(r.context.budget.used)} of ${String(r.context.budget.tokens)} MemoriaViva tokens.`:"MemoriaViva was disabled for the last request."}),r?.context.memories.map(e=>(0,n.jsxs)("article",{className:"chat-memory-item",children:[(0,n.jsxs)("div",{className:"chat-memory-item-head",children:[(0,n.jsx)("strong",{children:e.memoryId}),(0,n.jsx)("span",{children:e.inclusionReason})]}),(0,n.jsx)("p",{children:e.bodyExcerpt}),(0,n.jsxs)("dl",{className:"chat-memory-meta","aria-label":`Provenance for ${e.memoryId}`,children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Source"}),(0,n.jsx)("dd",{children:e.sourceKind})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Sensitivity"}),(0,n.jsx)("dd",{children:e.sensitivity})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Status"}),(0,n.jsx)("dd",{children:e.status})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Confidence"}),(0,n.jsx)("dd",{children:`${String(Math.round(100*e.confidence))}%`})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Captured"}),(0,n.jsx)("dd",{children:new Date(e.capturedAt).toISOString().slice(0,10)})]})]}),void 0!==e.captureRationale?(0,n.jsx)("p",{className:"chat-memory-rationale",children:e.captureRationale}):null]},e.memoryId)),r?.actions.map(e=>(0,n.jsx)(l7,{action:e,acceptCandidate:s,rejectCandidate:o,forgetMemoryAction:c,onActionSettled:b},"candidate"===e.kind?e.proposalId:"rejected"===e.kind?e.reason:e.memoryId)),(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite","aria-atomic":"true",children:m})]}):null]})}function ie({mini:e=!1,minimalChat:t=!1,compact:l=!1,controlsNarrow:i=!1,barCompact:s=!1,workflowCompact:o=!1,onOpenRunResult:c}){let d=r(),{messages:u,draft:p,loading:m,sending:h,sendStatus:f,error:g,noEligibleModels:v,selectedModel:b,sendMessage:x,cancelGrounded:y,activeChat:w,replaceChat:j,latestGrounded:k,latestMemory:N,lastSentDocuments:S,memoryEnabled:C,setMemoryEnabled:I,memoryBudgetTokens:E,setMemoryBudgetTokens:R,acceptMemoryCandidate:$,rejectMemoryCandidate:A,launchGroundedWorkflowHandoff:T,forgetMemoryAction:L}=d,P=p.trim().length>0&&!h&&!m&&!v,M=u.filter(e=>"user"===e.role||"assistant"===e.role&&e.content.length>0||lL(e)),D=(0,a.useRef)(null),q=(0,a.useRef)(!0),F=(0,a.useRef)(!1),O=M.length>0?M[M.length-1]:void 0,z=void 0===O?"":O.content,K=l||e,B=i||e||t||o,_=s||t,U=o||e||t;return(0,a.useEffect)(()=>{h&&!F.current&&(q.current=!0),F.current=h;let e=D.current;null!==e&&q.current&&(e.scrollTop=e.scrollHeight)},[M.length,h,z]),(0,n.jsxs)("div",{className:`chatw${K?" chatw-compact":""}${t?" chatw-minimal":""}`,children:[void 0!==w?(0,n.jsx)(l5,{chat:w,onChatChanged:j}):null,void 0!==w?(0,n.jsx)(l9,{memoryEnabled:C,setMemoryEnabled:I,memoryBudgetTokens:E,setMemoryBudgetTokens:R,latestMemory:N,acceptCandidate:$,rejectCandidate:A,forgetMemoryAction:L,compact:K||t}):null,v?(0,n.jsx)("div",{className:"chatw-foot",children:(0,n.jsx)(lH,{})}):null,m?(0,n.jsx)("div",{className:"chatw-foot",children:(0,n.jsx)(lY,{})}):null,(0,n.jsx)("div",{className:"chatw-scroll",ref:D,role:"log","aria-label":"Conversation",tabIndex:0,onScroll:e=>{let t=e.currentTarget;q.current=t.scrollHeight-t.scrollTop-t.clientHeight<64},children:0===M.length?void 0!==w?(0,n.jsx)(lX,{minimal:t}):(0,n.jsx)(lQ,{}):(0,n.jsxs)("div",{className:"chatw-log",children:[M.map((e,t)=>(0,n.jsx)(l_,{message:e,onOpenRunResult:c,streaming:"streaming"===f&&t===M.length-1&&"assistant"===e.role},e.id)),h&&"streaming"!==f?(0,n.jsxs)("div",{className:"chatw-typing-row",children:[(0,n.jsx)(lW,{}),l4(w)?(0,n.jsx)("button",{type:"button",className:"grounded-cancel-btn","aria-label":"Cancel grounded request",onClick:y,children:"Cancel"}):null]}):null,(0,n.jsx)(l8,{chat:w,answer:k,busy:h,selectedModelId:b,launchGroundedWorkflowHandoff:T}),(0,n.jsx)(lN,{documents:S})]})}),M.length>0?(0,n.jsx)("div",{className:"chatw-foot",children:(0,n.jsxs)("form",{className:`composer${K?" composer-chat-compact":""}`,onSubmit:e=>{e.preventDefault(),x()},children:[(0,n.jsx)(lJ,{session:d,ready:P,placeholder:lz,minimal:t,compact:K,controlsNarrow:B,barCompact:_,workflowCompact:U}),void 0!==g?(0,n.jsx)(aD,{error:g,fallback:"Could not send message.",onDismiss:d.clearError}):null]})}):null,0===M.length&&void 0!==w?(0,n.jsx)("div",{className:"chatw-foot",children:(0,n.jsxs)("form",{className:`composer${K?" composer-chat-compact":""}`,onSubmit:e=>{e.preventDefault(),x()},children:[(0,n.jsx)(lJ,{session:d,ready:P,placeholder:m?"Connecting to your gateway…":lz,minimal:t,compact:K,controlsNarrow:B,barCompact:_,workflowCompact:U}),void 0!==g?(0,n.jsx)(aD,{error:g,fallback:"Could not send message.",onDismiss:d.clearError}):null]})}):null,0===M.length&&void 0!==g&&void 0===w?(0,n.jsx)("div",{className:"chatw-foot",children:(0,n.jsx)(aD,{error:g,fallback:"Could not load chat.",onDismiss:d.clearError})}):null]})}let it=new Set(["ArrowDown","ArrowUp","ArrowRight","ArrowLeft","Home","End"]);function ia(e){return Array.from(e.querySelectorAll("button[role='treeitem']"))}function il({project:e,activeProjectPath:t,chats:l,activeChatId:i,onProject:r,onChat:s,treeRef:o}){let c=t===e.path,[d,u]=(0,a.useState)(c),p=e.available?"Available":"Unavailable";return(0,a.useEffect)(()=>{c&&u(!0)},[c]),(0,n.jsxs)("div",{className:"proj",children:[(0,n.jsxs)("button",{className:"proj-head",type:"button",role:"treeitem","aria-level":1,"aria-expanded":d,"aria-selected":c,"data-active":c?"true":"false","aria-current":c?"true":void 0,"aria-label":`${e.name} (${p})`,tabIndex:c?0:-1,onClick:()=>{u(e=>!e),r(e),null!==o.current&&ia(o.current).forEach(e=>{e.tabIndex=-1})},children:[(0,n.jsx)("span",{className:"proj-caret","data-open":d,"aria-hidden":"true",children:(0,n.jsx)(j.Icons.chevronR,{size:13})}),(0,n.jsx)(j.Icons.folder,{size:15,"aria-hidden":"true"}),(0,n.jsx)("span",{className:"proj-name",children:e.name}),(0,n.jsx)("span",{className:"chat-time",children:p})]}),d&&(0,n.jsx)("div",{className:"proj-chats",role:"group","aria-label":e.name,children:c?0===l.length?(0,n.jsx)("div",{className:"proj-empty",children:"No chats"}):l.map(e=>(0,n.jsxs)("button",{type:"button",role:"treeitem","aria-level":2,"aria-selected":i===e.id,className:"chat-row","data-active":i===e.id,tabIndex:-1,onClick:()=>{s(e)},children:[(0,n.jsx)("span",{className:"chat-title",children:e.title}),void 0!==e.branchLabel?(0,n.jsx)("span",{className:"chat-meta mono",children:e.branchLabel}):null]},e.id)):(0,n.jsx)("div",{className:"proj-empty",children:"Select project to load chats"})})]})}function ii(){let e=r(),t=(0,a.useRef)(null);return(0,n.jsxs)("div",{className:"tw-scroll",children:[(0,n.jsx)("div",{className:"sb-section",children:(0,n.jsx)("span",{className:"sb-section-label",children:"Projects"})}),0===e.projects.length?(0,n.jsx)("div",{className:"proj-empty",children:"No registered projects"}):(0,n.jsx)("div",{className:"proj-tree",role:"tree","aria-label":"Projects",tabIndex:-1,ref:t,onKeyDown:e=>{it.has(e.key)&&null!==t.current&&function(e,t){let n=ia(t),a=e.target;if(!(a instanceof HTMLElement))return;let l=a.closest("button[role='treeitem']");if(null===l)return;let i=n.indexOf(l);if(i<0)return;e.preventDefault();let r=e.key;if("ArrowDown"===r)n[i+1]?.focus();else if("ArrowUp"===r)n[i-1]?.focus();else if("Home"===r)n[0]?.focus();else if("End"===r)n[n.length-1]?.focus();else if("ArrowRight"===r)"false"===l.getAttribute("aria-expanded")?l.click():"true"===l.getAttribute("aria-expanded")&&n[i+1]?.focus();else if("ArrowLeft"===r)if("true"===l.getAttribute("aria-expanded"))l.click();else{let e=Number(l.getAttribute("aria-level")??"1");for(let t=i-1;t>=0;t-=1)if(Number(n[t]?.getAttribute("aria-level")??"1")<e){n[t]?.focus();break}}}(e,t.current)},children:e.projects.map(a=>(0,n.jsx)(il,{project:a,activeProjectPath:e.activeProject?.path,chats:e.activeProject?.path===a.path?e.chats:[],activeChatId:e.activeChat?.id,treeRef:t,onProject:t=>{e.openProject(t)},onChat:t=>{e.openChat(t)}},a.path))})]})}function ir({openChatWindow:e}){let t=r(),[l,i]=(0,a.useState)(""),[s,o]=(0,a.useState)("active"),[c,d]=(0,a.useState)(null),[u,p]=(0,a.useState)(""),[m,h]=(0,a.useState)(null),[f,g]=(0,a.useState)(null),[v,b]=(0,a.useState)(null),[x,y]=(0,a.useState)(null),k=(0,a.useRef)(null),N=(0,a.useId)(),S=(0,a.useId)(),C=(0,a.useId)(),I=(0,a.useId)(),E=(0,a.useMemo)(()=>t.chats.filter(e=>"closed"!==e.status).length,[t.chats]),R=t.chats.length-E,$=(0,a.useMemo)(()=>[...t.chats].sort((e,t)=>t.updatedAt-e.updatedAt).filter(e=>"deleted"===s?"closed"===e.status:"closed"!==e.status).filter(e=>{let t;return 0===(t=l.trim().toLowerCase()).length||e.title.toLowerCase().includes(t)||e.selectedModel.toLowerCase().includes(t)||(e.branchLabel?.toLowerCase().includes(t)??!1)}),[l,t.chats,s]);(0,a.useEffect)(()=>{null!==c&&k.current?.focus({preventScroll:!0})},[c]);let A=async()=>{b(null);let n=await t.openNewChat(void 0,"New chat");void 0!==n&&e(n)},T=e=>{d(e.id),p(e.title),h(null),b(null),y(null)},L=async e=>{let n=u.trim();if(0===n.length){y("Title cannot be empty."),k.current?.focus({preventScroll:!0});return}if(n===e.title){d(null),y(null);return}g(e.id),b(null),y(null);try{let a=await (0,w.updateChat)(e.id,{title:n});t.replaceChat(a.chat),d(null)}catch{b("Rename failed.")}finally{g(null)}},P=async e=>{g(e.id),b(null);try{let n=await (0,w.updateChat)(e.id,{status:"closed"});t.replaceChat(n.chat),h(null)}catch(t){let e=t instanceof Error?t.message:"Request failed.";b(`Delete failed: ${e}`)}finally{g(null)}},M=async e=>{g(e.id),b(null);try{let n=await (0,w.updateChat)(e.id,{status:"open"});t.replaceChat(n.chat),h(null)}catch(t){let e=t instanceof Error?t.message:"Request failed.";b(`Restore failed: ${e}`)}finally{g(null)}};return(0,n.jsxs)("div",{className:"chat-history",children:[(0,n.jsxs)("div",{className:"chat-history-head",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"chat-history-kicker",children:"Conversations"}),(0,n.jsx)("h2",{children:"Chat History"})]}),(0,n.jsxs)("button",{type:"button",className:"lk-btn lk-btn-primary",onClick:()=>void A(),children:[(0,n.jsx)(j.Icons.newChat,{size:15}),"New"]})]}),(0,n.jsxs)("label",{className:"chat-history-search",children:[(0,n.jsx)(j.Icons.search,{size:15}),(0,n.jsx)("input",{value:l,onChange:e=>i(e.target.value),placeholder:"Search","aria-label":"Search chat history"})]}),(0,n.jsxs)("div",{className:"chat-history-tabs",role:"tablist","aria-label":"Conversation state",children:[(0,n.jsxs)("button",{type:"button",id:N,role:"tab","aria-selected":"active"===s,"aria-controls":C,className:"chat-history-tab",onClick:()=>{o("active"),h(null)},children:["Active ",(0,n.jsx)("span",{children:E})]}),(0,n.jsxs)("button",{type:"button",id:S,role:"tab","aria-selected":"deleted"===s,"aria-controls":C,className:"chat-history-tab",onClick:()=>{o("deleted"),h(null)},children:["Deleted ",(0,n.jsx)("span",{children:R})]})]}),null!==v?(0,n.jsx)("div",{className:"lk-alert",role:"alert",children:v}):null,(0,n.jsx)("div",{id:C,className:"chat-history-list",role:"tabpanel","aria-labelledby":"active"===s?N:S,children:0===$.length?(0,n.jsx)("div",{className:"lk-empty",children:(0,n.jsx)("p",{className:"lk-empty-title",children:"No conversations"})}):$.map(t=>{var a;let l=e3(t).length+e6(t).length,i=c===t.id,r=m===t.id,s=f===t.id,o="closed"===t.status;return(0,n.jsxs)("article",{className:"chat-history-row","data-chat-id":t.id,"data-state":o?"deleted":"active",children:[(0,n.jsx)("div",{className:"chat-history-row-main",children:i?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("input",{ref:k,className:"chat-history-title-input",value:u,"aria-invalid":null!==x,"aria-describedby":null!==x?I:void 0,onChange:e=>{p(e.target.value),null!==x&&y(null)},onKeyDown:e=>{"Enter"===e.key&&L(t),"Escape"===e.key&&(d(null),y(null))}}),null!==x?(0,n.jsx)("span",{id:I,className:"chat-history-rename-error",role:"alert",children:x}):null]}):(0,n.jsxs)("button",{type:"button",className:"chat-history-open",disabled:o,onClick:()=>e(t),children:[(0,n.jsx)("span",{className:"chat-history-title",children:t.title}),(0,n.jsxs)("span",{className:"chat-history-meta",children:[(a=t.updatedAt,new Intl.DateTimeFormat(void 0,{month:"short",day:"2-digit",hour:"2-digit",minute:"2-digit"}).format(new Date(a)))," / ",t.selectedModel,l>0?` / ${String(l)} sources`:""]})]})}),(0,n.jsx)("div",{className:"chat-history-actions",children:i?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-primary",disabled:s,onClick:()=>void L(t),children:"Save"}),(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost",disabled:s,onClick:()=>{d(null),y(null)},children:"Cancel"})]}):r?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-danger",disabled:s,onClick:()=>void P(t),children:"Delete"}),(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost",disabled:s,onClick:()=>h(null),children:"Cancel"})]}):o?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("button",{type:"button",className:"lk-btn lk-btn-primary",disabled:s,onClick:()=>void M(t),children:[(0,n.jsx)(j.Icons.restore,{size:14}),"Restore"]}),(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost",onClick:()=>T(t),children:"Rename"})]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost",onClick:()=>T(t),children:"Rename"}),(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-ghost",onClick:()=>{h(t.id),d(null)},children:"Delete"})]})})]},t.id)})})]})}function is(){let e=s(),t=e?.activeProject?.name??"No project selected",l=(0,a.useId)();return(0,n.jsxs)("div",{className:"srch",children:[(0,n.jsxs)("div",{className:"srch-box",children:[(0,n.jsx)(j.Icons.search,{size:15,"aria-hidden":"true"}),(0,n.jsx)("input",{type:"search","aria-label":"Search files and symbols","aria-describedby":l,placeholder:"Search files & symbols…",disabled:!0})]}),(0,n.jsxs)("div",{className:"tw-label srch-label",children:[t," ",(0,n.jsx)("span",{className:"srch-meta mono",children:"workspace search"})]}),(0,n.jsxs)("div",{className:"tw-pad",children:[(0,n.jsxs)("div",{className:"rb-placeholder",style:{height:150},children:[(0,n.jsx)("div",{className:"ph-stripes"}),(0,n.jsx)("span",{className:"rb-ph-label mono",children:"search"})]}),(0,n.jsx)("div",{id:l,className:"rb-foot mono",style:{marginTop:14},children:"Search across workspace files & symbols — coming soon."})]})]})}let io=[{value:"auto",label:"Auto (recommended)"},{value:"fast",label:"Fast"},{value:"precise",label:"Precise"},{value:"research",label:"Research"},{value:"creative",label:"Creative"},{value:"technical",label:"Technical"},{value:"safety-critical",label:"Safety-critical"},{value:"agentic",label:"Agentic"}],ic=[{value:"clarify",label:"Ask clarifying questions"},{value:"assume",label:"State explicit assumptions"}],id="__none__";function iu({items:e,empty:t}){return 0===e.length?void 0===t?null:(0,n.jsx)("p",{className:"pe-empty",children:t}):(0,n.jsx)("ul",{className:"pe-list",children:e.map((e,t)=>(0,n.jsx)("li",{children:e},`${String(t)}:${e.slice(0,24)}`))})}function ip({title:e,children:t}){return(0,n.jsxs)("section",{className:"pe-section","aria-label":e,children:[(0,n.jsx)("h4",{className:"pe-section-title",children:e}),t]})}function im({routing:e}){let t="available"===e.availability?"ok":"unavailable"===e.availability?"warn":"muted",a="available"===e.availability?`Model ready: ${e.resolvedModelId??""}`:"unavailable"===e.availability?"Selected model unavailable — enhancement still completed deterministically":"No downstream model selected — enhancement is provider-neutral";return(0,n.jsx)("p",{className:`pe-routing pe-routing-${t}`,"data-testid":"pe-model-routing",role:"status","aria-live":"polite",children:a})}function ih({safety:e}){let t=e.requiresHumanReview;return(0,n.jsxs)(ip,{title:"Safety",children:[(0,n.jsxs)("p",{className:"pe-safety-summary","data-testid":"pe-safety-decision",children:["Decision: ",(0,n.jsx)("strong",{children:e.decision})," · verification: ",e.verificationStatus," ·"," ","human review: ",(0,n.jsx)("strong",{children:t?"required":"not required"})]}),t?(0,n.jsx)("p",{className:"pe-safety-warning",role:"alert",children:"This prompt requires human review before any downstream use."}):null,e.findings.length>0?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("h5",{className:"pe-subhead",children:"Safety findings"}),(0,n.jsx)("ul",{className:"pe-list","data-testid":"pe-safety-findings",children:e.findings.map(e=>(0,n.jsxs)("li",{children:[(0,n.jsx)("span",{className:`pe-sev pe-sev-${e.severity}`,children:e.severity})," ",e.detail]},`${e.ruleId}:${e.code}`))})]}):null,e.leastPrivilege.length>0?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("h5",{className:"pe-subhead",children:"Least-privilege constraints"}),(0,n.jsx)(iu,{items:[...e.leastPrivilege]})]}):null]})}function ig({plan:e,readiness:t}){let a="ready"===t.status?"Grounding readiness: connected context available":"unavailable"===t.status?`Grounding readiness: unavailable${void 0===t.notice?"":` — ${t.notice}`}`:"Grounding readiness: not required";return(0,n.jsxs)(ip,{title:"Grounding plan",children:[(0,n.jsx)("p",{className:`pe-grounding-readiness pe-grounding-readiness-${t.status}`,"data-testid":"pe-grounding-readiness",role:"unavailable"===t.status?"alert":"status","aria-live":"polite",children:a}),(0,n.jsxs)("p",{className:"pe-grounding-meta",children:["Strategy: ",(0,n.jsx)("strong",{children:e.strategy})," · ",e.required?"required":"optional"," · citations: ",e.citation.discipline," (",e.citation.granularity,")"]}),e.sourcePriority.length>0?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("h5",{className:"pe-subhead",children:"Source priority"}),(0,n.jsx)("ol",{className:"pe-list",children:e.sourcePriority.map(e=>(0,n.jsxs)("li",{children:[e.source,e.required?" (required)":""]},e.source))})]}):null,(0,n.jsx)(iu,{items:[...e.directives]})]})}function iv({evidence:e,fingerprint:t}){return(0,n.jsxs)("p",{className:"pe-evidence","data-testid":"pe-evidence",children:["Evidence fingerprint: ",t.slice(0,16),"…","recorded"===e.status&&void 0!==e.runId?(0,n.jsxs)(n.Fragment,{children:[" ","Manifest:"," ",(0,n.jsx)("a",{href:e.manifestUrl??"#",target:"_blank",rel:"noreferrer","aria-label":`Prompt enhancement evidence manifest ${e.runId}`,children:e.runId})]}):" Manifest not recorded."]})}function ib({candidates:e}){return(0,n.jsx)(ip,{title:"Candidate scorecards",children:(0,n.jsx)("div",{className:"c-tablewrap",children:(0,n.jsx)("div",{className:"c-tablescroll",children:(0,n.jsxs)("table",{className:"c-table pe-scorecards","data-testid":"pe-scorecards",children:[(0,n.jsx)("thead",{children:(0,n.jsxs)("tr",{children:[(0,n.jsx)("th",{scope:"col",children:"Profile"}),(0,n.jsx)("th",{scope:"col",className:"num",children:"Score"}),(0,n.jsx)("th",{scope:"col",className:"num",children:"Tokens"}),(0,n.jsx)("th",{scope:"col",children:"Winner"})]})}),(0,n.jsx)("tbody",{children:e.scorecards.map(t=>{let a=t.candidateId===e.winnerCandidateId;return(0,n.jsxs)("tr",{className:a?"pe-winner":void 0,children:[(0,n.jsx)("th",{scope:"row",children:t.profile}),(0,n.jsx)("td",{className:"num",children:t.aggregateScore.toFixed(3)}),(0,n.jsx)("td",{className:"num",children:t.estimatedTokens}),(0,n.jsx)("td",{children:a?"★":""})]},t.candidateId)})})]})})})})}function ix({result:e}){let t=e.enhancedPrompt,a=e.analysis.missingContext.map(e=>"assumption"===e.kind?e.statement:e.question);return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(ip,{title:"Role",children:(0,n.jsx)("p",{children:t.role})}),(0,n.jsx)(ip,{title:"Objective",children:(0,n.jsx)("p",{children:t.goal})}),(0,n.jsx)(ip,{title:"Context",children:(0,n.jsx)(iu,{items:[...t.context],empty:"No additional context."})}),(0,n.jsx)(ip,{title:e.analysis.missingContext.some(e=>"assumption"===e.kind)?"Assumptions":"Clarification questions",children:(0,n.jsx)(iu,{items:a,empty:"No clarifications or assumptions needed."})}),(0,n.jsx)(ip,{title:"Steps",children:(0,n.jsx)(iu,{items:[...t.taskDecomposition]})}),(0,n.jsx)(ip,{title:"Constraints",children:(0,n.jsx)(iu,{items:[...t.constraints]})}),(0,n.jsxs)(ip,{title:"Output schema",children:[(0,n.jsxs)("p",{children:["Format: ",(0,n.jsx)("strong",{children:t.outputSchema.format}),t.outputSchema.structured?" · structured":""]}),(0,n.jsx)(iu,{items:[...t.outputSchema.hints]})]}),(0,n.jsx)(ip,{title:"Quality criteria",children:(0,n.jsx)(iu,{items:[...t.qualityCriteria]})}),(0,n.jsx)(ip,{title:"Uncertainty handling",children:(0,n.jsx)(iu,{items:[...t.uncertaintyHandling]})}),(0,n.jsx)(ip,{title:"Safety rules",children:(0,n.jsx)(iu,{items:[...t.safetyRules]})})]})}function iy({enhanceImpl:e=w.enhancePrompt,fetchModelsImpl:t=w.fetchModels}={}){let[l,i]=(0,a.useState)(""),[r,s]=(0,a.useState)("auto"),[o,c]=(0,a.useState)("clarify"),[d,u]=(0,a.useState)(id),[p,m]=(0,a.useState)([]),[h,f]=(0,a.useState)(null),[g,v]=(0,a.useState)(!1),[b,x]=(0,a.useState)(null),[y,j]=(0,a.useState)(!1),[k,N]=(0,a.useState)(null),S=(0,a.useRef)(null),C=(0,a.useId)(),I=(0,a.useId)();(0,a.useEffect)(()=>{let e=!1;return t().then(t=>{e||m(t.models.filter(e=>"chat"===e.kind))}).catch(()=>{}),()=>{e=!0}},[t]),(0,a.useEffect)(()=>()=>{S.current?.abort()},[]);let E=(0,a.useCallback)(async()=>{let t=l.trim();if(0===t.length)return void x("Enter a prompt draft to enhance.");S.current?.abort();let n=new AbortController;S.current=n,v(!0),x(null),j(!1),N(null);let a={text:t,missingInformationStrategy:"assume"===o?"assume":"clarify",..."auto"===r?{}:{profilePreference:r},...d===id?{}:{modelId:d}};try{let t=await e(a,n.signal);n.signal.aborted||f(t)}catch(e){n.signal.aborted||x(e instanceof w.ApiError?`${e.message} (${e.code})`:e instanceof Error&&"AbortError"===e.name?"Request cancelled.":"Prompt enhancement failed. Please try again.")}finally{n.signal.aborted||v(!1)}},[l,o,r,d,e]),R=(0,a.useCallback)(async()=>{if(null===h)return;let e=navigator.clipboard?.writeText;if(void 0===e)return void x("Clipboard is not available in this browser.");try{await e.call(navigator.clipboard,h.renderedPrompt),j(!0),N("Rendered prompt copied to clipboard.")}catch{x("Could not copy to the clipboard.")}},[h]),$=[{options:[{value:id,label:"Deterministic only (no model)"},...p.map(e=>({value:e.id,label:e.id}))]}];return(0,n.jsxs)("div",{className:"pe-panel","data-testid":"prompt-enhancer-panel",children:[(0,n.jsx)("h3",{className:"pe-title",children:"Prompt Enhancer"}),(0,n.jsx)("p",{className:"pe-intro",children:"Turn a raw prompt into a governed, structured Enhanced Prompt. The result is for review and copy/export — it is never executed from here."}),(0,n.jsxs)("div",{className:"pe-form",children:[(0,n.jsx)("label",{className:"pe-label",htmlFor:C,children:"Raw prompt"}),(0,n.jsx)("textarea",{id:C,className:"pe-draft",value:l,onChange:e=>{i(e.target.value)},rows:5,placeholder:"Describe the task you want a strong prompt for…","aria-describedby":null===b?void 0:I}),(0,n.jsxs)("div",{className:"pe-controls",children:[(0,n.jsxs)("div",{className:"pe-control",children:[(0,n.jsx)("span",{className:"pe-label","aria-hidden":"true",children:"Profile"}),(0,n.jsx)(tz,{value:r,ariaLabel:"Profile",onValueChange:s,sections:[{options:io.map(e=>({...e}))}]})]}),(0,n.jsxs)("div",{className:"pe-control",children:[(0,n.jsx)("span",{className:"pe-label","aria-hidden":"true",children:"Missing information"}),(0,n.jsx)(tz,{value:o,ariaLabel:"Missing information",onValueChange:c,sections:[{options:ic.map(e=>({...e}))}]})]}),(0,n.jsxs)("div",{className:"pe-control",children:[(0,n.jsx)("span",{className:"pe-label","aria-hidden":"true",children:"Readiness model"}),(0,n.jsx)(tz,{value:d,ariaLabel:"Readiness model",onValueChange:u,sections:$})]})]}),(0,n.jsx)("button",{type:"button",className:"pe-enhance",onClick:()=>{E()},disabled:g||0===l.trim().length,children:g?"Enhancing…":"Enhance prompt"}),g?(0,n.jsx)("p",{className:"pe-status",role:"status","aria-live":"polite",children:"Enhancing prompt…"}):null]}),null!==b?(0,n.jsx)("p",{className:"pe-error",role:"alert",id:I,children:b}):null,null!==h?(0,n.jsxs)("div",{className:"pe-result","data-testid":"pe-result",children:[(0,n.jsx)(im,{routing:h.modelRouting}),(0,n.jsxs)("p",{className:"pe-analysis",children:["Task: ",(0,n.jsx)("strong",{children:h.analysis.taskClass})," · domain: ",h.analysis.domain," · criticality: ",h.analysis.criticality]}),(0,n.jsx)(ih,{safety:h.safety}),(0,n.jsx)(ix,{result:h}),(0,n.jsx)(ig,{plan:h.enhancedPrompt.groundingPlan,readiness:h.groundingReadiness}),(0,n.jsx)(ib,{candidates:h.candidates}),(0,n.jsxs)(ip,{title:"Rendered prompt",children:[(0,n.jsx)("pre",{className:"pe-rendered","aria-label":"Rendered prompt text",children:h.renderedPrompt}),(0,n.jsx)("div",{className:"pe-actions",children:(0,n.jsx)("button",{type:"button",className:"pe-copy",onClick:()=>{R()},children:"Copy rendered prompt"})}),y&&null!==k?(0,n.jsx)("p",{className:"pe-status",role:"status","aria-live":"polite",children:k}):null]}),(0,n.jsx)(iv,{evidence:h.evidence,fingerprint:h.inputFingerprintSha256})]}):null]})}let iw=[{name:"Context7",img:"upstash",desc:"Up-to-date library docs",on:!0},{name:"Sequential Thinking",icon:"layers",desc:"Step-by-step reasoning",on:!0},{name:"Filesystem",icon:"files",desc:"Local file access",on:!0},{name:"GitHub",img:"github",desc:"Repos · PRs · issues",on:!0},{name:"Playwright",img:"playwright",desc:"Browser automation",on:!1},{name:"Brave Search",img:"brave",desc:"Web search",on:!1},{name:"MemoriaViva",icon:"cube",desc:"Knowledge graph",on:!0}],ij=[{name:"GitHub",img:"github",on:!0},{name:"Linear",img:"linear",on:!0},{name:"PostgreSQL",img:"postgresql",on:!0},{name:"Sentry",img:"sentry",on:!1},{name:"Slack",img:"slack",on:!1},{name:"Notion",img:"notion",on:!1}];function ik({img:e,icon:t,glyph:a}){if(void 0!==e)return(0,n.jsx)("img",{className:"pl-img",src:`/assets/icons/${e}.svg`,width:"20",height:"20",alt:""});if(void 0!==t){let e=j.Icons[t];return(0,n.jsx)("span",{className:"pl-line",children:(0,n.jsx)(e,{size:18})})}return(0,n.jsx)("span",{className:"mono pl-glyph",children:a})}function iN(){let[e,t]=(0,a.useState)(iw.map(e=>e.on)),l=e.filter(Boolean).length;return(0,n.jsxs)("div",{className:"plg",children:[(0,n.jsxs)("div",{className:"plg-sec",children:[(0,n.jsx)("span",{className:"plg-sec-t",children:"MCP Servers"}),(0,n.jsxs)("span",{className:"plg-sec-c mono",children:[l,"/",iw.length," active"]})]}),iw.map((a,l)=>{let i=e[l]??!1;return(0,n.jsxs)("div",{className:"plg-row",children:[(0,n.jsx)("span",{className:"plg-ico",children:(0,n.jsx)(ik,{img:a.img,icon:a.icon})}),(0,n.jsxs)("span",{className:"plg-text",children:[(0,n.jsx)("span",{className:"plg-name",children:a.name}),(0,n.jsx)("span",{className:"plg-desc",children:a.desc})]}),(0,n.jsx)("button",{className:`plg-dot${i?" on":""}`,title:i?"Running":"Stopped","aria-label":`${a.name}: ${i?"running":"stopped"}`,onClick:()=>{t(e=>{let t=[...e];return t[l]=!t[l],t})}})]},a.name)}),(0,n.jsx)("div",{className:"plg-sec plg-sec2",children:(0,n.jsx)("span",{className:"plg-sec-t",children:"Connectors"})}),ij.map(e=>(0,n.jsxs)("button",{className:"plg-row plg-conn","data-on":e.on,children:[(0,n.jsx)("span",{className:"plg-ico",children:(0,n.jsx)(ik,{img:e.img})}),(0,n.jsxs)("span",{className:"plg-text",children:[(0,n.jsx)("span",{className:"plg-name",children:e.name}),(0,n.jsx)("span",{className:"plg-desc",children:e.on?"Connected":"Not connected"})]}),e.on?(0,n.jsx)("span",{className:"integ-on",children:(0,n.jsx)(j.Icons.check,{size:13})}):(0,n.jsx)("span",{className:"integ-add",children:(0,n.jsx)(j.Icons.plus,{size:14})})]},e.name))]})}let iS=[{id:"nightly-review",name:"Nightly review",when:"02:00 daily",defaultOn:!0},{id:"on-push-lint",name:"On push → lint",when:"git push",defaultOn:!0},{id:"weekly-digest",name:"Weekly digest",when:"Mon 09:00",defaultOn:!1}],iC="keiko.automations.v1",iI=Object.fromEntries(iS.map(e=>[e.id,e.defaultOn]));function iE(){try{let e=localStorage.getItem(iC);if(null===e)return{...iI};let t=JSON.parse(e);if("object"!=typeof t||null===t||Array.isArray(t))return{...iI};let n={...iI};for(let[e,a]of Object.entries(t))e in iI&&"boolean"==typeof a&&(n[e]=a);return n}catch{return{...iI}}}function iR(){let[e,t]=(0,a.useState)(iE);return(0,n.jsx)("div",{className:"tw-list",children:iS.map(a=>{let l=e[a.id]??a.defaultOn;return(0,n.jsxs)("div",{className:"auto-row",children:[(0,n.jsx)("span",{className:"dot",style:{background:l?"var(--accent)":"var(--fg-faint)"}}),(0,n.jsxs)("span",{className:"auto-text",children:[(0,n.jsx)("span",{className:"auto-name",children:a.name}),(0,n.jsx)("span",{className:"auto-when mono",children:a.when})]}),(0,n.jsx)(lM,{on:l,onChange:()=>{var e;e=a.id,t(t=>{let n={...t,[e]:!t[e]};try{localStorage.setItem(iC,JSON.stringify(n))}catch{}return n})},label:a.name})]},a.id)})})}function i$(){return(0,n.jsxs)("div",{className:"tw-pad mob",children:[(0,n.jsxs)("div",{className:"mob-qr",children:[(0,n.jsx)("div",{className:"ph-stripes"}),(0,n.jsx)(j.Icons.mobile,{size:28,style:{position:"relative",color:"var(--fg-dim)"}})]}),(0,n.jsx)("div",{className:"mob-title",children:"Keiko Mobile"}),(0,n.jsx)("div",{className:"mob-sub",children:"Scan to continue this workspace on your phone."})]})}function iA(){var e;let t,{wins:l,active:i,winCount:r}=(0,a.useContext)(y),s=null!==i?E[i.type]:null,o=null!==i?Object.entries(i.cfg).filter(([,e])=>""!==e&&null!=e):[];return(0,n.jsxs)("div",{className:"tw-pad",children:[(0,n.jsx)("div",{className:"rb-section-label",style:{marginTop:0},children:"Active window"}),null!==i&&null!==s?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"insp-top",children:[(0,n.jsx)("span",{className:"insp-ico",style:{color:!0===s.accent?"var(--accent)":"var(--fg-muted)"},children:(e=s.icon,t=j.Icons[e],(0,n.jsx)(t,{size:16}))}),(0,n.jsx)("span",{className:"insp-title",children:s.title})]}),(0,n.jsxs)("div",{className:"rb-rows",children:[(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"Size"}),(0,n.jsxs)("span",{className:"rb-row-v mono",children:[Math.round(i.w)," × ",Math.round(i.h)]})]}),(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"Position"}),(0,n.jsxs)("span",{className:"rb-row-v mono",children:[Math.round(i.x),", ",Math.round(i.y)]})]}),(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"State"}),(0,n.jsx)("span",{className:"rb-row-v mono",children:i.max?"maximized":"floating"})]})]}),o.length>0&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"rb-section-label",children:"Configuration"}),(0,n.jsx)("div",{className:"rb-rows",children:o.map(([e,t])=>(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:e}),(0,n.jsx)("span",{className:"rb-row-v mono",children:String(t).slice(0,20)||"—"})]},e))})]}),(0,n.jsx)("div",{className:"rb-section-label insp-governance",children:"Governance"}),(0,n.jsxs)("div",{className:"rb-rows insp-governance","data-testid":"insp-governance",children:[(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"Authority"}),(0,n.jsx)("span",{className:"rb-row-v mono",children:eT[i.type].authority})]}),(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"Persistence"}),(0,n.jsx)("span",{className:"rb-row-v mono",children:eT[i.type].persistence})]}),(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"Trust"}),(0,n.jsx)("span",{className:"rb-row-v mono",children:eT[i.type].trustBoundary.join(", ")})]}),(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"Lifecycle"}),(0,n.jsx)("span",{className:"rb-row-v mono",children:eT[i.type].lifecycle.join(" → ")})]})]})]}):(0,n.jsx)("div",{className:"insp-empty",children:"No window focused"}),(0,n.jsx)("div",{className:"rb-section-label",children:"Workspace"}),(0,n.jsx)("div",{className:"rb-rows",children:(0,n.jsxs)("div",{className:"rb-row",children:[(0,n.jsx)("span",{className:"rb-row-k",children:"Open windows"}),(0,n.jsx)("span",{className:"rb-row-v mono",children:r})]})})]})}let iT=[{t:"Agent finished build-board",time:"2m",c:"var(--accent)"},{t:"diff-review ready to merge",time:"9m",c:"var(--info)"},{t:"lint-pass queued",time:"14m",c:"var(--fg-faint)"}];function iL(){return(0,n.jsx)("ul",{className:"tw-list",children:iT.map((e,t)=>(0,n.jsxs)("li",{className:"nt-row",children:[(0,n.jsx)("span",{className:"dot",style:{background:e.c,marginTop:6},"aria-hidden":"true"}),(0,n.jsxs)("span",{className:"nt-text",children:[(0,n.jsx)("span",{className:"nt-title",children:e.t}),(0,n.jsxs)("span",{className:"nt-time mono",children:[e.time," ago"]})]})]},t))})}function iP(){return(0,n.jsxs)("div",{className:"tw-pad",children:[(0,n.jsxs)("div",{className:"rb-placeholder",style:{height:150},children:[(0,n.jsx)("div",{className:"ph-stripes"}),(0,n.jsx)("span",{className:"rb-ph-label mono",children:"resources"})]}),(0,n.jsx)("div",{className:"rb-foot mono",style:{marginTop:14},children:"Shared assets & references — coming soon."})]})}let iM="keiko-activity",iD={step:"var(--fg-dim)",approval:"var(--warn)",approved:"var(--accent)",rejected:"var(--danger)",stopped:"var(--danger)",open:"var(--info)","twin-approved":"var(--accent)","twin-denied":"var(--danger)"};function iq(){let e=function(){let[,e]=(0,a.useState)(0);return(0,a.useEffect)(()=>{let t=()=>{e(e=>e+1)};return window.addEventListener(iM,t),()=>{window.removeEventListener(iM,t)}},[]),window.__keikoActivity??[]}();return(0,n.jsxs)("div",{className:"tl",role:"log","aria-label":"Activity timeline",children:[0===e.length&&(0,n.jsxs)("div",{className:"tl-empty",children:["No activity yet.",(0,n.jsx)("br",{}),"Start an agent to see its actions stream here."]}),e.map((e,t)=>(0,n.jsxs)("div",{className:"tl-row",children:[(0,n.jsx)("span",{className:"tl-dot","aria-hidden":"true",style:{background:iD[e.type]??"var(--fg-faint)"}}),(0,n.jsxs)("div",{className:"tl-body",children:[(0,n.jsx)("span",{className:"visually-hidden",children:e.type}),(0,n.jsx)("span",{className:"tl-text",children:e.text}),(0,n.jsxs)("span",{className:"tl-meta mono",children:[e.agent??"workspace"," · ",new Date(e.time).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})]})]})]},t))]})}function iF({name:e,icon:t}){let a,l=t??("dockerfile"===(a=e.toLowerCase())||a.includes("docker-compose")||a.endsWith(".dockerignore")?"docker":a.endsWith(".json")?"json":a.endsWith(".yml")||a.endsWith(".yaml")?"yaml":a.endsWith(".md")?"markdown":a.endsWith(".properties")||a.endsWith(".env")||a.startsWith(".env.")?"properties":a.endsWith(".java")?"java":a.endsWith(".tsx")?"react":a.endsWith(".ts")?"typescript":a.endsWith(".jsx")||a.endsWith(".js")||a.endsWith(".mjs")||a.endsWith(".cjs")?"javascript":a.endsWith(".py")?"python":a.endsWith(".go")?"go":a.endsWith(".rs")?"rust":a.endsWith(".gradle")?"gradle":a.endsWith(".sql")?"postgresql":a.endsWith(".html")?"html5":a.endsWith(".css")?"css3":a.endsWith(".graphql")||a.endsWith(".gql")?"graphql":a.endsWith(".png")||a.endsWith(".jpg")||a.endsWith(".jpeg")||a.endsWith(".gif")||a.endsWith(".webp")||a.endsWith(".svg")?"image":null);return null!==l?(0,n.jsx)("img",{className:"fi-img",src:`/assets/icons/${l}.svg`,width:"15",height:"15",alt:""}):(0,n.jsx)("span",{className:"fi-fallback",children:(0,n.jsx)(j.Icons.file,{size:14})})}let iO={jsx:"js",js:"js",mjs:"js",ts:"ts",tsx:"ts",java:"java",kt:"kotlin",kts:"kotlin",py:"py",rb:"py",go:"go",rs:"rust",json:"json",yml:"yaml",yaml:"yaml",md:"md",markdown:"md",html:"html",xml:"html",css:"css",sql:"sql",sh:"sh",bash:"sh",cob:"cobol",cbl:"cobol",gradle:"js",graphql:"graphql",gql:"graphql",properties:"props",toml:"props",env:"props",dockerfile:"docker"};function iz(e){let t=e.toLowerCase();if(".env"===t||t.startsWith(".env."))return"props";if("dockerfile"===t||t.startsWith("dockerfile"))return"docker";if(t.includes("docker-compose"))return"yaml";let n=t.split("."),a=n.length>1?n[n.length-1]:void 0;return void 0===a?"code":iO[a]??"code"}let iK=new Set("const let var function return if else for while do switch case break continue import from export default class extends implements interface enum new async await yield of in typeof instanceof this super public private protected static final readonly void int long double float boolean char byte short val fun object data override companion package def pass lambda try catch except finally throw throws raise with as not and or is null nil None True False true false undefined struct impl trait pub use mod match where select insert update delete create table from join on group by order limit FROM RUN CMD ENV COPY WORKDIR EXPOSE ENTRYPOINT AS".split(" "));function iB(e){let t=[];return e.split(/(`[^`]+`|\*\*[^*]+\*\*)/).forEach(e=>{""!==e&&(e.startsWith("`")?t.push(["str",e]):e.startsWith("**")?t.push(["type",e]):t.push(["id",e]))}),t.length>0?t:[["id",e]]}function i_(e,t){if("md"===t)return e.split("\n").map(e=>{if(/^#{1,6}\s/.test(e))return[["head",e]];if(/^\s*```/.test(e))return[["com",e]];let t=/^(\s*)([-*+]|\d+\.)(\s)/.exec(e);return null!==t?[["ws",t[1]??""],["key",t[2]??""],["ws",t[3]??""],...iB(e.slice(t[0].length))]:iB(e)});if("json"===t)return e.split("\n").map(e=>{let t=[],n=0;for(;n<e.length;){let a=e.slice(n),l=/^"(?:[^"\\]|\\.)*"/.exec(a);if(null!==l){let a=e.slice(n+l[0].length),i=/^\s*:/.test(a);t.push([i?"key2":"str",l[0]]),n+=l[0].length;continue}let i=/^-?\d[\d.eE+\-]*/.exec(a);if(null!==i){t.push(["num",i[0]]),n+=i[0].length;continue}let r=/^(true|false|null)\b/.exec(a);if(null!==r){t.push(["lit",r[0]]),n+=r[0].length;continue}let s=/^\s+/.exec(a);if(null!==s){t.push(["ws",s[0]]),n+=s[0].length;continue}t.push(["punct",a.charAt(0)]),n+=1}return t});let n="py"===t||"sh"===t||"yaml"===t||"props"===t||"docker"===t?{line:"#",block:null}:"sql"===t?{line:"--",block:["/*","*/"]}:"cobol"===t?{line:"*>",block:null}:"html"===t?{line:null,block:["<!--","-->"]}:{line:"//",block:["/*","*/"]},a={inBlock:!1},l=[];for(let t of e.split("\n"))l.push(function(e,t,n){let a=[],l=0;if(t.inBlock&&null!==n.block){let i=e.indexOf(n.block[1]);if(-1===i)return a.push(["com",e]),a;a.push(["com",e.slice(0,i+n.block[1].length)]),l=i+n.block[1].length,t.inBlock=!1}for(;l<e.length;){let i=e.slice(l);if(null!==n.line&&i.startsWith(n.line)){a.push(["com",i]);break}if(null!==n.block&&i.startsWith(n.block[0])){let r=e.indexOf(n.block[1],l+n.block[0].length);if(-1===r){a.push(["com",i]),t.inBlock=!0;break}a.push(["com",e.slice(l,r+n.block[1].length)]),l=r+n.block[1].length;continue}let r=/^(?:"(?:[^"\\]|\\.)*"?|'(?:[^'\\]|\\.)*'?)/.exec(i);if(null!==r&&r[0].length>1){a.push(["str",r[0]]),l+=r[0].length;continue}if(/^\d/.test(i)){let e=/^\d[\w.]*/.exec(i),t=e?.[0]??i.charAt(0);a.push(["num",t]),l+=t.length;continue}let s=/^[@A-Za-z_$][\w$]*/.exec(i);if(null!==s){let t=s[0],n="id";iK.has(t)||iK.has(t.toLowerCase())?n="key":t.startsWith("@")||/^[A-Z]/.test(t)?n="type":"("===e.charAt(l+t.length)&&(n="fn"),a.push([n,t]),l+=t.length;continue}let o=/^\s+/.exec(i);if(null!==o){a.push(["ws",o[0]]),l+=o[0].length;continue}let c=/^[^\w\s$@"']+/.exec(i);if(null!==c){a.push(["punct",c[0]]),l+=c[0].length;continue}a.push(["id",i.charAt(0)]),l+=1}return a}(t,a,n));return l}let iU={docx:"DOCX",xlsx:"XLSX",pdf:"PDF"};function iW(e){if(!Number.isFinite(e)||e<=0)return"0 B";let t=["B","KB","MB","GB"],n=e,a=0;for(;n>=1024&&a<t.length-1;)n/=1024,a+=1;let l=0===a?n.toFixed(0):n.toFixed(n>=10?1:2);return`${l} ${t[a]}`}function iV(e){return new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}).format(new Date(e))}function iH({label:e,value:t}){return(0,n.jsxs)("div",{className:"fpv-meta-row",children:[(0,n.jsx)("span",{children:e}),(0,n.jsx)("strong",{children:t})]})}function iY({root:e,path:t,onClose:l,onOpenInEditor:i}){let[r,s]=(0,a.useState)(null),[o,c]=(0,a.useState)(!0),[d,u]=(0,a.useState)(null),[p,m]=(0,a.useState)(0),h=(0,a.useRef)(null);(0,a.useEffect)(()=>{h.current?.focus({preventScroll:!0})},[]),(0,a.useEffect)(()=>{let n=!1;return c(!0),u(null),s(null),(0,w.fetchFilesPreview)(e,t).then(e=>{n||s(e)}).catch(e=>{n||u(e instanceof w.ApiError&&"DENIED"===e.code?{message:"This file is excluded from the read surface for safety (matches a deny pattern such as .env, *.pem, node_modules, .git, …).",denied:!0}:e instanceof Error?{message:/^HTTP \d+$/.test(e.message)?"The file could not be loaded. Try again.":e.message,denied:!1}:{message:"Unable to read this file.",denied:!1})}).finally(()=>{n||c(!1)}),()=>{n=!0}},[t,e,p]);let f=d?.denied===!0,g=null!==r?"text"===r.kind?r.extension??"text":"image"===r.kind?r.mime:r.extension??"binary":f?"denied":null!==d?"error":"loading",v=f?"Hidden file":r?.name??(null!==d?"Preview unavailable":"Loading preview"),b=r?.kind==="text"&&r.content.length<=2e5,x=void 0!==i&&r?.kind==="text"&&!r.truncated,y=r?.kind==="text"?b?i_(r.content,iz(r.name)):r.content.split("\n").map(e=>[["id",e]]):[];return(0,n.jsxs)("div",{className:"fpv",onKeyDown:e=>{"Escape"===e.key&&(e.stopPropagation(),l())},children:[(0,n.jsxs)("div",{className:"fpv-bar",children:[(0,n.jsx)("button",{className:"fpv-back",type:"button",ref:h,onClick:l,title:"Back to files","aria-label":"Back to files",children:(0,n.jsx)(j.Icons.back,{size:15})}),(0,n.jsx)(iF,{name:f||null===r?"":r.name}),(0,n.jsx)("span",{className:"fpv-name",title:v,children:v}),(0,n.jsx)("span",{className:"fpv-lang mono",children:g}),(0,n.jsx)("span",{className:"spacer"}),x?(0,n.jsx)("button",{className:"fpv-back",type:"button",onClick:()=>i(e,t),title:"Open in editor","aria-label":"Open in editor",children:(0,n.jsx)(j.Icons.editor,{size:15})}):null,(0,n.jsx)("button",{className:"fpv-back",type:"button",onClick:l,title:"Close preview","aria-label":"Close preview",children:(0,n.jsx)(j.Icons.close,{size:15})})]}),o?(0,n.jsx)("div",{className:"fpv-state",role:"status",children:"Loading preview…"}):null,null!==d?(0,n.jsxs)("div",{className:"fpv-state fpv-error",role:"alert",children:[(0,n.jsx)("span",{children:d.message}),d.denied?null:(0,n.jsx)("button",{type:"button",className:"fpv-retry",onClick:()=>m(e=>e+1),children:"Retry"})]}):null,r?.kind==="text"?(0,n.jsxs)(n.Fragment,{children:[r.truncated?(0,n.jsxs)("div",{className:"fpv-banner",children:["Preview truncated at ",iW(r.maxBytes),". Larger files can't be shown in full here."]}):null,b?null:(0,n.jsx)("div",{className:"fpv-banner",children:"Syntax highlighting disabled for large previews."}),(0,n.jsx)("div",{className:"fpv-code mono",tabIndex:0,role:"region","aria-label":`File preview: ${r.name}`,style:{"--fpv-gutter-w":`max(44px, calc(${String(String(y.length).length)}ch + 16px))`},children:y.map((e,t)=>(0,n.jsxs)("div",{className:"fpv-line",children:[(0,n.jsx)("span",{className:"fpv-num",children:t+1}),(0,n.jsx)("span",{className:"fpv-src",children:e.map((e,t)=>(0,n.jsx)("span",{className:`hl-${e[0]}`,children:e[1]},t))})]},t))})]}):null,r?.kind==="image"?(0,n.jsxs)("div",{className:"fpv-image-pane",children:[(0,n.jsx)("div",{className:"fpv-image-card",children:(0,n.jsx)("img",{className:"fpv-image",src:r.dataUrl,alt:r.name})}),(0,n.jsxs)("div",{className:"fpv-meta",children:[(0,n.jsx)(iH,{label:"Type",value:r.mime}),(0,n.jsx)(iH,{label:"Size",value:iW(r.sizeBytes)}),(0,n.jsx)(iH,{label:"Modified",value:iV(r.modifiedAt)})]})]}):null,r?.kind==="binary"?(0,n.jsx)("div",{className:"fpv-meta-pane",children:(0,n.jsxs)("div",{className:"fpv-meta-card",children:[(0,n.jsx)(iF,{name:r.name}),(0,n.jsx)("h3",{children:r.name}),(0,n.jsx)("p",{children:function(e){if("too_large"===e.reason)return`Preview disabled because this file exceeds ${iW(e.maxBytes??0)}.`;let t=iU[function(e){let t=e.extension?.trim().toLowerCase();if(void 0!==t&&t.length>0)return t;let n=e.name.lastIndexOf(".");return n>=0?e.name.slice(n+1).trim().toLowerCase():""}(e)];if(void 0!==t)return`${t} files up to 2 MB are searchable in Repository Search via bounded text extraction when explicitly connected to a chat. Encrypted, scanned, or larger documents are not extracted — use Local Knowledge for those. No inline preview is available for this format here.`;return"No safe text or image preview is available for this file type."}(r)}),(0,n.jsxs)("div",{className:"fpv-meta",children:[(0,n.jsx)(iH,{label:"Type",value:r.mime}),(0,n.jsx)(iH,{label:"Extension",value:r.extension??"none"}),(0,n.jsx)(iH,{label:"Size",value:iW(r.sizeBytes)}),(0,n.jsx)(iH,{label:"Modified",value:iV(r.modifiedAt)})]})]})}):null]})}function iG(e){let t=e.replace(/[/\\]+$/,""),n=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"));return n<0?null:0===n?"/":/^[A-Za-z]:$/.test(t.slice(0,n))?`${t.slice(0,n)}\\`:t.slice(0,n)}function iJ(e){return 8+18*e}let iX=new Set(["ArrowDown","ArrowUp","ArrowRight","ArrowLeft","Home","End"]);function iQ({root:e,activeFilePath:t,openFilesDirectly:l=!1,onActiveFileChange:i,onRootChange:r,onOpenFile:s}){let o=e?.trim(),c=void 0!==o&&o.length>0?o:null,[d,u]=(0,a.useState)(null),p=c??d??"",[m,h]=(0,a.useState)(null),[f,g]=(0,a.useState)(""),[v,b]=(0,a.useState)(null),[x,y]=(0,a.useState)(null),[k,N]=(0,a.useState)({}),[S,C]=(0,a.useState)(()=>new Set([""])),[I,E]=(0,a.useState)(0),R=(0,a.useRef)(i);R.current=i;let $=(0,a.useRef)(null),A=(0,a.useRef)(null),T=(0,a.useId)();(0,a.useEffect)(()=>{if(null!==v)return;let e=A.current;if(null===e)return;A.current=null;let t=$.current?.querySelector(`.tr-file[data-path="${"u">typeof CSS&&"function"==typeof CSS.escape?CSS.escape(e):e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"]`);(t??$.current)?.focus({preventScroll:!0})},[v]),(0,a.useEffect)(()=>{if(null!==c)return;let e=!1;return(0,w.fetchProjects)().then(t=>{e||u(t.projects.find(e=>e.available)?.path??null)}).catch(()=>{e||u(null)}),()=>{e=!0}},[c]);let L=(0,a.useCallback)(async e=>{if(0===p.length)return void N(t=>({...t,[e]:{entries:[],truncated:!1,loading:!1,error:null,notice:"no-root"}}));N(t=>({...t,[e]:{entries:t[e]?.entries??[],truncated:t[e]?.truncated??!1,loading:!0,error:null,notice:null}}));try{let t=await (0,w.fetchFilesTree)(p,e);""===e&&(h(t.root),R.current?.(null,t.root,null),y(null)),N(n=>({...n,[e]:{entries:t.entries,truncated:t.truncated,loading:!1,error:null,notice:null}}))}catch(t){N(n=>({...n,[e]:{entries:n[e]?.entries??[],truncated:n[e]?.truncated??!1,loading:!1,error:t instanceof Error?t.message:"Unable to read this folder.",notice:null}}))}},[p]);(0,a.useEffect)(()=>{b(null),y(null),R.current?.(null,null,null),h(null),C(new Set([""])),N({}),L("")},[p,L,I]);let P=function(e,t){if(null===t||0===t.length)return e;let n=e.includes("\\")&&!e.includes("/")?"\\":"/";return`${e.replace(/[/\\]+$/u,"")}${n}${t.replace(/\//gu,n)}`}(m??(p.length>0?p:""),x);(0,a.useEffect)(()=>{g(P)},[P]);let M=(0,a.useCallback)(e=>{let t=e.trim();void 0===r||0===t.length||t!==P&&r(t)},[r,P]),D=(0,a.useCallback)(e=>{b(null),y(e),R.current?.(null,m??p,e),null!==e&&void 0===k[e]&&L(e)},[p,k,L,m]),q=(0,a.useCallback)(()=>{if(null!==x)return void D(function(e){let t=e.replace(/\/+$/u,""),n=t.lastIndexOf("/");if(n<0)return null;let a=t.slice(0,n);return a.length>0?a:null}(x));let e=iG(m??p);null!==e&&M(e)},[p,x,D,M,m]),F=(e,a,i=k[e])=>(0,n.jsxs)("div",{className:"tr-dir",role:0===a?void 0:"group",children:[i?.loading===!0?(0,n.jsx)("div",{className:"files-note",role:"status",style:{paddingLeft:iJ(a)+18},children:"Loading…"}):null,i?.notice==="no-root"?(0,n.jsx)("div",{className:"files-note",role:"status",style:{paddingLeft:iJ(a)+18},children:void 0!==r?"No folder is open yet. Enter a folder path above and press Open.":"No registered project is available."}):null,i?.error!==null&&i?.error!==void 0?(0,n.jsxs)("div",{className:"files-error",role:"alert",style:{marginLeft:iJ(a)},children:[(0,n.jsx)("span",{children:i.error}),(0,n.jsx)("button",{type:"button",className:"files-retry",onClick:()=>{L(e)},children:"Retry"})]}):null,i?.truncated===!0?(0,n.jsxs)("div",{className:"files-note files-warning",role:"status",style:{paddingLeft:iJ(a)+18},children:["Showing only the first ",i.entries.length," entries — this folder contains more."]}):null,i?.entries.map(e=>((e,a)=>{let i=iJ(a),r=S.has(e.path),o="This link can't be opened from this folder.";if("directory"===e.kind){let t=k[e.path];return(0,n.jsxs)("div",{className:"tr-row-wrap",children:[(0,n.jsxs)("div",{className:"tr-dir-line",style:{paddingLeft:i},children:[(0,n.jsx)("button",{className:"tr-caret-btn",type:"button",tabIndex:-1,disabled:!e.readable,"aria-label":`${r?"Collapse":"Expand"} folder: ${e.name}`,onClick:()=>(e=>{if(!e.readable)return;let t=S.has(e.path);C(t=>{let n=new Set(t);return n.has(e.path)?n.delete(e.path):n.add(e.path),n}),t||void 0!==k[e.path]||L(e.path)})(e),title:e.readable?`${r?"Collapse":"Expand"} ${e.path}`:o,children:(0,n.jsx)("span",{className:"tr-caret","data-open":r,children:(0,n.jsx)(j.Icons.chevronR,{size:11})})}),(0,n.jsxs)("button",{className:"tr-row tr-dir-enter",role:"treeitem","aria-level":a+1,"aria-selected":x===e.path,"data-active":x===e.path,"data-readable":e.readable,"data-path":e.path,type:"button","aria-disabled":!e.readable||void 0,"aria-describedby":e.readable?void 0:T,"aria-expanded":r,onClick:()=>{e.readable&&D(e.path)},title:e.readable?e.path:o,children:[(0,n.jsx)("span",{className:"fi-fallback",style:{color:"var(--accent)"},children:(0,n.jsx)(j.Icons.folder,{size:14})}),(0,n.jsx)("span",{className:"tr-name tr-folder",children:e.name}),e.symlink?(0,n.jsx)("span",{className:"tr-badge",children:"link"}):null]})]}),r?F(e.path,a+1,t):null]},e.path)}let c=v??t??null;return(0,n.jsxs)("button",{className:"tr-row tr-file",role:"treeitem","aria-level":a+1,"aria-selected":c===e.path,"data-active":c===e.path,"data-readable":e.readable,"data-path":e.path,style:{paddingLeft:i},type:"button","aria-disabled":!e.readable||void 0,"aria-describedby":e.readable?void 0:T,onClick:()=>{if(!e.readable)return;let t=m??p;if(l&&void 0!==s){R.current?.(e.path,t),s(t,e.path);return}b(e.path),R.current?.(e.path,t)},title:e.readable?e.path:o,children:[(0,n.jsx)("span",{className:"tr-caret tr-caret-ghost","aria-hidden":"true",children:(0,n.jsx)(j.Icons.chevronR,{size:11})}),(0,n.jsx)(iF,{name:e.name}),(0,n.jsx)("span",{className:"tr-name",children:e.name}),e.symlink?(0,n.jsx)("span",{className:"tr-badge",children:"link"}):null,(0,n.jsx)("span",{className:"tr-meta mono",children:function(e){if(!Number.isFinite(e)||e<=0)return"0 B";let t=["B","KB","MB","GB"],n=e,a=0;for(;n>=1024&&a<t.length-1;)n/=1024,a+=1;let l=0===a?n.toFixed(0):n.toFixed(n>=10?1:2);return`${l} ${t[a]}`}(e.sizeBytes)})]},e.path)})(e,a)),void 0===i||i.loading||null!==i.error||null!==i.notice||0!==i.entries.length?null:(0,n.jsx)("div",{className:"files-note",role:"status",style:{paddingLeft:iJ(a)+18},children:"Empty folder."})]});return null!==v?(0,n.jsx)(iY,{root:m??p,path:v,onOpenInEditor:s,onClose:()=>{A.current=v,b(null),R.current?.(null,m??p)}}):(0,n.jsxs)("div",{className:"files",ref:$,tabIndex:-1,children:[void 0!==r?(0,n.jsxs)("form",{className:"files-root-bar",role:"group","aria-label":"Folder root",onSubmit:e=>{e.preventDefault(),M(f)},children:[(0,n.jsx)("button",{type:"button",className:"files-root-up",onClick:q,disabled:null===x&&null===iG(m??p),title:"Open parent folder","aria-label":"Open parent folder",children:(0,n.jsx)(j.Icons.arrowUp,{size:13})}),(0,n.jsx)("input",{type:"text",className:"files-root-input mono","aria-label":"Folder path — open any folder on this machine",placeholder:"/path/to/any/folder",spellCheck:!1,value:f,onChange:e=>g(e.target.value)}),(0,n.jsx)("button",{type:"submit",className:"files-root-open",title:"Open this folder",children:"Open"})]}):null,(0,n.jsx)("button",{className:"files-refresh",type:"button",onClick:()=>E(e=>e+1),title:"Refresh folder","aria-label":"Refresh folder",children:(0,n.jsx)(j.Icons.reset,{size:13})}),(0,n.jsx)("span",{id:T,className:"visually-hidden",children:"This link can't be opened from this folder."}),(0,n.jsx)("div",{className:"tr files-tree",role:"tree","aria-label":"Files",tabIndex:-1,onKeyDown:e=>{if(!iX.has(e.key))return;let t=e.target,n=t instanceof HTMLElement?t.closest("button.tr-row"):null;if(null===n)return;let a=Array.from(e.currentTarget.querySelectorAll("button.tr-row")),l=a.indexOf(n);l<0||(e.preventDefault(),function(e,t,n){let a=e[t];if(void 0===a)return;let l=a.closest(".tr-row-wrap")?.querySelector("button.tr-caret-btn");if("ArrowDown"===n)e[t+1]?.focus();else if("ArrowUp"===n)e[t-1]?.focus();else if("Home"===n)e[0]?.focus();else if("End"===n)e[e.length-1]?.focus();else if("ArrowRight"===n){let n=a.getAttribute("aria-expanded");"false"===n?l?.click():"true"===n&&e[t+1]?.focus()}else"ArrowLeft"===n&&("true"===a.getAttribute("aria-expanded")?l?.click():function(e,t){let n=Number(e[t]?.getAttribute("aria-level")??"1");for(let a=t-1;a>=0;a-=1)if(Number(e[a]?.getAttribute("aria-level")??"1")<n)return void e[a]?.focus()}(e,t))}(a,l,e.key))},children:F(x??"",0)})]})}var iZ=e.i(70703);function i0(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function i1(e,t,n){return Math.min(n,Math.max(t,e))}function i2(e){return i1(Math.round(e),15,85)}function i4(e){if(!Array.isArray(e))return[];let t=[];for(let n of e)"string"==typeof n&&n.length>0&&!t.includes(n)&&t.push(n);return t}function i3(e,t,n){let a=[],l=e=>{e.length>0&&!a.includes(e)&&a.push(e)};for(let e of n??[])l(e);for(let e of t)l(e);return l(e),a}function i6(e,t,n){let a=i3(t,n);return{id:e,openFiles:a,activeFile:t.length>0?t:a[0]??"",tabOrder:a}}function i5(e,t){if(!i0(e))return null;let n="string"==typeof e.id&&e.id.length>0?e.id:t,a="string"==typeof e.activeFile?e.activeFile:"string"==typeof e.file?e.file:"",l=i6(n,a,i3(a,i4(e.openFiles),i4(e.tabOrder)));return l.openFiles.length>0||l.activeFile.length>0?l:null}function i8(e){return"column"===e?"column":"row"}function i7(e,t=[]){return"pane"===e.type?t.push(e.paneId):(i7(e.first,t),i7(e.second,t)),t}function i9(e,t){return"number"==typeof e.sidebarWidth&&Number.isFinite(e.sidebarWidth)?i1(e.sidebarWidth,t.minSidebarWidth,t.maxSidebarWidth):t.defaultSidebarWidth}function re(e,t,n){return"string"==typeof e.activePaneId&&void 0!==t[e.activePaneId]?e.activePaneId:n}function rt(e){return JSON.stringify({schemaVersion:2,root:e.root,activePaneId:e.activePaneId,tree:e.tree,panes:e.panes,sidebarWidth:Math.round(e.sidebarWidth),sidebarCollapsed:e.sidebarCollapsed})}function rn(e){return i7(e.tree)}function ra(e){return rn(e).map(t=>e.panes[t]).filter(e=>void 0!==e)}function rl(e){return e.panes[e.activePaneId]??ra(e)[0]??i6("pane-1","",[])}function ri(e,t,n){let a=e.panes[t];return void 0===a?e:{...e,panes:{...e.panes,[t]:n(a)}}}function rr(e,t){return e.filter(e=>e!==t)}function rs(e,t,n){let a=rr(e,t),l=void 0===n?a.length:i1(n,0,a.length);return[...a.slice(0,l),t,...a.slice(l)]}function ro(e,t,n){let a=i3(n,t);return{...e,openFiles:a,tabOrder:a,activeFile:n.length>0?n:a[0]??""}}function rc(e,t,n,a,l){let i=e.panes[t];if(void 0===i)return e;let r=a??i.activeFile;if(0===r.length)return e;let s=function(e){let t=Object.keys(e.panes).length+1;for(;void 0!==e.panes[`pane-${String(t)}`];)t+=1;return`pane-${String(t)}`}(e),o=i6(s,r,[r]),c={type:"split",id:function(e){let t=new Set,n=e=>{"split"===e.type&&(t.add(e.id),n(e.first),n(e.second))};n(e);let a=t.size+1;for(;t.has(`split-${String(a)}`);)a+=1;return`split-${String(a)}`}(e.tree),direction:n,ratio:50,first:{type:"pane",paneId:l?s:t},second:{type:"pane",paneId:l?t:s}};return{...e,activePaneId:s,tree:function e(t,n,a){return"pane"===t.type?t.paneId===n?a:t:{...t,first:e(t.first,n,a),second:e(t.second,n,a)}}(e.tree,t,c),panes:{...e.panes,[s]:o}}}function rd(e,t){if(void 0===e.panes[t]||rn(e).length<=1)return e;let n=function e(t,n){if("pane"===t.type)return t.paneId===n?null:t;let a=e(t.first,n),l=e(t.second,n);return null===a?l:null===l?a:{...t,first:a,second:l}}(e.tree,t);if(null===n)return e;let a={};for(let[n,l]of Object.entries(e.panes))n!==t&&(a[n]=l);let l=e.activePaneId===t?i7(n)[0]??e.activePaneId:e.activePaneId;return{...e,tree:n,panes:a,activePaneId:l}}function ru(e,t,n){let a=e.panes[t];if(!a?.openFiles.includes(n))return e;let l=a.tabOrder.indexOf(n),i=rr(a.openFiles,n);if(0===i.length)return rn(e).length>1?rd(e,t):ri(e,t,e=>ro(e,[],""));let r=a.activeFile===n?i[l]??i[l-1]??i[0]??"":a.activeFile;return ri(e,t,e=>ro(e,i,r))}function rp(e,t,n,a,l){if(t===n)return ri(e,n,e=>ro(e,rs(e.tabOrder,a,l),a));let i=e.panes[t],r=e.panes[n];if(void 0===i||void 0===r||!i.openFiles.includes(a))return e;let s=ru(e,t,a);return void 0===s.panes[n]?s:{...s=ri(s,n,e=>ro(e,rs(e.tabOrder,a,l),a)),activePaneId:n}}let rm=new Set(["open-file","select-file","close-tab","reorder-tab"]),rh=new Set(["close-pane","move-tab","drop-tab","split-pane"]);function rf(e,t){if(rm.has(t.type)){switch(t.type){case"open-file":return ri(e,t.paneId,e=>ro(e,i3(t.file,e.openFiles),t.file));case"select-file":return ri({...e,activePaneId:t.paneId},t.paneId,e=>e.openFiles.includes(t.file)?ro(e,e.openFiles,t.file):e);case"close-tab":return ru(e,t.paneId,t.file);case"reorder-tab":return ri(e,t.paneId,e=>e.openFiles.includes(t.file)?ro(e,rs(e.tabOrder,t.file,t.targetIndex),t.file):e)}return}return rh.has(t.type)?function(e,t){switch(t.type){case"close-pane":return rd(e,t.paneId);case"move-tab":return rp(e,t.fromPaneId,t.toPaneId,t.file,t.targetIndex);case"drop-tab":var n;return"center"===(n=t.intent).zone?rp(e,n.fromPaneId,n.toPaneId,n.file,n.targetIndex):rc(rp(e,n.fromPaneId,n.fromPaneId,n.file),n.toPaneId,"top"===n.zone||"bottom"===n.zone?"column":"row",n.file,"top"===n.zone||"left"===n.zone);case"split-pane":return rc(e,t.paneId,t.direction,t.file,!1)}}(e,t):function(e,t){switch(t.type){case"set-active-pane":return void 0===e.panes[t.paneId]?e:{...e,activePaneId:t.paneId};case"resize-split":return{...e,tree:function e(t,n,a){return"pane"===t.type?t:{...t,ratio:t.id===n?i2(a):t.ratio,first:e(t.first,n,a),second:e(t.second,n,a)}}(e.tree,t.splitId,t.ratio)};case"set-sidebar":return{...e,sidebarWidth:t.width??e.sidebarWidth,sidebarCollapsed:t.collapsed??e.sidebarCollapsed};case"replace-root":let n;return n=i6("pane-1","",[]),{schemaVersion:2,root:t.root,activePaneId:n.id,tree:{type:"pane",paneId:n.id},panes:{[n.id]:n},sidebarWidth:t.sidebarWidth??e.sidebarWidth,sidebarCollapsed:!1}}}(e,t)}function rg(e){let t=[];for(let n of ra(e))for(let e of n.openFiles)e.length>0&&!t.includes(e)&&t.push(e);return t}let rv=(0,iZ.default)(()=>e.A(37337),{loadableGenerated:{modules:[65890]},ssr:!1,loading:()=>(0,n.jsx)("div",{className:"ed-host-loading","aria-hidden":"true"})});function rb(e,t,n){return Math.min(n,Math.max(t,e))}function rx(e){return e.trim().replace(/\\/gu,"/").replace(/\/+$/u,"")}function ry(e,t){let n=t?.trim()??"";if(0===e.trim().length||0===n.length)return n;let a=rx(e),l=rx(n),i=a.toLowerCase(),r=l.toLowerCase();return r===i?"":r.startsWith(`${i}/`)?l.slice(a.length+1).replace(/^\/+/u,""):n}function rw(e,t,n){let a=[],l=t=>{let n=ry(e,t);0===n.length||a.includes(n)||a.push(n)};for(let e of n??[])l(e);return l(t),a}function rj(e,t){let n={};for(let[a,l]of Object.entries(t.panes))n[a]=function(e,t){let n=rw(e,t.activeFile,t.openFiles),a=ry(e,t.activeFile)||n[0]||"",l=rw(e,a,t.tabOrder);return{...t,openFiles:n,activeFile:a,tabOrder:l.length>0?l:n}}(e,l);return{...t,root:e,panes:n}}function rk(e){return rj(e.root,function(e){let t=function(e){if(void 0!==e.layoutJson&&e.layoutJson.trim().length>0)try{let t=JSON.parse(e.layoutJson);if(i0(t)){let n=t.schemaVersion??t.version,a=2===n||"2"===n?function(e,t,n){let a=function(e){if(!i0(e))return{};let t={};for(let[n,a]of Object.entries(e)){let e=i5(a,n);null!==e&&(t[e.id]=e)}return t}(t.panes),l=Object.keys(a)[0];if(void 0===l)return null;let i=function e(t,n){return i0(t)?("pane"===t.type&&"string"==typeof t.paneId&&void 0!==n[t.paneId]?{type:"pane",paneId:t.paneId}:null)??function(t,n){if("split"!==t.type)return null;let a=e(t.first,n),l=e(t.second,n);if(null===a||null===l)return null;let i="string"==typeof t.id&&t.id.length>0?t.id:"split-1",r="number"==typeof t.ratio&&Number.isFinite(t.ratio)?t.ratio:50;return{type:"split",id:i,direction:i8(t.direction),ratio:i2(r),first:a,second:l}}(t,n):null}(t.tree,a)??{type:"pane",paneId:l},r=function(e,t){let n={};for(let a of new Set(i7(e))){let e=t[a];void 0!==e&&(n[a]=e)}return n}(i,a);return{schemaVersion:2,root:e,activePaneId:re(t,r,i7(i)[0]??l),tree:i,panes:r,sidebarWidth:i9(t,n),sidebarCollapsed:!0===t.sidebarCollapsed}}(e.root,t,e):function(e,t,n){var a;let l=Array.isArray(a=t.panes)?a.map((e,t)=>i5(e,`pane-${String(t+1)}`)).filter(e=>null!==e):[];if(0===l.length)return null;let i={};for(let e of l)i[e.id]=e;let r=l[0];if(void 0===r)return null;let s=function(e,t,n){if(void 0===t)return{type:"pane",paneId:e.id};let a="number"==typeof n.splitRatio&&Number.isFinite(n.splitRatio)?i2(n.splitRatio):50;return{type:"split",id:"split-1",direction:i8(n.direction),ratio:a,first:{type:"pane",paneId:e.id},second:{type:"pane",paneId:t.id}}}(r,l[1],t);return{schemaVersion:2,root:e,activePaneId:re(t,i,r.id),tree:s,panes:i,sidebarWidth:i9(t,n),sidebarCollapsed:!0===t.sidebarCollapsed}}(e.root,t,e);if(null!==a)return a}}catch{}return null}(e);if(null!==t)return t;let n=i6("pane-1",e.file.length>0?e.file:e.openFiles[0]??"",e.openFiles);return{schemaVersion:2,root:e.root,activePaneId:n.id,tree:{type:"pane",paneId:n.id},panes:{[n.id]:n},sidebarWidth:e.defaultSidebarWidth,sidebarCollapsed:!1}}({root:e.root,file:e.file,openFiles:e.openFiles,layoutJson:e.layoutJson,defaultSidebarWidth:260,minSidebarWidth:180,maxSidebarWidth:440}))}function rN(e){let t=new Set;for(let n of Object.values(e))for(let e of Object.keys(n))t.add(e);return[...t]}function rS(e){let t="editor-dirty-close-title",l=(0,a.useRef)(null);return(0,a.useEffect)(()=>{l.current?.focus()},[]),(0,a.useEffect)(()=>{let t=t=>{"Escape"!==t.key||e.pending.saving||e.onCancel()};return document.addEventListener("keydown",t),()=>{document.removeEventListener("keydown",t)}},[e]),(0,n.jsx)("div",{className:"ed-dialog-backdrop",role:"presentation",children:(0,n.jsxs)("div",{className:"ed-dirty-dialog",ref:l,role:"dialog","aria-modal":"true","aria-labelledby":t,tabIndex:-1,children:[(0,n.jsx)("h2",{id:t,children:"Unsaved editor changes"}),(0,n.jsx)("p",{children:"Choose how to handle these files before continuing."}),(0,n.jsx)("ul",{children:e.pending.dirtyFiles.map(e=>(0,n.jsx)("li",{children:e},e))}),void 0!==e.pending.error?(0,n.jsx)("p",{role:"alert",children:e.pending.error}):null,(0,n.jsxs)("div",{className:"ed-dialog-actions",children:[(0,n.jsx)("button",{type:"button",className:"ed-save",onClick:e.onSave,disabled:e.pending.saving,children:e.pending.saving?"Saving...":"Save"}),(0,n.jsx)("button",{type:"button",className:"ed-reload",onClick:e.onDiscard,disabled:e.pending.saving,children:"Discard"}),(0,n.jsx)("button",{type:"button",className:"ed-icon-action",onClick:e.onCancel,disabled:e.pending.saving,children:"Cancel"})]})]})})}function rC({root:e,file:t,openFiles:l,layoutJson:i,onWorkspaceChange:r,...s}){let o=e?.trim()??"",c=ry(o,t),d=rw(o,c,l),u=rk({root:o,file:c,openFiles:d,layoutJson:i}),[p,m]=(0,a.useState)(o),[h,f]=(0,a.useState)(u),[g,v]=(0,a.useState)({}),[b,x]=(0,a.useState)(null),[y,w]=(0,a.useState)(null),[k,N]=(0,a.useState)(null),S=(0,a.useRef)(0),C=(0,a.useRef)(new Map),I=(0,a.useRef)(e?.trim()??""),E=(0,a.useRef)(null),R=(0,a.useCallback)((e,t)=>{var n;let a=rl(t);return{root:e,file:a.activeFile.length>0?a.activeFile:void 0,openFiles:(n=rg(t)).length>0?n:void 0,layoutJson:rt(t)}},[]),$=(0,a.useCallback)((e,t=p)=>{let n=rj(t,e);f(n),t.length>0&&r?.(R(t,n))},[R,r,p]);(0,a.useEffect)(()=>{let n=e?.trim()??"",a=ry(n,t),s=rw(n,a,l),o=rk({root:n,file:a,openFiles:s,layoutJson:i}),c=rl(o),d=rg(o),u=I.current!==n;if(I.current=n,m(n),f(o),u&&v({}),0===n.length||void 0===r)return;let p=(t?.trim()??"")!==c.activeFile,h=void 0===l?0!==d.length:!(l.length===d.length&&l.every((e,t)=>e===d[t])),g=i!==rt(o);(p||h||g)&&r(R(n,o))},[R,l,t,i,r,e]);let A=(0,a.useMemo)(()=>rN(g),[g]),T=rl(h),L=T.activeFile;(0,a.useEffect)(()=>{if(0===A.length)return;let e=e=>{e.preventDefault(),e.returnValue=""};return window.addEventListener("beforeunload",e),()=>{window.removeEventListener("beforeunload",e)}},[A.length]);let P=(0,a.useCallback)((e,t,n)=>{v(a=>{let l=a[e]??{};if(n)return!0===l[t]?a:{...a,[e]:{...l,[t]:!0}};if(!0!==l[t])return a;let{[t]:i,...r}=l;return{...a,[e]:r}})},[]),M=(0,a.useCallback)((e,t)=>{S.current+=1;let n=S.current;return $(rf(h,{type:"select-file",paneId:e,file:t})),N({id:n,paneId:e,file:t}),new Promise(e=>{C.current.set(n,e)})},[$,h]),D=(0,a.useCallback)((e,t,n,a)=>{let l=C.current.get(e);C.current.delete(e),k?.id===e&&N(null),a&&P(t,n,!1),l?.(a)},[P,k?.id]),q=(0,a.useCallback)(e=>{var t,n;let a,l=new Set(rN(g)),i="root-change"===e.reason||"window-close"===e.reason?e.files.filter(e=>l.has(e)):(t=e.paneId,n=e.files,a=g[t]??{},n.filter(e=>!0===a[e]));return 0===i.length?(e.apply(),!0):(x({intent:function(e){let t=[];for(let n of e.files)n.length>0&&!t.includes(n)&&t.push(n);return{paneId:e.paneId,files:t,reason:e.reason}}({paneId:e.paneId,files:i,reason:e.reason}),apply:e.apply,dirtyFiles:i,saving:!1}),!1)},[g]),F=(0,a.useCallback)(()=>{null===b||b.saving||(x({...b,saving:!0,error:void 0}),(async()=>{for(let e of b.dirtyFiles){let t=Object.entries(g).find(([,t])=>!0===t[e])?.[0]??b.intent.paneId;if(!await M(t,e))return void x({...b,saving:!1,error:"Save failed. The close action was not applied."})}b.apply(),x(null)})())},[g,b,M]),O=(0,a.useCallback)(()=>{if(null!==b&&!b.saving){for(let e of b.dirtyFiles)for(let[t,n]of Object.entries(g))!0===n[e]&&P(t,e,!1);b.apply(),x(null)}},[g,P,b]),z=(0,a.useCallback)(()=>{b?.saving!==!0&&x(null)},[b?.saving]),K=(0,a.useCallback)(e=>{let t=e.trim();0===t.length||q({paneId:rn(h)[0]??h.activePaneId,files:A,reason:"root-change",apply:()=>{let e=rf(h,{type:"replace-root",root:t,sidebarWidth:h.sidebarWidth});m(t),v({}),$(e,t)}})},[$,A,h,q]),B=(0,a.useCallback)((e,t)=>{let n=e.trim(),a=ry(n,t);if(0===n.length||0===a.length)return;let l=rf(h,{type:"open-file",paneId:T.id,file:a});m(n),$(l,n)},[$,T.id,h]),_=(0,a.useCallback)((e,t)=>{0!==p.length&&0!==t.length&&$(rf(h,{type:"select-file",paneId:e,file:t}))},[$,h,p]),U=(0,a.useCallback)(async(e,t)=>q({paneId:e,files:[t],reason:"tab-close",apply:()=>{P(e,t,!1),$(rf(h,{type:"close-tab",paneId:e,file:t}))}}),[$,h,P,q]),W=(0,a.useCallback)((e,t)=>{$(rf(h,{type:"split-pane",paneId:e,direction:t}))},[$,h]),V=(0,a.useCallback)(e=>{let t=h.panes[e];void 0!==t&&q({paneId:e,files:t.openFiles,reason:"pane-close",apply:()=>{v(t=>{let{[e]:n,...a}=t;return a}),$(rf(h,{type:"close-pane",paneId:e}))}})},[$,h,q]),H=(0,a.useCallback)(()=>{$(rf(h,{type:"set-sidebar",collapsed:!h.sidebarCollapsed}))},[$,h]),Y=(0,a.useCallback)(e=>{null===E.current||$(rf(h,{type:"set-sidebar",width:rb(e-E.current.getBoundingClientRect().left,180,440),collapsed:!1}))},[$,h]),G=(0,a.useCallback)(e=>{1===e.buttons&&Y(e.clientX)},[Y]),J=(0,a.useCallback)((e,t,n,a)=>{let l="row"===e.direction?(n-t.left)/t.width*100:(a-t.top)/t.height*100;$(rf(h,{type:"resize-split",splitId:e.id,ratio:rb(l,15,85)}))},[$,h]),X=(0,a.useCallback)(e=>{e.preventDefault();let t=e=>Y(e.clientX),n=()=>{window.removeEventListener("mousemove",t),window.removeEventListener("mouseup",n)};window.addEventListener("mousemove",t),window.addEventListener("mouseup",n,{once:!0})},[Y]),Q=(0,a.useCallback)((e,t)=>{t.preventDefault();let n=t.currentTarget.parentElement;if(null===n)return;let a=t=>J(e,n.getBoundingClientRect(),t.clientX,t.clientY),l=()=>{window.removeEventListener("mousemove",a),window.removeEventListener("mouseup",l)};window.addEventListener("mousemove",a),window.addEventListener("mouseup",l,{once:!0})},[J]),Z=(0,a.useCallback)(e=>{e.currentTarget.setPointerCapture(e.pointerId)},[]),ee=(0,a.useCallback)(e=>{e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId)},[]),et=(0,a.useCallback)((e,t,n)=>{if(!n.altKey)return;let a=h.panes[e];if(void 0!==a&&("ArrowLeft"===n.key||"ArrowRight"===n.key)){n.preventDefault();let l=rn(h);if(n.shiftKey){let a=l.indexOf(e),i="ArrowLeft"===n.key?l[a-1]:l[a+1];void 0!==i&&$(rf(h,{type:"move-tab",fromPaneId:e,toPaneId:i,file:t}));return}let i=a.tabOrder.indexOf(t);$(rf(h,{type:"reorder-tab",paneId:e,file:t,targetIndex:"ArrowLeft"===n.key?i-1:i+1}))}},[$,h]),en=(0,a.useCallback)((e,t,n)=>{n.preventDefault(),null!==y&&($(rf(h,{type:"drop-tab",intent:{fromPaneId:y.paneId,toPaneId:e,file:y.file,zone:t}})),w(null))},[$,y,h]);if(0===p.length)return(0,n.jsx)(rv,{...s});let ea=e=>{if("pane"===e.type){let t,a,l=h.panes[e.paneId];return void 0===l?null:(t=ra(h).map(e=>({paneId:e.id,activeFile:e.activeFile.length>0?e.activeFile:null,openFiles:e.openFiles})),a={...s,root:p,...l.activeFile.length>0?{file:l.activeFile}:{},openFiles:l.openFiles,dirtyFiles:A,windowId:`${s.windowId??"editor"}-${l.id}`,paneId:l.id,layoutPanes:t,activePaneId:h.activePaneId,onSelectOpenFile:e=>_(l.id,e),onCloseOpenFile:e=>U(l.id,e),onDirtyChange:(e,t)=>P(l.id,e,t),toolbarExtras:(0,n.jsxs)("span",{className:"ed-pane-actions","aria-label":"Editor split controls",children:[(0,n.jsx)("button",{type:"button",className:"ed-icon-action","aria-label":`Split ${l.activeFile||"editor"} right`,title:"Split right",onClick:()=>W(l.id,"row"),children:(0,n.jsx)(j.Icons.split,{size:14})}),(0,n.jsx)("button",{type:"button",className:"ed-icon-action","aria-label":`Split ${l.activeFile||"editor"} down`,title:"Split down",onClick:()=>W(l.id,"column"),children:(0,n.jsx)(j.Icons.tile,{size:14})}),rn(h).length>1?(0,n.jsx)("button",{type:"button",className:"ed-icon-action","aria-label":`Close split ${l.activeFile||"editor"}`,title:"Close split",onClick:()=>V(l.id),children:(0,n.jsx)(j.Icons.close,{size:14})}):null]}),externalSaveRequest:null!==k&&k.paneId===l.id?k:void 0,onExternalSaveComplete:D},(0,n.jsxs)("section",{className:"ed-pane","data-active":l.id===h.activePaneId?"true":"false","data-dragging":null===y?"false":"true",children:[(0,n.jsx)("div",{className:"ed-pane-drop-zones","aria-hidden":"true",children:["left","right","top","bottom","center"].map(e=>(0,n.jsx)("button",{type:"button",className:`ed-pane-drop-zone ${e}`,tabIndex:-1,"aria-label":`Drop tab ${e}`,onDragOver:e=>e.preventDefault(),onDrop:t=>en(l.id,e,t)},e))}),(0,n.jsx)(rv,{...a,renderTabHandle:(e,t,n)=>({draggable:!0,onDragStart:t=>{t.dataTransfer.effectAllowed="move",t.dataTransfer.setData("text/plain",e),w({paneId:l.id,file:e})},onDragEnd:()=>w(null),onKeyDown:t=>et(l.id,e,t),"data-active":t?"true":"false","data-dirty":n?"true":"false"})})]},l.id))}return(0,n.jsxs)("div",{className:`ed-panes ${e.direction}`,"data-split-id":e.id,style:{"--ed-split-ratio":`${String(e.ratio)}%`},children:[ea(e.first),(0,n.jsx)("button",{type:"button",className:"ed-pane-resizer","aria-label":"Resize editor split",title:"Resize editor split",onPointerDown:Z,onPointerMove:t=>{if(1!==t.buttons)return;let n=t.currentTarget.parentElement;null!==n&&J(e,n.getBoundingClientRect(),t.clientX,t.clientY)},onPointerUp:ee,onPointerCancel:ee,onMouseDown:t=>Q(e,t)}),ea(e.second)]})},el=1===rn(h).length;return(0,n.jsxs)("div",{className:`editor-workspace${h.sidebarCollapsed?" sidebar-collapsed":""}`,ref:E,style:{"--ed-sidebar-width":`${String(h.sidebarWidth)}px`},children:[h.sidebarCollapsed?(0,n.jsx)("button",{type:"button",className:"ed-sidebar-restore","aria-label":"Show project tree",title:"Show project tree",onClick:H,children:(0,n.jsx)(j.Icons.sidebar,{size:15})}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("aside",{className:"ed-sidebar","aria-label":"Editor files",children:[(0,n.jsx)("div",{className:"ed-sidebar-chrome",children:(0,n.jsx)("button",{type:"button",className:"ed-icon-action","aria-label":"Hide project tree",title:"Hide project tree",onClick:H,children:(0,n.jsx)(j.Icons.sidebar,{size:14})})}),(0,n.jsx)(iQ,{root:p,activeFilePath:L.length>0?L:void 0,openFilesDirectly:!0,onRootChange:K,onOpenFile:B})]}),(0,n.jsx)("button",{type:"button",className:"ed-sidebar-resizer","aria-label":"Resize project tree",title:"Resize project tree",onPointerDown:Z,onPointerMove:G,onPointerUp:ee,onPointerCancel:ee,onMouseDown:X})]}),(0,n.jsx)("div",{className:"ed-main",children:(0,n.jsx)("div",{className:`ed-panes ed-panes-root${el?" single":""}`,children:ea(h.tree)})}),null!==b?(0,n.jsx)(rS,{pending:b,onSave:F,onDiscard:O,onCancel:z}):null]})}async function rI(e,t){let n=(t?.method??"GET").toUpperCase(),a="GET"!==n&&"HEAD"!==n,l=await fetch(e,{...t,headers:{Accept:"application/json",...a?{"Content-Type":"application/json"}:{},...a?{"X-Keiko-CSRF":"1"}:{},...t?.headers??{}}});if(!l.ok){let e="INTERNAL",t=`HTTP ${l.status.toString()}`;try{let n=await l.json();e=n.error.code,t=n.error.message}catch{}throw new w.ApiError(e,t,l.status)}if(204!==l.status)return l.json()}async function rE(e){return rI(`/api/browser/status?port=${encodeURIComponent(String(e))}`)}async function rR(e){return rI("/api/browser/sessions",{method:"POST",body:JSON.stringify({port:e})})}async function r$(e){await rI(`/api/browser/sessions/${encodeURIComponent(e)}`,{method:"DELETE"})}async function rA(e,t){return rI(`/api/browser/sessions/${encodeURIComponent(e)}/navigate`,{method:"POST",body:JSON.stringify({url:t})})}async function rT(e){return rI(`/api/browser/sessions/${encodeURIComponent(e)}/screenshot`,{method:"POST",body:JSON.stringify({})})}async function rL(e,t){return rI(`/api/browser/sessions/${encodeURIComponent(e)}/apply`,{method:"POST",body:JSON.stringify({captureSeq:t})})}async function rP(e){return rI(`/api/browser/sessions/${encodeURIComponent(e)}/content`,{method:"POST",body:JSON.stringify({})})}function rM(e){return e instanceof w.ApiError?{code:e.code,message:e.message}:e instanceof Error?{code:"INTERNAL",message:e.message}:{code:"INTERNAL",message:"Unexpected error."}}function rD(e){let t=e.cdpPort??9222,l=e.url??"http://localhost:5173",[i,r]=(0,a.useState)(String(t)),[s,o]=(0,a.useState)(l),[c,d]=(0,a.useState)(null),[u,p]=(0,a.useState)(null),[m,h]=(0,a.useState)(!1),[f,g]=(0,a.useState)(null),[v,b]=(0,a.useState)(null),[x,y]=(0,a.useState)([]),[w,j]=(0,a.useState)(null),[k,N]=(0,a.useState)(null),[S,C]=(0,a.useState)(null),I=(0,a.useRef)(null),E=(0,a.useCallback)(()=>{b(null)},[]),R=(0,a.useCallback)(e=>{y(t=>{let n=[...t,e];return n.length>50?n.slice(n.length-50):n}),"navigated"===e.kind&&"string"==typeof e.payload.originOnly&&C(e.payload.originOnly),"error"===e.kind&&b({code:"string"==typeof e.payload.code?e.payload.code:"INTERNAL",message:"string"==typeof e.payload.message?e.payload.message:"Error."})},[]);(0,a.useEffect)(()=>{var e;if(null===c){I.current?.close(),I.current=null;return}let t=new EventSource((e=c.sessionId,`/api/browser/sessions/${encodeURIComponent(e)}/events`));for(let e of["session-opened","navigated","screenshot-captured","page-content-captured","session-closed","trust-warning","error"])t.addEventListener(`browser:${e}`,e=>{try{let t=JSON.parse(e.data);R(t)}catch{}});return I.current=t,()=>{t.close(),I.current=null}},[c,R]);let $=(0,a.useCallback)(async()=>{E(),h(!0);try{let e=Number.parseInt(i,10),t=await rE(e);p(t)}catch(e){b(rM(e))}finally{h(!1)}},[i,E]),A=(0,a.useCallback)(async()=>{E(),h(!0);try{let e=Number.parseInt(i,10),t=await rR(e);d(t),y([]),N(null),C(null)}catch(e){b(rM(e))}finally{h(!1)}},[i,E]),T=(0,a.useCallback)(async()=>{if(null!==c){E(),h(!0);try{await r$(c.sessionId),d(null),j(null),N(null),C(null)}catch(e){b(rM(e))}finally{h(!1)}}},[c,E]),L=(0,a.useCallback)(async()=>{if(null!==c){E(),h(!0);try{let e=await rA(c.sessionId,s);C(e.originOnly)}catch(e){b(rM(e))}finally{h(!1)}}},[c,s,E]),P=(0,a.useCallback)(async()=>{if(null!==c){E(),h(!0);try{let e=await rT(c.sessionId);e.persisted||j({seq:e.seq,dataBase64:e.dataBase64})}catch(e){b(rM(e))}finally{h(!1)}}},[c,E]),M=(0,a.useCallback)(async()=>{if(null!==c&&null!==w){E(),h(!0);try{let e=await rL(c.sessionId,w.seq);e.persisted&&N(e.path),j(null)}catch(e){b(rM(e))}finally{h(!1)}}},[c,w,E]),D=(0,a.useCallback)(async()=>{if(null!==c){E(),h(!0);try{await rP(c.sessionId)}catch(e){b(rM(e))}finally{h(!1)}}},[c,E]),q=(0,a.useMemo)(()=>m||null!==c,[m,c]),F=(0,a.useMemo)(()=>m||null===c,[m,c]),O=m||null!==c,z=m||null===w,K=m&&null!==f?f:null!==w?"Screenshot ready (dry-run) — press Apply to persist.":null!==k?`Persisted as ${k}.`:null!==S?`Current origin: ${S}`:null!==u&&null===c?`Reachable: ${u.reachable?"yes":"no"}`:"";return(0,n.jsxs)("div",{className:"browser",children:[(0,n.jsxs)("div",{className:"bw-bar",children:[(0,n.jsx)("span",{className:"bw-dot",style:{background:null===c?"var(--line-strong)":"var(--ok)"},"aria-hidden":"true"}),(0,n.jsxs)("label",{className:"bw-field",children:[(0,n.jsx)("span",{className:"bw-field-label",children:"Port"}),(0,n.jsx)("input",{type:"text",inputMode:"numeric",className:"bw-input",value:i,onChange:e=>r(e.target.value),disabled:null!==c||m})]}),(0,n.jsxs)("label",{className:"bw-field bw-field-url",children:[(0,n.jsx)("span",{className:"bw-field-label",children:"URL"}),(0,n.jsx)("input",{type:"url",className:"bw-input bw-input-url",value:s,onChange:e=>o(e.target.value),disabled:m})]})]}),(0,n.jsxs)("div",{className:"bw-actions",role:"group","aria-label":"Browser actions",children:[(0,n.jsx)("button",{type:"button",className:"bw-btn",onClick:()=>{O||(g("Checking Chrome…"),$())},"aria-disabled":O,children:"Check"}),(0,n.jsx)("button",{type:"button",className:"bw-btn bw-btn-primary",onClick:()=>{q||(g("Opening session…"),A())},"aria-disabled":q,children:"Open session"}),(0,n.jsx)("button",{type:"button",className:"bw-btn",onClick:()=>{F||(g("Navigating…"),L())},"aria-disabled":F,children:"Navigate"}),(0,n.jsx)("button",{type:"button",className:"bw-btn",onClick:()=>{F||(g("Capturing screenshot…"),P())},"aria-disabled":F,children:"Screenshot"}),(0,n.jsx)("button",{type:"button",className:"bw-btn",onClick:()=>{z||(g("Applying screenshot…"),M())},"aria-disabled":z,children:"Apply"}),(0,n.jsx)("button",{type:"button",className:"bw-btn",onClick:()=>{F||(g("Capturing HTML…"),D())},"aria-disabled":F,children:"Capture HTML"}),(0,n.jsx)("button",{type:"button",className:"bw-btn bw-btn-danger",onClick:()=>{F||(g("Closing session…"),T())},"aria-disabled":F,children:"Close"})]}),(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite",children:K}),m&&null!==f?(0,n.jsx)("p",{className:"bw-status",children:f}):null,null!==u&&null===c?(0,n.jsxs)("p",{className:"bw-status",children:["Reachable: ",u.reachable?"yes":"no",null===u.browserVersion?"":` — ${u.browserVersion}`]}):null,null!==S?(0,n.jsxs)("p",{className:"bw-status",children:["Current origin: ",(0,n.jsx)("span",{className:"mono",children:S})]}):null,null!==w?(0,n.jsx)("p",{className:"bw-status",children:"Screenshot ready (dry-run) — press Apply to persist."}):null,null!==k?(0,n.jsxs)("p",{className:"bw-status",children:["Persisted as ",(0,n.jsx)("span",{className:"mono",children:k}),"."]}):null,null!==v?(0,n.jsxs)("div",{className:"bw-error",role:"alert",children:[v.message," ",(0,n.jsxs)("span",{className:"err-code mono",children:["(",v.code,")"]})]}):null,(0,n.jsx)("div",{className:"bw-view",children:null!==w?(0,n.jsx)("img",{className:"bw-screenshot",src:`data:image/png;base64,${w.dataBase64}`,alt:"Pending screenshot preview"}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"ph-stripes","aria-hidden":"true"}),(0,n.jsx)("div",{className:"bw-overlay mono",children:null===c?"No session — choose a port and press Open session":"Session open — use Screenshot to capture a preview"})]})}),(0,n.jsx)("div",{className:"bw-log",role:"log","aria-label":"Browser event log",children:(0,n.jsx)("ul",{className:"bw-log-list",children:x.slice(-10).reverse().map((e,t)=>(0,n.jsxs)("li",{className:"bw-log-item",children:[(0,n.jsx)("span",{className:"bw-log-kind",children:function(e){switch(e){case"session-opened":return"session opened";case"navigated":return"navigated";case"screenshot-captured":return"screenshot captured";case"page-content-captured":return"content captured";case"session-closed":return"session closed";case"trust-warning":return"trust warning";case"error":return"error"}}(e.kind)}),(0,n.jsx)("span",{className:"bw-log-detail mono",children:function(e){let t=e.payload;if("navigated"===e.kind){let e="string"==typeof t.originOnly?t.originOnly:"",n="number"==typeof t.httpStatus?` (${String(t.httpStatus)})`:"";return`${e}${n}`}return"screenshot-captured"===e.kind?!0===t.persisted?"persisted":"dry-run":"page-content-captured"===e.kind?"number"==typeof t.byteLength?`${String(t.byteLength)} bytes`:"":"error"===e.kind||"trust-warning"===e.kind?"string"==typeof t.message?t.message:"string"==typeof t.warning?t.warning:"":""}(e)})]},`${String(e.kind)}-${String(t)}`))})})]})}async function rq(e,t){let n=(t?.method??"GET").toUpperCase(),a="GET"!==n&&"HEAD"!==n,l=await fetch(e,{...t,headers:{Accept:"application/json",...a?{"Content-Type":"application/json"}:{},...a?{"X-Keiko-CSRF":"1"}:{},...t?.headers??{}}});if(!l.ok){let e="INTERNAL",t=`HTTP ${l.status.toString()}`;try{let n=await l.json();e=n.error.code,t=n.error.message}catch{}throw new w.ApiError(e,t,l.status)}if(204!==l.status)return l.json()}async function rF(){return rq("/api/terminal/policy")}async function rO(e,t){let n=new URLSearchParams;return n.set("projectId",e),void 0!==t&&t.length>0&&n.set("path",t),rq(`/api/terminal/directories?${n.toString()}`)}async function rz(e){return rq("/api/terminal/executions",{method:"POST",body:JSON.stringify(e)})}async function rK(e){await rq(`/api/terminal/executions/${encodeURIComponent(e)}`,{method:"DELETE"})}function rB(e){return e instanceof w.ApiError?{code:e.code,message:e.message}:e instanceof Error?{code:"INTERNAL",message:e.message}:{code:"INTERNAL",message:"Unexpected error."}}function r_(e){let[t,l]=(0,a.useState)(null),[i,r]=(0,a.useState)(""),[s,o]=(0,a.useState)(""),[c,d]=(0,a.useState)(e.cwd??""),[u,p]=(0,a.useState)(e.projectPath??""),[m,h]=(0,a.useState)(!1),[f,g]=(0,a.useState)(null),[v,b]=(0,a.useState)(null),[x,y]=(0,a.useState)(null),[w,j]=(0,a.useState)([]),k=(0,a.useRef)(null),N=(0,a.useRef)(!1),S=(0,a.useRef)(null),[C,I]=(0,a.useState)([]);(0,a.useEffect)(()=>{let e=!1;return rF().then(t=>{e||(l(t),r(e=>e.length>0?e:t.commands[0]??""))}).catch(t=>{e||y(rB(t))}),()=>{e=!0}},[]),(0,a.useEffect)(()=>{if(0===u.length)return void I([]);let e=!1;return rO(u,c.length>0?c:void 0).then(t=>{e||I(t.entries)}).catch(()=>{e||I([])}),()=>{e=!0}},[u,c]),(0,a.useEffect)(()=>{let e=new EventSource("/api/terminal/events");k.current=e;let t=e=>{try{let t=JSON.parse(e.data);if("execution-started"===t.kind&&N.current){let e=t.payload;"string"==typeof e.requestId&&e.requestId===S.current&&g(e=>null!==e?e:t.executionId)}if("execution-completed"===t.kind||"execution-failed"===t.kind||"execution-cancelled"===t.kind){let e=t.payload;"string"==typeof e.requestId&&e.requestId===S.current&&g(e=>null===e||e!==t.executionId?e:null)}j(e=>{let n=[t,...e];return n.length>30?n.slice(0,30):n})}catch{}};for(let n of["execution-started","execution-completed","execution-failed","execution-cancelled"])e.addEventListener(`terminal:${n}`,t);return()=>{e.close(),k.current=null}},[]);let E=(0,a.useCallback)(async e=>{let t;if(e.preventDefault(),m)return;y(null),b(null),g(null);let n="function"==typeof crypto.randomUUID?crypto.randomUUID():`terminal-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;S.current=n;let a=0===(t=s.trim()).length?[]:t.split(/\s+/);N.current=!0,h(!0);try{let e={projectId:u,command:i,args:a,...c.length>0?{cwd:c}:{},requestId:n},t=await rz(e);b(t)}catch(e){y(rB(e))}finally{N.current=!1,h(!1),S.current=null,g(null)}},[s,i,c,u,m]),R=(0,a.useCallback)(async()=>{if(null!==f)try{await rK(f)}catch(e){y(rB(e))}},[f]),$=(0,a.useMemo)(()=>t?.limits??null,[t]),A=(0,a.useRef)(null),T=(0,a.useRef)(!1);return(0,a.useEffect)(()=>{T.current&&!m&&document.activeElement===document.body&&A.current?.focus(),T.current=m},[m]),(0,n.jsxs)("div",{className:"terminal",children:[(0,n.jsxs)("form",{className:"tm-form",onSubmit:e=>void E(e),children:[(0,n.jsxs)("label",{className:"tm-field",children:[(0,n.jsx)("span",{children:"Project path"}),(0,n.jsx)("input",{type:"text",value:u,onChange:e=>p(e.target.value),placeholder:"/absolute/path/to/project",required:!0})]}),(0,n.jsxs)("div",{className:"tm-field",children:[(0,n.jsx)("span",{children:"Command"}),(0,n.jsx)(tz,{value:i,ariaLabel:"Command",disabled:null===t,menuTitle:"Allowed commands",mono:!0,sections:[{options:t?.commands.map(e=>({value:e,label:e}))??[]}],onValueChange:r})]}),(0,n.jsxs)("label",{className:"tm-field",children:[(0,n.jsx)("span",{children:"Args (space-separated)"}),(0,n.jsx)("input",{type:"text",value:s,onChange:e=>o(e.target.value),placeholder:"e.g. -la src"})]}),(0,n.jsxs)("label",{className:"tm-field",children:[(0,n.jsx)("span",{children:"Working directory (optional)"}),(0,n.jsx)("input",{type:"text",value:c,onChange:e=>d(e.target.value),placeholder:"(project root)",list:"tm-cwd-suggestions"}),(0,n.jsx)("datalist",{id:"tm-cwd-suggestions",children:C.map(e=>(0,n.jsx)("option",{value:e.path},e.path))})]}),(0,n.jsxs)("div",{className:"tm-actions",children:[(0,n.jsx)("button",{type:"submit",className:"tm-action","data-primary":"true",ref:A,disabled:null===t,"aria-disabled":m||null===t,children:m?"Running…":"Run"}),m?(0,n.jsx)("button",{type:"button",className:"tm-action","aria-disabled":null===f,onClick:()=>void R(),children:"Cancel"}):null]}),null!==$?(0,n.jsxs)("p",{className:"tm-limits",children:["Limits: ",(0,aq.formatBytes)($.maxOutputBytes)," output ·"," ",(0,aq.formatMs)($.defaultTimeoutMs)," timeout"]}):null]}),null!==x?(0,n.jsxs)("div",{className:"tm-error",role:"alert",children:[(0,n.jsxs)("span",{className:"tm-error-text",children:[x.message," ",(0,n.jsxs)("span",{className:"err-code mono",children:["(",x.code,")"]})]}),(0,n.jsx)("button",{type:"button",className:"tm-error-dismiss","aria-label":"Dismiss error",onClick:()=>y(null),children:"✕"})]}):null,(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite",children:null!==v?`Command finished: exit ${String(v.exitCode)}, ${String(v.durationMs)} ms${v.truncated?", output truncated":""}${v.timedOut?", timed out":""}`:""}),null!==v?(0,n.jsxs)("div",{className:"tm-result",children:[(0,n.jsxs)("div",{className:"tm-badges",children:[(0,n.jsxs)("span",{className:0===v.exitCode?"tm-badge tm-badge-ok":"tm-badge tm-badge-fail",children:["exit ",String(v.exitCode)]}),(0,n.jsxs)("span",{className:"tm-badge",children:[v.durationMs," ms"]}),v.truncated?(0,n.jsx)("span",{className:"tm-badge tm-badge-warn",children:"truncated"}):null,v.timedOut?(0,n.jsx)("span",{className:"tm-badge tm-badge-warn",children:"timed out"}):null]}),v.stdout.length>0?(0,n.jsx)("pre",{className:"tm-stdout",children:v.stdout}):null,v.stderr.length>0?(0,n.jsx)("pre",{className:"tm-stderr",children:v.stderr}):null]}):null,(0,n.jsx)("ul",{className:"tm-events",role:"log","aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false","aria-label":"Recent terminal events",children:w.map((e,t)=>{var a;let l;return(0,n.jsxs)("li",{className:"tm-event",children:[(0,n.jsx)("span",{className:"tm-event-kind",children:function(e){switch(e){case"execution-started":return"started";case"execution-completed":return"completed";case"execution-failed":return"failed";case"execution-cancelled":return"cancelled"}}(e.kind)}),(0,n.jsx)("span",{className:"tm-event-detail",children:(l=(a=e).payload,"execution-completed"===a.kind?["number"==typeof l.exitCode||null===l.exitCode?`exit ${String(l.exitCode)}`:"","number"==typeof l.durationMs?`${String(l.durationMs)}ms`:""].filter(Boolean).join(" · "):"execution-failed"===a.kind?"string"==typeof l.code?l.code:"":"execution-started"===a.kind&&"string"==typeof l.command?l.command:"")})]},`${e.executionId}-${String(t)}-${e.kind}`)})})]})}function rU(e){return e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function rW(e){return e instanceof w.ApiError?{code:e.code,message:e.message}:e instanceof Error?{code:"INTERNAL",message:e.message}:{code:"INTERNAL",message:"Unexpected error."}}function rV(e){return("dry-run"===e.status||"fix-proposed"===e.status)&&void 0!==e.proposedDiff&&void 0===e.appliedAt}function rH(e){return void 0!==e.proposedDiff&&""!==e.proposedDiff}function rY({href:e,hasManifest:t,error:a}){return t?(0,n.jsx)("a",{className:"rv-evidence-link",href:e,target:"_blank",rel:"noopener noreferrer",children:"Evidence"}):null!==a?(0,n.jsxs)("span",{className:"rv-evidence-link rv-evidence-error",role:"alert",children:["Evidence error: ",a.message]}):(0,n.jsx)("button",{type:"button",className:"rv-evidence-link rv-evidence-disabled",disabled:!0,children:"Evidence"})}function rG({tokens:e}){return(0,n.jsx)(n.Fragment,{children:e.map((e,t)=>(0,n.jsx)("span",{className:`hl-${e[0]}`,children:e[1]},t))})}function rJ({line:e,lang:t}){let a,l="add"===e.kind?"+":"del"===e.kind?"−":"ctx"===e.kind?"·":"",i="ctx"===e.kind?"":` rv-${e.kind}`;if("meta"!==e.kind&&"code"!==t){let l=i_(e.text,iz(t))[0]??[];a=(0,n.jsx)(rG,{tokens:l})}else a=e.text;return(0,n.jsxs)("div",{className:`rv-line${i}`,children:[(0,n.jsx)("span",{className:"rv-sr-only",children:{add:"Added line",del:"Deleted line",ctx:"Context line",meta:"Diff metadata"}[e.kind]}),(0,n.jsx)("span",{className:"rv-num-old rv-num",children:e.oldLine??""}),(0,n.jsx)("span",{className:"rv-num-new rv-num",children:e.newLine??""}),(0,n.jsx)("span",{className:"rv-gutter","aria-hidden":"true",children:l}),(0,n.jsx)("code",{className:"rv-src",children:a})]})}function rX({hunk:e,lang:t}){return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"rv-hunk mono","aria-label":`Hunk header ${e.header}`,children:[(0,n.jsx)("span",{className:"rv-sr-only",children:"Hunk header"}),e.header]}),e.lines.map((e,a)=>(0,n.jsx)(rJ,{line:e,lang:t},a))]})}function rQ({file:e,index:t,changedFiles:a,sectionRef:l}){let i=a.find(t=>t.path===e.path),r=e.path.includes(".")?e.path.split(".").pop()??"code":"code";return(0,n.jsxs)("section",{id:`rv-file-${t}`,"aria-labelledby":`rv-file-${t}-h`,ref:l,children:[(0,n.jsxs)("h3",{id:`rv-file-${t}-h`,className:"rv-file mono",children:[(0,n.jsx)("span",{className:"rv-path",children:e.path}),void 0!==e.oldPath&&(0,n.jsxs)("span",{className:"rv-oldpath",children:[" (was ",e.oldPath,")"]}),(0,n.jsx)("span",{className:"spacer"}),(0,n.jsxs)("span",{className:"rv-stat add",children:["+",e.addedLines]}),(0,n.jsxs)("span",{className:"rv-stat del",children:["−",e.removedLines]}),i?.elevatedReview===!0&&(0,n.jsx)("span",{className:"rv-elevated","aria-label":"Elevated review",children:"!"})]}),(0,n.jsx)("div",{className:"rv-code mono",children:e.hunks.map((e,t)=>(0,n.jsx)(rX,{hunk:e,lang:r},t))})]})}function rZ({runId:e,onRunIdSubmit:t}){let[l,i]=(0,a.useState)(null),[r,s]=(0,a.useState)(!1),[o,c]=(0,a.useState)(null),[d,u]=(0,a.useState)(!1),[p,m]=(0,a.useState)(null),[h,f]=(0,a.useState)(!1),[g,v]=(0,a.useState)(null),[b,x]=(0,a.useState)(null),[y,j]=(0,a.useState)(""),[k,N]=(0,a.useState)(!1),S=(0,a.useRef)(null);(0,a.useEffect)(()=>()=>{null!==S.current&&window.clearTimeout(S.current)},[]),(0,a.useEffect)(()=>{if(void 0===e||""===e)return;let t=!1;return u(!0),m(null),i(null),s(!1),c(null),x(null),Promise.allSettled([(0,w.fetchRunReport)(e),(0,w.fetchEvidenceManifest)(e)]).then(([e,n])=>{if(!t){if("fulfilled"===n.status)s(!0),c(null);else{let e=rW(n.reason);s(!1),c("NOT_FOUND"===e.code?null:e)}if("fulfilled"===e.status){i(e.value.report),u(!1);return}m(rW(e.reason)),u(!1)}}),()=>{t=!0}},[e]);let C=`/api/evidence/${encodeURIComponent(e??"")}`,I=(0,a.useMemo)(()=>l?.proposedDiff!==void 0?function(e){let t=new TextEncoder,n=t.encode(e).byteLength;if(0===e.length)return{files:[],truncated:!1,totalBytes:0};let a=e,l=!1;if(n>524288){l=!0;let n=t.encode(e),i=new TextDecoder().decode(n.slice(0,524288)),r=i.lastIndexOf("\n");a=-1===r?i:i.slice(0,r+1)}let i=a.split("\n"),r=i.length>0&&""===i[i.length-1]?i.slice(0,-1):i,s=[],o=null,c=null,d=0,u=0,p=()=>{null!==o&&null!==c&&o.hunks.push(c),c=null},m=()=>{p(),null!==o&&(s.length<400?s.push(o):l=!0),o=null},h=0;for(;h<r.length;){let e=r[h]??"";if(e.startsWith("diff --git ")){m();let t=/^diff --git a\/(.+?) b\/(.+)$/.exec(e);if(null!==t&&void 0!==t[1]&&void 0!==t[2]){let e=t[1],n=t[2],a=rU(`b/${n}`),l=rU(`a/${e}`),i={path:a,hunks:[],addedLines:0,removedLines:0};l!==a&&(i.oldPath=l),o=i}h++;continue}if(null!==c){if(e.startsWith("+")){let t={kind:"add",oldLine:null,newLine:u,text:e.slice(1)};c.lines.push(t),null!==o&&o.addedLines++,u++,h++;continue}if(e.startsWith("-")){let t={kind:"del",oldLine:d,newLine:null,text:e.slice(1)};c.lines.push(t),null!==o&&o.removedLines++,d++,h++;continue}if(e.startsWith("\\ ")){let t={kind:"meta",oldLine:null,newLine:null,text:e};c.lines.push(t),h++;continue}if(e.startsWith(" ")||""===e){let t={kind:"ctx",oldLine:d,newLine:u,text:e.startsWith(" ")?e.slice(1):e};c.lines.push(t),d++,u++,h++;continue}}if(e.startsWith("--- ")){let t=e.slice(4);if("/dev/null"!==t&&null===o)m(),o={path:rU(t),hunks:[],addedLines:0,removedLines:0};else if("/dev/null"!==t&&null!==o){let e=rU(t);e!==o.path&&(o.oldPath=e)}h++;continue}if(e.startsWith("+++ ")){let t=e.slice(4);"/dev/null"!==t&&null!==o?o.path=rU(t):"/dev/null"!==t&&(m(),o={path:rU(t),hunks:[],addedLines:0,removedLines:0}),h++;continue}if(e.startsWith("@@ ")){null===o&&(o={path:"(unknown)",hunks:[],addedLines:0,removedLines:0}),p();let t=function(e){let t=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(e);return null===t||void 0===t[1]||void 0===t[2]?null:{oldStart:parseInt(t[1],10),newStart:parseInt(t[2],10)}}(e);d=t?.oldStart??1,u=t?.newStart??1,c={header:e,lines:[]},h++;continue}h++}return m(),{files:s,truncated:l,totalBytes:n}}(l.proposedDiff):null,[l?.proposedDiff]),E=l?.changedFiles??[],R=(0,a.useMemo)(()=>({added:I?.files.reduce((e,t)=>e+t.addedLines,0)??0,removed:I?.files.reduce((e,t)=>e+t.removedLines,0)??0}),[I]),$=null!==I&&I.files.length>0?Math.min(b??0,I.files.length-1):null,A=null!==$?I?.files[$]:void 0,T=l?.status==="running";return void 0===e||""===e?(0,n.jsxs)("section",{className:"review rv-empty","aria-label":"Diff review",children:[(0,n.jsx)("h2",{className:"rv-empty-h",children:"Review"}),void 0!==t?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("p",{className:"rv-empty-p",children:"Paste a run ID below to load a proposed diff."}),(0,n.jsxs)("form",{className:"rv-empty-form",onSubmit:e=>{e.preventDefault();let n=y.trim();0!==n.length&&t(n)},children:[(0,n.jsx)("label",{className:"rv-empty-label",htmlFor:"rv-runid-input",children:"Run ID"}),(0,n.jsx)("input",{id:"rv-runid-input",className:"rv-runid-input mono",type:"text",value:y,onChange:e=>j(e.target.value),placeholder:"e.g. 7f3a9c12…"}),(0,n.jsx)("button",{type:"submit",className:"arun-btn",children:"Load run"})]})]}):(0,n.jsx)("p",{className:"rv-empty-p",children:"Enter a run ID in the window configuration to load a proposed diff."})]}):(0,n.jsxs)("section",{className:"review","aria-label":"Diff review",children:[d&&(0,n.jsxs)("div",{className:"rv-loading",role:"status","aria-busy":"true","aria-label":"Loading diff",children:[(0,n.jsx)("div",{className:"rv-skel"}),(0,n.jsx)("div",{className:"rv-skel rv-skel-sm"})]}),!d&&null!==p&&(0,n.jsxs)("div",{role:"alert",className:"rv-error",children:["NOT_FOUND"===p.code?"No run with that ID was found.":(0,n.jsxs)(n.Fragment,{children:[p.message," ",(0,n.jsxs)("span",{className:"err-code mono",children:["(",p.code,")"]})]}),(r||null!==o)&&(0,n.jsx)("span",{className:"rv-error-evidence",children:(0,n.jsx)(rY,{href:C,hasManifest:r,error:o})})]}),(0,n.jsx)("p",{role:"status","aria-live":"polite",className:!d&&null===p&&null!==l&&T?"rv-no-diff":"sr-only",children:!d&&null===p&&null!==l&&T?"Run is still running. The proposed diff will appear when the run completes.":""}),!d&&null===p&&null!==l&&!T&&!rH(l)&&(0,n.jsx)("p",{className:"rv-no-diff",children:"This run has no proposed diff to review."}),!d&&null===p&&null!==l&&rH(l)&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"rv-header",children:[(0,n.jsx)("span",{className:"rv-status mono",children:(0,aq.runStatusLabel)(l.status)}),void 0!==l.modelId&&(0,n.jsx)("span",{className:"rv-model mono",children:l.modelId}),(0,n.jsxs)("span",{className:"rv-counts mono",children:[null!==I&&`${I.files.length} file${1!==I.files.length?"s":""}`," ",(0,n.jsxs)("span",{className:"rv-stat add",children:["+",R.added]})," ",(0,n.jsxs)("span",{className:"rv-stat del",children:["−",R.removed]})]}),(0,n.jsx)("span",{className:"spacer"}),(0,n.jsx)(rY,{href:C,hasManifest:r,error:o})]}),null!==I&&I.files.length>0&&null!==$&&void 0!==A&&(0,n.jsxs)("div",{className:"rv-layout",children:[(0,n.jsx)("nav",{className:"rv-filelist","aria-label":"Changed files",children:(0,n.jsx)("ul",{children:I.files.map((e,t)=>{let a=E.find(t=>t.path===e.path),l=$===t;return(0,n.jsx)("li",{children:(0,n.jsxs)("button",{type:"button",className:"rv-filerow",title:e.path,"aria-pressed":l,"aria-controls":l?`rv-file-${t}`:void 0,onClick:()=>{x(t)},children:[(0,n.jsx)("span",{className:"rv-filerow-path mono",children:function(e){if(e.length<=40)return e;let t=e.split("/");return t.length<=2?e:`…/${t.slice(-2).join("/")}`}(e.path)}),(0,n.jsxs)("span",{className:"rv-stat add",children:["+",e.addedLines]}),(0,n.jsxs)("span",{className:"rv-stat del",children:["−",e.removedLines]}),a?.elevatedReview===!0&&(0,n.jsx)("span",{className:"rv-elevated","aria-label":"Elevated review",children:"!"})]})},e.path)})})}),(0,n.jsxs)("div",{className:"rv-body",children:[(0,n.jsx)(rQ,{file:A,index:$,changedFiles:E,sectionRef:()=>void 0},A.path),I.truncated&&(0,n.jsxs)("p",{role:"note",className:"rv-truncated",children:["Diff truncated at 512 KB. Open the"," ",r?(0,n.jsx)("a",{href:C,target:"_blank",rel:"noopener noreferrer",children:"evidence manifest"}):"evidence manifest"," ","for the full record."]})]})]}),(0,n.jsxs)("div",{className:"rv-controls",children:[(0,n.jsx)("span",{role:"status","aria-live":"polite",className:"rv-apply-status",children:h?"Applying…":void 0!==l.appliedAt?"Applied":""}),null!==g&&(0,n.jsx)("span",{role:"alert",className:"rv-apply-error",children:g.message}),void 0!==l.appliedAt?(0,n.jsx)("span",{className:"rv-final mono",children:"Applied"}):rV(l)?(0,n.jsx)("button",{type:"button",className:"arun-btn","aria-disabled":h,onClick:()=>{if(!h){if(!k){N(!0),null!==S.current&&window.clearTimeout(S.current),S.current=window.setTimeout(()=>{N(!1),S.current=null},6e3);return}null!==S.current&&(window.clearTimeout(S.current),S.current=null),N(!1),void 0!==e&&null!==l&&rV(l)&&!h&&(f(!0),v(null),(0,w.applyRun)(e).then(e=>{i(e.report),f(!1)}).catch(e=>{v(rW(e)),f(!1)}))}},children:h?"Applying…":k?`Confirm apply (${(I?.files.length??0).toString()} file${I?.files.length===1?"":"s"})`:"Apply"}):null]})]})]})}let r0=["run:started","state:transition","model:call:started","model:call:completed","model:call:failed","tool:call:started","tool:call:completed","tool:call:failed","reasoning:trace","patch:proposed","verification:result","run:completed","run:cancelled","run:failed","command:executed","sandbox:configured","patch:applied","browser:session-opened","browser:navigated","browser:screenshot-captured","browser:page-content-captured","browser:session-closed","browser:trust-warning","browser:error","workflow:started","conventions:detected","context:selected","workflow:model:call:started","workflow:model:call:completed","patch:validated","workflow:patch:applied","workflow:verification:result","workflow:completed","workflow:failed","bug:started","bug:failure:parsed","bug:context:selected","bug:model:call:started","bug:model:call:completed","bug:rootcause:proposed","bug:patch:validated","bug:patch:applied","bug:verification:result","bug:completed","bug:failed","ready"],r1=new Set(["run:completed","run:cancelled","run:failed","workflow:completed","workflow:failed","bug:completed","bug:failed"]),r2=new Set(["completed","dry-run","rejected","cancelled","failed","fix-applied","fix-proposed","investigation-only"]),r4={verify:"Verify","explain-plan":"Explain plan","unit-test-generation":"Generate unit tests","bug-investigation":"Investigate bug"};function r3(e,t){return void 0===t||0===t.length?null:(0,n.jsxs)("div",{className:"arun-result-card",children:[(0,n.jsx)("div",{className:"arun-result-title",children:e}),(0,n.jsx)("pre",{children:t})]})}let r6={high:"High",medium:"Medium",low:"Low — verify"};function r5({level:e}){return(0,n.jsxs)("div",{className:"arun-kv",children:[(0,n.jsx)("span",{children:"Confidence"}),(0,n.jsxs)("span",{className:"ai-conf","data-level":e,children:[(0,n.jsxs)("span",{className:"track","aria-hidden":"true",children:[(0,n.jsx)("i",{}),(0,n.jsx)("i",{}),(0,n.jsx)("i",{})]}),(0,n.jsx)("span",{className:"lbl",children:r6[e]})]})]})}function r8({cfg:e={},linkedRoot:t=null,linkedFilePath:l}){var i,r;let s,o=e.runId??null,c="verify"===(i=e.workflow)||"explain-plan"===i||"unit-test-generation"===i||"bug-investigation"===i?i:null,d=e.model??"",u=function(e){if(void 0===e||0===e.length)return null;try{let t=JSON.parse(e);return"object"!=typeof t||null===t||Array.isArray(t)?null:t}catch{return null}}(e.inputJson),p=function(e){let[t,n]=(0,a.useState)([]),[l,i]=(0,a.useState)("connecting"),[r,s]=(0,a.useState)(null),o=(0,a.useRef)(-1);return(0,a.useEffect)(()=>{if(null===e)return;n([]),i("connecting"),s(null),o.current=-1;let t=null,a=!1,l=`/api/runs/${encodeURIComponent(e)}/events`;(t=new EventSource(o.current>=0?`${l}?lastEventId=${o.current.toString()}`:l)).onopen=()=>{a||(i("live"),s(null))},t.onerror=()=>{a||(i("error"),s("Stream disconnected. Attempting to reconnect…"))};let r=e=>{let l;if(!a){try{l=JSON.parse(e.data)}catch{return}o.current=l.seq,n(e=>[...e,l]),r1.has(l.type)&&(i("terminal"),t?.close())}};for(let e of r0)t.addEventListener(e,r);return()=>{a=!0,t?.close()}},[e]),{events:t,status:l,error:r}}(o),[m,h]=(0,a.useState)(null),[f,g]=(0,a.useState)(null),[v,b]=(0,a.useState)(null),[x,y]=(0,a.useState)(!1),[k,N]=(0,a.useState)(null),[S,C]=(0,a.useState)(null),[I,E]=(0,a.useState)(!1),R=(0,a.useRef)(null),$=(0,a.useRef)(null),A=(0,a.useCallback)(async()=>{if(null!==o){b(null);try{let e=await (0,w.fetchRunReport)(o);h(e.report),g(null)}catch(e){if(e instanceof w.ApiError&&404===e.status){try{let e=await (0,w.fetchEvidenceManifest)(o);g(e.manifest),h(null)}catch(e){b(e instanceof Error?e.message:"Unable to load evidence.")}return}b(e instanceof Error?e.message:"Unable to load run report.")}}},[o]);(0,a.useEffect)(()=>{A()},[A]),(0,a.useEffect)(()=>{"terminal"===p.status&&A()},[A,p.status]),(0,a.useEffect)(()=>{let e=!1;if(0!==d.length)return(0,w.fetchModels)().then(t=>{e||C(t.models.find(e=>e.id===d)?.costClass??null)}).catch(()=>{e||C(null)}),()=>{e=!0}},[d]);let T=(0,a.useMemo)(()=>(function(e,t){let n=t?.usage?.promptTokens??0,a=t?.usage?.completionTokens??0,l=t?.usage?.latencyMs??0,i=+(t?.usage!==void 0);if(i>0)return{promptTokens:n,completionTokens:a,latencyMs:l,requestCount:i};for(let t of e){let e=function(e){if("model:call:completed"===e.type)return{promptTokens:e.usage.promptTokens,completionTokens:e.usage.completionTokens,latencyMs:e.usage.latencyMs,requestCount:1};let t=e.promptTokens,n=e.completionTokens,a=e.latencyMs;return"number"==typeof t&&"number"==typeof n&&"number"==typeof a?{promptTokens:t,completionTokens:n,latencyMs:a,requestCount:1}:null}(t);null!==e&&(n+=e.promptTokens,a+=e.completionTokens,l+=e.latencyMs,i+=e.requestCount)}return{promptTokens:n,completionTokens:a,latencyMs:l,requestCount:i}})(p.events,m),[p.events,m]),L=m?.durationMs??f?.run.durationMs??(p.events.length>0?Math.max(0,Date.now()-Number(new Date(p.events[0]?.ts??Date.now()))):0),P=null!==m?m.status:null!==f?f.run.outcome:"loading",M=null!==m?(0,aq.runStatusLabel)(m.status):null!==f?(0,aq.outcomeLabel)(f.run.outcome):"Loading…",D=null!==m&&r2.has(m.status),q=null!==m&&void 0!==m.proposedDiff&&void 0===m.appliedAt&&("unit-test-generation"===c&&"dry-run"===m.status||"bug-investigation"===c&&"fix-proposed"===m.status),F=!D&&m?.status==="running",O=function(e){if(void 0===e||0===e.length)return 0;let t=e.match(/^diff --git /gm);if(null!==t)return t.length;let n=e.match(/^\+\+\+ /gm);return null===n?0:n.length}(m?.proposedDiff),z=x||"connecting"===p.status||m?.status==="running"||null===m&&null===f&&null===v,K=(0,a.useRef)(!1);(0,a.useEffect)(()=>{K.current&&!F&&document.activeElement===document.body&&$.current?.focus(),K.current=F},[F]),(0,a.useEffect)(()=>()=>{null!==R.current&&window.clearTimeout(R.current)},[]);let B=async()=>{if(null!==o){b(null);try{await (0,w.cancelRun)(o),await A()}catch(e){b(e instanceof Error?e.message:"Unable to cancel run.")}}},_=async()=>{if(null!==o&&q&&!x){y(!0),N(null);try{let e=await (0,w.applyRun)(o);h(e.report)}catch(e){N(e instanceof Error?e.message:"Unable to apply run.")}finally{y(!1)}}};return null===o||null===c?(0,n.jsxs)("div",{className:"arun arun-empty",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Agent run is not configured."}),(0,n.jsx)("p",{children:"Open a new Agent window from the launcher to start a workflow."})]}):(0,n.jsxs)("div",{className:"arun arun-real","aria-busy":z?"true":void 0,children:[(0,n.jsxs)("div",{className:"arun-head",children:[(0,n.jsx)("span",{className:"arun-role",children:r4[c]}),d.length>0?(0,n.jsx)("span",{className:"ag-model mono",children:d}):null,null!==S?(0,n.jsx)("span",{className:"arun-gov",title:"Model cost class",children:(0,aq.costClassLabel)(S)}):null,(0,n.jsx)("span",{className:"spacer"}),(0,n.jsxs)("span",{className:"arun-status",children:[(0,n.jsx)("span",{className:"dot","data-live":m?.status==="running","data-status":P}),M]})]}),(0,n.jsxs)("div",{className:"arun-summary",role:"status","aria-live":"polite",children:[(0,n.jsx)("strong",{children:function(e,t,n){if(null===t&&null===n)return"Loading run state…";let a=null===e?"Agent run":r4[e];return t?.status==="running"?`${a} is running.`:t?.status==="dry-run"?`${a} produced a reviewable dry-run.`:t?.status==="fix-proposed"?`${a} proposed a fix.`:t?.status==="fix-applied"?`${a} applied changes.`:t?.status==="investigation-only"?`${a} completed without a patch.`:t?.status==="failed"||t?.status==="rejected"?`${a} failed.`:t?.status==="cancelled"?`${a} was cancelled.`:null!==t?`${a} completed.`:n?.patch?.redactedDiff!==void 0?`${a} evidence loaded with a reviewable diff.`:`${a} evidence loaded: ${n?.run.outcome??"unknown"}.`}(c,m,f)}),(0,n.jsxs)("span",{className:"mono",title:o,children:["run ",o.slice(0,8)]})]}),(0,n.jsxs)("div",{className:"arun-meters",children:[(0,n.jsxs)("div",{className:"arun-meter",children:[(0,n.jsx)("span",{className:"arun-mk",children:"Elapsed"}),(0,n.jsx)("span",{className:"arun-mv mono",children:(0,aq.formatMs)(L)})]}),(0,n.jsxs)("div",{className:"arun-meter",children:[(0,n.jsx)("span",{className:"arun-mk",children:"Usage"}),(0,n.jsx)("span",{className:"arun-mv mono",children:0===T.requestCount?"No model usage":`${(0,aq.formatTokens)(T.promptTokens+T.completionTokens)} tok`})]}),(0,n.jsxs)("div",{className:"arun-meter",children:[(0,n.jsx)("span",{className:"arun-mk",children:"Latency"}),(0,n.jsx)("span",{className:"arun-mv mono",children:0===T.requestCount?"—":(0,aq.formatMs)(T.latencyMs)})]})]}),(0,n.jsxs)("div",{className:"arun-perms",children:[(0,n.jsxs)("span",{className:"arun-perm","data-on":null!==t,title:null!==t?t:e.workspaceRoot??void 0,children:[(0,n.jsx)(j.Icons.files,{size:11}),(0,n.jsx)("span",{className:"arun-perm-path",children:null!==t?t:e.workspaceRoot??"no workspace"})]}),void 0!==l?(0,n.jsxs)("span",{className:"arun-perm","data-on":!0,title:l,children:[(0,n.jsx)(j.Icons.files,{size:11}),(0,n.jsx)("span",{className:"arun-perm-path",children:l})]}):null]}),null!==u?(0,n.jsxs)("details",{className:"arun-input",children:[(0,n.jsx)("summary",{children:"Run input"}),(0,n.jsx)("pre",{children:JSON.stringify(u,null,2)})]}):null,(0,n.jsxs)("div",{className:"arun-log",role:"log","aria-live":"polite","aria-label":"Run events","aria-busy":z?"true":void 0,children:["error"===p.status&&null!==p.error?(0,n.jsxs)("div",{className:"arun-log-row",children:[(0,n.jsx)("span",{className:"arun-log-ico",children:(0,n.jsx)(j.Icons.reset,{size:12})}),(0,n.jsx)("span",{className:"arun-log-text",children:p.error})]}):null,0===p.events.length?"error"===p.status?null:(0,n.jsxs)("div",{className:"arun-log-row",children:[(0,n.jsx)("span",{className:"arun-log-ico",children:(0,n.jsx)(j.Icons.reset,{size:12})}),(0,n.jsx)("span",{className:"arun-log-text",children:"connecting"===p.status?"Connecting to run events…":"Waiting for run events…"})]}):p.events.slice().reverse().slice(0,50).map(e=>{let t;return(0,n.jsxs)("div",{className:"arun-log-row",children:[(0,n.jsx)("span",{className:"arun-log-ico",children:(0,n.jsx)(j.Icons.spark,{size:12})}),(0,n.jsx)("span",{className:"arun-log-text",children:function(e){switch(e.type){case"ready":return"SSE stream ready";case"run:started":return`Started ${e.taskType}`;case"run:completed":return"Run completed";case"run:failed":return`Run failed: ${e.failure.message}`;case"run:cancelled":return"Run cancelled";case"state:transition":return`${e.from} -> ${e.to}${void 0===e.reason?"":`: ${e.reason}`}`;case"model:call:started":return`Model call started (${(0,aq.formatBytes)(e.contextBytes)})`;case"model:call:completed":return`Model call completed (${(0,aq.formatTokens)(e.usage.promptTokens+e.usage.completionTokens)} tokens)`;case"model:call:failed":return`Model call failed: ${e.message}`;case"patch:proposed":return`Patch proposed (${(0,aq.formatBytes)(e.patchBytes)})`;case"verification:result":return`Verification ${e.passed?"passed":"failed"}: ${e.detail}`;case"workflow:started":return"Unit-test workflow started";case"workflow:model:call:completed":return`Unit-test model call completed (${(0,aq.formatTokens)(e.promptTokens+e.completionTokens)} tokens)`;case"workflow:verification:result":return`Unit-test verification ${e.overallStatus}`;case"workflow:completed":return`Unit-test workflow ${e.status}`;case"workflow:failed":return`Unit-test workflow failed: ${e.message}`;case"bug:started":return"Bug investigation started";case"bug:model:call:completed":return`Bug model call completed (${(0,aq.formatTokens)(e.promptTokens+e.completionTokens)} tokens)`;case"bug:rootcause:proposed":return`Root cause proposed${e.hasPatch?" with patch":""}`;case"bug:verification:result":return`Bug verification ${e.overallStatus}`;case"bug:completed":return`Bug investigation ${e.status}`;case"bug:failed":return`Bug investigation failed: ${e.message}`;default:return e.type}}(e)}),(0,n.jsx)("span",{className:"arun-log-t mono",children:Number.isFinite(t="number"==typeof e.ts?e.ts:Date.parse(e.ts))?new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):""})]},`${e.runId}:${e.seq}:${e.type}`)})]}),null!==m?(0,n.jsxs)("div",{className:"arun-results",children:[void 0===m.report?null:(0,n.jsxs)("div",{className:"arun-result-card",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Report"}),(0,n.jsx)("pre",{children:m.report})]}),void 0===m.overallStatus||void 0===m.results?null:(0,n.jsxs)("div",{className:"arun-result-card",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Verification"}),(0,n.jsxs)("div",{className:"arun-kv",children:[(0,n.jsx)("span",{children:"Status"}),(0,n.jsx)("strong",{children:m.overallStatus})]}),m.results.slice(0,8).map(e=>(0,n.jsxs)("div",{className:"arun-check-row",children:[(0,n.jsx)("span",{children:e.kind}),(0,n.jsx)("span",{className:"mono",children:e.status})]},`${e.kind}:${e.command}`))]}),r3("Failure",m.failureReason),r3("Covered behavior",m.coveredBehavior),r3("Known gaps",m.knownGaps),r3("Verification note",m.verificationSkipReason),function(e){let t=e.hypothesis;if(void 0===t)return null;let a=[["Root cause",t.rootCause],["Regression test",t.regressionTestStrategy],["Uncertainty",t.uncertainty]].filter(e=>"string"==typeof e[1]&&e[1].length>0),l="string"==typeof t.confidence?t.confidence:"",i="low"===l||"medium"===l||"high"===l?l:void 0,r=l.length>0&&void 0===i?l:void 0;return 0===a.length&&void 0===i&&void 0===r?null:(0,n.jsxs)("div",{className:"arun-result-card",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Hypothesis"}),a.map(([e,t])=>(0,n.jsxs)("div",{className:"arun-kv",children:[(0,n.jsx)("span",{children:e}),(0,n.jsx)("strong",{children:t})]},e)),void 0!==r?(0,n.jsxs)("div",{className:"arun-kv",children:[(0,n.jsx)("span",{children:"Confidence"}),(0,n.jsx)("strong",{children:r})]}):null,void 0!==i?(0,n.jsx)(r5,{level:i}):null]})}(m),void 0===(r=m.nextActions)||0===r.length?null:(0,n.jsxs)("div",{className:"arun-result-card",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Next actions"}),r.map(e=>(0,n.jsx)("div",{className:"arun-check-row",children:(0,n.jsx)("span",{children:e})},e))]}),void 0!==m.dryRunPreview?(0,n.jsxs)("div",{className:"arun-result-card",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Dry-run preview"}),(0,n.jsx)("pre",{children:m.dryRunPreview})]}):null,void 0!==m.proposedDiff?(0,n.jsxs)("div",{className:"arun-result-card",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Proposed diff"}),(0,n.jsx)("pre",{children:m.proposedDiff})]}):null,void 0===(s=m.verificationSummary)?null:(0,n.jsxs)("div",{className:"arun-result-card",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Verification"}),(0,n.jsxs)("div",{className:"arun-kv",children:[(0,n.jsx)("span",{children:"Status"}),(0,n.jsx)("strong",{children:s.overallStatus})]}),(0,n.jsxs)("div",{className:"arun-kv",children:[(0,n.jsx)("span",{children:"Duration"}),(0,n.jsx)("strong",{children:(0,aq.formatMs)(s.durationMs)})]}),s.results.slice(0,5).map(e=>(0,n.jsxs)("div",{className:"arun-check-row",children:[(0,n.jsx)("span",{children:e.kind}),(0,n.jsx)("span",{className:"mono",children:e.status})]},`${e.kind}:${e.command}`))]}),void 0!==m.applyReport?(0,n.jsxs)("div",{className:"arun-result-card arun-applied",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Applied"}),(0,n.jsx)("pre",{children:JSON.stringify(m.applyReport,null,2)})]}):null]}):null!==f?(0,n.jsxs)("div",{className:"arun-results",children:[(0,n.jsxs)("div",{className:"arun-result-card",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Evidence"}),(0,n.jsxs)("div",{className:"arun-kv",children:[(0,n.jsx)("span",{children:"Outcome"}),(0,n.jsx)("strong",{children:f.run.outcome})]}),(0,n.jsxs)("div",{className:"arun-kv",children:[(0,n.jsx)("span",{children:"Duration"}),(0,n.jsx)("strong",{children:(0,aq.formatMs)(f.run.durationMs)})]}),void 0!==f.patch?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"arun-kv",children:[(0,n.jsx)("span",{children:"Changed files"}),(0,n.jsx)("strong",{children:f.patch.changedFiles.toString()})]}),(0,n.jsxs)("div",{className:"arun-kv",children:[(0,n.jsx)("span",{children:"Patch size"}),(0,n.jsx)("strong",{children:(0,aq.formatBytes)(f.patch.patchBytes)})]})]}):null]}),f.patch?.redactedDiff!==void 0?(0,n.jsxs)("div",{className:"arun-result-card",children:[(0,n.jsx)("div",{className:"arun-result-title",children:"Proposed diff"}),(0,n.jsx)("pre",{children:f.patch.redactedDiff})]}):null]}):null,null!==v?(0,n.jsx)("div",{className:"arun-error",role:"alert",children:v}):null,null!==k?(0,n.jsx)("div",{className:"arun-error",role:"alert",children:k}):null,(0,n.jsxs)("div",{className:"arun-controls",children:[(0,n.jsx)("a",{className:"arun-btn ghost",href:`/api/evidence/${encodeURIComponent(o)}`,target:"_blank",rel:"noreferrer",ref:$,children:"Evidence"}),q?(0,n.jsx)("button",{type:"button",className:"arun-btn","aria-disabled":x,onClick:()=>{if(!x){if(!I){E(!0),null!==R.current&&window.clearTimeout(R.current),R.current=window.setTimeout(()=>{E(!1),R.current=null},6e3);return}null!==R.current&&(window.clearTimeout(R.current),R.current=null),E(!1),_()}},children:x?"Applying…":I?`Confirm apply (${O.toString()} file${1===O?"":"s"})`:"Apply"}):m?.appliedAt!==void 0?(0,n.jsx)("span",{className:"arun-final mono",children:"Applied"}):null,F?(0,n.jsx)("button",{type:"button",className:"arun-btn danger",onClick:()=>void B(),children:"Cancel"}):null]})]})}let r7=[{name:"Messaging",desc:"Catch up on threads",glyph:"#"},{name:"GitHub",desc:"PRs, code & CI",glyph:"{ }"},{name:"Linear",desc:"Track issues",glyph:"⊿"},{name:"Slack",desc:"Team channels",glyph:"≡"},{name:"Sentry",desc:"Error tracking",glyph:"◎"}];function r9(){return(0,n.jsx)("ul",{className:"integ","aria-label":"Integrations",children:r7.map(e=>(0,n.jsxs)("li",{className:"integ-row",children:[(0,n.jsx)("span",{className:"integ-glyph mono",children:e.glyph}),(0,n.jsxs)("span",{className:"integ-text",children:[(0,n.jsx)("span",{className:"integ-name",children:e.name}),(0,n.jsx)("span",{className:"integ-desc",children:e.desc})]}),(0,n.jsx)("span",{className:"integ-status",children:"Not connected — coming soon"})]},e.name))})}let se={allow:["Allow","var(--accent)"],ask:["Ask","var(--warn)"],deny:["Deny","var(--danger)"]},st={allow:"ask",ask:"deny",deny:"allow"},sn=[{id:1,label:"Write src/windows.jsx",kind:"write",risk:"low",expect:"allow"},{id:2,label:"Overwrite prod/secrets.env",kind:"write",risk:"high",expect:"deny"},{id:3,label:"Run `npm test`",kind:"command",risk:"low",expect:"allow"},{id:4,label:"Run `kubectl apply` → prod",kind:"command",risk:"high",expect:"ask"},{id:5,label:"Open pull request #142",kind:"git",risk:"low",expect:"allow"},{id:6,label:"Email the customer",kind:"mail",risk:"low",expect:"ask"}],sa=[["Developer","Codes, reviews diffs, runs tests, opens PRs"],["Product Owner","Searches docs, drafts Jira tickets, plans releases"],["Designer","Explores UI options, reviews flows, writes specs"]],sl=[["calendar","Calendar","automations"],["mail","Mail","bell"],["jira","Jira","review"],["docs","Docs","files"]];function si({policy:e,setPolicy:t}){return(0,n.jsxs)("div",{className:"pol",children:[(0,n.jsx)("div",{className:"pol-hint",children:"Rights an agent inherits when Keiko governs. Tap a decision to cycle through Allow → Ask → Deny."}),e.map(e=>{let a=se[e.decision];return(0,n.jsxs)("div",{className:"pol-row",children:[(0,n.jsxs)("div",{className:"pol-text",children:[(0,n.jsx)("span",{className:"pol-action",children:e.action}),(0,n.jsx)("span",{className:"pol-scope mono",children:e.scope})]}),(0,n.jsx)("button",{type:"button",className:"pol-dec",style:{color:a[1],borderColor:a[1]},onClick:()=>{let n;return n=e.id,t(e=>e.map(e=>e.id===n?{...e,decision:st[e.decision]}:e))},children:a[0]})]},e.id)})]})}function sr({decide:e}){let[t,l]=(0,a.useState)(!1),i=sn.map(t=>{let n=e(t.kind,t.risk);return{...t,actual:n,pass:n===t.expect}}),r=i.filter(e=>e.pass).length;return(0,n.jsxs)("div",{className:"evl",children:[(0,n.jsxs)("div",{className:"evl-head",children:[(0,n.jsxs)("button",{type:"button",className:"evl-run",onClick:()=>l(!0),children:[(0,n.jsx)(j.Icons.spark,{size:13})," Run evaluation"]}),t&&(0,n.jsxs)("span",{className:"evl-score"+(r===i.length?" ok":""),children:[r,"/",i.length," passed"]})]}),(0,n.jsx)("div",{className:"evl-hint",children:"Mock scenarios against your policy before going autonomous."}),i.map(e=>(0,n.jsxs)("div",{className:"evl-row","data-state":t?e.pass?"pass":"fail":"idle",children:[(0,n.jsx)("span",{className:"evl-ico",children:t?e.pass?(0,n.jsx)(j.Icons.check,{size:13}):(0,n.jsx)(j.Icons.close,{size:13}):(0,n.jsx)("span",{className:"evl-dot"})}),(0,n.jsx)("span",{className:"evl-label",children:e.label}),t&&(0,n.jsx)("span",{className:"evl-res mono",style:{color:se[e.actual][1]},children:se[e.actual][0]})]},e.id))]})}function ss({bridges:e,setBridges:t}){return(0,n.jsxs)("div",{className:"brg",children:[(0,n.jsx)("div",{className:"evl-hint",children:"What your twin can reach on your behalf."}),sl.map(([a,l,i])=>{let r=j.Icons[i],s=e[a];return(0,n.jsxs)("button",{type:"button",className:"brg-row","data-on":s,"aria-pressed":s,onClick:()=>t(e=>({...e,[a]:!e[a]})),children:[(0,n.jsx)("span",{className:"brg-ico",children:(0,n.jsx)(r,{size:16})}),(0,n.jsx)("span",{className:"brg-name",children:l}),(0,n.jsx)("span",{className:"brg-tg"+(s?" on":""),children:(0,n.jsx)("span",{})})]},a)})]})}function so({persona:e,setPersona:t}){return(0,n.jsxs)("div",{className:"prs",children:[(0,n.jsx)("div",{className:"evl-hint",children:"Keiko adapts behaviour & tools to who is at the wheel."}),sa.map(([a,l])=>(0,n.jsxs)("button",{type:"button",className:"prs-row","data-on":e===a,"aria-pressed":e===a,onClick:()=>t(a),children:[(0,n.jsx)("span",{className:"prs-dot"}),(0,n.jsxs)("span",{className:"prs-text",children:[(0,n.jsx)("span",{className:"prs-name",children:a}),(0,n.jsx)("span",{className:"prs-desc",children:l})]}),e===a&&(0,n.jsx)(j.Icons.check,{size:14,style:{color:"var(--accent)"}})]},a))]})}let sc=[["policy","Policy"],["eval","EVAL"],["bridges","Connections"],["persona","Persona"]];function sd(){let e=x(),[t,l]=(0,a.useState)("policy");return(0,n.jsxs)("div",{className:"twin",children:[(0,n.jsxs)("div",{className:"twin-hero",children:[(0,n.jsx)("img",{className:"twin-orca",src:"/assets/keiko-logo.svg",alt:""}),(0,n.jsxs)("div",{className:"twin-id",children:[(0,n.jsx)("span",{className:"twin-name",children:"Keiko — Digital Twin"}),(0,n.jsxs)("span",{className:"twin-sub mono",children:["mirroring · ",e.persona]})]}),(0,n.jsx)("span",{className:"twin-mode "+("autonomous"===e.mode?"on":""),children:"autonomous"===e.mode?"Autonomous":"Manual"})]}),(0,n.jsx)("div",{className:"twin-tabs",children:sc.map(([e,a])=>(0,n.jsx)("button",{type:"button",className:"twin-tab","data-on":t===e,onClick:()=>l(e),children:a},e))}),(0,n.jsxs)("div",{className:"twin-body",children:["policy"===t&&(0,n.jsx)(si,{policy:e.policy,setPolicy:e.setPolicy}),"eval"===t&&(0,n.jsx)(sr,{decide:e.decide}),"bridges"===t&&(0,n.jsx)(ss,{bridges:e.bridges,setBridges:e.setBridges}),"persona"===t&&(0,n.jsx)(so,{persona:e.persona,setPersona:e.setPersona})]})]})}function su(e){return"embedding-only"===e?"Embedding model — not selectable for text conversation":"ocr-vision-only"===e?"OCR/vision-only — not selectable for text conversation":"Not a chat model — not selectable for text conversation"}function sp(){return"Available for embeddings; not shown in the chat model picker"}function sm({model:e}){let t=function(e){if("chat"!==e.kind)return ny[e.kind]}(e);return void 0===t?(0,n.jsx)("span",{className:"ml-elig ml-elig-ok","data-testid":"conv-elig-ok",role:"status","aria-label":"Model eligibility: eligible for conversation",children:"Conversation-eligible"}):"embedding-only"===t?(0,n.jsx)("span",{className:"ml-elig ml-elig-embed","data-testid":"embedding-elig-ok",role:"status","aria-label":"Model eligibility: "+sp(),title:sp(),children:"Embedding-ready"}):(0,n.jsxs)("span",{className:"ml-elig ml-elig-no","data-testid":"conv-elig-no",role:"status","aria-label":"Model eligibility: "+su(t),title:su(t),children:["Not selectable — ","ocr-vision-only"===t?"OCR/vision-only":"not a chat model"]})}function sh({model:e}){var t;let a=nx(e),l="embedding"===e.kind;return(0,n.jsxs)("div",{className:"ml-row",children:[(0,n.jsx)("span",{className:"ml-ico",children:(0,n.jsx)(j.Icons.cube,{size:16})}),(0,n.jsxs)("div",{className:"ml-info",children:[(0,n.jsxs)("div",{className:"ml-top",children:[(0,n.jsx)("span",{className:"ml-name",children:e.id}),(0,n.jsx)("span",{className:"ml-type mono",children:"ocr-vision"===(t=e.kind)?"OCR":t}),(0,n.jsx)(sm,{model:e})]}),(0,n.jsxs)("div",{className:"ml-url mono",children:["tools ",e.toolCalling?"yes":"no"," · structured"," ",e.structuredOutput?"yes":"no"," · ",e.costClass,"/",e.latencyClass]})]}),(0,n.jsx)("span",{className:"ml-status "+(a||l?"connected":"ineligible"),title:a?"conversation-eligible":l?"available for embeddings":"not selectable for conversation","aria-hidden":"true"})]})}function sf(){let[e,t]=(0,a.useState)(eo),[l,i]=(0,a.useState)(ec),[r,s]=(0,a.useState)(ed),[o,c]=(0,a.useState)(eu),[d,u]=(0,a.useState)(ep),[p,m]=(0,a.useState)(em);(0,a.useEffect)(()=>{try{window.localStorage.setItem(G,e?"true":"false")}catch{}window.dispatchEvent(new CustomEvent(et,{detail:e}))},[e]),(0,a.useEffect)(()=>{try{window.localStorage.setItem(J,String(l))}catch{}window.dispatchEvent(new CustomEvent(en,{detail:l}))},[l]),(0,a.useEffect)(()=>{try{window.localStorage.setItem(X,String(r))}catch{}eh(r),window.dispatchEvent(new CustomEvent(ea,{detail:r}))},[r]),(0,a.useEffect)(()=>{try{window.localStorage.setItem(Q,String(o))}catch{}ef(o),window.dispatchEvent(new CustomEvent(el,{detail:o}))},[o]),(0,a.useEffect)(()=>{try{window.localStorage.setItem(Z,String(d))}catch{}eg(d),window.dispatchEvent(new CustomEvent(ei,{detail:d}))},[d]),(0,a.useEffect)(()=>{try{window.localStorage.setItem(ee,String(p))}catch{}ev(p),window.dispatchEvent(new CustomEvent(er,{detail:p}))},[p]);let h={"--p":`${String(l)}%`},f={"--p":`${String(r)}%`},g={"--p":`${String(o)}%`},v={"--p":`${String(d)}%`},b={"--p":`${String(p)}%`};return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"set-sec-h",children:(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{className:"set-sec-t",children:"Workspace wallpaper"}),(0,n.jsx)("div",{className:"set-sec-d",children:"Liquid Chrome — a subtle metallic flow behind the grid that reacts to your cursor and clicks. Turn it off to stop the WebGL animation completely."})]})}),(0,n.jsxs)("div",{className:"gpref",children:[(0,n.jsxs)("div",{className:"gpref-row",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{className:"gpref-label",children:"Liquid wallpaper"}),(0,n.jsx)("div",{className:"gpref-help",children:e?"Running":"Stopped"})]}),(0,n.jsx)(lM,{on:e,onChange:t,label:"Liquid wallpaper"})]}),(0,n.jsxs)("div",{className:"gpref-row",children:[(0,n.jsx)("label",{className:"gpref-label",htmlFor:"wp-op",children:"Wallpaper opacity"}),(0,n.jsxs)("span",{className:"gpref-val mono",children:[l,"%"]})]}),(0,n.jsx)("input",{id:"wp-op",className:"gpref-slider",type:"range",min:0,max:100,step:1,value:l,disabled:!e,onChange:e=>i(Number.parseInt(e.target.value,10)),style:h,"aria-label":"Wallpaper opacity"}),(0,n.jsxs)("div",{className:"gpref-scale",children:[(0,n.jsx)("span",{children:"Off"}),(0,n.jsx)("span",{children:"Full"})]})]}),(0,n.jsxs)("div",{className:"gpref",children:[(0,n.jsxs)("div",{className:"gpref-row",children:[(0,n.jsx)("label",{className:"gpref-label",htmlFor:"ws-bg-bright",children:"Workspace background brightness"}),(0,n.jsxs)("span",{className:"gpref-val mono",children:[r,"%"]})]}),(0,n.jsx)("input",{id:"ws-bg-bright",className:"gpref-slider",type:"range",min:0,max:100,step:1,value:r,onChange:e=>s(Number.parseInt(e.target.value,10)),style:f,"aria-label":"Workspace background brightness"}),(0,n.jsxs)("div",{className:"gpref-scale",children:[(0,n.jsx)("span",{children:"Base"}),(0,n.jsx)("span",{children:"Lighter"})]})]}),(0,n.jsxs)("div",{className:"gpref",children:[(0,n.jsxs)("div",{className:"gpref-row",children:[(0,n.jsx)("label",{className:"gpref-label",htmlFor:"ws-grid-strength",children:"Workspace grid strength"}),(0,n.jsxs)("span",{className:"gpref-val mono",children:[o,"%"]})]}),(0,n.jsx)("input",{id:"ws-grid-strength",className:"gpref-slider",type:"range",min:0,max:100,step:1,value:o,onChange:e=>c(Number.parseInt(e.target.value,10)),style:g,"aria-label":"Workspace grid strength"}),(0,n.jsxs)("div",{className:"gpref-scale",children:[(0,n.jsx)("span",{children:"Subtle"}),(0,n.jsx)("span",{children:"Strong"})]})]}),(0,n.jsxs)("div",{className:"gpref",children:[(0,n.jsxs)("div",{className:"gpref-row",children:[(0,n.jsx)("label",{className:"gpref-label",htmlFor:"frame-border-strength",children:"Workspace border strength"}),(0,n.jsxs)("span",{className:"gpref-val mono",children:[d,"%"]})]}),(0,n.jsx)("input",{id:"frame-border-strength",className:"gpref-slider",type:"range",min:0,max:100,step:1,value:d,onChange:e=>u(Number.parseInt(e.target.value,10)),style:v,"aria-label":"Workspace border strength"}),(0,n.jsxs)("div",{className:"gpref-scale",children:[(0,n.jsx)("span",{children:"Subtle"}),(0,n.jsx)("span",{children:"Strong"})]})]}),(0,n.jsxs)("div",{className:"gpref",children:[(0,n.jsxs)("div",{className:"gpref-row",children:[(0,n.jsx)("label",{className:"gpref-label",htmlFor:"frame-inner-glow-strength",children:"Workspace inner glow"}),(0,n.jsxs)("span",{className:"gpref-val mono",children:[p,"%"]})]}),(0,n.jsx)("input",{id:"frame-inner-glow-strength",className:"gpref-slider",type:"range",min:0,max:100,step:1,value:p,onChange:e=>m(Number.parseInt(e.target.value,10)),style:b,"aria-label":"Workspace inner glow"}),(0,n.jsxs)("div",{className:"gpref-scale",children:[(0,n.jsx)("span",{children:"Off"}),(0,n.jsx)("span",{children:"Strong"})]})]})]})}function sg(){let[e,t]=(0,a.useState)("models"),[l,i]=(0,a.useState)([]),[r,s]=(0,a.useState)(null),[o,c]=(0,a.useState)(!1),[d,u]=(0,a.useState)(!0),[p,m]=(0,a.useState)(),[h,f]=(0,a.useState)(!1),[g,v]=(0,a.useState)(0);(0,a.useEffect)(()=>{let e=!1;return async function(){u(!0),m(void 0);try{let[t,n]=await Promise.all([(0,w.fetchConfig)(),(0,w.fetchModels)()]);if(e)return;s(t.config),c(t.configPresent),i(n.models)}catch(t){if(e)return;m(function(e){let t="Could not load gateway settings — the local Keiko backend did not respond.";if(!(e instanceof Error))return t;let n=e.message.trim();return 0===n.length||/^HTTP \d+$/u.test(n)||"Failed to fetch"===n||"Load failed"===n||"NetworkError when attempting to fetch a resource."===n?t:n}(t))}finally{e||u(!1)}}(),()=>{e=!0}},[g]);let b=l.filter(nx).length,x=l.length>0,y=o?x?0===b?"Gateway connected, but none of the discovered models can be used for conversation. Add a chat-capable deployment.":"Keiko can use the configured gateway models for chat and agent workflows.":"The gateway is configured, but no conversation-capable models are currently available.":"Enter the gateway base URL and API token before using chat or agent workflows.",k=o?"connected":"untested";return(0,n.jsxs)("div",{className:"set",children:[(0,n.jsxs)("div",{className:"set-hero",children:[(0,n.jsx)(j.Icons.settings,{size:18}),(0,n.jsx)("span",{className:"set-title",children:"Settings"}),(0,n.jsxs)("span",{className:"set-onprem",title:"Runs inside your network",children:[(0,n.jsx)("span",{className:"dot",style:{background:"var(--accent)"}})," Self-hosted"]})]}),(0,n.jsx)("div",{className:"set-tabs",children:["models","general","security"].map(a=>(0,n.jsx)("button",{type:"button",className:"set-tab","data-on":e===a,"aria-pressed":e===a,onPointerDown:()=>t(a),onClick:()=>t(a),children:"models"===a?"Models":"general"===a?"General":"Security"},a))}),(0,n.jsxs)("div",{className:"set-body",children:["models"===e&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"set-sec-h",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{className:"set-sec-t",children:"Model gateway"}),(0,n.jsx)("div",{className:"set-sec-d",children:"Credentials are stored locally by the Keiko loopback server; secrets are never returned to the browser."})]}),(0,n.jsxs)("button",{type:"button",className:"set-add",onClick:()=>f(!0),children:[(0,n.jsx)(j.Icons.plus,{size:14}),o?"Update credentials":"Connect gateway"]})]}),(0,n.jsxs)("div",{className:"ml-row",children:[(0,n.jsx)("span",{className:"ml-ico",children:(0,n.jsx)(j.Icons.cube,{size:16})}),(0,n.jsxs)("div",{className:"ml-info",children:[(0,n.jsxs)("div",{className:"ml-top",children:[(0,n.jsx)("span",{className:"ml-name",children:o?x?"Gateway connected":"Gateway configured":"Gateway setup required"}),(0,n.jsxs)("span",{className:"ml-type mono",children:[l.length.toString()," models"]}),(0,n.jsxs)("span",{className:"ml-type mono",children:[b.toString()," chat"]})]}),(0,n.jsx)("div",{className:"ml-url mono",children:y})]}),(0,n.jsx)("span",{className:"ml-status "+k,title:o?"gateway configured":"setup required","aria-hidden":"true"})]}),void 0!==p?(0,n.jsxs)("div",{className:"gw-error",role:"alert",children:[p,(0,n.jsx)("button",{type:"button",className:"gw-error-retry",onClick:()=>v(e=>e+1),children:"Retry"})]}):null,d?(0,n.jsx)("div",{className:"set-placeholder",role:"status",children:"Loading gateway models…"}):0===l.length?(0,n.jsx)("div",{className:"set-placeholder",role:"status",children:o?"No conversation-capable models are currently available. Review the gateway configuration or discovered model set.":"No models are configured yet. Connect the gateway to load configured model capabilities."}):(0,n.jsx)("div",{className:"set-list",children:l.map(e=>(0,n.jsx)(sh,{model:e},e.id))}),h?(0,n.jsx)(tD,{onCancel:()=>f(!1),preserveExisting:o,storedApiKeyHeaderName:r?.providers[0]?.credentialHeaderName,storedModels:l}):null]}),"general"===e&&(0,n.jsx)(sf,{}),"security"===e&&(0,n.jsx)("div",{className:"set-placeholder",children:"SSO · audit log · data residency — coming soon."})]})]})}function sv(e){return e instanceof w.ApiError?`${e.message} (${e.code})`:e instanceof Error?e.message:"Failed to load connectors."}function sb(){return(0,n.jsx)("div",{className:"connector-picker-status",role:"status","aria-live":"polite",children:"Loading connectors…"})}function sx({message:e,onRetry:t}){return(0,n.jsxs)("div",{className:"connector-picker-error",role:"alert",children:[(0,n.jsx)("p",{children:e}),(0,n.jsx)("button",{type:"button",className:"connector-picker-retry",onClick:t,children:"Try again"})]})}function sy({onManageConnectors:e}){return(0,n.jsx)("div",{className:"connector-picker-empty",children:(0,n.jsx)("button",{type:"button",className:"lk-btn lk-btn-primary connector-picker-create-link",onClick:e,children:"Create a connector"})})}function sw({capsules:e,capsuleSets:t,selectedKind:a,selectedId:l}){let i=function(e,t,n,a){if(void 0===n||void 0===a||0===a.length)return null;if("capsule"===n){let t=e.find(e=>e.id===a);return void 0!==t?t.displayName:`Capsule ${a}`}if("capsule-set"===n){let e=t.find(e=>e.id===a);return void 0!==e?e.displayName:`Set ${a}`}return null}(e,t,a,l);return null===i?null:(0,n.jsxs)("div",{className:"connector-picker-selected",role:"status","aria-live":"polite",children:[(0,n.jsx)("span",{"aria-hidden":"true",children:"●"}),(0,n.jsx)("span",{children:i})]})}function sj({selectedId:e,selectedLabel:t,selectedState:a,onManageConnectors:l}){let i=void 0!==t&&t.trim().length>0?t.trim():`Capsule ${e}`;return(0,n.jsxs)("div",{className:"connector-node","data-testid":"knowledge-connector-node",children:[(0,n.jsx)("div",{className:"connector-node-icon","aria-hidden":"true",children:(0,n.jsx)(j.Icons.server,{size:42})}),(0,n.jsxs)("div",{className:"connector-node-copy",children:[(0,n.jsx)("p",{className:"connector-node-kicker",children:function(e){switch(e){case"ready":return"Indexed";case"draft":return"Draft";case"indexing":return"Indexing";case"stale":return"Stale";case"error":return"Failed";default:return"Local Knowledge"}}(a)}),(0,n.jsx)("h2",{className:"connector-node-title",title:i,children:i}),(0,n.jsx)("p",{className:"connector-node-id mono",title:e,children:e})]}),(0,n.jsx)("button",{type:"button",className:"connector-node-manage",onClick:l,children:"Manage"})]})}function sk({selectedKind:e,selectedId:t,selectedLabel:l,selectedState:i,presentation:r,onSelect:s,onManageConnectors:o=()=>void 0}){let[c,d]=(0,a.useState)([]),[u,p]=(0,a.useState)([]),[m,h]=(0,a.useState)(!0),[f,g]=(0,a.useState)(null),[v,b]=(0,a.useState)(!1),[x,y]=(0,a.useState)(0),w="node"===r&&"capsule"===e&&void 0!==t&&t.length>0;if((0,a.useEffect)(()=>{if(w)return;let e=!1;return async function(){h(!0),g(null),b(!1);try{let[t,n]=await Promise.allSettled([(0,lD.fetchCapsules)(),(0,lD.fetchCapsuleSets)()]);if(e)return;"fulfilled"===t.status?d(t.value.capsules.filter(e=>"ready"===e.lifecycleState)):g(sv(t.reason)),"fulfilled"===n.status?p(n.value.capsuleSets):b(!0)}catch(t){e||g(sv(t))}finally{e||h(!1)}}(),()=>{e=!0}},[w,x]),w)return(0,n.jsx)(sj,{selectedId:t,selectedLabel:l,selectedState:i,onManageConnectors:o});if(m)return(0,n.jsx)(sb,{});if(null!==f)return(0,n.jsx)(sx,{message:f,onRetry:()=>{y(e=>e+1)}});let j=c.length>0,k=u.length>0;if(!j&&!k)return(0,n.jsx)(sy,{onManageConnectors:o});let N=void 0!==e&&void 0!==t&&t.length>0?`${e}:${t}`:"";return(0,n.jsxs)("div",{className:"connector-picker",children:[(0,n.jsx)(sw,{capsules:c,capsuleSets:u,selectedKind:e,selectedId:t}),(0,n.jsx)("div",{className:"connector-picker-label",children:"Select a connector"}),(0,n.jsx)(tz,{triggerClassName:"connector-picker-select",value:N,ariaLabel:"Select a connector",placeholder:"— choose a connector —",menuTitle:"Available connectors",sections:[...j?[{label:"Capsules",options:c.map(e=>({value:`capsule:${e.id}`,label:`${e.displayName} (${function(e){switch(e){case"ready":return"Ready";case"indexing":return"Indexing…";case"error":return"Failed";default:return e}}(e.lifecycleState)})`}))}]:[],...k?[{label:"Capsule sets",options:u.map(e=>({value:`capsule-set:${e.id}`,label:`${e.displayName} (${String(e.capsuleCount)} capsules)`}))}]:[]],onValueChange:e=>{!function(e){if(""===e)return;let t=e.indexOf(":");if(-1===t)return;let n=e.slice(0,t),a=e.slice(t+1);0!==a.length&&s({selectedKind:n,selectedId:a})}(e)}}),v?(0,n.jsx)("p",{className:"connector-picker-notice",role:"status",children:"Capsule sets could not be loaded."}):null,(0,n.jsx)("div",{className:"connector-picker-footer",children:(0,n.jsx)("button",{type:"button",className:"connector-picker-create-link",onClick:o,children:"Create or manage connectors"})})]})}async function sN(e,t){let n=(t?.method??"GET").toUpperCase(),a="GET"!==n&&"HEAD"!==n,l=await fetch(e,{...t,headers:{Accept:"application/json",...a?{"Content-Type":"application/json"}:{},...a?{"X-Keiko-CSRF":"1"}:{},...t?.headers??{}}});if(!l.ok){let e="INTERNAL",t=`HTTP ${l.status.toString()}`;try{let n=await l.json();e=n.error.code,t=n.error.message}catch{}throw new w.ApiError(e,t,l.status)}return l.json()}async function sS(e,t={}){return sN("/api/figma/snapshots",{method:"POST",...void 0!==t.signal?{signal:t.signal}:{},body:JSON.stringify({boardLink:e,...!0===t.acknowledgeReadOnly?{acknowledgeReadOnly:!0}:{},...!0===t.isResnapshot?{isResnapshot:!0}:{},...void 0!==t.version?{version:t.version}:{}})})}async function sC(e,t){return sN(`/api/figma/snapshots/${encodeURIComponent(e)}`,{...void 0!==t?{signal:t}:{}})}async function sI(e={}){let t=new URLSearchParams;void 0!==e.fileKey&&t.set("fileKey",e.fileKey),void 0!==e.nodeId&&t.set("nodeId",e.nodeId),void 0!==e.limit&&t.set("limit",String(e.limit));let n=t.size>0?`?${t.toString()}`:"";return(await sN(`/api/figma/snapshots${n}`,{...void 0!==e.signal?{signal:e.signal}:{}})).snapshots}async function sE(e,t,n){return sN(`/api/figma/snapshots/${encodeURIComponent(e)}`,{method:"PATCH",...void 0!==n?{signal:n}:{},body:JSON.stringify({displayName:t})})}async function sR(e,t){return sN(`/api/figma/snapshots/${encodeURIComponent(e)}`,{method:"DELETE",...void 0!==t?{signal:t}:{}})}function s$(e,t){return`/api/figma/snapshots/${encodeURIComponent(e)}/screens/${encodeURIComponent(String(t))}/image`}async function sA(e,t,n){return sN(`/api/figma/snapshots/${encodeURIComponent(e)}/screens/${encodeURIComponent(t)}/json`,{...void 0!==n?{signal:n}:{}})}async function sT(e,t){return sN(`/api/figma/snapshots/${encodeURIComponent(e)}/code`,{method:"POST",...void 0!==t?{signal:t}:{},body:JSON.stringify({})})}async function sL(){return sN("/api/figma/token",{method:"DELETE",body:JSON.stringify({})})}let sP=/"(?:\\(?:["\\/bfnrt]|u[0-9a-fA-F]{4})|[^"\\])*"\s*:?|[-]?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|\b(?:true|false|null)\b|[{}\[\],:]/gu;function sM(e){return 0===e.length?0:"u">typeof TextEncoder?new TextEncoder().encode(e).byteLength:e.length}function sD({text:e,className:t}){let a=function(e){let t=[],n=0;for(let a of e.matchAll(sP)){let l=a[0],i=a.index;i>n&&t.push(e.slice(n,i)),t.push({kind:l.startsWith('"')?l.endsWith(":")?"key":"string":"true"===l||"false"===l?"boolean":"null"===l?"null":/^-?\d/u.test(l)?"number":"punctuation",text:l}),n=i+l.length}return n<e.length&&t.push(e.slice(n)),t}(e);return(0,n.jsx)("pre",{className:t,children:(0,n.jsx)("code",{children:a.map((e,t)=>"string"==typeof e?e:(0,n.jsx)("span",{className:`json-token-${e.kind}`,children:e.text},`${e.kind}-${t.toString()}`))})})}let sq=[];function sF(e){try{let t=new URL(e.trim()),n=t.hostname.toLowerCase();if("https:"!==t.protocol||"figma.com"!==n&&"www.figma.com"!==n||!/^\/(design|file)\//u.test(t.pathname))return!1;let a=t.searchParams.get("node-id");return null!==a&&a.length>0}catch{return!1}}function sO(e){let t=new URL(`https://www.figma.com/design/${e.fileKey}/board`);return t.searchParams.set("node-id",e.nodeId),void 0!==e.version&&e.version.length>0&&t.searchParams.set("version",e.version),t.toString()}function sz(e){return e.displayName??`Snapshot ${(0,aq.formatDate)(e.fetchedAt)}`}function sK(e){return void 0===e||0===e.length?"Latest":e}function sB(e){return e.length<=16?e:`${e.slice(0,12)}…`}function s_(e){return e.management??{}}function sU(e,t){return{runId:e.runId,...void 0!==t.displayName?{displayName:t.displayName}:{},management:s_(t),fileKey:e.fileKey,nodeId:e.nodeId,version:e.version,fetchedAt:e.fetchedAt,screenCount:e.screenCount,skippedCount:e.skippedCount,...void 0!==e.structuralOnlyCount?{structuralOnlyCount:e.structuralOnlyCount}:{},reductionHint:e.reductionHint,integrityHash:e.integrityHash}}let sW=new Set(["FIGMA_PROXY_EGRESS_FAILED","FIGMA_PROXY_UNREACHABLE","FIGMA_PROXY_AUTH_REQUIRED","FIGMA_PROXY_BLOCKED_BY_POLICY"]),sV=new Set(["FIGMA_TLS_CA_FAILURE"]),sH=new Set(["FIGMA_NETWORK_UNREACHABLE","FIGMA_EGRESS_TIMEOUT","FIGMA_EGRESS_FAILED"]);function sY(e){return e instanceof w.ApiError?"FIGMA_UPSTREAM_UNAVAILABLE"===e.code?{title:"Figma is currently unavailable",detail:`${e.code}: ${e.message}`,status:`HTTP ${e.status.toString()}`,remediation:"Retry later — no snapshot was stored.",assertive:!0}:sW.has(e.code)?{title:"Figma snapshot blocked by outbound egress",detail:`${e.code}: ${e.message}`,status:`HTTP ${e.status.toString()}`,remediation:"Check the configured proxy, NO_PROXY rules, and CA bundle, then retry. No snapshot was stored.",assertive:!0}:sV.has(e.code)?{title:"Figma snapshot blocked by outbound egress",detail:`${e.code}: ${e.message}`,status:`HTTP ${e.status.toString()}`,remediation:"A TLS certificate verification failure blocked the request. Check the CA bundle configuration, then retry. No snapshot was stored.",assertive:!0}:sH.has(e.code)?{title:"Figma snapshot blocked by outbound egress",detail:`${e.code}: ${e.message}`,status:`HTTP ${e.status.toString()}`,remediation:"The outbound network request to Figma failed. Check DNS resolution and network connectivity, then retry. No snapshot was stored.",assertive:!0}:{title:"Figma snapshot failed",detail:e.message}:e instanceof Error?{title:"Figma snapshot failed",detail:e.message}:{title:"Figma snapshot failed",detail:"An unexpected error occurred."}}function sG(e){let t=sY(e);return void 0===t.status?t.detail:`${t.detail} (${t.status})`}function sJ(e,t){let n=document.elementFromPoint(e,t);return n instanceof Element&&null!==n.closest("main.workspace")&&null===n.closest(".window")}function sX(e,t){let n={payload:e,clientX:t.clientX,clientY:t.clientY};window.dispatchEvent(new CustomEvent(tm,{detail:n}))}function sQ(e,t){let n={payload:e,clientX:t.clientX,clientY:t.clientY};window.dispatchEvent(new CustomEvent(tv,{detail:n}))}function sZ(e,t){let n={payload:e,clientX:t.clientX,clientY:t.clientY};window.dispatchEvent(new CustomEvent(tw,{detail:n}))}function s0({index:e,screenId:t,name:l,irSummary:i,imageSrc:r,imageByteLength:s,structuralReason:o,onAddSource:c,isSourceSelected:d=!1,dragPayload:u}){let p=(0,a.useRef)(null),m=(0,a.useRef)(!1),h=(0,a.useRef)(!1),f=void 0!==u&&void 0!==c&&!d,g=d?`${l} preview is already the active scoped source`:`Drag screen ${l} to the workspace, or click to add it as a Quality Intelligence source`,v=void 0!==r?(0,n.jsx)(aE.default,{className:"figma-snapshot-screen-image",src:r,alt:`Captured preview for ${l}`,loading:"lazy",width:72,height:54,unoptimized:!0}):(0,n.jsxs)("div",{className:"figma-snapshot-screen-image figma-snapshot-screen-placeholder","aria-label":`Structural data only for ${l}`,role:"img",children:[(0,n.jsx)(j.Icons.layers,{className:"figma-snapshot-screen-frame-icon","aria-hidden":"true"}),(0,n.jsx)("span",{className:"figma-snapshot-screen-placeholder-label",children:"IR"})]});return(0,n.jsxs)("article",{className:"figma-snapshot-screen-card","aria-label":`Screen ${String(e+1)}: ${l}`,children:[void 0!==c?(0,n.jsx)("button",{type:"button",className:"figma-snapshot-screen-preview-btn",onClick:e=>{if(h.current){h.current=!1,e.preventDefault(),e.stopPropagation();return}c?.()},disabled:d,"aria-disabled":d?"true":void 0,"aria-label":g,draggable:f,onDragStart:e=>{f&&(e.dataTransfer.effectAllowed="copy",e.dataTransfer.setData(tp,JSON.stringify(u)),e.dataTransfer.setData("text/plain",l))},onDragEnd:e=>{f&&sJ(e.clientX,e.clientY)&&sX(u,e)},onPointerDown:e=>{f&&0===e.button&&(m.current=!1,p.current={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY},e.currentTarget.setPointerCapture(e.pointerId))},onPointerMove:e=>{let t=p.current;null===t||t.pointerId!==e.pointerId||Math.hypot(e.clientX-t.startX,e.clientY-t.startY)>=6&&e.preventDefault()},onPointerUp:e=>{let t=p.current;if(null===t||t.pointerId!==e.pointerId)return;p.current=null,e.currentTarget.releasePointerCapture(e.pointerId);let n=Math.hypot(e.clientX-t.startX,e.clientY-t.startY);n>=6&&(m.current=!0),n>=6&&void 0!==u&&sJ(e.clientX,e.clientY)&&(e.preventDefault(),h.current=!0,sX(u,e))},onPointerCancel:e=>{let t=p.current;null!==t&&t.pointerId===e.pointerId&&(p.current=null,e.currentTarget.releasePointerCapture(e.pointerId))},onMouseDown:e=>{if(!f||0!==e.button||void 0===u)return;let t=e.clientX,n=e.clientY,a=e=>{Math.hypot(e.clientX-t,e.clientY-n)>=6&&e.preventDefault()},l=e=>{if(window.removeEventListener("mousemove",a),window.removeEventListener("mouseup",l),m.current){m.current=!1;return}Math.hypot(e.clientX-t,e.clientY-n)>=6&&sJ(e.clientX,e.clientY)&&(e.preventDefault(),h.current=!0,sX(u,e))};window.addEventListener("mousemove",a),window.addEventListener("mouseup",l)},children:v}):v,(0,n.jsxs)("div",{className:"figma-snapshot-screen-meta",children:[(0,n.jsx)("h3",{className:"figma-snapshot-screen-name",title:l,children:l}),(0,n.jsx)("p",{className:"figma-snapshot-screen-summary",children:i}),(0,n.jsx)("p",{className:"figma-snapshot-screen-size",children:void 0!==s?(0,aq.formatBytes)(s):`Structural IR only${void 0!==o?` (${o})`:""}`}),(0,n.jsx)("p",{className:"figma-snapshot-screen-id",children:t}),void 0!==c?(0,n.jsx)("div",{className:"figma-snapshot-screen-actions",children:(0,n.jsx)("button",{type:"button",className:"figma-snapshot-screen-source-btn",onClick:c,disabled:d,"aria-disabled":d?"true":void 0,"aria-label":d?`${l} is already the active scoped source`:`Add screen ${l} to the workspace as a Quality Intelligence source`,children:d?"Source active":"Add to workspace"})}):null]})]})}function s1({name:e,screenId:t,irSummary:l,imageSrc:i,imageByteLength:r,structuralReason:s,snapshotRunId:o,capturedAt:c,imageDragPayload:d}){let u=(0,a.useRef)(null),p=(0,a.useRef)(!1),m=void 0!==i&&void 0!==d,h=void 0!==i?(0,n.jsx)(aE.default,{className:"figma-view-preview-image",src:i,alt:`Captured preview for ${e}`,loading:"eager",width:360,height:240,draggable:!1,unoptimized:!0}):(0,n.jsxs)("div",{className:"figma-view-preview-image figma-view-preview-placeholder","aria-label":`Structural data only for ${e}`,role:"img",children:[(0,n.jsx)(j.Icons.layers,{className:"figma-view-preview-icon","aria-hidden":"true"}),(0,n.jsx)("span",{children:"Structural IR"})]});return(0,n.jsxs)("article",{className:"figma-view-source-card","aria-label":`Figma view source: ${e}`,children:[m?(0,n.jsx)("button",{type:"button",className:"figma-view-preview figma-view-preview-drag-surface",draggable:!0,onDragStart:e=>{m&&(e.dataTransfer.effectAllowed="copyMove",e.dataTransfer.setData(ty,JSON.stringify(d)),e.dataTransfer.setData("text/plain",`${d.name}.png`))},onDragEnd:e=>{m&&sJ(e.clientX,e.clientY)&&sZ(d,e)},onKeyDown:e=>{if(!m||"Enter"!==e.key&&" "!==e.key)return;e.preventDefault();let t=e.currentTarget.getBoundingClientRect();sZ(d,{clientX:t.right+24,clientY:t.top+t.height/2})},onPointerDown:e=>{m&&0===e.button&&(p.current=!1,u.current={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY},e.currentTarget.setPointerCapture(e.pointerId))},onPointerMove:e=>{let t=u.current;null===t||t.pointerId!==e.pointerId||Math.hypot(e.clientX-t.startX,e.clientY-t.startY)>=6&&e.preventDefault()},onPointerUp:e=>{let t=u.current;if(null===t||t.pointerId!==e.pointerId)return;u.current=null,e.currentTarget.releasePointerCapture(e.pointerId);let n=Math.hypot(e.clientX-t.startX,e.clientY-t.startY);n>=6&&(p.current=!0),n>=6&&m&&sJ(e.clientX,e.clientY)&&(e.preventDefault(),sZ(d,e))},onPointerCancel:e=>{let t=u.current;null!==t&&t.pointerId===e.pointerId&&(u.current=null,e.currentTarget.releasePointerCapture(e.pointerId))},onMouseDown:e=>{if(!m||0!==e.button)return;let t=e.clientX,n=e.clientY,a=e=>{Math.hypot(e.clientX-t,e.clientY-n)>=6&&e.preventDefault()},l=e=>{if(window.removeEventListener("mousemove",a),window.removeEventListener("mouseup",l),p.current){p.current=!1;return}Math.hypot(e.clientX-t,e.clientY-n)>=6&&sJ(e.clientX,e.clientY)&&(e.preventDefault(),sZ(d,e))};window.addEventListener("mousemove",a),window.addEventListener("mouseup",l)},"aria-label":`Create a standalone image source for ${e}`,title:`Drag image for ${e} to the workspace`,children:h}):(0,n.jsx)("div",{className:"figma-view-preview",children:h}),(0,n.jsxs)("div",{className:"figma-view-source-meta",children:[(0,n.jsx)("p",{className:"figma-view-source-kicker",children:"QI view source"}),(0,n.jsx)("h2",{className:"figma-view-source-title",title:e,children:e}),(0,n.jsx)("p",{className:"figma-view-source-summary",children:l}),(0,n.jsxs)("dl",{className:"figma-view-source-facts",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Screen"}),(0,n.jsx)("dd",{children:t})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Snapshot"}),(0,n.jsx)("dd",{children:o})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Captured"}),(0,n.jsx)("dd",{children:c})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Preview"}),(0,n.jsx)("dd",{children:void 0!==r?(0,aq.formatBytes)(r):`Structural IR${void 0!==s?` (${s})`:""}`})]})]})]})]})}function s2({sourceWindowId:e,snapshotRunId:t,selectedScreenIds:l=sq,selectedScreenName:i,openScreenSource:r,updateCfg:s,triggerImpl:o=sS,loadImpl:c=sC,listImpl:d=sI,updateMetadataImpl:u=sE,deleteImpl:p=sR,loadScreenJsonImpl:m=sA,codegenImpl:h=sT,revokeImpl:f=sL}){let g,v,b,x,y=(0,a.useId)(),k=(0,a.useId)(),N=(0,a.useId)(),S=(0,a.useId)(),[C,I]=(0,a.useState)(""),[E,R]=(0,a.useState)("idle"),[$,A]=(0,a.useState)(null),[T,L]=(0,a.useState)(null),[P,M]=(0,a.useState)(null),[D,q]=(0,a.useState)(null),[F,O]=(0,a.useState)(0),[z,K]=(0,a.useState)("recent"),[B,_]=(0,a.useState)([]),[U,W]=(0,a.useState)([]),[V,H]=(0,a.useState)(!1),[Y,G]=(0,a.useState)(!1),[J,X]=(0,a.useState)(null),[Q,Z]=(0,a.useState)(null),[ee,et]=(0,a.useState)(null),[en,ea]=(0,a.useState)(""),[el,ei]=(0,a.useState)(null),[er,es]=(0,a.useState)(null),[eo,ec]=(0,a.useState)(null),[ed,eu]=(0,a.useState)(null),[ep,em]=(0,a.useState)(!1),[eh,ef]=(0,a.useState)(!1),eg=(0,a.useRef)(null),ev=(0,a.useRef)(null),eb=(0,a.useRef)(null),ex=(0,a.useRef)(null),ey=(0,a.useRef)(null),ew=(0,a.useRef)(null),ej=(0,a.useRef)(null),ek=(0,a.useRef)(null),eN=(0,a.useRef)(!1),eS=(0,a.useCallback)(()=>{ef(!0)},[]),[eC,eI]=(0,a.useState)("idle"),[eE,eR]=(0,a.useState)(null),[e$,eA]=(0,a.useState)(null),[eT,eL]=(0,a.useState)("idle"),[eP,eM]=(0,a.useState)(null),[eD,eq]=(0,a.useState)(null),[eF,eO]=(0,a.useState)(null),[ez,eK]=(0,a.useState)(!1),[eB,e_]=(0,a.useState)(null),[eU,eW]=(0,a.useState)(null),eV=(0,a.useRef)(null),eH=(0,a.useRef)(null),[eY,eG]=(0,a.useState)(24),eJ=l.join("\0"),eX=sF(C),eQ=function(e){let t=e.trim();if(0===t.length||sF(t))return null;try{let e=new URL(t),n=e.hostname.toLowerCase();if("https:"===e.protocol&&("figma.com"===n||"www.figma.com"===n)&&/^\/(design|file)\//u.test(e.pathname))return"Add a node-id by selecting a frame or section in Figma and copying its link (Copy link to selection)."}catch{}return"This doesn't look like a Figma board link. Use a figma.com design/file link that includes a node-id parameter."}(C),eZ=(0,a.useMemo)(()=>null!==$?{fileKey:$.fileKey,nodeId:$.nodeId}:function(e){try{let t=new URL(e.trim()),n=t.hostname.toLowerCase();if("https:"!==t.protocol||"figma.com"!==n&&"www.figma.com"!==n)return null;let[,a,l]=t.pathname.split("/");if("design"!==a&&"file"!==a||void 0===l||0===l.length)return null;let i=t.searchParams.get("node-id");if(null===i||0===i.length)return null;return{fileKey:l,nodeId:i}}catch{return null}}(C),[C,$]),e0=eZ?.fileKey,e1=eZ?.nodeId,e2="building"===E,e4="loading"===E,e3=e2||e4,e6=e2&&null!==D?(v=Math.floor((g=Math.max(0,Math.floor(F/1e3)))/3600),b=Math.floor(g%3600/60),x=g%60,v>0?`${String(v)}h ${String(b)}m ${String(x)}s`:b>0?`${String(b)}m ${String(x)}s`:`${String(x)}s`):null,e5=(0,a.useMemo)(()=>new Set(l),[l]),e8=l.length>0,e7=e8&&void 0!==t&&t.length>0,e9=(0,a.useMemo)(()=>{if(null===$)return[];let e=new Set($.screens.map(e=>e.screenId)),t=[...$.screens.map((e,t)=>({kind:"rendered",screen:e,imageIndex:t})),...($.structuralScreens??[]).filter(t=>!e.has(t.screenId)).map(e=>({kind:"structural",screen:e}))];return e8?t.filter(e=>e5.has(e.screen.screenId)):t},[e8,e5,$]),te=1===l.length?l[0]:void 0,tt=(0,a.useMemo)(()=>null===eP?"":JSON.stringify(eP,null,2),[eP]),tn=(0,a.useMemo)(()=>sM(tt),[tt]),ta=($?.screens.length??0)+($?.structuralScreens?.length??0),tl=null===$?{}:s_($);(0,a.useEffect)(()=>{eh&&"error"===E&&eg.current?.focus()},[eh,E]),(0,a.useEffect)(()=>{ez&&eV.current?.focus()},[ez]),(0,a.useEffect)(()=>{if(!e2||null===D)return;O(Date.now()-D);let e=window.setInterval(()=>{O(Date.now()-D)},1e3);return()=>{window.clearInterval(e)}},[e2,D]),(0,a.useEffect)(()=>()=>{ev.current?.abort(),eb.current?.abort(),ex.current?.abort(),ey.current?.abort(),ew.current?.abort()},[]),(0,a.useEffect)(()=>{null===eZ&&"board"===z&&K("recent")},[eZ,z]);let ti=(0,a.useCallback)(()=>{ey.current?.abort();let e=new AbortController;if(ey.current=e,G(!0),Z(null),d({limit:12,signal:e.signal}).then(e=>{W(e)}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||(W([]),Z(sG(e)))}).finally(()=>{ey.current===e&&G(!1)}),void 0===e0||void 0===e1){_([]),X(null),H(!1);return}H(!0),X(null),d({fileKey:e0,nodeId:e1,limit:12,signal:e.signal}).then(e=>{_(e)}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||(_([]),X(sG(e)))}).finally(()=>{ey.current===e&&H(!1)})},[e0,e1,d]);(0,a.useEffect)(()=>{ti()},[ti,$?.runId]);let tr=(0,a.useCallback)(e=>{if(0===e.length||e3)return;ev.current?.abort();let n=new AbortController;ev.current=n,R("loading"),L(null),M(null),eI("idle"),eR(null),eA(null),eL("idle"),eM(null),eq(null),eO(null),c(e,n.signal).then(e=>{A(e),I(sO(e)),s({snapshotRunId:e.runId}),R("done")}).catch(n=>{n instanceof DOMException&&"AbortError"===n.name||(n instanceof w.ApiError&&"FIGMA_SNAPSHOT_NOT_FOUND"===n.code?(t===e&&s({snapshotRunId:void 0}),L({...sY(n),detail:t===e?`${n.message} The stored run ID has been cleared.`:n.message})):L(sY(n)),R("error"))})},[e3,c,t,s]);(0,a.useEffect)(()=>{e7&&void 0!==t&&0!==t.length&&null===$&&"idle"===E&&tr(t)},[E,e7,tr,t,$]);let ts=(0,a.useCallback)(async(e,t)=>{ev.current?.abort(),eb.current?.abort(),ex.current?.abort(),eb.current=null,ex.current=null;let n=new AbortController;ev.current=n,ej.current={link:e,isResnapshot:t},R("building"),L(null),M(null),q(Date.now()),O(0),eI("idle"),eR(null),eL("idle"),eM(null),eq(null),eO(null);try{let a=await o(e,{acknowledgeReadOnly:ep,isResnapshot:t,signal:n.signal});A(a),I(sO(a)),s({snapshotRunId:a.runId}),R("done"),q(null),O(0),ej.current=null}catch(n){if(n instanceof DOMException&&"AbortError"===n.name)return;if(q(null),O(0),n instanceof w.ApiError&&"FIGMA_CONSENT_REQUIRED"===n.code){let e=sY(n);L({...e,detail:`${e.detail} Tick the acknowledgement checkbox below, then snapshot again.`}),eS()}else n instanceof w.ApiError&&"FIGMA_BUILD_TIMEOUT"===n.code?(M({link:e,isResnapshot:t}),L({title:"Figma snapshot is still running",detail:"This window stopped waiting for the snapshot result. The server may still finish the build in the background.",status:`HTTP ${n.status.toString()}`,remediation:"Reconnect to the same board to keep waiting, or close this window and return later."})):L(sY(n));R("error"),ej.current=null}},[o,s,ep,eS]),to=(0,a.useCallback)(e=>{if(e.preventDefault(),eX&&!e3){if(!ep){L({title:"Figma snapshot failed",detail:"Tick the read-only acknowledgement checkbox below, then snapshot again."}),R("error"),eS();return}ts(C,!1)}},[C,e3,ep,eX,ts,eS]),tc=(0,a.useCallback)(()=>{e3||null!==$&&ts(sO($),!0)},[e3,ts,$]),td=(0,a.useCallback)(()=>{ev.current?.abort(),ev.current=null,q(null),O(0),null!==ej.current&&M(ej.current),ej.current=null,R("idle"),L(null)},[]),tu=(0,a.useCallback)(()=>{e3||null===P||ts(P.link,P.isResnapshot)},[e3,P,ts]),tp=(0,a.useCallback)(()=>{let e=$?.runId??t;if(void 0===e||0===e.length||"generating"===eC)return;let n=new AbortController;eb.current=n,eI("generating"),eA(null),h(e,n.signal).then(e=>{eR(e),eI("done")}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name?eI("idle"):(eA(sG(e)),eI("error"))}).finally(()=>{eb.current===n&&(eb.current=null)})},[h,eC,t,$]),tm=(0,a.useCallback)(()=>{let e=$?.runId??t;if(void 0===e||0===e.length||void 0===te||"loading"===eT)return;ex.current?.abort();let n=new AbortController;ex.current=n,eL("loading"),eq(null),eO(null),m(e,te,n.signal).then(e=>{eM(e),eL("done")}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name?eL("idle"):(eM(null),eq(sG(e)),eL("error"))}).finally(()=>{ex.current===n&&(ex.current=null)})},[te,m,eT,t,$?.runId]),th=(0,a.useCallback)(()=>{if(0!==tt.length){if(void 0===navigator.clipboard)return void eO("Clipboard unavailable");navigator.clipboard.writeText(tt).then(()=>{eO("Copied")}).catch(()=>{eO("Copy failed")})}},[tt]),tf=(0,a.useMemo)(()=>{let n=eP?.runId??$?.runId??t,a=eP?.screen.screenId??te,l=eP?.screen.name??i??a;return void 0===n||0===n.length||void 0===a||0===a.length||void 0===l||0===l.length?null:{snapshotRunId:n,screenId:a,name:l,...void 0!==e?{sourceWindowId:e}:{}}},[te,eP?.runId,eP?.screen.name,eP?.screen.screenId,i,t,e,$?.runId]),tv=(0,a.useCallback)(e=>{null!==tf&&(e.dataTransfer.effectAllowed="copyMove",e.dataTransfer.setData(tg,JSON.stringify(tf)),e.dataTransfer.setData("text/plain",`${tf.name}.json`))},[tf]),tb=(0,a.useCallback)(e=>{null!==tf&&sJ(e.clientX,e.clientY)&&sQ(tf,e)},[tf]),tx=(0,a.useCallback)(e=>{if(null===tf||"Enter"!==e.key&&" "!==e.key)return;e.preventDefault();let t=e.currentTarget.getBoundingClientRect();sQ(tf,{clientX:t.right+24,clientY:t.top+t.height/2})},[tf]),ty=(0,a.useCallback)(e=>{null!==tf&&0===e.button&&(eN.current=!1,ek.current={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY},e.currentTarget.setPointerCapture(e.pointerId))},[tf]),tw=(0,a.useCallback)(e=>{let t=ek.current;null===t||t.pointerId!==e.pointerId||Math.hypot(e.clientX-t.startX,e.clientY-t.startY)>=6&&e.preventDefault()},[]),tj=(0,a.useCallback)(e=>{let t=ek.current;if(null===t||t.pointerId!==e.pointerId)return;ek.current=null,e.currentTarget.releasePointerCapture(e.pointerId);let n=Math.hypot(e.clientX-t.startX,e.clientY-t.startY);n>=6&&(eN.current=!0),n>=6&&null!==tf&&sJ(e.clientX,e.clientY)&&(e.preventDefault(),sQ(tf,e))},[tf]),tk=(0,a.useCallback)(e=>{let t=ek.current;null!==t&&t.pointerId===e.pointerId&&(ek.current=null,e.currentTarget.releasePointerCapture(e.pointerId))},[]),tN=(0,a.useCallback)(e=>{if(null===tf||0!==e.button)return;let t=e.clientX,n=e.clientY,a=e=>{Math.hypot(e.clientX-t,e.clientY-n)>=6&&e.preventDefault()},l=e=>{if(window.removeEventListener("mousemove",a),window.removeEventListener("mouseup",l),eN.current){eN.current=!1;return}Math.hypot(e.clientX-t,e.clientY-n)>=6&&sJ(e.clientX,e.clientY)&&(e.preventDefault(),sQ(tf,e))};window.addEventListener("mousemove",a),window.addEventListener("mouseup",l)},[tf]),tS=(0,a.useCallback)(()=>{eb.current?.abort(),eb.current=null,eI("idle"),eA(null)},[]),tC=(0,a.useCallback)(()=>{void 0===t||0===t.length||e3||tr(t)},[e3,tr,t]);(0,a.useEffect)(()=>{eG(24)},[eJ,$?.runId]),(0,a.useEffect)(()=>{ex.current?.abort(),ex.current=null,eL("idle"),eM(null),eq(null),eO(null)},[eJ,t]);let tI=(0,a.useCallback)(()=>{eK(!1),eW(null),e_(null),f().then(e=>{e_(e.message),requestAnimationFrame(()=>eH.current?.focus())}).catch(e=>{eW(sG(e)),requestAnimationFrame(()=>eH.current?.focus())})},[f]),tE=(0,a.useCallback)(()=>{eK(!1),requestAnimationFrame(()=>eH.current?.focus())},[]),tR=(0,a.useCallback)(e=>{et(e.runId),ea(e.displayName??""),ei(null),es(null),eu(null)},[]),t$=(0,a.useCallback)(()=>{et(null),ea("")},[]),tA=(0,a.useCallback)(e=>{if(null!==eo)return;ew.current?.abort();let t=new AbortController;ew.current=t,ec(e),eu(null);let n=en.trim();u(e,0===n.length?null:n,t.signal).then(t=>{$?.runId===e&&A(t),_(n=>n.map(n=>n.runId===e?sU(n,t):n)),W(n=>n.map(n=>n.runId===e?sU(n,t):n)),et(null),ea("")}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||eu(sG(e))}).finally(()=>{ew.current===t&&(ew.current=null),ec(null)})},[en,eo,$?.runId,u]),tT=(0,a.useCallback)(e=>{ei(t=>t===e?null:e),et(null),es(null),eu(null)},[]),tL=(0,a.useCallback)(e=>{es(e),et(null),ei(null),eu(null)},[]),tP=(0,a.useCallback)(e=>{if(null!==eo)return;ew.current?.abort();let n=new AbortController;ew.current=n,ec(e),eu(null),p(e,n.signal).then(n=>{_(t=>t.filter(t=>t.runId!==e)),W(t=>t.filter(t=>t.runId!==e)),es(null),et(null),ei(null),$?.runId===e&&(A(null),R("idle"),eI("idle"),eR(null),eL("idle"),eM(null)),($?.runId===e||t===e)&&s({snapshotRunId:void 0})}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||eu(sG(e))}).finally(()=>{ew.current===n&&(ew.current=null),ec(null)})},[p,eo,t,$?.runId,s]),tM=void 0!==t&&t.length>0&&null===$&&("idle"===E||"loading"===E||"error"===E),tD=(e,a,l,i,r,s)=>a?(0,n.jsx)("p",{className:"figma-snapshot-dashboard-status",children:"Loading snapshots…"}):null!==l?(0,n.jsx)("p",{className:"figma-snapshot-dashboard-status figma-snapshot-dashboard-status-error",children:l}):0===e.length?(0,n.jsxs)("div",{className:"figma-snapshot-dashboard-empty",children:[(0,n.jsx)("p",{className:"figma-snapshot-dashboard-empty-title",children:i}),(0,n.jsx)("p",{className:"figma-snapshot-dashboard-empty-detail",children:r})]}):(0,n.jsx)("div",{className:"figma-snapshot-dashboard-list",role:"list",children:e.map(e=>{let a=$?.runId===e.runId,l=sz(e),i=s_(e),r=eo===e.runId,o=el===e.runId,c=ee===e.runId,d=er===e.runId;return(0,n.jsxs)("article",{className:"figma-snapshot-dashboard-item",role:"listitem","aria-current":a?"true":void 0,"aria-busy":e4&&t===e.runId?"true":void 0,children:[(0,n.jsxs)("div",{className:"figma-snapshot-dashboard-item-head",children:[(0,n.jsxs)("div",{className:"figma-snapshot-dashboard-item-title-block",children:[(0,n.jsx)("h3",{className:"figma-snapshot-dashboard-item-title",title:l,children:l}),(0,n.jsx)("span",{className:"figma-snapshot-dashboard-item-date",children:(0,aq.formatDate)(e.fetchedAt)})]}),a&&(0,n.jsx)("span",{className:"figma-snapshot-dashboard-item-badge",children:"Current"}),(0,n.jsxs)("div",{className:"figma-snapshot-dashboard-item-actions",children:[(0,n.jsx)("button",{type:"button",className:"figma-snapshot-dashboard-load",onClick:()=>{tr(e.runId)},disabled:e3,"aria-disabled":e3?"true":void 0,"aria-label":`Load snapshot ${l}`,children:"Load"}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-dashboard-icon-btn",onClick:()=>tR(e),disabled:r,"aria-label":`Rename snapshot ${l}`,title:"Rename",children:(0,n.jsx)(j.Icons.edit,{"aria-hidden":"true"})}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-dashboard-icon-btn",onClick:()=>tT(e.runId),"aria-expanded":o,"aria-label":`${o?"Hide":"Show"} metadata for snapshot ${l}`,title:"Metadata",children:(0,n.jsx)(j.Icons.info,{"aria-hidden":"true"})}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-dashboard-icon-btn figma-snapshot-dashboard-icon-btn-danger",onClick:()=>tL(e.runId),disabled:r,"aria-label":`Delete snapshot ${l}`,title:"Delete",children:(0,n.jsx)(j.Icons.trash,{"aria-hidden":"true"})})]})]}),(0,n.jsx)("p",{className:"figma-snapshot-dashboard-item-hint",children:e.reductionHint}),(0,n.jsxs)("p",{className:"figma-snapshot-dashboard-item-meta",children:[e.screenCount.toString()," screen",1!==e.screenCount?"s":"",e.skippedCount>0?`, ${e.skippedCount.toString()} skipped`:", no skipped renders"]}),s&&(0,n.jsxs)("p",{className:"figma-snapshot-dashboard-item-scope",children:[e.fileKey," · ",e.nodeId]}),c?(0,n.jsxs)("form",{className:"figma-snapshot-dashboard-rename",onSubmit:t=>{t.preventDefault(),tA(e.runId)},children:[(0,n.jsx)("input",{type:"text",className:"figma-snapshot-dashboard-rename-input",value:en,onChange:e=>ea(e.target.value),maxLength:120,disabled:r,"aria-label":`Snapshot name for ${l}`,placeholder:"Snapshot name"}),(0,n.jsx)("button",{type:"submit",className:"figma-snapshot-dashboard-rename-save",disabled:r,"aria-busy":r,children:"Save"}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-dashboard-rename-cancel",onClick:t$,disabled:r,children:"Cancel"})]}):null,d?(0,n.jsxs)("div",{className:"figma-snapshot-dashboard-delete-confirm",children:[(0,n.jsx)("span",{children:"Delete this snapshot?"}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-dashboard-delete-confirm-btn",onClick:()=>tP(e.runId),disabled:r,"aria-busy":r,children:"Delete"}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-dashboard-delete-cancel-btn",onClick:()=>es(null),disabled:r,children:"Cancel"})]}):null,o?(0,n.jsxs)("dl",{className:"figma-snapshot-dashboard-details",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Run"}),(0,n.jsx)("dd",{children:e.runId})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Version"}),(0,n.jsx)("dd",{children:sK(e.version)})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Integrity"}),(0,n.jsx)("dd",{title:e.integrityHash,children:sB(e.integrityHash)})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Structural"}),(0,n.jsx)("dd",{children:(e.structuralOnlyCount??0).toString()})]}),void 0!==i.updatedAt?(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Name updated"}),(0,n.jsx)("dd",{children:(0,aq.formatDate)(i.updatedAt)})]}):null]}):null]},e.runId)})});if(e7){let a=i??l.join(", "),r=void 0!==te&&($?.runId??t)!==void 0&&"loading"!==eT;return(0,n.jsxs)("section",{className:"figma-snapshot-window figma-view-window","aria-label":`Figma view source ${a}`,children:[(0,n.jsxs)("div",{className:"figma-view-source-header",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"figma-view-source-eyebrow",children:"Figma view"}),(0,n.jsx)("h1",{className:"figma-view-source-heading",title:a,children:a})]}),(0,n.jsxs)("div",{className:"figma-view-source-actions",children:[(0,n.jsx)("span",{className:"figma-view-source-badge",children:"QI source"}),(0,n.jsx)("button",{type:"button",className:"figma-view-json-btn",onClick:tm,disabled:!r,"aria-disabled":r?void 0:"true","aria-busy":"loading"===eT?"true":void 0,children:"loading"===eT?"Loading JSON…":"Inspect JSON"})]})]}),(0,n.jsxs)("div",{id:k,role:"status","aria-live":"polite","aria-atomic":"true",className:"figma-snapshot-status",children:[e4&&(0,n.jsx)("p",{className:"figma-snapshot-progress",children:"Loading view preview…"}),"error"===E&&null!==T&&(0,n.jsx)("p",{className:"figma-snapshot-error",children:T.detail}),"done"===E&&null!==$&&(0,n.jsxs)("p",{className:"sr-only",children:["Figma view loaded — ",a,"."]})]}),null===$?(0,n.jsxs)("div",{className:"figma-view-source-empty",children:[(0,n.jsx)("p",{className:"figma-view-source-empty-title",children:e4?"Loading the selected view…":"Selected view preview not loaded."}),!e4&&(0,n.jsx)("button",{type:"button",className:"figma-snapshot-load-btn",onClick:tC,children:"Load view"})]}):e9.length>0?e9.map(t=>{let a="rendered"===t.kind?s$($.runId,t.imageIndex):void 0,l=void 0===a?void 0:{snapshotRunId:$.runId,screenId:t.screen.screenId,name:t.screen.name,imageSrc:a,...void 0!==e?{sourceWindowId:e}:{}};return(0,n.jsx)(s1,{name:t.screen.name,screenId:t.screen.screenId,irSummary:t.screen.irSummary,imageSrc:a,imageByteLength:"rendered"===t.kind?t.screen.imageByteLength:void 0,structuralReason:"structural"===t.kind?t.screen.reason:void 0,snapshotRunId:$.runId,capturedAt:(0,aq.formatDate)($.fetchedAt),imageDragPayload:l},t.screen.screenId)}):(0,n.jsx)("div",{className:"lk-empty",children:(0,n.jsx)("p",{className:"lk-empty-body",children:"The selected screen is not present in this stored snapshot."})}),"error"===eT&&null!==eD?(0,n.jsx)("p",{className:"figma-snapshot-error",role:"alert",children:eD}):null,"done"===eT&&null!==eP?(0,n.jsxs)("section",{className:"figma-view-json-inspector","aria-label":`Scoped JSON for ${eP.screen.name}`,children:[(0,n.jsxs)("div",{className:"figma-view-json-inspector-header",children:[(0,n.jsxs)("div",{className:"figma-view-json-drag-surface",role:"button",tabIndex:null!==tf?0:-1,draggable:!1,onDragStart:tv,onDragEnd:tb,onKeyDown:tx,onPointerDown:ty,onPointerMove:tw,onPointerUp:tj,onPointerCancel:tk,onMouseDown:tN,"aria-label":`Create a standalone JSON source for ${eP.screen.name}`,"aria-disabled":null===tf?"true":void 0,title:`Drag JSON for ${eP.screen.name} to the workspace`,children:[(0,n.jsx)("p",{className:"figma-view-json-kicker",children:"Stored Screen-IR JSON"}),(0,n.jsx)("h2",{className:"figma-view-json-title",children:eP.screen.screenId}),(0,n.jsxs)("p",{className:"figma-view-json-meta",children:[eP.screen.kind," · ",(0,aq.formatBytes)(tn)," ·"," ",eP.relatedLinks.length.toString()," related link",1!==eP.relatedLinks.length?"s":""]})]}),(0,n.jsx)("button",{type:"button",className:"figma-view-json-copy-btn",onClick:th,children:"Copy JSON"})]}),null!==eF?(0,n.jsx)("p",{className:"figma-view-json-copy-status",role:"status",children:eF}):null,(0,n.jsx)(sD,{text:tt,className:"figma-view-json-code"})]}):null]})}return(0,n.jsxs)("section",{className:"figma-snapshot-window","aria-label":"Figma Snapshot",children:[(0,n.jsxs)("form",{className:"figma-snapshot-form",onSubmit:to,noValidate:!0,children:[(0,n.jsx)("label",{className:"figma-snapshot-label",htmlFor:y,children:"Board link"}),(0,n.jsxs)("div",{className:"figma-snapshot-input-row",children:[(0,n.jsx)("input",{id:y,type:"url",className:"figma-snapshot-input",placeholder:"https://www.figma.com/design/…?node-id=…",value:C,onChange:e=>{I(e.target.value),null!==T&&L(null),"error"===E&&R("idle"),null!==P&&M(null),eh&&ef(!1)},"aria-describedby":null!==eQ?`${N} ${k}`:k,"aria-invalid":null!==eQ?"true":void 0,readOnly:e3,autoComplete:"off",spellCheck:!1}),(0,n.jsx)("button",{type:"submit",className:"figma-snapshot-trigger-btn",disabled:!eX&&!e3,"aria-disabled":!eX||e3?"true":void 0,"aria-busy":e2,children:e2?"Building…":"Snapshot"})]}),null!==eQ&&(0,n.jsx)("p",{id:N,className:"figma-snapshot-link-error",role:"alert",children:eQ}),(0,n.jsxs)("label",{className:"figma-snapshot-consent",children:[(0,n.jsx)("input",{type:"checkbox",className:"figma-snapshot-consent-checkbox",ref:eg,checked:ep,"aria-invalid":eh?"true":void 0,onChange:e=>{em(e.target.checked),null!==T&&L(null),"error"===E&&R("idle"),ef(!1)},disabled:e2}),(0,n.jsxs)("span",{children:["I acknowledge the configured Figma PAT is read-only and least-privilege (",(0,n.jsx)("code",{children:"file_content:read"}),")."," ",(0,n.jsx)("span",{className:"figma-snapshot-consent-required",children:"Required before the first snapshot of a board."})]})]}),(0,n.jsx)("p",{className:"figma-snapshot-hint",children:"Paste a Figma board link with a node-id param (section or frame anchor). The access token is resolved server-side — it never reaches this page."})]}),"error"===E&&null!==T&&!0===T.assertive&&(0,n.jsxs)("div",{className:"figma-snapshot-error-card",role:"alert","aria-labelledby":`${k}-error-title`,children:[(0,n.jsx)("p",{id:`${k}-error-title`,className:"figma-snapshot-error-title",children:T.title}),(0,n.jsx)("p",{className:"figma-snapshot-error-detail",children:T.detail}),void 0!==T.status&&(0,n.jsx)("p",{className:"figma-snapshot-error-status",children:T.status}),void 0!==T.remediation&&(0,n.jsx)("p",{className:"figma-snapshot-error-remediation",children:T.remediation})]}),(0,n.jsxs)("div",{id:k,role:"status","aria-live":"polite","aria-atomic":"true",className:"figma-snapshot-status",children:[e2&&(0,n.jsxs)("p",{className:"figma-snapshot-progress",children:["Building snapshot — fetching screens from Figma…"," ",null!==e6?`${e6} elapsed.`:""," Large boards can take several minutes."]}),e4&&(0,n.jsx)("p",{className:"figma-snapshot-progress",children:"Loading stored snapshot…"}),"done"===E&&null!==$&&(0,n.jsxs)("p",{className:"sr-only",children:["Snapshot complete — ",$.reductionHint,"."]}),"done"===eC&&null!==eE&&(0,n.jsxs)("p",{className:"sr-only",children:["Code generated — ",String(eE.fileCount)," file",1!==eE.fileCount?"s":""," ready for review."]}),"idle"===E&&(0,n.jsx)("p",{className:"sr-only","aria-live":"polite"}),"error"===E&&null!==T&&!0!==T.assertive&&(0,n.jsx)("p",{className:"figma-snapshot-error",children:T.detail})]}),e2&&(0,n.jsxs)("div",{className:"figma-snapshot-cancel-row",children:[(0,n.jsx)("button",{type:"button",className:"figma-snapshot-cancel-btn",onClick:td,children:"Cancel"}),(0,n.jsx)("p",{className:"figma-snapshot-cancel-note",role:"status","aria-live":"polite",children:"Cancelling stops this window from waiting — the server-side build continues on demand."})]}),null!==P&&!e3&&(0,n.jsxs)("div",{className:"figma-snapshot-stored-notice",children:[(0,n.jsx)("p",{className:"figma-snapshot-stored-text",children:"This window is no longer waiting. The server may still be building the snapshot in the background. You can close this window safely."}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-load-btn",onClick:tu,children:"Reconnect build"})]}),"idle"===E&&null===$&&null===P&&!tM&&(0,n.jsxs)("div",{className:"figma-snapshot-empty",children:[(0,n.jsx)("p",{className:"figma-snapshot-empty-title",children:"Capture screens from a Figma board"}),(0,n.jsxs)("ol",{className:"figma-snapshot-empty-steps",children:[(0,n.jsx)("li",{children:"In Figma, select the frame or section you want to capture."}),(0,n.jsx)("li",{children:"Copy its link (Copy link to selection) — it contains the node-id."}),(0,n.jsx)("li",{children:"Paste it above, acknowledge the read-only scope, then take the snapshot."})]}),(0,n.jsx)("p",{className:"figma-snapshot-empty-note",children:"The snapshot stores the captured screens and their structure as immutable evidence — connect this window to Quality Intelligence to ground generated tests in the design. Requires a Figma access token configured on the server."})]}),tM&&(0,n.jsxs)("div",{className:"figma-snapshot-stored-notice",children:[(0,n.jsx)("p",{className:"figma-snapshot-stored-text",children:"A stored snapshot is available."}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-load-btn",onClick:tC,"aria-disabled":e4?"true":void 0,"aria-busy":e4,children:e4?"Loading…":"Load snapshot"})]}),(0,n.jsxs)("section",{className:"figma-snapshot-dashboard","aria-label":"Snapshot dashboard",children:[(0,n.jsxs)("div",{className:"figma-snapshot-dashboard-header",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"figma-snapshot-dashboard-eyebrow",children:"Snapshot dashboard"}),(0,n.jsx)("h2",{className:"figma-snapshot-dashboard-title",children:"Stored snapshots"})]}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-dashboard-refresh",onClick:ti,children:"Refresh"})]}),(0,n.jsxs)("div",{className:"figma-snapshot-dashboard-tabs",role:"tablist","aria-label":"Snapshot views",children:[(0,n.jsx)("button",{type:"button",className:"figma-snapshot-dashboard-tab",role:"tab","aria-selected":"board"===z,"aria-controls":`${S}-board-panel`,id:`${S}-board-tab`,onClick:()=>{null!==eZ&&K("board")},disabled:null===eZ,children:"This board"}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-dashboard-tab",role:"tab","aria-selected":"recent"===z,"aria-controls":`${S}-recent-panel`,id:`${S}-recent-tab`,onClick:()=>{K("recent")},children:"Recent"})]}),null!==ed?(0,n.jsx)("p",{className:"figma-snapshot-dashboard-status figma-snapshot-dashboard-status-error",role:"alert",children:ed}):null,"board"===z?(0,n.jsx)("div",{id:`${S}-board-panel`,className:"figma-snapshot-dashboard-panel",role:"tabpanel","aria-labelledby":`${S}-board-tab`,children:null===eZ?tD([],!1,null,"No board selected yet","Paste a valid Figma board link or load a stored snapshot to see this board's history.",!1):tD(B,V,J,"No snapshots stored for this board","Take the first snapshot for this board to make it available here.",!1)}):(0,n.jsx)("div",{id:`${S}-recent-panel`,className:"figma-snapshot-dashboard-panel",role:"tabpanel","aria-labelledby":`${S}-recent-tab`,children:tD(U,Y,Q,"No snapshots stored yet","Stored Figma snapshots will appear here once the first board capture completes.",!0)})]}),null!==$&&(0,n.jsxs)("div",{className:"figma-snapshot-result",children:[(0,n.jsxs)("div",{className:"figma-snapshot-reduction",children:[(0,n.jsxs)("div",{className:"figma-snapshot-result-head",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("h2",{className:"figma-snapshot-result-title",title:sz($),children:sz($)}),(0,n.jsx)("p",{className:"figma-snapshot-result-run",children:$.runId})]}),(0,n.jsx)("span",{className:"figma-snapshot-result-hash",title:$.integrityHash,children:sB($.integrityHash)})]}),(0,n.jsx)("p",{className:"figma-snapshot-reduction-hint",children:$.reductionHint}),(0,n.jsxs)("p",{className:"figma-snapshot-captured-at",children:["Captured ",(0,aq.formatDate)($.fetchedAt)]}),(0,n.jsxs)("dl",{className:"figma-snapshot-result-metadata",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"File"}),(0,n.jsx)("dd",{children:$.fileKey})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Node"}),(0,n.jsx)("dd",{children:$.nodeId})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Version"}),(0,n.jsx)("dd",{children:sK($.version)})]}),void 0!==tl.updatedAt?(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Name updated"}),(0,n.jsx)("dd",{children:(0,aq.formatDate)(tl.updatedAt)})]}):null]}),e8&&(0,n.jsxs)("p",{className:"figma-snapshot-scope-note",children:["QI source scope: ",i??l.join(", ")]}),$.skippedCount>0&&(0,n.jsxs)("p",{className:"figma-snapshot-skipped-notice",children:[String($.skippedCount)," screen",1!==$.skippedCount?"s":""," could not be rendered and were skipped."]})]}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-resnapshot-btn",onClick:tc,"aria-disabled":e3?"true":void 0,"aria-busy":e2,"aria-label":"Re-snapshot this board",children:e2?"Building…":"Re-snapshot"}),(0,n.jsxs)("div",{className:"figma-snapshot-codegen",children:[(0,n.jsxs)("div",{className:"figma-snapshot-codegen-actions",children:[(0,n.jsx)("button",{type:"button",className:"figma-snapshot-codegen-btn",onClick:tp,"aria-disabled":"generating"===eC?"true":void 0,"aria-busy":"generating"===eC,children:"generating"===eC?"Generating code…":"Generate code"}),"generating"===eC&&(0,n.jsx)("button",{type:"button",className:"figma-snapshot-codegen-cancel-btn",onClick:tS,children:"Cancel"})]}),"error"===eC&&null!==e$&&(0,n.jsx)("p",{className:"figma-snapshot-error",role:"alert",children:e$}),"done"===eC&&null!==eE&&(0,n.jsxs)("div",{className:"figma-snapshot-code-result",children:[(0,n.jsxs)("p",{className:"figma-snapshot-code-summary",children:[String(eE.fileCount)," reviewable file",1!==eE.fileCount?"s":""," (",String(eE.screenCount)," screen",1!==eE.screenCount?"s":"",","," ",eE.adapterName,") — proposal only, never auto-applied."]}),eE.files.map(e=>(0,n.jsxs)("details",{className:"figma-snapshot-code-file",children:[(0,n.jsx)("summary",{className:"figma-snapshot-code-file-path",children:e.path}),(0,n.jsx)("pre",{className:"figma-snapshot-code-file-contents",children:(0,n.jsx)("code",{children:e.contents})})]},e.path))]})]}),(0,n.jsxs)("details",{className:"figma-snapshot-scopes",children:[(0,n.jsx)("summary",{className:"figma-snapshot-scopes-summary",children:"Required Figma PAT scopes"}),(0,n.jsx)("ul",{className:"figma-snapshot-scopes-list",children:(0,n.jsxs)("li",{children:[(0,n.jsx)("code",{children:"file_content:read"})," — read design file structure, node metadata, and rendered images"]})}),(0,n.jsxs)("p",{className:"figma-snapshot-scopes-note",children:["The token is read server-side from the vault, Keiko config, or"," ",(0,n.jsx)("code",{children:"FIGMA_ACCESS_TOKEN"})," environment variable. This window never holds or transmits the token."]}),(0,n.jsxs)("div",{className:"figma-snapshot-revoke-row",children:[ez?(0,n.jsxs)("span",{className:"figma-snapshot-revoke-confirm",children:[(0,n.jsx)("span",{className:"figma-snapshot-revoke-confirm-label",children:"Really revoke the stored token?"}),(0,n.jsx)("button",{ref:eV,type:"button",className:"figma-snapshot-revoke-confirm-btn",onClick:tI,children:"Yes, revoke"}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-revoke-cancel-btn",onClick:tE,children:"Cancel"})]}):(0,n.jsx)("button",{ref:eH,type:"button",className:"figma-snapshot-revoke-btn",onClick:()=>{eK(!0),e_(null),eW(null)},children:"Revoke stored token"}),(0,n.jsx)("p",{className:"figma-snapshot-revoke-status",role:"status","aria-live":"polite","aria-atomic":"true",children:eB??eU??""})]})]}),e9.length>0?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("section",{className:"figma-snapshot-gallery","aria-label":e8?`${String(e9.length)} selected screen${1!==e9.length?"s":""}`:`${String(ta)} captured and structural screen${1!==ta?"s":""}`,children:e9.slice(0,eY).map((e,t)=>{let a=void 0===r?void 0:()=>r({snapshotRunId:$.runId,screenId:e.screen.screenId,name:e.screen.name}),l={snapshotRunId:$.runId,screenId:e.screen.screenId,name:e.screen.name};return"rendered"===e.kind?(0,n.jsx)(s0,{index:t,screenId:e.screen.screenId,name:e.screen.name,irSummary:e.screen.irSummary,imageSrc:s$($.runId,e.imageIndex),imageByteLength:e.screen.imageByteLength,onAddSource:a,isSourceSelected:e5.has(e.screen.screenId),dragPayload:l},e.screen.screenId):(0,n.jsx)(s0,{index:t,screenId:e.screen.screenId,name:e.screen.name,irSummary:e.screen.irSummary,structuralReason:e.screen.reason,onAddSource:a,isSourceSelected:e5.has(e.screen.screenId),dragPayload:l},e.screen.screenId)})}),eY<e9.length?(0,n.jsx)("button",{type:"button",className:"figma-snapshot-gallery-more",onClick:()=>eG(e=>Math.min(e+24,e9.length)),children:"Show more screens"}):null]}):(0,n.jsx)("div",{className:"lk-empty",children:(0,n.jsx)("p",{className:"lk-empty-body",children:e8?"The selected screen is not present in this stored snapshot.":"No screens were captured from this board section."})})]})]})}function s4({snapshotRunId:e,screenId:t,screenName:l,loadScreenJsonImpl:i=sA}){let r,s=(0,a.useRef)(null),[o,c]=(0,a.useState)("idle"),[d,u]=(0,a.useState)(null),[p,m]=(0,a.useState)(null),[h,f]=(0,a.useState)(null),g=void 0!==(r=l?.trim())&&r.length>0?r:t?.trim()??"Selected Figma view",v=(0,a.useMemo)(()=>null===d?"":JSON.stringify(d,null,2),[d]),b=(0,a.useMemo)(()=>sM(v),[v]),x=(0,a.useCallback)(()=>{if(void 0===e||0===e.trim().length||void 0===t||0===t.trim().length){u(null),c("error"),m("Missing Figma JSON source reference.");return}s.current?.abort();let n=new AbortController;s.current=n,c("loading"),m(null),f(null),i(e,t,n.signal).then(e=>{u(e),c("done")}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||(u(null),m(e instanceof Error?e.message:"Failed to load Figma JSON."),c("error"))}).finally(()=>{s.current===n&&(s.current=null)})},[i,t,e]);(0,a.useEffect)(()=>(x(),()=>{s.current?.abort(),s.current=null}),[x]);let y=(0,a.useCallback)(()=>{if(0!==v.length){if(void 0===navigator.clipboard)return void f("Clipboard unavailable");navigator.clipboard.writeText(v).then(()=>f("Copied")).catch(()=>f("Copy failed"))}},[v]);return(0,n.jsxs)("section",{className:"figma-json-window","aria-label":`Figma JSON source ${g}`,children:[(0,n.jsxs)("header",{className:"figma-json-header",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"figma-json-eyebrow",children:"Figma JSON"}),(0,n.jsx)("h1",{className:"figma-json-heading",title:g,children:g}),(0,n.jsx)("p",{className:"figma-json-meta",children:null!==d?`${d.screen.kind} \xb7 ${(0,aq.formatBytes)(b)} \xb7 captured ${(0,aq.formatDate)(d.fetchedAt)}`:t})]}),(0,n.jsxs)("div",{className:"figma-json-actions",children:[(0,n.jsx)("span",{className:"figma-view-source-badge",children:"QI source"}),(0,n.jsx)("button",{type:"button",className:"figma-view-json-copy-btn",onClick:y,disabled:0===v.length,"aria-disabled":0===v.length?"true":void 0,children:"Copy JSON"})]})]}),"loading"===o?(0,n.jsx)("p",{className:"figma-json-status",role:"status",children:"Loading JSON…"}):null,"error"===o&&null!==p?(0,n.jsxs)("div",{className:"figma-json-error",role:"alert",children:[(0,n.jsx)("p",{children:p}),(0,n.jsx)("button",{type:"button",className:"figma-snapshot-load-btn",onClick:x,children:"Retry"})]}):null,null!==h?(0,n.jsx)("p",{className:"figma-view-json-copy-status",role:"status",children:h}):null,"done"===o&&v.length>0?(0,n.jsx)(sD,{text:v,className:"figma-json-code"}):null]})}function s3({imageSrc:e,screenName:t}){let a,l=void 0!==(a=t?.trim())&&a.length>0?a:"Figma image source";return void 0===e||0===e.trim().length?(0,n.jsx)("section",{className:"figma-image-window","aria-label":l,children:(0,n.jsx)("div",{className:"figma-image-missing",role:"alert",children:"Image preview is unavailable."})}):(0,n.jsx)("section",{className:"figma-image-window","aria-label":l,children:(0,n.jsx)(aE.default,{className:"figma-image-preview",src:e,alt:l,width:720,height:480,unoptimized:!0,priority:!0})})}async function s6(e,t){let n=(t?.method??"GET").toUpperCase(),a="GET"!==n&&"HEAD"!==n,l=await fetch(e,{...t,headers:{Accept:"application/json",...a?{"Content-Type":"application/json"}:{},...a?{"X-Keiko-CSRF":"1"}:{},...t?.headers??{}}});if(!l.ok){let e="INTERNAL",t=`HTTP ${l.status.toString()}`;try{let n=await l.json();e=n.error.code,t=n.error.message}catch{}throw new w.ApiError(e,t,l.status)}return l.json()}async function s5(){return s6("/api/quality-intelligence/runs")}async function s8(e){return s6(`/api/quality-intelligence/runs/${encodeURIComponent(e)}`)}async function s7(e){let t="QI_RUN_FAILED",n=`HTTP ${e.status.toString()}`;try{let a=await e.json();t=a.error?.code??t,n=a.error?.message??n}catch{}return new w.ApiError(t,n,e.status)}async function s9(e,t,n){let a=await fetch("/api/quality-intelligence/runs",{method:"POST",headers:{Accept:"text/event-stream","Content-Type":"application/json","X-Keiko-CSRF":"1"},body:JSON.stringify(e),signal:t}),l=a.headers.get("content-type")??"";if(!a.ok||!l.includes("text/event-stream"))throw await s7(a);let i=a.body;if(null===i)throw new w.ApiError("QI_NO_STREAM","The server did not return a progress stream.",a.status);let r=i.getReader(),s=new TextDecoder,o="";try{for(;!t.aborted;){let e=await r.read();if(e.done)break;let t=(o+=s.decode(e.value,{stream:!0})).split("\n");for(let e of(o=t.pop()??"",t)){let t=e.trim();if(t.startsWith("data:"))try{n(JSON.parse(t.slice(5).trim()))}catch{}}}}finally{await r.cancel().catch(()=>{}),r.releaseLock()}}async function oe(e){return s6(`/api/quality-intelligence/runs/${encodeURIComponent(e)}`,{method:"DELETE"})}async function ot(e,t,n,a){return s6(`/api/quality-intelligence/runs/${encodeURIComponent(e)}/review`,{method:"POST",body:JSON.stringify({action:t,...void 0!==n?{candidateId:n}:{},...void 0!==a?{reviewerLabel:a}:{}})})}async function on(e,t,n,a){return(await s6(`/api/quality-intelligence/runs/${encodeURIComponent(e)}/edit`,{method:"POST",body:JSON.stringify({candidateId:t,edited:n,...void 0!==a?{editorLabel:a}:{}})})).candidate}async function oa(e,t){return s6(`/api/quality-intelligence/runs/${encodeURIComponent(e)}/re-check`,{method:"POST",body:JSON.stringify({sources:t})})}async function ol(e,t){return s6(`/api/quality-intelligence/runs/${encodeURIComponent(e)}/regenerate-stale`,{method:"POST",body:JSON.stringify({sources:t})})}async function oi(e,t,n){return s6(`/api/quality-intelligence/runs/${encodeURIComponent(e)}/export`,{method:"POST",body:JSON.stringify({adapter:t,dryRun:n?.dryRun??!1,approvedOnly:n?.approvedOnly??!1})})}async function or(e,t){return s6(`/api/quality-intelligence/runs/${encodeURIComponent(e)}/traceability`,{method:"POST",body:JSON.stringify({format:t})})}var os=e.i(68336);let oo={open:"Open",approved:"Approved","changes-requested":"Changes requested",rejected:"Rejected",withdrawn:"Withdrawn"},oc={open:"qi-review-open",approved:"qi-review-approved","changes-requested":"qi-review-changes",rejected:"qi-review-rejected",withdrawn:"qi-review-withdrawn"};function od({state:e}){return(0,n.jsxs)("span",{className:`qi-review-badge ${oc[e]}`,children:[(0,n.jsx)("span",{className:"sr-only",children:"Review: "}),oo[e]]})}function ou(e){if(e instanceof w.ApiError){var t,n;return t=e.code,n=e.message,`${n} (${t})`}return e instanceof Error?e.message:"An unexpected error occurred."}function op(e){try{return new Date(e).toLocaleString(void 0,{dateStyle:"medium",timeStyle:"short"})}catch{return e}}let om={running:"Running",succeeded:"Succeeded",failed:"Failed",cancelled:"Cancelled"},oh={running:"qi-badge-running",succeeded:"qi-badge-succeeded",failed:"qi-badge-failed",cancelled:"qi-badge-cancelled"};function of(e){return"running"===e||"succeeded"===e||"failed"===e||"cancelled"===e}function og({status:e}){let t=of(e)?om[e]:e,a=of(e)?oh[e]:"qi-badge-default";return(0,n.jsx)("span",{className:`qi-badge ${a}`,children:t})}let ov={critical:"qi-sev-critical",high:"qi-sev-high",medium:"qi-sev-medium",low:"qi-sev-low"};function ob({severity:e}){let t="critical"===e||"high"===e||"medium"===e||"low"===e?ov[e]:"qi-sev-low";return(0,n.jsxs)("span",{className:`qi-sev ${t}`,children:[(0,n.jsx)("span",{className:"sr-only",children:"Severity: "}),e]})}function ox({score:e}){if(null===e)return(0,n.jsxs)("span",{className:"qi-badge qi-badge-default","data-testid":"qi-quality-badge",children:[(0,n.jsx)("span",{"aria-hidden":"true",children:"—"}),(0,n.jsx)("span",{className:"sr-only",children:"Quality score not available"})]});let t=Math.round(e);return(0,n.jsxs)("span",{className:`qi-badge ${t>=90?"qi-quality-high":t>=70?"qi-quality-mid":"qi-quality-low"}`,"data-testid":"qi-quality-badge",children:[t.toString(),(0,n.jsx)("span",{className:"sr-only",children:" out of 100"})]})}function oy({flag:e}){return(0,n.jsxs)("div",{role:"note","aria-label":`Weak test flagged by the quality judge: ${e.rationale}`,className:"qi-weak-flag","data-testid":"qi-weak-flag",children:[(0,n.jsxs)("span",{className:"qi-weak-flag-badge",children:[(0,n.jsx)("span",{"aria-hidden":"true",className:"qi-weak-flag-icon",children:"⚠"}),"Weak test"]}),(0,n.jsx)("p",{className:"qi-weak-flag-reason",children:e.rationale})]})}let ow={verifiability:"Verifiability",atomicity:"Atomicity",determinism:"Determinism","ac-fidelity":"AC fidelity"};function oj({verdict:e}){let t=Math.round(e.score),a="strong"===e.verdict?"Strong":"Weak";return(0,n.jsxs)("div",{role:"note","aria-label":`Quality judge verdict: ${a}, ${t.toString()} out of 100. ${e.overallRationale}`,className:"qi-cand-block","data-testid":"qi-quality-verdict",children:[(0,n.jsx)("p",{className:"qi-cand-block-label",children:"Quality verdict"}),(0,n.jsxs)("p",{children:[a," - ",t.toString(),"/100"]}),(0,n.jsx)("ul",{className:"qi-cand-list","aria-label":"Quality dimensions",children:e.dimensions.map(e=>(0,n.jsxs)("li",{children:[ow[e.name]??e.name," ",Math.round(e.score).toString(),": ",e.rationale]},e.name))})]})}function ok({height:e=20,width:t="100%"}){return(0,n.jsx)("div",{"aria-hidden":"true",className:"qi-skeleton",style:{height:e,width:t}})}function oN(){return(0,n.jsx)("div",{"data-testid":"qi-loading-state","aria-busy":"true",style:{display:"flex",flexDirection:"column",gap:8,padding:"12px 0"},children:[1,2,3].map(e=>(0,n.jsxs)("div",{className:"qi-skeleton-row",children:[(0,n.jsx)(ok,{height:14,width:"60%"}),(0,n.jsx)(ok,{height:12,width:"40%"})]},e))})}function oS({message:e,onRetry:t}){return(0,n.jsxs)("div",{role:"alert","aria-live":"assertive",className:"lk-alert","data-testid":"qi-error-state",children:[e,(0,n.jsx)("button",{type:"button",className:"lk-alert-retry",onClick:t,children:"Retry"})]})}let oC="connectedSourcesJson";function oI(e,t){let n=e[t];return"string"==typeof n?n:void 0}function oE(e,t){return"string"==typeof e[t]}function oR(e){if(!("object"==typeof e&&null!==e&&!Array.isArray(e))||!oE(e,"label"))return!1;switch(e.kind){case"file":case"workspace":return oE(e,"path");case"capsule":return oE(e,"capsuleId");case"capsule-set":return oE(e,"capsuleSetId");case"figma-snapshot":let t;return oE(e,"snapshotRunId")&&(void 0===(t=e.screenIds)||Array.isArray(t)&&t.length>0&&t.every(e=>"string"==typeof e&&e.trim().length>0));case"image":return"figma-snapshot-screen"===e.sourceKind&&oE(e,"snapshotRunId")&&oE(e,"screenId");default:return!1}}function o$(e){return e.length>0?{[oC]:JSON.stringify(e)}:{}}function oA(e){let t=e.split(/[\\/]/u).filter(e=>e.length>0);return t.length>0?t[t.length-1]??e:e}function oT(e){return e.replaceAll("\\","/")}function oL(e){if(/^[A-Za-z]:[/\\]?$/u.test(e))return e.replaceAll("\\","/");if(/^\/\/[^/]+\/[^/]+$/u.test(oT(e)))return oT(e);let t=oT(e).replace(/\/+$/u,"");return 0===t.length&&e.length>0?"/":t}function oP(e){let t=e.connectedRoot??null,n=function(e,t){let n=t?.trim()??"";if(0===n.length)return null;if(n.startsWith("/")||/^[A-Za-z]:[/\\]/u.test(n)||n.startsWith("\\\\")||n.startsWith("//"))return n;let a=e?.trim()??"";if(0===a.length)return null;let l=oL(a),i=oT(n).replace(/^\/+/u,""),r=l.endsWith("/")?"":"/";return`${l}${r}${i}`}(t,e.connectedFilePath??null),a=null!==t?oL(t):null,l=(void 0!==e.connectedRoots&&null!==e.connectedRoots&&e.connectedRoots.length>0?e.connectedRoots:null!==t?[t]:[]).map(oL),i=null!==n?l.filter(e=>e!==a):l,r=[];for(let e of(null!==n&&r.push({kind:"file",label:oA(n),path:n}),i))r.push({kind:"workspace",label:oA(e),path:e});for(let t of e.connectedCapsuleIds??[])r.push({kind:"capsule",label:t,capsuleId:t});for(let t of e.connectedCapsuleSetIds??[])r.push({kind:"capsule-set",label:t,capsuleSetId:t});for(let t of void 0!==e.connectedFigmaSnapshotSources?e.connectedFigmaSnapshotSources:(e.connectedFigmaSnapshotRunIds??[]).map(e=>({kind:"figma-snapshot",label:e,snapshotRunId:e})))r.push(t);for(let t of e.connectedImageSources??[])r.push(t);let s=new Set,o=[];for(let e of r){if(o.length>=16)break;let t=function(e){switch(e.kind){case"file":case"workspace":return`${e.kind}:${e.path}`;case"capsule":return`capsule:${e.capsuleId}`;case"capsule-set":return`capsule-set:${e.capsuleSetId}`;case"figma-snapshot":{let t=e.screenIds,n=void 0===t||0===t.length?"*":[...new Set(t.map(e=>e.trim()).filter(e=>e.length>0))].sort().join(",");return`figma-snapshot:${e.snapshotRunId}:${n}`}case"image":return`image:${e.sourceKind}:${e.snapshotRunId}:${e.screenId}`}}(e);s.has(t)||(s.add(t),o.push(e))}return o}let oM=[{id:"regression-default",label:"Regression (default)"},{id:"banking-default",label:"Banking"},{id:"insurance-default",label:"Insurance"}],oD=[{id:"requirements",label:"Requirements",hint:"Paste text"},{id:"workspace",label:"Folder",hint:"Browse local"},{id:"file",label:"File",hint:"Browse local"},{id:"capsule",label:"Capsule",hint:"Local Knowledge"},{id:"capsule-set",label:"Capsule set",hint:"Local Knowledge"}];function oq({kind:e}){return"requirements"===e?(0,n.jsx)(j.Icons.review,{size:15}):"workspace"===e?(0,n.jsx)(j.Icons.folder,{size:15}):"file"===e?(0,n.jsx)(j.Icons.file,{size:15}):"capsule-set"===e?(0,n.jsx)(j.Icons.layers,{size:15}):(0,n.jsx)("svg",{"aria-hidden":"true",className:"qi-source-kind-icon-svg",viewBox:"0 0 24 24",children:(0,n.jsx)("path",{d:"M12 3.8 19 7.7v8.6L12 20.2 5 16.3V7.7z"})})}let oF={phase:"Starting…",stageName:null,candidates:0,findings:0,atomCount:null,droppedSourceCount:0,skippedSources:[]},oO="Der Lauf wurde nicht erfolgreich abgeschlossen. Passe die Quelle an und versuche es erneut.";function oz(e){switch(e.code){case"QI_IMAGE_DESCRIPTION_UNAVAILABLE":return`${e.label} (image was readable, but the image model produced no usable description)`;case"QI_IMAGE_UNAVAILABLE":return`${e.label} (stored image could not be found or read)`;case"QI_FIGMA_SNAPSHOT_UNAVAILABLE":return`${e.label} (stored Figma snapshot could not be found or read)`;case"QI_SOURCE_EMPTY":return`${e.label} (source produced no usable evidence)`;case"QI_SOURCE_DENIED":return`${e.label} (source is in a protected location)`;case"QI_SOURCE_TOO_LARGE":return`${e.label} (source is too large for this run)`;case"QI_SOURCE_UNSUPPORTED":return`${e.label} (source format is not supported)`;case"QI_WORKSPACE_NOT_FOUND":return`${e.label} (workspace path could not be read)`;case"QI_CAPSULE_UNAVAILABLE":return`${e.label} (knowledge source is unavailable)`;default:return`${e.label} (could not be read)`}}function oK(e){switch(e.kind){case"file":return"File";case"workspace":return"Folder";case"capsule":return"Capsule";case"capsule-set":return"Capsule set";case"figma-snapshot":return e.label.startsWith("JSON ·")?"Figma JSON":"Figma snapshot";case"image":return"Image"}}function oB(e){switch(e.kind){case"file":case"workspace":return e.path;case"capsule":return e.capsuleId;case"capsule-set":return e.capsuleSetId;case"figma-snapshot":return void 0!==e.screenIds&&e.screenIds.length>0?`${e.snapshotRunId}#${e.screenIds.join(",")}`:e.snapshotRunId;case"image":return`${e.snapshotRunId}#${e.screenId}`}}function o_({onRunCompleted:e,startImpl:t=s9,fetchCapsulesImpl:l=lD.fetchCapsules,fetchCapsuleSetsImpl:i=lD.fetchCapsuleSets,fetchProjectsImpl:r=w.fetchProjects,fetchFilesTreeImpl:s=w.fetchFilesTree,connectedRoot:o=null,connectedFilePath:c=null,connectedRoots:d,connectedCapsuleIds:u,connectedCapsuleSetIds:p,connectedFigmaSnapshotRunIds:m,connectedFigmaSnapshotSources:h,connectedImageSources:f}){let[g,v]=(0,a.useState)(""),[b,x]=(0,a.useState)("requirements"),[y,j]=(0,a.useState)(""),[k,N]=(0,a.useState)(""),[S,C]=(0,a.useState)(""),[I,E]=(0,a.useState)(""),[R,$]=(0,a.useState)(!1),[A,T]=(0,a.useState)([]),[L,P]=(0,a.useState)([]),[M,D]=(0,a.useState)(!1),[q,F]=(0,a.useState)(null),[O,z]=(0,a.useState)("regression-default"),[K,B]=(0,a.useState)(""),[_,U]=(0,a.useState)(!1),[W,V]=(0,a.useState)(oF),[H,Y]=(0,a.useState)(null),[G,J]=(0,a.useState)(null),X=(0,a.useRef)(null),Q=(0,a.useRef)(null),Z=(0,a.useRef)(null),ee=(0,a.useRef)(!1),et=oP({connectedRoot:o,connectedFilePath:c,connectedRoots:d,connectedCapsuleIds:u,connectedCapsuleSetIds:p,connectedFigmaSnapshotRunIds:m,connectedFigmaSnapshotSources:h,connectedImageSources:f}),en=et.length>0,ea=A.find(e=>e.id===S),el=L.find(e=>e.id===I),ei=k.trim().length>0,er="requirements"===b?y.trim().length>0:"workspace"===b||"file"===b?ei:"capsule"===b?S.trim().length>0:I.trim().length>0,es="requirements"===b?0===y.trim().length:("workspace"===b||"file"===b)&&!ei,eo=er||es&&en,ec=K.trim(),ed=0===ec.length?void 0:/^\d+$/u.test(ec)?Number(ec):NaN,eu=void 0===ed||Number.isSafeInteger(ed)&&Number.isFinite(ed),ep=e=>{let t=Number.parseInt(K.trim(),10);B(String(Math.max(0,(Number.isFinite(t)?t:0)+e))),Y(null)},em=!eo||!eu,eh=(0,a.useId)(),ef=(0,a.useId)(),eg=(0,a.useId)(),ev=(0,a.useId)(),eb=(0,a.useId)(),ex=eo?eu?void 0:ef:eh,ey="workspace"===b||"file"===b?b:null,ew=(0,a.useCallback)(e=>{x(e),$(!1),Y(null),F(null)},[]),ej=(0,a.useCallback)((e,t)=>{_||0!==e.button||ew(t)},[ew,_]),ek=(0,a.useCallback)(e=>{if(_)return;let t="ArrowRight"===e.key||"ArrowDown"===e.key?1:"ArrowLeft"===e.key||"ArrowUp"===e.key?-1:0;if(0===t)return;e.preventDefault();let n=oD.length,a=(Math.max(0,oD.findIndex(e=>e.id===b))+t+n)%n,l=oD[a];void 0!==l&&(ew(l.id),e.currentTarget.parentElement?.querySelectorAll('[role="radio"]')[a]?.focus())},[ew,_,b]),eN=(0,a.useCallback)(e=>{var t,n,a;"event"===e.type&&("stage:failed"===e.kind||"run:failed"===e.kind)&&"string"==typeof e.reasonSummary&&(Z.current=e.reasonSummary),"done"===e.type&&("succeeded"===e.status?(Q.current=e.runId,!0===e.degraded&&J(function(e){let t="Die Modellgenerierung ist fehlgeschlagen — Keiko hat deterministische Baseline-Testfälle aus der Evidenz erstellt. Diese sind nicht modellgestützt; prüfe das Modell-Gateway und starte den Lauf für modellgestützte Testfälle erneut.";if(null==e||0===e.trim().length)return t;if("qi-error: UnparseableModelOutputError"===e)return`${t} (Modellausgabe nicht als JSON parsebar)`;if("qi-error: QI_PROMPT_TOO_LARGE"===e)return`${t} (Quellkontext f\xfcr das Modell zu gro\xdf)`;let n=e.startsWith("qi-error: ")?e.slice(10):e.startsWith("qi-safe-error: ")?e.slice(15):e;return`${t} (${n})`}(e.reasonSummary??null))):"failed"===e.status&&Y(null==(t=e.reasonSummary??Z.current)||0===t.trim().length?oO:"qi-run-error"===t?"Die Modellgenerierung ist fehlgeschlagen, bevor nutzbare Testfälle zurückgegeben wurden. Versuche es mit einer kleineren Quelle oder prüfe das ausgewählte Modell-Gateway.":"qi-error: UnparseableModelOutputError"===t?"Das Modell hat eine Ausgabe geliefert, die nicht zu Testfällen geparst werden konnte. Versuche es erneut oder nutze ein Modell mit strukturierter JSON-Ausgabe.":"qi-error: QI_PROMPT_TOO_LARGE"===t?"Der zusammengestellte Quellkontext ist für das Modell zu groß. Reduziere die Quelle und versuche es erneut.":t.startsWith("qi-error: ")?`${oO} (${t.slice(10)})`:t.startsWith("qi-safe-error: ")?`${oO} (${t.slice(15)})`:`${oO} (${t})`)),"error"===e.type&&Y((n=e.code,a=e.message,`${a} (${n})`)),V(t=>(function(e,t){if("accepted"===t.type)return{...e,phase:"Ingested sources",atomCount:t.atomCount,droppedSourceCount:t.droppedSourceCount??0,skippedSources:t.skippedSources??[]};if("event"===t.type){let n="candidate:proposed"===t.kind?e.candidates+1:e.candidates,a="finding:recorded"===t.kind?e.findings+1:e.findings,l=t.stageName??e.stageName;return{...e,phase:t.kind,stageName:l,candidates:n,findings:a}}return e})(t,e))},[]),eS="capsule"===b||"capsule-set"===b;(0,a.useEffect)(()=>{if(!eS)return;let e=!1;return async function(){D(!0),F(null);try{let[t,n]=await Promise.allSettled([l(),i()]);if(e)return;"fulfilled"===t.status?T(t.value.capsules.filter(e=>"ready"===e.lifecycleState)):(T([]),"capsule"===b&&F(ou(t.reason))),"fulfilled"===n.status?P(n.value.capsuleSets):(P([]),"capsule-set"===b&&F(ou(n.reason)))}finally{e||D(!1)}}(),()=>{e=!0}},[l,i,eS,b]),(0,a.useEffect)(()=>{if("capsule"===b){let e=A.some(e=>e.id===S)?S:A[0]?.id??"";e!==S&&C(e)}if("capsule-set"===b){let e=L.some(e=>e.id===I)?I:L[0]?.id??"";e!==I&&E(e)}},[S,I,L,A,b]);let eC=(0,a.useCallback)(()=>{let e=g.trim();return"requirements"===b&&y.trim().length>0?[{kind:"requirements",label:e||"Requirements",text:y}]:"workspace"===b&&k.trim().length>0?[{kind:"workspace",label:e||"Folder",path:k.trim()}]:"file"===b&&k.trim().length>0?[{kind:"file",label:e||"File",path:k.trim()}]:"capsule"===b&&S.trim().length>0?[{kind:"capsule",label:e||ea?.displayName||"Knowledge capsule",capsuleId:S.trim()}]:"capsule-set"===b&&I.trim().length>0?[{kind:"capsule-set",label:e||el?.displayName||"Capsule set",capsuleSetId:I.trim()}]:null},[S,I,g,k,ea,el,b,y]),eI=(0,a.useCallback)(async()=>{if(!eo||_||!eu||ee.current)return;ee.current=!0,U(!0),Y(null),J(null),V(oF),Q.current=null,Z.current=null;let n=new AbortController;X.current=n;let a=eC()??et,l={sources:a,profileId:O,...void 0!==ed?{seed:ed}:{}};try{await t(l,n.signal,eN);let i=Q.current;null!==i&&e?.(i,a.filter(e=>"requirements"!==e.kind))}catch(e){n.signal.aborted||Y(ou(e))}finally{U(!1),X.current=null,ee.current=!1}},[eo,O,_,et,eC,eN,e,ed,eu,t]),eE=(0,a.useCallback)(()=>{X.current?.abort()},[]),eR=W.droppedSourceCount>0?`${W.droppedSourceCount.toString()} source${1!==W.droppedSourceCount?"s":""} over the 16-source limit ${1!==W.droppedSourceCount?"were":"was"} not included.`:null,e$=function(e){if(0===e.length)return null;let t=e.length.toString(),n=1!==e.length?"sources were":"source was";return`${t} connected ${n} skipped: ${e.map(oz).join(", ")}.`}(W.skippedSources),eA=[eR,e$].filter(e=>null!==e).join(" ");return(0,n.jsxs)("section",{className:"qi-launcher","aria-label":"Start a Quality Intelligence run",children:[(0,n.jsx)("header",{className:"qi-col-header",children:(0,n.jsx)("h2",{className:"qi-col-title",children:"New run"})}),(0,n.jsxs)("div",{className:"qi-launcher-body",children:[1===et.length&&void 0!==et[0]?(0,n.jsxs)("div",{className:"qi-connected-source","data-testid":"qi-connected-source",children:[(0,n.jsxs)("span",{className:"qi-connected-kind",children:["Connected ",oK(et[0]).toLowerCase()]}),(0,n.jsx)("span",{className:"qi-connected-path qi-monospace",title:oB(et[0]),children:oB(et[0])}),(0,n.jsx)("span",{className:"qi-connected-hint",children:er?"Manual input below overrides the connected source for this run.":`Generate uses the connected ${oK(et[0]).toLowerCase()}.`})]}):et.length>1?(0,n.jsxs)("div",{className:"qi-connected-source","data-testid":"qi-connected-source",children:[(0,n.jsxs)("span",{className:"qi-connected-kind",children:["Connected sources (",et.length.toString(),")"]}),(0,n.jsx)("ul",{className:"qi-connected-roots","aria-label":"Connected sources",children:et.map(e=>(0,n.jsxs)("li",{className:"qi-connected-root-item",children:[(0,n.jsx)("span",{className:"qi-connected-root-name",children:oK(e)}),(0,n.jsx)("span",{className:"qi-connected-path qi-monospace",title:oB(e),children:oB(e)})]},`${e.kind}:${oB(e)}`))}),(0,n.jsx)("span",{className:"qi-connected-hint",children:er?"Manual input below overrides the connected sources for this run.":"Generate uses all connected sources."})]}):null,(0,n.jsxs)("div",{className:"qi-launcher-row",children:[(0,n.jsxs)("label",{className:"qi-field",children:[(0,n.jsx)("span",{className:"qi-field-label",children:"Source label"}),(0,n.jsx)("input",{type:"text",className:"qi-input",value:g,placeholder:"e.g. Funds Transfer — acceptance criteria",disabled:_,"aria-describedby":en&&!er?eg:void 0,onChange:e=>{v(e.target.value)}}),en&&!er?(0,n.jsx)("span",{className:"qi-field-hint",id:eg,children:"Applies to manual input only — connected sources use their own labels."}):null]}),(0,n.jsxs)("div",{className:"qi-field qi-field-kind",children:[(0,n.jsx)("span",{className:"qi-field-label",id:ev,children:"Source type"}),(0,n.jsx)("div",{className:"qi-source-kind-grid",role:"radiogroup","aria-labelledby":ev,"aria-disabled":_||void 0,children:oD.map(e=>(0,n.jsxs)("button",{type:"button",className:"qi-source-kind-option",role:"radio","aria-label":e.label,"data-tip":e.label,"aria-checked":b===e.id,tabIndex:b===e.id?0:-1,disabled:_,onPointerDown:t=>{ej(t,e.id)},onClick:()=>ew(e.id),onKeyDown:ek,children:[(0,n.jsx)("span",{className:"qi-source-kind-label",children:e.label}),(0,n.jsx)("span",{className:"qi-source-kind-icon","aria-hidden":"true",children:(0,n.jsx)(oq,{kind:e.id})})]},e.id))})]})]}),function(){if("requirements"===b)return(0,n.jsxs)("label",{className:"qi-field",children:[(0,n.jsx)("span",{className:"qi-field-label",children:"Requirements"}),(0,n.jsx)("textarea",{className:"qi-textarea",value:y,rows:6,placeholder:"Paste requirements or acceptance criteria, one statement per line.",disabled:_,onChange:e=>{j(e.target.value)}})]});if("workspace"===b||"file"===b){let e="file"===b;return(0,n.jsxs)("div",{className:"qi-field",children:[(0,n.jsx)("span",{className:"qi-field-label",id:eb,children:e?"File path":"Folder path"}),(0,n.jsxs)("div",{className:"qi-path-picker",children:[(0,n.jsx)("div",{className:"qi-path-value qi-monospace",role:"textbox","aria-readonly":"true","aria-labelledby":eb,title:k,"data-empty":0===k.trim().length?"true":void 0,children:k.trim().length>0?k:e?"Choose a local file…":"Choose a local folder…"}),(0,n.jsx)("button",{type:"button",className:"qi-btn qi-btn-secondary qi-browse-btn",disabled:_,onClick:()=>$(!0),children:"Browse"})]})]})}let e="capsule"===b,t=e?A:L;return(0,n.jsxs)("label",{className:"qi-field",children:[(0,n.jsx)("span",{className:"qi-field-label",children:e?"Knowledge capsule":"Capsule set"}),(0,n.jsxs)("select",{className:"qi-select",value:e?S:I,disabled:_||M||null!==q||0===t.length,onChange:t=>{e?C(t.target.value):E(t.target.value)},children:[M?(0,n.jsx)("option",{value:"",children:"Loading connectors..."}):null,M||0!==t.length?null:(0,n.jsx)("option",{value:"",children:e?"No ready capsules":"No capsule sets"}),e?A.map(e=>(0,n.jsx)("option",{value:e.id,children:e.displayName},e.id)):L.map(e=>(0,n.jsx)("option",{value:e.id,children:`${e.displayName} (${String(e.capsuleCount)} capsules)`},e.id))]})]})}(),null!==q?(0,n.jsx)("p",{className:"lk-alert",role:"alert","data-testid":"qi-connector-error",children:q}):null,(0,n.jsxs)("div",{className:"qi-launcher-controls",children:[(0,n.jsxs)("div",{className:"qi-field qi-field-inline qi-policy-profile-field",children:[(0,n.jsx)("span",{className:"qi-field-label",children:"Policy profile"}),(0,n.jsx)(tz,{triggerClassName:"qi-select",value:O,ariaLabel:"Policy profile",disabled:_,menuTitle:"Policy",menuClassName:"qi-policy-profile-menu",sections:[{options:oM.map(e=>({value:e.id,label:e.label}))}],onValueChange:z})]}),(0,n.jsxs)("label",{className:"qi-field qi-field-inline",children:[(0,n.jsx)("span",{className:"qi-field-label",children:"Seed (optional)"}),(0,n.jsxs)("span",{className:"number-control qi-number-control",children:[(0,n.jsx)("input",{type:"number",min:0,step:1,className:"qi-input number-control-input",value:K,placeholder:"e.g. 42",disabled:_,"aria-invalid":!eu||void 0,"aria-describedby":eu?void 0:ef,onChange:e=>{B(e.target.value),Y(null)},onWheel:e=>{_||0===e.deltaY||(e.preventDefault(),ep(e.deltaY<0?1:-1))}}),(0,n.jsx)(a3,{label:"seed",disabled:_,onStepUp:()=>ep(1),onStepDown:()=>ep(-1)})]}),eu?null:(0,n.jsx)("span",{className:"qi-field-error",id:ef,children:"Seed must be a non-negative integer."})]}),(0,n.jsx)("button",{type:"button",className:_?"qi-btn qi-btn-secondary":"qi-btn qi-btn-primary","aria-disabled":!_&&em||void 0,"aria-describedby":_?void 0:ex,onClick:()=>{_?eE():em||eI()},children:_?"Cancel":"Generate test cases"}),_||eo?null:(0,n.jsx)("span",{className:"qi-generate-hint",id:eh,children:"Add requirements text, a folder path, a file path, select a capsule, select a capsule set, or connect a source to generate."})]}),_?(0,n.jsxs)("div",{className:"qi-progress","data-testid":"qi-launch-progress","aria-hidden":"true",children:[(0,n.jsx)("span",{className:"qi-progress-spinner","aria-hidden":"true"}),(0,n.jsxs)("span",{className:"qi-progress-text",children:[null!==W.stageName?`Stage: ${W.stageName} \xb7 `:"",W.candidates.toString()," test case",1!==W.candidates?"s":"",W.findings>0?` \xb7 ${W.findings.toString()} finding${1!==W.findings?"s":""}`:""]})]}):null,(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite","data-testid":"qi-launch-progress-sr",children:function(e,t){if(!e)return"";if(null===t.stageName&&0===t.candidates&&0===t.findings)return"Generating test cases…";let n=null!==t.stageName?`Stage: ${t.stageName}. `:"",a=`${t.candidates.toString()} test case${1!==t.candidates?"s":""}`,l=t.findings>0?`, ${t.findings.toString()} finding${1!==t.findings?"s":""}`:"";return`${n}${a}${l}`}(_,W)}),(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite",children:eA}),null!==eR||null!==e$?(0,n.jsxs)("div",{className:"qi-coverage-notice","data-testid":"qi-coverage-notice",children:[null!==eR?(0,n.jsx)("p",{className:"qi-coverage-line",children:eR}):null,null!==e$?(0,n.jsx)("p",{className:"qi-coverage-line",children:e$}):null]}):null,null!==G?(0,n.jsx)("p",{className:"qi-degraded-notice",role:"status","data-testid":"qi-launch-degraded",children:G}):null,null!==H?(0,n.jsx)("p",{className:"lk-alert",role:"alert","data-testid":"qi-launch-error",children:H}):null]}),R&&null!==ey?(0,n.jsx)(os.LocalFileBrowserDialog,{mode:"file"===ey?"file":"folder",title:`Choose ${"file"===ey?"file":"folder"} source`,description:"Browse a registered local project or enter an absolute folder root.",initialRootPath:"file"===ey?(0,os.dirname)(k):k,fetchProjectsImpl:r,fetchFilesTreeImpl:s,onCancel:()=>$(!1),onApply:e=>{N("file"===ey?(0,os.displayLocalPath)(e.rootPath,e.files[0]??null):e.folderPath),$(!1),Y(null)}}):null]})}function oU({run:e,onOpen:t,onDelete:l,deleting:i}){var r;let s=e.totals.candidates,[o,c]=(0,a.useState)(!1),d=(0,a.useRef)(null),u=(0,a.useRef)(null),p=(0,a.useRef)(null);(0,a.useEffect)(()=>{o&&u.current?.focus()},[o]);let m=(0,a.useCallback)(()=>{c(!1),requestAnimationFrame(()=>{d.current?.focus()})},[]),h=(0,a.useCallback)(e=>{"Escape"===e.key&&(e.preventDefault(),m())},[m]),f=(0,a.useCallback)(()=>{i||l(e.id)},[i,l,e.id]);return(0,n.jsxs)("li",{style:{display:"flex",alignItems:"stretch"},children:[(0,n.jsxs)("button",{type:"button",className:"qi-run-item",style:{flex:1},onClick:()=>{t(e.id,[])},"aria-label":`Open run ${e.id} — ${of(r=e.status)?om[r]:r}, ${op(e.requestedAt)}, ${s.toString()} test case${1!==s?"s":""}, review ${oo[e.reviewState]}`,title:`Open run ${e.id}`,children:[(0,n.jsx)("span",{className:"qi-run-title",children:op(e.requestedAt)}),(0,n.jsx)(og,{status:e.status}),(0,n.jsx)(od,{state:e.reviewState}),(0,n.jsxs)("span",{className:"qi-run-id",children:[e.id.slice(0,16),"…"]}),(0,n.jsxs)("span",{className:"qi-run-totals",children:[e.totals.candidates.toString()," test case",1!==e.totals.candidates?"s":""]})]}),o?(0,n.jsxs)("div",{className:"qi-cand-actions",role:"group","aria-label":`Confirm deleting run ${op(e.requestedAt)}`,style:{display:"flex",alignItems:"center",gap:4,padding:"0 6px",flexShrink:0},children:[(0,n.jsx)("button",{ref:p,type:"button",className:"qi-btn qi-btn-reject",style:{minWidth:0,padding:"4px 10px",fontSize:12,flexShrink:0},"aria-label":`Confirm delete of run ${op(e.requestedAt)}`,"aria-busy":i||void 0,"aria-disabled":i||void 0,onClick:f,onKeyDown:h,children:i?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{"aria-hidden":"true",children:"Deleting…"}),(0,n.jsx)("span",{className:"sr-only",children:"Deleting run, please wait"})]}):"Confirm delete"}),(0,n.jsx)("button",{ref:u,type:"button",className:"qi-btn qi-btn-secondary",style:{minWidth:0,padding:"4px 10px",fontSize:12,flexShrink:0},"aria-disabled":i||void 0,onClick:()=>{i||m()},onKeyDown:h,children:"Cancel"})]}):(0,n.jsx)("button",{ref:d,type:"button",className:"qi-btn qi-btn-reject",style:{alignSelf:"center",minWidth:0,padding:"4px 10px",fontSize:12,margin:"0 6px 0 0",flexShrink:0},"aria-label":`Delete run ${op(e.requestedAt)}`,onClick:()=>{c(!0)},children:"Delete"})]})}function oW({openRun:e,connectedRoot:t=null,connectedFilePath:l=null,connectedRoots:i,connectedCapsuleIds:r,connectedCapsuleSetIds:s,connectedFigmaSnapshotRunIds:o,connectedFigmaSnapshotSources:c,connectedImageSources:d,fetchRunsImpl:u=s5,deleteImpl:p=oe}){let[m,h]=(0,a.useState)([]),[f,g]=(0,a.useState)(0),[v,b]=(0,a.useState)(!1),[x,y]=(0,a.useState)(!0),[w,j]=(0,a.useState)(null),[k,N]=(0,a.useState)(25),[S,C]=(0,a.useState)(null),[I,E]=(0,a.useState)(""),R=(0,a.useCallback)(async()=>{y(!0),j(null);try{let e=await u();h(e.runs),g(e.totalRunIds),b(e.truncated)}catch(e){j(ou(e))}finally{y(!1)}},[u]);(0,a.useEffect)(()=>{R()},[R]);let $=(0,a.useCallback)((t,n)=>{R(),e(t,n)},[R,e]),A=(0,a.useCallback)(async e=>{if(null===S){C(e),j(null);try{await p(e),E("Run deleted."),await R()}catch(e){j(ou(e))}finally{C(null)}}},[S,p,R]);return(0,n.jsxs)("div",{className:"qi-hub",children:[(0,n.jsx)(o_,{onRunCompleted:$,connectedRoot:t,connectedFilePath:l,connectedRoots:i,connectedCapsuleIds:r,connectedCapsuleSetIds:s,connectedFigmaSnapshotRunIds:o,connectedFigmaSnapshotSources:c,connectedImageSources:d}),(0,n.jsxs)("section",{className:"qi-hub-runs","aria-label":"Quality Intelligence runs",children:[(0,n.jsxs)("header",{className:"qi-col-header",children:[(0,n.jsx)("h2",{className:"qi-col-title",children:"Runs"}),x||null!==w?null:(0,n.jsx)("span",{className:"qi-col-count",children:f.toString()})]}),(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite",children:x?"Loading runs…":null===w?`Run list loaded: ${m.length.toString()} run${1===m.length?"":"s"}${v?` of ${f.toString()}`:""}.`:""}),(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite","aria-atomic":"true",children:I}),(0,n.jsx)("div",{className:"qi-col-body","aria-busy":x,children:x?(0,n.jsx)(oN,{}):null!==w?(0,n.jsx)(oS,{message:w,onRetry:()=>{R()}}):0===m.length?(0,n.jsxs)("div",{className:"lk-empty",children:[(0,n.jsx)("p",{className:"lk-empty-title",children:"No runs yet"}),(0,n.jsx)("p",{className:"lk-empty-body",children:"Start a run above — generated test cases open as cards on your workspace."})]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("ul",{className:"qi-run-list","aria-label":"Run list",children:m.slice(0,k).map(t=>(0,n.jsx)(oU,{run:t,onOpen:e,onDelete:e=>{A(e)},deleting:S===t.id},t.id))}),k<m.length?(0,n.jsxs)("button",{type:"button",className:"qi-btn qi-btn-secondary qi-show-more",onClick:()=>{N(e=>e+25)},children:["Show more runs (",(m.length-k).toString()," remaining)"]}):null,v?(0,n.jsx)("p",{className:"qi-runs-truncated","data-testid":"qi-runs-truncated",children:`Showing ${m.length.toString()} of ${f.toString()} runs.`}):null]})})]})]})}e.s(["QUALITY_INTELLIGENCE_SCHEMA_VERSION",0,"1"],73859),e.i(73859);let oV=["..","/","\\"],oH=(e,t)=>"string"!=typeof e?{ok:!1,reason:`${t} must be a string`}:0===e.length?{ok:!1,reason:`${t} must not be empty`}:0===e.trim().length?{ok:!1,reason:`${t} must not be whitespace-only`}:e!==e.trim()?{ok:!1,reason:`${t} must not have leading or trailing whitespace`}:e.length>256?{ok:!1,reason:`${t} exceeds max length ${String(256)}`}:e.normalize("NFKC")!==e?{ok:!1,reason:`${t} must be NFKC-normalised`}:(e=>{for(let t=0;t<e.length;t+=1){let n=e.charCodeAt(t);if(n<=31||127===n||n>=128&&n<=159)return!0}return!1})(e)?{ok:!1,reason:`${t} contains control characters`}:oV.some(t=>e.includes(t))?{ok:!1,reason:`${t} contains forbidden path fragment`}:{ok:!0},oY=(e,t)=>{let n=oH(e,t);if(!n.ok)throw TypeError(`Invalid ${t}: ${n.reason}`);return e},oG=e=>1564===e||e>=8203&&e<=8207||e>=8234&&e<=8238||e>=8294&&e<=8297||65279===e,oJ=e=>!!(/[a-z][a-z0-9+.-]*:\/\//iu.test(e)||/AKIA[0-9A-Z]{12,}/u.test(e)||/(?:ghp_|gho_|github_pat_)[A-Za-z0-9_]{20,}/u.test(e)||/xox[baprs]-[A-Za-z0-9-]{10,}/u.test(e)||/sk-[A-Za-z0-9]{16,}/u.test(e)||/\bBearer\s+\S/u.test(e)||/-----BEGIN [A-Z ]*PRIVATE KEY-----/u.test(e)||/^(?:\/|[A-Za-z]:[\\/]|\\\\)/u.test(e)||(e=>{for(let t of e)if(oG(t.codePointAt(0)??0))return!0;return!1})(e)),oX=e=>Number.isFinite(e)&&e>=0&&e<=1,oQ=Object.freeze({critical:0,high:1,medium:2,low:3}),oZ=new Set(["jira-issues","qtest","xray","polarion","alm","quality-center"]),o0=["verifiability","atomicity","determinism","ac-fidelity"],o1=Object.freeze({type:"object",additionalProperties:!1,required:["dimensions","overallRationale"],properties:{dimensions:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","score","rationale"],properties:{name:{type:"string",enum:[...o0]},score:{type:"integer",minimum:0,maximum:100},rationale:{type:"string"}}}},overallRationale:{type:"string"}}});e.s(["QUALITY_INTELLIGENCE_AUDIT_MANIFEST_SCHEMA_VERSION",0,1,"QUALITY_INTELLIGENCE_COVERAGE_KINDS",0,["derived","asserted","manual"],"QUALITY_INTELLIGENCE_EVENT_SCHEMA_VERSION",0,1,"QUALITY_INTELLIGENCE_EVIDENCE_ATOM_KINDS",0,["requirement","design-fragment","code-fragment","document-excerpt","human-statement"],"QUALITY_INTELLIGENCE_EXPORT_ADAPTERS",0,["jira-issues","qtest","xray","polarion","alm","csv","json","spreadsheet-safe-csv","markdown","plain-text","quality-center"],"QUALITY_INTELLIGENCE_HANDOFF_PROMPTED_ACTIONS",0,["design-tests","validate-tests","review-coverage","request-export"],"QUALITY_INTELLIGENCE_LIFECYCLE_STATUSES",0,["draft","finalised","archived"],"QUALITY_INTELLIGENCE_PLANNER_KINDS",0,["scripted","model-routed"],"QUALITY_INTELLIGENCE_PRIORITIES",0,["P0","P1","P2","P3"],"QUALITY_INTELLIGENCE_REDACTION_STATUSES",0,["redacted","not-required"],"QUALITY_INTELLIGENCE_REVIEWER_KINDS",0,["human-author","human-reviewer","judge"],"QUALITY_INTELLIGENCE_REVIEW_STATES",0,["open","approved","changes-requested","rejected","withdrawn"],"QUALITY_INTELLIGENCE_RISK_CLASSES",0,["safety","compliance","regression","functional","visual"],"QUALITY_INTELLIGENCE_RUN_EVENT_KINDS",0,["run:queued","run:started","stage:started","stage:completed","stage:failed","candidate:proposed","finding:recorded","review:requested","review:completed","run:succeeded","run:failed","run:cancelled"],"QUALITY_INTELLIGENCE_SCHEMA_VERSION",0,"1","QUALITY_INTELLIGENCE_SEVERITIES",0,["critical","high","medium","low"],"QUALITY_INTELLIGENCE_SEVERITY_RANK",0,oQ,"QUALITY_INTELLIGENCE_SOURCE_KINDS",0,["repository-context","local-knowledge-capsule","figma-evidence","human-context","connector-document"],"QUALITY_INTELLIGENCE_TEST_CASE_STATUSES",0,["proposed","accepted","rejected","needs-review"],"QUALITY_INTELLIGENCE_TMS_ADAPTERS",0,oZ,"QUALITY_INTELLIGENCE_VALIDATION_FINDING_KINDS",0,["logic-defect","faithfulness-defect","semantic-defect","mutation-defect","policy-violation","manual-rejection","coverage-gap","test-quality"],"TEST_QUALITY_JUDGE_RESPONSE_SCHEMA",0,o1,"TEST_QUALITY_RUBRIC_DIMENSIONS",0,o0,"asQualityIntelligenceAuditSummaryId",0,e=>oY(e,"QualityIntelligenceAuditSummaryId"),"asQualityIntelligenceCoverageMapId",0,e=>oY(e,"QualityIntelligenceCoverageMapId"),"asQualityIntelligenceEvidenceAtomId",0,e=>oY(e,"QualityIntelligenceEvidenceAtomId"),"asQualityIntelligenceExportBundleId",0,e=>oY(e,"QualityIntelligenceExportBundleId"),"asQualityIntelligenceReviewRecordId",0,e=>oY(e,"QualityIntelligenceReviewRecordId"),"asQualityIntelligenceRunId",0,e=>oY(e,"QualityIntelligenceRunId"),"asQualityIntelligenceSourceEnvelopeId",0,e=>oY(e,"QualityIntelligenceSourceEnvelopeId"),"asQualityIntelligenceTestCaseId",0,e=>oY(e,"QualityIntelligenceTestCaseId"),"asQualityIntelligenceValidationFindingId",0,e=>oY(e,"QualityIntelligenceValidationFindingId"),"assertCoverageMapInvariant",0,e=>{for(let t=0;t<e.mappings.length;t+=1){let n=e.mappings[t];if(void 0===n)throw RangeError(`Coverage map mapping[${String(t)}] is missing`);if(!oX(n.confidence))throw RangeError(`Coverage map mapping[${String(t)}] has out-of-range confidence ${String(n.confidence)}`);if(0===n.candidateIds.length)throw RangeError(`Coverage map mapping[${String(t)}] must reference at least one candidate`)}},"assertExportBundleInvariant",0,e=>{if(!/^[0-9a-f]{64}$/u.test(e.integrityHashSha256Hex))throw Error(`Export bundle integrity hash must be a lowercase sha256 hex string (id=${e.id})`);if(oZ.has(e.targetAdapter)&&!e.redactionAttested)throw Error(`Export bundle targeting TMS adapter "${e.targetAdapter}" requires redactionAttested === true (id=${e.id})`)},"assertQualityIntelligenceNever",0,e=>{throw TypeError(`Unexpected Quality Intelligence discriminant: ${JSON.stringify(e)}`)},"assertRunEventSequenceMonotonic",0,e=>{let t=-1;for(let n=0;n<e.length;n+=1){let a=e[n];if(void 0===a)throw RangeError(`Run event[${String(n)}] is missing`);if(!Number.isInteger(a.sequence)||a.sequence<0)throw RangeError(`Run event[${String(n)}] has invalid sequence ${String(a.sequence)}`);if(a.sequence<=t)throw RangeError(`Run event[${String(n)}] sequence ${String(a.sequence)} is not strictly greater than previous ${String(t)}`);t=a.sequence}},"hasCanonicalSha256Hash",0,e=>/^[0-9a-f]{64}$/u.test(e.canonicalHashSha256Hex),"looksLikeBrowserSafeSourceEnvelope",0,e=>{let{displayLabel:t,provenance:n,localRef:a}=e;return!(0===t.length||t.length>256||/^[A-Za-z0-9+/]{40,}={0,2}$/u.test(t)||!/^[0-9a-f]{64}$/u.test(n.integrityHashSha256Hex)||oJ(t)||oJ(a)||oJ(n.origin)||"connector-document"===e.kind&&oJ(e.adapterId))},"validateQualityIntelligenceIdString",0,oH],47425);var o2=e.i(47425),o2=o2;let o4=o2.QUALITY_INTELLIGENCE_PRIORITIES,o3=o2.QUALITY_INTELLIGENCE_RISK_CLASSES,o6=e=>e.split("\n").map(e=>e.trim()).filter(e=>e.length>0),o5=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]);function o8(e,t){let n=o6(t.preconditions),a=o6(t.steps),l=o6(t.expectedResults),i=t.tags.split(",").map(e=>e.trim()).filter(e=>e.length>0);return{...t.title!==e.title?{title:t.title}:{},...!o5(n,e.preconditions)?{preconditions:n}:{},...!o5(a,e.steps)?{steps:a}:{},...!o5(l,e.expectedResults)?{expectedResults:l}:{},...t.priority!==e.priority?{priority:t.priority}:{},...t.riskClass!==e.riskClass?{riskClass:t.riskClass}:{},...!o5(i,e.tags)?{tags:i}:{}}}function o7({id:e,label:t,value:a,disabled:l=!1,onChange:i}){return(0,n.jsxs)("label",{className:"qi-edit-field",htmlFor:e,children:[(0,n.jsx)("span",{className:"qi-edit-label",children:t}),(0,n.jsx)("textarea",{id:e,className:"qi-edit-textarea",value:a,rows:3,disabled:l,onChange:e=>{i(e.target.value)}})]})}function o9({id:e,label:t,value:a,disabled:l=!1,required:i=!1,onChange:r}){return(0,n.jsxs)("label",{className:"qi-edit-field",htmlFor:e,children:[(0,n.jsx)("span",{className:"qi-edit-label","data-required":i?"true":void 0,children:t}),(0,n.jsx)("input",{id:e,className:"qi-edit-input",value:a,disabled:l,required:i,"aria-required":i?"true":void 0,onChange:e=>{r(e.target.value)}})]})}function ce({id:e,label:t,value:a,options:l,disabled:i=!1,onChange:r}){return(0,n.jsxs)("label",{className:"qi-edit-field",htmlFor:e,children:[(0,n.jsx)("span",{className:"qi-edit-label",children:t}),(0,n.jsx)("select",{id:e,className:"qi-edit-select",value:a,disabled:i,onChange:e=>{r(e.target.value)},children:l.map(e=>(0,n.jsx)("option",{value:e,children:e},e))})]})}function ct({onCancel:e,saving:t}){return(0,n.jsxs)("div",{className:"qi-edit-actions",children:[(0,n.jsx)("button",{type:"submit",className:"qi-btn qi-btn-approve qi-edit-save","aria-disabled":t||void 0,children:"Save"}),(0,n.jsx)("button",{type:"button",className:"qi-btn qi-btn-secondary qi-edit-cancel","aria-disabled":t||void 0,onClick:()=>{t||e()},children:"Cancel"})]})}function cn({candidate:e,onSave:t,onCancel:l}){let[i,r]=(0,a.useState)(()=>({title:e.title,preconditions:e.preconditions.join("\n"),steps:e.steps.join("\n"),expectedResults:e.expectedResults.join("\n"),priority:e.priority,riskClass:e.riskClass,tags:e.tags.join(", ")})),[s,o]=(0,a.useState)(null),[c,d]=(0,a.useState)(!1),[u,p]=(0,a.useState)(!1),m=(0,a.useRef)(null),h=(e,t)=>{o(null),p(!1),r(n=>({...n,[e]:t}))},f=(0,a.useCallback)(()=>{c||(!(Object.keys(o8(e,i)).length>0)||u?l():p(!0))},[e,u,l,c,i]);(0,a.useEffect)(()=>{let e=e=>{if("Escape"!==e.key||c)return;let t=m.current;null!==t&&t.contains(document.activeElement)&&f()};return document.addEventListener("keydown",e),()=>{document.removeEventListener("keydown",e)}},[f,c]),(0,a.useEffect)(()=>{m.current?.querySelector("input.qi-edit-input")?.focus()},[]);let g=`qi-edit-${e.id}`,v=async()=>{if(!c){d(!0),o(null);try{await t(o8(e,i))}catch(e){o(ou(e))}finally{d(!1)}}};return(0,n.jsxs)("form",{ref:m,className:"qi-edit-form","aria-label":`Edit ${e.title}`,"aria-busy":c,onSubmit:e=>{e.preventDefault(),v()},children:[(0,n.jsxs)("div",{className:"qi-edit-head",children:[(0,n.jsxs)("div",{className:"qi-edit-head-copy",children:[(0,n.jsx)("p",{className:"qi-edit-eyebrow",children:"Edit test case"}),(0,n.jsx)("h3",{className:"qi-edit-heading",children:e.title})]}),(0,n.jsx)(ct,{onCancel:f,saving:c})]}),null!==s?(0,n.jsx)("p",{className:"qi-edit-error",role:"alert","aria-live":"assertive",children:s}):null,(0,n.jsx)("p",{className:"qi-edit-discard-note",role:"status","aria-live":"polite",children:u?"Unsaved changes — press Escape or activate Cancel again to discard them.":""}),(0,n.jsxs)("div",{className:"qi-edit-layout",children:[(0,n.jsxs)("div",{className:"qi-edit-main",children:[(0,n.jsx)(o9,{id:`${g}-title`,label:"Title",value:i.title,disabled:c,required:!0,onChange:e=>{h("title",e)}}),(0,n.jsx)(o7,{id:`${g}-preconditions`,label:"Preconditions (one per line)",value:i.preconditions,disabled:c,onChange:e=>{h("preconditions",e)}}),(0,n.jsx)(o7,{id:`${g}-steps`,label:"Steps (one per line)",value:i.steps,disabled:c,onChange:e=>{h("steps",e)}}),(0,n.jsx)(o7,{id:`${g}-expected`,label:"Expected results (one per line)",value:i.expectedResults,disabled:c,onChange:e=>{h("expectedResults",e)}})]}),(0,n.jsxs)("div",{className:"qi-edit-side",children:[(0,n.jsx)(ce,{id:`${g}-priority`,label:"Priority",value:i.priority,options:o4,disabled:c,onChange:e=>{h("priority",e)}}),(0,n.jsx)(ce,{id:`${g}-risk`,label:"Risk class",value:i.riskClass,options:o3,disabled:c,onChange:e=>{h("riskClass",e)}}),(0,n.jsx)(o9,{id:`${g}-tags`,label:"Tags (comma-separated)",value:i.tags,disabled:c,onChange:e=>{h("tags",e)}})]})]})]})}let ca=new Set(["approved","rejected","withdrawn"]);function cl({items:e,label:t}){return 0===e.length?null:(0,n.jsxs)("div",{className:"qi-cand-block",children:[(0,n.jsx)("p",{className:"qi-cand-block-label",children:t}),(0,n.jsx)("ol",{className:"qi-cand-list","aria-label":t,children:e.map((e,a)=>(0,n.jsx)("li",{children:e},`${t}-${String(a)}`))})]})}function ci({candidate:e}){return(0,n.jsxs)("dl",{className:"qi-cand-meta","aria-label":"Test case metadata",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Steps"}),(0,n.jsx)("dd",{children:e.steps.length.toString()})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Expected"}),(0,n.jsx)("dd",{children:e.expectedResults.length.toString()})]}),void 0!==e.qualityVerdict?(0,n.jsxs)("div",{children:[(0,n.jsx)("dt",{children:"Quality"}),(0,n.jsx)("dd",{children:Math.round(e.qualityVerdict.score).toString()})]}):null]})}function cr({title:e,children:t}){return(0,n.jsxs)("details",{className:"qi-cand-accordion",children:[(0,n.jsx)("summary",{className:"qi-cand-accordion-summary",children:(0,n.jsx)("span",{children:e})}),(0,n.jsx)("div",{className:"qi-cand-accordion-body",children:t})]})}function cs({candidate:e}){return(0,n.jsxs)(cr,{title:"Scenario",children:[(0,n.jsx)(cl,{items:e.preconditions,label:"Preconditions"}),(0,n.jsx)(cl,{items:e.steps,label:"Steps"}),(0,n.jsx)(cl,{items:e.expectedResults,label:"Expected results"})]})}function co({candidate:e}){return 0===e.tags.length&&void 0===e.qualityVerdict&&void 0===e.weakTestFlag?null:(0,n.jsxs)(cr,{title:"Evidence",children:[void 0!==e.weakTestFlag?(0,n.jsx)(oy,{flag:e.weakTestFlag}):null,void 0!==e.qualityVerdict?(0,n.jsx)(oj,{verdict:e.qualityVerdict}):null,e.tags.length>0?(0,n.jsx)("ul",{className:"qi-cand-tags","aria-label":"Tags",children:e.tags.map(e=>(0,n.jsx)("li",{className:"qi-cand-tag",children:e},e))}):null]})}function cc({className:e,label:t,pressed:a,disabled:l,describedBy:i,onActivate:r}){return(0,n.jsx)("button",{type:"button",className:e,...void 0!==a?{"aria-pressed":a}:{},"aria-disabled":l||void 0,"aria-describedby":l?i:void 0,onClick:()=>{l||r()},children:t})}function cd({candidateId:e,state:t,onReview:l,disabled:i=!1,describedBy:r,pendingReview:s}){let o=null!=s,c=t=>o&&s.candidateId===e&&s.action===t,d=ca.has(t),u=(0,a.useId)(),p=d?u:r;return(0,n.jsxs)("div",{className:"qi-cand-actions",role:"group","aria-label":"Review decision",children:[d?(0,n.jsx)("p",{id:u,className:"qi-cand-governance-note",role:"note",children:"This review decision is final — reopen to change it."}):null,(0,n.jsx)(cc,{className:"qi-btn qi-btn-approve",label:c("approve")?"Saving…":"Approve",pressed:"approved"===t,disabled:i||o||d,describedBy:p,onActivate:()=>{l(e,"approve")}}),(0,n.jsx)(cc,{className:"qi-btn qi-btn-reject",label:c("reject")?"Saving…":"Reject",pressed:"rejected"===t,disabled:i||o||d,describedBy:p,onActivate:()=>{l(e,"reject")}}),(0,n.jsx)(cc,{className:"qi-btn qi-btn-secondary",label:c("request-changes")?"Saving…":"Request changes",pressed:"changes-requested"===t,disabled:i||o||d,describedBy:p,onActivate:()=>{l(e,"request-changes")}}),d?(0,n.jsx)(cc,{className:"qi-btn qi-btn-secondary",label:c("reopen")?"Saving…":"Reopen",disabled:i||o,describedBy:i?r:void 0,onActivate:()=>{l(e,"reopen")}}):null]})}function cu({candidate:e,onReview:t,onStartEdit:l,actionsDisabled:i=!1,actionsDisabledReason:r,describedBy:s,editButtonRef:o,pendingReview:c}){let d=(0,a.useId)(),u=i&&void 0!==r?[s,d].filter(Boolean).join(" "):s;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"qi-cand-header",children:[(0,n.jsx)("div",{className:"qi-cand-title-wrap",children:(0,n.jsx)("h3",{className:"qi-cand-title",children:e.title})}),(0,n.jsxs)("div",{className:"qi-cand-status",children:[(0,n.jsxs)("div",{className:"qi-cand-badges",children:[(0,n.jsx)("span",{className:"qi-cand-risk",children:e.riskClass}),"open"!==e.reviewState?(0,n.jsx)(od,{state:e.reviewState}):null]}),(0,n.jsx)(ci,{candidate:e})]})]}),(0,n.jsxs)("div",{className:"qi-cand-accordion-stack",children:[(0,n.jsx)(cs,{candidate:e}),(0,n.jsx)(co,{candidate:e})]}),(0,n.jsxs)("div",{className:"qi-cand-actions-row",children:[i&&void 0!==r?(0,n.jsx)("p",{id:d,className:"qi-cand-action-note",role:"note",children:r}):null,(0,n.jsxs)("div",{className:"qi-cand-action-buttons",children:[void 0!==l?(0,n.jsx)("button",{ref:o,type:"button",className:"qi-btn qi-btn-secondary qi-cand-edit","aria-disabled":i||void 0,"aria-describedby":i?u:void 0,onClick:()=>{i||l()},children:"Edit"}):null,void 0!==t?(0,n.jsx)(cd,{candidateId:e.id,state:e.reviewState,onReview:t,disabled:i,describedBy:u,pendingReview:c}):null]})]})]})}function cp({candidate:e,onReview:t,onEdit:l,actionsDisabled:i=!1,actionsDisabledReason:r,describedBy:s,pendingReview:o}){let[c,d]=(0,a.useState)(!1),u=(0,a.useRef)(null),p=(0,a.useRef)(!1);(0,a.useEffect)(()=>{p.current&&!c&&u.current?.focus(),p.current=c},[c]);let m=async t=>{void 0!==l&&await l(e.id,t),d(!1)};return(0,n.jsx)("li",{className:c?"qi-cand-card qi-cand-card-editing":"qi-cand-card",children:c&&void 0!==l?(0,n.jsx)(cn,{candidate:e,onSave:m,onCancel:()=>{d(!1)}}):(0,n.jsx)(cu,{candidate:e,onReview:t,actionsDisabled:i,actionsDisabledReason:r,describedBy:s,pendingReview:o,editButtonRef:u,onStartEdit:void 0!==l?()=>{d(!0)}:void 0})})}function cm({candidates:e,onReview:t,onEdit:l,actionsDisabled:i=!1,actionsDisabledReason:r,pendingReview:s}){let[o,c]=(0,a.useState)(25),d=(0,a.useId)(),u=i&&void 0!==r;if(0===e.length)return(0,n.jsxs)("div",{className:"lk-empty",children:[(0,n.jsx)("p",{className:"lk-empty-title",children:"No test cases"}),(0,n.jsx)("p",{className:"lk-empty-body",children:"This run produced no generated test cases."})]});let p=[...e].sort((e,t)=>!!e.tags.includes("source:deterministic-baseline")-!!t.tags.includes("source:deterministic-baseline")).slice(0,o);return(0,n.jsxs)("div",{className:"qi-cand-pane",children:[u?(0,n.jsx)("p",{id:d,className:"qi-cand-governance-note",role:"note",children:r}):null,(0,n.jsx)("ul",{className:"qi-cand-cards","aria-label":"Test case list",children:p.map(e=>(0,n.jsx)(cp,{candidate:e,onReview:t,onEdit:l,actionsDisabled:i,actionsDisabledReason:r,describedBy:u?d:void 0,pendingReview:s},e.id))}),o<e.length?(0,n.jsxs)("button",{type:"button",className:"qi-btn qi-btn-secondary qi-cand-more",onClick:()=>{c(e=>e+25)},children:["Show more test cases (",(e.length-o).toString()," remaining)"]}):null]})}function ch(e){return 0===e?"No drift — every test is current.":`${e.toString()} ${1===e?"test is":"tests are"} stale — source changed since this run.`}function cf(e){let t=e.regeneratedCount,n=e.preservedCount;return`Regenerated ${t.toString()} ${1===t?"test":"tests"} as a new run (${n.toString()} ${1===n?"test":"tests"} preserved).`}function cg({staleCount:e}){return 0===e?(0,n.jsxs)("p",{className:"qi-drift-fresh","data-testid":"qi-drift-fresh",children:[(0,n.jsx)("span",{"aria-hidden":"true",className:"qi-drift-icon-ok",children:"✓"}),ch(0)]}):(0,n.jsxs)("p",{className:"qi-drift-stale","data-testid":"qi-drift-stale",children:[(0,n.jsx)("span",{"aria-hidden":"true",className:"qi-drift-icon-warn",children:"⚠"}),ch(e)]})}function cv({runId:e,connectedSources:t,onRegenerated:l,reCheckImpl:i=oa,regenerateImpl:r=ol}){let[s,o]=(0,a.useState)(null),[c,d]=(0,a.useState)(null),u=null!==c,[p,m]=(0,a.useState)(null),[h,f]=(0,a.useState)(null),g=(0,a.useRef)(null),v=(0,a.useRef)(null),b=(0,a.useCallback)(()=>{u||(async()=>{d("check"),m(null),f(null);try{o(await i(e,t))}catch(e){m(ou(e))}finally{d(null)}})()},[u,i,e,t]),x=(0,a.useCallback)(()=>{u||(async()=>{d("regenerate"),m(null);try{let n=await r(e,t);document.activeElement===v.current&&g.current?.focus(),f(n),o(null),l?.(n)}catch(e){m(ou(e))}finally{d(null)}})()},[u,r,e,t,l]);return(0,n.jsxs)("section",{className:"qi-drift-panel","aria-label":"Drift detection",children:[(0,n.jsx)("p",{className:"sr-only",role:"status","aria-live":"polite",children:null!==h?cf(h):null!==s?ch(s.staleCount):""}),(0,n.jsxs)("div",{className:"qi-drift-head",children:[(0,n.jsx)("h3",{className:"qi-col-subtitle",children:"Living tests"}),(0,n.jsx)("button",{type:"button",ref:g,className:"qi-btn qi-btn-secondary",onClick:b,"aria-disabled":u||void 0,"data-testid":"qi-drift-recheck",children:"check"===c?"Checking…":"Re-check drift"})]}),null!==p?(0,n.jsx)("p",{className:"lk-alert",role:"alert",children:p}):null,null!==s?(0,n.jsx)(cg,{staleCount:s.staleCount}):null,null!==s&&s.staleCount>0&&null===h?(0,n.jsx)("button",{type:"button",ref:v,className:"qi-btn qi-btn-approve",onClick:x,"aria-disabled":u||void 0,"data-testid":"qi-drift-regenerate",children:"regenerate"===c?"Regenerating…":`Regenerate ${s.staleCount.toString()} stale ${1===s.staleCount?"test":"tests"}`}):null,null!==h?(0,n.jsx)("p",{className:"qi-drift-regenerated","data-testid":"qi-drift-regenerated",children:cf(h)}):null]})}let cb={"traceability-csv":"csv","traceability-markdown":"markdown"},cx=[{id:"csv",label:"CSV",tms:!1},{id:"json",label:"JSON",tms:!1},{id:"spreadsheet-safe-csv",label:"Spreadsheet-safe CSV",tms:!1},{id:"markdown",label:"Markdown",tms:!1},{id:"plain-text",label:"Plain text",tms:!1},{id:"pdf",label:"PDF",tms:!1},{id:"zip-bundle",label:"ZIP bundle (all formats)",tms:!1},{id:"traceability-csv",label:"Traceability matrix (CSV)",tms:!1},{id:"traceability-markdown",label:"Traceability matrix (Markdown)",tms:!1},{id:"jira-issues",label:"Jira (preview)",tms:!0},{id:"qtest",label:"qTest (preview)",tms:!0},{id:"xray",label:"Xray (preview)",tms:!0},{id:"polarion",label:"Polarion (preview)",tms:!0},{id:"quality-center",label:"Quality Center (preview)",tms:!0}];function cy(e,t,n,a){let l=new Blob(["base64"===a?function(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}(n):n],{type:t}),i=URL.createObjectURL(l),r=document.createElement("a");r.href=i,r.download=e,document.body.appendChild(r),r.click(),r.remove(),window.setTimeout(()=>{URL.revokeObjectURL(i)},250)}function cw({runId:e,exportImpl:t=oi,traceabilityImpl:l=or}){let[i,r]=(0,a.useState)("csv"),[s,o]=(0,a.useState)(!1),[c,d]=(0,a.useState)(null),[u,p]=(0,a.useState)(null),[m,h]=(0,a.useState)(null),[f,g]=(0,a.useState)(!1),v=cx.find(e=>e.id===i),b=v?.tms??!1,x=(0,a.useCallback)(async()=>{let n=cb[i];if(void 0!==n){let t=await l(e,n);cy(t.filename,t.contentType,t.body),h(t.filename);return}let a=await t(e,i,{dryRun:b,approvedOnly:f});a.dryRun?p(`${a.candidateCount.toString()} test case${1===a.candidateCount?"":"s"} \xb7 ${a.byteLen.toString()} bytes
|