@cuongtran001/kanna 1.1.2 → 1.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/dist/client/assets/{arc-C1skjXP3.js → arc-IdUNkfrT.js} +1 -1
  2. package/dist/client/assets/{architectureDiagram-3BPJPVTR-BteUvEIc.js → architectureDiagram-3BPJPVTR-RD8UyEDs.js} +1 -1
  3. package/dist/client/assets/{blockDiagram-GPEHLZMM-CYdyGDmi.js → blockDiagram-GPEHLZMM-CBp2ITpB.js} +1 -1
  4. package/dist/client/assets/{c4Diagram-AAUBKEIU-Xknk3xg-.js → c4Diagram-AAUBKEIU-RVNVZyu2.js} +1 -1
  5. package/dist/client/assets/channel-SMmV1lCd.js +1 -0
  6. package/dist/client/assets/{chunk-2J33WTMH-BAgcE7Nl.js → chunk-2J33WTMH-BioSWRhV.js} +1 -1
  7. package/dist/client/assets/{chunk-4BX2VUAB-JrfFZvXY.js → chunk-4BX2VUAB-FcPD0OHv.js} +1 -1
  8. package/dist/client/assets/{chunk-55IACEB6-B9u1I4Om.js → chunk-55IACEB6-D-VYvhww.js} +1 -1
  9. package/dist/client/assets/{chunk-727SXJPM-C-m-xQRM.js → chunk-727SXJPM-D3yn6PoB.js} +1 -1
  10. package/dist/client/assets/{chunk-AQP2D5EJ-SKs1S-R-.js → chunk-AQP2D5EJ-DlZM0zMZ.js} +1 -1
  11. package/dist/client/assets/{chunk-FMBD7UC4-DKmQ_Mnf.js → chunk-FMBD7UC4-Bql2fVFC.js} +1 -1
  12. package/dist/client/assets/{chunk-ND2GUHAM-C0LtJMFL.js → chunk-ND2GUHAM-DB1qkBJK.js} +1 -1
  13. package/dist/client/assets/{chunk-QZHKN3VN-DTldKht_.js → chunk-QZHKN3VN-BiY9tUJX.js} +1 -1
  14. package/dist/client/assets/classDiagram-4FO5ZUOK-z8JXEtnE.js +1 -0
  15. package/dist/client/assets/classDiagram-v2-Q7XG4LA2-z8JXEtnE.js +1 -0
  16. package/dist/client/assets/{cose-bilkent-S5V4N54A-Cv0GEXWK.js → cose-bilkent-S5V4N54A-sRNRpJ9a.js} +1 -1
  17. package/dist/client/assets/{dagre-BM42HDAG-tn6V33dQ.js → dagre-BM42HDAG-C_pG-mmQ.js} +1 -1
  18. package/dist/client/assets/{diagram-2AECGRRQ-COpwOOVS.js → diagram-2AECGRRQ-C1Sd0F3T.js} +1 -1
  19. package/dist/client/assets/{diagram-5GNKFQAL-weLyadG0.js → diagram-5GNKFQAL-C4sbYmUy.js} +1 -1
  20. package/dist/client/assets/{diagram-KO2AKTUF-B5SZOYvY.js → diagram-KO2AKTUF-BSkhedaS.js} +1 -1
  21. package/dist/client/assets/{diagram-LMA3HP47-DGnCcV1_.js → diagram-LMA3HP47-C7HRWlFc.js} +1 -1
  22. package/dist/client/assets/{diagram-OG6HWLK6-IZCcEKyL.js → diagram-OG6HWLK6-DiJzyEdI.js} +1 -1
  23. package/dist/client/assets/{erDiagram-TEJ5UH35-XIMvpeI-.js → erDiagram-TEJ5UH35-DtvwYy06.js} +1 -1
  24. package/dist/client/assets/{flowDiagram-I6XJVG4X-BCHVmM33.js → flowDiagram-I6XJVG4X-DUZQLxSg.js} +1 -1
  25. package/dist/client/assets/{ganttDiagram-6RSMTGT7-DiVrUbj8.js → ganttDiagram-6RSMTGT7-DKEBnULO.js} +1 -1
  26. package/dist/client/assets/{gitGraphDiagram-PVQCEYII-CXpio127.js → gitGraphDiagram-PVQCEYII-PdHTamNf.js} +1 -1
  27. package/dist/client/assets/{index-DnEzw7n2.js → index-DXMKk4xA.js} +2 -2
  28. package/dist/client/assets/{index-BciRFXmS.js → index-DxYefG8F.js} +1 -1
  29. package/dist/client/assets/{infoDiagram-5YYISTIA-Ba5-V8R6.js → infoDiagram-5YYISTIA-BgQYxH71.js} +1 -1
  30. package/dist/client/assets/{ishikawaDiagram-YF4QCWOH-D4Pnu_e7.js → ishikawaDiagram-YF4QCWOH-OQmKyTIm.js} +1 -1
  31. package/dist/client/assets/{journeyDiagram-JHISSGLW-CbFv1z0V.js → journeyDiagram-JHISSGLW-BgWZXRqQ.js} +1 -1
  32. package/dist/client/assets/{kanban-definition-UN3LZRKU-Bj3xxZFi.js → kanban-definition-UN3LZRKU-zDNUU-fD.js} +1 -1
  33. package/dist/client/assets/{linear-4XntOfIg.js → linear-B08htpTH.js} +1 -1
  34. package/dist/client/assets/{mermaid.core-CDfcYbPP.js → mermaid.core-BeCusr1Y.js} +4 -4
  35. package/dist/client/assets/{mindmap-definition-RKZ34NQL-CN2Rht9K.js → mindmap-definition-RKZ34NQL-CZ9_e2MI.js} +1 -1
  36. package/dist/client/assets/{pieDiagram-4H26LBE5-DYarhIyb.js → pieDiagram-4H26LBE5-PRWaNxAa.js} +1 -1
  37. package/dist/client/assets/{quadrantDiagram-W4KKPZXB-Cd_7JnFh.js → quadrantDiagram-W4KKPZXB-Bbyx7ane.js} +1 -1
  38. package/dist/client/assets/{requirementDiagram-4Y6WPE33-CDW8_iAb.js → requirementDiagram-4Y6WPE33-DN-Je3ad.js} +1 -1
  39. package/dist/client/assets/{sankeyDiagram-5OEKKPKP-BjuOyIe3.js → sankeyDiagram-5OEKKPKP-CupnnbU_.js} +1 -1
  40. package/dist/client/assets/{sequenceDiagram-3UESZ5HK-2VdCuiWh.js → sequenceDiagram-3UESZ5HK-BzJ1VwZW.js} +1 -1
  41. package/dist/client/assets/{stateDiagram-AJRCARHV-D6Y8Tli_.js → stateDiagram-AJRCARHV-D7T232t1.js} +1 -1
  42. package/dist/client/assets/stateDiagram-v2-BHNVJYJU-BMSWjPfi.js +1 -0
  43. package/dist/client/assets/{timeline-definition-PNZ67QCA-B0OltX1Q.js → timeline-definition-PNZ67QCA-BURPUzrP.js} +1 -1
  44. package/dist/client/assets/{vennDiagram-CIIHVFJN-BGoD3ggg.js → vennDiagram-CIIHVFJN-BAdLpjSp.js} +1 -1
  45. package/dist/client/assets/{wardley-L42UT6IY-DViW7r2J.js → wardley-L42UT6IY-D5VL2nwj.js} +1 -1
  46. package/dist/client/assets/{wardleyDiagram-YWT4CUSO-DDwsmwus.js → wardleyDiagram-YWT4CUSO-xPQkrbLX.js} +1 -1
  47. package/dist/client/assets/{xychartDiagram-2RQKCTM6-CFLw7GVr.js → xychartDiagram-2RQKCTM6-BrI58sxn.js} +1 -1
  48. package/dist/client/index.html +1 -1
  49. package/package.json +1 -1
  50. package/src/server/agent.test.ts +256 -0
  51. package/src/server/agent.ts +62 -9
  52. package/dist/client/assets/channel-JjgSQr9C.js +0 -1
  53. package/dist/client/assets/classDiagram-4FO5ZUOK-JferVEg1.js +0 -1
  54. package/dist/client/assets/classDiagram-v2-Q7XG4LA2-JferVEg1.js +0 -1
  55. package/dist/client/assets/stateDiagram-v2-BHNVJYJU-CanW25y1.js +0 -1
@@ -753,7 +753,7 @@ For more information, see https://radix-ui.com/primitives/docs/components/${t.do
753
753
  `)!==n.readPathDeny.join(`
754
754
  `)&&(C.readPathDeny=x),S.join(`
755
755
  `)!==n.writePathDeny.join(`
756
- `)&&(C.writePathDeny=S),Object.keys(C).length===0?null:C}function v(){r(m())}function b(){r(null)}return u.jsxs(u.Fragment,{children:[u.jsx($a,{open:e,onOpenChange:x=>{x||i()},children:u.jsxs(ia,{className:"max-w-2xl",children:[u.jsxs(za,{children:["Permissions — ",t]}),u.jsxs(El,{className:"space-y-5",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx("div",{className:"text-sm font-medium",children:"Default action"}),u.jsxs("div",{className:"text-xs text-muted-foreground",children:["Behaviour when a tool call has no explicit allow/deny rule. ",u.jsx("strong",{children:"auto-allow"})," bypasses prompts and runs untrusted shell commands without supervision — use a worktree."]}),u.jsx(Ns,{value:s,onValueChange:p,options:[{value:"ask",label:"Ask"},{value:"auto-allow",label:"Auto-allow (unsafe)"},{value:"auto-deny",label:"Auto-deny"}]})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx("div",{className:"text-sm font-medium",children:"Read-path deny list"}),u.jsx("div",{className:"text-xs text-muted-foreground",children:"One glob per line. The model cannot read paths matching any entry. Defaults shown below — edit to add or remove."}),u.jsx("textarea",{value:o,onChange:x=>h.getState().setReadDenyText(x.target.value),rows:8,className:"w-full rounded-md border border-border bg-background px-3 py-2 font-mono text-xs",spellCheck:!1})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx("div",{className:"text-sm font-medium",children:"Write-path deny list"}),u.jsx("div",{className:"text-xs text-muted-foreground",children:"One glob per line. The model cannot edit or write paths matching any entry."}),u.jsx("textarea",{value:a,onChange:x=>h.getState().setWriteDenyText(x.target.value),rows:8,className:"w-full rounded-md border border-border bg-background px-3 py-2 font-mono text-xs",spellCheck:!1})]})]}),u.jsxs(bd,{className:"justify-between",children:[u.jsx(Ie,{variant:"ghost",onClick:b,children:"Reset to defaults"}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx(Ie,{variant:"ghost",onClick:i,children:"Cancel"}),u.jsx(Ie,{onClick:v,children:"Apply"})]})]})]})}),u.jsx($a,{open:l,onOpenChange:x=>{x||(h.getState().setConfirmUnsafeOpen(!1),h.getState().setPendingDefaultAction(null))},children:u.jsxs(ia,{className:"max-w-md",children:[u.jsx(za,{children:"Enable auto-allow for this chat?"}),u.jsxs(El,{className:"space-y-3 text-sm",children:[u.jsx("p",{children:"Auto-allow disables tool-call prompts. The model can run shell commands, write files, and edit code without asking. Read/write deny lists still apply."}),u.jsx("p",{className:"text-warning",children:"Use a worktree for risky tasks."})]}),u.jsxs(bd,{className:"justify-end gap-2",children:[u.jsx(Ie,{variant:"ghost",onClick:()=>{h.getState().setConfirmUnsafeOpen(!1),h.getState().setPendingDefaultAction(null)},children:"Cancel"}),u.jsx(Ie,{variant:"destructive",onClick:()=>{const x=h.getState();d&&x.setDefaultAction(d),x.setConfirmUnsafeOpen(!1),x.setPendingDefaultAction(null)},children:"Enable auto-allow"})]})]})})]})}const Vde={defaultAction:"ask",bash:{autoAllowVerbs:["ls","pwd","git status","git diff","git log"]},readPathDeny:["~/.ssh","~/.aws","~/.gcp","~/.config/gh","~/.claude","~/.kanna","~/Library/Keychains","/etc/shadow","/etc/sudoers","~/.gnupg","~/.gitconfig","**/.git/config","~/.npmrc","~/.netrc","~/.docker/config.json","**/.env","**/.env.*","**/credentials*","**/*.pem","**/*.key","**/id_rsa*","**/id_ed25519*"],writePathDeny:["/etc/**","/usr/**","/System/**","~/.ssh/**","~/.aws/**","~/.config/gh/**","~/.claude/**","~/.kanna/**","~/.gnupg/**","~/.gitconfig","**/.git/config"],toolDenyList:[{tool:"mcp__kanna__bash",pattern:"rm\\s+-rf\\s+(/|~|\\$HOME)(?:\\b|$|\\s)"},{tool:"mcp__kanna__bash",pattern:"git\\s+push\\b.*--force"}],toolAllowList:[]},dn=_.forwardRef(({className:e,type:t,...n},r)=>u.jsx("input",{ref:r,type:t,className:he("flex w-full rounded-lg border border-border bg-background px-3 py-2 text-sm text-foreground outline-none placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50",e),...n}));dn.displayName="Input";const t9=_.createContext(null);function Kde({children:e}){const[t,n]=_.useState(null),[r,i]=_.useState(""),s=_.useRef(null);_.useEffect(()=>{(t==null?void 0:t.kind)==="prompt"&&(i(t.options.initialValue??""),setTimeout(()=>{var b,x;(b=s.current)==null||b.focus(),(x=s.current)==null||x.select()},0))},[t]);const o=_.useCallback(()=>{n(null),i("")},[]),a=_.useCallback(()=>{t&&(t.kind==="confirm"?t.resolve(!1):t.kind==="prompt"?t.resolve(null):t.resolve(),o())},[o,t]),l=_.useCallback(()=>{t&&(t.kind==="confirm"?t.resolve(!0):t.kind==="prompt"?t.resolve(r.trim()||null):t.resolve(),o())},[o,t,r]),d=_.useCallback(b=>new Promise(x=>{n({kind:"confirm",options:b,resolve:x})}),[]),h=_.useCallback(b=>new Promise(x=>{n({kind:"prompt",options:b,resolve:x})}),[]),p=_.useCallback(b=>new Promise(x=>{n({kind:"alert",options:b,resolve:x})}),[]),m=_.useMemo(()=>({confirm:d,prompt:h,alert:p}),[p,d,h]);let v="Confirm";return t&&(t.kind==="alert"?v=t.options.closeLabel??"OK":"confirmLabel"in t.options&&(v=t.options.confirmLabel??"Confirm")),u.jsxs(t9.Provider,{value:m,children:[e,u.jsx($a,{open:t!==null,onOpenChange:b=>{b||!t||a()},children:u.jsx(ia,{size:"sm",onKeyDown:b=>{b.key!=="Enter"||b.shiftKey||!t||t.kind!=="confirm"||(b.preventDefault(),l())},children:t?u.jsxs(u.Fragment,{children:[u.jsxs(El,{className:"space-y-4",children:[u.jsx(za,{children:t.options.title}),t.options.description?u.jsx(jx,{children:t.options.description}):null,t.kind==="prompt"?u.jsx(dn,{ref:s,type:"text",value:r,onChange:b=>i(b.target.value),onKeyDown:b=>{b.key==="Enter"&&(b.preventDefault(),l())},placeholder:t.options.placeholder}):null]}),u.jsxs(bd,{children:[u.jsx(Ie,{variant:"ghost",size:"sm",onClick:a,className:t.kind==="alert"?"hidden":void 0,children:"cancelLabel"in t.options?t.options.cancelLabel??"Cancel":"Cancel"}),u.jsx(Ie,{variant:t.kind==="confirm"?t.options.confirmVariant??"default":"secondary",size:"sm",onClick:l,disabled:t.kind==="prompt"&&!r.trim(),children:v})]})]}):null})})]})}function Ox(){const e=_.useContext(t9);if(!e)throw new Error("useAppDialog must be used within AppDialogProvider");return e}const Cj=_.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:he("bg-card text-card-foreground",e),...t}));Cj.displayName="Card";const kj=_.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:he("flex flex-col space-y-1.5 p-2",e),...t}));kj.displayName="CardHeader";const n9=_.forwardRef(({className:e,...t},n)=>u.jsx("h3",{ref:n,className:he("text-2xl font-semibold leading-none tracking-tight",e),...t}));n9.displayName="CardTitle";const r9=_.forwardRef(({className:e,...t},n)=>u.jsx("p",{ref:n,className:he("text-sm text-muted-foreground",e),...t}));r9.displayName="CardDescription";const Ej=_.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:he("p-6 pt-0",e),...t}));Ej.displayName="CardContent";const Gde=_.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:he("flex items-center p-6 pt-0",e),...t}));Gde.displayName="CardFooter";const qde={info:{dotVar:"var(--info)",bgClass:"bg-info/[0.06]"},warning:{dotVar:"var(--warning)",bgClass:"bg-warning/[0.06]"},success:{dotVar:"var(--success)",bgClass:"bg-success/[0.06]"},error:{dotVar:"var(--destructive)",bgClass:"bg-destructive/[0.06]"}};function Yde({variant:e,children:t,dot:n=!0,className:r}){const i=qde[e];return u.jsxs("div",{role:"status",className:he("flex flex-wrap items-center justify-center gap-x-2 gap-y-1 border-b border-border px-4 py-2 text-xs leading-tight",i.bgClass,r),children:[n?u.jsx("span",{"aria-hidden":"true",className:"inline-block size-1.5 shrink-0 rounded-full",style:{backgroundColor:i.dotVar}}):null,t]})}const Xde="modulepreload",Jde=function(e){return"/"+e},v$={},J=function(t,n,r){let i=Promise.resolve();if(n&&n.length>0){let o=function(d){return Promise.all(d.map(h=>Promise.resolve(h).then(p=>({status:"fulfilled",value:p}),p=>({status:"rejected",reason:p}))))};document.getElementsByTagName("link");const a=document.querySelector("meta[property=csp-nonce]"),l=(a==null?void 0:a.nonce)||(a==null?void 0:a.getAttribute("nonce"));i=o(n.map(d=>{if(d=Jde(d),d in v$)return;v$[d]=!0;const h=d.endsWith(".css"),p=h?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${p}`))return;const m=document.createElement("link");if(m.rel=h?"stylesheet":Xde,h||(m.as="script"),m.crossOrigin="",m.href=d,l&&m.setAttribute("nonce",l),document.head.appendChild(m),h)return new Promise((v,b)=>{m.addEventListener("load",v),m.addEventListener("error",()=>b(new Error(`Unable to preload CSS for ${d}`)))})}))}function s(o){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=o,window.dispatchEvent(a),!a.defaultPrevented)throw o}return i.then(o=>{for(const a of o||[])a.status==="rejected"&&s(a.reason);return t().catch(s)})},Zde=_.lazy(()=>J(()=>import("./index-BciRFXmS.js"),[]).then(e=>({default:e.Toaster})));function Qde(){return u.jsx(_.Suspense,{fallback:null,children:u.jsx(Zde,{position:"bottom-right",theme:"system",closeButton:!0,duration:6e3})})}const efe="1.1.2",tfe={version:efe},$r="Kanna",b$="kanna",nfe=".kanna",rfe=".kanna-dev",ife="KANNA_RUNTIME_PROFILE",Nj=`kanna/${tfe.version}`,sfe="[kanna]",ofe=`~/${$r}`;function kC(){const e=Reflect.get(globalThis,"process");return e==null?void 0:e.env}function afe(e=kC()){var t;return((t=e==null?void 0:e[ife])==null?void 0:t.trim().toLowerCase())==="dev"?"dev":"prod"}function lfe(e=kC()){return afe(e)==="dev"?rfe:nfe}function cfe(e=kC()){return`~/${lfe(e)}`}function ufe(e=kC()){return`${cfe(e)}/keybindings.json`}function $_(e){return e?`${b$} ${e}`:b$}const i9="always",s9="funk",dfe=[{value:"blow",label:"Blow"},{value:"bottle",label:"Bottle"},{value:"frog",label:"Frog"},{value:"funk",label:"Funk"},{value:"glass",label:"Glass"},{value:"ping",label:"Ping"},{value:"pop",label:"Pop"},{value:"purr",label:"Purr"},{value:"tink",label:"Tink"}];function ffe(e){switch(e){case"never":case"unfocused":case"always":return e;default:return i9}}function hfe(e){switch(e){case"blow":case"bottle":case"frog":case"funk":case"glass":case"ping":case"pop":case"purr":case"tink":return e;default:return s9}}const Af=dr()(e=>({chatSoundPreference:i9,chatSoundId:s9,setChatSoundPreference:t=>e({chatSoundPreference:ffe(t)}),setChatSoundId:t=>e({chatSoundId:hfe(t)})})),pfe={blow:"/chat-sounds/Blow.mp3",bottle:"/chat-sounds/Bottle.mp3",frog:"/chat-sounds/Frog.mp3",funk:"/chat-sounds/Funk.mp3",glass:"/chat-sounds/Glass.mp3",ping:"/chat-sounds/Ping.mp3",pop:"/chat-sounds/Pop.mp3",purr:"/chat-sounds/Purr.mp3",tink:"/chat-sounds/Tink.mp3"};function mfe(e=document){return e.visibilityState!=="visible"||!e.hasFocus()}function gfe(e){const t=new Audio(pfe[e]);return t.preload="auto",t.play()}async function v2(e,t){if(t<=0)return;const n=Array.from({length:t},(r,i)=>new Promise(s=>{window.setTimeout(()=>{gfe(e).catch(()=>{}).finally(()=>s())},i*90)}));await Promise.all(n)}function vfe(e,t=document){return e==="never"?!1:e==="always"?!0:mfe(t)}function bfe(e){return e.projectGroups.reduce((t,n)=>t+n.chats.reduce((r,i)=>r+(i.unread?1:0)+(i.status==="waiting_for_user"?1:0),0),0)}function x$(e){let t=0;const n=new Set;for(const r of e.projectGroups)for(const i of r.chats)i.unread&&(t+=1),i.status==="waiting_for_user"&&n.add(i.chatId);return{unreadCount:t,waitingChatIds:n}}function xfe(e,t){if(!e)return 0;const n=x$(e),r=x$(t),i=Math.max(0,r.unreadCount-n.unreadCount);let s=0;for(const o of r.waitingChatIds)n.waitingChatIds.has(o)||(s+=1);return i+s}function b2(e){return e.split(/[\s_-]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" ")}const yfe=[/^(?:\/usr\/bin\/env\s+)?(?:\/bin\/)?(?:bash|zsh|sh)\s+(?:-[a-zA-Z]*c|-c)\s+(['"])([\s\S]*)\1$/,/^(?:\/usr\/bin\/env\s+)?(?:\/bin\/)?(?:bash|zsh|sh)\s+(?:-[a-zA-Z]*c|-c)\s+(.+)$/,/^(?:\/usr\/bin\/env\s+)?(?:cmd(?:\.exe)?)\s+\/c\s+(['"])([\s\S]*)\1$/i,/^(?:\/usr\/bin\/env\s+)?(?:cmd(?:\.exe)?)\s+\/c\s+(.+)$/i,/^(?:\/usr\/bin\/env\s+)?(?:powershell(?:\.exe)?|pwsh)\s+(?:-NoProfile\s+)?-Command\s+(['"])([\s\S]*)\1$/i,/^(?:\/usr\/bin\/env\s+)?(?:powershell(?:\.exe)?|pwsh)\s+(?:-NoProfile\s+)?-Command\s+(.+)$/i];function o9(e){const t=e.trim();for(const n of yfe){const r=t.match(n);if(!r)continue;const i=(r[2]??r[1]??"").trim();if(i)return i}return t}function Tj(e){return e.split("/").pop()||e}const _fe=1440*6e4;function Sfe(e,t){if(e===void 0)return null;const n=Math.max(0,t-e),r=6e4,i=60*r,s=_fe,o=7*s;return n<r?"now":n<i?`${Math.floor(n/r)}m`:n<s?`${Math.floor(n/i)}h`:n<o?`${Math.floor(n/s)}d`:`${Math.floor(n/o)}w`}function wfe(e){return e.lastMessageAt??e._creationTime}const Aj=1e3,Z0=60*Aj,$p=60*Z0,oN=24*$p;function Go(e){const t=Math.max(0,e);if(t<Z0)return`${Math.floor(t/Aj)}s`;if(t<$p)return`${Math.floor(t/Z0)}m`;if(t<oN){const i=Math.floor(t/$p),s=Math.floor(t%$p/Z0);return s===0?`${i}h`:`${i}h ${s}m`}const n=Math.floor(t/oN),r=Math.floor(t%oN/$p);return r===0?`${n}d`:`${n}d ${r}h`}function x2(e){const t=Math.max(0,e);if(t>=$p)return Go(t);const n=Math.floor(t/Aj),r=Math.floor(n/60),i=n%60;return`${r}:${i.toString().padStart(2,"0")}`}function y2(e){switch(e){case"idle":return"Idle";case"starting":return"Starting";case"running":return"Running";case"waiting_for_user":return"Waiting";case"failed":return"Failed"}}function y$(e){switch(e){case"running":return"active";case"waiting_for_user":return"attention";case"failed":return"destructive";case"idle":case"starting":default:return"muted"}}function _$(e){switch(e){case"active":return"text-emerald-500 dark:text-emerald-400";case"attention":return"text-amber-500 dark:text-amber-400";case"destructive":return"text-destructive";case"muted":default:return"text-muted-foreground"}}function Rj(e){const t=e+"CollectionProvider",[n,r]=Xc(t),[i,s]=n(t,{collectionRef:{current:null},itemMap:new Map}),o=x=>{const{scope:S,children:C}=x,k=$n.useRef(null),w=$n.useRef(new Map).current;return u.jsx(i,{scope:S,itemMap:w,collectionRef:k,children:C})};o.displayName=t;const a=e+"CollectionSlot",l=Gf(a),d=$n.forwardRef((x,S)=>{const{scope:C,children:k}=x,w=s(a,C),N=Kn(S,w.collectionRef);return u.jsx(l,{ref:N,children:k})});d.displayName=a;const h=e+"CollectionItemSlot",p="data-radix-collection-item",m=Gf(h),v=$n.forwardRef((x,S)=>{const{scope:C,children:k,...w}=x,N=$n.useRef(null),A=Kn(S,N),T=s(h,C);return $n.useEffect(()=>(T.itemMap.set(N,{ref:N,...w}),()=>void T.itemMap.delete(N))),u.jsx(m,{[p]:"",ref:A,children:k})});v.displayName=h;function b(x){const S=s(e+"CollectionConsumer",x);return $n.useCallback(()=>{const k=S.collectionRef.current;if(!k)return[];const w=Array.from(k.querySelectorAll(`[${p}]`));return Array.from(S.itemMap.values()).sort((T,M)=>w.indexOf(T.ref.current)-w.indexOf(M.ref.current))},[S.collectionRef,S.itemMap])}return[{Provider:o,Slot:d,ItemSlot:v},b,r]}var Cfe=_.createContext(void 0);function Mj(e){const t=_.useContext(Cfe);return e||t||"ltr"}var aN="rovingFocusGroup.onEntryFocus",kfe={bubbles:!1,cancelable:!0},Dx="RovingFocusGroup",[_2,a9,Efe]=Rj(Dx),[Nfe,l9]=Xc(Dx,[Efe]),[Tfe,Afe]=Nfe(Dx),c9=_.forwardRef((e,t)=>u.jsx(_2.Provider,{scope:e.__scopeRovingFocusGroup,children:u.jsx(_2.Slot,{scope:e.__scopeRovingFocusGroup,children:u.jsx(Rfe,{...e,ref:t})})}));c9.displayName=Dx;var Rfe=_.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:i=!1,dir:s,currentTabStopId:o,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:l,onEntryFocus:d,preventScrollOnEntryFocus:h=!1,...p}=e,m=_.useRef(null),v=Kn(t,m),b=Mj(s),[x,S]=vm({prop:o,defaultProp:a??null,onChange:l,caller:Dx}),[C,k]=_.useState(!1),w=Da(d),N=a9(n),A=_.useRef(!1),[T,M]=_.useState(0);return _.useEffect(()=>{const j=m.current;if(j)return j.addEventListener(aN,w),()=>j.removeEventListener(aN,w)},[w]),u.jsx(Tfe,{scope:n,orientation:r,dir:b,loop:i,currentTabStopId:x,onItemFocus:_.useCallback(j=>S(j),[S]),onItemShiftTab:_.useCallback(()=>k(!0),[]),onFocusableItemAdd:_.useCallback(()=>M(j=>j+1),[]),onFocusableItemRemove:_.useCallback(()=>M(j=>j-1),[]),children:u.jsx(yn.div,{tabIndex:C||T===0?-1:0,"data-orientation":r,...p,ref:v,style:{outline:"none",...e.style},onMouseDown:st(e.onMouseDown,()=>{A.current=!0}),onFocus:st(e.onFocus,j=>{const P=!A.current;if(j.target===j.currentTarget&&P&&!C){const D=new CustomEvent(aN,kfe);if(j.currentTarget.dispatchEvent(D),!D.defaultPrevented){const L=N().filter(F=>F.focusable),I=L.find(F=>F.active),$=L.find(F=>F.id===x),z=[I,$,...L].filter(Boolean).map(F=>F.ref.current);f9(z,h)}}A.current=!1}),onBlur:st(e.onBlur,()=>k(!1))})})}),u9="RovingFocusGroupItem",d9=_.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:i=!1,tabStopId:s,children:o,...a}=e,l=Tc(),d=s||l,h=Afe(u9,n),p=h.currentTabStopId===d,m=a9(n),{onFocusableItemAdd:v,onFocusableItemRemove:b,currentTabStopId:x}=h;return _.useEffect(()=>{if(r)return v(),()=>b()},[r,v,b]),u.jsx(_2.ItemSlot,{scope:n,id:d,focusable:r,active:i,children:u.jsx(yn.span,{tabIndex:p?0:-1,"data-orientation":h.orientation,...a,ref:t,onMouseDown:st(e.onMouseDown,S=>{r?h.onItemFocus(d):S.preventDefault()}),onFocus:st(e.onFocus,()=>h.onItemFocus(d)),onKeyDown:st(e.onKeyDown,S=>{if(S.key==="Tab"&&S.shiftKey){h.onItemShiftTab();return}if(S.target!==S.currentTarget)return;const C=Ife(S,h.orientation,h.dir);if(C!==void 0){if(S.metaKey||S.ctrlKey||S.altKey||S.shiftKey)return;S.preventDefault();let w=m().filter(N=>N.focusable).map(N=>N.ref.current);if(C==="last")w.reverse();else if(C==="prev"||C==="next"){C==="prev"&&w.reverse();const N=w.indexOf(S.currentTarget);w=h.loop?Pfe(w,N+1):w.slice(N+1)}setTimeout(()=>f9(w))}}),children:typeof o=="function"?o({isCurrentTabStop:p,hasTabStop:x!=null}):o})})});d9.displayName=u9;var Mfe={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function jfe(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function Ife(e,t,n){const r=jfe(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return Mfe[r]}function f9(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function Pfe(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var Lfe=c9,Ofe=d9,S2=["Enter"," "],Dfe=["ArrowDown","PageUp","Home"],h9=["ArrowUp","PageDown","End"],$fe=[...Dfe,...h9],zfe={ltr:[...S2,"ArrowRight"],rtl:[...S2,"ArrowLeft"]},Bfe={ltr:["ArrowLeft"],rtl:["ArrowRight"]},$x="Menu",[kb,Ffe,Ufe]=Rj($x),[gh,p9]=Xc($x,[Ufe,jd,l9]),EC=jd(),m9=l9(),[Hfe,vh]=gh($x),[Wfe,zx]=gh($x),g9=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:i,onOpenChange:s,modal:o=!0}=e,a=EC(t),[l,d]=_.useState(null),h=_.useRef(!1),p=Da(s),m=Mj(i);return _.useEffect(()=>{const v=()=>{h.current=!0,document.addEventListener("pointerdown",b,{capture:!0,once:!0}),document.addEventListener("pointermove",b,{capture:!0,once:!0})},b=()=>h.current=!1;return document.addEventListener("keydown",v,{capture:!0}),()=>{document.removeEventListener("keydown",v,{capture:!0}),document.removeEventListener("pointerdown",b,{capture:!0}),document.removeEventListener("pointermove",b,{capture:!0})}},[]),u.jsx(yC,{...a,children:u.jsx(Hfe,{scope:t,open:n,onOpenChange:p,content:l,onContentChange:d,children:u.jsx(Wfe,{scope:t,onClose:_.useCallback(()=>p(!1),[p]),isUsingKeyboardRef:h,dir:m,modal:o,children:r})})})};g9.displayName=$x;var Vfe="MenuAnchor",jj=_.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=EC(n);return u.jsx(Px,{...i,...r,ref:t})});jj.displayName=Vfe;var Ij="MenuPortal",[Kfe,v9]=gh(Ij,{forceMount:void 0}),b9=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:i}=e,s=vh(Ij,t);return u.jsx(Kfe,{scope:t,forceMount:n,children:u.jsx(fa,{present:n||s.open,children:u.jsx(Ym,{asChild:!0,container:i,children:r})})})};b9.displayName=Ij;var ea="MenuContent",[Gfe,Pj]=gh(ea),x9=_.forwardRef((e,t)=>{const n=v9(ea,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,s=vh(ea,e.__scopeMenu),o=zx(ea,e.__scopeMenu);return u.jsx(kb.Provider,{scope:e.__scopeMenu,children:u.jsx(fa,{present:r||s.open,children:u.jsx(kb.Slot,{scope:e.__scopeMenu,children:o.modal?u.jsx(qfe,{...i,ref:t}):u.jsx(Yfe,{...i,ref:t})})})})}),qfe=_.forwardRef((e,t)=>{const n=vh(ea,e.__scopeMenu),r=_.useRef(null),i=Kn(t,r);return _.useEffect(()=>{const s=r.current;if(s)return pC(s)},[]),u.jsx(Lj,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:st(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),Yfe=_.forwardRef((e,t)=>{const n=vh(ea,e.__scopeMenu);return u.jsx(Lj,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),Xfe=Gf("MenuContent.ScrollLock"),Lj=_.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:i,onOpenAutoFocus:s,onCloseAutoFocus:o,disableOutsidePointerEvents:a,onEntryFocus:l,onEscapeKeyDown:d,onPointerDownOutside:h,onFocusOutside:p,onInteractOutside:m,onDismiss:v,disableOutsideScroll:b,...x}=e,S=vh(ea,n),C=zx(ea,n),k=EC(n),w=m9(n),N=Ffe(n),[A,T]=_.useState(null),M=_.useRef(null),j=Kn(t,M,S.onContentChange),P=_.useRef(0),D=_.useRef(""),L=_.useRef(0),I=_.useRef(null),$=_.useRef("right"),H=_.useRef(0),z=b?Mx:_.Fragment,F=b?{as:Xfe,allowPinchZoom:!0}:void 0,K=V=>{var ne,ie;const X=D.current+V,G=N().filter(ae=>!ae.disabled),te=document.activeElement,oe=(ne=G.find(ae=>ae.ref.current===te))==null?void 0:ne.textValue,ue=G.map(ae=>ae.textValue),de=lhe(ue,X,oe),ee=(ie=G.find(ae=>ae.textValue===de))==null?void 0:ie.ref.current;(function ae(Q){D.current=Q,window.clearTimeout(P.current),Q!==""&&(P.current=window.setTimeout(()=>ae(""),1e3))})(X),ee&&setTimeout(()=>ee.focus())};_.useEffect(()=>()=>window.clearTimeout(P.current),[]),fC();const W=_.useCallback(V=>{var G,te;return $.current===((G=I.current)==null?void 0:G.side)&&uhe(V,(te=I.current)==null?void 0:te.area)},[]);return u.jsx(Gfe,{scope:n,searchRef:D,onItemEnter:_.useCallback(V=>{W(V)&&V.preventDefault()},[W]),onItemLeave:_.useCallback(V=>{var X;W(V)||((X=M.current)==null||X.focus(),T(null))},[W]),onTriggerLeave:_.useCallback(V=>{W(V)&&V.preventDefault()},[W]),pointerGraceTimerRef:L,onPointerGraceIntentChange:_.useCallback(V=>{I.current=V},[]),children:u.jsx(z,{...F,children:u.jsx(Rx,{asChild:!0,trapped:i,onMountAutoFocus:st(s,V=>{var X;V.preventDefault(),(X=M.current)==null||X.focus({preventScroll:!0})}),onUnmountAutoFocus:o,children:u.jsx(qm,{asChild:!0,disableOutsidePointerEvents:a,onEscapeKeyDown:d,onPointerDownOutside:h,onFocusOutside:p,onInteractOutside:m,onDismiss:v,children:u.jsx(Lfe,{asChild:!0,...w,dir:C.dir,orientation:"vertical",loop:r,currentTabStopId:A,onCurrentTabStopIdChange:T,onEntryFocus:st(l,V=>{C.isUsingKeyboardRef.current||V.preventDefault()}),preventScrollOnEntryFocus:!0,children:u.jsx(_C,{role:"menu","aria-orientation":"vertical","data-state":L9(S.open),"data-radix-menu-content":"",dir:C.dir,...k,...x,ref:j,style:{outline:"none",...x.style},onKeyDown:st(x.onKeyDown,V=>{const G=V.target.closest("[data-radix-menu-content]")===V.currentTarget,te=V.ctrlKey||V.altKey||V.metaKey,oe=V.key.length===1;G&&(V.key==="Tab"&&V.preventDefault(),!te&&oe&&K(V.key));const ue=M.current;if(V.target!==ue||!$fe.includes(V.key))return;V.preventDefault();const ee=N().filter(ne=>!ne.disabled).map(ne=>ne.ref.current);h9.includes(V.key)&&ee.reverse(),ohe(ee)}),onBlur:st(e.onBlur,V=>{V.currentTarget.contains(V.target)||(window.clearTimeout(P.current),D.current="")}),onPointerMove:st(e.onPointerMove,Eb(V=>{const X=V.target,G=H.current!==V.clientX;if(V.currentTarget.contains(X)&&G){const te=V.clientX>H.current?"right":"left";$.current=te,H.current=V.clientX}}))})})})})})})});x9.displayName=ea;var Jfe="MenuGroup",Oj=_.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return u.jsx(yn.div,{role:"group",...r,ref:t})});Oj.displayName=Jfe;var Zfe="MenuLabel",y9=_.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return u.jsx(yn.div,{...r,ref:t})});y9.displayName=Zfe;var qS="MenuItem",S$="menu.itemSelect",NC=_.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...i}=e,s=_.useRef(null),o=zx(qS,e.__scopeMenu),a=Pj(qS,e.__scopeMenu),l=Kn(t,s),d=_.useRef(!1),h=()=>{const p=s.current;if(!n&&p){const m=new CustomEvent(S$,{bubbles:!0,cancelable:!0});p.addEventListener(S$,v=>r==null?void 0:r(v),{once:!0}),$H(p,m),m.defaultPrevented?d.current=!1:o.onClose()}};return u.jsx(_9,{...i,ref:l,disabled:n,onClick:st(e.onClick,h),onPointerDown:p=>{var m;(m=e.onPointerDown)==null||m.call(e,p),d.current=!0},onPointerUp:st(e.onPointerUp,p=>{var m;d.current||(m=p.currentTarget)==null||m.click()}),onKeyDown:st(e.onKeyDown,p=>{const m=a.searchRef.current!=="";n||m&&p.key===" "||S2.includes(p.key)&&(p.currentTarget.click(),p.preventDefault())})})});NC.displayName=qS;var _9=_.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:i,...s}=e,o=Pj(qS,n),a=m9(n),l=_.useRef(null),d=Kn(t,l),[h,p]=_.useState(!1),[m,v]=_.useState("");return _.useEffect(()=>{const b=l.current;b&&v((b.textContent??"").trim())},[s.children]),u.jsx(kb.ItemSlot,{scope:n,disabled:r,textValue:i??m,children:u.jsx(Ofe,{asChild:!0,...a,focusable:!r,children:u.jsx(yn.div,{role:"menuitem","data-highlighted":h?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...s,ref:d,onPointerMove:st(e.onPointerMove,Eb(b=>{r?o.onItemLeave(b):(o.onItemEnter(b),b.defaultPrevented||b.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:st(e.onPointerLeave,Eb(b=>o.onItemLeave(b))),onFocus:st(e.onFocus,()=>p(!0)),onBlur:st(e.onBlur,()=>p(!1))})})})}),Qfe="MenuCheckboxItem",S9=_.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...i}=e;return u.jsx(N9,{scope:e.__scopeMenu,checked:n,children:u.jsx(NC,{role:"menuitemcheckbox","aria-checked":YS(n)?"mixed":n,...i,ref:t,"data-state":$j(n),onSelect:st(i.onSelect,()=>r==null?void 0:r(YS(n)?!0:!n),{checkForDefaultPrevented:!1})})})});S9.displayName=Qfe;var w9="MenuRadioGroup",[ehe,the]=gh(w9,{value:void 0,onValueChange:()=>{}}),C9=_.forwardRef((e,t)=>{const{value:n,onValueChange:r,...i}=e,s=Da(r);return u.jsx(ehe,{scope:e.__scopeMenu,value:n,onValueChange:s,children:u.jsx(Oj,{...i,ref:t})})});C9.displayName=w9;var k9="MenuRadioItem",E9=_.forwardRef((e,t)=>{const{value:n,...r}=e,i=the(k9,e.__scopeMenu),s=n===i.value;return u.jsx(N9,{scope:e.__scopeMenu,checked:s,children:u.jsx(NC,{role:"menuitemradio","aria-checked":s,...r,ref:t,"data-state":$j(s),onSelect:st(r.onSelect,()=>{var o;return(o=i.onValueChange)==null?void 0:o.call(i,n)},{checkForDefaultPrevented:!1})})})});E9.displayName=k9;var Dj="MenuItemIndicator",[N9,nhe]=gh(Dj,{checked:!1}),T9=_.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...i}=e,s=nhe(Dj,n);return u.jsx(fa,{present:r||YS(s.checked)||s.checked===!0,children:u.jsx(yn.span,{...i,ref:t,"data-state":$j(s.checked)})})});T9.displayName=Dj;var rhe="MenuSeparator",A9=_.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return u.jsx(yn.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});A9.displayName=rhe;var ihe="MenuArrow",R9=_.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=EC(n);return u.jsx(SC,{...i,...r,ref:t})});R9.displayName=ihe;var she="MenuSub",[s8e,M9]=gh(she),Tv="MenuSubTrigger",j9=_.forwardRef((e,t)=>{const n=vh(Tv,e.__scopeMenu),r=zx(Tv,e.__scopeMenu),i=M9(Tv,e.__scopeMenu),s=Pj(Tv,e.__scopeMenu),o=_.useRef(null),{pointerGraceTimerRef:a,onPointerGraceIntentChange:l}=s,d={__scopeMenu:e.__scopeMenu},h=_.useCallback(()=>{o.current&&window.clearTimeout(o.current),o.current=null},[]);return _.useEffect(()=>h,[h]),_.useEffect(()=>{const p=a.current;return()=>{window.clearTimeout(p),l(null)}},[a,l]),u.jsx(jj,{asChild:!0,...d,children:u.jsx(_9,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":i.contentId,"data-state":L9(n.open),...e,ref:sj(t,i.onTriggerChange),onClick:p=>{var m;(m=e.onClick)==null||m.call(e,p),!(e.disabled||p.defaultPrevented)&&(p.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:st(e.onPointerMove,Eb(p=>{s.onItemEnter(p),!p.defaultPrevented&&!e.disabled&&!n.open&&!o.current&&(s.onPointerGraceIntentChange(null),o.current=window.setTimeout(()=>{n.onOpenChange(!0),h()},100))})),onPointerLeave:st(e.onPointerLeave,Eb(p=>{var v,b;h();const m=(v=n.content)==null?void 0:v.getBoundingClientRect();if(m){const x=(b=n.content)==null?void 0:b.dataset.side,S=x==="right",C=S?-5:5,k=m[S?"left":"right"],w=m[S?"right":"left"];s.onPointerGraceIntentChange({area:[{x:p.clientX+C,y:p.clientY},{x:k,y:m.top},{x:w,y:m.top},{x:w,y:m.bottom},{x:k,y:m.bottom}],side:x}),window.clearTimeout(a.current),a.current=window.setTimeout(()=>s.onPointerGraceIntentChange(null),300)}else{if(s.onTriggerLeave(p),p.defaultPrevented)return;s.onPointerGraceIntentChange(null)}})),onKeyDown:st(e.onKeyDown,p=>{var v;const m=s.searchRef.current!=="";e.disabled||m&&p.key===" "||zfe[r.dir].includes(p.key)&&(n.onOpenChange(!0),(v=n.content)==null||v.focus(),p.preventDefault())})})})});j9.displayName=Tv;var I9="MenuSubContent",P9=_.forwardRef((e,t)=>{const n=v9(ea,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,s=vh(ea,e.__scopeMenu),o=zx(ea,e.__scopeMenu),a=M9(I9,e.__scopeMenu),l=_.useRef(null),d=Kn(t,l);return u.jsx(kb.Provider,{scope:e.__scopeMenu,children:u.jsx(fa,{present:r||s.open,children:u.jsx(kb.Slot,{scope:e.__scopeMenu,children:u.jsx(Lj,{id:a.contentId,"aria-labelledby":a.triggerId,...i,ref:d,align:"start",side:o.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:h=>{var p;o.isUsingKeyboardRef.current&&((p=l.current)==null||p.focus()),h.preventDefault()},onCloseAutoFocus:h=>h.preventDefault(),onFocusOutside:st(e.onFocusOutside,h=>{h.target!==a.trigger&&s.onOpenChange(!1)}),onEscapeKeyDown:st(e.onEscapeKeyDown,h=>{o.onClose(),h.preventDefault()}),onKeyDown:st(e.onKeyDown,h=>{var v;const p=h.currentTarget.contains(h.target),m=Bfe[o.dir].includes(h.key);p&&m&&(s.onOpenChange(!1),(v=a.trigger)==null||v.focus(),h.preventDefault())})})})})})});P9.displayName=I9;function L9(e){return e?"open":"closed"}function YS(e){return e==="indeterminate"}function $j(e){return YS(e)?"indeterminate":e?"checked":"unchecked"}function ohe(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function ahe(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function lhe(e,t,n){const i=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,s=n?e.indexOf(n):-1;let o=ahe(e,Math.max(s,0));i.length===1&&(o=o.filter(d=>d!==n));const l=o.find(d=>d.toLowerCase().startsWith(i.toLowerCase()));return l!==n?l:void 0}function che(e,t){const{x:n,y:r}=e;let i=!1;for(let s=0,o=t.length-1;s<t.length;o=s++){const a=t[s],l=t[o],d=a.x,h=a.y,p=l.x,m=l.y;h>r!=m>r&&n<(p-d)*(r-h)/(m-h)+d&&(i=!i)}return i}function uhe(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return che(n,t)}function Eb(e){return t=>t.pointerType==="mouse"?e(t):void 0}var dhe=g9,fhe=jj,hhe=b9,phe=x9,mhe=Oj,ghe=y9,vhe=NC,bhe=S9,xhe=C9,yhe=E9,_he=T9,She=A9,whe=R9,Che=j9,khe=P9,zj="ContextMenu",[Ehe]=Xc(zj,[p9]),Ps=p9(),[Nhe,O9]=Ehe(zj),D9=e=>{const{__scopeContextMenu:t,children:n,onOpenChange:r,dir:i,modal:s=!0}=e,[o,a]=_.useState(!1),l=Ps(t),d=Da(r),h=_.useCallback(p=>{a(p),d(p)},[d]);return u.jsx(Nhe,{scope:t,open:o,onOpenChange:h,modal:s,children:u.jsx(dhe,{...l,dir:i,open:o,onOpenChange:h,modal:s,children:n})})};D9.displayName=zj;var $9="ContextMenuTrigger",z9=_.forwardRef((e,t)=>{const{__scopeContextMenu:n,disabled:r=!1,...i}=e,s=O9($9,n),o=Ps(n),a=_.useRef({x:0,y:0}),l=_.useRef({getBoundingClientRect:()=>DOMRect.fromRect({width:0,height:0,...a.current})}),d=_.useRef(0),h=_.useCallback(()=>window.clearTimeout(d.current),[]),p=m=>{a.current={x:m.clientX,y:m.clientY},s.onOpenChange(!0)};return _.useEffect(()=>h,[h]),_.useEffect(()=>void(r&&h()),[r,h]),u.jsxs(u.Fragment,{children:[u.jsx(fhe,{...o,virtualRef:l}),u.jsx(yn.span,{"data-state":s.open?"open":"closed","data-disabled":r?"":void 0,...i,ref:t,style:{WebkitTouchCallout:"none",...e.style},onContextMenu:r?e.onContextMenu:st(e.onContextMenu,m=>{h(),p(m),m.preventDefault()}),onPointerDown:r?e.onPointerDown:st(e.onPointerDown,z_(m=>{h(),d.current=window.setTimeout(()=>p(m),700)})),onPointerMove:r?e.onPointerMove:st(e.onPointerMove,z_(h)),onPointerCancel:r?e.onPointerCancel:st(e.onPointerCancel,z_(h)),onPointerUp:r?e.onPointerUp:st(e.onPointerUp,z_(h))})]})});z9.displayName=$9;var The="ContextMenuPortal",B9=e=>{const{__scopeContextMenu:t,...n}=e,r=Ps(t);return u.jsx(hhe,{...r,...n})};B9.displayName=The;var F9="ContextMenuContent",U9=_.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=O9(F9,n),s=Ps(n),o=_.useRef(!1);return u.jsx(phe,{...s,...r,ref:t,side:"right",sideOffset:2,align:"start",onCloseAutoFocus:a=>{var l;(l=e.onCloseAutoFocus)==null||l.call(e,a),!a.defaultPrevented&&o.current&&a.preventDefault(),o.current=!1},onInteractOutside:a=>{var l;(l=e.onInteractOutside)==null||l.call(e,a),!a.defaultPrevented&&!i.modal&&(o.current=!0)},style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});U9.displayName=F9;var Ahe="ContextMenuGroup",Rhe=_.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Ps(n);return u.jsx(mhe,{...i,...r,ref:t})});Rhe.displayName=Ahe;var Mhe="ContextMenuLabel",jhe=_.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Ps(n);return u.jsx(ghe,{...i,...r,ref:t})});jhe.displayName=Mhe;var Ihe="ContextMenuItem",H9=_.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Ps(n);return u.jsx(vhe,{...i,...r,ref:t})});H9.displayName=Ihe;var Phe="ContextMenuCheckboxItem",Lhe=_.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Ps(n);return u.jsx(bhe,{...i,...r,ref:t})});Lhe.displayName=Phe;var Ohe="ContextMenuRadioGroup",Dhe=_.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Ps(n);return u.jsx(xhe,{...i,...r,ref:t})});Dhe.displayName=Ohe;var $he="ContextMenuRadioItem",zhe=_.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Ps(n);return u.jsx(yhe,{...i,...r,ref:t})});zhe.displayName=$he;var Bhe="ContextMenuItemIndicator",Fhe=_.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Ps(n);return u.jsx(_he,{...i,...r,ref:t})});Fhe.displayName=Bhe;var Uhe="ContextMenuSeparator",W9=_.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Ps(n);return u.jsx(She,{...i,...r,ref:t})});W9.displayName=Uhe;var Hhe="ContextMenuArrow",Whe=_.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Ps(n);return u.jsx(whe,{...i,...r,ref:t})});Whe.displayName=Hhe;var Vhe="ContextMenuSubTrigger",Khe=_.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Ps(n);return u.jsx(Che,{...i,...r,ref:t})});Khe.displayName=Vhe;var Ghe="ContextMenuSubContent",qhe=_.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Ps(n);return u.jsx(khe,{...i,...r,ref:t,style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});qhe.displayName=Ghe;function z_(e){return t=>t.pointerType!=="mouse"?e(t):void 0}var Yhe=D9,Xhe=z9,Jhe=B9,V9=U9,K9=H9,G9=W9;const q9=_.createContext(null);function bh({onOpenChange:e,...t}){const[n,r]=_.useState(0),i=_.useCallback(()=>{r(s=>s+1),e==null||e(!1)},[e]);return u.jsx(q9.Provider,{value:i,children:u.jsx(Yhe,{onOpenChange:e,...t},n)})}const xh=Xhe,Id=_.forwardRef(({className:e,...t},n)=>u.jsx(Jhe,{children:u.jsx(V9,{ref:n,className:he("z-50 min-w-[170px] overflow-hidden rounded-xl border border-border bg-background p-1 shadow-lg outline-hidden animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",e),...t})}));Id.displayName=V9.displayName;const br=_.forwardRef(({className:e,onSelect:t,...n},r)=>{const i=_.useContext(q9);return u.jsx(K9,{ref:r,className:he("relative flex cursor-default select-none items-center gap-2.5 rounded-lg px-3 py-2 text-xs font-medium text-foreground outline-hidden transition-colors hover:bg-muted focus:bg-muted data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),onSelect:s=>{t==null||t(s),i==null||i()},...n})});br.displayName=K9.displayName;const Y9=_.forwardRef(({className:e,...t},n)=>u.jsx(G9,{ref:n,className:he("-mx-1 my-1 h-px bg-border",e),...t}));Y9.displayName=G9.displayName;var TC="Popover",[X9]=Xc(TC,[jd]),Bx=jd(),[Zhe,Pd]=X9(TC),J9=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:i,onOpenChange:s,modal:o=!1}=e,a=Bx(t),l=_.useRef(null),[d,h]=_.useState(!1),[p,m]=vm({prop:r,defaultProp:i??!1,onChange:s,caller:TC});return u.jsx(yC,{...a,children:u.jsx(Zhe,{scope:t,contentId:Tc(),triggerRef:l,open:p,onOpenChange:m,onOpenToggle:_.useCallback(()=>m(v=>!v),[m]),hasCustomAnchor:d,onCustomAnchorAdd:_.useCallback(()=>h(!0),[]),onCustomAnchorRemove:_.useCallback(()=>h(!1),[]),modal:o,children:n})})};J9.displayName=TC;var Z9="PopoverAnchor",Qhe=_.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=Pd(Z9,n),s=Bx(n),{onCustomAnchorAdd:o,onCustomAnchorRemove:a}=i;return _.useEffect(()=>(o(),()=>a()),[o,a]),u.jsx(Px,{...s,...r,ref:t})});Qhe.displayName=Z9;var Q9="PopoverTrigger",eW=_.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=Pd(Q9,n),s=Bx(n),o=Kn(t,i.triggerRef),a=u.jsx(yn.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":sW(i.open),...r,ref:o,onClick:st(e.onClick,i.onOpenToggle)});return i.hasCustomAnchor?a:u.jsx(Px,{asChild:!0,...s,children:a})});eW.displayName=Q9;var Bj="PopoverPortal",[epe,tpe]=X9(Bj,{forceMount:void 0}),tW=e=>{const{__scopePopover:t,forceMount:n,children:r,container:i}=e,s=Pd(Bj,t);return u.jsx(epe,{scope:t,forceMount:n,children:u.jsx(fa,{present:n||s.open,children:u.jsx(Ym,{asChild:!0,container:i,children:r})})})};tW.displayName=Bj;var ym="PopoverContent",nW=_.forwardRef((e,t)=>{const n=tpe(ym,e.__scopePopover),{forceMount:r=n.forceMount,...i}=e,s=Pd(ym,e.__scopePopover);return u.jsx(fa,{present:r||s.open,children:s.modal?u.jsx(rpe,{...i,ref:t}):u.jsx(ipe,{...i,ref:t})})});nW.displayName=ym;var npe=Gf("PopoverContent.RemoveScroll"),rpe=_.forwardRef((e,t)=>{const n=Pd(ym,e.__scopePopover),r=_.useRef(null),i=Kn(t,r),s=_.useRef(!1);return _.useEffect(()=>{const o=r.current;if(o)return pC(o)},[]),u.jsx(Mx,{as:npe,allowPinchZoom:!0,children:u.jsx(rW,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:st(e.onCloseAutoFocus,o=>{var a;o.preventDefault(),s.current||(a=n.triggerRef.current)==null||a.focus()}),onPointerDownOutside:st(e.onPointerDownOutside,o=>{const a=o.detail.originalEvent,l=a.button===0&&a.ctrlKey===!0,d=a.button===2||l;s.current=d},{checkForDefaultPrevented:!1}),onFocusOutside:st(e.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1})})})}),ipe=_.forwardRef((e,t)=>{const n=Pd(ym,e.__scopePopover),r=_.useRef(!1),i=_.useRef(!1);return u.jsx(rW,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{var o,a;(o=e.onCloseAutoFocus)==null||o.call(e,s),s.defaultPrevented||(r.current||(a=n.triggerRef.current)==null||a.focus(),s.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:s=>{var l,d;(l=e.onInteractOutside)==null||l.call(e,s),s.defaultPrevented||(r.current=!0,s.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const o=s.target;((d=n.triggerRef.current)==null?void 0:d.contains(o))&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&i.current&&s.preventDefault()}})}),rW=_.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:s,disableOutsidePointerEvents:o,onEscapeKeyDown:a,onPointerDownOutside:l,onFocusOutside:d,onInteractOutside:h,...p}=e,m=Pd(ym,n),v=Bx(n);return fC(),u.jsx(Rx,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:s,children:u.jsx(qm,{asChild:!0,disableOutsidePointerEvents:o,onInteractOutside:h,onEscapeKeyDown:a,onPointerDownOutside:l,onFocusOutside:d,onDismiss:()=>m.onOpenChange(!1),children:u.jsx(_C,{"data-state":sW(m.open),role:"dialog",id:m.contentId,...v,...p,ref:t,style:{...p.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),iW="PopoverClose",spe=_.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=Pd(iW,n);return u.jsx(yn.button,{type:"button",...r,ref:t,onClick:st(e.onClick,()=>i.onOpenChange(!1))})});spe.displayName=iW;var ope="PopoverArrow",ape=_.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=Bx(n);return u.jsx(SC,{...i,...r,ref:t})});ape.displayName=ope;function sW(e){return e?"open":"closed"}var lpe=J9,cpe=eW,upe=tW,oW=nW;const Ld=lpe,Od=cpe,Zc=_.forwardRef(({className:e,align:t="center",sideOffset:n=4,...r},i)=>u.jsx(upe,{children:u.jsx(oW,{ref:i,align:t,sideOffset:n,[yb]:"",onCloseAutoFocus:s=>{var o;s.preventDefault(),window.dispatchEvent(new Event(FS)),(o=r.onCloseAutoFocus)==null||o.call(r,s)},className:he("z-50 w-72 rounded-xl border border-border bg-background p-4 shadow-lg outline-hidden animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r})}));Zc.displayName=oW.displayName;const w2=tn("StackActionsPopover",()=>e=>({open:!1,setOpen:t=>e({open:t})}));function dpe({editorLabel:e,starred:t,onCopyPath:n,onShowArchived:r,onOpenInFinder:i,onOpenInEditor:s,onToggleStar:o,onHide:a,children:l}){return u.jsxs(bh,{children:[u.jsx(xh,{asChild:!0,children:l}),u.jsxs(Id,{children:[u.jsxs(br,{onSelect:d=>{d.stopPropagation(),o()},children:[t?u.jsx(hae,{className:"h-3.5 w-3.5"}):u.jsx(bH,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"text-xs font-medium",children:t?"Unstar project":"Star project"})]}),u.jsxs(br,{onSelect:d=>{d.stopPropagation(),n()},children:[u.jsx(Oa,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"text-xs font-medium",children:"Copy Path"})]}),u.jsxs(br,{onSelect:d=>{d.stopPropagation(),r()},children:[u.jsx(KM,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"text-xs font-medium",children:"Show Archived"})]}),u.jsxs(br,{onSelect:d=>{d.stopPropagation(),i()},children:[u.jsx(cC,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"text-xs font-medium",children:"Show in Finder"})]}),u.jsxs(br,{onSelect:d=>{d.stopPropagation(),s()},children:[u.jsx(GM,{className:"h-3.5 w-3.5"}),u.jsxs("span",{className:"text-xs font-medium",children:["Open in ",e]})]}),u.jsxs(br,{onSelect:d=>{d.stopPropagation(),a()},className:"text-destructive hover:bg-destructive/10 focus:bg-destructive/10",children:[u.jsx(ose,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"text-xs font-medium",children:"Hide"})]})]})]})}function fpe({canFork:e,onRename:t,onOpenInFinder:n,onFork:r,onArchive:i,onDelete:s,onEditPermissions:o,children:a}){return u.jsxs(bh,{children:[u.jsx(xh,{asChild:!0,children:a}),u.jsxs(Id,{children:[u.jsxs(br,{onSelect:l=>{l.preventDefault(),t()},children:[u.jsx(Rd,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"text-xs font-medium",children:"Rename"})]}),u.jsxs(br,{onSelect:l=>{l.preventDefault(),n()},children:[u.jsx(cC,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"text-xs font-medium",children:"Open in Finder"})]}),u.jsxs(br,{disabled:!e,onSelect:l=>{l.preventDefault(),e&&r()},children:[u.jsx(vH,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"text-xs font-medium",children:"Fork"})]}),o?u.jsxs(br,{onSelect:l=>{l.preventDefault(),o()},children:[u.jsx(QM,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"text-xs font-medium",children:"Permissions…"})]}):null,u.jsxs(br,{onSelect:l=>{l.preventDefault(),i()},children:[u.jsx(KM,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"text-xs font-medium",children:"Archive"})]}),u.jsxs(br,{onSelect:l=>{l.preventDefault(),s()},className:"text-destructive dark:text-red-400 hover:bg-destructive/10 focus:bg-destructive/10 dark:hover:bg-red-500/20 dark:focus:bg-red-500/20",children:[u.jsx(Yc,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"text-xs font-medium",children:"Delete"})]})]})]})}function hpe({stackTitle:e,onRename:t,onEditMembers:n,onDelete:r,children:i}){const s=w2.useScopedStore(l=>l.open),o=w2.useScopedStore(l=>l.setOpen);function a(l){return()=>{o(!1),l()}}return u.jsxs(Ld,{open:s,onOpenChange:o,children:[u.jsx(Od,{asChild:!0,children:i}),u.jsxs(Zc,{align:"end",sideOffset:4,className:"w-44 p-1",role:"menu","aria-label":`Actions for ${e}`,children:[u.jsxs("button",{type:"button",role:"menuitem",onClick:a(t),className:"flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-left text-xs font-medium hover:bg-muted focus-visible:bg-muted outline-hidden",children:[u.jsx(Rd,{className:"h-3.5 w-3.5"}),u.jsx("span",{children:"Rename"})]}),u.jsxs("button",{type:"button",role:"menuitem",onClick:a(n),className:"flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-left text-xs font-medium hover:bg-muted focus-visible:bg-muted outline-hidden",children:[u.jsx(yH,{className:"h-3.5 w-3.5"}),u.jsx("span",{children:"Edit members"})]}),u.jsxs("button",{type:"button",role:"menuitem",onClick:a(r),className:"flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-left text-xs font-medium text-destructive dark:text-red-400 hover:bg-destructive/10 focus-visible:bg-destructive/10 dark:hover:bg-red-500/20 dark:focus-visible:bg-red-500/20 outline-hidden",children:[u.jsx(Yc,{className:"h-3.5 w-3.5"}),u.jsxs("span",{children:["Delete ",e]})]})]})]})}function ppe({stackTitle:e,onRename:t,onEditMembers:n,onDelete:r,children:i}){return u.jsx(w2.Provider,{init:{},children:u.jsx(hpe,{stackTitle:e,onRename:t,onEditMembers:n,onDelete:r,children:i})})}function mpe({stackTitle:e,onRename:t,onEditMembers:n,onDelete:r,children:i}){return u.jsxs(bh,{children:[u.jsx(xh,{asChild:!0,children:i}),u.jsxs(Id,{children:[u.jsxs(br,{onSelect:s=>{s.preventDefault(),t()},children:[u.jsx(Rd,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"text-xs font-medium",children:"Rename"})]}),u.jsxs(br,{onSelect:s=>{s.preventDefault(),n()},children:[u.jsx(yH,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"text-xs font-medium",children:"Edit members"})]}),u.jsxs(br,{onSelect:s=>{s.preventDefault(),r()},className:"text-destructive dark:text-red-400 hover:bg-destructive/10 focus:bg-destructive/10 dark:hover:bg-red-500/20 dark:focus:bg-red-500/20",children:[u.jsx(Yc,{className:"h-3.5 w-3.5"}),u.jsxs("span",{className:"text-xs font-medium",children:["Delete ",e]})]})]})]})}function gpe(e){return e.status==="running"||e.status==="starting"?"warning":e.status==="waiting_for_user"?"info":e.status==="failed"?"destructive":e.unread?"success":null}function vpe(e){switch(e){case"warning":return"bg-warning";case"info":return"bg-info";case"success":return"bg-success";case"destructive":return"bg-destructive";default:return""}}function bpe(e){switch(e){case"warning":return"text-warning";case"info":return"text-info";case"success":return"text-success";case"destructive":return"text-destructive";default:return"text-muted-foreground"}}function xpe(e){switch(e){case"active":return{glyph:"●",tone:"text-success",title:"Claude PTY session active"};case"warming":return{glyph:"◐",tone:"text-warning",title:"Claude PTY session warming"};case"idle":return{glyph:"○",tone:"text-muted-foreground",title:"Claude PTY session idle"};case"cooling":return{glyph:"◌",tone:"text-muted-foreground",title:"Claude PTY session cooling down"};case"cold":default:return null}}function ype({chat:e,activeChatId:t,nowMs:n,shortcutHint:r=null,showShortcutHint:i=!1,onSelectChat:s,onRenameChat:o,onOpenInFinder:a,onForkChat:l,onArchiveChat:d,onDeleteChat:h,onEditPermissions:p}){const m=(e.status==="running"||e.status==="waiting_for_user")&&e.stateEnteredAt!=null,v=m&&e.stateEnteredAt!=null?`${y2(e.status)} ${x2(n-e.stateEnteredAt)}`:Go(n-(e.lastMessageAt??e._creationTime)),b=i&&r?r:v,x=i&&!!r,S=Cle(e.chatId),C=t===S,k=gpe(e);let w;e.canFork?w="w-12":m?w="w-12 md:w-20":w="w-6 md:w-14";let N=null;b&&(x?N=u.jsx("span",{className:"hidden md:flex absolute inset-0 items-center justify-end pr-0.5 text-[11px] text-foreground transition-opacity duration-150 group-hover:opacity-0",children:u.jsx(Q7,{className:"h-4 min-w-4 rounded-sm border-border/50 bg-transparent px-1 text-[10px]",children:r})}):N=u.jsx("span",{className:he("hidden md:flex absolute inset-0 items-center justify-end pr-1 text-[11px] tabular-nums transition-opacity duration-150 group-hover:opacity-0 whitespace-nowrap",m?bpe(k):"text-muted-foreground"),children:b}));const A=u.jsxs("div",{"data-chat-id":S,className:he("group flex items-center gap-2 pl-2 pr-1 py-1.5 rounded-md cursor-pointer transition-colors duration-150",C?"bg-muted":"hover:bg-muted/40"),onClick:()=>s(e.chatId),children:[u.jsx("span",{className:"relative flex h-3.5 w-3.5 shrink-0 items-center justify-center","aria-hidden":!0,children:k?u.jsx("span",{className:he("h-2 w-2 rounded-full",vpe(k))}):null}),(()=>{const T=xpe(e.sessionState);return T?u.jsx("span",{className:he("shrink-0 text-[10px] leading-none",T.tone),title:T.title,"aria-label":T.title,children:T.glyph}):null})(),e.hasPolicyOverride?u.jsx(QM,{className:"size-3 shrink-0 text-warning","aria-label":"Per-chat permission override active"}):null,u.jsx("span",{className:he("truncate flex-1 text-sm",C?"text-foreground font-medium":"text-foreground/90",e.status==="idle"&&!e.unread&&!C?"text-muted-foreground":""),children:e.title}),u.jsxs("div",{className:he("relative h-6 shrink-0",w),children:[N,u.jsxs("div",{className:he("absolute inset-0 flex items-center justify-end gap-0 transition-opacity duration-150",b?"opacity-100 md:opacity-0 md:group-hover:opacity-100":"opacity-100"),children:[e.canFork?u.jsx(Ie,{variant:"ghost",size:"icon",className:"h-6 w-6 cursor-pointer rounded-sm hover:!bg-transparent !border-0",onClick:T=>{T.stopPropagation(),l(e.chatId)},title:"Fork chat",children:u.jsx(vH,{className:"size-3.5"})}):null,u.jsx(Ie,{variant:"ghost",size:"icon",className:"h-6 w-6 cursor-pointer rounded-sm hover:!bg-transparent !border-0",onClick:T=>{T.stopPropagation(),d(e.chatId)},title:"Archive chat",children:u.jsx(KM,{className:"size-3.5"})})]})]})]},e._id);return u.jsx(fpe,{canFork:e.canFork,onRename:()=>o(e.chatId),onOpenInFinder:()=>a(e.localPath),onFork:()=>l(e.chatId),onArchive:()=>d(e.chatId),onDelete:()=>h(e.chatId),onEditPermissions:p?()=>p(e.chatId):void 0,children:A})}const _pe=_.memo(ype);function Spe(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return _.useMemo(()=>r=>{t.forEach(i=>i(r))},t)}const AC=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function Zm(e){const t=Object.prototype.toString.call(e);return t==="[object Window]"||t==="[object global]"}function Fj(e){return"nodeType"in e}function so(e){var t,n;return e?Zm(e)?e:Fj(e)&&(t=(n=e.ownerDocument)==null?void 0:n.defaultView)!=null?t:window:window}function Uj(e){const{Document:t}=so(e);return e instanceof t}function Fx(e){return Zm(e)?!1:e instanceof so(e).HTMLElement}function aW(e){return e instanceof so(e).SVGElement}function Qm(e){return e?Zm(e)?e.document:Fj(e)?Uj(e)?e:Fx(e)||aW(e)?e.ownerDocument:document:document:document}const Nl=AC?_.useLayoutEffect:_.useEffect;function Hj(e){const t=_.useRef(e);return Nl(()=>{t.current=e}),_.useCallback(function(){for(var n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];return t.current==null?void 0:t.current(...r)},[])}function wpe(){const e=_.useRef(null),t=_.useCallback((r,i)=>{e.current=setInterval(r,i)},[]),n=_.useCallback(()=>{e.current!==null&&(clearInterval(e.current),e.current=null)},[]);return[t,n]}function Nb(e,t){t===void 0&&(t=[e]);const n=_.useRef(e);return Nl(()=>{n.current!==e&&(n.current=e)},t),n}function Ux(e,t){const n=_.useRef();return _.useMemo(()=>{const r=e(n.current);return n.current=r,r},[...t])}function XS(e){const t=Hj(e),n=_.useRef(null),r=_.useCallback(i=>{i!==n.current&&(t==null||t(i,n.current)),n.current=i},[]);return[n,r]}function C2(e){const t=_.useRef();return _.useEffect(()=>{t.current=e},[e]),t.current}let lN={};function Hx(e,t){return _.useMemo(()=>{if(t)return t;const n=lN[e]==null?0:lN[e]+1;return lN[e]=n,e+"-"+n},[e,t])}function lW(e){return function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return r.reduce((s,o)=>{const a=Object.entries(o);for(const[l,d]of a){const h=s[l];h!=null&&(s[l]=h+e*d)}return s},{...t})}}const Zp=lW(1),JS=lW(-1);function Cpe(e){return"clientX"in e&&"clientY"in e}function Wj(e){if(!e)return!1;const{KeyboardEvent:t}=so(e.target);return t&&e instanceof t}function kpe(e){if(!e)return!1;const{TouchEvent:t}=so(e.target);return t&&e instanceof t}function k2(e){if(kpe(e)){if(e.touches&&e.touches.length){const{clientX:t,clientY:n}=e.touches[0];return{x:t,y:n}}else if(e.changedTouches&&e.changedTouches.length){const{clientX:t,clientY:n}=e.changedTouches[0];return{x:t,y:n}}}return Cpe(e)?{x:e.clientX,y:e.clientY}:null}const Tb=Object.freeze({Translate:{toString(e){if(!e)return;const{x:t,y:n}=e;return"translate3d("+(t?Math.round(t):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(e){if(!e)return;const{scaleX:t,scaleY:n}=e;return"scaleX("+t+") scaleY("+n+")"}},Transform:{toString(e){if(e)return[Tb.Translate.toString(e),Tb.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:t,duration:n,easing:r}=e;return t+" "+n+"ms "+r}}}),w$="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function Epe(e){return e.matches(w$)?e:e.querySelector(w$)}const Npe={display:"none"};function Tpe(e){let{id:t,value:n}=e;return $n.createElement("div",{id:t,style:Npe},n)}function Ape(e){let{id:t,announcement:n,ariaLiveType:r="assertive"}=e;const i={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return $n.createElement("div",{id:t,style:i,role:"status","aria-live":r,"aria-atomic":!0},n)}function Rpe(){const[e,t]=_.useState("");return{announce:_.useCallback(r=>{r!=null&&t(r)},[]),announcement:e}}const cW=_.createContext(null);function Mpe(e){const t=_.useContext(cW);_.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of <DndContext>");return t(e)},[e,t])}function jpe(){const[e]=_.useState(()=>new Set),t=_.useCallback(r=>(e.add(r),()=>e.delete(r)),[e]);return[_.useCallback(r=>{let{type:i,event:s}=r;e.forEach(o=>{var a;return(a=o[i])==null?void 0:a.call(o,s)})},[e]),t]}const Ipe={draggable:`
756
+ `)&&(C.writePathDeny=S),Object.keys(C).length===0?null:C}function v(){r(m())}function b(){r(null)}return u.jsxs(u.Fragment,{children:[u.jsx($a,{open:e,onOpenChange:x=>{x||i()},children:u.jsxs(ia,{className:"max-w-2xl",children:[u.jsxs(za,{children:["Permissions — ",t]}),u.jsxs(El,{className:"space-y-5",children:[u.jsxs("div",{className:"space-y-2",children:[u.jsx("div",{className:"text-sm font-medium",children:"Default action"}),u.jsxs("div",{className:"text-xs text-muted-foreground",children:["Behaviour when a tool call has no explicit allow/deny rule. ",u.jsx("strong",{children:"auto-allow"})," bypasses prompts and runs untrusted shell commands without supervision — use a worktree."]}),u.jsx(Ns,{value:s,onValueChange:p,options:[{value:"ask",label:"Ask"},{value:"auto-allow",label:"Auto-allow (unsafe)"},{value:"auto-deny",label:"Auto-deny"}]})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx("div",{className:"text-sm font-medium",children:"Read-path deny list"}),u.jsx("div",{className:"text-xs text-muted-foreground",children:"One glob per line. The model cannot read paths matching any entry. Defaults shown below — edit to add or remove."}),u.jsx("textarea",{value:o,onChange:x=>h.getState().setReadDenyText(x.target.value),rows:8,className:"w-full rounded-md border border-border bg-background px-3 py-2 font-mono text-xs",spellCheck:!1})]}),u.jsxs("div",{className:"space-y-2",children:[u.jsx("div",{className:"text-sm font-medium",children:"Write-path deny list"}),u.jsx("div",{className:"text-xs text-muted-foreground",children:"One glob per line. The model cannot edit or write paths matching any entry."}),u.jsx("textarea",{value:a,onChange:x=>h.getState().setWriteDenyText(x.target.value),rows:8,className:"w-full rounded-md border border-border bg-background px-3 py-2 font-mono text-xs",spellCheck:!1})]})]}),u.jsxs(bd,{className:"justify-between",children:[u.jsx(Ie,{variant:"ghost",onClick:b,children:"Reset to defaults"}),u.jsxs("div",{className:"flex gap-2",children:[u.jsx(Ie,{variant:"ghost",onClick:i,children:"Cancel"}),u.jsx(Ie,{onClick:v,children:"Apply"})]})]})]})}),u.jsx($a,{open:l,onOpenChange:x=>{x||(h.getState().setConfirmUnsafeOpen(!1),h.getState().setPendingDefaultAction(null))},children:u.jsxs(ia,{className:"max-w-md",children:[u.jsx(za,{children:"Enable auto-allow for this chat?"}),u.jsxs(El,{className:"space-y-3 text-sm",children:[u.jsx("p",{children:"Auto-allow disables tool-call prompts. The model can run shell commands, write files, and edit code without asking. Read/write deny lists still apply."}),u.jsx("p",{className:"text-warning",children:"Use a worktree for risky tasks."})]}),u.jsxs(bd,{className:"justify-end gap-2",children:[u.jsx(Ie,{variant:"ghost",onClick:()=>{h.getState().setConfirmUnsafeOpen(!1),h.getState().setPendingDefaultAction(null)},children:"Cancel"}),u.jsx(Ie,{variant:"destructive",onClick:()=>{const x=h.getState();d&&x.setDefaultAction(d),x.setConfirmUnsafeOpen(!1),x.setPendingDefaultAction(null)},children:"Enable auto-allow"})]})]})})]})}const Vde={defaultAction:"ask",bash:{autoAllowVerbs:["ls","pwd","git status","git diff","git log"]},readPathDeny:["~/.ssh","~/.aws","~/.gcp","~/.config/gh","~/.claude","~/.kanna","~/Library/Keychains","/etc/shadow","/etc/sudoers","~/.gnupg","~/.gitconfig","**/.git/config","~/.npmrc","~/.netrc","~/.docker/config.json","**/.env","**/.env.*","**/credentials*","**/*.pem","**/*.key","**/id_rsa*","**/id_ed25519*"],writePathDeny:["/etc/**","/usr/**","/System/**","~/.ssh/**","~/.aws/**","~/.config/gh/**","~/.claude/**","~/.kanna/**","~/.gnupg/**","~/.gitconfig","**/.git/config"],toolDenyList:[{tool:"mcp__kanna__bash",pattern:"rm\\s+-rf\\s+(/|~|\\$HOME)(?:\\b|$|\\s)"},{tool:"mcp__kanna__bash",pattern:"git\\s+push\\b.*--force"}],toolAllowList:[]},dn=_.forwardRef(({className:e,type:t,...n},r)=>u.jsx("input",{ref:r,type:t,className:he("flex w-full rounded-lg border border-border bg-background px-3 py-2 text-sm text-foreground outline-none placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50",e),...n}));dn.displayName="Input";const t9=_.createContext(null);function Kde({children:e}){const[t,n]=_.useState(null),[r,i]=_.useState(""),s=_.useRef(null);_.useEffect(()=>{(t==null?void 0:t.kind)==="prompt"&&(i(t.options.initialValue??""),setTimeout(()=>{var b,x;(b=s.current)==null||b.focus(),(x=s.current)==null||x.select()},0))},[t]);const o=_.useCallback(()=>{n(null),i("")},[]),a=_.useCallback(()=>{t&&(t.kind==="confirm"?t.resolve(!1):t.kind==="prompt"?t.resolve(null):t.resolve(),o())},[o,t]),l=_.useCallback(()=>{t&&(t.kind==="confirm"?t.resolve(!0):t.kind==="prompt"?t.resolve(r.trim()||null):t.resolve(),o())},[o,t,r]),d=_.useCallback(b=>new Promise(x=>{n({kind:"confirm",options:b,resolve:x})}),[]),h=_.useCallback(b=>new Promise(x=>{n({kind:"prompt",options:b,resolve:x})}),[]),p=_.useCallback(b=>new Promise(x=>{n({kind:"alert",options:b,resolve:x})}),[]),m=_.useMemo(()=>({confirm:d,prompt:h,alert:p}),[p,d,h]);let v="Confirm";return t&&(t.kind==="alert"?v=t.options.closeLabel??"OK":"confirmLabel"in t.options&&(v=t.options.confirmLabel??"Confirm")),u.jsxs(t9.Provider,{value:m,children:[e,u.jsx($a,{open:t!==null,onOpenChange:b=>{b||!t||a()},children:u.jsx(ia,{size:"sm",onKeyDown:b=>{b.key!=="Enter"||b.shiftKey||!t||t.kind!=="confirm"||(b.preventDefault(),l())},children:t?u.jsxs(u.Fragment,{children:[u.jsxs(El,{className:"space-y-4",children:[u.jsx(za,{children:t.options.title}),t.options.description?u.jsx(jx,{children:t.options.description}):null,t.kind==="prompt"?u.jsx(dn,{ref:s,type:"text",value:r,onChange:b=>i(b.target.value),onKeyDown:b=>{b.key==="Enter"&&(b.preventDefault(),l())},placeholder:t.options.placeholder}):null]}),u.jsxs(bd,{children:[u.jsx(Ie,{variant:"ghost",size:"sm",onClick:a,className:t.kind==="alert"?"hidden":void 0,children:"cancelLabel"in t.options?t.options.cancelLabel??"Cancel":"Cancel"}),u.jsx(Ie,{variant:t.kind==="confirm"?t.options.confirmVariant??"default":"secondary",size:"sm",onClick:l,disabled:t.kind==="prompt"&&!r.trim(),children:v})]})]}):null})})]})}function Ox(){const e=_.useContext(t9);if(!e)throw new Error("useAppDialog must be used within AppDialogProvider");return e}const Cj=_.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:he("bg-card text-card-foreground",e),...t}));Cj.displayName="Card";const kj=_.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:he("flex flex-col space-y-1.5 p-2",e),...t}));kj.displayName="CardHeader";const n9=_.forwardRef(({className:e,...t},n)=>u.jsx("h3",{ref:n,className:he("text-2xl font-semibold leading-none tracking-tight",e),...t}));n9.displayName="CardTitle";const r9=_.forwardRef(({className:e,...t},n)=>u.jsx("p",{ref:n,className:he("text-sm text-muted-foreground",e),...t}));r9.displayName="CardDescription";const Ej=_.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:he("p-6 pt-0",e),...t}));Ej.displayName="CardContent";const Gde=_.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:he("flex items-center p-6 pt-0",e),...t}));Gde.displayName="CardFooter";const qde={info:{dotVar:"var(--info)",bgClass:"bg-info/[0.06]"},warning:{dotVar:"var(--warning)",bgClass:"bg-warning/[0.06]"},success:{dotVar:"var(--success)",bgClass:"bg-success/[0.06]"},error:{dotVar:"var(--destructive)",bgClass:"bg-destructive/[0.06]"}};function Yde({variant:e,children:t,dot:n=!0,className:r}){const i=qde[e];return u.jsxs("div",{role:"status",className:he("flex flex-wrap items-center justify-center gap-x-2 gap-y-1 border-b border-border px-4 py-2 text-xs leading-tight",i.bgClass,r),children:[n?u.jsx("span",{"aria-hidden":"true",className:"inline-block size-1.5 shrink-0 rounded-full",style:{backgroundColor:i.dotVar}}):null,t]})}const Xde="modulepreload",Jde=function(e){return"/"+e},v$={},J=function(t,n,r){let i=Promise.resolve();if(n&&n.length>0){let o=function(d){return Promise.all(d.map(h=>Promise.resolve(h).then(p=>({status:"fulfilled",value:p}),p=>({status:"rejected",reason:p}))))};document.getElementsByTagName("link");const a=document.querySelector("meta[property=csp-nonce]"),l=(a==null?void 0:a.nonce)||(a==null?void 0:a.getAttribute("nonce"));i=o(n.map(d=>{if(d=Jde(d),d in v$)return;v$[d]=!0;const h=d.endsWith(".css"),p=h?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${p}`))return;const m=document.createElement("link");if(m.rel=h?"stylesheet":Xde,h||(m.as="script"),m.crossOrigin="",m.href=d,l&&m.setAttribute("nonce",l),document.head.appendChild(m),h)return new Promise((v,b)=>{m.addEventListener("load",v),m.addEventListener("error",()=>b(new Error(`Unable to preload CSS for ${d}`)))})}))}function s(o){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=o,window.dispatchEvent(a),!a.defaultPrevented)throw o}return i.then(o=>{for(const a of o||[])a.status==="rejected"&&s(a.reason);return t().catch(s)})},Zde=_.lazy(()=>J(()=>import("./index-DxYefG8F.js"),[]).then(e=>({default:e.Toaster})));function Qde(){return u.jsx(_.Suspense,{fallback:null,children:u.jsx(Zde,{position:"bottom-right",theme:"system",closeButton:!0,duration:6e3})})}const efe="1.1.3",tfe={version:efe},$r="Kanna",b$="kanna",nfe=".kanna",rfe=".kanna-dev",ife="KANNA_RUNTIME_PROFILE",Nj=`kanna/${tfe.version}`,sfe="[kanna]",ofe=`~/${$r}`;function kC(){const e=Reflect.get(globalThis,"process");return e==null?void 0:e.env}function afe(e=kC()){var t;return((t=e==null?void 0:e[ife])==null?void 0:t.trim().toLowerCase())==="dev"?"dev":"prod"}function lfe(e=kC()){return afe(e)==="dev"?rfe:nfe}function cfe(e=kC()){return`~/${lfe(e)}`}function ufe(e=kC()){return`${cfe(e)}/keybindings.json`}function $_(e){return e?`${b$} ${e}`:b$}const i9="always",s9="funk",dfe=[{value:"blow",label:"Blow"},{value:"bottle",label:"Bottle"},{value:"frog",label:"Frog"},{value:"funk",label:"Funk"},{value:"glass",label:"Glass"},{value:"ping",label:"Ping"},{value:"pop",label:"Pop"},{value:"purr",label:"Purr"},{value:"tink",label:"Tink"}];function ffe(e){switch(e){case"never":case"unfocused":case"always":return e;default:return i9}}function hfe(e){switch(e){case"blow":case"bottle":case"frog":case"funk":case"glass":case"ping":case"pop":case"purr":case"tink":return e;default:return s9}}const Af=dr()(e=>({chatSoundPreference:i9,chatSoundId:s9,setChatSoundPreference:t=>e({chatSoundPreference:ffe(t)}),setChatSoundId:t=>e({chatSoundId:hfe(t)})})),pfe={blow:"/chat-sounds/Blow.mp3",bottle:"/chat-sounds/Bottle.mp3",frog:"/chat-sounds/Frog.mp3",funk:"/chat-sounds/Funk.mp3",glass:"/chat-sounds/Glass.mp3",ping:"/chat-sounds/Ping.mp3",pop:"/chat-sounds/Pop.mp3",purr:"/chat-sounds/Purr.mp3",tink:"/chat-sounds/Tink.mp3"};function mfe(e=document){return e.visibilityState!=="visible"||!e.hasFocus()}function gfe(e){const t=new Audio(pfe[e]);return t.preload="auto",t.play()}async function v2(e,t){if(t<=0)return;const n=Array.from({length:t},(r,i)=>new Promise(s=>{window.setTimeout(()=>{gfe(e).catch(()=>{}).finally(()=>s())},i*90)}));await Promise.all(n)}function vfe(e,t=document){return e==="never"?!1:e==="always"?!0:mfe(t)}function bfe(e){return e.projectGroups.reduce((t,n)=>t+n.chats.reduce((r,i)=>r+(i.unread?1:0)+(i.status==="waiting_for_user"?1:0),0),0)}function x$(e){let t=0;const n=new Set;for(const r of e.projectGroups)for(const i of r.chats)i.unread&&(t+=1),i.status==="waiting_for_user"&&n.add(i.chatId);return{unreadCount:t,waitingChatIds:n}}function xfe(e,t){if(!e)return 0;const n=x$(e),r=x$(t),i=Math.max(0,r.unreadCount-n.unreadCount);let s=0;for(const o of r.waitingChatIds)n.waitingChatIds.has(o)||(s+=1);return i+s}function b2(e){return e.split(/[\s_-]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" ")}const yfe=[/^(?:\/usr\/bin\/env\s+)?(?:\/bin\/)?(?:bash|zsh|sh)\s+(?:-[a-zA-Z]*c|-c)\s+(['"])([\s\S]*)\1$/,/^(?:\/usr\/bin\/env\s+)?(?:\/bin\/)?(?:bash|zsh|sh)\s+(?:-[a-zA-Z]*c|-c)\s+(.+)$/,/^(?:\/usr\/bin\/env\s+)?(?:cmd(?:\.exe)?)\s+\/c\s+(['"])([\s\S]*)\1$/i,/^(?:\/usr\/bin\/env\s+)?(?:cmd(?:\.exe)?)\s+\/c\s+(.+)$/i,/^(?:\/usr\/bin\/env\s+)?(?:powershell(?:\.exe)?|pwsh)\s+(?:-NoProfile\s+)?-Command\s+(['"])([\s\S]*)\1$/i,/^(?:\/usr\/bin\/env\s+)?(?:powershell(?:\.exe)?|pwsh)\s+(?:-NoProfile\s+)?-Command\s+(.+)$/i];function o9(e){const t=e.trim();for(const n of yfe){const r=t.match(n);if(!r)continue;const i=(r[2]??r[1]??"").trim();if(i)return i}return t}function Tj(e){return e.split("/").pop()||e}const _fe=1440*6e4;function Sfe(e,t){if(e===void 0)return null;const n=Math.max(0,t-e),r=6e4,i=60*r,s=_fe,o=7*s;return n<r?"now":n<i?`${Math.floor(n/r)}m`:n<s?`${Math.floor(n/i)}h`:n<o?`${Math.floor(n/s)}d`:`${Math.floor(n/o)}w`}function wfe(e){return e.lastMessageAt??e._creationTime}const Aj=1e3,Z0=60*Aj,$p=60*Z0,oN=24*$p;function Go(e){const t=Math.max(0,e);if(t<Z0)return`${Math.floor(t/Aj)}s`;if(t<$p)return`${Math.floor(t/Z0)}m`;if(t<oN){const i=Math.floor(t/$p),s=Math.floor(t%$p/Z0);return s===0?`${i}h`:`${i}h ${s}m`}const n=Math.floor(t/oN),r=Math.floor(t%oN/$p);return r===0?`${n}d`:`${n}d ${r}h`}function x2(e){const t=Math.max(0,e);if(t>=$p)return Go(t);const n=Math.floor(t/Aj),r=Math.floor(n/60),i=n%60;return`${r}:${i.toString().padStart(2,"0")}`}function y2(e){switch(e){case"idle":return"Idle";case"starting":return"Starting";case"running":return"Running";case"waiting_for_user":return"Waiting";case"failed":return"Failed"}}function y$(e){switch(e){case"running":return"active";case"waiting_for_user":return"attention";case"failed":return"destructive";case"idle":case"starting":default:return"muted"}}function _$(e){switch(e){case"active":return"text-emerald-500 dark:text-emerald-400";case"attention":return"text-amber-500 dark:text-amber-400";case"destructive":return"text-destructive";case"muted":default:return"text-muted-foreground"}}function Rj(e){const t=e+"CollectionProvider",[n,r]=Xc(t),[i,s]=n(t,{collectionRef:{current:null},itemMap:new Map}),o=x=>{const{scope:S,children:C}=x,k=$n.useRef(null),w=$n.useRef(new Map).current;return u.jsx(i,{scope:S,itemMap:w,collectionRef:k,children:C})};o.displayName=t;const a=e+"CollectionSlot",l=Gf(a),d=$n.forwardRef((x,S)=>{const{scope:C,children:k}=x,w=s(a,C),N=Kn(S,w.collectionRef);return u.jsx(l,{ref:N,children:k})});d.displayName=a;const h=e+"CollectionItemSlot",p="data-radix-collection-item",m=Gf(h),v=$n.forwardRef((x,S)=>{const{scope:C,children:k,...w}=x,N=$n.useRef(null),A=Kn(S,N),T=s(h,C);return $n.useEffect(()=>(T.itemMap.set(N,{ref:N,...w}),()=>void T.itemMap.delete(N))),u.jsx(m,{[p]:"",ref:A,children:k})});v.displayName=h;function b(x){const S=s(e+"CollectionConsumer",x);return $n.useCallback(()=>{const k=S.collectionRef.current;if(!k)return[];const w=Array.from(k.querySelectorAll(`[${p}]`));return Array.from(S.itemMap.values()).sort((T,M)=>w.indexOf(T.ref.current)-w.indexOf(M.ref.current))},[S.collectionRef,S.itemMap])}return[{Provider:o,Slot:d,ItemSlot:v},b,r]}var Cfe=_.createContext(void 0);function Mj(e){const t=_.useContext(Cfe);return e||t||"ltr"}var aN="rovingFocusGroup.onEntryFocus",kfe={bubbles:!1,cancelable:!0},Dx="RovingFocusGroup",[_2,a9,Efe]=Rj(Dx),[Nfe,l9]=Xc(Dx,[Efe]),[Tfe,Afe]=Nfe(Dx),c9=_.forwardRef((e,t)=>u.jsx(_2.Provider,{scope:e.__scopeRovingFocusGroup,children:u.jsx(_2.Slot,{scope:e.__scopeRovingFocusGroup,children:u.jsx(Rfe,{...e,ref:t})})}));c9.displayName=Dx;var Rfe=_.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:i=!1,dir:s,currentTabStopId:o,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:l,onEntryFocus:d,preventScrollOnEntryFocus:h=!1,...p}=e,m=_.useRef(null),v=Kn(t,m),b=Mj(s),[x,S]=vm({prop:o,defaultProp:a??null,onChange:l,caller:Dx}),[C,k]=_.useState(!1),w=Da(d),N=a9(n),A=_.useRef(!1),[T,M]=_.useState(0);return _.useEffect(()=>{const j=m.current;if(j)return j.addEventListener(aN,w),()=>j.removeEventListener(aN,w)},[w]),u.jsx(Tfe,{scope:n,orientation:r,dir:b,loop:i,currentTabStopId:x,onItemFocus:_.useCallback(j=>S(j),[S]),onItemShiftTab:_.useCallback(()=>k(!0),[]),onFocusableItemAdd:_.useCallback(()=>M(j=>j+1),[]),onFocusableItemRemove:_.useCallback(()=>M(j=>j-1),[]),children:u.jsx(yn.div,{tabIndex:C||T===0?-1:0,"data-orientation":r,...p,ref:v,style:{outline:"none",...e.style},onMouseDown:st(e.onMouseDown,()=>{A.current=!0}),onFocus:st(e.onFocus,j=>{const P=!A.current;if(j.target===j.currentTarget&&P&&!C){const D=new CustomEvent(aN,kfe);if(j.currentTarget.dispatchEvent(D),!D.defaultPrevented){const L=N().filter(F=>F.focusable),I=L.find(F=>F.active),$=L.find(F=>F.id===x),z=[I,$,...L].filter(Boolean).map(F=>F.ref.current);f9(z,h)}}A.current=!1}),onBlur:st(e.onBlur,()=>k(!1))})})}),u9="RovingFocusGroupItem",d9=_.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:i=!1,tabStopId:s,children:o,...a}=e,l=Tc(),d=s||l,h=Afe(u9,n),p=h.currentTabStopId===d,m=a9(n),{onFocusableItemAdd:v,onFocusableItemRemove:b,currentTabStopId:x}=h;return _.useEffect(()=>{if(r)return v(),()=>b()},[r,v,b]),u.jsx(_2.ItemSlot,{scope:n,id:d,focusable:r,active:i,children:u.jsx(yn.span,{tabIndex:p?0:-1,"data-orientation":h.orientation,...a,ref:t,onMouseDown:st(e.onMouseDown,S=>{r?h.onItemFocus(d):S.preventDefault()}),onFocus:st(e.onFocus,()=>h.onItemFocus(d)),onKeyDown:st(e.onKeyDown,S=>{if(S.key==="Tab"&&S.shiftKey){h.onItemShiftTab();return}if(S.target!==S.currentTarget)return;const C=Ife(S,h.orientation,h.dir);if(C!==void 0){if(S.metaKey||S.ctrlKey||S.altKey||S.shiftKey)return;S.preventDefault();let w=m().filter(N=>N.focusable).map(N=>N.ref.current);if(C==="last")w.reverse();else if(C==="prev"||C==="next"){C==="prev"&&w.reverse();const N=w.indexOf(S.currentTarget);w=h.loop?Pfe(w,N+1):w.slice(N+1)}setTimeout(()=>f9(w))}}),children:typeof o=="function"?o({isCurrentTabStop:p,hasTabStop:x!=null}):o})})});d9.displayName=u9;var Mfe={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function jfe(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function Ife(e,t,n){const r=jfe(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return Mfe[r]}function f9(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function Pfe(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var Lfe=c9,Ofe=d9,S2=["Enter"," "],Dfe=["ArrowDown","PageUp","Home"],h9=["ArrowUp","PageDown","End"],$fe=[...Dfe,...h9],zfe={ltr:[...S2,"ArrowRight"],rtl:[...S2,"ArrowLeft"]},Bfe={ltr:["ArrowLeft"],rtl:["ArrowRight"]},$x="Menu",[kb,Ffe,Ufe]=Rj($x),[gh,p9]=Xc($x,[Ufe,jd,l9]),EC=jd(),m9=l9(),[Hfe,vh]=gh($x),[Wfe,zx]=gh($x),g9=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:i,onOpenChange:s,modal:o=!0}=e,a=EC(t),[l,d]=_.useState(null),h=_.useRef(!1),p=Da(s),m=Mj(i);return _.useEffect(()=>{const v=()=>{h.current=!0,document.addEventListener("pointerdown",b,{capture:!0,once:!0}),document.addEventListener("pointermove",b,{capture:!0,once:!0})},b=()=>h.current=!1;return document.addEventListener("keydown",v,{capture:!0}),()=>{document.removeEventListener("keydown",v,{capture:!0}),document.removeEventListener("pointerdown",b,{capture:!0}),document.removeEventListener("pointermove",b,{capture:!0})}},[]),u.jsx(yC,{...a,children:u.jsx(Hfe,{scope:t,open:n,onOpenChange:p,content:l,onContentChange:d,children:u.jsx(Wfe,{scope:t,onClose:_.useCallback(()=>p(!1),[p]),isUsingKeyboardRef:h,dir:m,modal:o,children:r})})})};g9.displayName=$x;var Vfe="MenuAnchor",jj=_.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=EC(n);return u.jsx(Px,{...i,...r,ref:t})});jj.displayName=Vfe;var Ij="MenuPortal",[Kfe,v9]=gh(Ij,{forceMount:void 0}),b9=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:i}=e,s=vh(Ij,t);return u.jsx(Kfe,{scope:t,forceMount:n,children:u.jsx(fa,{present:n||s.open,children:u.jsx(Ym,{asChild:!0,container:i,children:r})})})};b9.displayName=Ij;var ea="MenuContent",[Gfe,Pj]=gh(ea),x9=_.forwardRef((e,t)=>{const n=v9(ea,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,s=vh(ea,e.__scopeMenu),o=zx(ea,e.__scopeMenu);return u.jsx(kb.Provider,{scope:e.__scopeMenu,children:u.jsx(fa,{present:r||s.open,children:u.jsx(kb.Slot,{scope:e.__scopeMenu,children:o.modal?u.jsx(qfe,{...i,ref:t}):u.jsx(Yfe,{...i,ref:t})})})})}),qfe=_.forwardRef((e,t)=>{const n=vh(ea,e.__scopeMenu),r=_.useRef(null),i=Kn(t,r);return _.useEffect(()=>{const s=r.current;if(s)return pC(s)},[]),u.jsx(Lj,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:st(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),Yfe=_.forwardRef((e,t)=>{const n=vh(ea,e.__scopeMenu);return u.jsx(Lj,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),Xfe=Gf("MenuContent.ScrollLock"),Lj=_.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:i,onOpenAutoFocus:s,onCloseAutoFocus:o,disableOutsidePointerEvents:a,onEntryFocus:l,onEscapeKeyDown:d,onPointerDownOutside:h,onFocusOutside:p,onInteractOutside:m,onDismiss:v,disableOutsideScroll:b,...x}=e,S=vh(ea,n),C=zx(ea,n),k=EC(n),w=m9(n),N=Ffe(n),[A,T]=_.useState(null),M=_.useRef(null),j=Kn(t,M,S.onContentChange),P=_.useRef(0),D=_.useRef(""),L=_.useRef(0),I=_.useRef(null),$=_.useRef("right"),H=_.useRef(0),z=b?Mx:_.Fragment,F=b?{as:Xfe,allowPinchZoom:!0}:void 0,K=V=>{var ne,ie;const X=D.current+V,G=N().filter(ae=>!ae.disabled),te=document.activeElement,oe=(ne=G.find(ae=>ae.ref.current===te))==null?void 0:ne.textValue,ue=G.map(ae=>ae.textValue),de=lhe(ue,X,oe),ee=(ie=G.find(ae=>ae.textValue===de))==null?void 0:ie.ref.current;(function ae(Q){D.current=Q,window.clearTimeout(P.current),Q!==""&&(P.current=window.setTimeout(()=>ae(""),1e3))})(X),ee&&setTimeout(()=>ee.focus())};_.useEffect(()=>()=>window.clearTimeout(P.current),[]),fC();const W=_.useCallback(V=>{var G,te;return $.current===((G=I.current)==null?void 0:G.side)&&uhe(V,(te=I.current)==null?void 0:te.area)},[]);return u.jsx(Gfe,{scope:n,searchRef:D,onItemEnter:_.useCallback(V=>{W(V)&&V.preventDefault()},[W]),onItemLeave:_.useCallback(V=>{var X;W(V)||((X=M.current)==null||X.focus(),T(null))},[W]),onTriggerLeave:_.useCallback(V=>{W(V)&&V.preventDefault()},[W]),pointerGraceTimerRef:L,onPointerGraceIntentChange:_.useCallback(V=>{I.current=V},[]),children:u.jsx(z,{...F,children:u.jsx(Rx,{asChild:!0,trapped:i,onMountAutoFocus:st(s,V=>{var X;V.preventDefault(),(X=M.current)==null||X.focus({preventScroll:!0})}),onUnmountAutoFocus:o,children:u.jsx(qm,{asChild:!0,disableOutsidePointerEvents:a,onEscapeKeyDown:d,onPointerDownOutside:h,onFocusOutside:p,onInteractOutside:m,onDismiss:v,children:u.jsx(Lfe,{asChild:!0,...w,dir:C.dir,orientation:"vertical",loop:r,currentTabStopId:A,onCurrentTabStopIdChange:T,onEntryFocus:st(l,V=>{C.isUsingKeyboardRef.current||V.preventDefault()}),preventScrollOnEntryFocus:!0,children:u.jsx(_C,{role:"menu","aria-orientation":"vertical","data-state":L9(S.open),"data-radix-menu-content":"",dir:C.dir,...k,...x,ref:j,style:{outline:"none",...x.style},onKeyDown:st(x.onKeyDown,V=>{const G=V.target.closest("[data-radix-menu-content]")===V.currentTarget,te=V.ctrlKey||V.altKey||V.metaKey,oe=V.key.length===1;G&&(V.key==="Tab"&&V.preventDefault(),!te&&oe&&K(V.key));const ue=M.current;if(V.target!==ue||!$fe.includes(V.key))return;V.preventDefault();const ee=N().filter(ne=>!ne.disabled).map(ne=>ne.ref.current);h9.includes(V.key)&&ee.reverse(),ohe(ee)}),onBlur:st(e.onBlur,V=>{V.currentTarget.contains(V.target)||(window.clearTimeout(P.current),D.current="")}),onPointerMove:st(e.onPointerMove,Eb(V=>{const X=V.target,G=H.current!==V.clientX;if(V.currentTarget.contains(X)&&G){const te=V.clientX>H.current?"right":"left";$.current=te,H.current=V.clientX}}))})})})})})})});x9.displayName=ea;var Jfe="MenuGroup",Oj=_.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return u.jsx(yn.div,{role:"group",...r,ref:t})});Oj.displayName=Jfe;var Zfe="MenuLabel",y9=_.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return u.jsx(yn.div,{...r,ref:t})});y9.displayName=Zfe;var qS="MenuItem",S$="menu.itemSelect",NC=_.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...i}=e,s=_.useRef(null),o=zx(qS,e.__scopeMenu),a=Pj(qS,e.__scopeMenu),l=Kn(t,s),d=_.useRef(!1),h=()=>{const p=s.current;if(!n&&p){const m=new CustomEvent(S$,{bubbles:!0,cancelable:!0});p.addEventListener(S$,v=>r==null?void 0:r(v),{once:!0}),$H(p,m),m.defaultPrevented?d.current=!1:o.onClose()}};return u.jsx(_9,{...i,ref:l,disabled:n,onClick:st(e.onClick,h),onPointerDown:p=>{var m;(m=e.onPointerDown)==null||m.call(e,p),d.current=!0},onPointerUp:st(e.onPointerUp,p=>{var m;d.current||(m=p.currentTarget)==null||m.click()}),onKeyDown:st(e.onKeyDown,p=>{const m=a.searchRef.current!=="";n||m&&p.key===" "||S2.includes(p.key)&&(p.currentTarget.click(),p.preventDefault())})})});NC.displayName=qS;var _9=_.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:i,...s}=e,o=Pj(qS,n),a=m9(n),l=_.useRef(null),d=Kn(t,l),[h,p]=_.useState(!1),[m,v]=_.useState("");return _.useEffect(()=>{const b=l.current;b&&v((b.textContent??"").trim())},[s.children]),u.jsx(kb.ItemSlot,{scope:n,disabled:r,textValue:i??m,children:u.jsx(Ofe,{asChild:!0,...a,focusable:!r,children:u.jsx(yn.div,{role:"menuitem","data-highlighted":h?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...s,ref:d,onPointerMove:st(e.onPointerMove,Eb(b=>{r?o.onItemLeave(b):(o.onItemEnter(b),b.defaultPrevented||b.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:st(e.onPointerLeave,Eb(b=>o.onItemLeave(b))),onFocus:st(e.onFocus,()=>p(!0)),onBlur:st(e.onBlur,()=>p(!1))})})})}),Qfe="MenuCheckboxItem",S9=_.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...i}=e;return u.jsx(N9,{scope:e.__scopeMenu,checked:n,children:u.jsx(NC,{role:"menuitemcheckbox","aria-checked":YS(n)?"mixed":n,...i,ref:t,"data-state":$j(n),onSelect:st(i.onSelect,()=>r==null?void 0:r(YS(n)?!0:!n),{checkForDefaultPrevented:!1})})})});S9.displayName=Qfe;var w9="MenuRadioGroup",[ehe,the]=gh(w9,{value:void 0,onValueChange:()=>{}}),C9=_.forwardRef((e,t)=>{const{value:n,onValueChange:r,...i}=e,s=Da(r);return u.jsx(ehe,{scope:e.__scopeMenu,value:n,onValueChange:s,children:u.jsx(Oj,{...i,ref:t})})});C9.displayName=w9;var k9="MenuRadioItem",E9=_.forwardRef((e,t)=>{const{value:n,...r}=e,i=the(k9,e.__scopeMenu),s=n===i.value;return u.jsx(N9,{scope:e.__scopeMenu,checked:s,children:u.jsx(NC,{role:"menuitemradio","aria-checked":s,...r,ref:t,"data-state":$j(s),onSelect:st(r.onSelect,()=>{var o;return(o=i.onValueChange)==null?void 0:o.call(i,n)},{checkForDefaultPrevented:!1})})})});E9.displayName=k9;var Dj="MenuItemIndicator",[N9,nhe]=gh(Dj,{checked:!1}),T9=_.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...i}=e,s=nhe(Dj,n);return u.jsx(fa,{present:r||YS(s.checked)||s.checked===!0,children:u.jsx(yn.span,{...i,ref:t,"data-state":$j(s.checked)})})});T9.displayName=Dj;var rhe="MenuSeparator",A9=_.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return u.jsx(yn.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});A9.displayName=rhe;var ihe="MenuArrow",R9=_.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=EC(n);return u.jsx(SC,{...i,...r,ref:t})});R9.displayName=ihe;var she="MenuSub",[s8e,M9]=gh(she),Tv="MenuSubTrigger",j9=_.forwardRef((e,t)=>{const n=vh(Tv,e.__scopeMenu),r=zx(Tv,e.__scopeMenu),i=M9(Tv,e.__scopeMenu),s=Pj(Tv,e.__scopeMenu),o=_.useRef(null),{pointerGraceTimerRef:a,onPointerGraceIntentChange:l}=s,d={__scopeMenu:e.__scopeMenu},h=_.useCallback(()=>{o.current&&window.clearTimeout(o.current),o.current=null},[]);return _.useEffect(()=>h,[h]),_.useEffect(()=>{const p=a.current;return()=>{window.clearTimeout(p),l(null)}},[a,l]),u.jsx(jj,{asChild:!0,...d,children:u.jsx(_9,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":i.contentId,"data-state":L9(n.open),...e,ref:sj(t,i.onTriggerChange),onClick:p=>{var m;(m=e.onClick)==null||m.call(e,p),!(e.disabled||p.defaultPrevented)&&(p.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:st(e.onPointerMove,Eb(p=>{s.onItemEnter(p),!p.defaultPrevented&&!e.disabled&&!n.open&&!o.current&&(s.onPointerGraceIntentChange(null),o.current=window.setTimeout(()=>{n.onOpenChange(!0),h()},100))})),onPointerLeave:st(e.onPointerLeave,Eb(p=>{var v,b;h();const m=(v=n.content)==null?void 0:v.getBoundingClientRect();if(m){const x=(b=n.content)==null?void 0:b.dataset.side,S=x==="right",C=S?-5:5,k=m[S?"left":"right"],w=m[S?"right":"left"];s.onPointerGraceIntentChange({area:[{x:p.clientX+C,y:p.clientY},{x:k,y:m.top},{x:w,y:m.top},{x:w,y:m.bottom},{x:k,y:m.bottom}],side:x}),window.clearTimeout(a.current),a.current=window.setTimeout(()=>s.onPointerGraceIntentChange(null),300)}else{if(s.onTriggerLeave(p),p.defaultPrevented)return;s.onPointerGraceIntentChange(null)}})),onKeyDown:st(e.onKeyDown,p=>{var v;const m=s.searchRef.current!=="";e.disabled||m&&p.key===" "||zfe[r.dir].includes(p.key)&&(n.onOpenChange(!0),(v=n.content)==null||v.focus(),p.preventDefault())})})})});j9.displayName=Tv;var I9="MenuSubContent",P9=_.forwardRef((e,t)=>{const n=v9(ea,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,s=vh(ea,e.__scopeMenu),o=zx(ea,e.__scopeMenu),a=M9(I9,e.__scopeMenu),l=_.useRef(null),d=Kn(t,l);return u.jsx(kb.Provider,{scope:e.__scopeMenu,children:u.jsx(fa,{present:r||s.open,children:u.jsx(kb.Slot,{scope:e.__scopeMenu,children:u.jsx(Lj,{id:a.contentId,"aria-labelledby":a.triggerId,...i,ref:d,align:"start",side:o.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:h=>{var p;o.isUsingKeyboardRef.current&&((p=l.current)==null||p.focus()),h.preventDefault()},onCloseAutoFocus:h=>h.preventDefault(),onFocusOutside:st(e.onFocusOutside,h=>{h.target!==a.trigger&&s.onOpenChange(!1)}),onEscapeKeyDown:st(e.onEscapeKeyDown,h=>{o.onClose(),h.preventDefault()}),onKeyDown:st(e.onKeyDown,h=>{var v;const p=h.currentTarget.contains(h.target),m=Bfe[o.dir].includes(h.key);p&&m&&(s.onOpenChange(!1),(v=a.trigger)==null||v.focus(),h.preventDefault())})})})})})});P9.displayName=I9;function L9(e){return e?"open":"closed"}function YS(e){return e==="indeterminate"}function $j(e){return YS(e)?"indeterminate":e?"checked":"unchecked"}function ohe(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function ahe(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function lhe(e,t,n){const i=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,s=n?e.indexOf(n):-1;let o=ahe(e,Math.max(s,0));i.length===1&&(o=o.filter(d=>d!==n));const l=o.find(d=>d.toLowerCase().startsWith(i.toLowerCase()));return l!==n?l:void 0}function che(e,t){const{x:n,y:r}=e;let i=!1;for(let s=0,o=t.length-1;s<t.length;o=s++){const a=t[s],l=t[o],d=a.x,h=a.y,p=l.x,m=l.y;h>r!=m>r&&n<(p-d)*(r-h)/(m-h)+d&&(i=!i)}return i}function uhe(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return che(n,t)}function Eb(e){return t=>t.pointerType==="mouse"?e(t):void 0}var dhe=g9,fhe=jj,hhe=b9,phe=x9,mhe=Oj,ghe=y9,vhe=NC,bhe=S9,xhe=C9,yhe=E9,_he=T9,She=A9,whe=R9,Che=j9,khe=P9,zj="ContextMenu",[Ehe]=Xc(zj,[p9]),Ps=p9(),[Nhe,O9]=Ehe(zj),D9=e=>{const{__scopeContextMenu:t,children:n,onOpenChange:r,dir:i,modal:s=!0}=e,[o,a]=_.useState(!1),l=Ps(t),d=Da(r),h=_.useCallback(p=>{a(p),d(p)},[d]);return u.jsx(Nhe,{scope:t,open:o,onOpenChange:h,modal:s,children:u.jsx(dhe,{...l,dir:i,open:o,onOpenChange:h,modal:s,children:n})})};D9.displayName=zj;var $9="ContextMenuTrigger",z9=_.forwardRef((e,t)=>{const{__scopeContextMenu:n,disabled:r=!1,...i}=e,s=O9($9,n),o=Ps(n),a=_.useRef({x:0,y:0}),l=_.useRef({getBoundingClientRect:()=>DOMRect.fromRect({width:0,height:0,...a.current})}),d=_.useRef(0),h=_.useCallback(()=>window.clearTimeout(d.current),[]),p=m=>{a.current={x:m.clientX,y:m.clientY},s.onOpenChange(!0)};return _.useEffect(()=>h,[h]),_.useEffect(()=>void(r&&h()),[r,h]),u.jsxs(u.Fragment,{children:[u.jsx(fhe,{...o,virtualRef:l}),u.jsx(yn.span,{"data-state":s.open?"open":"closed","data-disabled":r?"":void 0,...i,ref:t,style:{WebkitTouchCallout:"none",...e.style},onContextMenu:r?e.onContextMenu:st(e.onContextMenu,m=>{h(),p(m),m.preventDefault()}),onPointerDown:r?e.onPointerDown:st(e.onPointerDown,z_(m=>{h(),d.current=window.setTimeout(()=>p(m),700)})),onPointerMove:r?e.onPointerMove:st(e.onPointerMove,z_(h)),onPointerCancel:r?e.onPointerCancel:st(e.onPointerCancel,z_(h)),onPointerUp:r?e.onPointerUp:st(e.onPointerUp,z_(h))})]})});z9.displayName=$9;var The="ContextMenuPortal",B9=e=>{const{__scopeContextMenu:t,...n}=e,r=Ps(t);return u.jsx(hhe,{...r,...n})};B9.displayName=The;var F9="ContextMenuContent",U9=_.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=O9(F9,n),s=Ps(n),o=_.useRef(!1);return u.jsx(phe,{...s,...r,ref:t,side:"right",sideOffset:2,align:"start",onCloseAutoFocus:a=>{var l;(l=e.onCloseAutoFocus)==null||l.call(e,a),!a.defaultPrevented&&o.current&&a.preventDefault(),o.current=!1},onInteractOutside:a=>{var l;(l=e.onInteractOutside)==null||l.call(e,a),!a.defaultPrevented&&!i.modal&&(o.current=!0)},style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});U9.displayName=F9;var Ahe="ContextMenuGroup",Rhe=_.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Ps(n);return u.jsx(mhe,{...i,...r,ref:t})});Rhe.displayName=Ahe;var Mhe="ContextMenuLabel",jhe=_.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Ps(n);return u.jsx(ghe,{...i,...r,ref:t})});jhe.displayName=Mhe;var Ihe="ContextMenuItem",H9=_.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Ps(n);return u.jsx(vhe,{...i,...r,ref:t})});H9.displayName=Ihe;var Phe="ContextMenuCheckboxItem",Lhe=_.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Ps(n);return u.jsx(bhe,{...i,...r,ref:t})});Lhe.displayName=Phe;var Ohe="ContextMenuRadioGroup",Dhe=_.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Ps(n);return u.jsx(xhe,{...i,...r,ref:t})});Dhe.displayName=Ohe;var $he="ContextMenuRadioItem",zhe=_.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Ps(n);return u.jsx(yhe,{...i,...r,ref:t})});zhe.displayName=$he;var Bhe="ContextMenuItemIndicator",Fhe=_.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Ps(n);return u.jsx(_he,{...i,...r,ref:t})});Fhe.displayName=Bhe;var Uhe="ContextMenuSeparator",W9=_.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Ps(n);return u.jsx(She,{...i,...r,ref:t})});W9.displayName=Uhe;var Hhe="ContextMenuArrow",Whe=_.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Ps(n);return u.jsx(whe,{...i,...r,ref:t})});Whe.displayName=Hhe;var Vhe="ContextMenuSubTrigger",Khe=_.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Ps(n);return u.jsx(Che,{...i,...r,ref:t})});Khe.displayName=Vhe;var Ghe="ContextMenuSubContent",qhe=_.forwardRef((e,t)=>{const{__scopeContextMenu:n,...r}=e,i=Ps(n);return u.jsx(khe,{...i,...r,ref:t,style:{...e.style,"--radix-context-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-context-menu-content-available-width":"var(--radix-popper-available-width)","--radix-context-menu-content-available-height":"var(--radix-popper-available-height)","--radix-context-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-context-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});qhe.displayName=Ghe;function z_(e){return t=>t.pointerType!=="mouse"?e(t):void 0}var Yhe=D9,Xhe=z9,Jhe=B9,V9=U9,K9=H9,G9=W9;const q9=_.createContext(null);function bh({onOpenChange:e,...t}){const[n,r]=_.useState(0),i=_.useCallback(()=>{r(s=>s+1),e==null||e(!1)},[e]);return u.jsx(q9.Provider,{value:i,children:u.jsx(Yhe,{onOpenChange:e,...t},n)})}const xh=Xhe,Id=_.forwardRef(({className:e,...t},n)=>u.jsx(Jhe,{children:u.jsx(V9,{ref:n,className:he("z-50 min-w-[170px] overflow-hidden rounded-xl border border-border bg-background p-1 shadow-lg outline-hidden animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",e),...t})}));Id.displayName=V9.displayName;const br=_.forwardRef(({className:e,onSelect:t,...n},r)=>{const i=_.useContext(q9);return u.jsx(K9,{ref:r,className:he("relative flex cursor-default select-none items-center gap-2.5 rounded-lg px-3 py-2 text-xs font-medium text-foreground outline-hidden transition-colors hover:bg-muted focus:bg-muted data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),onSelect:s=>{t==null||t(s),i==null||i()},...n})});br.displayName=K9.displayName;const Y9=_.forwardRef(({className:e,...t},n)=>u.jsx(G9,{ref:n,className:he("-mx-1 my-1 h-px bg-border",e),...t}));Y9.displayName=G9.displayName;var TC="Popover",[X9]=Xc(TC,[jd]),Bx=jd(),[Zhe,Pd]=X9(TC),J9=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:i,onOpenChange:s,modal:o=!1}=e,a=Bx(t),l=_.useRef(null),[d,h]=_.useState(!1),[p,m]=vm({prop:r,defaultProp:i??!1,onChange:s,caller:TC});return u.jsx(yC,{...a,children:u.jsx(Zhe,{scope:t,contentId:Tc(),triggerRef:l,open:p,onOpenChange:m,onOpenToggle:_.useCallback(()=>m(v=>!v),[m]),hasCustomAnchor:d,onCustomAnchorAdd:_.useCallback(()=>h(!0),[]),onCustomAnchorRemove:_.useCallback(()=>h(!1),[]),modal:o,children:n})})};J9.displayName=TC;var Z9="PopoverAnchor",Qhe=_.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=Pd(Z9,n),s=Bx(n),{onCustomAnchorAdd:o,onCustomAnchorRemove:a}=i;return _.useEffect(()=>(o(),()=>a()),[o,a]),u.jsx(Px,{...s,...r,ref:t})});Qhe.displayName=Z9;var Q9="PopoverTrigger",eW=_.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=Pd(Q9,n),s=Bx(n),o=Kn(t,i.triggerRef),a=u.jsx(yn.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":sW(i.open),...r,ref:o,onClick:st(e.onClick,i.onOpenToggle)});return i.hasCustomAnchor?a:u.jsx(Px,{asChild:!0,...s,children:a})});eW.displayName=Q9;var Bj="PopoverPortal",[epe,tpe]=X9(Bj,{forceMount:void 0}),tW=e=>{const{__scopePopover:t,forceMount:n,children:r,container:i}=e,s=Pd(Bj,t);return u.jsx(epe,{scope:t,forceMount:n,children:u.jsx(fa,{present:n||s.open,children:u.jsx(Ym,{asChild:!0,container:i,children:r})})})};tW.displayName=Bj;var ym="PopoverContent",nW=_.forwardRef((e,t)=>{const n=tpe(ym,e.__scopePopover),{forceMount:r=n.forceMount,...i}=e,s=Pd(ym,e.__scopePopover);return u.jsx(fa,{present:r||s.open,children:s.modal?u.jsx(rpe,{...i,ref:t}):u.jsx(ipe,{...i,ref:t})})});nW.displayName=ym;var npe=Gf("PopoverContent.RemoveScroll"),rpe=_.forwardRef((e,t)=>{const n=Pd(ym,e.__scopePopover),r=_.useRef(null),i=Kn(t,r),s=_.useRef(!1);return _.useEffect(()=>{const o=r.current;if(o)return pC(o)},[]),u.jsx(Mx,{as:npe,allowPinchZoom:!0,children:u.jsx(rW,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:st(e.onCloseAutoFocus,o=>{var a;o.preventDefault(),s.current||(a=n.triggerRef.current)==null||a.focus()}),onPointerDownOutside:st(e.onPointerDownOutside,o=>{const a=o.detail.originalEvent,l=a.button===0&&a.ctrlKey===!0,d=a.button===2||l;s.current=d},{checkForDefaultPrevented:!1}),onFocusOutside:st(e.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1})})})}),ipe=_.forwardRef((e,t)=>{const n=Pd(ym,e.__scopePopover),r=_.useRef(!1),i=_.useRef(!1);return u.jsx(rW,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{var o,a;(o=e.onCloseAutoFocus)==null||o.call(e,s),s.defaultPrevented||(r.current||(a=n.triggerRef.current)==null||a.focus(),s.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:s=>{var l,d;(l=e.onInteractOutside)==null||l.call(e,s),s.defaultPrevented||(r.current=!0,s.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const o=s.target;((d=n.triggerRef.current)==null?void 0:d.contains(o))&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&i.current&&s.preventDefault()}})}),rW=_.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:s,disableOutsidePointerEvents:o,onEscapeKeyDown:a,onPointerDownOutside:l,onFocusOutside:d,onInteractOutside:h,...p}=e,m=Pd(ym,n),v=Bx(n);return fC(),u.jsx(Rx,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:s,children:u.jsx(qm,{asChild:!0,disableOutsidePointerEvents:o,onInteractOutside:h,onEscapeKeyDown:a,onPointerDownOutside:l,onFocusOutside:d,onDismiss:()=>m.onOpenChange(!1),children:u.jsx(_C,{"data-state":sW(m.open),role:"dialog",id:m.contentId,...v,...p,ref:t,style:{...p.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),iW="PopoverClose",spe=_.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=Pd(iW,n);return u.jsx(yn.button,{type:"button",...r,ref:t,onClick:st(e.onClick,()=>i.onOpenChange(!1))})});spe.displayName=iW;var ope="PopoverArrow",ape=_.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=Bx(n);return u.jsx(SC,{...i,...r,ref:t})});ape.displayName=ope;function sW(e){return e?"open":"closed"}var lpe=J9,cpe=eW,upe=tW,oW=nW;const Ld=lpe,Od=cpe,Zc=_.forwardRef(({className:e,align:t="center",sideOffset:n=4,...r},i)=>u.jsx(upe,{children:u.jsx(oW,{ref:i,align:t,sideOffset:n,[yb]:"",onCloseAutoFocus:s=>{var o;s.preventDefault(),window.dispatchEvent(new Event(FS)),(o=r.onCloseAutoFocus)==null||o.call(r,s)},className:he("z-50 w-72 rounded-xl border border-border bg-background p-4 shadow-lg outline-hidden animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r})}));Zc.displayName=oW.displayName;const w2=tn("StackActionsPopover",()=>e=>({open:!1,setOpen:t=>e({open:t})}));function dpe({editorLabel:e,starred:t,onCopyPath:n,onShowArchived:r,onOpenInFinder:i,onOpenInEditor:s,onToggleStar:o,onHide:a,children:l}){return u.jsxs(bh,{children:[u.jsx(xh,{asChild:!0,children:l}),u.jsxs(Id,{children:[u.jsxs(br,{onSelect:d=>{d.stopPropagation(),o()},children:[t?u.jsx(hae,{className:"h-3.5 w-3.5"}):u.jsx(bH,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"text-xs font-medium",children:t?"Unstar project":"Star project"})]}),u.jsxs(br,{onSelect:d=>{d.stopPropagation(),n()},children:[u.jsx(Oa,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"text-xs font-medium",children:"Copy Path"})]}),u.jsxs(br,{onSelect:d=>{d.stopPropagation(),r()},children:[u.jsx(KM,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"text-xs font-medium",children:"Show Archived"})]}),u.jsxs(br,{onSelect:d=>{d.stopPropagation(),i()},children:[u.jsx(cC,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"text-xs font-medium",children:"Show in Finder"})]}),u.jsxs(br,{onSelect:d=>{d.stopPropagation(),s()},children:[u.jsx(GM,{className:"h-3.5 w-3.5"}),u.jsxs("span",{className:"text-xs font-medium",children:["Open in ",e]})]}),u.jsxs(br,{onSelect:d=>{d.stopPropagation(),a()},className:"text-destructive hover:bg-destructive/10 focus:bg-destructive/10",children:[u.jsx(ose,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"text-xs font-medium",children:"Hide"})]})]})]})}function fpe({canFork:e,onRename:t,onOpenInFinder:n,onFork:r,onArchive:i,onDelete:s,onEditPermissions:o,children:a}){return u.jsxs(bh,{children:[u.jsx(xh,{asChild:!0,children:a}),u.jsxs(Id,{children:[u.jsxs(br,{onSelect:l=>{l.preventDefault(),t()},children:[u.jsx(Rd,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"text-xs font-medium",children:"Rename"})]}),u.jsxs(br,{onSelect:l=>{l.preventDefault(),n()},children:[u.jsx(cC,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"text-xs font-medium",children:"Open in Finder"})]}),u.jsxs(br,{disabled:!e,onSelect:l=>{l.preventDefault(),e&&r()},children:[u.jsx(vH,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"text-xs font-medium",children:"Fork"})]}),o?u.jsxs(br,{onSelect:l=>{l.preventDefault(),o()},children:[u.jsx(QM,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"text-xs font-medium",children:"Permissions…"})]}):null,u.jsxs(br,{onSelect:l=>{l.preventDefault(),i()},children:[u.jsx(KM,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"text-xs font-medium",children:"Archive"})]}),u.jsxs(br,{onSelect:l=>{l.preventDefault(),s()},className:"text-destructive dark:text-red-400 hover:bg-destructive/10 focus:bg-destructive/10 dark:hover:bg-red-500/20 dark:focus:bg-red-500/20",children:[u.jsx(Yc,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"text-xs font-medium",children:"Delete"})]})]})]})}function hpe({stackTitle:e,onRename:t,onEditMembers:n,onDelete:r,children:i}){const s=w2.useScopedStore(l=>l.open),o=w2.useScopedStore(l=>l.setOpen);function a(l){return()=>{o(!1),l()}}return u.jsxs(Ld,{open:s,onOpenChange:o,children:[u.jsx(Od,{asChild:!0,children:i}),u.jsxs(Zc,{align:"end",sideOffset:4,className:"w-44 p-1",role:"menu","aria-label":`Actions for ${e}`,children:[u.jsxs("button",{type:"button",role:"menuitem",onClick:a(t),className:"flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-left text-xs font-medium hover:bg-muted focus-visible:bg-muted outline-hidden",children:[u.jsx(Rd,{className:"h-3.5 w-3.5"}),u.jsx("span",{children:"Rename"})]}),u.jsxs("button",{type:"button",role:"menuitem",onClick:a(n),className:"flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-left text-xs font-medium hover:bg-muted focus-visible:bg-muted outline-hidden",children:[u.jsx(yH,{className:"h-3.5 w-3.5"}),u.jsx("span",{children:"Edit members"})]}),u.jsxs("button",{type:"button",role:"menuitem",onClick:a(r),className:"flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-left text-xs font-medium text-destructive dark:text-red-400 hover:bg-destructive/10 focus-visible:bg-destructive/10 dark:hover:bg-red-500/20 dark:focus-visible:bg-red-500/20 outline-hidden",children:[u.jsx(Yc,{className:"h-3.5 w-3.5"}),u.jsxs("span",{children:["Delete ",e]})]})]})]})}function ppe({stackTitle:e,onRename:t,onEditMembers:n,onDelete:r,children:i}){return u.jsx(w2.Provider,{init:{},children:u.jsx(hpe,{stackTitle:e,onRename:t,onEditMembers:n,onDelete:r,children:i})})}function mpe({stackTitle:e,onRename:t,onEditMembers:n,onDelete:r,children:i}){return u.jsxs(bh,{children:[u.jsx(xh,{asChild:!0,children:i}),u.jsxs(Id,{children:[u.jsxs(br,{onSelect:s=>{s.preventDefault(),t()},children:[u.jsx(Rd,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"text-xs font-medium",children:"Rename"})]}),u.jsxs(br,{onSelect:s=>{s.preventDefault(),n()},children:[u.jsx(yH,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"text-xs font-medium",children:"Edit members"})]}),u.jsxs(br,{onSelect:s=>{s.preventDefault(),r()},className:"text-destructive dark:text-red-400 hover:bg-destructive/10 focus:bg-destructive/10 dark:hover:bg-red-500/20 dark:focus:bg-red-500/20",children:[u.jsx(Yc,{className:"h-3.5 w-3.5"}),u.jsxs("span",{className:"text-xs font-medium",children:["Delete ",e]})]})]})]})}function gpe(e){return e.status==="running"||e.status==="starting"?"warning":e.status==="waiting_for_user"?"info":e.status==="failed"?"destructive":e.unread?"success":null}function vpe(e){switch(e){case"warning":return"bg-warning";case"info":return"bg-info";case"success":return"bg-success";case"destructive":return"bg-destructive";default:return""}}function bpe(e){switch(e){case"warning":return"text-warning";case"info":return"text-info";case"success":return"text-success";case"destructive":return"text-destructive";default:return"text-muted-foreground"}}function xpe(e){switch(e){case"active":return{glyph:"●",tone:"text-success",title:"Claude PTY session active"};case"warming":return{glyph:"◐",tone:"text-warning",title:"Claude PTY session warming"};case"idle":return{glyph:"○",tone:"text-muted-foreground",title:"Claude PTY session idle"};case"cooling":return{glyph:"◌",tone:"text-muted-foreground",title:"Claude PTY session cooling down"};case"cold":default:return null}}function ype({chat:e,activeChatId:t,nowMs:n,shortcutHint:r=null,showShortcutHint:i=!1,onSelectChat:s,onRenameChat:o,onOpenInFinder:a,onForkChat:l,onArchiveChat:d,onDeleteChat:h,onEditPermissions:p}){const m=(e.status==="running"||e.status==="waiting_for_user")&&e.stateEnteredAt!=null,v=m&&e.stateEnteredAt!=null?`${y2(e.status)} ${x2(n-e.stateEnteredAt)}`:Go(n-(e.lastMessageAt??e._creationTime)),b=i&&r?r:v,x=i&&!!r,S=Cle(e.chatId),C=t===S,k=gpe(e);let w;e.canFork?w="w-12":m?w="w-12 md:w-20":w="w-6 md:w-14";let N=null;b&&(x?N=u.jsx("span",{className:"hidden md:flex absolute inset-0 items-center justify-end pr-0.5 text-[11px] text-foreground transition-opacity duration-150 group-hover:opacity-0",children:u.jsx(Q7,{className:"h-4 min-w-4 rounded-sm border-border/50 bg-transparent px-1 text-[10px]",children:r})}):N=u.jsx("span",{className:he("hidden md:flex absolute inset-0 items-center justify-end pr-1 text-[11px] tabular-nums transition-opacity duration-150 group-hover:opacity-0 whitespace-nowrap",m?bpe(k):"text-muted-foreground"),children:b}));const A=u.jsxs("div",{"data-chat-id":S,className:he("group flex items-center gap-2 pl-2 pr-1 py-1.5 rounded-md cursor-pointer transition-colors duration-150",C?"bg-muted":"hover:bg-muted/40"),onClick:()=>s(e.chatId),children:[u.jsx("span",{className:"relative flex h-3.5 w-3.5 shrink-0 items-center justify-center","aria-hidden":!0,children:k?u.jsx("span",{className:he("h-2 w-2 rounded-full",vpe(k))}):null}),(()=>{const T=xpe(e.sessionState);return T?u.jsx("span",{className:he("shrink-0 text-[10px] leading-none",T.tone),title:T.title,"aria-label":T.title,children:T.glyph}):null})(),e.hasPolicyOverride?u.jsx(QM,{className:"size-3 shrink-0 text-warning","aria-label":"Per-chat permission override active"}):null,u.jsx("span",{className:he("truncate flex-1 text-sm",C?"text-foreground font-medium":"text-foreground/90",e.status==="idle"&&!e.unread&&!C?"text-muted-foreground":""),children:e.title}),u.jsxs("div",{className:he("relative h-6 shrink-0",w),children:[N,u.jsxs("div",{className:he("absolute inset-0 flex items-center justify-end gap-0 transition-opacity duration-150",b?"opacity-100 md:opacity-0 md:group-hover:opacity-100":"opacity-100"),children:[e.canFork?u.jsx(Ie,{variant:"ghost",size:"icon",className:"h-6 w-6 cursor-pointer rounded-sm hover:!bg-transparent !border-0",onClick:T=>{T.stopPropagation(),l(e.chatId)},title:"Fork chat",children:u.jsx(vH,{className:"size-3.5"})}):null,u.jsx(Ie,{variant:"ghost",size:"icon",className:"h-6 w-6 cursor-pointer rounded-sm hover:!bg-transparent !border-0",onClick:T=>{T.stopPropagation(),d(e.chatId)},title:"Archive chat",children:u.jsx(KM,{className:"size-3.5"})})]})]})]},e._id);return u.jsx(fpe,{canFork:e.canFork,onRename:()=>o(e.chatId),onOpenInFinder:()=>a(e.localPath),onFork:()=>l(e.chatId),onArchive:()=>d(e.chatId),onDelete:()=>h(e.chatId),onEditPermissions:p?()=>p(e.chatId):void 0,children:A})}const _pe=_.memo(ype);function Spe(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return _.useMemo(()=>r=>{t.forEach(i=>i(r))},t)}const AC=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function Zm(e){const t=Object.prototype.toString.call(e);return t==="[object Window]"||t==="[object global]"}function Fj(e){return"nodeType"in e}function so(e){var t,n;return e?Zm(e)?e:Fj(e)&&(t=(n=e.ownerDocument)==null?void 0:n.defaultView)!=null?t:window:window}function Uj(e){const{Document:t}=so(e);return e instanceof t}function Fx(e){return Zm(e)?!1:e instanceof so(e).HTMLElement}function aW(e){return e instanceof so(e).SVGElement}function Qm(e){return e?Zm(e)?e.document:Fj(e)?Uj(e)?e:Fx(e)||aW(e)?e.ownerDocument:document:document:document}const Nl=AC?_.useLayoutEffect:_.useEffect;function Hj(e){const t=_.useRef(e);return Nl(()=>{t.current=e}),_.useCallback(function(){for(var n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];return t.current==null?void 0:t.current(...r)},[])}function wpe(){const e=_.useRef(null),t=_.useCallback((r,i)=>{e.current=setInterval(r,i)},[]),n=_.useCallback(()=>{e.current!==null&&(clearInterval(e.current),e.current=null)},[]);return[t,n]}function Nb(e,t){t===void 0&&(t=[e]);const n=_.useRef(e);return Nl(()=>{n.current!==e&&(n.current=e)},t),n}function Ux(e,t){const n=_.useRef();return _.useMemo(()=>{const r=e(n.current);return n.current=r,r},[...t])}function XS(e){const t=Hj(e),n=_.useRef(null),r=_.useCallback(i=>{i!==n.current&&(t==null||t(i,n.current)),n.current=i},[]);return[n,r]}function C2(e){const t=_.useRef();return _.useEffect(()=>{t.current=e},[e]),t.current}let lN={};function Hx(e,t){return _.useMemo(()=>{if(t)return t;const n=lN[e]==null?0:lN[e]+1;return lN[e]=n,e+"-"+n},[e,t])}function lW(e){return function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return r.reduce((s,o)=>{const a=Object.entries(o);for(const[l,d]of a){const h=s[l];h!=null&&(s[l]=h+e*d)}return s},{...t})}}const Zp=lW(1),JS=lW(-1);function Cpe(e){return"clientX"in e&&"clientY"in e}function Wj(e){if(!e)return!1;const{KeyboardEvent:t}=so(e.target);return t&&e instanceof t}function kpe(e){if(!e)return!1;const{TouchEvent:t}=so(e.target);return t&&e instanceof t}function k2(e){if(kpe(e)){if(e.touches&&e.touches.length){const{clientX:t,clientY:n}=e.touches[0];return{x:t,y:n}}else if(e.changedTouches&&e.changedTouches.length){const{clientX:t,clientY:n}=e.changedTouches[0];return{x:t,y:n}}}return Cpe(e)?{x:e.clientX,y:e.clientY}:null}const Tb=Object.freeze({Translate:{toString(e){if(!e)return;const{x:t,y:n}=e;return"translate3d("+(t?Math.round(t):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(e){if(!e)return;const{scaleX:t,scaleY:n}=e;return"scaleX("+t+") scaleY("+n+")"}},Transform:{toString(e){if(e)return[Tb.Translate.toString(e),Tb.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:t,duration:n,easing:r}=e;return t+" "+n+"ms "+r}}}),w$="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function Epe(e){return e.matches(w$)?e:e.querySelector(w$)}const Npe={display:"none"};function Tpe(e){let{id:t,value:n}=e;return $n.createElement("div",{id:t,style:Npe},n)}function Ape(e){let{id:t,announcement:n,ariaLiveType:r="assertive"}=e;const i={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return $n.createElement("div",{id:t,style:i,role:"status","aria-live":r,"aria-atomic":!0},n)}function Rpe(){const[e,t]=_.useState("");return{announce:_.useCallback(r=>{r!=null&&t(r)},[]),announcement:e}}const cW=_.createContext(null);function Mpe(e){const t=_.useContext(cW);_.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of <DndContext>");return t(e)},[e,t])}function jpe(){const[e]=_.useState(()=>new Set),t=_.useCallback(r=>(e.add(r),()=>e.delete(r)),[e]);return[_.useCallback(r=>{let{type:i,event:s}=r;e.forEach(o=>{var a;return(a=o[i])==null?void 0:a.call(o,s)})},[e]),t]}const Ipe={draggable:`
757
757
  To pick up a draggable item, press the space bar.
758
758
  While dragging, use the arrow keys to move the item.
759
759
  Press space again to drop the item in its new position, or press escape to cancel.
@@ -2669,7 +2669,7 @@ XID_Start XIDS`.split(/\s/).map(e=>[JC(e),e])),aCe=new Map([["s",gi(383)],[gi(38
2669
2669
  |(?![\\s\\S])))+`,"m"),alias:i,inside:{line:{pattern:/(.)(?=[\s\S]).*(?:\r\n?|\n)?/,lookbehind:!0},prefix:{pattern:/[\s\S]/,alias:/\w+/.exec(n)[0]}}}}),Object.defineProperty(e.languages.diff,"PREFIXES",{value:t})})(Prism);const um=/^(\d+(?:\.\d+)?)px$/,An={BOTH:3,COLUMN:2,NO_STATUS:0,ROW:1};let Rl=class fJ extends Ki{constructor(n=An.NO_STATUS,r=1,i,s){super(s);U(this,"__colSpan");U(this,"__rowSpan");U(this,"__headerState");U(this,"__width");U(this,"__backgroundColor");U(this,"__verticalAlign");this.__colSpan=r,this.__rowSpan=1,this.__headerState=n,this.__width=i,this.__backgroundColor=null,this.__verticalAlign=void 0}static getType(){return"tablecell"}static clone(n){return new fJ(n.__headerState,n.__colSpan,n.__width,n.__key)}afterCloneFrom(n){super.afterCloneFrom(n),this.__rowSpan=n.__rowSpan,this.__backgroundColor=n.__backgroundColor,this.__verticalAlign=n.__verticalAlign,this.__colSpan=n.__colSpan,this.__headerState=n.__headerState,this.__width=n.__width}static importDOM(){return{td:n=>({conversion:WF,priority:0}),th:n=>({conversion:WF,priority:0})}}static importJSON(n){return no().updateFromJSON(n)}updateFromJSON(n){return super.updateFromJSON(n).setHeaderStyles(n.headerState).setColSpan(n.colSpan||1).setRowSpan(n.rowSpan||1).setWidth(n.width||void 0).setBackgroundColor(n.backgroundColor||null).setVerticalAlign(n.verticalAlign||void 0)}createDOM(n){const r=document.createElement(this.getTag());return this.__width&&(r.style.width=`${this.__width}px`),this.__colSpan>1&&(r.colSpan=this.__colSpan),this.__rowSpan>1&&(r.rowSpan=this.__rowSpan),this.__backgroundColor!==null&&(r.style.backgroundColor=this.__backgroundColor),SR(this.__verticalAlign)&&(r.style.verticalAlign=this.__verticalAlign),Gr(r,n.theme.tableCell,this.hasHeader()&&n.theme.tableCellHeader),r}exportDOM(n){const r=super.exportDOM(n);if(Nt(r.element)){const i=r.element;i.setAttribute("data-temporary-table-cell-lexical-key",this.getKey()),i.style.border="1px solid black",this.__colSpan>1&&(i.colSpan=this.__colSpan),this.__rowSpan>1&&(i.rowSpan=this.__rowSpan),i.style.width=`${this.getWidth()||75}px`,i.style.verticalAlign=this.getVerticalAlign()||"top",i.style.textAlign="start",this.__backgroundColor===null&&this.hasHeader()&&(i.style.backgroundColor="#f2f3f5")}return r}exportJSON(){return{...super.exportJSON(),...SR(this.__verticalAlign)&&{verticalAlign:this.__verticalAlign},backgroundColor:this.getBackgroundColor(),colSpan:this.__colSpan,headerState:this.__headerState,rowSpan:this.__rowSpan,width:this.getWidth()}}getColSpan(){return this.getLatest().__colSpan}setColSpan(n){const r=this.getWritable();return r.__colSpan=n,r}getRowSpan(){return this.getLatest().__rowSpan}setRowSpan(n){const r=this.getWritable();return r.__rowSpan=n,r}getTag(){return this.hasHeader()?"th":"td"}setHeaderStyles(n,r=An.BOTH){const i=this.getWritable();return i.__headerState=n&r|i.__headerState&~r,i}getHeaderStyles(){return this.getLatest().__headerState}setWidth(n){const r=this.getWritable();return r.__width=n,r}getWidth(){return this.getLatest().__width}getBackgroundColor(){return this.getLatest().__backgroundColor}setBackgroundColor(n){const r=this.getWritable();return r.__backgroundColor=n,r}getVerticalAlign(){return this.getLatest().__verticalAlign}setVerticalAlign(n){const r=this.getWritable();return r.__verticalAlign=n||void 0,r}toggleHeaderStyle(n){const r=this.getWritable();return(r.__headerState&n)===n?r.__headerState-=n:r.__headerState+=n,r}hasHeaderState(n){return(this.getHeaderStyles()&n)===n}hasHeader(){return this.getLatest().__headerState!==An.NO_STATUS}updateDOM(n){return n.__headerState!==this.__headerState||n.__width!==this.__width||n.__colSpan!==this.__colSpan||n.__rowSpan!==this.__rowSpan||n.__backgroundColor!==this.__backgroundColor||n.__verticalAlign!==this.__verticalAlign}isShadowRoot(){return!0}collapseAtStart(){return!0}canBeEmpty(){return!1}canIndent(){return!1}};function SR(e){return e==="middle"||e==="bottom"}function WF(e){const t=e,n=e.nodeName.toLowerCase();let r;um.test(t.style.width)&&(r=parseFloat(t.style.width));let i=An.NO_STATUS;if(n==="th"){const x=t.getAttribute("scope");if(x==="col")i=An.COLUMN;else if(x==="row")i=An.ROW;else{const S=t.parentElement,C=Nt(S)&&S.nodeName.toLowerCase()==="tr"&&Nt(S.parentElement)&&(S.parentElement.nodeName.toLowerCase()==="thead"||S.rowIndex===0),k=t.cellIndex===0;C&&(i|=An.ROW),k&&(i|=An.COLUMN),i===An.NO_STATUS&&(i=An.ROW)}}const s=no(i,t.colSpan,r);s.__rowSpan=t.rowSpan;const o=t.style.backgroundColor;o!==""&&(s.__backgroundColor=o);const a=t.style.verticalAlign;SR(a)&&(s.__verticalAlign=a);const l=t.style,d=(l&&l.textDecoration||"").split(" "),h=l.fontWeight==="700"||l.fontWeight==="bold",p=d.includes("line-through"),m=l.fontStyle==="italic",v=d.includes("underline"),b=l.color;return{after:x=>{const S=[];let C=null;const k=()=>{if(C){const w=C.getFirstChild();oi(w)&&C.getChildrenSize()===1&&w.remove()}};for(const w of x)if(TY(w)||Pe(w)||oi(w)){if(Pe(w)&&(h&&w.toggleFormat("bold"),p&&w.toggleFormat("strikethrough"),m&&w.toggleFormat("italic"),v&&w.toggleFormat("underline"),b)){const N=w.getStyle();N.includes("color:")||w.setStyle(N+`color: ${b};`)}C?C.append(w):(C=Tt().append(w),S.push(C))}else S.push(w),k(),C=null;return k(),S.length===0&&S.push(Tt()),S},node:s}}function no(e=An.NO_STATUS,t=1,n){return ai(new Rl(e,t,n))}function yt(e){return e instanceof Rl}const eRe=gt("INSERT_TABLE_COMMAND");function Et(e,...t){const n=new URL("https://lexical.dev/docs/error"),r=new URLSearchParams;r.append("code",e);for(const i of t)r.append("v",i);throw n.search=r.toString(),Error(`Minified Lexical error #${e}; visit ${n.toString()} for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`)}let Rh=class hJ extends Ki{constructor(n,r){super(r);U(this,"__height");this.__height=n}static getType(){return"tablerow"}static clone(n){return new hJ(n.__height,n.__key)}afterCloneFrom(n){super.afterCloneFrom(n),this.__height=n.__height}static importDOM(){return{tr:n=>({conversion:tRe,priority:0})}}static importJSON(n){return Ed().updateFromJSON(n)}updateFromJSON(n){return super.updateFromJSON(n).setHeight(n.height)}exportJSON(){const n=this.getHeight();return{...super.exportJSON(),...n===void 0?void 0:{height:n}}}createDOM(n){const r=document.createElement("tr");return this.__height&&(r.style.height=`${this.__height}px`),Gr(r,n.theme.tableRow),r}extractWithChild(n,r,i){return i==="html"}isShadowRoot(){return!0}setHeight(n){const r=this.getWritable();return r.__height=n,r}getHeight(){return this.getLatest().__height}updateDOM(n){return n.__height!==this.__height}canBeEmpty(){return!1}canIndent(){return!1}};function tRe(e){const t=e;let n;return um.test(t.style.height)&&(n=parseFloat(t.style.height)),{after:r=>zw(r,yt),node:Ed(n)}}function Ed(e){return ai(new Rh(e))}function ur(e){return e instanceof Rh}function nRe(e,t,n=!0){const r=fy();for(let i=0;i<e;i++){const s=Ed();for(let o=0;o<t;o++){let a=An.NO_STATUS;typeof n=="object"?(i===0&&n.rows&&(a|=An.ROW),o===0&&n.columns&&(a|=An.COLUMN)):n&&(i===0&&(a|=An.ROW),o===0&&(a|=An.COLUMN));const l=no(a),d=Tt();d.append(Wn()),l.append(d),s.append(l)}r.append(s)}return r}function rRe(e){const t=Ut(e,n=>pr(n));if(pr(t))return t;throw new Error("Expected table cell to be inside of table.")}const wR=(e,t)=>e===An.BOTH||e===t?t:An.NO_STATUS;function iRe(e,t=!0){const[,,n]=gl(e),[r,i]=ca(n,e,e),s=r[0].length,{startRow:o}=i;let a=null;if(t){const l=o+e.__rowSpan-1,d=r[l],h=Ed();for(let m=0;m<s;m++){const{cell:v,startRow:b}=d[m];if(b+v.__rowSpan-1<=l){const x=d[m].cell.__headerState,S=wR(x,An.COLUMN);h.append(no(S).append(Tt()))}else v.setRowSpan(v.__rowSpan+1)}const p=n.getChildAtIndex(l);ur(p)||Et(256),p.insertAfter(h),a=h}else{const l=o,d=r[l],h=Ed();for(let m=0;m<s;m++){const{cell:v,startRow:b}=d[m];if(b===l){const x=d[m].cell.__headerState,S=wR(x,An.COLUMN);h.append(no(S).append(Tt()))}else v.setRowSpan(v.__rowSpan+1)}const p=n.getChildAtIndex(l);ur(p)||Et(257),p.insertBefore(h),a=h}return a}function sRe(e,t=!0,n=!0){const[,,r]=gl(e),[i,s]=ca(r,e,e),o=i.length,{startColumn:a}=s,l=t?a+e.__colSpan-1:a-1,d=r.getFirstChild();ur(d)||Et(120);let h=null;function p(b=An.NO_STATUS){const x=no(b).append(Tt());return h===null&&(h=x),x}let m=d;e:for(let b=0;b<o;b++){if(b!==0){const A=m.getNextSibling();ur(A)||Et(121),m=A}const x=i[b],S=x[l<0?0:l].cell.__headerState,C=wR(S,An.ROW);if(l<0){pJ(m,p(C));continue}const{cell:k,startColumn:w,startRow:N}=x[l];if(w+k.__colSpan-1<=l){let A=k,T=N,M=l;for(;T!==b&&A.__rowSpan>1;){if(M-=k.__colSpan,!(M>=0)){m.append(p(C));continue e}{const{cell:j,startRow:P}=x[M];A=j,T=P}}A.insertAfter(p(C))}else k.setColSpan(k.__colSpan+1)}h!==null&&n&&oRe(h);const v=r.getColWidths();if(v){const b=[...v],x=l<0?0:l,S=b[x];b.splice(x,0,S),r.setColWidths(b)}return h}function oRe(e){const t=e.getFirstDescendant();t==null?e.selectStart():t.getParentOrThrow().selectStart()}function pJ(e,t){const n=e.getFirstChild();n!==null?n.insertBefore(t):e.append(t)}function aRe(e){if(e.length===0)return null;const t=rRe(e[0]),[n]=Ec(t,null,null);let r=1/0,i=-1/0,s=1/0,o=-1/0;const a=new Set;for(const v of n)for(const b of v){if(!b||!b.cell)continue;const x=b.cell.getKey();if(!a.has(x)&&e.some(S=>S.is(b.cell))){a.add(x);const S=b.startRow,C=b.startColumn,k=b.cell.__rowSpan||1,w=b.cell.__colSpan||1;r=Math.min(r,S),i=Math.max(i,S+k-1),s=Math.min(s,C),o=Math.max(o,C+w-1)}}if(r===1/0||s===1/0)return null;const l=i-r+1,d=o-s+1,h=n[r][s];if(!h.cell)return null;const p=h.cell;p.setColSpan(d),p.setRowSpan(l);const m=new Set([p.getKey()]);for(let v=r;v<=i;v++)for(let b=s;b<=o;b++){const x=n[v][b];if(!x.cell)continue;const S=x.cell,C=S.getKey();m.has(C)||(m.add(C),lRe(S)||p.append(...S.getChildren()),S.remove())}return p.getChildrenSize()===0&&p.append(Tt()),p}function lRe(e){if(e.getChildrenSize()!==1)return!1;const t=e.getFirstChildOrThrow();return!(!ha(t)||!t.isEmpty())}function cRe(e){const[t,n,r]=gl(e),i=t.__colSpan,s=t.__rowSpan;if(i===1&&s===1)return;const[o,a]=ca(r,t,t),{startColumn:l,startRow:d}=a,h=t.__headerState&An.COLUMN,p=Array.from({length:i},(b,x)=>{let S=h;for(let C=0;S!==0&&C<o.length;C++)S&=o[C][x+l].cell.__headerState;return S}),m=t.__headerState&An.ROW,v=Array.from({length:s},(b,x)=>{let S=m;for(let C=0;S!==0&&C<o[0].length;C++)S&=o[x+d][C].cell.__headerState;return S});if(i>1){for(let b=1;b<i;b++)t.insertAfter(no(p[b]|v[0]).append(Tt()));t.setColSpan(1)}if(s>1){let b;for(let x=1;x<s;x++){const S=d+x,C=o[S];b=(b||n).getNextSibling(),ur(b)||Et(125);let k=null;for(let w=0;w<l;w++){const N=C[w],A=N.cell;N.startRow===S&&(k=A),A.__colSpan>1&&(w+=A.__colSpan-1)}if(k===null)for(let w=i-1;w>=0;w--)pJ(b,no(p[w]|v[x]).append(Tt()));else for(let w=i-1;w>=0;w--)k.insertAfter(no(p[w]|v[x]).append(Tt()))}t.setRowSpan(1)}}function ca(e,t,n){const[r,i,s]=Ec(e,t,n);return i===null&&Et(207),s===null&&Et(208),[r,i,s]}function Ec(e,t,n){const r=[];let i=null,s=null;function o(l){let d=r[l];return d===void 0&&(r[l]=d=[]),d}const a=e.getChildren();for(let l=0;l<a.length;l++){const d=a[l];ur(d)||Et(209);const h=o(l);for(let p=d.getFirstChild(),m=0;p!=null;p=p.getNextSibling()){for(yt(p)||Et(147);h[m]!==void 0;)m++;const v={cell:p,startColumn:m,startRow:l},{__rowSpan:b,__colSpan:x}=p;for(let S=0;S<b&&!(l+S>=a.length);S++){const C=o(l+S);for(let k=0;k<x;k++)C[m+k]=v}t!==null&&i===null&&t.is(p)&&(i=v),n!==null&&s===null&&n.is(p)&&(s=v)}}return[r,i,s]}function gl(e){let t;if(e instanceof Rl)t=e;else if("__type"in e){const i=Ut(e,yt);yt(i)||Et(148),t=i}else{const i=Ut(e.getNode(),yt);yt(i)||Et(148),t=i}const n=t.getParent();ur(n)||Et(149);const r=n.getParent();return pr(r)||Et(210),[t,n,r]}function Ww(e,t,n){let r,i=Math.min(t.startColumn,n.startColumn),s=Math.min(t.startRow,n.startRow),o=Math.max(t.startColumn+t.cell.__colSpan-1,n.startColumn+n.cell.__colSpan-1),a=Math.max(t.startRow+t.cell.__rowSpan-1,n.startRow+n.cell.__rowSpan-1);do{r=!1;for(let l=0;l<e.length;l++)for(let d=0;d<e[0].length;d++){const h=e[l][d];if(!h)continue;const p=h.startColumn+h.cell.__colSpan-1,m=h.startRow+h.cell.__rowSpan-1,v=h.startColumn<=o&&p>=i,b=h.startRow<=a&&m>=s;if(v&&b){const x=Math.min(i,h.startColumn),S=Math.max(o,p),C=Math.min(s,h.startRow),k=Math.max(a,m);x===i&&S===o&&C===s&&k===a||(i=x,o=S,s=C,a=k,r=!0)}}}while(r);return{maxColumn:o,maxRow:a,minColumn:i,minRow:s}}function VF(e){const[t,,n]=gl(e),r=n.getChildren(),i=r.length,s=r[0].getChildren().length,o=new Array(i);for(let a=0;a<i;a++)o[a]=new Array(s);for(let a=0;a<i;a++){const l=r[a].getChildren();let d=0;for(let h=0;h<l.length;h++){for(;o[a][d];)d++;const p=l[h],m=p.__rowSpan||1,v=p.__colSpan||1;for(let b=0;b<m;b++)for(let x=0;x<v;x++)o[a+b][d+x]=p;if(t===p)return{colSpan:v,columnIndex:d,rowIndex:a,rowSpan:m};d+=v}}return null}function KF(e){const[[t,n,r,i],[s,o,a,l]]=["anchor","focus"].map(d=>{const h=e[d].getNode(),p=Ut(h,yt);yt(p)||Et(238,d,h.getKey(),h.getType());const m=p.getParent();ur(m)||Et(239,d);const v=m.getParent();return pr(v)||Et(240,d),[h,p,m,v]});return i.is(l)||Et(241),{anchorCell:n,anchorNode:t,anchorRow:r,anchorTable:i,focusCell:o,focusNode:s,focusRow:a,focusTable:l}}let mJ=class gJ{constructor(t,n,r){U(this,"tableKey");U(this,"anchor");U(this,"focus");U(this,"_cachedNodes");U(this,"dirty");this.anchor=n,this.focus=r,n._selection=this,r._selection=this,this._cachedNodes=null,this.dirty=!1,this.tableKey=t}getStartEndPoints(){return[this.anchor,this.focus]}isValid(){if(this.tableKey==="root"||this.anchor.key==="root"||this.anchor.type!=="element"||this.focus.key==="root"||this.focus.type!=="element")return!1;const t=lr(this.tableKey),n=lr(this.anchor.key),r=lr(this.focus.key);return t!==null&&n!==null&&r!==null}isBackward(){return this.focus.isBefore(this.anchor)}getCachedNodes(){return this._cachedNodes}setCachedNodes(t){this._cachedNodes=t}is(t){return hr(t)&&this.tableKey===t.tableKey&&this.anchor.is(t.anchor)&&this.focus.is(t.focus)}set(t,n,r){this.dirty=this.dirty||t!==this.tableKey||n!==this.anchor.key||r!==this.focus.key,this.tableKey=t,this.anchor.key=n,this.focus.key=r,this._cachedNodes=null}clone(){return new gJ(this.tableKey,io(this.anchor.key,this.anchor.offset,this.anchor.type),io(this.focus.key,this.focus.offset,this.focus.type))}isCollapsed(){return!1}extract(){return this.getNodes()}insertRawText(t){}insertText(){}hasFormat(t){let n=0;this.getNodes().filter(yt).forEach(i=>{const s=i.getFirstChild();ha(s)&&(n|=s.getTextFormat())});const r=wd[t];return(n&r)!==0}insertNodes(t){const n=this.focus.getNode();pe(n)||Et(151),Cd(n.select(0,n.getChildrenSize())).insertNodes(t)}getShape(){const{anchorCell:t,focusCell:n}=KF(this),r=VF(t);r===null&&Et(153);const i=VF(n);i===null&&Et(155);const s=Math.min(r.columnIndex,i.columnIndex),o=Math.max(r.columnIndex+r.colSpan-1,i.columnIndex+i.colSpan-1),a=Math.min(r.rowIndex,i.rowIndex),l=Math.max(r.rowIndex+r.rowSpan-1,i.rowIndex+i.rowSpan-1);return{fromX:Math.min(s,o),fromY:Math.min(a,l),toX:Math.max(s,o),toY:Math.max(a,l)}}getNodes(){if(!this.isValid())return[];const t=this._cachedNodes;if(t!==null)return t;const{anchorTable:n,anchorCell:r,focusCell:i}=KF(this),s=i.getParents()[1];if(s!==n){if(n.isParentOf(i)){const S=s.getParent();S==null&&Et(159),this.set(this.tableKey,i.getKey(),S.getKey())}else{const S=n.getParent();S==null&&Et(158),this.set(this.tableKey,S.getKey(),i.getKey())}return this.getNodes()}const[o,a,l]=ca(n,r,i),{minColumn:d,maxColumn:h,minRow:p,maxRow:m}=Ww(o,a,l),v=new Map([[n.getKey(),n]]);let b=null;for(let S=p;S<=m;S++)for(let C=d;C<=h;C++){const{cell:k}=o[S][C],w=k.getParent();ur(w)||Et(160),w!==b&&(v.set(w.getKey(),w),b=w),v.has(k.getKey())||dRe(k,N=>{v.set(N.getKey(),N)})}const x=Array.from(v.values());return sh()||(this._cachedNodes=x),x}getTextContent(){const t=this.getNodes().filter(r=>yt(r));let n="";for(let r=0;r<t.length;r++){const i=t[r],s=i.__parent,o=(t[r+1]||{}).__parent;n+=i.getTextContent()+(o!==s?`
2670
2670
  `:" ")}return n}};function hr(e){return e instanceof mJ}function uRe(){const e=io("root",0,"element"),t=io("root",0,"element");return new mJ("root",e,t)}function CR(e,t,n){e.getKey(),t.getKey(),n.getKey();const r=ze(),i=hr(r)?r.clone():uRe();return i.set(e.getKey(),t.getKey(),n.getKey()),i}function dRe(e,t){const n=[[e]];for(let r=n.at(-1);r!==void 0&&n.length>0;r=n.at(-1)){const i=r.pop();i===void 0?n.pop():t(i)!==!1&&pe(i)&&n.push(i.getChildren())}}function vJ(e,t=xr()){const n=lr(e);pr(n)||Et(231,e);const r=Vc(n,t.getElementByKey(e));return r===null&&Et(232,e),{tableElement:r,tableNode:n}}let fRe=class{constructor(){U(this,"observers");U(this,"nextFocus");U(this,"shouldCheckSelectionForTable");this.observers=new Map,this.nextFocus=null,this.shouldCheckSelectionForTable=null}setNextFocus(t){this.nextFocus=t}getAndClearNextFocus(){const{nextFocus:t}=this;return t!==null&&(this.nextFocus=null),t}setShouldCheckSelectionForTable(t){this.shouldCheckSelectionForTable=t}getAndClearShouldCheckSelectionForTable(){const{shouldCheckSelectionForTable:t}=this;return t?(this.shouldCheckSelectionForTable=null,t):null}},hRe=class{constructor(t,n){U(this,"focusX");U(this,"focusY");U(this,"listenersToRemove");U(this,"table");U(this,"isHighlightingCells");U(this,"anchorX");U(this,"anchorY");U(this,"tableNodeKey");U(this,"anchorCell");U(this,"focusCell");U(this,"anchorCellNodeKey");U(this,"focusCellNodeKey");U(this,"editor");U(this,"tableSelection");U(this,"hasHijackedSelectionStyles");U(this,"isSelecting");U(this,"pointerType");U(this,"abortController");U(this,"listenerOptions");this.isHighlightingCells=!1,this.anchorX=-1,this.anchorY=-1,this.focusX=-1,this.focusY=-1,this.listenersToRemove=new Set,this.tableNodeKey=n,this.editor=t,this.table={columns:0,domRows:[],rows:0},this.tableSelection=null,this.anchorCellNodeKey=null,this.focusCellNodeKey=null,this.anchorCell=null,this.focusCell=null,this.hasHijackedSelectionStyles=!1,this.isSelecting=!1,this.pointerType=null,this.abortController=new AbortController,this.listenerOptions={signal:this.abortController.signal},this.trackTable()}getTable(){return this.table}removeListeners(){this.abortController.abort("removeListeners"),Array.from(this.listenersToRemove).forEach(t=>t()),this.listenersToRemove.clear()}$lookup(){return vJ(this.tableNodeKey,this.editor)}trackTable(){const t=new MutationObserver(n=>{this.editor.getEditorState().read(()=>{let r=!1;for(let o=0;o<n.length;o++){const a=n[o].target.nodeName;if(a==="TABLE"||a==="TBODY"||a==="THEAD"||a==="TR"){r=!0;break}}if(!r)return;const{tableNode:i,tableElement:s}=this.$lookup();this.table=fm(i,s)},{editor:this.editor})});this.editor.getEditorState().read(()=>{const{tableNode:n,tableElement:r}=this.$lookup();this.table=fm(n,r),t.observe(r,{attributes:!0,childList:!0,subtree:!0})},{editor:this.editor})}$clearHighlight(t=!0){const n=this.editor;this.isHighlightingCells=!1,this.anchorX=-1,this.anchorY=-1,this.focusX=-1,this.focusY=-1,this.tableSelection=null,this.anchorCellNodeKey=null,this.focusCellNodeKey=null,this.anchorCell=null,this.focusCell=null,this.hasHijackedSelectionStyles=!1,this.$enableHighlightStyle();const{tableNode:r,tableElement:i}=this.$lookup();S0(n,fm(r,i),null),t&&ze()!==null&&(mr(null),n.dispatchCommand(pl,void 0))}$enableHighlightStyle(){const t=this.editor,{tableElement:n}=this.$lookup();Cl(n,t._config.theme.tableSelection),n.classList.remove("disable-selection"),this.hasHijackedSelectionStyles=!1}$disableHighlightStyle(){const{tableElement:t}=this.$lookup();Gr(t,this.editor._config.theme.tableSelection),this.hasHijackedSelectionStyles=!0}$updateTableTableSelection(t){if(t!==null){t.tableKey!==this.tableNodeKey&&Et(233,t.tableKey,this.tableNodeKey);const n=this.editor;this.tableSelection=t,this.isHighlightingCells=!0,this.$disableHighlightStyle(),this.updateDOMSelection(),S0(n,this.table,this.tableSelection)}else this.$clearHighlight()}updateDOMSelection(){if(this.anchorCell!==null&&this.focusCell!==null){const t=Gi(this.editor._window);t&&t.rangeCount>0&&t.removeAllRanges()}}$setFocusCellForSelection(t,n=!1){const r=this.editor,{tableNode:i}=this.$lookup(),s=t.x,o=t.y;if(this.focusCell=t,!this.isHighlightingCells&&(n||this.anchorX!==s||this.anchorY!==o||this.tableSelection!=null&&this.anchorCellNodeKey!=null)&&(this.isHighlightingCells=!0,this.$disableHighlightStyle()),this.focusX!==-1&&this.focusY!==-1&&s===this.focusX&&o===this.focusY)return!1;if(this.focusX=s,this.focusY=o,this.isHighlightingCells){const a=ER(i,t.elem);if(this.tableSelection!=null&&this.anchorCellNodeKey!=null){let l=a;if(l===null&&n&&(l=i.getCellNodeFromCords(s,o,this.table)),l!==null){const d=this.$getAnchorTableCellOrThrow();return this.focusCellNodeKey=l.getKey(),this.tableSelection=CR(i,d,l),mr(this.tableSelection),r.dispatchCommand(pl,void 0),S0(r,this.table,this.tableSelection),!0}}}return!1}$getAnchorTableCell(){return this.anchorCellNodeKey?lr(this.anchorCellNodeKey):null}$getAnchorTableCellOrThrow(){const t=this.$getAnchorTableCell();return t===null&&Et(234),t}$getFocusTableCell(){return this.focusCellNodeKey?lr(this.focusCellNodeKey):null}$getFocusTableCellOrThrow(){const t=this.$getFocusTableCell();return t===null&&Et(235),t}$setAnchorCellForSelection(t){this.isHighlightingCells=!1,this.anchorCell=t,this.anchorX=t.x,this.anchorY=t.y,this.focusX=-1,this.focusY=-1,this.focusCell=null,this.focusCellNodeKey=null;const{tableNode:n}=this.$lookup(),r=ER(n,t.elem);if(r!==null){const i=r.getKey();this.tableSelection!=null?(this.tableSelection=this.tableSelection.clone(),this.tableSelection.set(n.getKey(),i,i)):this.tableSelection=CR(n,r,r),this.anchorCellNodeKey=i}}$formatCells(t){const n=ze();hr(n)||Et(236);const r=uP(),i=r.anchor,s=r.focus,o=n.getNodes().filter(yt);o.length>0||Et(237);const a=o[0].getFirstChild(),l=ha(a)?a.getFormatFlags(t,null):null;o.forEach(d=>{i.set(d.getKey(),0,"element"),s.set(d.getKey(),d.getChildrenSize(),"element"),r.formatText(t,l)}),mr(n),this.editor.dispatchCommand(pl,void 0)}$clearText(){const{editor:t}=this,n=lr(this.tableNodeKey);if(!pr(n))throw new Error("Expected TableNode.");const r=ze();hr(r)||Et(253);const i=r.getNodes().filter(yt),s=n.getFirstChild(),o=n.getLastChild();if(i.length>0&&s!==null&&o!==null&&ur(s)&&ur(o)&&i[0]===s.getFirstChild()&&i[i.length-1]===o.getLastChild()){n.selectPrevious();const a=n.getParent();return n.remove(),void(bi(a)&&a.isEmpty()&&t.dispatchCommand(nh,void 0))}i.forEach(a=>{if(pe(a)){const l=Tt(),d=Wn();l.append(d),a.append(l),a.getChildren().forEach(h=>{h!==l&&h.remove()})}}),S0(t,this.table,null),mr(null),t.dispatchCommand(pl,void 0)}};const dm="__lexicalTableSelection";function Tf(e){return Nt(e)&&e.nodeName==="TABLE"}function Vc(e,t){if(!t)return t;const n=Tf(t)?t:t.querySelector("table");return Tf(n)||Et(341,e.constructor.name,e.getType(),e.getKey(),t.nodeName),n}function T1(e){return e._window}function vx(e,t){for(let n=t,r=null;n!==null;n=n.getParent()){if(e.is(n))return r;yt(n)&&(r=n)}return null}const pRe=[[s1,"down"],[i1,"up"],[nP,"backward"],[tP,"forward"]],mRe=[jm,rh,hd],gRe=[rP,iP];function vRe(e,t){return e.registerRootListener(n=>{if(n===null)return;const r=e._window;if(r===null)return;const i=s=>{const o=s.target;if(s.button!==0||!Wa(o)||!n.contains(o))return;const a=(function(l){const d=Vw(l);if(d===null)return null;let h=d.elem;for(;h!=null;){if(h.nodeName==="TABLE"&&dm in h&&h[dm])return{cellElement:d,tableElement:h,tableObserver:h[dm]};h=h.parentNode}return null})(o);e.update(()=>{if(hr(ze())){for(const[p]of t.observers.values())p.$clearHighlight(!1);mr(null),e.dispatchCommand(pl,void 0)}if(!a)return;const{tableObserver:l,tableElement:d,cellElement:h}=a;(function(p,m,v,b,x,S){const C=p._window;if(!C)return;const k=A=>{if(x.isSelecting)return;x.isSelecting=!0,A!==null&&x.anchorCell===null&&p.update(()=>{x.$setAnchorCellForSelection(A)});const T=()=>{x.isSelecting=!1,C.removeEventListener("pointerup",T),C.removeEventListener("pointermove",M)},M=j=>{if(!(L=>!(1&~L.buttons))(j)&&x.isSelecting)return x.isSelecting=!1,C.removeEventListener("pointerup",T),void C.removeEventListener("pointermove",M);if(!Wa(j.target))return;let P=null;const D=!(Tl||b.contains(j.target));if(D)P=qF(b,j.target);else for(const L of document.elementsFromPoint(j.clientX,j.clientY))if(P=qF(b,L),P)break;if(P){const L=P;x.anchorCell===null&&p.update(()=>{x.$setAnchorCellForSelection(L)}),x.focusCell!==null&&P.elem===x.focusCell.elem||(S.setNextFocus({focusCell:P,override:D,tableKey:x.tableNodeKey}),p.dispatchCommand(pl,void 0))}};C.addEventListener("pointerup",T,x.listenerOptions),C.addEventListener("pointermove",M,x.listenerOptions)};x.pointerType=m.pointerType;const w=ub(x.tableNodeKey),N=eo();if(Tl&&m.shiftKey&&pc(N,w)&&(_e(N)||hr(N))){const A=N.anchor.getNode(),T=vx(w,N.anchor.getNode());T?(x.$setAnchorCellForSelection(Lf(x,T)),x.$setFocusCellForSelection(v),xc(m)):(w.isBefore(A)?w.selectStart():w.selectEnd()).anchor.set(N.anchor.key,N.anchor.offset,N.anchor.type)}else m.pointerType!=="touch"&&x.$setAnchorCellForSelection(v);k(v)})(e,s,h,d,l,t)})};return r.addEventListener("pointerdown",i),()=>{r.removeEventListener("pointerdown",i)}})}function bRe(e,t,n,r,i){const s=n.getRootElement(),o=T1(n);s!==null&&o!==null||Et(246);const a=new hRe(n,e.getKey()),l=Vc(e,t);(function(m,v){GF(m)!==null&&Et(205),m[dm]=v})(l,a),a.listenersToRemove.add(()=>(function(m,v){GF(m)===v&&delete m[dm]})(l,a));const d=m=>{m.detail>=3&&Wa(m.target)&&Vw(m.target)!==null&&m.preventDefault()};l.addEventListener("mousedown",d,a.listenerOptions),a.listenersToRemove.add(()=>{l.removeEventListener("mousedown",d)});for(const[m,v]of pRe)a.listenersToRemove.add(n.registerCommand(m,b=>yJ(n,b,v,e,a,i),cs));a.listenersToRemove.add(n.registerCommand(o1,m=>{const v=ze();if(hr(v)){const b=vx(e,v.focus.getNode());if(b!==null)return xc(m),b.selectEnd(),!0}return!1},cs));const h=m=>()=>{const v=ze();if(!pc(v,e))return!1;if(hr(v))return a.$clearText(),!0;if(_e(v)){if(!yt(vx(e,v.anchor.getNode())))return!1;const b=v.anchor.getNode(),x=v.focus.getNode(),S=e.isParentOf(b),C=e.isParentOf(x);if(S&&!C||C&&!S)return a.$clearText(),!0;const k=Ut(v.anchor.getNode(),N=>pe(N)),w=k&&Ut(k,N=>pe(N)&&yt(N.getParent()));if(!pe(w)||!pe(k))return!1;if(m===rh&&w.getPreviousSibling()===null)return!0}return!1};for(const m of mRe)a.listenersToRemove.add(n.registerCommand(m,h(m),cs));const p=m=>{const v=ze();if(!hr(v)&&!_e(v))return!1;const b=e.isParentOf(v.anchor.getNode());if(b!==e.isParentOf(v.focus.getNode())){const x=b?"anchor":"focus",S=b?"focus":"anchor",{key:C,offset:k,type:w}=v[S];return e[v[x].isBefore(v[S])?"selectPrevious":"selectNext"]()[S].set(C,k,w),!1}return!!pc(v,e)&&!!hr(v)&&(m&&(m.preventDefault(),m.stopPropagation()),a.$clearText(),!0)};for(const m of gRe)a.listenersToRemove.add(n.registerCommand(m,p,cs));return a.listenersToRemove.add(n.registerCommand(l1,m=>{const v=ze();if(v){if(!hr(v)&&!_e(v))return!1;gR(n,ml(m,ClipboardEvent)?m:null,FP(v));const b=p(m);return _e(v)?(v.removeText(),!0):b}return!1},cs)),a.listenersToRemove.add(n.registerCommand(kc,m=>{const v=ze();if(!pc(v,e))return!1;if(hr(v))return a.$formatCells(m),!0;if(_e(v)){const b=Ut(v.anchor.getNode(),x=>yt(x));if(!yt(b))return!1}return!1},cs)),a.listenersToRemove.add(n.registerCommand(Pq,m=>{const v=ze();if(!hr(v)||!pc(v,e))return!1;const b=v.anchor.getNode(),x=v.focus.getNode();if(!yt(b)||!yt(x))return!1;if((function(j,P){if(hr(j)){const D=j.anchor.getNode(),L=j.focus.getNode();if(P&&D&&L){const[I]=ca(P,D,L);return D.getKey()===I[0][0].cell.getKey()&&L.getKey()===I[I.length-1].at(-1).cell.getKey()}}return!1})(v,e))return e.setFormat(m),!0;const[S,C,k]=ca(e,b,x),w=Math.max(C.startRow+C.cell.__rowSpan-1,k.startRow+k.cell.__rowSpan-1),N=Math.max(C.startColumn+C.cell.__colSpan-1,k.startColumn+k.cell.__colSpan-1),A=Math.min(C.startRow,k.startRow),T=Math.min(C.startColumn,k.startColumn),M=new Set;for(let j=A;j<=w;j++)for(let P=T;P<=N;P++){const D=S[j][P].cell;if(M.has(D))continue;M.add(D),D.setFormat(m);const L=D.getChildren();for(let I=0;I<L.length;I++){const $=L[I];pe($)&&!$.isInline()&&$.setFormat(m)}}return!0},cs)),a.listenersToRemove.add(n.registerCommand(Uf,m=>{const v=ze();if(!pc(v,e))return!1;if(hr(v))return a.$clearHighlight(),!1;if(_e(v)){const b=Ut(v.anchor.getNode(),x=>yt(x));if(!yt(b))return!1;if(typeof m=="string"){const x=XF(n,v,e);if(x)return YF(x,e,[Wn(m)]),!0}}return!1},cs)),r&&a.listenersToRemove.add(n.registerCommand(ty,m=>{const v=ze();if(!_e(v)||!v.isCollapsed()||!pc(v,e))return!1;const b=Lv(v.anchor.getNode());return!(b===null||!e.is(zm(b)))&&(xc(m),(function(x,S){const C=S==="next"?"getNextSibling":"getPreviousSibling",k=S==="next"?"getFirstChild":"getLastChild",w=x[C]();if(pe(w))return w.selectEnd();const N=Ut(x,ur);N===null&&Et(247);for(let T=N[C]();ur(T);T=T[C]()){const M=T[k]();if(pe(M))return M.selectEnd()}const A=Ut(N,pr);A===null&&Et(248),S==="next"?A.selectNext():A.selectPrevious()})(b,m.shiftKey?"previous":"next"),!0)},cs)),a.listenersToRemove.add(n.registerCommand(Oq,m=>e.isSelected(),cs)),a.listenersToRemove.add(n.registerCommand(nh,()=>{const m=ze();if(!_e(m)||!m.isCollapsed()||!pc(m,e))return!1;const v=XF(n,m,e);return!!v&&(YF(v,e),!0)},cs)),a}function xRe(e,t){const n=ze(),r=eo(),i=e.getAndClearNextFocus();if(i!==null){const{tableKey:a,focusCell:l}=i,d=e.observers.get(a);d||Et(335,a);const[h]=d;if(hr(n)&&n.tableKey===h.tableNodeKey)return(l.x!==h.focusX||l.y!==h.focusY)&&(h.$setFocusCellForSelection(l),!0);if(h.anchorCell!==null&&h.anchorCellNodeKey!==null&&l.elem!==h.anchorCell.elem&&h.tableSelection!==null)return h.$setFocusCellForSelection(l,!0),!0}const s=e.getAndClearShouldCheckSelectionForTable();if(s&&_e(r)&&_e(n)&&n.isCollapsed()){const a=ub(s),l=n.anchor.getNode(),d=a.getFirstChild(),h=Lv(l);if(h!==null&&ur(d)){const p=d.getFirstChild();if(yt(p)&&a.is(Ut(h,m=>m.is(a)||m.is(p))))return p.selectStart(),!0}}hr(n)&&(function(a,l){const d=T1(a),h=eo();if(!l.is(h))return;const p=ub(l.tableKey),m=Gi(d);if(m&&m.anchorNode&&m.focusNode){const v=Is(m.focusNode),b=v&&!p.isParentOf(v),x=Is(m.anchorNode),S=x&&p.isParentOf(x);if(b&&S&&m.rangeCount>0){const C=lNe(m,a);C&&(C.anchor.set(p.getKey(),l.isBackward()?p.getChildrenSize():0,"element"),m.removeAllRanges(),mr(C))}}})(t,n),_e(n)&&(function(a,l){const d=eo(),{anchor:h,focus:p}=a,m=h.getNode(),v=p.getNode(),b=Lv(m),x=Lv(v),S=b?zm(b):null,C=x?zm(x):null,k=a.isBackward(),w=b&&x&&S&&C&&S.is(C),N=C&&(!S||S.isParentOf(C)),A=S&&(!C||C.isParentOf(S));if(N){const T=a.clone(),[M]=ca(C,x,x),j=M[0][0].cell,P=M[M.length-1].at(-1).cell;T.focus.set(k?j.getKey():P.getKey(),k?0:P.getChildrenSize(),"element"),mr(T)}else if(A){const T=a.clone(),[M]=ca(S,b,b),j=M[0][0].cell,P=M[M.length-1].at(-1).cell;T.anchor.set(k?P.getKey():j.getKey(),k?P.getChildrenSize():0,"element"),mr(T)}else if(w){const T=l.observers.get(S.getKey());T||Et(335,S.getKey());const[M]=T;if(b.is(x)||(M.$setAnchorCellForSelection(Lf(M,b)),M.$setFocusCellForSelection(Lf(M,x),!0)),M.pointerType==="touch"&&M.isSelecting&&a.isCollapsed()&&_e(d)&&d.isCollapsed()){const j=Lv(d.anchor.getNode());j&&!j.is(x)&&(M.$setAnchorCellForSelection(Lf(M,j)),M.$setFocusCellForSelection(Lf(M,x),!0),M.pointerType=null)}}})(n,e);const o=Array.from(e.observers.entries()).map(([a,[l]])=>({tableNode:ub(a),tableObserver:l}));for(const{tableNode:a,tableObserver:l}of o)yRe(t,a,l);return!1}function yRe(e,t,n){const r=ze(),i=eo();r&&!r.is(i)&&(hr(r)||hr(i))&&n.tableSelection&&!n.tableSelection.is(i)&&(hr(r)&&r.tableKey===n.tableNodeKey?n.$updateTableTableSelection(r):!hr(r)&&hr(i)&&i.tableKey===n.tableNodeKey&&n.$updateTableTableSelection(null)),n.hasHijackedSelectionStyles&&!t.isSelected()?(function(s,o){o.$enableHighlightStyle(),kR(o.table,a=>{const l=a.elem;a.highlighted=!1,xJ(s,a),l.getAttribute("style")||l.removeAttribute("style")})})(e,n):!n.hasHijackedSelectionStyles&&t.isSelected()&&(function(s,o){o.$disableHighlightStyle(),kR(o.table,a=>{a.highlighted=!0,bJ(s,a)})})(e,n)}function GF(e){return e[dm]||null}function Vw(e){let t=e;for(;t!=null;){const n=t.nodeName;if(n==="TD"||n==="TH"){const r=t._cell;return r===void 0?null:r}t=t.parentNode}return null}function qF(e,t){if(!e.contains(t))return null;let n=null;for(let r=t;r!=null;r=r.parentNode){if(r===e)return n;const i=r.nodeName;i!=="TD"&&i!=="TH"||(n=r._cell||null)}return null}function fm(e,t){const n=[],r={columns:0,domRows:n,rows:0};let i=Vc(e,t).querySelector("tr"),s=0,o=0;for(n.length=0;i!=null;){const a=i.nodeName;if(a==="TD"||a==="TH"){const h={elem:i,hasBackgroundColor:i.style.backgroundColor!=="",highlighted:!1,x:s,y:o};i._cell=h;let p=n[o];p===void 0&&(p=n[o]=[]),p[s]=h}else{const h=i.firstChild;if(h!=null){i=h;continue}}const l=i.nextSibling;if(l!=null){s++,i=l;continue}const d=i.parentNode;if(d!=null){const h=d.nextSibling;if(h==null)break;o++,s=0,i=h}}return r.columns=s+1,r.rows=o+1,r}function S0(e,t,n){const r=new Set(n?n.getNodes():[]);kR(t,(i,s)=>{const o=i.elem;r.has(s)?(i.highlighted=!0,bJ(e,i)):(i.highlighted=!1,xJ(e,i),o.getAttribute("style")||o.removeAttribute("style"))})}function kR(e,t){const{domRows:n}=e;for(let r=0;r<n.length;r++){const i=n[r];if(i)for(let s=0;s<i.length;s++){const o=i[s];if(!o)continue;const a=Is(o.elem);a!==null&&t(o,a,{x:s,y:r})}}}const _Re=(e,t,n,r,i)=>{const s=i==="forward";switch(i){case"backward":case"forward":return n!==(s?e.table.columns-1:0)?C0(t.getCellNodeFromCordsOrThrow(n+(s?1:-1),r,e.table),s):r!==(s?e.table.rows-1:0)?C0(t.getCellNodeFromCordsOrThrow(s?0:e.table.columns-1,r+(s?1:-1),e.table),s):s?t.selectNext():t.selectPrevious(),!0;case"up":return r!==0?C0(t.getCellNodeFromCordsOrThrow(n,r-1,e.table),!1):t.selectPrevious(),!0;case"down":return r!==e.table.rows-1?C0(t.getCellNodeFromCordsOrThrow(n,r+1,e.table),!0):t.selectNext(),!0;default:return!1}};function yT(e,t){let n,r;if(t.startColumn===e.minColumn)n="minColumn";else{if(t.startColumn+t.cell.__colSpan-1!==e.maxColumn)return null;n="maxColumn"}if(t.startRow===e.minRow)r="minRow";else{if(t.startRow+t.cell.__rowSpan-1!==e.maxRow)return null;r="maxRow"}return[n,r]}function w0([e,t]){return[e==="minColumn"?"maxColumn":"minColumn",t==="minRow"?"maxRow":"minRow"]}function Cp(e,t,[n,r]){const i=t[r],s=e[i];s===void 0&&Et(250,r,String(i));const o=t[n],a=s[o];return a===void 0&&Et(250,n,String(o)),a}function SRe(e,t,n,r,i){const s=Ww(t,n,r),o=(function(T,M){const{minColumn:j,maxColumn:P,minRow:D,maxRow:L}=M;let I=1,$=1,H=1,z=1;const F=T[D],K=T[L];for(let W=j;W<=P;W++)I=Math.max(I,F[W].cell.__rowSpan),z=Math.max(z,K[W].cell.__rowSpan);for(let W=D;W<=L;W++)$=Math.max($,T[W][j].cell.__colSpan),H=Math.max(H,T[W][P].cell.__colSpan);return{bottomSpan:z,leftSpan:$,rightSpan:H,topSpan:I}})(t,s),{topSpan:a,leftSpan:l,bottomSpan:d,rightSpan:h}=o,p=(function(T,M){const j=yT(T,M);return j===null&&Et(249,M.cell.getKey()),j})(s,n),[m,v]=w0(p);let b=s[m],x=s[v];i==="forward"?b+=m==="maxColumn"?1:l:i==="backward"?b-=m==="minColumn"?1:h:i==="down"?x+=v==="maxRow"?1:a:i==="up"&&(x-=v==="minRow"?1:d);const S=t[x];if(S===void 0)return!1;const C=S[b];if(C===void 0)return!1;const[k,w]=(function(T,M,j){const P=Ww(T,M,j),D=yT(P,M);if(D)return[Cp(T,P,D),Cp(T,P,w0(D))];const L=yT(P,j);if(L)return[Cp(T,P,w0(L)),Cp(T,P,L)];const I=["minColumn","minRow"];return[Cp(T,P,I),Cp(T,P,w0(I))]})(t,n,C),N=Lf(e,k.cell),A=Lf(e,w.cell);return e.$setAnchorCellForSelection(N),e.$setFocusCellForSelection(A,!0),!0}function pc(e,t){if(_e(e)||hr(e)){const n=t.isParentOf(e.anchor.getNode()),r=t.isParentOf(e.focus.getNode());return n&&r}return!1}function C0(e,t){t?e.selectStart():e.selectEnd()}function bJ(e,t){const n=t.elem,r=e._config.theme;yt(Is(n))||Et(131),Gr(n,r.tableCellSelected)}function xJ(e,t){const n=t.elem;yt(Is(n))||Et(131);const r=e._config.theme;Cl(n,r.tableCellSelected)}function Lv(e){const t=Ut(e,yt);return yt(t)?t:null}function zm(e){const t=Ut(e,pr);return pr(t)?t:null}function wRe(e,t,n,r,i,s,o){const a=la(n.focus,i?"previous":"next");if(jP(a))return!1;let l=a;for(const S of fx(a).iterNodeCarets("shadowRoot")){if(!aa(S)||!pe(S.origin))return!1;l=S}const d=l.getParentAtCaret();if(!yt(d))return!1;const h=d,p=(function(S){for(const C of fx(S).iterNodeCarets("root")){const{origin:k}=C;if(yt(k)){if(ps(C))return _i(k,S.direction)}else if(!ur(k))break}return null})(tr(h,l.direction)),m=Ut(h,pr);if(!m||!m.is(s))return!1;const v=e.getElementByKey(h.getKey()),b=Vw(v);if(!v||!b)return!1;const x=kRe(e,m);if(o.table=x,p)if(r==="extend"){const S=Vw(e.getElementByKey(p.origin.getKey()));if(!S)return!1;o.$setAnchorCellForSelection(b),o.$setFocusCellForSelection(S,!0)}else{const S=xi(p);Qo(n.anchor,S),Qo(n.focus,S)}else if(r==="extend")o.$setAnchorCellForSelection(b),o.$setFocusCellForSelection(b,!0);else{const S=(function(C){const k=ah(C);return ps(k)?xi(k):C})(tr(m,a.direction));Qo(n.anchor,S),Qo(n.focus,S)}return xc(t),!0}function yJ(e,t,n,r,i,s){if((n==="up"||n==="down")&&(function(a){const l=a.getRootElement();return l?l.hasAttribute("aria-controls")&&l.getAttribute("aria-controls")==="typeahead-menu":!1})(e))return!1;const o=ze();if(!pc(o,r)){if(_e(o)){if(n==="backward"){if(o.focus.offset>0)return!1;const a=(function(d){for(let h=d,p=d;p!==null;h=p,p=p.getParent())if(pe(p)){if(p!==h&&p.getFirstChild()!==h)return null;if(!p.isInline())return p}return null})(o.focus.getNode());if(!a)return!1;const l=a.getPreviousSibling();return!!pr(l)&&(xc(t),t.shiftKey?o.focus.set(l.getParentOrThrow().getKey(),l.getIndexWithinParent(),"element"):l.selectEnd(),!0)}if(t.shiftKey&&(n==="up"||n==="down")){const a=o.focus.getNode();if(!o.isCollapsed()&&(n==="up"&&!o.isBackward()||n==="down"&&o.isBackward())){let l=Ut(a,v=>pr(v));if(yt(l)&&(l=Ut(l,pr)),l!==r||!l)return!1;const d=n==="down"?l.getNextSibling():l.getPreviousSibling();if(!d)return!1;let h=0;n==="up"&&pe(d)&&(h=d.getChildrenSize());let p=d;n==="up"&&pe(d)&&(p=d.getLastChild()||d,h=Pe(p)?p.getTextContentSize():0);const m=o.clone();return m.focus.set(p.getKey(),h,Pe(p)?"text":"element"),mr(m),xc(t),!0}if(Vi(a)){const l=n==="up"?o.getNodes()[o.getNodes().length-1]:o.getNodes()[0];if(l&&vx(r,l)!==null){const d=r.getFirstDescendant(),h=r.getLastDescendant();if(!d||!h)return!1;const[p]=gl(d),[m]=gl(h),v=r.getCordsFromCellNode(p,i.table),b=r.getCordsFromCellNode(m,i.table),x=r.getDOMCellFromCordsOrThrow(v.x,v.y,i.table),S=r.getDOMCellFromCordsOrThrow(b.x,b.y,i.table);return i.$setAnchorCellForSelection(x),i.$setFocusCellForSelection(S,!0),!0}return!1}{let l=Ut(a,h=>pe(h)&&!h.isInline());if(yt(l)&&(l=Ut(l,pr)),!l)return!1;const d=n==="down"?l.getNextSibling():l.getPreviousSibling();if(pr(d)&&i.tableNodeKey===d.getKey()){const h=d.getFirstDescendant(),p=d.getLastDescendant();if(!h||!p)return!1;const[m]=gl(h),[v]=gl(p),b=o.clone();return b.focus.set((n==="up"?m:v).getKey(),n==="up"?0:v.getChildrenSize(),"element"),xc(t),mr(b),!0}}}}return n==="down"&&Kw(e)&&s.setShouldCheckSelectionForTable(r.getKey()),!1}if(_e(o)){if(n==="backward"||n==="forward")return wRe(e,t,o,t.shiftKey?"extend":"move",n==="backward",r,i);if(o.isCollapsed()){const{anchor:a,focus:l}=o,d=Ut(a.getNode(),yt),h=Ut(l.getNode(),yt);if(!yt(d)||!d.is(h))return!1;const p=zm(d);if(p!==r&&p!=null){const k=Vc(p,e.getElementByKey(p.getKey()));if(k!=null)return i.table=fm(p,k),yJ(e,t,n,p,i,s)}const m=e.getElementByKey(d.__key),v=e.getElementByKey(a.key);if(v==null||m==null)return!1;let b;if(a.type==="element")b=v.getBoundingClientRect();else{const k=Gi(T1(e));if(k===null||k.rangeCount===0)return!1;b=k.getRangeAt(0).getBoundingClientRect()}const x=n==="up"?d.getFirstChild():d.getLastChild();if(x==null)return!1;const S=e.getElementByKey(x.__key);if(S==null)return!1;const C=S.getBoundingClientRect();if(n==="up"?C.top>b.top-b.height:b.bottom+b.height>C.bottom){xc(t);const k=r.getCordsFromCellNode(d,i.table);if(!t.shiftKey)return _Re(i,r,k.x,k.y,n);{const w=r.getDOMCellFromCordsOrThrow(k.x,k.y,i.table);i.$setAnchorCellForSelection(w),i.$setFocusCellForSelection(w,!0)}return!0}}}else if(hr(o)){const{anchor:a,focus:l,tableKey:d}=o;if(d!==r.getKey())return!1;const h=Ut(a.getNode(),yt),p=Ut(l.getNode(),yt),[m]=o.getNodes();pr(m)||Et(251);const v=Vc(m,e.getElementByKey(m.getKey()));if(!yt(h)||!yt(p)||!pr(m)||v==null)return!1;i.$updateTableTableSelection(o);const b=fm(m,v),x=r.getCordsFromCellNode(h,b),S=r.getDOMCellFromCordsOrThrow(x.x,x.y,b);if(i.$setAnchorCellForSelection(S),xc(t),t.shiftKey){const[C,k,w]=ca(r,h,p);return SRe(i,C,k,w,n)}return p.selectEnd(),!0}return!1}function xc(e){e.preventDefault(),e.stopImmediatePropagation(),e.stopPropagation()}function YF(e,t,n){const r=Tt();e==="first"?t.insertBefore(r):t.insertAfter(r),r.append(...n||[]),r.selectEnd()}function XF(e,t,n){const r=n.getParent();if(!r)return;const i=Gi(T1(e));if(!i)return;const s=i.anchorNode,o=e.getElementByKey(r.getKey()),a=Vc(n,e.getElementByKey(n.getKey()));if(!s||!o||!a||!o.contains(s)||a.contains(s))return;const l=Ut(t.anchor.getNode(),k=>yt(k));if(!l)return;const d=Ut(l,k=>pr(k));if(!pr(d)||!d.is(n))return;const[h,p]=ca(n,l,l),m=h[0][0],v=h[h.length-1][h[0].length-1],{startRow:b,startColumn:x}=p,S=b===m.startRow&&x===m.startColumn,C=b===v.startRow&&x===v.startColumn;return S?"first":C?"last":void 0}function Lf(e,t){const{tableNode:n}=e.$lookup(),r=n.getCordsFromCellNode(t,e.table);return n.getDOMCellFromCordsOrThrow(r.x,r.y,e.table)}function ER(e,t,n){return vx(e,Is(t,n))}function JF(e,t,n){const r=e.querySelector("colgroup");if(!r)return;const i=[];for(let s=0;s<t;s++){const o=document.createElement("col"),a=n&&n[s];a&&(o.style.width=`${a}px`),i.push(o)}r.replaceChildren(...i)}function ZF(e,t,n){if(!t.theme.tableAlignment)return;const r=[],i=[];for(const s of["center","right"]){const o=t.theme.tableAlignment[s];o&&(s===n?i:r).push(o)}Cl(e,...r),Gr(e,...i)}const NR=new WeakSet;function Kw(e=xr()){return NR.has(e)}function CRe(e,t){t?NR.add(e):NR.delete(e)}let Kc=class _J extends Ki{constructor(n){super(n);U(this,"__rowStriping");U(this,"__frozenColumnCount");U(this,"__frozenRowCount");U(this,"__colWidths");this.__rowStriping=!1,this.__frozenColumnCount=0,this.__frozenRowCount=0,this.__colWidths=void 0}static getType(){return"table"}getColWidths(){return this.getLatest().__colWidths}setColWidths(n){const r=this.getWritable();return r.__colWidths=n,r}static clone(n){return new _J(n.__key)}afterCloneFrom(n){super.afterCloneFrom(n),this.__colWidths=n.__colWidths,this.__rowStriping=n.__rowStriping,this.__frozenColumnCount=n.__frozenColumnCount,this.__frozenRowCount=n.__frozenRowCount}static importDOM(){return{table:n=>({conversion:ERe,priority:1})}}static importJSON(n){return fy().updateFromJSON(n)}updateFromJSON(n){return super.updateFromJSON(n).setRowStriping(n.rowStriping||!1).setFrozenColumns(n.frozenColumnCount||0).setFrozenRows(n.frozenRowCount||0).setColWidths(n.colWidths)}exportJSON(){return{...super.exportJSON(),colWidths:this.getColWidths(),frozenColumnCount:this.__frozenColumnCount?this.__frozenColumnCount:void 0,frozenRowCount:this.__frozenRowCount?this.__frozenRowCount:void 0,rowStriping:this.__rowStriping?this.__rowStriping:void 0}}extractWithChild(n,r,i){return i==="html"}getDOMSlot(n){const r=Tf(n)?n:n.querySelector("table");return Tf(r)||Et(229),super.getDOMSlot(n).withElement(r).withAfter(r.querySelector("colgroup"))}createDOM(n,r){const i=document.createElement("table");this.__style&&pd(i.style,this.__style);const s=document.createElement("colgroup");if(i.appendChild(s),PNe(s),Gr(i,n.theme.table),this.updateTableElement(null,i,n),Kw(r)){const o=document.createElement("div"),a=n.theme.tableScrollableWrapper;return a?Gr(o,a):o.style.overflowX="auto",o.appendChild(i),this.updateTableWrapper(null,o,i,n),o}return i}updateTableWrapper(n,r,i,s){this.__frozenColumnCount!==(n?n.__frozenColumnCount:0)&&(function(o,a,l,d){d>0?(Gr(o,l.theme.tableFrozenColumn),a.setAttribute("data-lexical-frozen-column","true")):(Cl(o,l.theme.tableFrozenColumn),a.removeAttribute("data-lexical-frozen-column"))})(r,i,s,this.__frozenColumnCount),this.__frozenRowCount!==(n?n.__frozenRowCount:0)&&(function(o,a,l,d){d>0?(Gr(o,l.theme.tableFrozenRow),a.setAttribute("data-lexical-frozen-row","true")):(Cl(o,l.theme.tableFrozenRow),a.removeAttribute("data-lexical-frozen-row"))})(r,i,s,this.__frozenRowCount)}updateTableElement(n,r,i){this.__style!==(n?n.__style:"")&&pd(r.style,this.__style,n?n.__style:""),this.__rowStriping!==(!!n&&n.__rowStriping)&&(function(a,l,d){d?(Gr(a,l.theme.tableRowStriping),a.setAttribute("data-lexical-row-striping","true")):(Cl(a,l.theme.tableRowStriping),a.removeAttribute("data-lexical-row-striping"))})(r,i,this.__rowStriping);const s=n?n.getColumnCount():0,o=n?n.__colWidths:void 0;this.getColumnCount()===s&&this.getColWidths()===o||JF(r,this.getColumnCount(),this.getColWidths()),ZF(r,i,this.getFormatType())}updateDOM(n,r,i){const s=Vc(this,r);return r===s===Kw()||(Nt(o=r)&&o.nodeName==="DIV"&&this.updateTableWrapper(n,r,s,i),this.updateTableElement(n,s,i),!1);var o}scaleDOMColWidths(n,r){const i=this.getColWidths();i&&JF(Vc(this,n),this.getColumnCount(),i.map(s=>s*r))}exportDOM(n){const r=super.exportDOM(n),{element:i}=r;return{after:s=>{if(r.after&&(s=r.after(s)),!Tf(s)&&Nt(s)&&(s=s.querySelector("table")),!Tf(s))return null;ZF(s,n._config,this.getFormatType());const[o]=Ec(this,null,null),a=new Map;for(const p of o)for(const m of p){const v=m.cell.getKey();a.has(v)||a.set(v,{colSpan:m.cell.getColSpan(),startColumn:m.startColumn})}const l=new Set;for(const p of s.querySelectorAll(":scope > tr > [data-temporary-table-cell-lexical-key]")){const m=p.getAttribute("data-temporary-table-cell-lexical-key");if(m){const v=a.get(m);if(p.removeAttribute("data-temporary-table-cell-lexical-key"),v){a.delete(m);for(let b=0;b<v.colSpan;b++)l.add(b+v.startColumn)}}}const d=s.querySelector(":scope > colgroup");if(d){const p=Array.from(s.querySelectorAll(":scope > colgroup > col")).filter((m,v)=>l.has(v));d.replaceChildren(...p)}const h=s.querySelectorAll(":scope > tr");if(h.length>0){const p=document.createElement("tbody");for(const m of h)p.appendChild(m);s.append(p)}return s},element:!Tf(i)&&Nt(i)?i.querySelector("table"):i}}canBeEmpty(){return!1}isShadowRoot(){return!0}getCordsFromCellNode(n,r){const{rows:i,domRows:s}=r;for(let o=0;o<i;o++){const a=s[o];if(a!=null)for(let l=0;l<a.length;l++){const d=a[l];if(d==null)continue;const{elem:h}=d,p=ER(this,h);if(p!==null&&n.is(p))return{x:l,y:o}}}throw new Error("Cell not found in table.")}getDOMCellFromCords(n,r,i){const{domRows:s}=i,o=s[r];if(o==null)return null;const a=o[n<o.length?n:o.length-1];return a??null}getDOMCellFromCordsOrThrow(n,r,i){const s=this.getDOMCellFromCords(n,r,i);if(!s)throw new Error("Cell not found at cords.");return s}getCellNodeFromCords(n,r,i){const s=this.getDOMCellFromCords(n,r,i);if(s==null)return null;const o=Is(s.elem);return yt(o)?o:null}getCellNodeFromCordsOrThrow(n,r,i){const s=this.getCellNodeFromCords(n,r,i);if(!s)throw new Error("Node at cords not TableCellNode.");return s}getRowStriping(){return!!this.getLatest().__rowStriping}setRowStriping(n){const r=this.getWritable();return r.__rowStriping=n,r}setFrozenColumns(n){const r=this.getWritable();return r.__frozenColumnCount=n,r}getFrozenColumns(){return this.getLatest().__frozenColumnCount}setFrozenRows(n){const r=this.getWritable();return r.__frozenRowCount=n,r}getFrozenRows(){return this.getLatest().__frozenRowCount}canSelectBefore(){return!0}canIndent(){return!1}getColumnCount(){const n=this.getFirstChild();if(!n)return 0;let r=0;return n.getChildren().forEach(i=>{yt(i)&&(r+=i.getColSpan())}),r}};function kRe(e,t){const n=e.getElementByKey(t.getKey());return n===null&&Et(230),fm(t,n)}function ERe(e){const t=fy();e.hasAttribute("data-lexical-row-striping")&&t.setRowStriping(!0),e.hasAttribute("data-lexical-frozen-column")&&t.setFrozenColumns(1),e.hasAttribute("data-lexical-frozen-row")&&t.setFrozenRows(1);const n=e.querySelector(":scope > colgroup");if(n){let r=[];for(const i of n.querySelectorAll(":scope > col")){let s=i.style.width||"";if(!um.test(s)&&(s=i.getAttribute("width")||"",!/^\d+$/.test(s))){r=void 0;break}r.push(parseFloat(s))}r&&t.setColWidths(r)}return{after:r=>zw(r,ur),node:t}}function fy(){return ai(new Kc)}function pr(e){return e instanceof Kc}function NRe(e){ur(e.getParent())?e.isEmpty()&&e.append(Tt()):e.remove()}function TRe(e){pr(e.getParent())?VY(e,yt):e.remove()}function ARe(e){VY(e,ur);const[t]=Ec(e,null,null),n=t.reduce((o,a)=>Math.max(o,a.length),0),r=e.getChildren();for(let o=0;o<t.length;++o){const a=r[o];if(!a)continue;ur(a)||Et(254,a.constructor.name,a.getType());const l=t[o].reduce((d,h)=>h?1+d:d,0);if(l!==n)for(let d=l;d<n;++d){const h=no();h.append(Tt()),a.append(h)}}const i=e.getColWidths(),s=e.getColumnCount();if(i&&i.length!==s){let o;if(s<i.length)o=i.slice(0,s);else if(i.length>0){const a=i[i.length-1];o=[...i,...Array(s-i.length).fill(a)]}e.setColWidths(o)}}function RRe(e){if(e.detail<3||!Wa(e.target))return!1;const t=Is(e.target);if(t===null)return!1;const n=Ut(t,r=>pe(r)&&!r.isInline());return n===null?!1:!!yt(n.getParent())&&(n.select(0),!0)}function MRe(){const e=ze();if(!_e(e))return!1;const t=zm(e.anchor.getNode());if(t===null)return!1;const n=Pn();if(!n.is(t.getParent())||n.getChildrenSize()!==1)return!1;const[r]=Ec(t,null,null);if(r.length===0||r[0].length===0)return!1;const i=r[0][0];if(!i||!i.cell)return!1;const s=r[r.length-1],o=s[s.length-1];if(!o||!o.cell)return!1;const a=CR(t,i.cell,o.cell);return mr(a),!0}function jRe(e){return e.registerNodeTransform(Rl,t=>{if(t.getColSpan()>1||t.getRowSpan()>1){const[,,n]=gl(t),[r]=ca(n,t,t),i=r.length,s=r[0].length;let o=n.getFirstChild();ur(o)||Et(175);const a=[];for(let l=0;l<i;l++){l!==0&&(o=o.getNextSibling(),ur(o)||Et(175));let d=null;for(let h=0;h<s;h++){const p=r[l][h],m=p.cell;if(p.startRow===l&&p.startColumn===h)d=m,a.push(m);else if(m.getColSpan()>1||m.getRowSpan()>1){yt(m)||Et(176);const v=no(m.__headerState);d!==null?d.insertAfter(v):QNe(o,v)}}}for(const l of a)l.setColSpan(1),l.setRowSpan(1)}})}function IRe(e,t=!0){const n=new fRe,r=(i,s,o)=>{const a=Vc(i,o),l=bRe(i,a,e,t,n);n.observers.set(s,[l,a])};return Si(vRe(e,n),e.registerCommand(pl,()=>xRe(n,e),cs),e.registerMutationListener(Kc,i=>{e.getEditorState().read(()=>{for(const[s,o]of i){const a=n.observers.get(s);if(o==="created"||o==="updated"){const{tableNode:l,tableElement:d}=vJ(s);a===void 0?r(l,s,d):d!==a[1]&&(a[0].removeListeners(),n.observers.delete(s),r(l,s,d))}else o==="destroyed"&&a!==void 0&&(a[0].removeListeners(),n.observers.delete(s))}},{editor:e})},{skipInitialization:!1}),()=>{for(const[,[i]]of n.observers)i.removeListeners()})}function PRe(e,t){e.hasNodes([Kc])||Et(255);const{hasNestedTables:n=Wc(!1)}=t??{};return Si(e.registerCommand(eRe,r=>(function({rows:i,columns:s,includeHeaders:o},a){const l=ze()||eo();if(!l||!_e(l)||!a&&zm(l.anchor.getNode()))return!1;const d=nRe(Number(i),Number(s),o);WY(d);const h=d.getFirstDescendant();return Pe(h)&&h.select(),!0})(r,n.peek()),Ft),e.registerCommand(kq,(r,i)=>e===i&&(function(s,o){const{nodes:a,selection:l}=s;if(!a.some(p=>pr(p)||KNe(p).some(m=>pr(m.node))))return!1;const d=hr(l),h=_e(l);return h&&Ut(l.anchor.getNode(),p=>yt(p))!==null&&Ut(l.focus.getNode(),p=>yt(p))!==null||d?a.length===1&&pr(a[0])?(function(p,m){const v=m.getStartEndPoints(),b=hr(m);if(v===null)return!1;const[x,S]=v,[C,k,w]=gl(x),N=Ut(S.getNode(),te=>yt(te));if(!(yt(C)&&yt(N)&&ur(k)&&pr(w)))return!1;const[A,T,M]=ca(w,C,N),[j]=Ec(p,null,null),P=A.length,D=P>0?A[0].length:0;let L=T.startRow,I=T.startColumn,$=j.length,H=$>0?j[0].length:0;if(b){const te=Ww(A,T,M),oe=te.maxRow-te.minRow+1,ue=te.maxColumn-te.minColumn+1;L=te.minRow,I=te.minColumn,$=Math.min($,oe),H=Math.min(H,ue)}let z=!1;const F=Math.min(P,L+$)-1,K=Math.min(D,I+H)-1,W=new Set;for(let te=L;te<=F;te++)for(let oe=I;oe<=K;oe++){const ue=A[te][oe];W.has(ue.cell.getKey())||ue.cell.__rowSpan===1&&ue.cell.__colSpan===1||(cRe(ue.cell),W.add(ue.cell.getKey()),z=!0)}let[V]=Ec(w.getWritable(),null,null);const X=$-P+L;for(let te=0;te<X;te++)iRe(V[P-1][0].cell);const G=H-D+I;for(let te=0;te<G;te++)sRe(V[0][D-1].cell,!0,!1);[V]=Ec(w.getWritable(),null,null);for(let te=L;te<L+$;te++)for(let oe=I;oe<I+H;oe++){const ue=te-L,de=oe-I,ee=j[ue][de];if(ee.startRow!==ue||ee.startColumn!==de)continue;const ne=ee.cell;if(ne.__rowSpan!==1||ne.__colSpan!==1){const ke=[],Se=Math.min(te+ne.__rowSpan,L+$)-1,Ne=Math.min(oe+ne.__colSpan,I+H)-1;for(let Xe=te;Xe<=Se;Xe++)for(let ht=oe;ht<=Ne;ht++){const St=V[Xe][ht];ke.push(St.cell)}aRe(ke),z=!0}const{cell:ie}=V[te][oe],ae=ne.getBackgroundColor();ae!=null&&ie.setBackgroundColor(ae);const Q=ie.getChildren();ne.getChildren().forEach(ke=>{Pe(ke)&&Tt().append(ke),ie.append(ke)}),Q.forEach(ke=>ke.remove())}if(b&&z){const[te]=Ec(w.getWritable(),null,null);te[T.startRow][T.startColumn].cell.selectEnd()}return!0})(a[0],l):!(h&&o.peek()&&!(function(p){return!!(hr(p)&&!p.focus.getNode().is(p.anchor.getNode())||_e(p)&&yt(p.anchor.getNode())&&!p.anchor.getNode().is(p.focus.getNode()))})(l)):!1})(r,n),Ft),e.registerCommand(aP,MRe,Jo),e.registerCommand(r1,RRe,Ft),e.registerNodeTransform(Kc,ARe),e.registerNodeTransform(Rh,TRe),e.registerNodeTransform(Rl,NRe))}const LRe={build:(e,t,n)=>iu(t),config:{hasCellBackgroundColor:!0,hasCellMerge:!0,hasHorizontalScroll:!0,hasNestedTables:!1,hasTabHandler:!0},name:"@lexical/table/Table",nodes:()=>[Kc,Rh,Rl],register(e,t,n){const r=n.getOutput();return Si(is(()=>{const i=r.hasHorizontalScroll.value;Kw(e)!==i&&(CRe(e,i),e.update(uNe))}),PRe(e,r),is(()=>IRe(e,r.hasTabHandler.value)),is(()=>r.hasCellMerge.value?void 0:jRe(e)),is(()=>r.hasCellBackgroundColor.value?void 0:e.registerNodeTransform(Rl,i=>{i.getBackgroundColor()!==null&&i.setBackgroundColor(null)})))}};function ORe(e){const t=[];let n=null;const r=()=>{if(n!==null){const i=n.getFirstChild();oi(i)&&n.getChildrenSize()===1&&i.remove()}};for(const i of e)TY(i)||Pe(i)||oi(i)?n!==null?n.append(i):(n=Tt().append(i),t.push(n)):(r(),t.push(i),n=null);return r(),t.length===0&&t.push(Tt()),t}const DRe=[{$import:(e,t)=>{const n=fy();t.hasAttribute("data-lexical-row-striping")&&n.setRowStriping(!0),t.hasAttribute("data-lexical-frozen-column")&&n.setFrozenColumns(1),t.hasAttribute("data-lexical-frozen-row")&&n.setFrozenRows(1);const r=t.querySelector(":scope > colgroup");if(r){let i=[];for(const s of r.querySelectorAll(":scope > col")){let o=s.style.width||"";if(!um.test(o)&&(o=s.getAttribute("width")||"",!/^\d+$/.test(o))){i=void 0;break}i.push(parseFloat(o))}i&&n.setColWidths(i)}return[n.splice(0,0,zw(e.$importChildren(t),ur))]},match:si.tag("table"),name:"@lexical/table/table"},{$import:(e,t)=>[Ed(um.test(t.style.height)?parseFloat(t.style.height):void 0).splice(0,0,zw(e.$importChildren(t),yt))],match:si.tag("tr"),name:"@lexical/table/tr"},{$import:(e,t)=>{const n=t.nodeName==="TH",r=um.test(t.style.width)?parseFloat(t.style.width):void 0;let i=An.NO_STATUS;if(n){const b=t.getAttribute("scope");if(b==="col")i=An.COLUMN;else if(b==="row")i=An.ROW;else{const x=t.parentElement,S=TNe(x)&&(x.parentElement&&x.parentElement.nodeName==="THEAD"||x.rowIndex===0),C=t.cellIndex===0;S&&(i|=An.ROW),C&&(i|=An.COLUMN),i===An.NO_STATUS&&(i=An.ROW)}}const s=no(i,t.colSpan,r);s.__rowSpan=t.rowSpan;const o=t.style.backgroundColor;o!==""&&(s.__backgroundColor=o);const a=t.style.verticalAlign;(function(b){return b==="middle"||b==="bottom"})(a)&&(s.__verticalAlign=a);const l=e.get(mx),d=l|(function(b){let x=0;const S=b.fontWeight;S!=="700"&&S!=="bold"||(x|=ex),b.fontStyle==="italic"&&(x|=tx);const C=(b.textDecoration||"").split(" ");return C.includes("underline")&&(x|=TA),C.includes("line-through")&&(x|=nx),x})(t.style),h=e.get(aR),p=t.style.color,m=p?{...h,color:p}:h,v=[];return d!==l&&v.push(Om(mx,d)),m!==h&&v.push(Om(aR,m)),[s.splice(0,0,ORe(e.$importChildren(t,{context:v})))]},match:si.tag("td","th"),name:"@lexical/table/cell"}];ru(zd,{rules:DRe});function TR(e){const t=e.trim(),n=t.startsWith("|")?t.slice(1):t;return(n.endsWith("|")?n.slice(0,-1):n).split("|").map(i=>i.trim())}function $Re(e){const t=TR(e);return t.length>0&&t.every(n=>/^:?-+:?$/.test(n.trim())&&n.trim().length>=1)}const zRe={type:"multiline-element",dependencies:[Kc,Rh,Rl],regExpStart:/^\|?[^|]*\|.*$/,regExpEnd:{optional:!0,regExp:/^\x00$/},handleImportAfterStartMatch({lines:e,rootNode:t,startLineIndex:n}){const r=e[n];if(r===void 0)return null;const i=e[n+1];if(i===void 0||!$Re(i))return null;const s=TR(r),o=s.length,a=[];let l=n+1;for(let p=n+2;p<e.length;p++){const m=e[p];if(m===void 0||!m.trim().includes("|")&&m.trim()!==""||m.trim()==="")break;a.push(TR(m)),l=p}const d=fy(),h=Ed();for(let p=0;p<o;p++){const m=no(An.ROW),v=Tt(),b=s[p]??"";v.append(Wn(b)),m.append(v),h.append(m)}d.append(h);for(const p of a){const m=Ed();for(let v=0;v<o;v++){const b=no(An.NO_STATUS),x=Tt(),S=p[v]??"";x.append(Wn(S)),b.append(x),m.append(b)}d.append(m)}return t.append(d),[!0,l]},replace(e,t,n,r,i,s){return!1},export(e,t){if(!pr(e))return null;const n=e.getChildren();if(n.length===0)return null;const r=[];return n.forEach((i,s)=>{if(!ur(i))return;const o=i.getChildren(),a=o.map(l=>yt(l)?t(l).trim():"");r.push(`| ${a.join(" | ")} |`),s===0&&r.push(`| ${o.map(()=>"---").join(" | ")} |`)}),r.join(`
2671
2671
  `)}},SJ=[zRe,NAe,...uJ],BRe={paragraph:"break-words mt-5 mb-3 first:mt-0 last:mb-0",quote:"my-2 mt-5 mb-3 first:mt-0 last:mb-0 border-l-2 border-border/80 pl-2 text-muted-foreground",heading:{h1:"text-[20px] font-normal leading-tight mt-5 mb-3 first:mt-0 last:mb-0",h2:"text-[18px] font-normal leading-tight mt-5 mb-3 first:mt-0 last:mb-0",h3:"text-[16px] font-normal leading-tight mt-5 mb-3 first:mt-0 last:mb-0",h4:"text-[16px] font-normal leading-tight mt-5 mb-3 first:mt-0 last:mb-0",h5:"text-[16px] font-normal leading-tight mt-5 mb-3 first:mt-0 last:mb-0",h6:"text-[16px] font-normal leading-tight mt-5 mb-3 first:mt-0 last:mb-0"},list:{ul:"list-disc ml-5 my-2",ol:"list-decimal ml-5 my-2",listitem:"my-0.5",nested:{listitem:"list-none"}},link:"text-primary underline underline-offset-2",text:{bold:"font-semibold",italic:"italic",strikethrough:"line-through",code:"break-all px-1 bg-border/60 py-0.5 rounded text-sm"},code:"block text-xs whitespace-pre"};function FRe(e){throw e}function WP(e){return{namespace:e.namespace,theme:BRe,nodes:[...e.nodes],editable:e.editable??!0,onError:FRe}}function URe(e,t){var n,r,i,s,o,a,l,d,h,p,m,v,b;return{...e,...t,terminal:{...e.terminal,...t.terminal},editor:{...e.editor,...t.editor},providerDefaults:{claude:{...e.providerDefaults.claude,...(n=t.providerDefaults)==null?void 0:n.claude,modelOptions:{...e.providerDefaults.claude.modelOptions,...(i=(r=t.providerDefaults)==null?void 0:r.claude)==null?void 0:i.modelOptions}},codex:{...e.providerDefaults.codex,...(s=t.providerDefaults)==null?void 0:s.codex,modelOptions:{...e.providerDefaults.codex.modelOptions,...(a=(o=t.providerDefaults)==null?void 0:o.codex)==null?void 0:a.modelOptions}},openrouter:{...e.providerDefaults.openrouter,...(l=t.providerDefaults)==null?void 0:l.openrouter,modelOptions:{}}},cloudflareTunnel:{...e.cloudflareTunnel,...t.cloudflareTunnel},claudeAuth:{tokens:((d=t.claudeAuth)==null?void 0:d.tokens)??e.claudeAuth.tokens,concurrencyDefault:((h=t.claudeAuth)==null?void 0:h.concurrencyDefault)??e.claudeAuth.concurrencyDefault},auth:{...e.auth,...t.auth},uploads:{...e.uploads,...t.uploads},subagents:e.subagents,customMcpServers:e.customMcpServers,customModels:e.customModels,textSnippets:e.textSnippets,claudeDriver:{preference:((p=t.claudeDriver)==null?void 0:p.preference)??e.claudeDriver.preference,lifecycle:{...e.claudeDriver.lifecycle,...(m=t.claudeDriver)==null?void 0:m.lifecycle}},globalPromptAppend:t.globalPromptAppend??e.globalPromptAppend,subagentRuntime:{runTimeoutMs:((v=t.subagentRuntime)==null?void 0:v.runTimeoutMs)??e.subagentRuntime.runTimeoutMs,defaultLoopSubagentId:((b=t.subagentRuntime)==null?void 0:b.defaultLoopSubagentId)!==void 0?t.subagentRuntime.defaultLoopSubagentId:e.subagentRuntime.defaultLoopSubagentId}}}const Ir=dr()(e=>({settings:null,hydrationStatus:"idle",setHydrationStatus:t=>e({hydrationStatus:t}),setFromServer:t=>e({settings:t,hydrationStatus:"ready"}),applyOptimisticPatch:t=>e(n=>({settings:n.settings?URe(n.settings,t):n.settings}))})),HRe=[],WRe=e=>{var t;return((t=e.settings)==null?void 0:t.customMcpServers)??HRe},VRe=[],hy=e=>{var t;return((t=e.settings)==null?void 0:t.customModels)??VRe},KRe=[],wJ=e=>{var t;return((t=e.settings)==null?void 0:t.textSnippets)??KRe},CJ=_.createContext(void 0),GRe=e=>e==="light"||e==="dark"||e==="system";function qRe(e){return e==="dark"?"black-translucent":"default"}function QF(e,t){if(typeof document>"u")return;let n=document.head.querySelector(`meta[name="${e}"]`);n||(n=document.createElement("meta"),n.setAttribute("name",e),document.head.appendChild(n)),n.setAttribute("content",t)}function e6(e){if(typeof document>"u"||typeof window>"u")return;const t=getComputedStyle(document.body).backgroundColor||getComputedStyle(document.documentElement).backgroundColor;t&&QF("theme-color",t),QF("apple-mobile-web-app-status-bar-style",qRe(e)),document.documentElement.style.colorScheme=e}const CS=()=>typeof window>"u"?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",t6=e=>{if(typeof document>"u")return;const t=e==="system"?CS():e;document.documentElement.classList.toggle("dark",t==="dark")},YRe=()=>{var t;const e=(t=Ir.getState().settings)==null?void 0:t.theme;return e&&GRe(e)?e:"system"};function XRe({children:e}){const t=Ir(o=>{var a;return(a=o.settings)==null?void 0:a.theme}),n=Ir(o=>o.applyOptimisticPatch),[r,i]=_.useState(YRe);_.useEffect(()=>{!t||t===r||i(t)},[t,r]),_.useEffect(()=>{t6(r)},[r]),_.useEffect(()=>{const o=r==="system"?CS():r;e6(o)},[r]),_.useEffect(()=>{if(r!=="system")return;const o=window.matchMedia("(prefers-color-scheme: dark)"),a=()=>{t6("system"),e6(CS())};return o.addEventListener?(o.addEventListener("change",a),()=>o.removeEventListener("change",a)):(o.addListener(a),()=>o.removeListener(a))},[r]);const s=_.useMemo(()=>{const o=r==="system"?CS():r;return{theme:r,resolvedTheme:o,setTheme:a=>{i(a),n({theme:a})}}},[n,r]);return u.jsx(CJ.Provider,{value:s,children:e})}function A1(){const e=_.useContext(CJ);if(!e)throw new Error("useTheme must be used within ThemeProvider");return e}const AR=tn("HighlightedCode",()=>e=>({highlighted:null,setHighlighted:t=>e({highlighted:t})})),JRe=200*1024,ZRe={ts:"typescript",typescript:"typescript",tsx:"tsx",js:"javascript",javascript:"javascript",jsx:"jsx",py:"python",python:"python",go:"go",golang:"go",rs:"rust",rust:"rust",java:"java",rb:"ruby",ruby:"ruby",sh:"bash",bash:"bash",zsh:"bash",shell:"bash",yml:"yaml",yaml:"yaml",css:"css",scss:"scss",html:"html",xml:"xml",json:"json",json5:"json5",md:"markdown",markdown:"markdown",sql:"sql",cpp:"cpp","c++":"cpp",c:"c",h:"c",swift:"swift",kt:"kotlin",kotlin:"kotlin",php:"php",toml:"toml",dockerfile:"dockerfile",diff:"diff",patch:"diff",vue:"vue",svelte:"svelte"};function QRe(e){return ZRe[e.toLowerCase()]??null}const eMe=/^<pre[^>]*>/,tMe=/<\/pre>\s*$/,nMe=/^<code[^>]*>/,rMe=/<\/code>\s*$/;function iMe(e){return e.replace(eMe,"").replace(tMe,"").replace(nMe,"").replace(rMe,"")}function sMe({source:e,lang:t}){const{resolvedTheme:n}=A1(),r=n==="dark"?"github-dark":"github-light",i=QRe(t),s=i!==null&&e.length<=JRe,o=AR.useScopedStore(h=>h.highlighted),a=AR.useScopedStore(h=>h.setHighlighted);_.useEffect(()=>{if(!s||i===null)return;let h=!1;return J(()=>Promise.resolve().then(()=>OG),void 0).then(async p=>{if(h)return;const m=await p.codeToHtml(e,{lang:i,theme:r});h||a({source:e,theme:r,lang:i,html:iMe(m)})}).catch(()=>{Qs.warn("[transcript] Shiki unavailable; falling back to plain code")}),()=>{h=!0}},[s,e,i,r,a]);const l=i??t.toLowerCase();return o!==null&&o.source===e&&o.theme===r&&o.lang===i?u.jsx("code",{className:`block text-xs whitespace-pre language-${l} shiki-highlighted`,dangerouslySetInnerHTML:{__html:o.html}}):u.jsx("code",{className:`block text-xs whitespace-pre language-${l}`,children:e})}function Ov({source:e,lang:t}){return u.jsx(AR.Provider,{init:void 0,children:u.jsx(sMe,{source:e,lang:t})})}const RR=tn("MessageCodeBlock",()=>e=>({copied:!1,setCopied:t=>e({copied:t})}));function oMe({source:e,lang:t}){const n=RR.useScopedStore(s=>s.copied),r=RR.useScopedStore(s=>s.setCopied),i=_.useCallback(async()=>{await navigator.clipboard.writeText(e),r(!0),setTimeout(()=>r(!1),2e3)},[e,r]);return u.jsxs("div",{className:"relative overflow-x-auto max-w-full min-w-0 no-code-highlight group/pre",children:[u.jsx("pre",{className:"min-w-0 rounded-xl py-2.5 px-3.5",children:t?u.jsx(Ov,{source:e,lang:t}):u.jsx("code",{className:"block text-xs whitespace-pre",children:e})}),u.jsx(Ie,{variant:"ghost",size:"icon","aria-label":n?"Copied":"Copy code",className:he("absolute top-[35px] -translate-y-[50%] -translate-x-[1px] rounded-md right-1.5 h-11 w-11 md:h-8 md:w-8 text-muted-foreground opacity-100 md:opacity-0 md:group-hover/pre:opacity-100 transition-opacity [@media(hover:none)]:!opacity-100",!n&&"hover:text-foreground",n&&"hover:!bg-transparent hover:!border-transparent"),onClick:i,children:n?u.jsx(ro,{className:"h-4 w-4 text-success"}):u.jsx(Oa,{className:"h-4 w-4"})})]})}function kJ({source:e,lang:t}){return u.jsx(RR.Provider,{init:void 0,children:u.jsx(oMe,{source:e,lang:t})})}const aMe=[pg,hg,su,Il,fg,dy,Bd,k1,Kc,Rh,Rl];let EJ=0;function Ai(){return String(EJ++)}function NJ(e){if(UP(e)){const n=e.getTag(),r=Ou(e),i={h1:"text-[20px] font-normal leading-tight mt-5 mb-3 first:mt-0 last:mb-0",h2:"text-[18px] font-normal leading-tight mt-5 mb-3 first:mt-0 last:mb-0",h3:"text-[16px] font-normal leading-tight mt-5 mb-3 first:mt-0 last:mb-0",h4:"text-[16px] font-normal leading-tight mt-5 mb-3 first:mt-0 last:mb-0",h5:"text-[16px] font-normal leading-tight mt-5 mb-3 first:mt-0 last:mb-0",h6:"text-[16px] font-normal leading-tight mt-5 mb-3 first:mt-0 last:mb-0"},s=i[n]??i.h1,o=Ai();switch(n){case"h1":return u.jsx("h1",{className:s,children:r},o);case"h2":return u.jsx("h2",{className:s,children:r},o);case"h3":return u.jsx("h3",{className:s,children:r},o);case"h4":return u.jsx("h4",{className:s,children:r},o);case"h5":return u.jsx("h5",{className:s,children:r},o);default:return u.jsx("h6",{className:s,children:r},o)}}if(gx(e))return u.jsx("blockquote",{className:"my-2 mt-5 mb-3 first:mt-0 last:mb-0 border-l-2 border-border/80 pl-2 text-muted-foreground",children:Ou(e)},Ai());if(ha(e))return u.jsx("p",{className:"break-words mt-5 mb-3 first:mt-0 last:mb-0",children:Ou(e)},Ai());if(uy(e)){const n=e.getLanguage()??"",r=e.getChildren().map(i=>Pe(i)||Dm(i)?i.getTextContent():oi(i)?`
2672
- `:"").join("");return u.jsx(kJ,{source:r,lang:n},Ai())}if(kt(e)){const n=e.getListType(),r=Ou(e),i=Ai();return n==="number"?u.jsx("ol",{className:"list-decimal ml-5 my-2",children:r},i):u.jsx("ul",{className:"list-disc ml-5 my-2",children:r},i)}if(xn(e)){const n=e.getChecked(),r=Ou(e),i=Ai();return n!==void 0?u.jsxs("li",{className:"my-0.5 list-none flex items-start gap-1.5",children:[u.jsx("input",{type:"checkbox",readOnly:!0,checked:n,className:"mt-[3px] shrink-0"}),u.jsx("span",{children:r})]},i):u.jsx("li",{className:"my-0.5",children:r},i)}if(Gs(e)||ed(e)){const n=e.getURL();return u.jsx("a",{href:n,className:"transition-all underline decoration-2 text-logo decoration-logo/50 hover:text-logo/70 dark:text-logo dark:decoration-logo/70 dark:hover:text-logo/60 dark:hover:decoration-logo/40",target:"_blank",rel:"noopener noreferrer",children:Ou(e)},Ai())}if(pr(e)){const n=e.getChildren(),r=n[0],i=r!==void 0&&ur(r)&&r.getChildren().every(a=>yt(a)&&(a.getHeaderStyles()&An.ROW)!==0),s=i?r:void 0,o=i?n.slice(1):n;return u.jsx("div",{className:"border border-border rounded-xl overflow-x-auto",children:u.jsxs("table",{className:"table-auto min-w-full divide-y divide-border bg-background",children:[s!==void 0&&u.jsx("thead",{children:u.jsx("tr",{children:s.getChildren().map(a=>u.jsx("th",{className:"text-left text-xs uppercase text-muted-foreground tracking-wider p-2 pl-0 first:pl-3 bg-muted dark:bg-card [&_*]:font-semibold",children:Ou(a)},Ai()))})}),u.jsx("tbody",{className:"divide-y divide-border",children:o.map(a=>ur(a)?u.jsx("tr",{children:a.getChildren().map(l=>yt(l)?u.jsx("td",{className:"text-left p-2 pl-0 first:pl-3 [&_*]:font-normal",children:Ou(l)},Ai()):null)},Ai()):null)})]})},Ai())}if(oi(e))return u.jsx("br",{},Ai());if(Pe(e))return lMe(e);if(Dm(e))return u.jsx("code",{className:"break-all px-1 bg-border/60 py-0.5 rounded text-sm",children:e.getTextContent()},Ai());const t=e.getTextContent();return t?u.jsx("span",{children:t},Ai()):null}function lMe(e){const t=e.getFormat(),n=e.getTextContent(),r=(t&ex)!==0,i=(t&tx)!==0,s=(t&nx)!==0,o=(t&qI)!==0;let a=n;return o?u.jsx("code",{className:"break-all px-1 bg-border/60 py-0.5 rounded text-sm",children:n},Ai()):(s&&(a=u.jsx("del",{className:"line-through",children:a},Ai())),i&&(a=u.jsx("em",{className:"italic",children:a},Ai())),r&&(a=u.jsx("strong",{className:"font-semibold",children:a},Ai())),!r&&!i&&!s?n:a)}function Ou(e){return e.getChildren().map(NJ)}function cMe(){EJ=0;const t=Pn().getChildren();return u.jsx(u.Fragment,{children:t.map(NJ)})}function Gc(e,t=SJ){const n=DY(WP({namespace:"kanna-md-renderer",nodes:aMe,editable:!1}));return n.update(()=>{dJ(e,t,void 0,!0)},{discrete:!0}),n.getEditorState().read(()=>cMe())}const kS=new Map;function uMe(e){return`${e.id}|${e.contentUrl}|${e.size??0}`}function dMe(e,t){return t.type==="setLoadState"?{...e,loadState:t.payload}:{lastKey:t.newKey,loadState:kS.get(t.newKey)??{status:"loading"}}}function py(e){const t=uMe(e),n=kS.get(t),[{loadState:r,lastKey:i},s]=_.useReducer(dMe,{loadState:n??{status:"loading"},lastKey:t}),o=_.useRef(t);return o.current=t,i!==t&&s({type:"resetForKey",newKey:t}),_.useEffect(()=>{if(n&&n.status!=="loading")return;let a=!1;const l=t;return KI(e.contentUrl,VG).then(d=>{if(a||o.current!==l)return;const h={status:"ready",content:d.content,truncated:d.truncated};kS.set(l,h),s({payload:h,type:"setLoadState"})}).catch(d=>{if(a||o.current!==l)return;const p={status:"error",message:d instanceof Error?d.message:"Unable to load preview."};kS.set(l,p),s({payload:p,type:"setLoadState"})}),()=>{a=!0}},[n,t,e.contentUrl]),r}function fMe({source:e}){const t=py(e);return t.status==="loading"?u.jsxs("div",{className:"p-4 text-sm text-muted-foreground",children:[u.jsx("div",{className:"prose hidden"})," Loading…"]}):t.status==="error"?u.jsx("div",{className:"p-4 text-sm text-destructive",children:t.message}):u.jsxs("div",{className:"space-y-2 p-3",children:[t.truncated?u.jsx("div",{className:"rounded-xl border border-border bg-background px-3 py-2 text-xs text-muted-foreground",children:"Preview truncated to 1024 KB."}):null,u.jsx("div",{className:"prose prose-sm prose-invert max-w-none rounded-xl border border-border bg-background p-4",children:Gc(t.content)})]})}const MR=tn("TableBody",e=>t=>({state:e.initialState,setState:n=>t({state:n})})),ES=new Map;function TJ(e){return`${e.id}|${e.contentUrl}|${e.size??0}|${e.mimeType}`}function hMe({source:e}){const t=TJ(e),n=ES.get(t),r=MR.useScopedStore(h=>h.state),i=MR.useScopedStore(h=>h.setState),s=_.useRef(t);if(s.current=t,_.useEffect(()=>{if(n&&n.status!=="loading")return;const h=e.mimeType==="text/tab-separated-values"?" ":",";let p=!1;const m=t;return KI(e.contentUrl,VG).then(v=>{if(p||s.current!==m)return;const b={status:"ready",table:Gke(v.content,h),truncated:v.truncated};ES.set(m,b),i(b)}).catch(v=>{if(p||s.current!==m)return;const b={status:"error",message:v instanceof Error?v.message:"Unable to load preview."};ES.set(m,b),i(b)}),()=>{p=!0}},[n,t,e.contentUrl,e.mimeType,i]),r.status==="loading")return u.jsxs("div",{className:"p-4 text-sm text-muted-foreground",children:[u.jsx("table",{className:"sr-only"})," Loading…"]});if(r.status==="error")return u.jsxs("div",{className:"p-4 text-sm text-destructive",children:[u.jsx("table",{className:"sr-only"})," ",r.message]});const{table:o}=r,[a,...l]=o.rows,d=[r.truncated?"Preview truncated to 1024 KB.":null,o.truncatedRows?`Showing first ${o.rows.length} of ${o.rowCount} rows.`:null,o.truncatedColumns?`Showing first ${SA} of ${o.columnCount} columns.`:null].filter(Boolean);return u.jsxs("div",{className:"space-y-2 p-3",children:[d.length?u.jsx("div",{className:"rounded-xl border border-border bg-background px-3 py-2 text-xs text-muted-foreground",children:d.join(" ")}):null,u.jsx("div",{className:"overflow-x-auto rounded-xl border border-border bg-background",children:u.jsxs("table",{className:"min-w-full border-collapse text-xs",children:[a?u.jsx("thead",{className:"sticky top-0 bg-muted",children:u.jsx("tr",{children:a.map((h,p)=>u.jsx("th",{className:"border-b border-border px-3 py-2 text-left font-medium",children:h||" "},p))})}):null,u.jsx("tbody",{children:l.map((h,p)=>u.jsx("tr",{className:"odd:bg-background even:bg-muted/20",children:h.map((m,v)=>u.jsx("td",{className:"max-w-[320px] border-b border-border px-3 py-2 align-top",children:u.jsx("div",{className:"whitespace-pre-wrap break-words",children:m||" "})},v))},p))})]})})]})}function pMe({source:e}){const t=TJ(e),n=ES.get(t);return u.jsx(MR.Provider,{init:{initialState:n??{status:"loading"}},children:u.jsx(hMe,{source:e})})}function mMe({source:e}){const t=py(e);return t.status==="loading"?u.jsxs("div",{className:"p-4 text-sm text-muted-foreground",children:[u.jsx("pre",{className:"sr-only"})," Loading…"]}):t.status==="error"?u.jsxs("div",{className:"p-4 text-sm text-destructive",children:[u.jsx("pre",{className:"sr-only"})," ",t.message]}):u.jsxs("div",{className:"space-y-2 p-3",children:[t.truncated?u.jsx(gMe,{children:"Preview truncated to 1024 KB."}):null,u.jsx("pre",{className:"whitespace-pre-wrap break-words rounded-xl border border-border bg-background p-3 text-xs",children:t.content})]})}function gMe({children:e}){return u.jsx("div",{className:"rounded-xl border border-border bg-background px-3 py-2 text-xs text-muted-foreground",children:e})}function vMe({source:e}){const t=py(e),n=_.useMemo(()=>t.status==="ready"?Kke(t.content):"",[t]);return t.status==="loading"?u.jsxs("div",{className:"p-4 text-sm text-muted-foreground",children:[u.jsx("pre",{className:"sr-only"})," Loading…"]}):t.status==="error"?u.jsxs("div",{className:"p-4 text-sm text-destructive",children:[u.jsx("pre",{className:"sr-only"})," ",t.message]}):u.jsxs("div",{className:"space-y-2 p-3",children:[t.truncated?u.jsx("div",{className:"rounded-xl border border-border bg-background px-3 py-2 text-xs text-muted-foreground",children:"Preview truncated to 1024 KB."}):null,u.jsx("pre",{className:"whitespace-pre-wrap break-words rounded-xl border border-border bg-background p-3 text-xs",children:n})]})}function bMe({source:e}){return u.jsxs("div",{className:"flex h-full flex-col items-stretch justify-center gap-3 p-4",children:[u.jsx("div",{className:"text-sm font-medium text-foreground",children:e.displayName}),u.jsx("audio",{src:e.contentUrl,controls:!0,preload:"metadata",className:"w-full"})]})}function xMe({source:e}){return u.jsx("div",{className:"flex h-full items-center justify-center bg-black/40 p-2",children:u.jsx("video",{src:e.contentUrl,controls:!0,playsInline:!0,preload:"metadata",className:"max-h-[60dvh] w-full rounded-xl"})})}const jR=tn("CodeBody",()=>e=>({highlighted:null,setHighlighted:t=>e({highlighted:t})})),yMe=200*1024;function _Me(e){const t=e.lastIndexOf(".");if(t<0)return"text";const n=e.slice(t+1).toLowerCase();return{ts:"typescript",tsx:"tsx",js:"javascript",jsx:"jsx",py:"python",go:"go",rs:"rust",java:"java",rb:"ruby",sh:"bash",zsh:"bash",yml:"yaml",yaml:"yaml",css:"css",scss:"scss",html:"html",json:"json",md:"markdown",sql:"sql",cpp:"cpp",c:"c",h:"c",swift:"swift",kt:"kotlin",php:"php",toml:"toml"}[n]??"text"}function SMe({source:e}){const t=py(e),n=t.status==="ready"&&t.content.length<=yMe,r=n?`${e.id}|${e.contentUrl}|${e.size??0}|${t.content.length}`:null,i=jR.useScopedStore(o=>o.highlighted),s=jR.useScopedStore(o=>o.setHighlighted);return _.useEffect(()=>{if(!n||t.status!=="ready"||r===null)return;let o=!1;const a=r;return J(()=>Promise.resolve().then(()=>OG),void 0).then(async l=>{if(o)return;const d=await l.codeToHtml(t.content,{lang:_Me(e.fileName),theme:"github-dark"});o||s({key:a,html:d})}).catch(()=>{Qs.warn("[file-preview] Shiki unavailable; falling back to plain text")}),()=>{o=!0}},[n,r,t,e.fileName,s]),t.status==="loading"?u.jsxs("div",{className:"p-4 text-sm text-muted-foreground",children:[u.jsx("pre",{className:"sr-only"})," Loading…"]}):t.status==="error"?u.jsxs("div",{className:"p-4 text-sm text-destructive",children:[u.jsx("pre",{className:"sr-only"})," ",t.message]}):i&&i.key===r?u.jsx("div",{className:"overflow-x-auto p-3 text-xs",dangerouslySetInnerHTML:{__html:i.html}}):u.jsxs("div",{className:"space-y-2 p-3",children:[t.truncated?u.jsx("div",{className:"rounded-xl border border-border bg-background px-3 py-2 text-xs text-muted-foreground",children:"Preview truncated to 1024 KB."}):null,u.jsx("pre",{className:"whitespace-pre-wrap break-words rounded-xl border border-border bg-background p-3 text-xs",children:t.content})]})}function wMe({source:e}){return u.jsx(jR.Provider,{init:void 0,children:u.jsx(SMe,{source:e})})}const gf=tn("MermaidZoomModal",()=>e=>({scale:1,offset:{x:0,y:0},drag:null,setScale:t=>e({scale:t}),setOffset:t=>e({offset:t}),setDrag:t=>e({drag:t})}));function CMe({svg:e,onClose:t}){const n=gf.useScopedStore(m=>m.scale),r=gf.useScopedStore(m=>m.offset),i=gf.useScopedStore(m=>m.drag),s=gf.useScopedStore(m=>m.setScale),o=gf.useScopedStore(m=>m.setOffset),a=gf.useScopedStore(m=>m.setDrag);_.useEffect(()=>{const m=v=>{v.key==="Escape"&&t()};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[t]);const l=m=>Math.min(8,Math.max(.25,m)),d=m=>{a({x:m.clientX-r.x,y:m.clientY-r.y})},h=m=>{i&&o({x:m.clientX-i.x,y:m.clientY-i.y})},p=()=>a(null);return Rs.createPortal(u.jsxs("div",{className:"fixed inset-0 z-[100] flex flex-col bg-background/95",role:"dialog","aria-modal":"true","aria-label":"Diagram zoom view",children:[u.jsxs("div",{className:"flex justify-end gap-1 p-2",children:[u.jsx(Ie,{variant:"ghost",size:"icon","aria-label":"Zoom out",className:"h-9 w-9",onClick:()=>s(l(n-.25)),children:u.jsx(mH,{className:"h-4 w-4"})}),u.jsx(Ie,{variant:"ghost",size:"icon","aria-label":"Zoom in",className:"h-9 w-9",onClick:()=>s(l(n+.25)),children:u.jsx(Eo,{className:"h-4 w-4"})}),u.jsx(Ie,{variant:"ghost",size:"icon","aria-label":"Reset view",className:"h-9 w-9",onClick:()=>{s(1),o({x:0,y:0})},children:u.jsx(zoe,{className:"h-4 w-4"})}),u.jsx(Ie,{variant:"ghost",size:"icon","aria-label":"Close",className:"h-9 w-9",onClick:t,children:u.jsx(da,{className:"h-4 w-4"})})]}),u.jsx("div",{className:"flex-1 overflow-hidden touch-none cursor-grab active:cursor-grabbing",onPointerDown:d,onPointerMove:h,onPointerUp:p,onPointerLeave:p,children:u.jsx("div",{"data-mermaid-stage":!0,className:"w-full h-full flex items-center justify-center",style:{transform:`translate(${r.x}px, ${r.y}px) scale(${n})`},dangerouslySetInnerHTML:{__html:e}})})]}),document.body)}function kMe({svg:e,onClose:t}){return u.jsx(gf.Provider,{init:void 0,children:u.jsx(CMe,{svg:e,onClose:t})})}const uc=tn("MermaidDiagram",()=>e=>({renderState:{status:"loading"},showSource:!1,zoomOpen:!1,copied:!1,setRenderState:t=>e({renderState:t}),setShowSource:t=>e({showSource:t}),setZoomOpen:t=>e({zoomOpen:t}),setCopied:t=>e({copied:t})}));let _T=null;function EMe(){return _T||(_T=J(()=>import("./mermaid.core-CDfcYbPP.js").then(e=>e.bm),[]).then(e=>e.default)),_T}function NMe({source:e}){const{resolvedTheme:t}=A1(),n=t==="dark"?"dark":"default",r=uc.useScopedStore(x=>x.renderState),i=uc.useScopedStore(x=>x.showSource),s=uc.useScopedStore(x=>x.zoomOpen),o=uc.useScopedStore(x=>x.copied),a=uc.useScopedStore(x=>x.setRenderState),l=uc.useScopedStore(x=>x.setShowSource),d=uc.useScopedStore(x=>x.setZoomOpen),h=uc.useScopedStore(x=>x.setCopied),m=`mermaid-${_.useId().replace(/[^a-zA-Z0-9_-]/g,"")}`,v=_.useCallback(()=>d(!1),[d]),b=async()=>{await navigator.clipboard.writeText(e),h(!0),setTimeout(()=>h(!1),2e3)};return _.useEffect(()=>{let x=!1;return EMe().then(async S=>{S.initialize({startOnLoad:!1,securityLevel:"strict",theme:n});const{svg:C}=await S.render(m,e);x||a({status:"ready",svg:C})}).catch(()=>{x||a({status:"error"})}),()=>{x=!0}},[e,n,m,a]),r.status==="error"?u.jsx(QN,{source:e}):r.status==="loading"?u.jsx("div",{className:"relative group/mermaid",children:u.jsx(QN,{source:e})}):i?u.jsxs("div",{className:"relative group/mermaid",children:[u.jsx(QN,{source:e}),u.jsx(n6,{showSource:i,onToggleSource:()=>l(!i),onCopy:b,copied:o,onZoom:void 0})]}):u.jsxs("div",{className:"relative group/mermaid my-3",children:[u.jsx("div",{className:"flex justify-center overflow-x-auto",dangerouslySetInnerHTML:{__html:r.svg}}),u.jsx(n6,{showSource:i,onToggleSource:()=>l(!i),onCopy:b,copied:o,onZoom:()=>d(!0)}),s&&u.jsx(kMe,{svg:r.svg,onClose:v})]})}function AJ({source:e}){return u.jsx(uc.Provider,{init:void 0,children:u.jsx(NMe,{source:e})})}function n6({showSource:e,onToggleSource:t,onCopy:n,copied:r,onZoom:i}){return u.jsxs("div",{className:"absolute top-1.5 right-1.5 flex gap-1 opacity-100 md:opacity-0 md:group-hover/mermaid:opacity-100 transition-opacity [@media(hover:none)]:!opacity-100",children:[i&&!e&&u.jsx(Ie,{variant:"ghost",size:"icon","aria-label":"Zoom diagram",className:"h-8 w-8 rounded-md text-muted-foreground hover:text-foreground",onClick:i,children:u.jsx(uoe,{className:"h-4 w-4"})}),u.jsx(Ie,{variant:"ghost",size:"icon","aria-label":e?"View rendered diagram":"View diagram source",className:"h-8 w-8 rounded-md text-muted-foreground hover:text-foreground",onClick:t,children:u.jsx(a2,{className:"h-4 w-4"})}),u.jsx(Ie,{variant:"ghost",size:"icon","aria-label":r?"Copied":"Copy diagram source",className:he("h-8 w-8 rounded-md text-muted-foreground",!r&&"hover:text-foreground",r&&"hover:!bg-transparent"),onClick:n,children:r?u.jsx(ro,{className:"h-4 w-4 text-success"}):u.jsx(Oa,{className:"h-4 w-4"})})]})}function TMe({source:e}){const t=py(e);return t.status==="loading"?u.jsxs("div",{className:"p-4 text-sm text-muted-foreground",children:[u.jsx("div",{className:"hidden"})," Loading…"]}):t.status==="error"?u.jsx("div",{className:"p-4 text-sm text-destructive",children:t.message}):u.jsx("div",{className:"p-4",children:u.jsx(AJ,{source:t.content})})}async function AMe(e){var n;const t=MMe(e.contentUrl);if("share"in navigator&&typeof navigator.share=="function")try{return await navigator.share({title:e.displayName,url:t}),"shared"}catch(r){if(r instanceof DOMException&&r.name==="AbortError")return"shared"}if((n=navigator.clipboard)!=null&&n.writeText)try{return await navigator.clipboard.writeText(t),"copied"}catch{return"failed"}return"failed"}function RMe(e){const t=document.createElement("a");t.href=e.contentUrl,t.download=e.fileName,t.rel="noopener",document.body.appendChild(t),t.click(),t.remove()}function MMe(e){return typeof window>"u"?e:new URL(e,document.baseURI||window.location.href).toString()}const IR=tn("SheetBody",()=>e=>({dy:0,setDy:t=>e({dy:t})}));function Mh({source:e,open:t,onOpenChange:n}){const r=_.useCallback(()=>n(!1),[n]);return u.jsx($a,{open:t&&e!==null,onOpenChange:n,children:u.jsx(ia,{size:"lg",className:"inset-0 h-[100dvh] max-h-none w-full max-w-none translate-x-0 translate-y-0 rounded-none p-0 md:inset-auto md:left-1/2 md:top-1/2 md:h-auto md:max-h-[90dvh] md:w-auto md:max-w-3xl md:-translate-x-1/2 md:-translate-y-1/2 md:rounded-2xl",children:e?u.jsx(OMe,{source:e,onClose:r}):null})})}const jMe=120,IMe=.5;function PMe({startY:e,lastY:t,lastT:n,endY:r,now:i}){const s=r-e,o=Math.max(1,i-n),a=(r-t)/o;return s>jMe||a>IMe}function LMe({source:e,onClose:t}){const n=$Me(e),r=IR.useScopedStore(p=>p.dy),i=IR.useScopedStore(p=>p.setDy),s=_.useRef(null),o=_.useCallback(p=>{s.current={y:p.clientY,lastY:p.clientY,lastT:Date.now()};try{p.currentTarget.setPointerCapture(p.pointerId)}catch{}},[]),a=_.useCallback(p=>{if(!s.current)return;const m=p.clientY-s.current.y;m<0||(s.current.lastY=p.clientY,s.current.lastT=Date.now(),i(m))},[i]),l=_.useCallback(p=>{const m=s.current;s.current=null;try{p.currentTarget.releasePointerCapture(p.pointerId)}catch{}m&&(PMe({startY:m.y,lastY:m.lastY,lastT:m.lastT,endY:p.clientY,now:Date.now()})?t():i(0))},[t,i]),d=_.useCallback(()=>{AMe(e)},[e]),h=_.useCallback(()=>RMe(e),[e]);return u.jsxs("div",{className:"flex min-h-0 flex-1 flex-col",style:r>0?{transform:`translateY(${r}px)`,transition:"none"}:void 0,children:[u.jsxs("div",{onPointerDown:o,onPointerMove:a,onPointerUp:l,onPointerCancel:l,className:"border-b border-border px-4 py-3 touch-none",children:[u.jsx("div",{className:"mx-auto mb-2 h-1 w-12 rounded-full bg-muted md:hidden",role:"button","aria-label":"Drag down to close"}),u.jsx(za,{className:"truncate text-base",children:e.displayName}),u.jsx(jx,{className:"truncate text-xs",children:n})]}),u.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto overscroll-contain touch-pan-y [-webkit-overflow-scrolling:touch]",role:"region","aria-label":"File preview",children:_.createElement(DMe(e),{source:e})},e.id),u.jsxs("div",{className:"flex items-center justify-end gap-2 border-t border-border px-4 py-3",children:[u.jsxs(Ie,{type:"button",variant:"outline",onClick:d,children:[u.jsx(eae,{className:"mr-2 h-4 w-4"}),"Share"]}),e.origin==="offer_download"?u.jsxs(Ie,{type:"button",onClick:h,children:[u.jsx(qM,{className:"mr-2 h-4 w-4"}),"Download"]}):null]})]})}function OMe({source:e,onClose:t}){return u.jsx(IR.Provider,{init:void 0,children:u.jsx(LMe,{source:e,onClose:t})})}function DMe(e){const t={id:e.id,displayName:e.displayName,mimeType:e.mimeType,size:e.size??0,contentUrl:e.contentUrl,relativePath:e.relativePath??""},n=Ch(t);return n==="image"?lEe:n==="pdf"?Hz:n==="audio"?bMe:n==="video"?xMe:n==="table"?pMe:n==="markdown"?fMe:n==="json"?vMe:n==="mermaid"?TMe:n==="code"?wMe:ag(t).kind==="external"?Hz:mMe}function $Me(e){const t={id:e.id,displayName:e.displayName,mimeType:e.mimeType,size:e.size??0,contentUrl:e.contentUrl,relativePath:e.relativePath??""},n=Ch(t),r=Xx(n,e.mimeType),i=e.size?` · ${kh(e.size)}`:"";return`${r}${i}`}function mg(e,t){return{id:e.id,contentUrl:e.contentUrl,displayName:e.displayName,fileName:e.displayName,relativePath:e.relativePath,mimeType:e.mimeType,size:e.size,origin:t}}const jc=_.forwardRef(({className:e,...t},n)=>u.jsx("textarea",{"data-gramm":"false","data-gramm_editor":"false","data-enable-grammarly":"false","data-1p-ignore":!0,autoComplete:"off",className:he("flex w-full rounded-lg border border-border bg-background px-2.5 py-2 text-sm placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),ref:n,...t}));jc.displayName="Textarea";const zMe=new Set(["changes","history"]),BMe=new Set(["public","private"]),FMe=new Set(["branches","pull_requests"]);function UMe(e){return zMe.has(e)}function HMe(e){return BMe.has(e)}function WMe(e){return FMe.has(e)}const k0={};function r6(e){return!e.isCollapsed&&!e.hasPreviewAttachment&&e.patch===void 0&&e.patchError===void 0&&!e.isPatchLoading}function VMe(e,t){return!e||!t.mimeType||typeof t.size!="number"||t.changeType==="deleted"||!t.mimeType.startsWith("image/")&&t.mimeType!=="application/pdf"?null:{id:`diff:${t.path}`,kind:t.mimeType.startsWith("image/")?"image":"file",displayName:t.path.split("/").pop()??t.path,absolutePath:t.path,relativePath:t.path,contentUrl:`/api/projects/${e}/files/${encodeURIComponent(t.path)}/content`,mimeType:t.mimeType,size:t.size}}function RJ(e){return e.isUntracked}function KMe(e){return RJ(e)?e.path.includes("/"):!1}function ST(e){return u.jsxs(Js,{delayDuration:0,children:[u.jsx(Zs,{asChild:!0,children:u.jsx("button",{type:"button","aria-label":e.label,title:e.label,onClick:e.onClick,className:he("flex h-11 w-11 md:h-7 md:w-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",e.active&&"bg-accent text-foreground"),children:e.children})}),u.jsx(js,{children:e.label})]})}function MJ({checked:e,mixed:t=!1,label:n,className:r,onClick:i}){let s;return t?s=u.jsx(mH,{className:"h-3 w-3",strokeWidth:3}):e?s=u.jsx(ro,{className:"h-3 w-3",strokeWidth:3}):s=null,u.jsx("button",{type:"button","aria-label":n??(e?"Exclude file from commit":"Include file in commit"),"aria-checked":t?"mixed":e,"aria-pressed":t?"mixed":e,onClick:o=>{o.stopPropagation(),i()},className:he("flex size-4.5 shrink-0 items-center justify-center rounded border transition-colors",e||t?"border-foreground bg-foreground text-background":"border-border bg-background text-transparent",r),children:s})}function VP(e){const t=Date.parse(e);if(!Number.isFinite(t))return"";const n=Date.now()-t,r=6e4,i=60*r,s=24*i,o=7*s,a=30*s,l=365*s;return n<r?"just now":n<i?`${Math.round(n/r)}m ago`:n<s?`${Math.round(n/i)}hr ago`:n<o?`${Math.round(n/s)}d ago`:n<a?`${Math.round(n/o)}wk ago`:n<l?`${Math.round(n/a)}mo ago`:`${Math.round(n/l)}yr ago`}function GMe(e){return e?`Last fetched ${VP(e)}`:"No local fetch recorded"}function qMe({entry:e,isPendingPush:t=!1}){const n=VP(e.authoredAt),r=!!e.githubUrl;let i;return e.tags.length>0?i=u.jsxs("div",{className:"flex shrink-0 flex-wrap justify-end gap-1",children:[e.tags.map(s=>u.jsx("span",{className:"inline-flex items-center rounded-full bg-muted border border-border px-2 py-0.5 text-[11px]",children:s},s)),t?u.jsx("span",{className:"inline-flex items-center rounded-full bg-muted border border-border px-2 py-0.5 text-[11px]",children:u.jsx(vb,{className:"size-3"})}):null]}):t?i=u.jsx("div",{className:"flex shrink-0 flex-wrap justify-end gap-1",children:u.jsx("span",{className:"inline-flex items-center rounded-full bg-muted border border-border px-2 py-0.5 text-[11px]",children:u.jsx(vb,{className:"size-3"})})}):i=null,u.jsxs("button",{type:"button",disabled:!r,onClick:()=>{!e.githubUrl||typeof window>"u"||window.open(e.githubUrl,"_blank","noopener,noreferrer")},className:he("flex w-full items-start gap-3 rounded-lg border border-border bg-background pl-3 pr-2 py-2 text-left transition-colors",r?"hover:bg-accent":"cursor-default opacity-60"),children:[u.jsxs("div",{className:"min-w-0 flex-1",children:[u.jsx("div",{className:"truncate text-sm font-medium text-foreground",children:e.summary}),e.description?u.jsx("div",{className:"mt-1 line-clamp-2 whitespace-pre-wrap text-xs text-muted-foreground",children:e.description}):null,u.jsxs("div",{className:"mt-1 flex min-w-0 items-center gap-1 text-xs text-muted-foreground",children:[e.authorName?u.jsx("span",{className:"truncate",children:e.authorName}):null,e.authorName&&n?u.jsx("span",{"aria-hidden":"true",children:"•"}):null,n?u.jsx("span",{children:n}):null]})]}),i]})}function i6(e){switch(e.kind){case"local":return 0;case"pull_request":return 1;case"remote":default:return 2}}function YMe(e){const t=new Map;for(const n of e){const r=t.get(n.name);(!r||i6(n)<i6(r))&&t.set(n.name,n)}return t}function XMe(e,t){const n=YMe([...e.local,...e.pullRequests,...e.remote]);t&&n.delete(t);const r=new Set,i=e.defaultBranchName?n.get(e.defaultBranchName):void 0;i&&r.add(i.name);const s=e.recent.map(a=>n.get(a.name)??a).filter(a=>!!a&&!r.has(a.name));for(const a of s)r.add(a.name);const o=[...n.values()].filter(a=>!r.has(a.name)).sort((a,l)=>a.displayName.localeCompare(l.displayName));return{defaultBranch:i,recent:s,other:o}}function JMe({open:e,onOpenChange:t,onGetGitHubPublishInfo:n,onCheckGitHubRepoAvailability:r,onPublish:i}){const s=at(L=>L.publishInfo),o=at(L=>L.isLoadingPublishInfo),a=at(L=>L.publishOwner),l=at(L=>L.publishName),d=at(L=>L.publishVisibility),h=at(L=>L.publishDescription),p=at(L=>L.publishAvailability),m=at(L=>L.isCheckingPublishAvailability),v=at(L=>L.isPublishing),b=at(L=>L.setPublishInfo),x=at(L=>L.setIsLoadingPublishInfo),S=at(L=>L.setPublishOwner),C=at(L=>L.setPublishName),k=at(L=>L.setPublishVisibility),w=at(L=>L.setPublishDescription),N=at(L=>L.setPublishAvailability),A=at(L=>L.setIsCheckingPublishAvailability),T=at(L=>L.setIsPublishing);_.useEffect(()=>{if(!e)return;let L=!1;return x(!0),N(null),n().then(I=>{L||(b(I),S(I.owners[0]??I.activeAccountLogin??""),C(I.suggestedRepoName),k("private"),w(""))}).finally(()=>{L||x(!1)}),()=>{L=!0}},[n,e,N,w,b,x,C,S,k]),_.useEffect(()=>{if(!e||!(s!=null&&s.ghInstalled)||!s.authenticated)return;const L=a.trim(),I=l.trim();if(!L||!I){N(null);return}let $=!1;A(!0);const H=window.setTimeout(()=>{r({owner:L,name:I}).then(z=>{$||N(z)}).finally(()=>{$||A(!1)})},250);return()=>{$=!0,window.clearTimeout(H)}},[s==null?void 0:s.authenticated,s==null?void 0:s.ghInstalled,l,r,e,a,N,A]);async function M(){if(!(!a.trim()||!l.trim())){T(!0);try{const L=await i({owner:a.trim(),name:l.trim(),visibility:d,description:h});Wi(L)&&L.ok&&t(!1)}finally{T(!1)}}}const j=!!(s!=null&&s.ghInstalled&&s.authenticated&&a.trim()&&l.trim()&&(p!=null&&p.available)&&!m&&!v);let P;m?P=u.jsx("div",{className:"pointer-events-none absolute inset-y-0 right-3 flex items-center text-muted-foreground",children:u.jsx(In,{className:"size-4 animate-spin"})}):p?P=u.jsx("div",{className:"absolute inset-y-0 right-2 flex items-center",children:u.jsxs(Js,{delayDuration:0,children:[u.jsx(Zs,{asChild:!0,children:u.jsx("button",{type:"button",tabIndex:-1,"aria-label":p.message,className:he("flex size-6 items-center justify-center rounded-md",p.available?"text-success":"text-destructive"),children:p.available?u.jsx(ro,{className:"size-4"}):u.jsx(xb,{className:"size-4"})})}),u.jsx(js,{children:p.message})]})}):P=null;let D;return o?D=u.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[u.jsx(In,{className:"size-4 animate-spin"}),u.jsx("span",{children:"Checking GitHub CLI…"})]}):s&&!s.ghInstalled?D=u.jsxs("div",{className:"space-y-2 text-sm text-muted-foreground",children:[u.jsx("p",{children:"GitHub CLI is not installed."}),u.jsx("div",{className:"rounded-lg border border-border px-3 py-2 font-mono text-xs text-foreground",children:"brew install gh"}),u.jsx("p",{children:"Then run:"}),u.jsx("div",{className:"rounded-lg border border-border px-3 py-2 font-mono text-xs text-foreground",children:"gh auth login"})]}):s&&!s.authenticated?D=u.jsxs("div",{className:"space-y-2 text-sm text-muted-foreground",children:[u.jsx("p",{children:"GitHub CLI is installed but not signed in."}),u.jsx("div",{className:"rounded-lg border border-border px-3 py-2 font-mono text-xs text-foreground",children:"gh auth login"})]}):D=u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"space-y-2",children:u.jsxs(Yo,{value:a,onValueChange:S,children:[u.jsx(So,{className:"pl-[11px] [&>span]:flex [&>span]:items-center [&>span]:gap-2",children:u.jsx(Ta,{placeholder:"Select owner"})}),u.jsx(wo,{children:((s==null?void 0:s.owners)??[]).map(L=>u.jsx(ri,{value:L,children:u.jsxs("span",{className:"flex items-center gap-2",children:[L===(s==null?void 0:s.activeAccountLogin)?u.jsx(dC,{className:"size-4 text-muted-foreground"}):u.jsx(Nie,{className:"size-4 text-muted-foreground"}),u.jsx("span",{className:"pl-[1px]",children:L})]})},L))})]})}),u.jsx("div",{className:"space-y-2",children:u.jsxs("div",{className:"relative",children:[u.jsx(dn,{value:l,onChange:L=>C(L.target.value),placeholder:"my-repo",className:"pl-9 pr-10"}),u.jsx(Noe,{className:"pointer-events-none absolute inset-y-0 left-3 my-auto size-4 text-muted-foreground"}),P]})}),u.jsx("div",{className:"space-y-2",children:u.jsxs("div",{className:"relative",children:[u.jsx(Ax,{className:"pointer-events-none absolute left-3 top-3 size-4 text-muted-foreground"}),u.jsx(jc,{value:h,onChange:L=>w(L.target.value),rows:3,placeholder:"Optional description",className:"pl-9 outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"})]})}),u.jsx("div",{className:"space-y-2",children:u.jsxs(Yo,{value:d,onValueChange:L=>{HMe(L)&&k(L)},children:[u.jsx(So,{className:"pl-[11px] [&>span]:flex [&>span]:items-center [&>span]:gap-2",children:u.jsx(Ta,{placeholder:"Select visibility"})}),u.jsxs(wo,{children:[u.jsx(ri,{value:"private",children:u.jsxs("span",{className:"flex items-center gap-2",children:[u.jsx(ooe,{className:"size-4 text-muted-foreground"}),u.jsx("span",{className:"pl-[1px]",children:"Private"})]})}),u.jsx(ri,{value:"public",children:u.jsxs("span",{className:"flex items-center gap-2",children:[u.jsx(Wse,{className:"size-4 text-muted-foreground"}),u.jsx("span",{className:"pl-[1px]",children:"Public"})]})})]})]})})]}),u.jsx($a,{open:e,onOpenChange:t,children:u.jsxs(ia,{size:"sm",className:"max-w-[min(92vw,475px)]",children:[u.jsxs(El,{className:"space-y-2 px-4 pb-4 pt-4",children:[u.jsxs("div",{className:"space-y-1",children:[u.jsx(za,{children:"Push to GitHub"}),u.jsx(jx,{children:"Create a GitHub repository from this local project using GitHub CLI."})]}),D]}),u.jsxs(bd,{children:[u.jsx(Ie,{variant:"ghost",size:"sm",onClick:()=>t(!1),children:"Cancel"}),u.jsx(Ie,{size:"sm",disabled:!j,onClick:()=>void M(),children:v?u.jsxs(u.Fragment,{children:[u.jsx(In,{className:"mr-1.5 size-3.5 animate-spin"}),"Publishing…"]}):"Push to GitHub"})]})]})})}function jJ({value:e,onChange:t,placeholder:n,disabled:r,trailingAction:i}){return u.jsxs("div",{className:"relative",children:[u.jsx(Yp,{className:"pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),u.jsx(dn,{value:e,onChange:s=>t(s.target.value),placeholder:n,className:he("h-9 pl-7 text-sm",i?"pr-14":void 0),disabled:r}),i?u.jsx("div",{className:"absolute right-1 top-1/2 -translate-y-1/2",children:i}):null]})}function Of({title:e,entries:t,emptyLabel:n,selectedName:r,disabled:i,stickyTitle:s=!1,onSelect:o}){return t.length===0&&!n?null:u.jsxs("div",{className:"space-y-1",children:[u.jsx("div",{className:he("px-1 py-1 text-[11px] font-medium uppercase tracking-[0.08em] text-muted-foreground",s&&"sticky top-0 z-10 bg-background"),children:e}),t.length===0?u.jsx("div",{className:"px-1 py-1 text-xs text-muted-foreground",children:n}):t.map(a=>{const l=r===a.name;return u.jsxs("button",{type:"button",disabled:i,onClick:()=>o(a),className:he("flex w-full items-start gap-2 rounded-lg px-2 py-2 text-left transition-colors disabled:opacity-60",l?"bg-accent text-foreground":"hover:bg-accent"),children:[a.kind==="pull_request"?u.jsx(dH,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}):u.jsx(Sc,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}),u.jsxs("div",{className:"min-w-0 flex-1",children:[u.jsxs("div",{className:"flex w-full items-center gap-3",children:[u.jsx("div",{className:"min-w-0 flex-1 overflow-hidden whitespace-nowrap text-sm text-foreground",children:a.displayName}),a.updatedAt?u.jsx("div",{className:"ml-auto shrink-0 text-right text-[11px] text-muted-foreground",children:VP(a.updatedAt)}):null]}),a.kind==="pull_request"&&a.description||a.headLabel?u.jsx("div",{className:"truncate text-xs text-muted-foreground",children:a.kind==="pull_request"?a.description??a.headLabel??a.name:a.headLabel??void 0}):null]})]},a.id)})]})}function ZMe({open:e,onOpenChange:t,branchList:n,currentBranchName:r,onPreviewMergeBranch:i,onMergeBranch:s}){const o=at(z=>z.mergeBranchQuery),a=at(z=>z.mergeBranchSelectedName),l=at(z=>z.mergePreview),d=at(z=>z.mergePreviewError),h=at(z=>z.isMergePreviewLoading),p=at(z=>z.isMergeBranching),m=at(z=>z.setMergeBranchQuery),v=at(z=>z.setMergeBranchSelectedName),b=at(z=>z.setMergePreview),x=at(z=>z.setMergePreviewError),S=at(z=>z.setIsMergePreviewLoading),C=at(z=>z.setIsMergeBranching),k=at(z=>z.resetMergeBranchModal),w=at(z=>z.resetMergePreview),N=_.useMemo(()=>n?XMe(n,r):{defaultBranch:void 0,recent:[],other:[]},[n,r]),A=o.trim().toLowerCase(),T=_.useCallback(z=>A?[z.displayName,z.name,z.description,z.prTitle,z.headLabel].some(F=>F==null?void 0:F.toLowerCase().includes(A)):!0,[A]),M=N.defaultBranch&&T(N.defaultBranch)?N.defaultBranch:void 0,j=N.recent.filter(T),P=N.other.filter(T),D=_.useMemo(()=>a?[N.defaultBranch,...N.recent,...N.other].find(z=>z!==void 0&&z.name===a)??null:null,[N.defaultBranch,N.other,N.recent,a]);_.useEffect(()=>{e||k()},[e,k]),_.useEffect(()=>{if(!e||!D){w();return}let z=!1;return b(null),x(null),S(!0),i(D).then(F=>{z||b(F)}).catch(F=>{z||x(F instanceof Error?F.message:String(F))}).finally(()=>{z||S(!1)}),()=>{z=!0}},[i,e,w,D,S,b,x]);const L=!D||!l||h||p||l.status!=="mergeable";async function I(){if(!(!D||L)){C(!0);try{const z=await s(D);z!=null&&z.ok&&t(!1)}finally{C(!1)}}}let $;l?l.status==="up_to_date"?$=u.jsx(ro,{className:"mt-1 size-3.5 shrink-0 text-success"}):l.status==="conflicts"?$=u.jsx(xb,{className:"mt-1 size-3.5 shrink-0 text-warning"}):l.status==="mergeable"?$=u.jsx(uH,{className:"mt-1 size-3.5 shrink-0 text-muted-foreground"}):$=u.jsx(xb,{className:"mt-1 size-3.5 shrink-0 text-destructive"}):$=null;let H;return D?h?H=u.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[u.jsx(In,{className:"size-3.5 animate-spin"}),u.jsx("span",{children:"Checking merge preview…"})]}):d?H=u.jsx("div",{className:"text-sm text-destructive",children:d}):l?H=u.jsxs("div",{className:"flex items-start gap-2",children:[$,u.jsxs("div",{className:"min-w-0 space-y-1",children:[u.jsx("div",{className:"text-sm font-medium text-foreground",children:l.message}),l.detail?u.jsx("div",{className:"line-clamp-2 whitespace-pre-wrap text-xs text-muted-foreground",children:l.detail}):null]})]}):H=u.jsx("div",{className:"text-sm text-muted-foreground",children:"Preview unavailable."}):H=u.jsx("div",{className:"text-sm text-muted-foreground",children:"Select a branch to preview the merge."}),u.jsx($a,{open:e,onOpenChange:t,children:u.jsxs(ia,{size:"sm",className:"max-w-[min(92vw,475px)]",children:[u.jsxs(El,{className:"flex min-h-0 flex-col gap-3 px-4 pb-4 pt-4",children:[u.jsxs("div",{className:"space-y-1",children:[u.jsxs(za,{children:["Merge into ",r??"current branch"]}),u.jsx(jx,{children:"Choose a branch to continue."})]}),u.jsx(jJ,{value:o,onChange:m,placeholder:"Search branches"}),u.jsxs("div",{className:"max-h-[375px] space-y-3 overflow-y-auto pr-1",children:[u.jsx(Of,{title:"Default Branch",entries:M?[M]:[],emptyLabel:"No default branch available.",selectedName:a,onSelect:z=>v(z.name)}),u.jsx(Of,{title:"Recent Branches",entries:j,emptyLabel:"No recent branches.",selectedName:a,onSelect:z=>v(z.name)}),u.jsx(Of,{title:"Other Branches",entries:P,emptyLabel:"No other branches match this search.",selectedName:a,onSelect:z=>v(z.name)})]}),u.jsx("div",{className:"px-2",children:H})]}),u.jsx(bd,{children:u.jsxs("div",{className:"flex min-w-0 w-full items-center justify-end gap-2",children:[u.jsx(Ie,{variant:"ghost",size:"sm",onClick:()=>t(!1),children:"Cancel"}),u.jsx(Ie,{className:"max-w-full min-w-0",size:"sm",disabled:L,onClick:()=>void I(),children:p?u.jsxs(u.Fragment,{children:[u.jsx(In,{className:"mr-1.5 h-3.5 w-3.5 animate-spin"}),"Merging…"]}):u.jsx("span",{className:"block max-w-full truncate",children:"Merge"})})]})})]})})}function QMe({currentBranchName:e,onListBranches:t,onPreviewMergeBranch:n,onMergeBranch:r,onCheckoutBranch:i,onCreateBranch:s}){const o=at(X=>X.branchSwitcherOpen),a=at(X=>X.mergeModalOpen),l=at(X=>X.branchSwitcherIsLoading),d=at(X=>X.branchSwitcherIsMutating),h=at(X=>X.branchSwitcherQuery),p=at(X=>X.branchSwitcherEntryView),m=at(X=>X.branchList),v=at(X=>X.branchSwitcherError),b=at(X=>X.setBranchSwitcherOpen),x=at(X=>X.setMergeModalOpen),S=at(X=>X.setBranchSwitcherIsLoading),C=at(X=>X.setBranchSwitcherIsMutating),k=at(X=>X.setBranchSwitcherQuery),w=at(X=>X.setBranchSwitcherEntryView),N=at(X=>X.setBranchList),A=at(X=>X.setBranchSwitcherError);_.useEffect(()=>{o&&(S(!0),A(null),t().then(X=>N(X)).catch(X=>{A(X instanceof Error?X.message:String(X))}).finally(()=>{S(!1)}))},[t,o,N,A,S]);const T=h.trim().toLowerCase(),M=X=>X.filter(G=>T?[G.displayName,G.name,G.description,G.prTitle,G.headLabel].some(te=>te==null?void 0:te.toLowerCase().includes(T)):!0),j=(m==null?void 0:m.currentBranchName)??e,P=new Set(((m==null?void 0:m.pullRequests)??[]).map(X=>X.headRefName??X.name)),D=M((m==null?void 0:m.recent)??[]).filter(X=>X.name!==j),L=M((m==null?void 0:m.local)??[]).filter(X=>X.name!==j),I=M((m==null?void 0:m.remote)??[]).filter(X=>X.name!==j&&!P.has(X.name)),$=M((m==null?void 0:m.pullRequests)??[]).filter(X=>X.name!==j),H=(m==null?void 0:m.pullRequests.length)??0;async function z(X){C(!0);try{await i(X),b(!1),k(""),w("branches")}finally{C(!1)}}async function F(){C(!0);try{await s(),b(!1),k(""),w("branches")}finally{C(!1)}}function K(){b(!1),x(!0)}let W;(m==null?void 0:m.pullRequestsStatus)==="error"?W=m.pullRequestsError??"Could not load pull requests.":(m==null?void 0:m.pullRequestsStatus)==="unavailable"?W="Pull requests unavailable for this repository.":W="No open pull requests.";let V;return l?V=u.jsxs("div",{className:"flex items-center justify-center gap-2 py-6 text-sm text-muted-foreground",children:[u.jsx(In,{className:"h-4 w-4 animate-spin"}),u.jsx("span",{children:"Loading branches…"})]}):v?V=u.jsx("div",{className:"rounded-lg border border-border px-3 py-2 text-sm text-muted-foreground",children:v}):p==="pull_requests"?V=u.jsx(Of,{title:"Open PRs",entries:$,emptyLabel:W,disabled:d,stickyTitle:!0,onSelect:X=>{z(X)}}):V=u.jsxs("div",{className:"space-y-3",children:[u.jsx(Of,{title:"Recent",entries:D,emptyLabel:"No recent branches.",disabled:d,stickyTitle:!0,onSelect:X=>{z(X)}}),u.jsx(Of,{title:"Local",entries:L,emptyLabel:"No local branches.",disabled:d,stickyTitle:!0,onSelect:X=>{z(X)}}),u.jsx(Of,{title:"Remote",entries:I,emptyLabel:"No remote branches.",disabled:d,stickyTitle:!0,onSelect:X=>{z(X)}})]}),u.jsxs(Ld,{open:o,onOpenChange:b,children:[u.jsx(Od,{asChild:!0,children:u.jsxs("button",{type:"button",className:"flex min-w-0 max-w-full items-center gap-1 rounded-md px-1.5 py-1 text-sm transition-colors hover:bg-accent hover:text-foreground","aria-label":"Open branch switcher",children:[u.jsx(Sc,{className:"h-3.5 w-3.5 shrink-0"}),u.jsx("span",{className:"truncate",children:e??"Detached HEAD"}),u.jsx(Gm,{className:"h-3.5 w-3.5 shrink-0"})]})}),u.jsx(Zc,{align:"start",className:"w-[320px] p-2",children:u.jsxs("div",{className:"space-y-2",children:[u.jsx(jJ,{value:h,onChange:k,placeholder:p==="pull_requests"?"Search pull requests":"Search branches",disabled:l||d,trailingAction:u.jsx(Ie,{variant:"ghost",size:"sm",onClick:()=>void F(),disabled:l||d,className:"h-7 px-2 text-xs hover:!bg-transparent hover:!border-border/0",children:"+ New"})}),u.jsx(Ns,{value:p,onValueChange:X=>{WMe(X)&&w(X)},size:"sm",className:"w-full",optionClassName:"flex-1 justify-center",options:[{value:"branches",label:"Branches"},{value:"pull_requests",label:`Open PRs ${H}`}]}),u.jsx("div",{className:"max-h-[420px] overflow-y-auto pr-1.5 -mr-[8px]",children:V}),j?u.jsx(Ie,{variant:"default",size:"sm",disabled:l||d||!!v,onClick:K,className:"h-9 w-full justify-center rounded-lg px-3 text-sm",children:u.jsxs("span",{className:"block max-w-full truncate",children:[u.jsx(zse,{className:"mr-1.5 inline h-3.5 w-3.5 shrink-0"}),"Merge branch into ",j,"..."]})}):null]})}),u.jsx(ZMe,{open:a,onOpenChange:x,branchList:m,currentBranchName:j,onPreviewMergeBranch:n,onMergeBranch:r})]})}function eje({file:e,rootRef:t,projectId:n,isCollapsed:r,isChecked:i,editorLabel:s,diffRenderMode:o,wrapLines:a,onToggleCollapsed:l,onToggleChecked:d,fileActions:h,patch:p,patchError:m,isPatchLoading:v,onLoadPatch:b}){const x=RJ(e),S=KMe(e),C=_A.useScopedStore(z=>z.selectedAttachmentId),k=_A.useScopedStore(z=>z.setSelectedAttachmentId),w=_.useRef(null),N=_.useRef(null),{sentinelRef:A,isStuck:T}=Oke({rootRef:t,disabled:r}),M=_.useMemo(()=>VMe(n,e),[e,n]),j=M!==null,P=r6({isCollapsed:r,hasPreviewAttachment:j,patch:p,patchError:m,isPatchLoading:v});_.useEffect(()=>{if(!P)return;const z=`${e.path}\0${e.patchDigest}`;N.current!==z&&(N.current=z,b(e.path).catch(()=>{}))},[e.patchDigest,e.path,b,P]);function D(z){if(ag(z).openInNewTab){typeof window<"u"&&window.open(new URL(z.contentUrl,window.location.origin).toString(),"_blank","noopener,noreferrer");return}k(z.id)}function L(z){var K;z.preventDefault(),z.stopPropagation();const F=z.currentTarget.getBoundingClientRect();(K=w.current)==null||K.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,clientX:F.left+F.width/2,clientY:F.bottom,view:window}))}function I(){if(!r){l();return}if(j||p!==void 0){l();return}if(v)return;if(!(m!==void 0||r6({isCollapsed:!1,hasPreviewAttachment:j,patch:p,patchError:m,isPatchLoading:v}))){l();return}b(e.path).then(()=>{l()}).catch(()=>{})}let $;v&&r&&!M?$=u.jsx(In,{className:"h-3.5 w-3.5 shrink-0 animate-spin"}):r?$=u.jsx(Gm,{className:"h-3.5 w-3.5 shrink-0"}):$=u.jsx(sH,{className:"h-3.5 w-3.5 shrink-0"});let H;return M?H=u.jsx("div",{className:"flex justify-center p-3",children:M.kind==="image"?u.jsx(t1,{attachment:M,onClick:()=>D(M)}):u.jsx(ko,{attachment:M,onClick:()=>D(M)})}):v?H=u.jsxs("div",{className:"flex items-center justify-center px-3 py-8 text-sm text-muted-foreground",children:[u.jsx(In,{className:"mr-2 h-4 w-4 animate-spin"}),"Loading diff..."]}):m?H=u.jsx("div",{className:"px-3 py-4 text-sm text-destructive",children:m}):p!==void 0?H=u.jsx(Pke,{patch:p,options:{diffStyle:o,disableFileHeader:!0,disableBackground:!1,overflow:a?"wrap":"scroll",lineDiffType:"word",diffIndicators:"classic"}}):H=u.jsx("div",{className:"px-3 py-4 text-sm text-muted-foreground",children:"Diff unavailable."}),u.jsxs(bh,{children:[u.jsx(xh,{asChild:!0,children:u.jsxs("div",{ref:w,className:"relative rounded-lg border border-border bg-background",children:[r?null:u.jsx("div",{ref:A,className:"pointer-events-none absolute inset-x-0 top-0 h-px","aria-hidden":"true"}),u.jsxs("div",{role:"button",tabIndex:0,onClick:I,onKeyDown:z=>{z.key!=="Enter"&&z.key!==" "||(z.preventDefault(),I())},className:he("group/header sticky top-0 z-20 flex cursor-pointer items-center justify-between gap-3 bg-background pl-[7px] pr-2.5 py-1.5 text-[13px] text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",!r&&!T&&"rounded-t-[calc(theme(borderRadius.lg)-1px)]",r&&"rounded-[calc(theme(borderRadius.lg)-1px)]",!r&&"border-b border-border/50"),children:[u.jsxs("div",{className:"flex min-w-0 items-center",children:[u.jsx(MJ,{checked:i,onClick:d}),u.jsx("div",{className:"min-w-0 truncate select-none ml-2 mr-1",children:e.path})]}),u.jsxs("div",{className:"flex shrink-0 items-center gap-2 select-none",children:[u.jsxs("span",{className:"whitespace-nowrap text-xs font-mono",children:[e.additions>0?u.jsxs("span",{className:"text-success",children:["+",e.additions]}):null,e.deletions>0?u.jsxs("span",{className:e.additions>0?"ml-2 text-destructive":"text-destructive",children:["-",e.deletions]}):null]}),u.jsx("button",{type:"button","aria-label":`Open actions for ${e.path}`,onClick:L,className:"flex h-5 w-5 shrink-0 items-center justify-center rounded-sm text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",children:u.jsx(bb,{className:"h-3.5 w-3.5 shrink-0"})}),$]})]}),r?null:u.jsx("div",{className:"kanna-diff-patch overflow-hidden rounded-b-[calc(theme(borderRadius.lg)-1px)] pb-[1px]",children:H}),u.jsx(Mh,{source:M&&C===M.id?mg(M,"user_attachment"):null,open:M!==null&&C===M.id,onOpenChange:z=>!z&&k(null)})]},e.path)}),u.jsxs(Id,{children:[u.jsxs(br,{onSelect:z=>{z.stopPropagation(),h.onOpenFile(e.path)},children:[u.jsx(GM,{className:"h-3.5 w-3.5"}),u.jsxs("span",{className:"text-xs font-medium",children:["Open in ",s]})]}),u.jsxs(br,{onSelect:z=>{z.stopPropagation(),h.onOpenInFinder(e.path)},children:[u.jsx(cC,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"text-xs font-medium",children:"Open in Finder"})]}),u.jsxs(br,{onSelect:z=>{z.stopPropagation(),h.onDiscardFile(e.path)},className:"text-destructive hover:bg-destructive/10 focus:bg-destructive/10",children:[u.jsx(Yc,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"text-xs font-medium",children:"Discard Changes"})]}),u.jsxs(br,{disabled:!x,onSelect:z=>{z.stopPropagation(),x&&h.onIgnoreFile(e.path)},children:[u.jsx(k3,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"text-xs font-medium",children:"Ignore File"})]}),u.jsxs(br,{disabled:!S,onSelect:z=>{z.stopPropagation(),S&&h.onIgnoreFolder(e.path)},children:[u.jsx(k3,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"text-xs font-medium",children:"Ignore folder..."})]}),u.jsx(Y9,{}),u.jsxs(br,{onSelect:z=>{z.stopPropagation(),h.onCopyFilePath(e.path)},children:[u.jsx(Oa,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"text-xs font-medium",children:"Copy File Path"})]}),u.jsxs(br,{onSelect:z=>{z.stopPropagation(),h.onCopyRelativePath(e.path)},children:[u.jsx(Oa,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"text-xs font-medium",children:"Copy Relative Path"})]})]})]})}function tje({projectId:e,diffs:t,editorLabel:n,diffRenderMode:r,wrapLines:i,onOpenFile:s,onOpenInFinder:o,onDiscardFile:a,onIgnoreFile:l,onIgnoreFolder:d,onCopyFilePath:h,onCopyRelativePath:p,onListBranches:m,onPreviewMergeBranch:v,onMergeBranch:b,onCheckoutBranch:x,onCreateBranch:S,onGenerateCommitMessage:C,onInitializeGit:k,onGetGitHubPublishInfo:w,onCheckGitHubRepoAvailability:N,onSetupGitHub:A,onCommit:T,onSyncWithRemote:M,onLoadPatch:j,onDiffRenderModeChange:P,onWrapLinesChange:D}){var Yn;const L=_.useMemo(()=>({onOpenFile:s,onOpenInFinder:o,onDiscardFile:a,onIgnoreFile:l,onIgnoreFolder:d,onCopyFilePath:h,onCopyRelativePath:p}),[s,o,a,l,d,h,p]),I=t.files.length>0,$=at(ye=>ye.isGenerating),H=at(ye=>ye.commitModeInFlight),z=at(ye=>ye.isSyncing),F=at(ye=>ye.isGitHubPublishModalOpen),K=at(ye=>ye.patchesByPath),W=at(ye=>ye.patchErrorsByPath),V=at(ye=>ye.loadingPatchPaths),X=at(ye=>ye.setIsGenerating),G=at(ye=>ye.setCommitModeInFlight),te=at(ye=>ye.setIsSyncing),oe=at(ye=>ye.setIsGitHubPublishModalOpen),ue=at(ye=>ye.reconcilePatches),de=at(ye=>ye.setPatchLoading),ee=at(ye=>ye.clearPatchLoading),ne=at(ye=>ye.clearPatchError),ie=at(ye=>ye.setPatchResult),ae=at(ye=>ye.setPatchError),Q=_.useRef(null),ke=_.useRef(null),Se=_.useRef({}),Ne=_.useMemo(()=>t.files.map(ye=>ye.path),[t.files]),Xe=_.useMemo(()=>Ne.join("\0"),[Ne]),ht=I?"changes":"history",St=Ks(ye=>{var tt;return e?((tt=ye.projectUi[e])==null?void 0:tt.viewMode)??ht:ht}),Bt=Ks(ye=>{var tt;return e?((tt=ye.projectUi[e])==null?void 0:tt.collapsedPaths)??k0:k0}),Yt=Ks(ye=>{var tt;return e?((tt=ye.projectUi[e])==null?void 0:tt.summary)??"":""}),Mt=Ks(ye=>{var tt;return e?((tt=ye.projectUi[e])==null?void 0:tt.description)??"":""}),mn=Ks(ye=>ye.reconcileCollapsedPaths),Ge=Ks(ye=>ye.toggleCollapsedPath),Pt=Ks(ye=>ye.setViewMode),gn=Ks(ye=>ye.setCommitDraft),_t=Ks(ye=>ye.clearCommitDraft),jt=d0(ye=>e?ye.checkedPathsByProjectId[e]??k0:k0),Jt=d0(ye=>ye.reconcileProject),Wt=d0(ye=>ye.setChecked),Vt=d0(ye=>ye.setAllChecked),an=_.useRef(I);_.useEffect(()=>{e&&mn(e,Ne)},[Ne,Xe,e,mn]),_.useEffect(()=>{const ye=Object.fromEntries(t.files.map(zn=>[zn.path,zn.patchDigest]));ue(Ne,zn=>Se.current[zn]===ye[zn]),Se.current=ye},[t.files,Ne,Xe,ue]),_.useEffect(()=>{e&&Jt(e,Ne)},[Ne,Xe,e,Jt]),_.useEffect(()=>{if(!e)return;if(an.current!==I){Pt(e,I?"changes":"history"),an.current=I;return}an.current=I},[I,e,Pt]);const Nn=_.useMemo(()=>t.files.filter(ye=>jt[ye.path]??!0).map(ye=>ye.path),[jt,t.files]),Ue=Nn.length,nn=t.files.length>0&&Ue===t.files.length,_n=Ue>0&&Ue<t.files.length,Le=Yt.trim(),Ze=Le.length>0,Fe=H!==null,ot=$||Fe,Kt=((Yn=t.branchHistory)==null?void 0:Yn.entries)??[],ln=t.behindCount??0,Sn=t.aheadCount??0,rn=t.hasUpstream===!0,At=t.hasUpstream===!1&&!!t.branchName,Lt=t.hasOriginRemote===!0,Zt=t.branchName?t.branchName.split("/").map(ye=>encodeURIComponent(ye)).join("/"):null;let It;At?It="publish":ln>0?It="pull":It="fetch";const re=t.originRepoSlug&&Zt?`https://github.com/${t.originRepoSlug}/compare/${Zt}?expand=1`:null,Me=!!(rn&&re&&t.branchName&&t.branchName!==t.defaultBranchName),pt=t.status==="ready"&&Ue>0&&!ot,Ee=t.status==="ready"&&Ue>0&&Ze&&!ot,Ve=Lt?"commit_and_push":"commit_only",qe=t.branchName??"current branch";async function Qe(ye){if(Ee){G(ye);try{const tt=await T({paths:Nn,summary:Le,description:Mt.trim(),mode:ye});(tt!=null&&tt.ok||tt!=null&&tt.localCommitCreated)&&e&&_t(e)}finally{G(null)}}}async function mt(){if(pt){X(!0);try{const ye=await C({paths:Nn});e&&gn(e,{summary:ye.subject,description:ye.body})}finally{X(!1)}}}function Rt(ye){if(!(!(ye.metaKey||ye.ctrlKey)||ye.key!=="Enter")){if(ye.preventDefault(),Ze){Qe(Ve);return}mt()}}async function bt(ye=It){if(!(t.status!=="ready"||z)){te(!0);try{await M(ye)}finally{te(!1)}}}const Be=_.useCallback(async ye=>{var qr;const{patchesByPath:tt,loadingPatchPaths:zn}=at.getState();if(tt[ye]!==void 0||zn[ye])return tt[ye]??"";de(ye),ne(ye);try{const ce=await j(ye);ie(ye,ce);const Je=(qr=t.files.find(ut=>ut.path===ye))==null?void 0:qr.patchDigest;return Je&&(Se.current={...Se.current,[ye]:Je}),ce}catch(ce){const Je=ce instanceof Error?ce.message:String(ce);throw ae(ye,Je),ce}finally{ee(ye)}},[ne,ee,t.files,j,ae,de,ie]),Ot=_.useCallback(ye=>ye.path,[]),Ln=_.useCallback(({item:ye})=>{const tt=Bt[ye.path]??!0,zn=jt[ye.path]??!0;return u.jsx("div",{className:"pb-1.5",children:u.jsx(_A.Provider,{init:void 0,children:u.jsx(eje,{file:ye,rootRef:Q,projectId:e,isCollapsed:tt,isChecked:zn,editorLabel:n,diffRenderMode:r,wrapLines:i,onToggleCollapsed:()=>{e&&Ge(e,ye.path)},onToggleChecked:()=>{e&&Wt(e,ye.path,!zn)},fileActions:L,patch:K[ye.path],patchError:W[ye.path],isPatchLoading:!!V[ye.path],onLoadPatch:Be})})})},[jt,Bt,r,n,L,Be,V,W,K,e,Wt,Ge,i]);_.useEffect(()=>{var tt,zn;const ye=(zn=(tt=ke.current)==null?void 0:tt.getScrollableNode)==null?void 0:zn.call(tt);Q.current=ye instanceof HTMLElement?ye:null},[St,t.files.length]);let Ht;_n?Ht="Select all files for commit":nn?Ht="Unselect all files from commit":Ht="Select all files for commit";let Gt;t.status==="ready"?Lt?It==="publish"?Gt=u.jsxs(Ie,{variant:"ghost",size:"sm",onClick:()=>void bt(),disabled:z,className:"h-7 gap-1.5 px-2 text-xs hover:!bg-transparent hover:!border-border/0",children:[z?u.jsx(In,{className:"h-3.5 w-3.5 animate-spin"}):u.jsx(q0,{className:"h-3.5 w-3.5"}),u.jsx("span",{children:"Publish Branch"})]}):Gt=u.jsxs("div",{className:"flex items-center gap-1",children:[It==="fetch"?u.jsxs(Js,{delayDuration:0,children:[u.jsx(Zs,{asChild:!0,children:u.jsxs(Ie,{variant:"ghost",size:"sm",onClick:()=>void bt(),disabled:z,className:"h-7 gap-1.5 px-2 text-xs hover:!bg-transparent hover:!border-border/0",children:[z?u.jsx(In,{className:"h-3.5 w-3.5 animate-spin"}):u.jsx(ZM,{className:"h-3.5 w-3.5"}),u.jsx("span",{children:"Fetch"})]})}),u.jsx(js,{children:GMe(t.lastFetchedAt)})]}):u.jsxs(Ie,{variant:"ghost",size:"sm",onClick:()=>void bt(),disabled:z,className:"h-7 gap-1.5 px-2 text-xs hover:!bg-transparent hover:!border-border/0",children:[z?u.jsx(In,{className:"h-3.5 w-3.5 animate-spin"}):u.jsx(qM,{className:"h-3.5 w-3.5"}),u.jsx("span",{children:"Pull"}),u.jsx("span",{className:"inline-flex min-w-4 items-center justify-center rounded-full bg-muted px-1 text-[10px] text-muted-foreground",children:ln})]}),rn&&Sn>0?u.jsxs(Ie,{variant:"default",size:"sm",onClick:()=>void bt("push"),disabled:z,className:"h-7 gap-1.5 px-2 text-xs",children:[z?u.jsx(In,{className:"h-3.5 w-3.5 animate-spin"}):u.jsx(q0,{className:"h-3.5 w-3.5"}),u.jsx("span",{children:"Push"}),u.jsx("span",{className:"inline-flex min-w-4 items-center justify-center rounded-full bg-primary-foreground/15 px-1 text-[10px] text-primary-foreground",children:Sn})]}):null,Me&&re?u.jsxs(Ie,{variant:"ghost",size:"sm",onClick:()=>{typeof window>"u"||window.open(re,"_blank","noopener,noreferrer")},className:"h-7 gap-1.5 px-2 text-xs hover:!bg-transparent hover:!border-border/0",children:[u.jsx(dH,{className:"h-3.5 w-3.5"}),u.jsx("span",{children:"PR"})]}):null]}):Gt=u.jsxs(Ie,{variant:"default",size:"sm",onClick:()=>oe(!0),className:"h-7 gap-1.5 px-3 text-xs",children:[u.jsx(Use,{className:"h-3.5 w-3.5"}),u.jsx("span",{children:"Push to GitHub"})]}):Gt=null;let yr;t.status==="no_repo"?yr=u.jsx("div",{className:"flex h-full items-center justify-center px-6 py-3 text-center",children:u.jsxs("div",{className:"flex max-w-[280px] flex-col items-center gap-3",children:[u.jsx("p",{className:"text-sm text-muted-foreground",children:"Initialize git here to start tracking branches, diffs, and history."}),u.jsx(Ie,{size:"sm",onClick:()=>void k(),children:"Init Git"})]})}):St==="history"?Kt.length===0?yr=u.jsx("div",{className:"flex h-full items-center justify-center px-6 py-3 text-center",children:u.jsxs("p",{className:"text-sm text-muted-foreground",children:["No recent commits on ",t.branchName??"this branch","."]})}):yr=u.jsx("div",{className:"h-full overflow-y-auto [scrollbar-gutter:stable] space-y-1.5 p-1.5",children:Kt.map((ye,tt)=>u.jsx(qMe,{entry:ye,isPendingPush:tt<Sn},ye.sha))}):t.files.length===0?yr=u.jsx("div",{className:"flex h-full items-center justify-center px-6 py-3 text-center",children:u.jsx("p",{className:"text-sm text-muted-foreground",children:"No file changes."})}):yr=null;let Mn;Ze?Fe?Mn=u.jsx(In,{strokeWidth:2.5,className:"size-3 shrink-0 animate-spin"}):Ve==="commit_and_push"&&t.hasUpstream?Mn=u.jsx(q0,{strokeWidth:2.5,className:"size-3 shrink-0"}):Ve==="commit_and_push"?Mn=u.jsx(uH,{strokeWidth:2.5,className:"size-3 shrink-0"}):Mn=u.jsx(ro,{strokeWidth:2.5,className:"size-3 shrink-0"}):$?Mn=u.jsx(In,{strokeWidth:2.5,className:"size-3 shrink-0 animate-spin"}):Mn=u.jsx(koe,{strokeWidth:2.5,className:"size-3 shrink-0"});let qn;return Ze?Fe?qn=H==="commit_only"?"Committing...":"Committing & Pushing...":Ve==="commit_only"?qn=u.jsxs(u.Fragment,{children:["Commit to ",u.jsx(Sc,{strokeWidth:2.5,className:"mr-[4.5px] ml-0.5 inline size-3 "}),qe]}):t.hasUpstream?qn=u.jsxs(u.Fragment,{children:["Commit & push to ",u.jsx(Sc,{strokeWidth:2.5,className:"mr-[4.5px] ml-0.5 inline size-3 "}),qe]}):qn=u.jsxs(u.Fragment,{children:["Commit & publish ",u.jsx(Sc,{strokeWidth:2.5,className:"mr-[4.5px] ml-0.5 inline size-3 "}),qe]}):$?qn="Generating...":qn=u.jsxs(u.Fragment,{children:["Generate message for ",u.jsx(Sc,{strokeWidth:2.5,className:"mr-[4.5px] ml-0.5 inline size-3 "}),qe]}),u.jsx("div",{className:"h-full min-h-0 border-l border-border bg-background md:min-w-[370px]",children:u.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[u.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border pl-2.5 pr-2 py-2",children:[u.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:u.jsx(QMe,{currentBranchName:t.branchName,onListBranches:m,onPreviewMergeBranch:v,onMergeBranch:b,onCheckoutBranch:x,onCreateBranch:S})}),Gt]}),u.jsxs("div",{className:"relative min-h-0 flex-1",children:[u.jsx("div",{className:"sticky top-0 z-30 pl-[14px] pr-[12px] pt-[6px] bg-gradient-to-b from-background to-transparent",children:u.jsx("div",{className:"relative h-[40px] flex min-w-0 items-center justify-center gap-[13px]",children:u.jsxs("div",{className:"flex min-w-0 flex-1 items-center justify-between gap-[13px] relative",children:[St==="changes"?u.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground/70",children:[u.jsx(MJ,{checked:nn,mixed:_n,label:Ht,onClick:()=>{!e||t.files.length===0||Vt(e,Ne,_n?!0:!nn)}}),u.jsxs("span",{children:[Ue," files"]})]}):u.jsx("div",{}),u.jsx("div",{className:"pointer-events-none absolute left-1/2 -translate-x-1/2 top-1/2 -translate-y-1/2",children:u.jsx("div",{className:"pointer-events-auto",children:u.jsx(Ns,{value:St,onValueChange:ye=>{e&&UMe(ye)&&Pt(e,ye)},size:"sm",optionClassName:"flex-1 justify-center",options:[{value:"changes",label:"Changes"},{value:"history",label:"History"}]})})}),St==="changes"?u.jsxs("div",{className:"flex items-center gap-1",children:[u.jsx(ST,{label:"Unified diff",active:r==="unified",onClick:()=>P("unified"),children:u.jsx(Hoe,{className:"h-4 w-4"})}),u.jsx(ST,{label:"Side-by-side diff",active:r==="split",onClick:()=>P("split"),children:u.jsx(Gie,{className:"h-4 w-4"})}),u.jsx(ST,{label:i?"Disable word wrap":"Enable word wrap",active:i,onClick:()=>D(!i),children:u.jsx(xae,{className:"h-4 w-4"})})]}):u.jsx("div",{})]})})}),u.jsxs("div",{className:"h-full min-h-0",children:[yr,t.status!=="no_repo"&&St!=="history"&&t.files.length>0&&u.jsxs("div",{className:"relative h-full min-h-0",children:[u.jsx(rK,{ref:ke,data:t.files,keyExtractor:Ot,renderItem:Ln,extraData:{collapsedPaths:Bt,checkedPaths:jt,patchesByPath:K,patchErrorsByPath:W,loadingPatchPaths:V,diffRenderMode:r,wrapLines:i},estimatedItemSize:44,className:"h-full overflow-y-auto [scrollbar-gutter:stable] p-1.5",contentContainerStyle:{paddingBottom:St==="changes"?220:40}}),St==="changes"?u.jsxs("div",{className:"pointer-events-none absolute inset-x-0 bottom-0 py-1 pb-6 z-30",children:[u.jsx("div",{className:"absolute inset-x-0 bottom-0 top-0 bg-gradient-to-t from-background to-transparent"}),u.jsx("div",{className:"pointer-events-auto relative",children:u.jsxs("div",{className:"space-y-0 rounded-xl mx-auto max-w-[700px]",children:[u.jsx(dn,{value:Yt,onChange:ye=>{e&&gn(e,{summary:ye.target.value,description:Mt})},onKeyDown:Rt,placeholder:"Commit message (override)",className:"rounded-t-xl rounded-b-none px-3",disabled:ot||t.status!=="ready"}),u.jsx(jc,{value:Mt,onChange:ye=>{e&&gn(e,{summary:Yt,description:ye.target.value})},onKeyDown:Rt,placeholder:"Description",rows:5,className:"-mt-px rounded-t-none rounded-b-xl px-3 outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background mb-2",disabled:ot||t.status!=="ready"}),u.jsx("div",{className:"w-full flex flex-row",children:u.jsxs(bh,{children:[u.jsx(xh,{asChild:!0,children:u.jsx(Ie,{type:"button",className:"-mt-px w-full rounded-xl",disabled:Ze?!Ee:!pt,onClick:()=>{if(Ze){Qe(Ve);return}mt()},children:u.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[Mn,u.jsx("span",{className:"min-w-0 truncate text-left",children:qn})]})})}),t.hasUpstream?u.jsx(Id,{children:u.jsx(br,{disabled:!Ze||!Ee,onSelect:ye=>{ye.stopPropagation(),Qe("commit_only")},children:"Commit Only"})}):null]})})]})})]}):null]})]})]}),u.jsx(JMe,{open:F,onOpenChange:oe,onGetGitHubPublishInfo:w,onCheckGitHubRepoAvailability:N,onPublish:A})]})})}const nje=_.memo(tje);function rje(e,t){const n=getComputedStyle(e),r=parseFloat(n.fontSize);return t*r}function ije(e,t){const n=getComputedStyle(e.ownerDocument.body),r=parseFloat(n.fontSize);return t*r}function sje(e){return e/100*window.innerHeight}function oje(e){return e/100*window.innerWidth}function aje(e){switch(typeof e){case"number":return[e,"px"];case"string":{const t=parseFloat(e);return e.endsWith("%")?[t,"%"]:e.endsWith("px")?[t,"px"]:e.endsWith("rem")?[t,"rem"]:e.endsWith("em")?[t,"em"]:e.endsWith("vh")?[t,"vh"]:e.endsWith("vw")?[t,"vw"]:[t,"%"]}}}function Dv({groupSize:e,panelElement:t,styleProp:n}){let r;const[i,s]=aje(n);switch(s){case"%":{r=i/100*e;break}case"px":{r=i;break}case"rem":{r=ije(t,i);break}case"em":{r=rje(t,i);break}case"vh":{r=sje(i);break}case"vw":{r=oje(i);break}}return r}function Xs(e){return parseFloat(e.toFixed(3))}function Bm({group:e}){const{orientation:t,panels:n}=e;return n.reduce((r,i)=>(r+=t==="horizontal"?i.element.offsetWidth:i.element.offsetHeight,r),0)}function PR(e){const{panels:t}=e,n=Bm({group:e});return n===0?t.map(r=>({groupResizeBehavior:r.panelConstraints.groupResizeBehavior,collapsedSize:0,collapsible:r.panelConstraints.collapsible===!0,defaultSize:void 0,disabled:r.panelConstraints.disabled,minSize:0,maxSize:100,panelId:r.id})):t.map(r=>{const{element:i,panelConstraints:s}=r;let o=0;if(s.collapsedSize!==void 0){const h=Dv({groupSize:n,panelElement:i,styleProp:s.collapsedSize});o=Xs(h/n*100)}let a;if(s.defaultSize!==void 0){const h=Dv({groupSize:n,panelElement:i,styleProp:s.defaultSize});a=Xs(h/n*100)}let l=0;if(s.minSize!==void 0){const h=Dv({groupSize:n,panelElement:i,styleProp:s.minSize});l=Xs(h/n*100)}let d=100;if(s.maxSize!==void 0){const h=Dv({groupSize:n,panelElement:i,styleProp:s.maxSize});d=Xs(h/n*100)}return{groupResizeBehavior:s.groupResizeBehavior,collapsedSize:o,collapsible:s.collapsible===!0,defaultSize:a,disabled:s.disabled,minSize:l,maxSize:d,panelId:r.id}})}function ar(e,t="Assertion error"){if(!e)throw Error(t)}function LR(e,t){return Array.from(t).sort(e==="horizontal"?lje:cje)}function lje(e,t){const n=e.element.offsetLeft-t.element.offsetLeft;return n!==0?n:e.element.offsetWidth-t.element.offsetWidth}function cje(e,t){const n=e.element.offsetTop-t.element.offsetTop;return n!==0?n:e.element.offsetHeight-t.element.offsetHeight}function IJ(e){return e!==null&&typeof e=="object"&&"nodeType"in e&&e.nodeType===Node.ELEMENT_NODE}function PJ(e,t){return{x:e.x>=t.left&&e.x<=t.right?0:Math.min(Math.abs(e.x-t.left),Math.abs(e.x-t.right)),y:e.y>=t.top&&e.y<=t.bottom?0:Math.min(Math.abs(e.y-t.top),Math.abs(e.y-t.bottom))}}function uje({orientation:e,rects:t,targetRect:n}){const r={x:n.x+n.width/2,y:n.y+n.height/2};let i,s=Number.MAX_VALUE;for(const o of t){const{x:a,y:l}=PJ(r,o),d=e==="horizontal"?a:l;d<s&&(s=d,i=o)}return ar(i,"No rect found"),i}let E0;function dje(){return E0===void 0&&(typeof matchMedia=="function"?E0=!!matchMedia("(pointer:coarse)").matches:E0=!1),E0}function LJ(e){const{element:t,orientation:n,panels:r,separators:i}=e,s=LR(n,Array.from(t.children).filter(IJ).map(b=>({element:b}))).map(({element:b})=>b),o=[];let a=!1,l=!1,d=-1,h=-1,p=0,m,v=[];{let b=-1;for(const x of s)x.hasAttribute("data-panel")&&(b++,x.ariaDisabled===null&&(p++,d===-1&&(d=b),h=b))}if(p>1){let b=-1;for(const x of s)if(x.hasAttribute("data-panel")){b++;const S=r.find(C=>C.element===x);if(S){if(m){const C=m.element.getBoundingClientRect(),k=x.getBoundingClientRect();let w;if(l){const N=n==="horizontal"?new DOMRect(C.right,C.top,0,C.height):new DOMRect(C.left,C.bottom,C.width,0),A=n==="horizontal"?new DOMRect(k.left,k.top,0,k.height):new DOMRect(k.left,k.top,k.width,0);switch(v.length){case 0:{w=[N,A];break}case 1:{const T=v[0],M=uje({orientation:n,rects:[C,k],targetRect:T.element.getBoundingClientRect()});w=[T,M===C?A:N];break}default:{w=v;break}}}else v.length?w=v:w=[n==="horizontal"?new DOMRect(C.right,k.top,k.left-C.right,k.height):new DOMRect(k.left,C.bottom,k.width,k.top-C.bottom)];for(const N of w){let A="width"in N?N:N.element.getBoundingClientRect();const T=dje()?e.resizeTargetMinimumSize.coarse:e.resizeTargetMinimumSize.fine;if(A.width<T){const j=T-A.width;A=new DOMRect(A.x-j/2,A.y,A.width+j,A.height)}if(A.height<T){const j=T-A.height;A=new DOMRect(A.x,A.y-j/2,A.width,A.height+j)}const M=b<=d||b>h;!a&&!M&&o.push({group:e,groupSize:Bm({group:e}),panels:[m,S],separator:"width"in N?void 0:N,rect:A}),a=!1}}l=!1,m=S,v=[]}}else if(x.hasAttribute("data-separator")){x.ariaDisabled!==null&&(a=!0);const S=i.find(C=>C.element===x);S?v.push(S):(m=void 0,v=[])}else l=!0}return o}var sd,MU;let OJ=(MU=class{constructor(){Iu(this,sd,{})}addListener(t,n){const r=di(this,sd)[t];return r===void 0?di(this,sd)[t]=[n]:r.includes(n)||r.push(n),()=>{this.removeListener(t,n)}}emit(t,n){const r=di(this,sd)[t];if(r!==void 0)if(r.length===1)r[0].call(null,n);else{let i=!1,s=null;const o=Array.from(r);for(let a=0;a<o.length;a++){const l=o[a];try{l.call(null,n)}catch(d){s===null&&(i=!0,s=d)}}if(i)throw s}}removeAllListeners(){zo(this,sd,{})}removeListener(t,n){const r=di(this,sd)[t];if(r!==void 0){const i=r.indexOf(n);i>=0&&r.splice(i,1)}}},sd=new WeakMap,MU),vl=new Map;const DJ=new OJ;function fje(e){vl=new Map(vl),vl.delete(e)}function s6(e,t){for(const[n]of vl)if(n.id===e)return n}function md(e,t){for(const[n,r]of vl)if(n.id===e)return r;if(t)throw Error(`Could not find data for Group with id ${e}`)}function jh(){return vl}function KP(e,t){return DJ.addListener("groupChange",n=>{n.group.id===e&&t(n)})}function qc(e,t){const n=vl.get(e);vl=new Map(vl),vl.set(e,t),DJ.emit("groupChange",{group:e,prev:n,next:t})}function hje(e,t,n){let r,i={x:1/0,y:1/0};for(const s of t){const o=PJ(n,s.rect);switch(e){case"horizontal":{o.x<=i.x&&(r=s,i=o);break}case"vertical":{o.y<=i.y&&(r=s,i=o);break}}}return r?{distance:i,hitRegion:r}:void 0}function pje(e){return e!==null&&typeof e=="object"&&"nodeType"in e&&e.nodeType===Node.DOCUMENT_FRAGMENT_NODE}function mje(e,t){if(e===t)throw new Error("Cannot compare node with itself");const n={a:l6(e),b:l6(t)};let r;for(;n.a.at(-1)===n.b.at(-1);)r=n.a.pop(),n.b.pop();ar(r,"Stacking order can only be calculated for elements with a common ancestor");const i={a:a6(o6(n.a)),b:a6(o6(n.b))};if(i.a===i.b){const s=r.childNodes,o={a:n.a.at(-1),b:n.b.at(-1)};let a=s.length;for(;a--;){const l=s[a];if(l===o.a)return 1;if(l===o.b)return-1}}return Math.sign(i.a-i.b)}const gje=/\b(?:position|zIndex|opacity|transform|webkitTransform|mixBlendMode|filter|webkitFilter|isolation)\b/;function vje(e){const t=getComputedStyle($J(e)??e).display;return t==="flex"||t==="inline-flex"}function bje(e){const t=getComputedStyle(e);return!!(t.position==="fixed"||t.zIndex!=="auto"&&(t.position!=="static"||vje(e))||+t.opacity<1||"transform"in t&&t.transform!=="none"||"webkitTransform"in t&&t.webkitTransform!=="none"||"mixBlendMode"in t&&t.mixBlendMode!=="normal"||"filter"in t&&t.filter!=="none"||"webkitFilter"in t&&t.webkitFilter!=="none"||"isolation"in t&&t.isolation==="isolate"||gje.test(t.willChange)||t.webkitOverflowScrolling==="touch")}function o6(e){let t=e.length;for(;t--;){const n=e[t];if(ar(n,"Missing node"),bje(n))return n}return null}function a6(e){return e&&Number(getComputedStyle(e).zIndex)||0}function l6(e){const t=[];for(;e;)t.push(e),e=$J(e);return t}function $J(e){const{parentNode:t}=e;return pje(t)?t.host:t}function xje(e,t){return e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y}function yje({groupElement:e,hitRegion:t,pointerEventTarget:n}){if(!IJ(n)||n.contains(e)||e.contains(n))return!0;if(mje(n,e)>0){let r=n;for(;r;){if(r.contains(e))return!0;if(xje(r.getBoundingClientRect(),t))return!1;r=r.parentElement}}return!0}function GP(e,t){const n=[];return t.forEach((r,i)=>{if(i.disabled)return;const s=LJ(i),o=hje(i.orientation,s,{x:e.clientX,y:e.clientY});o&&o.distance.x<=0&&o.distance.y<=0&&yje({groupElement:i.element,hitRegion:o.hitRegion.rect,pointerEventTarget:e.target})&&n.push(o.hitRegion)}),n}function _je(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!=t[n])return!1;return!0}function ks(e,t,n=0){return Math.abs(Xs(e)-Xs(t))<=n}function ol(e,t){return ks(e,t)?0:e>t?1:-1}function Hp({overrideDisabledPanels:e,panelConstraints:t,prevSize:n,size:r}){const{collapsedSize:i=0,collapsible:s,disabled:o,maxSize:a=100,minSize:l=0}=t;if(o&&!e)return n;if(ol(r,l)<0)if(s){const d=(i+l)/2;ol(r,d)<0?r=i:r=l}else r=l;return r=Math.min(a,r),r=Xs(r),r}function bx({delta:e,initialLayout:t,panelConstraints:n,pivotIndices:r,prevLayout:i,trigger:s}){if(ks(e,0))return t;const o=s==="imperative-api",a=Object.values(t),l=Object.values(i),d=[...a],[h,p]=r;ar(h!=null,"Invalid first pivot index"),ar(p!=null,"Invalid second pivot index");let m=0;switch(s){case"keyboard":{{const x=e<0?p:h,S=n[x];ar(S,`Panel constraints not found for index ${x}`);const{collapsedSize:C=0,collapsible:k,minSize:w=0}=S;if(k){const N=a[x];if(ar(N!=null,`Previous layout not found for panel index ${x}`),ks(N,C)){const A=w-N;ol(A,Math.abs(e))>0&&(e=e<0?0-A:A)}}}{const x=e<0?h:p,S=n[x];ar(S,`No panel constraints found for index ${x}`);const{collapsedSize:C=0,collapsible:k,minSize:w=0}=S;if(k){const N=a[x];if(ar(N!=null,`Previous layout not found for panel index ${x}`),ks(N,w)){const A=N-C;ol(A,Math.abs(e))>0&&(e=e<0?0-A:A)}}}break}default:{const x=e<0?p:h,S=n[x];ar(S,`Panel constraints not found for index ${x}`);const C=a[x],{collapsible:k,collapsedSize:w,minSize:N}=S;if(k&&ol(C,N)<0)if(e>0){const A=N-w,T=A/2,M=C+e;ol(M,N)<0&&(e=ol(e,T)<=0?0:A)}else{const A=N-w,T=100-A/2,M=C-e;ol(M,N)<0&&(e=ol(100+e,T)>0?0:-A)}break}}{const x=e<0?1:-1;let S=e<0?p:h,C=0;for(;;){const w=a[S];ar(w!=null,`Previous layout not found for panel index ${S}`);const N=Hp({overrideDisabledPanels:o,panelConstraints:n[S],prevSize:w,size:100})-w;if(C+=N,S+=x,S<0||S>=n.length)break}const k=Math.min(Math.abs(e),Math.abs(C));e=e<0?0-k:k}{let x=e<0?h:p;for(;x>=0&&x<n.length;){const S=Math.abs(e)-Math.abs(m),C=a[x];ar(C!=null,`Previous layout not found for panel index ${x}`);const k=C-S,w=Hp({overrideDisabledPanels:o,panelConstraints:n[x],prevSize:C,size:k});if(!ks(C,w)&&(m+=C-w,d[x]=w,m.toFixed(3).localeCompare(Math.abs(e).toFixed(3),void 0,{numeric:!0})>=0))break;e<0?x--:x++}}if(_je(l,d))return i;{const x=e<0?p:h,S=a[x];ar(S!=null,`Previous layout not found for panel index ${x}`);const C=S+m,k=Hp({overrideDisabledPanels:o,panelConstraints:n[x],prevSize:S,size:C});if(d[x]=k,!ks(k,C)){let w=C-k,N=e<0?p:h;for(;N>=0&&N<n.length;){const A=d[N];ar(A!=null,`Previous layout not found for panel index ${N}`);const T=A+w,M=Hp({overrideDisabledPanels:o,panelConstraints:n[N],prevSize:A,size:T});if(ks(A,M)||(w-=M-A,d[N]=M),ks(w,0))break;e>0?N--:N++}}}const v=Object.values(d).reduce((x,S)=>S+x,0);if(!ks(v,100,.1))return i;const b=Object.keys(i);return d.reduce((x,S,C)=>(x[b[C]]=S,x),{})}function ch(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(t[n]===void 0||ol(e[n],t[n])!==0)return!1;return!0}function uh({layout:e,panelConstraints:t}){const n=Object.values(e),r=[...n],i=r.reduce((a,l)=>a+l,0);if(r.length!==t.length)throw Error(`Invalid ${t.length} panel layout: ${r.map(a=>`${a}%`).join(", ")}`);if(!ks(i,100)&&r.length>0)for(let a=0;a<t.length;a++){const l=r[a];ar(l!=null,`No layout data found for index ${a}`);const d=100/i*l;r[a]=d}let s=0;for(let a=0;a<t.length;a++){const l=n[a];ar(l!=null,`No layout data found for index ${a}`);const d=r[a];ar(d!=null,`No layout data found for index ${a}`);const h=Hp({overrideDisabledPanels:!0,panelConstraints:t[a],prevSize:l,size:d});d!=h&&(s+=d-h,r[a]=h)}if(!ks(s,0))for(let a=0;a<t.length;a++){const l=r[a];ar(l!=null,`No layout data found for index ${a}`);const d=l+s,h=Hp({overrideDisabledPanels:!0,panelConstraints:t[a],prevSize:l,size:d});if(l!==h&&(s-=h-l,r[a]=h,ks(s,0)))break}const o=Object.keys(e);return r.reduce((a,l,d)=>(a[o[d]]=l,a),{})}function zJ({groupId:e,panelId:t}){const n=()=>{const a=jh();for(const[l,{defaultLayoutDeferred:d,derivedPanelConstraints:h,layout:p,groupSize:m,separatorToPanels:v}]of a)if(l.id===e)return{defaultLayoutDeferred:d,derivedPanelConstraints:h,group:l,groupSize:m,layout:p,separatorToPanels:v};throw Error(`Group ${e} not found`)},r=()=>{const a=n().derivedPanelConstraints.find(l=>l.panelId===t);if(a!==void 0)return a;throw Error(`Panel constraints not found for Panel ${t}`)},i=()=>{const a=n().group.panels.find(l=>l.id===t);if(a!==void 0)return a;throw Error(`Layout not found for Panel ${t}`)},s=()=>{const a=n().layout[t];if(a!==void 0)return a;throw Error(`Layout not found for Panel ${t}`)},o=a=>{const l=s();if(a===l)return;const{defaultLayoutDeferred:d,derivedPanelConstraints:h,group:p,groupSize:m,layout:v,separatorToPanels:b}=n(),x=p.panels.findIndex(w=>w.id===t),S=x===p.panels.length-1,C=bx({delta:S?l-a:a-l,initialLayout:v,panelConstraints:h,pivotIndices:S?[x-1,x]:[x,x+1],prevLayout:v,trigger:"imperative-api"}),k=uh({layout:C,panelConstraints:h});ch(v,k)||qc(p,{defaultLayoutDeferred:d,derivedPanelConstraints:h,groupSize:m,layout:k,separatorToPanels:b})};return{collapse:()=>{const{collapsible:a,collapsedSize:l}=r(),{mutableValues:d}=i(),h=s();a&&h!==l&&(d.expandToSize=h,o(l))},expand:()=>{const{collapsible:a,collapsedSize:l,minSize:d}=r(),{mutableValues:h}=i(),p=s();if(a&&p===l){let m=h.expandToSize??d;m===0&&(m=1),o(m)}},getSize:()=>{const{group:a}=n(),l=s(),{element:d}=i(),h=a.orientation==="horizontal"?d.offsetWidth:d.offsetHeight;return{asPercentage:l,inPixels:h}},isCollapsed:()=>{const{collapsible:a,collapsedSize:l}=r(),d=s();return a&&ks(l,d)},resize:a=>{const{group:l}=n(),{element:d}=i(),h=Bm({group:l}),p=Dv({groupSize:h,panelElement:d,styleProp:a}),m=Xs(p/h*100);o(m)}}}function c6(e){if(e.defaultPrevented)return;const t=jh();GP(e,t).forEach(n=>{if(n.separator){const r=n.panels.find(i=>i.panelConstraints.defaultSize!==void 0);if(r){const i=r.panelConstraints.defaultSize,s=zJ({groupId:n.group.id,panelId:r.id});s&&i!==void 0&&(s.resize(i),e.preventDefault())}}})}function NS(e){const t=jh();for(const[n]of t)if(n.separators.some(r=>r.element===e))return n;throw Error("Could not find parent Group for separator element")}function BJ({groupId:e}){const t=()=>{const n=jh();for(const[r,i]of n)if(r.id===e)return{group:r,...i};throw Error(`Could not find Group with id "${e}"`)};return{getLayout(){const{defaultLayoutDeferred:n,layout:r}=t();return n?{}:r},setLayout(n){const{defaultLayoutDeferred:r,derivedPanelConstraints:i,group:s,groupSize:o,layout:a,separatorToPanels:l}=t(),d=uh({layout:n,panelConstraints:i});return r?a:(ch(a,d)||qc(s,{defaultLayoutDeferred:r,derivedPanelConstraints:i,groupSize:o,layout:d,separatorToPanels:l}),d)}}}function cf(e,t){const n=NS(e),r=md(n.id,!0),i=n.separators.find(h=>h.element===e);ar(i,"Matching separator not found");const s=r.separatorToPanels.get(i);ar(s,"Matching panels not found");const o=s.map(h=>n.panels.indexOf(h)),a=BJ({groupId:n.id}).getLayout(),l=bx({delta:t,initialLayout:a,panelConstraints:r.derivedPanelConstraints,pivotIndices:o,prevLayout:a,trigger:"keyboard"}),d=uh({layout:l,panelConstraints:r.derivedPanelConstraints});ch(a,d)||qc(n,{defaultLayoutDeferred:r.defaultLayoutDeferred,derivedPanelConstraints:r.derivedPanelConstraints,groupSize:r.groupSize,layout:d,separatorToPanels:r.separatorToPanels})}function u6(e){if(e.defaultPrevented)return;const t=e.currentTarget,n=NS(t);if(!n.disabled)switch(e.key){case"ArrowDown":{e.preventDefault(),n.orientation==="vertical"&&cf(t,5);break}case"ArrowLeft":{e.preventDefault(),n.orientation==="horizontal"&&cf(t,-5);break}case"ArrowRight":{e.preventDefault(),n.orientation==="horizontal"&&cf(t,5);break}case"ArrowUp":{e.preventDefault(),n.orientation==="vertical"&&cf(t,-5);break}case"End":{e.preventDefault(),cf(t,100);break}case"Enter":{e.preventDefault();const r=NS(t),i=md(r.id,!0),{derivedPanelConstraints:s,layout:o,separatorToPanels:a}=i,l=r.separators.find(m=>m.element===t);ar(l,"Matching separator not found");const d=a.get(l);ar(d,"Matching panels not found");const h=d[0],p=s.find(m=>m.panelId===h.id);if(ar(p,"Panel metadata not found"),p.collapsible){const m=o[h.id],v=p.collapsedSize===m?r.mutableState.expandedPanelSizes[h.id]??p.minSize:p.collapsedSize;cf(t,v-m)}break}case"F6":{e.preventDefault();const r=NS(t).separators.map(o=>o.element),i=Array.from(r).findIndex(o=>o===e.currentTarget);ar(i!==null,"Index not found");const s=e.shiftKey?i>0?i-1:r.length-1:i+1<r.length?i+1:0;r[s].focus({preventScroll:!0});break}case"Home":{e.preventDefault(),cf(t,-100);break}}}let hm={cursorFlags:0,state:"inactive"};const qP=new OJ;function dh(){return hm}function Sje(e){return qP.addListener("change",e)}function wje(e){const t=hm,n={...hm};n.cursorFlags=e,hm=n,qP.emit("change",{prev:t,next:n})}function pm(e){const t=hm;hm=e,qP.emit("change",{prev:t,next:e})}function d6(e){if(e.defaultPrevented||e.pointerType==="mouse"&&e.button>0)return;const t=jh(),n=GP(e,t),r=new Map;let i=!1;n.forEach(s=>{s.separator&&(i||(i=!0,s.separator.element.focus({preventScroll:!0})));const o=t.get(s.group);o&&r.set(s.group,o.layout)}),pm({cursorFlags:0,hitRegions:n,initialLayoutMap:r,pointerDownAtPoint:{x:e.clientX,y:e.clientY},state:"active"}),n.length&&e.preventDefault()}const Cje=e=>e,wT=()=>{},FJ=1,UJ=2,HJ=4,WJ=8,f6=3,h6=12;let N0;function p6(){return N0===void 0&&(N0=!1,typeof window<"u"&&(window.navigator.userAgent.includes("Chrome")||window.navigator.userAgent.includes("Firefox"))&&(N0=!0)),N0}function kje({cursorFlags:e,groups:t,state:n}){let r=0,i=0;switch(n){case"active":case"hover":t.forEach(s=>{if(!s.mutableState.disableCursor)switch(s.orientation){case"horizontal":{r++;break}case"vertical":{i++;break}}})}if(!(r===0&&i===0)){switch(n){case"active":{if(e&&p6()){const s=(e&FJ)!==0,o=(e&UJ)!==0,a=(e&HJ)!==0,l=(e&WJ)!==0;if(s)return a?"se-resize":l?"ne-resize":"e-resize";if(o)return a?"sw-resize":l?"nw-resize":"w-resize";if(a)return"s-resize";if(l)return"n-resize"}break}}return p6()?r>0&&i>0?"move":r>0?"ew-resize":"ns-resize":r>0&&i>0?"grab":r>0?"col-resize":"row-resize"}}const m6=new WeakMap;function YP(e){if(e.defaultView===null||e.defaultView===void 0)return;let{prevStyle:t,styleSheet:n}=m6.get(e)??{};n===void 0&&(n=new e.defaultView.CSSStyleSheet,e.adoptedStyleSheets&&e.adoptedStyleSheets.push(n));const r=dh();switch(r.state){case"active":case"hover":{const i=kje({cursorFlags:r.cursorFlags,groups:r.hitRegions.map(o=>o.group),state:r.state}),s=`*, *:hover {cursor: ${i} !important; }`;if(t===s)return;t=s,i?n.cssRules.length===0?n.insertRule(s):n.replaceSync(s):n.cssRules.length===1&&n.deleteRule(0);break}case"inactive":{t=void 0,n.cssRules.length===1&&n.deleteRule(0);break}}m6.set(e,{prevStyle:t,styleSheet:n})}function VJ({document:e,event:t,hitRegions:n,initialLayoutMap:r,mountedGroups:i,pointerDownAtPoint:s,prevCursorFlags:o}){let a=0;n.forEach(d=>{const{group:h,groupSize:p}=d,{orientation:m,panels:v}=h,{disableCursor:b}=h.mutableState;let x=0;s?m==="horizontal"?x=(t.clientX-s.x)/p*100:x=(t.clientY-s.y)/p*100:m==="horizontal"?x=t.clientX<0?-100:100:x=t.clientY<0?-100:100;const S=r.get(h),C=i.get(h);if(!S||!C)return;const{defaultLayoutDeferred:k,derivedPanelConstraints:w,groupSize:N,layout:A,separatorToPanels:T}=C;if(w&&A&&T){const M=bx({delta:x,initialLayout:S,panelConstraints:w,pivotIndices:d.panels.map(j=>v.indexOf(j)),prevLayout:A,trigger:"mouse-or-touch"});if(ch(M,A)){if(x!==0&&!b)switch(m){case"horizontal":{a|=x<0?FJ:UJ;break}case"vertical":{a|=x<0?HJ:WJ;break}}}else qc(d.group,{defaultLayoutDeferred:k,derivedPanelConstraints:w,groupSize:N,layout:M,separatorToPanels:T})}});let l=0;t.movementX===0?l|=o&f6:l|=a&f6,t.movementY===0?l|=o&h6:l|=a&h6,wje(l),YP(e)}function g6(e){const t=jh(),n=dh();switch(n.state){case"active":VJ({document:e.currentTarget,event:e,hitRegions:n.hitRegions,initialLayoutMap:n.initialLayoutMap,mountedGroups:t,prevCursorFlags:n.cursorFlags})}}function v6(e){if(e.defaultPrevented)return;const t=dh(),n=jh();switch(t.state){case"active":{if(e.buttons===0){pm({cursorFlags:0,state:"inactive"}),t.hitRegions.forEach(r=>{const i=md(r.group.id,!0);qc(r.group,i)});return}VJ({document:e.currentTarget,event:e,hitRegions:t.hitRegions,initialLayoutMap:t.initialLayoutMap,mountedGroups:n,pointerDownAtPoint:t.pointerDownAtPoint,prevCursorFlags:t.cursorFlags});break}default:{const r=GP(e,n);r.length===0?t.state!=="inactive"&&pm({cursorFlags:0,state:"inactive"}):pm({cursorFlags:0,hitRegions:r,state:"hover"}),YP(e.currentTarget);break}}}function b6(e){if(e.relatedTarget instanceof HTMLIFrameElement)switch(dh().state){case"hover":pm({cursorFlags:0,state:"inactive"})}}function x6(e){if(e.defaultPrevented||e.pointerType==="mouse"&&e.button>0)return;const t=dh();switch(t.state){case"active":pm({cursorFlags:0,state:"inactive"}),t.hitRegions.length>0&&(YP(e.currentTarget),t.hitRegions.forEach(n=>{const r=md(n.group.id,!0);qc(n.group,r)}),e.preventDefault())}}function y6(e){let t=0,n=0;const r={};for(const s of e)if(s.defaultSize!==void 0){t++;const o=Xs(s.defaultSize);n+=o,r[s.panelId]=o}else r[s.panelId]=void 0;const i=e.length-t;if(i!==0){const s=Xs((100-n)/i);for(const o of e)o.defaultSize===void 0&&(r[o.panelId]=s)}return r}function Eje(e,t,n){if(!n[0])return;const r=e.panels.find(l=>l.element===t);if(!r||!r.onResize)return;const i=Bm({group:e}),s=e.orientation==="horizontal"?r.element.offsetWidth:r.element.offsetHeight,o=r.mutableValues.prevSize,a={asPercentage:Xs(s/i*100),inPixels:s};r.mutableValues.prevSize=a,r.onResize(a,r.id,o)}function Nje(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}function Tje({group:e,nextGroupSize:t,prevGroupSize:n,prevLayout:r}){if(n<=0||t<=0||n===t)return r;let i=0,s=0,o=!1;const a=new Map,l=[];for(const p of e.panels){const m=r[p.id]??0;switch(p.panelConstraints.groupResizeBehavior){case"preserve-pixel-size":{o=!0;const v=m/100*n,b=Xs(v/t*100);a.set(p.id,b),i+=b;break}case"preserve-relative-size":default:{l.push(p.id),s+=m;break}}}if(!o||l.length===0)return r;const d=100-i,h={...r};if(a.forEach((p,m)=>{h[m]=p}),s>0)for(const p of l){const m=r[p]??0;h[p]=Xs(m/s*d)}else{const p=Xs(d/l.length);for(const m of l)h[m]=p}return h}function Aje(e,t){const n=e.map(i=>i.id),r=Object.keys(t);if(n.length!==r.length)return!1;for(const i of n)if(!r.includes(i))return!1;return!0}const kp=new Map;function Rje(e){let t=!0;ar(e.element.ownerDocument.defaultView,"Cannot register an unmounted Group");const n=e.element.ownerDocument.defaultView.ResizeObserver,r=new Set,i=new Set,s=new n(b=>{for(const x of b){const{borderBoxSize:S,target:C}=x;if(C===e.element){if(t){const k=Bm({group:e});if(k===0)return;const w=md(e.id);if(!w)return;const N=PR(e),A=w.defaultLayoutDeferred?y6(N):w.layout,T=Tje({group:e,nextGroupSize:k,prevGroupSize:w.groupSize,prevLayout:A}),M=uh({layout:T,panelConstraints:N});if(!w.defaultLayoutDeferred&&ch(w.layout,M)&&Nje(w.derivedPanelConstraints,N)&&w.groupSize===k)return;qc(e,{defaultLayoutDeferred:!1,derivedPanelConstraints:N,groupSize:k,layout:M,separatorToPanels:w.separatorToPanels})}}else Eje(e,C,S)}});s.observe(e.element),e.panels.forEach(b=>{ar(!r.has(b.id),`Panel ids must be unique; id "${b.id}" was used more than once`),r.add(b.id),b.onResize&&s.observe(b.element)});const o=Bm({group:e}),a=PR(e),l=e.panels.map(({id:b})=>b).join(",");let d=e.mutableState.defaultLayout;d&&(Aje(e.panels,d)||(d=void 0));const h=e.mutableState.layouts[l]??d??y6(a),p=uh({layout:h,panelConstraints:a}),m=e.element.ownerDocument;kp.set(m,(kp.get(m)??0)+1);const v=new Map;return LJ(e).forEach(b=>{b.separator&&v.set(b.separator,b.panels)}),qc(e,{defaultLayoutDeferred:o===0,derivedPanelConstraints:a,groupSize:o,layout:p,separatorToPanels:v}),e.separators.forEach(b=>{ar(!i.has(b.id),`Separator ids must be unique; id "${b.id}" was used more than once`),i.add(b.id),b.element.addEventListener("keydown",u6)}),kp.get(m)===1&&(m.addEventListener("dblclick",c6,!0),m.addEventListener("pointerdown",d6,!0),m.addEventListener("pointerleave",g6),m.addEventListener("pointermove",v6),m.addEventListener("pointerout",b6),m.addEventListener("pointerup",x6,!0)),function(){t=!1,kp.set(m,Math.max(0,(kp.get(m)??0)-1)),fje(e),e.separators.forEach(b=>{b.element.removeEventListener("keydown",u6)}),kp.get(m)||(m.removeEventListener("dblclick",c6,!0),m.removeEventListener("pointerdown",d6,!0),m.removeEventListener("pointerleave",g6),m.removeEventListener("pointermove",v6),m.removeEventListener("pointerout",b6),m.removeEventListener("pointerup",x6,!0)),s.disconnect()}}function Mje(){const[e,t]=_.useState({}),n=_.useCallback(()=>t({}),[]);return[e,n]}function XP(e){const t=_.useId();return`${e??t}`}const Ih=typeof window<"u"?_.useLayoutEffect:_.useEffect;function fb(e){const t=_.useRef(e);return Ih(()=>{t.current=e},[e]),_.useCallback((...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[t])}function JP(...e){return fb(t=>{e.forEach(n=>{if(n)switch(typeof n){case"function":{n(t);break}case"object":{n.current=t;break}}})})}function ZP(e){const t=_.useRef({...e});return Ih(()=>{for(const n in e)t.current[n]=e[n]},[e]),t.current}const KJ=_.createContext(null);function jje(e,t){const n=_.useRef({getLayout:()=>({}),setLayout:Cje});_.useImperativeHandle(t,()=>n.current,[]),Ih(()=>{Object.assign(n.current,BJ({groupId:e}))})}function GJ({children:e,className:t,defaultLayout:n,disableCursor:r,disabled:i,elementRef:s,groupRef:o,id:a,onLayoutChange:l,onLayoutChanged:d,orientation:h="horizontal",resizeTargetMinimumSize:p={coarse:20,fine:10},style:m,...v}){const b=_.useRef({onLayoutChange:{},onLayoutChanged:{}}),x=fb(L=>{ch(b.current.onLayoutChange,L)||(b.current.onLayoutChange=L,l==null||l(L))}),S=fb(L=>{ch(b.current.onLayoutChanged,L)||(b.current.onLayoutChanged=L,d==null||d(L))}),C=XP(a),k=_.useRef(null),[w,N]=Mje(),A=_.useRef({lastExpandedPanelSizes:{},layouts:{},panels:[],resizeTargetMinimumSize:p,separators:[]}),T=JP(k,s);jje(C,o);const M=fb((L,I)=>{const $=dh(),H=s6(L),z=md(L);if(z){let F=!1;switch($.state){case"active":{F=$.hitRegions.some(K=>K.group===H);break}}return{flexGrow:z.layout[I]??1,pointerEvents:F?"none":void 0}}return{flexGrow:(n==null?void 0:n[I])??1}}),j=ZP({defaultLayout:n,disableCursor:r}),P=_.useMemo(()=>({get disableCursor(){return!!j.disableCursor},getPanelStyles:M,id:C,orientation:h,registerPanel:L=>{const I=A.current;return I.panels=LR(h,[...I.panels,L]),N(),()=>{I.panels=I.panels.filter($=>$!==L),N()}},registerSeparator:L=>{const I=A.current;return I.separators=LR(h,[...I.separators,L]),N(),()=>{I.separators=I.separators.filter($=>$!==L),N()}},togglePanelDisabled:(L,I)=>{const $=A.current.panels.find(F=>F.id===L);$&&($.panelConstraints.disabled=I);const H=s6(C),z=md(C);H&&z&&qc(H,{...z,derivedPanelConstraints:PR(H)})},toggleSeparatorDisabled:(L,I)=>{const $=A.current.separators.find(H=>H.id===L);$&&($.disabled=I)}}),[M,C,N,h,j]),D=_.useRef(null);return Ih(()=>{const L=k.current;if(L===null)return;const I=A.current;let $;if(j.defaultLayout!==void 0&&Object.keys(j.defaultLayout).length===I.panels.length){$={};for(const X of I.panels){const G=j.defaultLayout[X.id];G!==void 0&&($[X.id]=G)}}const H={disabled:!!i,element:L,id:C,mutableState:{defaultLayout:$,disableCursor:!!j.disableCursor,expandedPanelSizes:A.current.lastExpandedPanelSizes,layouts:A.current.layouts},orientation:h,panels:I.panels,resizeTargetMinimumSize:I.resizeTargetMinimumSize,separators:I.separators};D.current=H;const z=Rje(H),{defaultLayoutDeferred:F,derivedPanelConstraints:K,layout:W}=md(H.id,!0);!F&&K.length>0&&(x(W),S(W));const V=KP(C,X=>{const{defaultLayoutDeferred:G,derivedPanelConstraints:te,layout:oe}=X.next;if(G||te.length===0)return;const ue=H.panels.map(({id:ee})=>ee).join(",");H.mutableState.layouts[ue]=oe,te.forEach(ee=>{if(ee.collapsible){const{layout:ne}=X.prev??{};if(ne){const ie=ks(ee.collapsedSize,oe[ee.panelId]),ae=ks(ee.collapsedSize,ne[ee.panelId]);ie&&!ae&&(H.mutableState.expandedPanelSizes[ee.panelId]=ne[ee.panelId])}}});const de=dh().state!=="active";x(oe),de&&S(oe)});return()=>{D.current=null,z(),V()}},[i,C,S,x,h,w,j]),_.useEffect(()=>{const L=D.current;L&&(L.mutableState.defaultLayout=n,L.mutableState.disableCursor=!!r)}),u.jsx(KJ.Provider,{value:P,children:u.jsx("div",{...v,className:t,"data-group":!0,"data-testid":C,id:C,ref:T,style:{height:"100%",width:"100%",overflow:"hidden",...m,display:"flex",flexDirection:h==="horizontal"?"row":"column",flexWrap:"nowrap",touchAction:h==="horizontal"?"pan-y":"pan-x"},children:e})})}GJ.displayName="Group";function QP(){const e=_.useContext(KJ);return ar(e,"Group Context not found; did you render a Panel or Separator outside of a Group?"),e}function Ije(e,t){const{id:n}=QP(),r=_.useRef({collapse:wT,expand:wT,getSize:()=>({asPercentage:0,inPixels:0}),isCollapsed:()=>!1,resize:wT});_.useImperativeHandle(t,()=>r.current,[]),Ih(()=>{Object.assign(r.current,zJ({groupId:n,panelId:e}))})}function qJ({children:e,className:t,collapsedSize:n="0%",collapsible:r=!1,defaultSize:i,disabled:s,elementRef:o,groupResizeBehavior:a="preserve-relative-size",id:l,maxSize:d="100%",minSize:h="0%",onResize:p,panelRef:m,style:v,...b}){const x=!!l,S=XP(l),C=ZP({disabled:s}),k=_.useRef(null),w=JP(k,o),{getPanelStyles:N,id:A,orientation:T,registerPanel:M,togglePanelDisabled:j}=QP(),P=p!==null,D=fb((I,$,H)=>{p==null||p(I,l,H)});Ih(()=>{const I=k.current;if(I!==null){const $={element:I,id:S,idIsStable:x,mutableValues:{expandToSize:void 0,prevSize:void 0},onResize:P?D:void 0,panelConstraints:{groupResizeBehavior:a,collapsedSize:n,collapsible:r,defaultSize:i,disabled:C.disabled,maxSize:d,minSize:h}};return M($)}},[a,n,r,i,P,S,x,d,h,D,M,C]),_.useEffect(()=>{j(S,!!s)},[s,S,j]),Ije(S,m);const L=_.useSyncExternalStore(I=>KP(A,I),()=>JSON.stringify(N(A,S)),()=>JSON.stringify(N(A,S)));return u.jsx("div",{...b,"aria-disabled":s||void 0,"data-panel":!0,"data-testid":S,id:S,ref:w,style:{...Pje,display:"flex",flexBasis:0,flexShrink:1,overflow:"visible",...JSON.parse(L)},children:u.jsx("div",{className:t,style:{maxHeight:"100%",maxWidth:"100%",flexGrow:1,overflow:"auto",...v,touchAction:T==="horizontal"?"pan-y":"pan-x"},children:e})})}qJ.displayName="Panel";const Pje={minHeight:0,maxHeight:"100%",height:"auto",minWidth:0,maxWidth:"100%",width:"auto",border:"none",borderWidth:0,padding:0,margin:0};function Lje({layout:e,panelConstraints:t,panelId:n,panelIndex:r}){let i,s;const o=e[n],a=t.find(l=>l.panelId===n);if(a){const l=a.maxSize,d=a.collapsible?a.collapsedSize:a.minSize,h=[r,r+1];s=uh({layout:bx({delta:d-o,initialLayout:e,panelConstraints:t,pivotIndices:h,prevLayout:e}),panelConstraints:t})[n],i=uh({layout:bx({delta:l-o,initialLayout:e,panelConstraints:t,pivotIndices:h,prevLayout:e}),panelConstraints:t})[n]}return{valueControls:n,valueMax:i,valueMin:s,valueNow:o}}function YJ({children:e,className:t,disabled:n,elementRef:r,id:i,style:s,...o}){const a=XP(i),l=ZP({disabled:n}),[d,h]=_.useState({}),[p,m]=_.useState("inactive"),v=_.useRef(null),b=JP(v,r),{disableCursor:x,id:S,orientation:C,registerSeparator:k,toggleSeparatorDisabled:w}=QP(),N=C==="horizontal"?"vertical":"horizontal";Ih(()=>{const T=v.current;if(T!==null){const M={disabled:l.disabled,element:T,id:a},j=k(M),P=Sje(L=>{m(L.next.state!=="inactive"&&L.next.hitRegions.some(I=>I.separator===M)?L.next.state:"inactive")}),D=KP(S,L=>{const{derivedPanelConstraints:I,layout:$,separatorToPanels:H}=L.next,z=H.get(M);if(z){const F=z[0],K=z.indexOf(F);h(Lje({layout:$,panelConstraints:I,panelId:F.id,panelIndex:K}))}});return()=>{P(),D(),j()}}},[S,a,k,l]),_.useEffect(()=>{w(a,!!n)},[n,a,w]);let A;return n&&!x&&(A="not-allowed"),u.jsx("div",{...o,"aria-controls":d.valueControls,"aria-disabled":n||void 0,"aria-orientation":N,"aria-valuemax":d.valueMax,"aria-valuemin":d.valueMin,"aria-valuenow":d.valueNow,children:e,className:t,"data-separator":n?"disabled":p,"data-testid":a,id:a,ref:b,role:"separator",style:{flexBasis:"auto",cursor:A,...s,flexGrow:0,flexShrink:0,touchAction:"none"},tabIndex:n?void 0:0})}YJ.displayName="Separator";const eL=({className:e,...t})=>u.jsx(GJ,{className:he("flex h-full w-full",e),...t}),xx=e=>u.jsx(qJ,{...e}),tL=({withHandle:e,orientation:t,disabled:n,className:r,...i})=>u.jsx(YJ,{disabled:n,className:he("relative flex items-center justify-center bg-transparent focus-visible:outline-none",t==="vertical"?"h-2 w-full -my-1 cursor-row-resize":"h-full w-2 -mx-1 cursor-col-resize",e&&(t==="vertical"?"before:absolute before:inset-x-0 before:top-1/2 before:h-0.5 before:-translate-y-1/2 before:bg-border":"before:absolute before:inset-y-0 before:left-1/2 before:w-px before:-translate-x-1/2 before:bg-border"),r),...i,children:u.jsx("span",{className:"sr-only",children:t==="vertical"?"Resize rows":"Resize columns"})});function XJ(e,t,n){const r=typeof e.maxTokens=="number"&&Number.isFinite(e.maxTokens)?e.maxTokens:null,i=r&&r>0?Math.min(100,e.usedTokens/r*100):null,s=r!==null?Math.max(0,Math.round(r-e.usedTokens)):null,o=i!==null?Math.max(0,100-i):null;return{...e,compactsAutomatically:e.compactsAutomatically||n,maxTokens:r??void 0,remainingTokens:s,usedPercentage:i,remainingPercentage:o,updatedAt:t}}function Oje(e){const t=e.some(n=>n.kind==="compact_boundary"||n.kind==="compact_summary"||n.kind==="context_cleared");for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r&&!(r.kind!=="context_window_updated"||r.usage.usedTokens<=0))return XJ(r.usage,new Date(r.createdAt).toISOString(),t)}return null}function Dje(e,t){return!e||t===null||!Number.isFinite(t)||t<=0?e:XJ({...e,maxTokens:t},e.updatedAt,e.compactsAutomatically)}function Du(e){return e===void 0||!Number.isFinite(e)||e<0?0:e}function $je(e,t){let n=0,r=0,i=0,s=0;for(const a of e){if(a.kind!=="result")continue;const l=a.usage;l&&(n+=Du(l.inputTokens),r+=Du(l.outputTokens),i+=Du(l.cachedInputTokens)),s+=Du(a.costUsd??(l==null?void 0:l.costUsd))}for(const a of t){const l=a.usage;l&&(n+=Du(l.inputTokens),r+=Du(l.outputTokens),i+=Du(l.cachedInputTokens),s+=Du(l.costUsd))}if(n===0&&r===0&&i===0&&s===0)return null;const o=n>0?i/n*100:null;return{inputTokens:n,outputTokens:r,cachedTokens:i,costUsd:s,cacheHitPercentage:o}}function zje(e){return!Number.isFinite(e)||e<=0?"$0.00":e<.01?"<$0.01":`$${e.toFixed(2)}`}function qs(e){return e==null||!Number.isFinite(e)?"0":e<1e3?`${Math.round(e)}`:e<1e4?`${(e/1e3).toFixed(1).replace(/\.0$/,"")}k`:e<1e6?`${Math.round(e/1e3)}k`:`${(e/1e6).toFixed(1).replace(/\.0$/,"")}m`}const Bje=typeof window>"u"?0:window.innerWidth,Vn=dr()(e=>({typedEmptyStateText:"",isEmptyStateTypingComplete:!1,setTypedEmptyStateText:t=>e({typedEmptyStateText:t}),setIsEmptyStateTypingComplete:t=>e({isEmptyStateTypingComplete:t}),resetEmptyStateTyping:()=>e({typedEmptyStateText:"",isEmptyStateTypingComplete:!1}),isPageFileDragActive:!1,setIsPageFileDragActive:t=>e({isPageFileDragActive:t}),layoutWidth:0,setLayoutWidth:t=>e({layoutWidth:t}),inputHeight:148,setInputHeight:t=>e({inputHeight:t}),viewportWidth:Bje,setViewportWidth:t=>e({viewportWidth:t}),fixedTerminalHeight:0,setFixedTerminalHeight:t=>e({fixedTerminalHeight:t}),showScrollToBottom:!1,setShowScrollToBottom:t=>e({showScrollToBottom:t}),toolGroupExpanded:{},setToolGroupExpanded:t=>e(n=>({toolGroupExpanded:t(n.toolGroupExpanded)})),resetToolGroupExpanded:()=>e({toolGroupExpanded:{}}),localLinkMenuTarget:null,setLocalLinkMenuTarget:t=>e({localLinkMenuTarget:t}),diffRenderMode:"unified",wrapDiffLines:!1,setDiffRenderMode:t=>e({diffRenderMode:t}),setWrapDiffLines:t=>e({wrapDiffLines:t}),terminalFocusRequestVersion:0,incrementTerminalFocusRequestVersion:()=>e(t=>({terminalFocusRequestVersion:t.terminalFocusRequestVersion+1}))})),nL=[68,32];function Fje(){return{isVisible:!1,mainSizes:[...nL],terminals:[],nextTerminalIndex:0}}function Uje(e,t){return e[t]??Fje()}function CT(e){if(e.length===0)return[];const t=e.reduce((n,r)=>n+Math.max(r,0),0);return!Number.isFinite(t)||t<=0?Array.from({length:e.length},()=>100/e.length):e.map(n=>Math.max(n,0)/t*100)}function Hje(e){let t=e,n="";do n=String.fromCharCode(65+t%26)+n,t=Math.floor(t/26)-1;while(t>=0);return`Terminal ${n}`}function Wje(e){if(e.length===0)return e;const t=e.length+1;return e.map(n=>({...n,size:n.size*e.length/t}))}function Ep(e,t,n){return{...e,[t]:n(Uje(e,t))}}const Ku=dr()(og(e=>({projects:{},addTerminal:(t,n)=>e(r=>({projects:Ep(r.projects,t,i=>{var l,d;const s=Wje(i.terminals),o={id:((d=(l=globalThis.crypto)==null?void 0:l.randomUUID)==null?void 0:d.call(l))??`terminal-${Date.now()}-${i.nextTerminalIndex}`,title:Hje(i.nextTerminalIndex),size:100/(s.length+1)},a=n?Math.max(s.findIndex(h=>h.id===n)+1,0):s.length;return{...i,isVisible:!0,nextTerminalIndex:i.nextTerminalIndex+1,terminals:[...s.slice(0,a),o,...s.slice(a)]}})})),removeTerminal:(t,n)=>e(r=>({projects:Ep(r.projects,t,i=>{const s=i.terminals.filter(a=>a.id!==n);if(s.length===0)return{...i,isVisible:!1,terminals:[]};const o=CT(s.map(a=>a.size));return{...i,terminals:s.map((a,l)=>({...a,size:o[l]??100/s.length}))}})})),toggleVisibility:t=>e(n=>({projects:Ep(n.projects,t,r=>({...r,isVisible:r.terminals.length>0?!r.isVisible:!1}))})),resetMainSizes:t=>e(n=>({projects:Ep(n.projects,t,r=>({...r,mainSizes:[...nL]}))})),setMainSizes:(t,n)=>e(r=>{if(n.length!==2)return r;const[i=50,s=50]=CT(n),o=[i,s];return{projects:Ep(r.projects,t,a=>({...a,mainSizes:o}))}}),setTerminalSizes:(t,n)=>e(r=>({projects:Ep(r.projects,t,i=>{if(n.length!==i.terminals.length)return i;const s=CT(n);return{...i,terminals:i.terminals.map((o,a)=>({...o,size:s[a]??o.size}))}})})),clearProject:t=>e(n=>{const{[t]:r,...i}=n.projects;return{projects:i}})}),{name:"terminal-layouts",version:1})),Vje={isVisible:!1,mainSizes:[...nL],terminals:[],nextTerminalIndex:0},Kje=35;function Gje(e,t){return!Number.isFinite(e)||e<=0||!Number.isFinite(t)||t<=0?0:e*(t/100)}function qje(e,t){const n=Gje(e,t);return n>=0&&n<Kje}const R1=350,Yje=[.4,0,.2,1],Xje=8,_6=1e-6;function Jje(e,t,n){const r=1-e;return 3*r*r*e*t+3*r*e*e*n+e*e*e}function Zje(e,t,n){const r=1-e;return 3*r*r*e*t+3*r*e*e*n+e*e*e}function Qje(e,t,n){const r=1-e;return 3*r*r*t+6*r*e*(n-t)+3*e*e*(1-n)}function eIe(e,t,n){let r=e;for(let i=0;i<Xje;i+=1){const s=Jje(r,t,n)-e;if(Math.abs(s)<_6)return r;const o=Qje(r,t,n);if(Math.abs(o)<_6)break;r-=s/o}return r}function tIe(e){if(e<=0)return 0;if(e>=1)return 1;const[t,n,r,i]=Yje,s=eIe(e,t,r);return Zje(s,n,i)}function JJ(e,t,n){const r=tIe(n);return[e[0]+(t[0]-e[0])*r,e[1]+(t[1]-e[1])*r]}function nIe({projectId:e,shouldRenderRightSidebarLayout:t,showRightSidebar:n,rightSidebarSize:r}){const i=_.useRef(null),s=_.useRef(null),o=_.useRef(null),a=_.useRef(null),l=_.useRef(null),d=_.useRef(!1),h=_.useRef(null),p=_.useRef(!1),m=_.useRef(!1);return _.useEffect(()=>()=>{a.current!==null&&window.cancelAnimationFrame(a.current),l.current!==null&&window.clearTimeout(l.current)},[]),_.useLayoutEffect(()=>{var M,j,P,D,L,I;if(!t){a.current!==null&&(window.cancelAnimationFrame(a.current),a.current=null),l.current!==null&&(window.clearTimeout(l.current),l.current=null),d.current=!1;return}const v=i.current;if(!v)return;a.current!==null&&(window.cancelAnimationFrame(a.current),a.current=null),l.current!==null&&(window.clearTimeout(l.current),l.current=null);const b=h.current,x=b!==null&&b!==e,S=n&&!m.current,C=!p.current,k=n?[100-r,r]:[100,0],w=x||C&&n,N=S||C?[100,0]:[v.getLayout().workspace??k[0],v.getLayout().rightSidebar??k[1]];if(h.current=e,p.current=t,m.current=n,w||Math.abs(N[0]-k[0])<.1&&Math.abs(N[1]-k[1])<.1){v.setLayout({workspace:k[0],rightSidebar:k[1]}),(M=s.current)==null||M.setAttribute("data-right-sidebar-open",n?"true":"false"),(j=o.current)==null||j.setAttribute("data-right-sidebar-open",n?"true":"false"),(P=o.current)==null||P.setAttribute("data-right-sidebar-animated","false");return}d.current=!0,(D=s.current)==null||D.setAttribute("data-right-sidebar-open",n?"true":"false"),(L=o.current)==null||L.setAttribute("data-right-sidebar-open",n?"true":"false"),(I=o.current)==null||I.setAttribute("data-right-sidebar-animated","true"),v.setLayout({workspace:N[0],rightSidebar:N[1]});const A=performance.now(),T=$=>{const H=Math.min(1,($-A)/R1),z=JJ(N,k,H);if(v.setLayout({workspace:z[0],rightSidebar:z[1]}),H<1){a.current=window.requestAnimationFrame(T);return}v.setLayout({workspace:k[0],rightSidebar:k[1]}),a.current=null,l.current=window.setTimeout(()=>{d.current=!1,l.current=null},0)};a.current=window.requestAnimationFrame(T)},[e,r,t,n]),_.useEffect(()=>{t||(p.current=!1,m.current=!1)},[t]),{isAnimating:d,panelGroupRef:i,sidebarPanelRef:s,sidebarVisualRef:o}}function rIe(e){return e.visibilityState==="visible"?e.activeChatId:null}function iIe(e){e.socket.setFocusedChat(rIe({activeChatId:e.activeChatId,visibilityState:e.visibilityState}))}function sIe({socket:e,activeChatId:t}){_.useEffect(()=>{if(typeof document>"u")return;const n=()=>{iIe({socket:e,activeChatId:t,visibilityState:document.visibilityState})};return n(),document.addEventListener("visibilitychange",n),window.addEventListener("pagehide",n),window.addEventListener("pageshow",n),()=>{document.removeEventListener("visibilitychange",n),window.removeEventListener("pagehide",n),window.removeEventListener("pageshow",n),e.setFocusedChat(null)}},[e,t])}function oIe({rootRef:e,fallbackRef:t,enabled:n,canCancel:r}){_.useEffect(()=>{if(!n)return;let i=0,s=null;const o=p=>{const m=p instanceof Element?p:null,v=e.current,b=t.current;if(t$({trigger:"pointer",activeElement:document.activeElement,pointerStartTarget:s,pointerEndTarget:m,root:v,fallback:b,hasActiveOverlay:e$(document),hasActiveSelection:tue(window.getSelection())})!=="restore"){s=null;return}b==null||b.focus({preventScroll:!0}),s=null},a=p=>{cancelAnimationFrame(i),s=p.target instanceof Element?p.target:null},l=p=>{cancelAnimationFrame(i),i=window.requestAnimationFrame(()=>{o(p.target)})},d=()=>{s=null;const p=t.current;!p||p.disabled||p.focus({preventScroll:!0})},h=p=>{if(p.key!=="Escape")return;const m=t.current;t$({trigger:"escape",activeElement:document.activeElement,fallback:m,hasActiveOverlay:e$(document),canCancel:r,defaultPrevented:p.defaultPrevented})==="escape-focus"&&(p.preventDefault(),m==null||m.focus({preventScroll:!0}))};return window.addEventListener("pointerdown",a,!0),window.addEventListener("pointerup",l,!0),window.addEventListener("keydown",h,!0),window.addEventListener(FS,d),()=>{cancelAnimationFrame(i),window.removeEventListener("pointerdown",a,!0),window.removeEventListener("pointerup",l,!0),window.removeEventListener("keydown",h,!0),window.removeEventListener(FS,d)}},[r,n,t,e])}function aIe(e){const t=e.previousProjectId!==null&&e.previousProjectId!==e.projectId,n=e.previousProjectId===null&&e.projectId!==null;return!t&&!n&&e.showTerminalPane&&!e.wasTerminalVisible}function lIe({previousProjectId:e,projectId:t,previousShouldRenderTerminalLayout:n,previousShowTerminalPane:r,showTerminalPane:i,terminalLayout:s,liveLayout:o}){const a=e!==null&&e!==t,l=i&&!r,d=!n,h=e===null&&t!==null,p=i?s.mainSizes:[100,0];return{currentLayout:l||d?[100,0]:o,shouldSkipAnimation:a||h&&d,targetLayout:p}}function cIe({chatInputRef:e,projectId:t,shouldRenderTerminalLayout:n,showTerminalPane:r,terminalLayout:i}){const s=_.useRef(null),o=_.useRef(null),a=_.useRef(null),l=_.useRef(null),d=_.useRef(null),h=_.useRef(!1),p=_.useRef(null),m=_.useRef(!1),v=_.useRef(!1),b=_.useRef(!1),x=Vn(C=>C.terminalFocusRequestVersion),S=Vn(C=>C.incrementTerminalFocusRequestVersion);return _.useEffect(()=>{var w;const C=p.current,k=b.current;aIe({previousProjectId:C,projectId:t,showTerminalPane:r,wasTerminalVisible:k})&&S(),C!==null&&C===t&&!r&&k&&((w=e.current)==null||w.focus({preventScroll:!0})),b.current=r,p.current=t},[e,S,t,r]),_.useEffect(()=>()=>{l.current!==null&&window.cancelAnimationFrame(l.current),d.current!==null&&window.clearTimeout(d.current)},[]),_.useLayoutEffect(()=>{var j,P,D,L,I,$;if(!n){l.current!==null&&(window.cancelAnimationFrame(l.current),l.current=null),d.current!==null&&(window.clearTimeout(d.current),d.current=null),h.current=!1;return}const C=s.current;if(!C)return;l.current!==null&&(window.cancelAnimationFrame(l.current),l.current=null),d.current!==null&&(window.clearTimeout(d.current),d.current=null);const k=p.current,{currentLayout:w,shouldSkipAnimation:N,targetLayout:A}=lIe({previousProjectId:k,projectId:t,previousShouldRenderTerminalLayout:m.current,previousShowTerminalPane:v.current,showTerminalPane:r,terminalLayout:i,liveLayout:[C.getLayout().chat??i.mainSizes[0],C.getLayout().terminal??i.mainSizes[1]]});if(m.current=n,v.current=r,N||Math.abs(w[0]-A[0])<.1&&Math.abs(w[1]-A[1])<.1){C.setLayout({chat:A[0],terminal:A[1]}),(j=o.current)==null||j.setAttribute("data-terminal-open",r?"true":"false"),(P=a.current)==null||P.setAttribute("data-terminal-open",r?"true":"false"),(D=a.current)==null||D.setAttribute("data-terminal-animated","false");return}h.current=!0,(L=o.current)==null||L.setAttribute("data-terminal-open",r?"true":"false"),(I=a.current)==null||I.setAttribute("data-terminal-open",r?"true":"false"),($=a.current)==null||$.setAttribute("data-terminal-animated","true"),C.setLayout({chat:w[0],terminal:w[1]});const T=performance.now(),M=H=>{const z=Math.min(1,(H-T)/R1),F=JJ(w,A,z);if(C.setLayout({chat:F[0],terminal:F[1]}),z<1){l.current=window.requestAnimationFrame(M);return}C.setLayout({chat:A[0],terminal:A[1]}),l.current=null,d.current=window.setTimeout(()=>{h.current=!1,d.current=null},0)};l.current=window.requestAnimationFrame(M)},[t,n,r,i]),_.useEffect(()=>{n||(m.current=!1,v.current=!1)},[n]),{isAnimating:h,mainPanelGroupRef:s,terminalFocusRequestVersion:x,terminalPanelRef:o,terminalVisualRef:a}}const S6=e=>Symbol.iterator in e,w6=e=>"entries"in e,C6=(e,t)=>{const n=e instanceof Map?e:new Map(e.entries()),r=t instanceof Map?t:new Map(t.entries());if(n.size!==r.size)return!1;for(const[i,s]of n)if(!r.has(i)||!Object.is(s,r.get(i)))return!1;return!0},uIe=(e,t)=>{const n=e[Symbol.iterator](),r=t[Symbol.iterator]();let i=n.next(),s=r.next();for(;!i.done&&!s.done;){if(!Object.is(i.value,s.value))return!1;i=n.next(),s=r.next()}return!!i.done&&!!s.done};function dIe(e,t){return Object.is(e,t)?!0:typeof e!="object"||e===null||typeof t!="object"||t===null||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:S6(e)&&S6(t)?w6(e)&&w6(t)?C6(e,t):uIe(e,t):C6({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function mm(e){const t=$n.useRef(void 0);return n=>{const r=e(n);return dIe(t.current,r)?t.current:t.current=r}}function bv(){var e;return((e=Ir.getState().settings)==null?void 0:e.customModels)??[]}const hb="__new__";function Np(e,t){var o,a;const n=(o=e==null?void 0:e.modelOptions)==null?void 0:o.reasoningEffort;let r;tw(n)?r=n:tw(e==null?void 0:e.effort)?r=e.effort:r=_o.reasoningEffort;const i=yge(e==null?void 0:e.model,void 0,t),s=Zj(i,(a=e==null?void 0:e.modelOptions)==null?void 0:a.contextWindow,t);return{model:i,modelOptions:{reasoningEffort:!jW(i,t)&&r==="max"?"high":r,contextWindow:s},planMode:!!(e!=null&&e.planMode)}}function T0(e,t){var i,s;const n=(i=e==null?void 0:e.modelOptions)==null?void 0:i.reasoningEffort;let r;return nw(n)?r=n:nw(e==null?void 0:e.effort)?r=e.effort:r=fd.reasoningEffort,{model:_ge(e==null?void 0:e.model,void 0,t),modelOptions:{reasoningEffort:r,fastMode:typeof((s=e==null?void 0:e.modelOptions)==null?void 0:s.fastMode)=="boolean"?e.modelOptions.fastMode:fd.fastMode},planMode:!!(e!=null&&e.planMode)}}function fIe(){return{claude:{model:"claude-opus-4-7",modelOptions:{..._o},planMode:!1},codex:{model:"gpt-5.5",modelOptions:{...fd},planMode:!1},openrouter:{model:jC,modelOptions:{},planMode:!1}}}function hIe(e,t){return e.reasoningEffort===t.reasoningEffort&&e.contextWindow===t.contextWindow}function pIe(e,t){return e.reasoningEffort===t.reasoningEffort&&e.fastMode===t.fastMode}function mIe(e,t){return e.claude.model===t.claude.model&&e.claude.planMode===t.claude.planMode&&hIe(e.claude.modelOptions,t.claude.modelOptions)&&e.codex.model===t.codex.model&&e.codex.planMode===t.codex.planMode&&pIe(e.codex.modelOptions,t.codex.modelOptions)&&e.openrouter.model===t.openrouter.model&&e.openrouter.planMode===t.openrouter.planMode}function gIe(e,t){if(t===void 0){Qs.info(`[chat-preferences] ${e}`);return}Qs.info(`[chat-preferences] ${e}`,t)}function pb(e,t){if(e==="claude"){const r=t.claude;return{provider:"claude",model:r.model,modelOptions:{...r.modelOptions},planMode:r.planMode}}if(e==="openrouter"){const r=t.openrouter;return{provider:"openrouter",model:r.model,modelOptions:{...r.modelOptions},planMode:r.planMode}}const n=t.codex;return{provider:"codex",model:n.model,modelOptions:{...n.modelOptions},planMode:n.planMode}}function OR(e){return e.provider==="claude"?{provider:"claude",model:e.model,modelOptions:{...e.modelOptions},planMode:e.planMode}:e.provider==="openrouter"?{provider:"openrouter",model:e.model,modelOptions:{...e.modelOptions},planMode:e.planMode}:{provider:"codex",model:e.model,modelOptions:{...e.modelOptions},planMode:e.planMode}}function ZJ(e){return e.providerHint?pb(e.providerHint,e.providerDefaults):e.defaultProvider==="last_used"?e.sourceState?OR(e.sourceState):pb("claude",e.providerDefaults):pb(e.defaultProvider,e.providerDefaults)}function QJ(e,t){const n=e.chatStates[t];return n||ZJ({defaultProvider:e.defaultProvider,providerDefaults:e.providerDefaults,legacyComposerState:e.legacyComposerState})}function A0(e,t,n){const r=QJ(e,t);return{chatStates:{...e.chatStates,[t]:n(r)}}}const Ts=dr()(og((e,t)=>({defaultProvider:"last_used",providerDefaults:fIe(),chatStates:{},legacyComposerState:{provider:"claude",model:"claude-opus-4-7",modelOptions:{..._o},planMode:!1},setDefaultProvider:n=>e({defaultProvider:n}),applyServerDefaults:(n,r)=>e(i=>{if(i.defaultProvider===n&&mIe(i.providerDefaults,r))return{defaultProvider:n,providerDefaults:r};const{[hb]:o,...a}=i.chatStates;return{defaultProvider:n,providerDefaults:r,chatStates:a}}),setProviderDefaultModel:(n,r)=>e(i=>{const s=bv();return n==="claude"?{providerDefaults:{...i.providerDefaults,[n]:Np({...i.providerDefaults.claude,model:r},s)}}:n==="openrouter"?{providerDefaults:{...i.providerDefaults,[n]:{...i.providerDefaults.openrouter,model:r}}}:{providerDefaults:{...i.providerDefaults,[n]:T0({...i.providerDefaults.codex,model:r},s)}}}),setProviderDefaultModelOptions:(n,r)=>e(i=>{const s=bv();if(n==="claude"){const a=r;return{providerDefaults:{...i.providerDefaults,[n]:Np({...i.providerDefaults.claude,modelOptions:{...i.providerDefaults.claude.modelOptions,...a}},s)}}}if(n==="openrouter")return{providerDefaults:{...i.providerDefaults,[n]:{...i.providerDefaults.openrouter,modelOptions:{}}}};const o=r;return{providerDefaults:{...i.providerDefaults,[n]:T0({...i.providerDefaults.codex,modelOptions:{...i.providerDefaults.codex.modelOptions,...o}},s)}}}),setProviderDefaultPlanMode:(n,r)=>e(i=>({providerDefaults:{...i.providerDefaults,[n]:{...i.providerDefaults[n],planMode:r}}})),getComposerState:n=>OR(QJ(t(),n)),initializeComposerForChat:(n,r)=>e(i=>{if(i.chatStates[n])return i;const s=ZJ({defaultProvider:i.defaultProvider,providerDefaults:i.providerDefaults,sourceState:r==null?void 0:r.sourceState,legacyComposerState:i.legacyComposerState,providerHint:r==null?void 0:r.providerHint});return gIe("initializeComposerForChat",{chatId:n,composerState:s}),{chatStates:{...i.chatStates,[n]:s}}}),setComposerState:(n,r)=>e(i=>{const s=bv();return{chatStates:{...i.chatStates,[n]:r.provider==="claude"?{provider:"claude",model:Np(r,s).model,modelOptions:Np(r,s).modelOptions,planMode:r.planMode}:OR(r)}}}),setChatComposerProvider:(n,r)=>e(i=>A0(i,n,()=>pb(r,i.providerDefaults))),setChatComposerModel:(n,r)=>e(i=>A0(i,n,s=>{const o=bv();if(s.provider==="claude"){const a=Np({...s,model:r},o);return{provider:"claude",model:a.model,modelOptions:a.modelOptions,planMode:s.planMode}}return s.provider==="openrouter"?{provider:"openrouter",model:r,modelOptions:{},planMode:s.planMode}:{provider:"codex",model:r,modelOptions:T0({...s,model:r},o).modelOptions,planMode:s.planMode}})),setChatComposerModelOptions:(n,r)=>e(i=>A0(i,n,s=>{const o=bv();if(s.provider==="claude"){const l=r;return{provider:"claude",model:s.model,modelOptions:Np({...s,modelOptions:{...s.modelOptions,...l}},o).modelOptions,planMode:s.planMode}}if(s.provider==="openrouter")return{provider:"openrouter",model:s.model,modelOptions:{},planMode:s.planMode};const a=r;return{provider:"codex",model:s.model,modelOptions:T0({...s,modelOptions:{...s.modelOptions,...a}},o).modelOptions,planMode:s.planMode}})),setChatComposerPlanMode:(n,r)=>e(i=>A0(i,n,s=>({...s,planMode:r}))),resetChatComposerFromProvider:(n,r)=>e(i=>({chatStates:{...i.chatStates,[n]:pb(r,i.providerDefaults)}}))}),{name:"chat-preferences-state",version:1,partialize:e=>({chatStates:e.chatStates,legacyComposerState:e.legacyComposerState})}));function vIe(e){return e===void 0?null:typeof e=="string"?e?{text:e}:null:e.text||e.lexicalState?e:null}const DR=dr()(og((e,t)=>({drafts:{},attachmentDrafts:{},setDraft:(n,r,i)=>e(s=>{let o;if(typeof r=="string"){if(!r){const{[n]:a,...l}=s.drafts;return{drafts:l}}o={text:r}}else{const a=i??"";if(!a){const{[n]:l,...d}=s.drafts;return{drafts:d}}o={text:a,lexicalState:r}}return{drafts:{...s.drafts,[n]:o}}}),clearDraft:n=>e(r=>{const{[n]:i,...s}=r.drafts;return{drafts:s}}),getDraft:n=>vIe(t().drafts[n]),setAttachmentDrafts:(n,r)=>e(i=>{if(r.length===0){const{[n]:s,...o}=i.attachmentDrafts;return{attachmentDrafts:o}}return{attachmentDrafts:{...i.attachmentDrafts,[n]:r}}}),clearAttachmentDrafts:n=>e(r=>{const{[n]:i,...s}=r.attachmentDrafts;return{attachmentDrafts:s}}),getAttachmentDrafts:n=>t().attachmentDrafts[n]??[]}),{name:"chat-input-drafts"})),rL=dr()(e=>({byChatId:{},loadingByChatId:{},setForChat:(t,n)=>e(r=>({byChatId:{...r.byChatId,[t]:n}})),setLoadingForChat:(t,n)=>e(r=>(r.loadingByChatId[t]??!1)===n?r:{loadingByChatId:{...r.loadingByChatId,[t]:n}}),clear:t=>e(n=>{const r=t in n.byChatId,i=t in n.loadingByChatId;if(!r&&!i)return n;const{[t]:s,...o}=n.byChatId,{[t]:a,...l}=n.loadingByChatId;return{byChatId:o,loadingByChatId:l}})}));function bIe(e){return{autoResumeOnRateLimit:!!(e!=null&&e.autoResumeOnRateLimit)}}const $R=dr()(og(e=>({autoResumeOnRateLimit:!1,setAutoResumeOnRateLimit:t=>e({autoResumeOnRateLimit:t})}),{name:"kanna-preferences",version:1,migrate:e=>bIe(e)})),xIe="kanna",yIe=`mcp__${xIe}__preview_file`;function uf(e){return Wi(e)?e:null}function xv(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function _Ie(e){let t;Wi(e)&&"content"in e&&Array.isArray(e.content)?t=e.content:Array.isArray(e)?t=e:t=[];const n=[];for(const r of t)if(!(!r||typeof r!="object"||!("type"in r))){if(r.type==="text"&&"text"in r&&typeof r.text=="string"){n.push({type:"text",text:r.text});continue}if(r.type==="image"){if("data"in r&&typeof r.data=="string"){n.push({type:"image",data:r.data,mimeType:"mimeType"in r&&typeof r.mimeType=="string"?r.mimeType:void 0});continue}"source"in r&&r.source&&typeof r.source=="object"&&"type"in r.source&&r.source.type==="base64"&&"data"in r.source&&typeof r.source.data=="string"&&n.push({type:"image",data:r.source.data,mimeType:"media_type"in r.source&&typeof r.source.media_type=="string"?r.source.media_type:void 0})}}return n}function R0(e){let t;if(Wi(e)&&"content"in e&&Array.isArray(e.content)?t=e.content:Array.isArray(e)?t=e:t=null,!t)return null;const n=[];for(const r of t)r&&typeof r=="object"&&"type"in r&&r.type==="text"&&"text"in r&&typeof r.text=="string"&&n.push(r.text);return n.length>0?n.join(""):null}function SIe(e,t){var r;const n=xv(t);switch(e.toolKind){case"ask_user_question":{const i=R0(n),s=i!==null?xv(i):n,o=uf(s),a=uf(o==null?void 0:o.answers)??(o||{}),l={};for(const[d,h]of Object.entries(a))Array.isArray(h)?l[d]=h.map(p=>String(p)):Wi(h)&&Array.isArray(h.answers)?l[d]=h.answers.map(p=>String(p)):h==null||h===""?l[d]=[]:l[d]=[String(h)];return{answers:l,...(o==null?void 0:o.discarded)===!0?{discarded:!0}:{}}}case"exit_plan_mode":{const i=R0(n),s=i!==null?xv(i):n,o=uf(s);return{confirmed:typeof(o==null?void 0:o.confirmed)=="boolean"?o.confirmed:void 0,clearContext:typeof(o==null?void 0:o.clearContext)=="boolean"?o.clearContext:void 0,message:typeof(o==null?void 0:o.message)=="string"?o.message:void 0,...(o==null?void 0:o.discarded)===!0?{discarded:!0}:{}}}case"offer_download":{const i=R0(n),s=i?xv(i):n,o=uf(s);let a;return typeof(o==null?void 0:o.displayName)=="string"?a=o.displayName:typeof(o==null?void 0:o.fileName)=="string"?a=o.fileName:a="",{contentUrl:typeof(o==null?void 0:o.contentUrl)=="string"?o.contentUrl:"",relativePath:typeof(o==null?void 0:o.relativePath)=="string"?o.relativePath:"",fileName:typeof(o==null?void 0:o.fileName)=="string"?o.fileName:"",displayName:a,size:typeof(o==null?void 0:o.size)=="number"?o.size:0,...typeof(o==null?void 0:o.mimeType)=="string"?{mimeType:o.mimeType}:{}}}case"preview_file":{const i=R0(n),s=i?xv(i):n,o=uf(s);let a;return typeof(o==null?void 0:o.displayName)=="string"?a=o.displayName:typeof(o==null?void 0:o.fileName)=="string"?a=o.fileName:a="",{contentUrl:typeof(o==null?void 0:o.contentUrl)=="string"?o.contentUrl:"",relativePath:typeof(o==null?void 0:o.relativePath)=="string"?o.relativePath:"",fileName:typeof(o==null?void 0:o.fileName)=="string"?o.fileName:"",displayName:a,size:typeof(o==null?void 0:o.size)=="number"?o.size:0,mimeType:typeof(o==null?void 0:o.mimeType)=="string"?o.mimeType:"application/octet-stream"}}case"image_generation":{const i=uf(n);return{contentUrl:typeof(i==null?void 0:i.contentUrl)=="string"?i.contentUrl:"",relativePath:typeof(i==null?void 0:i.relativePath)=="string"?i.relativePath:"",fileName:typeof(i==null?void 0:i.fileName)=="string"?i.fileName:""}}case"workflow":{const i=typeof t=="string"?t:"";return{taskId:(r=i.match(/Task ID:\s*(\S+)/))==null?void 0:r[1],text:i}}case"read_file":{if(typeof n=="string")return n;const i=_Ie(n);if(i.length>0)return{content:i.flatMap(o=>o.type==="text"?[o.text]:[]).join(""),blocks:i};const s=uf(n);return{content:typeof(s==null?void 0:s.content)=="string"?s.content:JSON.stringify(n,null,2)}}default:return n}}function wIe(e){return e.kind==="tool"}function eZ(e){return new Date(e).toISOString()}function Ti(e){return{id:e._id,messageId:e.messageId,timestamp:eZ(e.createdAt),hidden:e.hidden}}function CIe(e){return{id:e._id,messageId:e.messageId,hidden:e.hidden,kind:"tool",toolKind:e.tool.toolKind,toolName:e.tool.toolName,toolId:e.tool.toolId,input:e.tool.input,timestamp:eZ(e.createdAt)}}function kIe(e){if(e.debugRaw)try{const t=JSON.parse(e.debugRaw);return(t==null?void 0:t.tool_use_result)??void 0}catch{return}}function al(e){return typeof e=="number"?e:void 0}function M0(e){return typeof e=="string"?e:void 0}function EIe(e){if(!Wi(e))return;const t=e,n={readCount:al(t.readCount),searchCount:al(t.searchCount),bashCount:al(t.bashCount),editFileCount:al(t.editFileCount),linesAdded:al(t.linesAdded),linesRemoved:al(t.linesRemoved),otherToolCount:al(t.otherToolCount)};return Object.values(n).some(r=>r!==void 0)?n:void 0}function NIe(e){if(!e.debugRaw)return;let t;try{t=JSON.parse(e.debugRaw).toolUseResult}catch{return}if(!Wi(t))return;const n=t,r={agentId:M0(n.agentId),agentType:M0(n.agentType),status:M0(n.status),totalTokens:al(n.totalTokens),totalDurationMs:al(n.totalDurationMs),totalToolUseCount:al(n.totalToolUseCount),toolStats:EIe(n.toolStats),content:M0(n.content)};return r.agentId!==void 0||r.agentType!==void 0||r.totalTokens!==void 0||r.totalDurationMs!==void 0||r.status!==void 0?r:void 0}function M1(e){const t=new Map,n=[];for(const r of e)switch(r.kind){case"user_prompt":n.push({...Ti(r),kind:"user_prompt",content:r.content,attachments:r.attachments??[],steered:r.steered,autoContinue:r.autoContinue});break;case"system_init":n.push({...Ti(r),kind:"system_init",provider:r.provider,model:r.model,tools:r.tools,agents:r.agents,slashCommands:r.slashCommands,mcpServers:r.mcpServers,debugRaw:r.debugRaw});break;case"account_info":n.push({...Ti(r),kind:"account_info",accountInfo:r.accountInfo});break;case"assistant_text":n.push({...Ti(r),kind:"assistant_text",text:r.text});break;case"assistant_thinking":n.push({...Ti(r),kind:"assistant_thinking",text:r.text,signature:r.signature});break;case"api_error":n.push({...Ti(r),kind:"api_error",status:r.status,text:r.text,requestId:r.requestId});break;case"policy_refusal":n.push({...Ti(r),kind:"policy_refusal",text:r.text,requestId:r.requestId});break;case"tool_call":{const i=CIe(r);t.set(r.tool.toolId,{hydrated:i,normalized:r.tool}),wIe(i)&&n.push(i);break}case"tool_result":{const i=t.get(r.toolId);if(i){const s=i.normalized.toolKind==="ask_user_question"||i.normalized.toolKind==="exit_plan_mode"?kIe(r)??r.content:r.content;i.normalized.toolKind==="subagent_task"?i.hydrated.result=NIe(r):i.hydrated.result=SIe(i.normalized,s),i.hydrated.rawResult=s,i.hydrated.isError=r.isError,r.persisted&&(i.hydrated.persisted=r.persisted)}break}case"result":n.push({...Ti(r),kind:"result",success:!r.isError,cancelled:r.subtype==="cancelled",result:r.result,durationMs:r.durationMs,costUsd:r.costUsd});break;case"status":n.push({...Ti(r),kind:"status",status:r.status});break;case"context_window_updated":n.push({...Ti(r),kind:"context_window_updated",usage:r.usage});break;case"compact_boundary":n.push({...Ti(r),kind:"compact_boundary"});break;case"compact_summary":n.push({...Ti(r),kind:"compact_summary",summary:r.summary});break;case"context_cleared":n.push({...Ti(r),kind:"context_cleared"});break;case"interrupted":n.push({...Ti(r),kind:"interrupted"});break;case"memory_loaded":n.push({...Ti(r),kind:"memory_loaded",path:r.path});break;case"auto_continue_prompt":n.push({...Ti(r),kind:"auto_continue_prompt",scheduleId:r.scheduleId});break;case"pending_tool_request":n.push({...Ti(r),kind:"pending_tool_request",toolRequestId:r.toolRequestId,toolName:r.toolName,arguments:r.arguments});break;case"tool_request_resolved":break;default:n.push({...Ti(r),kind:"unknown",json:JSON.stringify(r,null,2)});break}return n}function tZ(e){return e.kind==="tool"}const TIe=["AskUserQuestion","ExitPlanMode","TodoWrite"],AIe=new Set(["TodoWrite"]);function RIe(e,t){for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(tZ(r)&&r.toolName===t&&!r.result)return r.id}return null}function MIe(e,t){for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(tZ(r)&&r.toolName===t)return r.id}return null}function jIe(e){const t={};for(const n of TIe)t[n]=AIe.has(n)?MIe(e,n):RIe(e,n);return t}function IIe(e){return e==="starting"||e==="running"||e==="waiting_for_user"}function PIe(e){return e==="starting"||e==="running"||e==="waiting_for_user"}const iL="pushDeviceId";function nZ(){return typeof localStorage>"u"?null:localStorage.getItem(iL)}function LIe(e){typeof localStorage>"u"||localStorage.setItem(iL,e)}function OIe(){typeof localStorage>"u"||localStorage.removeItem(iL)}function DIe(){return!(typeof window>"u"||typeof Notification>"u"||!("serviceWorker"in navigator)||typeof Reflect.get(globalThis,"PushManager")>"u")}function $Ie(){var t;if(typeof window>"u")return!1;if(window.isSecureContext)return!0;const e=((t=window.location)==null?void 0:t.hostname)??"";return e==="localhost"||e==="127.0.0.1"||e==="::1"}function sL(){if(!DIe())return{state:"unsupported"};if(!$Ie())return{state:"insecure-context"};switch(Notification.permission){case"granted":return{state:"granted"};case"denied":return{state:"denied"};default:return{state:"default"}}}function zIe(e){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64url"));const t="=".repeat((4-e.length%4)%4),n=(e+t).replace(/-/g,"+").replace(/_/g,"/"),r=atob(n),i=new Uint8Array(r.length);for(let s=0;s<r.length;s+=1)i[s]=r.charCodeAt(s);return i}function BIe(e){const t=e||"";return/iPhone|iPad/i.test(t)?"iPhone / iPad":/Android/i.test(t)?"Android":/Macintosh/i.test(t)?"Mac":/Windows/i.test(t)?"Windows PC":t||"Browser"}async function FIe(e){const t=sL();if(t.state==="unsupported")throw new Error("Push not supported in this browser");if(t.state==="insecure-context")throw new Error("Push requires a secure context (HTTPS)");if(t.state==="denied")throw new Error("Notification permission previously denied");if(await Notification.requestPermission()!=="granted")throw new Error("Notification permission was not granted");const r=await navigator.serviceWorker.register("/sw.js");await navigator.serviceWorker.ready;const i=await r.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:zIe(e.vapidPublicKey)}),s=i.toJSON(),o=s.endpoint??i.endpoint,a=s.keys??{};if(!o||!a.p256dh||!a.auth)throw new Error("Subscription returned without endpoint or keys");const l=navigator.userAgent??"",{id:d}=await e.sendToServer({subscription:{endpoint:o,keys:{p256dh:a.p256dh,auth:a.auth}},label:BIe(l),userAgent:l});return d}async function UIe(e){const n=await(await navigator.serviceWorker.ready).pushManager.getSubscription();n&&await n.unsubscribe(),await e.sendToServer(e.pushDeviceId)}typeof navigator<"u"&&"serviceWorker"in navigator&&navigator.serviceWorker.addEventListener("message",e=>{const t=e.data;(t==null?void 0:t.type)==="kanna.navigate"&&typeof t.url=="string"&&(window.location.href=t.url)});const HIe=25e3,WIe=15e3,VIe=4e3,k6="kanna:profile-send-to-starting";function E6(){try{return window.sessionStorage.getItem(k6)==="1"||window.localStorage.getItem(k6)==="1"}catch{return!1}}class KIe{constructor(t){U(this,"url");U(this,"ws",null);U(this,"started",!1);U(this,"reconnectTimer",null);U(this,"reconnectDelayMs",750);U(this,"subscriptions",new Map);U(this,"pending",new Map);U(this,"outboundQueue",[]);U(this,"statusListeners",new Set);U(this,"heartbeatTimer",null);U(this,"pingTimeoutTimer",null);U(this,"pingPromise",null);U(this,"lastOpenAt",0);U(this,"lastMessageAt",0);U(this,"reconnectImmediatelyOnClose",!1);U(this,"handleWindowFocus",()=>{this.ensureHealthyConnection()});U(this,"handleVisibilityChange",()=>{if(document.visibilityState==="visible"){this.startHeartbeat(),this.ensureHealthyConnection();return}this.stopHeartbeat()});U(this,"handleOnline",()=>{this.ensureHealthyConnection()});this.url=t}start(){this.started||(this.started=!0,window.addEventListener("focus",this.handleWindowFocus),window.addEventListener("online",this.handleOnline),document.addEventListener("visibilitychange",this.handleVisibilityChange),this.connect())}dispose(){var t;this.started=!1,this.reconnectTimer&&(window.clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.stopHeartbeat(),this.clearPingState(),window.removeEventListener("focus",this.handleWindowFocus),window.removeEventListener("online",this.handleOnline),document.removeEventListener("visibilitychange",this.handleVisibilityChange),(t=this.ws)==null||t.close(),this.ws=null;for(const n of this.pending.values())n.reject(new Error("Socket disposed"));this.pending.clear()}onStatus(t){return this.statusListeners.add(t),t(this.getStatus()),()=>{this.statusListeners.delete(t)}}subscribe(t,n,r){const i=Sf(),s={topic:t,listener:n,eventListener:r};return this.subscriptions.set(i,s),this.enqueue({v:1,type:"subscribe",id:i,topic:t}),()=>{this.subscriptions.delete(i),this.enqueue({v:1,type:"unsubscribe",id:i})}}subscribeTerminal(t,n){const r=Sf(),i={type:"terminal",terminalId:t},s={topic:i,listener:n.onSnapshot,eventListener:n.onEvent};return this.subscriptions.set(r,s),this.enqueue({v:1,type:"subscribe",id:r,topic:i}),()=>{this.subscriptions.delete(r),this.enqueue({v:1,type:"unsubscribe",id:r})}}command(t){const n=Sf(),r={v:1,type:"command",id:n,command:t};return new Promise((i,s)=>{this.pending.set(n,{resolve:i,reject:s}),this.enqueue(r)})}setFocusedChat(t){const n=Sf();this.enqueue({v:1,type:"command",id:n,command:{type:"push.setFocusedChat",chatId:t}})}ensureHealthyConnection(){return!this.ws||this.ws.readyState===WebSocket.CLOSED||this.ws.readyState===WebSocket.CLOSING?(this.reconnectNow(),Promise.resolve()):this.ws.readyState===WebSocket.CONNECTING||!this.isConnectionStale()?Promise.resolve():this.sendPing()}connect(){this.started&&(this.emitStatus("connecting"),this.ws=new WebSocket(this.url),this.ws.addEventListener("open",()=>{this.reconnectDelayMs=750,this.reconnectImmediatelyOnClose=!1,this.lastOpenAt=Date.now(),this.lastMessageAt=this.lastOpenAt,this.emitStatus("connected"),this.startHeartbeat();for(const[n,r]of this.subscriptions.entries())this.sendNow({v:1,type:"subscribe",id:n,topic:r.topic});for(;this.outboundQueue.length>0;){const n=this.outboundQueue.shift();n&&this.sendNow(n)}const t=nZ();t&&this.sendNow({v:1,type:"command",id:Sf(),command:{type:"push.identifyDevice",pushDeviceId:t}})}),this.ws.addEventListener("message",t=>{var s,o;this.lastMessageAt=Date.now();const n=performance.now(),r=String(t.data);let i;try{i=JSON.parse(r)}catch{return}if(E6()&&i.type==="snapshot"&&i.snapshot.type==="chat"&&((s=i.snapshot.data)==null?void 0:s.runtime.status)==="starting"&&Qs.debug("[kanna/send->starting][client-ws]",{stage:"socket_message_received",receivedAt:n,payloadBytes:r.length,chatId:i.snapshot.data.runtime.chatId,status:i.snapshot.data.runtime.status,messageCount:i.snapshot.data.messages.length}),E6()&&i.type==="ack"&&Qs.debug("[kanna/send->starting][client-ws]",{stage:"socket_ack_received",receivedAt:n,payloadBytes:r.length,commandId:i.id}),i.type==="snapshot"){const a=this.subscriptions.get(i.id);a==null||a.listener(i.snapshot.data);return}if(i.type==="event"){const a=this.subscriptions.get(i.id);(o=a==null?void 0:a.eventListener)==null||o.call(a,i.event);return}if(i.type==="ack"){const a=this.pending.get(i.id);if(!a)return;this.pending.delete(i.id),a.resolve(i.result);return}if(i.type==="error"){if(!i.id){Qs.error(sfe,i.message);return}const a=this.pending.get(i.id);if(!a)return;this.pending.delete(i.id),a.reject(new Error(i.message))}}),this.ws.addEventListener("close",()=>{if(!this.started)return;const t=this.reconnectImmediatelyOnClose;this.reconnectImmediatelyOnClose=!1,this.stopHeartbeat(),this.clearPingState(),this.emitStatus("disconnected");for(const n of this.pending.values())n.reject(new Error("Disconnected"));if(this.pending.clear(),t){this.connect();return}this.scheduleReconnect()}))}scheduleReconnect(){this.reconnectTimer===null&&(this.reconnectTimer=window.setTimeout(()=>{this.reconnectTimer=null,this.connect(),this.reconnectDelayMs=Math.min(this.reconnectDelayMs*2,5e3)},this.reconnectDelayMs))}getStatus(){var t,n;return((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN?"connected":((n=this.ws)==null?void 0:n.readyState)===WebSocket.CONNECTING?"connecting":"disconnected"}emitStatus(t){for(const n of this.statusListeners)n(t)}isConnectionStale(){const t=Math.max(this.lastMessageAt,this.lastOpenAt);return t>0&&Date.now()-t>=HIe}sendPing(){if(this.pingPromise)return this.pingPromise;const t=this.command({type:"system.ping"}).then(()=>{this.clearPingState()}).catch(n=>{throw this.clearPingState(),this.reconnectNow(),n});return this.pingTimeoutTimer=window.setTimeout(()=>{this.clearPingState(),this.reconnectNow()},VIe),this.pingPromise=t,t}reconnectNow(){if(this.reconnectTimer!==null&&(window.clearTimeout(this.reconnectTimer),this.reconnectTimer=null),!this.ws||this.ws.readyState===WebSocket.CLOSED){this.connect();return}this.ws.readyState!==WebSocket.CONNECTING&&(this.reconnectImmediatelyOnClose=!0,this.ws.close())}startHeartbeat(){document.visibilityState==="visible"&&this.heartbeatTimer===null&&(this.heartbeatTimer=window.setInterval(()=>{var t;if(document.visibilityState!=="visible"){this.stopHeartbeat();return}((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN&&this.ensureHealthyConnection()},WIe))}stopHeartbeat(){this.heartbeatTimer!==null&&(window.clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}clearPingState(){this.pingTimeoutTimer!==null&&(window.clearTimeout(this.pingTimeoutTimer),this.pingTimeoutTimer=null),this.pingPromise=null}enqueue(t){var n;if(((n=this.ws)==null?void 0:n.readyState)===WebSocket.OPEN){this.sendNow(t);return}this.outboundQueue.push(t)}sendNow(t){var n;(n=this.ws)==null||n.send(JSON.stringify(t))}}const GIe=[],j1=dr()(e=>({byChat:{},setRuns:(t,n)=>e(r=>({byChat:{...r.byChat,[t]:n}}))}));function oL(e){return t=>t.byChat[e]??GIe}const qIe=[],j0=dr()(e=>({models:qIe,status:"idle",error:null,setLoading:()=>e({status:"loading",error:null}),setModels:t=>e({models:t,status:"ready",error:null}),setError:t=>e({status:"error",error:t})})),YIe=[],XIe=[],JIe={},ZIe={starredProjectGroups:[],projectGroups:[],stacks:[]};function QIe(){return typeof window>"u"?null:window.sessionStorage.getItem("kanna:ui-update-restart")}const me=dr()(e=>({sidebarData:ZIe,optimisticSidebarProjectOrder:null,localProjects:null,updateSnapshot:null,uiRestartPhase:QIe(),chatSnapshot:null,olderHistoryEntries:XIe,isHistoryLoading:!1,historyCursor:null,hasOlderHistory:!1,projectDiffSnapshots:JIe,keybindings:null,appSettings:null,pushConfig:null,llmProvider:null,connectionStatus:"connecting",sidebarReady:!1,localProjectsReady:!1,chatReady:!1,selectedProjectId:null,sidebarOpen:!1,sidebarCollapsed:!1,addProjectModalOpen:!1,commandError:null,startingLocalPath:null,pendingChatId:null,optimisticUserPrompts:YIe,optimisticProcessing:null,focusEpoch:0,setSidebarData:t=>e({sidebarData:t}),setOptimisticSidebarProjectOrder:t=>e(n=>({optimisticSidebarProjectOrder:typeof t=="function"?t(n.optimisticSidebarProjectOrder):t})),setLocalProjects:t=>e({localProjects:t}),setUpdateSnapshot:t=>e({updateSnapshot:t}),setUiRestartPhase:t=>e({uiRestartPhase:t}),setChatSnapshot:t=>e(n=>({chatSnapshot:typeof t=="function"?t(n.chatSnapshot):t})),setOlderHistoryEntries:t=>e(n=>({olderHistoryEntries:typeof t=="function"?t(n.olderHistoryEntries):t})),setIsHistoryLoading:t=>e({isHistoryLoading:t}),setHistoryCursor:t=>e({historyCursor:t}),setHasOlderHistory:t=>e({hasOlderHistory:t}),setProjectDiffSnapshots:t=>e(n=>({projectDiffSnapshots:typeof t=="function"?t(n.projectDiffSnapshots):t})),setKeybindings:t=>e({keybindings:t}),setAppSettings:t=>e({appSettings:t}),setPushConfig:t=>e({pushConfig:t}),setLlmProvider:t=>e({llmProvider:t}),setConnectionStatus:t=>e({connectionStatus:t}),setSidebarReady:t=>e({sidebarReady:t}),setLocalProjectsReady:t=>e({localProjectsReady:t}),setChatReady:t=>e({chatReady:t}),setSelectedProjectId:t=>e({selectedProjectId:t}),setSidebarOpen:t=>e({sidebarOpen:t}),setSidebarCollapsed:t=>e({sidebarCollapsed:t}),setAddProjectModalOpen:t=>e({addProjectModalOpen:t}),setCommandError:t=>e({commandError:t}),setStartingLocalPath:t=>e({startingLocalPath:t}),setPendingChatId:t=>e({pendingChatId:t}),setOptimisticUserPrompts:t=>e(n=>({optimisticUserPrompts:typeof t=="function"?t(n.optimisticUserPrompts):t})),setOptimisticProcessing:t=>e(n=>({optimisticProcessing:typeof t=="function"?t(n.optimisticProcessing):t})),incrementFocusEpoch:()=>e(t=>({focusEpoch:t.focusEpoch+1}))}));function ePe(e,t){const n=["claude","codex","openrouter"];for(const r of n)if(e[r]!==t[r])return!1;return!0}function tPe(e,t){return e===t?!0:!e||!t?!1:e.chatId===t.chatId&&e.projectId===t.projectId&&e.localPath===t.localPath&&e.title===t.title&&e.status===t.status&&e.isDraining===t.isDraining&&e.provider===t.provider&&e.planMode===t.planMode&&ePe(e.sessionTokensByProvider,t.sessionTokensByProvider)}function nPe(e,t){return e===t?!0:!e||!t||e.length!==t.length?!1:e.every((n,r)=>{var i;return n._id===((i=t[r])==null?void 0:i._id)})}function rPe(e,t){return t.length===0?e:e.map(n=>n.id!=="openrouter"?n:{...n,models:t.map(r=>({id:r.id,label:r.label,supportsEffort:!1}))})}function iPe(e,t){return e===t?!0:!e||!t||e.length!==t.length?!1:e.every((n,r)=>{var i;return n.id===((i=t[r])==null?void 0:i.id)})}function sPe(e,t){return e===t?!0:!e||!t?!1:e.hasOlder===t.hasOlder&&e.olderCursor===t.olderCursor&&e.recentLimit===t.recentLimit}function oPe(e,t){return e.id===t.id&&e.content===t.content&&e.createdAt===t.createdAt&&e.provider===t.provider&&e.model===t.model&&e.planMode===t.planMode&&JSON.stringify(e.modelOptions)===JSON.stringify(t.modelOptions)&&aPe(e.attachments,t.attachments)}function aPe(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>{const i=t[r];return!!i&&n.id===i.id&&n.kind===i.kind&&n.displayName===i.displayName&&n.absolutePath===i.absolutePath&&n.relativePath===i.relativePath&&n.contentUrl===i.contentUrl&&n.mimeType===i.mimeType&&n.size===i.size})}function lPe(e,t){return e===t?!0:!e||!t||e.length!==t.length?!1:e.every((n,r)=>oPe(n,t[r]))}function cPe(e,t){var s,o;if(e===t)return!0;if(!e||!t||e.status!==t.status||e.branchName!==t.branchName||e.defaultBranchName!==t.defaultBranchName||e.hasOriginRemote!==t.hasOriginRemote||e.originRepoSlug!==t.originRepoSlug||e.hasUpstream!==t.hasUpstream||e.aheadCount!==t.aheadCount||e.behindCount!==t.behindCount||e.lastFetchedAt!==t.lastFetchedAt)return!1;const n=((s=e.branchHistory)==null?void 0:s.entries)??[],r=((o=t.branchHistory)==null?void 0:o.entries)??[];return n.length!==r.length||!n.every((a,l)=>{const d=r[l];return!!d&&a.sha===d.sha&&a.summary===d.summary&&a.description===d.description&&a.authorName===d.authorName&&a.authoredAt===d.authoredAt&&a.githubUrl===d.githubUrl&&a.tags.length===d.tags.length&&a.tags.every((h,p)=>h===d.tags[p])})||e.files.length!==t.files.length?!1:e.files.every((a,l)=>{const d=t.files[l];return!!d&&a.path===d.path&&a.changeType===d.changeType&&a.isUntracked===d.isUntracked&&a.additions===d.additions&&a.deletions===d.deletions&&a.patchDigest===d.patchDigest&&a.mimeType===d.mimeType&&a.size===d.size})}function uPe(e,t){return!!(e&&e.status!=="unknown"&&t&&t.status==="unknown"&&t.files.length===0)}function dPe(e,t){if(e===t)return!0;if(!e||!t)return!1;const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(i=>{const s=e[i],o=t[i];return!s||!o?!1:s.state===o.state&&s.scheduledAt===o.scheduledAt&&s.resetAt===o.resetAt&&s.detectedAt===o.detectedAt&&s.tz===o.tz})}function fPe(e,t){if(e===t)return!0;if(!e||!t)return!1;const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(i=>{const s=e[i],o=t[i];return!s||!o?!1:s.state===o.state&&s.url===o.url&&s.error===o.error&&s.port===o.port&&s.activatedAt===o.activatedAt&&s.stoppedAt===o.stoppedAt})}function hPe(e,t){if(e===t)return!0;if(!e||!t)return!1;const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(i=>{var a,l,d,h,p,m;const s=e[i],o=t[i];return!s||!o?!1:s.status===o.status&&s.entries.length===o.entries.length&&(s.finalText??"")===(o.finalText??"")&&(((a=s.pendingTool)==null?void 0:a.toolUseId)??null)===(((l=o.pendingTool)==null?void 0:l.toolUseId)??null)&&(((d=s.usage)==null?void 0:d.outputTokens)??null)===(((h=o.usage)==null?void 0:h.outputTokens)??null)&&s.finishedAt===o.finishedAt&&(((p=s.error)==null?void 0:p.code)??null)===(((m=o.error)==null?void 0:m.code)??null)})}function pPe(e,t){return e===t?!0:!e||!t?!1:tPe(e.runtime,t.runtime)&&lPe(e.queuedMessages,t.queuedMessages)&&nPe(e.messages,t.messages)&&sPe(e.history,t.history)&&iPe(e.availableProviders,t.availableProviders)&&dPe(e.schedules,t.schedules)&&e.liveScheduleId===t.liveScheduleId&&fPe(e.tunnels,t.tunnels)&&e.liveTunnelId===t.liveTunnelId&&hPe(e.subagentRuns,t.subagentRuns)}function N6(e,t){const n=new Map;for(const r of e)n.set(r._id,r);for(const r of t)n.set(r._id,r);return[...n.values()]}function mPe(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if((n==null?void 0:n.kind)==="user_prompt"&&n.content.trim().length>0)return n.content}return null}const T6="__new_chat__",rZ="lever-theme",iZ="chat-sound-preferences",sZ="terminal-preferences",oZ="chat-preferences";function kT(e){if(typeof window>"u")return null;const t=window.localStorage.getItem(e);if(!t)return null;try{const n=JSON.parse(t);return Wi(n.state)?n.state:null}catch{return null}}function gPe(){if(typeof window>"u")return null;const e={},t=window.localStorage.getItem(rZ);(t==="light"||t==="dark"||t==="system")&&(e.theme=t);const n=kT(iZ);((n==null?void 0:n.chatSoundPreference)==="never"||(n==null?void 0:n.chatSoundPreference)==="unfocused"||(n==null?void 0:n.chatSoundPreference)==="always")&&(e.chatSoundPreference=n.chatSoundPreference),((n==null?void 0:n.chatSoundId)==="blow"||(n==null?void 0:n.chatSoundId)==="bottle"||(n==null?void 0:n.chatSoundId)==="frog"||(n==null?void 0:n.chatSoundId)==="funk"||(n==null?void 0:n.chatSoundId)==="glass"||(n==null?void 0:n.chatSoundId)==="ping"||(n==null?void 0:n.chatSoundId)==="pop"||(n==null?void 0:n.chatSoundId)==="purr"||(n==null?void 0:n.chatSoundId)==="tink")&&(e.chatSoundId=n.chatSoundId);const r=kT(sZ);if(r){e.terminal={},typeof r.scrollbackLines=="number"&&(e.terminal.scrollbackLines=r.scrollbackLines),typeof r.minColumnWidth=="number"&&(e.terminal.minColumnWidth=r.minColumnWidth);const s={};(r.editorPreset==="cursor"||r.editorPreset==="vscode"||r.editorPreset==="xcode"||r.editorPreset==="windsurf"||r.editorPreset==="custom")&&(s.preset=r.editorPreset),typeof r.editorCommandTemplate=="string"&&(s.commandTemplate=r.editorCommandTemplate),Object.keys(s).length>0&&(e.editor=s)}const i=kT(oZ);if(((i==null?void 0:i.defaultProvider)==="last_used"||(i==null?void 0:i.defaultProvider)==="claude"||(i==null?void 0:i.defaultProvider)==="codex")&&(e.defaultProvider=i.defaultProvider),Wi(i==null?void 0:i.providerDefaults)){const s=i.providerDefaults;e.providerDefaults=s}return e.browserSettingsMigrated=!0,Object.keys(e).length>1?e:null}function vPe(){typeof window>"u"||(window.localStorage.removeItem(rZ),window.localStorage.removeItem(iZ),window.localStorage.removeItem(sZ),window.localStorage.removeItem(oZ))}function yv(e){Ir.getState().setFromServer(e);const t=ws.getState();t.setScrollbackLines(e.terminal.scrollbackLines),t.setMinColumnWidth(e.terminal.minColumnWidth),t.setEditorPreset(e.editor.preset),t.setEditorCommandTemplate(e.editor.commandTemplate);const n=Af.getState();n.setChatSoundPreference(e.chatSoundPreference),n.setChatSoundId(e.chatSoundId),Ts.getState().applyServerDefaults(e.defaultProvider,e.providerDefaults)}function bPe(e){return JSON.stringify({id:e.id,kind:e.kind,displayName:e.displayName,relativePath:e.relativePath,mimeType:e.mimeType,size:e.size,contentUrl:e.contentUrl})}function aL(e,t=[]){return JSON.stringify({content:e,attachments:t.map(bPe)})}function xPe(e,t){return e.reduce((n,r)=>r.kind!=="user_prompt"?n:n+(aL(r.content,r.attachments??[])===t?1:0),0)}function yPe(e,t,n){const r=new Map;for(const i of n){if(i.kind!=="user_prompt")continue;const s=aL(i.content,i.attachments??[]);r.set(s,(r.get(s)??0)+1)}return e.filter(i=>i.scopeId!==t?!0:(r.get(i.signature)??0)<i.requiredMatchCount)}function _Pe(e,t,n){return e.some(r=>r.id===t)?e.filter(r=>r.id!==t):e}const SPe=200,wPe=500;function A6(e,t){var r;const n=e.find(i=>i.chats.some(s=>s.chatId===t));return n?((r=n.chats.find(i=>i.chatId!==t))==null?void 0:r.chatId)??null:null}function R6(e,t){if(!(t!=null&&t.length)||e.length<=1)return e;const n=new Map(e.map((o,a)=>[o.groupKey,a])),r=new Set,i=t.map(o=>{if(r.has(o))return null;r.add(o);const a=n.get(o);return a===void 0?null:e[a]}).filter(o=>!!o);if(i.length===0)return e;const s=[...i,...e.filter(o=>!r.has(o.groupKey))];return s.every((o,a)=>o===e[a])?e:s}function CPe(e=document){return e.visibilityState==="visible"&&e.hasFocus()}function kPe(){return`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`}function EPe(){const e=_.useMemo(()=>new KIe(kPe()),[]);return _.useEffect(()=>(e.start(),()=>{e.dispose()}),[e]),e}const M6="kanna:profile-send-to-starting";function NPe(){try{return window.sessionStorage.getItem(M6)==="1"||window.localStorage.getItem(M6)==="1"}catch{return!1}}function aZ(e){return Number((performance.now()-e).toFixed(1))}function $u(e,t,n){!e||!NPe()||Qs.debug("[kanna/send->starting][client]",{traceId:e.traceId,stage:t,elapsedMs:aZ(e.startedAt),serverChatId:e.serverChatId,routeChatIdAtSend:e.routeChatIdAtSend,...n})}function TPe(e){var t,n;return(e==null?void 0:e.provider)==="claude"&&e.model&&((t=e.modelOptions)!=null&&t.claude)?{provider:"claude",model:e.model,modelOptions:{reasoningEffort:e.modelOptions.claude.reasoningEffort??"high",contextWindow:e.modelOptions.claude.contextWindow??"200k"},planMode:!!e.planMode}:(e==null?void 0:e.provider)==="codex"&&e.model&&((n=e.modelOptions)!=null&&n.codex)?{provider:"codex",model:e.model,modelOptions:{reasoningEffort:e.modelOptions.codex.reasoningEffort??"high",fastMode:e.modelOptions.codex.fastMode??!1},planMode:!!e.planMode}:null}function APe(e,t){var n;return t?((n=e.find(r=>r.chats.some(i=>i.chatId===t)))==null?void 0:n.groupKey)??null:null}function RPe(e,t){return e==="awaiting_disconnect"&&t==="disconnected"?"awaiting_server_ready":"none"}function MPe(e,t){return t==="updating"||t==="restart_pending"?{active:!0,label:"Installing update"}:e==="awaiting_disconnect"||e==="awaiting_server_ready"?{active:!0,label:"Re-deploying Kanna"}:{active:!1,label:""}}const jPe=30,lL="kanna:ui-update-restart",lZ="kanna:last-update-reload-request";function IPe(e){return e+jPe}function PPe(e,t){return t>0?t:e}function j6(){return window.sessionStorage.getItem(lL)}function LPe(e){window.sessionStorage.setItem(lL,e)}function OPe(){window.sessionStorage.removeItem(lL)}function DPe(e,t){return e?String(e)!==t:!1}function $Pe(){return window.sessionStorage.getItem(lZ)}function zPe(e){window.sessionStorage.setItem(lZ,String(e))}function BPe(){return"/auth/status"}async function FPe(e=fetch){return(await e(BPe(),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}})).ok}function UPe(e){const t=e.selectedProjectId??e.sidebarProjectId??null;return t?{kind:"project_id",projectId:t}:e.fallbackLocalProjectPath?{kind:"local_path",localPath:e.fallbackLocalProjectPath}:null}function HPe(e,t){return!e||!t?null:e.runtime.chatId!==t?(e.runtime.chatId,e.runtime.provider,null):e}function WPe(e){var va,vs,Ya;const t=Ad(),n=EPe(),r=Ox(),i=me(q=>q.sidebarData),s=me(q=>q.optimisticSidebarProjectOrder),o=me(q=>q.localProjects),a=me(q=>q.updateSnapshot),l=me(q=>q.uiRestartPhase),d=_.useCallback(q=>{LPe(q),me.getState().setUiRestartPhase(q)},[]),h=_.useCallback(()=>{OPe(),me.getState().setUiRestartPhase(null)},[]),p=me(q=>q.chatSnapshot),m=me(q=>q.olderHistoryEntries),v=me(q=>q.isHistoryLoading),b=me(q=>q.historyCursor),x=me(q=>q.hasOlderHistory),S=me(q=>q.projectDiffSnapshots),C=me(q=>q.keybindings),k=me(q=>q.appSettings),w=me(q=>q.pushConfig),N=me(q=>q.llmProvider),A=me(q=>q.connectionStatus),T=me(q=>q.sidebarReady),M=me(q=>q.localProjectsReady),j=me(q=>q.chatReady),P=me(q=>q.selectedProjectId),D=me(q=>q.sidebarOpen),L=me(q=>q.sidebarCollapsed),I=me(q=>q.addProjectModalOpen),$=me(q=>q.commandError),H=me(q=>q.startingLocalPath),z=me(q=>q.pendingChatId),F=me(q=>q.optimisticUserPrompts),K=me(q=>q.optimisticProcessing),W=me(q=>q.focusEpoch),V=_.useRef(new Map),X=DR(mm(q=>Object.keys(q.drafts).sort())),G=DR(mm(q=>Object.keys(q.attachmentDrafts).sort())),te=_.useRef(0),oe=_.useRef(null),ue=_.useRef({projectId:null,diffs:null}),de=ive(ws(q=>q.editorPreset)),ee=_.useMemo(()=>R6(i.projectGroups,s),[s,i.projectGroups]),ne=_.useRef(ee);_.useLayoutEffect(()=>{ne.current=ee});const ie=_.useMemo(()=>ee===i.projectGroups?i:{...i,projectGroups:ee},[i,ee]);_.useEffect(()=>n.onStatus(q=>me.getState().setConnectionStatus(q)),[n]),_.useEffect(()=>n.subscribe({type:"sidebar"},q=>{const Z=me.getState();Z.setSidebarData(q),Z.setOptimisticSidebarProjectOrder(xe=>xe&&R6(q.projectGroups,xe)===q.projectGroups?null:xe),Z.setSidebarReady(!0),Z.setCommandError(null)}),[n]),_.useEffect(()=>{if(A!=="connected")return;const q=[...new Set([...X,...G])].sort();n.command({type:"chat.setDraftProtection",chatIds:q}).catch(Z=>{me.getState().setCommandError(Z instanceof Error?Z.message:String(Z))})},[G,A,X,n]),_.useEffect(()=>n.subscribe({type:"local-projects"},q=>{const Z=me.getState();Z.setLocalProjects(q),Z.setLocalProjectsReady(!0),Z.setCommandError(null)}),[n]),_.useEffect(()=>n.subscribe({type:"update"},q=>{const Z=me.getState();Z.setUpdateSnapshot(q),Z.setCommandError(null)}),[n]),_.useEffect(()=>{A==="connected"&&n.command({type:"update.check",force:!0}).catch(q=>{me.getState().setCommandError(q instanceof Error?q.message:String(q))})},[A,n]),_.useEffect(()=>{const q=a==null?void 0:a.reloadRequestedAt;DPe(q,$Pe())&&q&&(zPe(q),d("awaiting_disconnect"))},[d,a==null?void 0:a.reloadRequestedAt]),_.useEffect(()=>{const q=j6();RPe(q,A)==="awaiting_server_ready"&&d("awaiting_server_ready")},[A,d]),_.useEffect(()=>{if(j6()!=="awaiting_server_ready")return;let q=!1,Z=null;const xe=async()=>{try{if(await FPe()){if(q)return;h(),window.location.reload();return}}catch{}q||(Z=window.setTimeout(()=>{xe()},500))};return xe(),()=>{q=!0,Z!==null&&window.clearTimeout(Z)}},[A,h]),_.useEffect(()=>{function q(){a!=null&&a.lastCheckedAt&&(Date.now()-a.lastCheckedAt<=3600*1e3||n.command({type:"update.check"}).catch(Z=>{me.getState().setCommandError(Z instanceof Error?Z.message:String(Z))}))}return window.addEventListener("focus",q),()=>{window.removeEventListener("focus",q)}},[n,a==null?void 0:a.lastCheckedAt]),_.useEffect(()=>n.subscribe({type:"keybindings"},q=>{const Z=me.getState();Z.setKeybindings(q),Z.setCommandError(null)}),[n]),_.useEffect(()=>n.subscribe({type:"app-settings"},q=>{const Z=me.getState();Z.setAppSettings(q),yv(q),Z.setCommandError(null)}),[n]),_.useEffect(()=>n.subscribe({type:"push-config"},q=>{me.getState().setPushConfig(q)}),[n]),_.useEffect(()=>n.subscribe({type:"pty-instances"},q=>{wc.getState().applySnapshot(q.instances)},q=>{q.type==="pty-instances.added"?wc.getState().applyDiff({op:"added",instance:q.instance}):q.type==="pty-instances.updated"?wc.getState().applyDiff({op:"updated",instance:q.instance}):wc.getState().applyDiff({op:"removed",chatId:q.chatId})}),[n]);const ae=_.useCallback(async()=>{try{Ir.getState().setHydrationStatus("loading");const q=await n.command({type:"settings.readAppSettings"}),Z=me.getState();Z.setAppSettings(q),yv(q),Z.setCommandError(null)}catch(q){Ir.getState().setHydrationStatus("error"),me.getState().setCommandError(q instanceof Error?q.message:String(q))}},[n]),Q=_.useCallback(async(q,Z)=>{try{await n.command({type:"chat.setPolicyOverride",chatId:q,policyOverride:Z}),me.getState().setCommandError(null)}catch(xe){throw me.getState().setCommandError(xe instanceof Error?xe.message:String(xe)),xe}},[n]),ke=_.useCallback(async q=>{try{Ir.getState().applyOptimisticPatch(q);const Z=await n.command({type:"settings.writeAppSettingsPatch",patch:q}),xe=me.getState();xe.setAppSettings(Z),yv(Z),xe.setCommandError(null)}catch(Z){throw me.getState().setCommandError(Z instanceof Error?Z.message:String(Z)),await ae(),Z}},[ae,n]),Se=_.useCallback(async q=>{try{await n.command({type:"settings.testMcpServer",id:q}),me.getState().setCommandError(null)}catch(Z){throw me.getState().setCommandError(Z instanceof Error?Z.message:String(Z)),Z}},[n]),Ne=_.useCallback(async q=>{try{const Z=await n.command({type:"settings.startMcpOAuth",id:q});return me.getState().setCommandError(null),Z}catch(Z){const xe=Z instanceof Error?Z.message:String(Z);return me.getState().setCommandError(xe),{ok:!1,error:xe}}},[n]),Xe=_.useCallback(async(q,Z)=>{try{const xe=await n.command({type:"settings.completeMcpOAuth",id:q,callbackUrl:Z});return me.getState().setCommandError(null),xe}catch(xe){const et=xe instanceof Error?xe.message:String(xe);return me.getState().setCommandError(et),{ok:!1,error:et}}},[n]),ht=_.useCallback(async q=>{try{Ir.getState().applyOptimisticPatch({cloudflareTunnel:q});const Z=await n.command({type:"appSettings.setCloudflareTunnel",patch:q}),xe=me.getState();xe.setAppSettings(Z),yv(Z),xe.setCommandError(null)}catch(Z){throw me.getState().setCommandError(Z instanceof Error?Z.message:String(Z)),await ae(),Z}},[ae,n]),St=_.useCallback(async q=>{try{Ir.getState().applyOptimisticPatch({claudeAuth:q});const Z=await n.command({type:"appSettings.setClaudeAuth",patch:q}),xe=me.getState();xe.setAppSettings(Z),yv(Z),xe.setCommandError(null)}catch(Z){throw me.getState().setCommandError(Z instanceof Error?Z.message:String(Z)),await ae(),Z}},[ae,n]),Bt=_.useCallback(async q=>await n.command({type:"appSettings.testOAuthToken",token:q}),[n]),Yt=_.useCallback(async()=>{try{const q=await n.command({type:"settings.readLlmProvider"}),Z=me.getState();Z.setLlmProvider(q),Z.setCommandError(null)}catch(q){me.getState().setCommandError(q instanceof Error?q.message:String(q))}},[n]),Mt=_.useCallback(async q=>{try{const Z=await n.command({type:"settings.writeLlmProvider",provider:q.provider,apiKey:q.apiKey,model:q.model,baseUrl:q.baseUrl}),xe=me.getState();xe.setLlmProvider(Z),xe.setCommandError(null)}catch(Z){throw me.getState().setCommandError(Z instanceof Error?Z.message:String(Z)),Z}},[n]),mn=_.useCallback(async q=>await n.command({type:"settings.validateLlmProvider",provider:q.provider,apiKey:q.apiKey,model:q.model,baseUrl:q.baseUrl}),[n]);_.useEffect(()=>{A==="connected"&&ae()},[A,ae]),_.useEffect(()=>{if(A!=="connected")return;j0.getState().setLoading(),n.command({type:"settings.listOpenRouterModels"}).then(Z=>{j0.getState().setModels(Z)}).catch(Z=>{const xe=Z instanceof Error?Z.message:String(Z);j0.getState().setError(xe)})},[A,n]),_.useEffect(()=>{if(A!=="connected"||(k==null?void 0:k.browserSettingsMigrated)!==!1)return;const q=gPe();q&&ke(q).then(vPe).catch(()=>{})},[k==null?void 0:k.browserSettingsMigrated,A,ke]),_.useEffect(()=>{A==="connected"&&Yt()},[A,Yt]),_.useEffect(()=>{function q(){me.getState().incrementFocusEpoch()}return window.addEventListener("focus",q),document.addEventListener("visibilitychange",q),()=>{window.removeEventListener("focus",q),document.removeEventListener("visibilitychange",q)}},[]),_.useEffect(()=>{if(!e){me.getState().setChatSnapshot(null),me.getState().setChatReady(!0);return}++te.current,ne.current.length,ne.current.reduce((Z,xe)=>Z+xe.chats.length,0),me.getState().setChatSnapshot(null),me.getState().setChatReady(!1);const q=n.subscribe({type:"chat",chatId:e,recentLimit:SPe},Z=>{if(Z!=null&&Z.runtime.chatId){const et=[...V.current.values()].filter(Cn=>Cn.serverChatId===Z.runtime.chatId).sort((Cn,Rr)=>Rr.startedAt-Cn.startedAt)[0];et&&et.snapshotAt===void 0&&(et.snapshotAt=performance.now(),$u(et,"chat_snapshot_received",{status:Z.runtime.status,messageCount:Z.messages.length}))}me.getState().setChatSnapshot(et=>{const Cn=pPe(et,Z);return Z==null||Z.runtime.chatId,Z==null||Z.runtime.provider,Z==null||Z.runtime.status,Z==null||Z.messages.length,Cn?et:Z});const xe=me.getState();if(xe.setHistoryCursor((Z==null?void 0:Z.history.olderCursor)??null),xe.setHasOlderHistory((Z==null?void 0:Z.history.hasOlder)??!1),xe.setChatReady(!0),xe.setCommandError(null),Z){const et=rL.getState();et.setForChat(Z.runtime.chatId,Z.slashCommands??[]),et.setLoadingForChat(Z.runtime.chatId,Z.slashCommandsLoading??!1)}});return()=>{ne.current.length,ne.current.reduce((Z,xe)=>Z+xe.chats.length,0),q()}},[e,n]),_.useEffect(()=>{if(e)return n.subscribe({type:"workflows",chatId:e},q=>{j1.getState().setRuns(q.chatId,q.runs)})},[e,n]),_.useEffect(()=>{if(P)return;const q=ee[0];q&&me.getState().setSelectedProjectId(q.groupKey)},[P,ee]),_.useEffect(()=>{if(!e||!T||!j)return;if(ee.some(Z=>Z.chats.some(xe=>xe.chatId===e))){z===e&&me.getState().setPendingChatId(null);return}z!==e&&t("/")},[e,j,t,z,ee,T]),_.useEffect(()=>{p&&(me.getState().setSelectedProjectId(p.runtime.projectId),z===p.runtime.chatId&&me.getState().setPendingChatId(null))},[p,z]),_.useEffect(()=>{if(!e||!T||!CPe())return;const q=ee.flatMap(Z=>Z.chats).find(Z=>Z.chatId===e);q!=null&&q.unread&&n.command({type:"chat.markRead",chatId:e}).catch(Z=>{me.getState().setCommandError(Z instanceof Error?Z.message:String(Z))})},[e,W,ee,T,n]),_.useEffect(()=>{const q=me.getState();q.setOlderHistoryEntries([]),q.setIsHistoryLoading(!1),q.setHistoryCursor(null),q.setHasOlderHistory(!1)},[e]);const Ge=_.useMemo(()=>HPe(p,e),[e,p]),Pt=_.useMemo(()=>(Ge==null?void 0:Ge.runtime.projectId)??APe(ee,e)??P,[e,Ge==null?void 0:Ge.runtime.projectId,P,ee]),gn=_.useMemo(()=>{const q=Pt?S[Pt]??null:null;return Pt&&q?(ue.current={projectId:Pt,diffs:q},q):Pt&&ue.current.projectId===Pt?ue.current.diffs:q},[Pt,S]);_.useEffect(()=>Pt?n.subscribe({type:"project-git",projectId:Pt},Z=>{me.getState().setProjectDiffSnapshots(xe=>{const et=Z??null;return uPe(xe[Pt]??null,et)||cPe(xe[Pt]??null,et)?xe:{...xe,[Pt]:et}}),me.getState().setCommandError(null)}):void 0,[Pt,n]),_.useEffect(()=>{p==null||p.runtime.chatId,p==null||p.runtime.provider,Ge==null||Ge.runtime.chatId,Ge==null||Ge.runtime.provider},[e,Ge,p,z]);const _t=_.useMemo(()=>N6(m,(Ge==null?void 0:Ge.messages)??[]),[Ge==null?void 0:Ge.messages,m]),jt=e??T6,Jt=_.useMemo(()=>F.filter(q=>q.scopeId===jt).map(q=>q.entry),[jt,F]),Wt=_.useMemo(()=>[..._t,...Jt],[Jt,_t]),Vt=_.useMemo(()=>M1(Wt),[Wt]),an=_.useMemo(()=>mPe(Vt),[Vt]),Nn=_.useMemo(()=>jIe(Vt),[Vt]),Ue=(Ge==null?void 0:Ge.runtime)??null,nn=(Ge==null?void 0:Ge.queuedMessages)??[],Le=((K==null?void 0:K.scopeId)===jt&&(!Ue||Ue.status==="idle")?"starting":null)??(Ue==null?void 0:Ue.status)??null,Ze=(Ge==null?void 0:Ge.availableProviders)??Mb,Fe=j0(mm(q=>q.models)),ot=_.useMemo(()=>rPe(Ze,Fe),[Ze,Fe]),Kt=PIe(Le??void 0),ln=IIe(Le??void 0),Sn=(Ue==null?void 0:Ue.isDraining)??!1,rn=((va=o==null?void 0:o.projects[0])==null?void 0:va.localPath)??null,At=(Ue==null?void 0:Ue.localPath)??rn??((vs=ee[0])==null?void 0:vs.localPath),Lt=!!(P??(Ue==null?void 0:Ue.projectId)??((Ya=ee[0])==null?void 0:Ya.groupKey)??rn);_.useEffect(()=>{(K==null?void 0:K.scopeId)===jt&&Ue!=null&&Ue.status&&Ue.status!=="idle"&&me.getState().setOptimisticProcessing(null)},[K,jt,Ue==null?void 0:Ue.status]),_.useEffect(()=>{if(!(K!=null&&K.ackedAt)||K.scopeId!==jt||Ue!=null&&Ue.status&&Ue.status!=="idle")return;const q=K.ackedAt,Z=window.setTimeout(()=>{me.getState().setOptimisticProcessing(xe=>(xe==null?void 0:xe.scopeId)===jt&&xe.ackedAt===q?null:xe)},300);return()=>window.clearTimeout(Z)},[K,jt,Ue==null?void 0:Ue.status]),_.useEffect(()=>{if(!e||(Ue==null?void 0:Ue.status)!=="starting")return;const q=[...V.current.values()].filter(Z=>Z.serverChatId===e).sort((Z,xe)=>xe.startedAt-Z.startedAt)[0];!q||q.startingStatusAt!==void 0||(q.startingStatusAt=performance.now(),$u(q,"runtime_status_starting",{status:Ue.status}))},[e,Ue==null?void 0:Ue.status]),_.useEffect(()=>{if(!e||!Ue||Ue.status==="starting")return;const q=[...V.current.values()].filter(Z=>Z.serverChatId===e).sort((Z,xe)=>xe.startedAt-Z.startedAt)[0];!q||q.startingRenderedAt!==void 0||($u(q,"starting_not_observed",{status:Ue.status}),V.current.delete(q.traceId))},[e,Ue]),_.useLayoutEffect(()=>{if(!e||(Ue==null?void 0:Ue.status)!=="starting"){oe.current=null;return}const q=[...V.current.values()].filter(Z=>Z.serverChatId===e).sort((Z,xe)=>xe.startedAt-Z.startedAt)[0];q&&oe.current!==q.traceId&&(oe.current=q.traceId,q.startingRenderedAt=performance.now(),$u(q,"starting_render_committed",{totalMs:aZ(q.startedAt)}),V.current.delete(q.traceId))},[e,Ue==null?void 0:Ue.status]),_.useEffect(()=>{me.getState().setOptimisticUserPrompts(q=>{const Z=yPe(q,jt,_t);return Z.length===q.length&&Z.every((xe,et)=>xe===q[et])?q:Z})},[jt,_t]);const Zt=_.useCallback(async()=>{if(!(!e||!b||v||!x)){me.getState().setIsHistoryLoading(!0);try{const q=await n.command({type:"chat.loadHistory",chatId:e,beforeCursor:b,limit:wPe}),Z=me.getState();Z.setOlderHistoryEntries(xe=>N6(q.messages,xe)),Z.setHistoryCursor(q.olderCursor),Z.setHasOlderHistory(q.hasOlder),Z.setCommandError(null)}catch(q){const Z=q instanceof Error?q.message:String(q);me.getState().setCommandError(Z)}finally{me.getState().setIsHistoryLoading(!1)}}},[e,x,b,v,n]),It=_.useCallback(async q=>{const Z=Ts.getState(),xe=e?Z.getComposerState(e):Z.getComposerState(hb),et=await n.command({type:"chat.create",projectId:q});Z.initializeComposerForChat(et.chatId,{sourceState:xe});const Cn=me.getState();Cn.setSelectedProjectId(q),Cn.setPendingChatId(et.chatId),t(`/chat/${et.chatId}`),Cn.setSidebarOpen(!1),Cn.setCommandError(null)},[e,t,n]),re=_.useCallback(async q=>q.kind==="project_id"?{projectId:q.projectId}:q.kind==="local_path"?{projectId:(await n.command({type:"project.open",localPath:q.localPath})).projectId,localPath:q.localPath}:{projectId:(await n.command(q.project.mode==="new"?{type:"project.create",localPath:q.project.localPath,title:q.project.title}:{type:"project.open",localPath:q.project.localPath})).projectId,localPath:q.project.localPath},[n]),Me=_.useCallback(async q=>{try{let Z;q.kind==="project_id"?Z=null:q.kind==="local_path"?Z=q.localPath:Z=q.project.localPath,Z&&me.getState().setStartingLocalPath(Z);const{projectId:xe}=await re(q);await It(xe)}catch(Z){me.getState().setCommandError(Z instanceof Error?Z.message:String(Z))}finally{me.getState().setStartingLocalPath(null)}},[It,re]),pt=_.useCallback(async q=>{await Me({kind:"project_id",projectId:q})},[Me]),Ee=_.useCallback(async q=>{try{const Z=await n.command({type:"chat.fork",chatId:q.chatId}),xe=Ts.getState();xe.initializeComposerForChat(Z.chatId,{sourceState:xe.getComposerState(q.chatId)});const et=me.getState();et.setPendingChatId(Z.chatId),t(`/chat/${Z.chatId}`),et.setSidebarOpen(!1),et.setCommandError(null)}catch(Z){me.getState().setCommandError(Z instanceof Error?Z.message:String(Z))}},[t,n]),Ve=_.useCallback(async q=>{await Me({kind:"local_path",localPath:q})},[Me]),qe=_.useCallback(async q=>{await Me({kind:"project_request",project:q})},[Me]),Qe=_.useCallback(async q=>{try{await n.command({type:"update.check",force:q==null?void 0:q.force}),me.getState().setCommandError(null)}catch(Z){me.getState().setCommandError(Z instanceof Error?Z.message:String(Z))}},[n]),mt=_.useCallback(async q=>{d("awaiting_disconnect");try{const Z=await n.command({type:"update.install",version:q});if(!Z.ok){h(),me.getState().setCommandError(null),await r.alert({title:Z.userTitle??"Update failed",description:Z.userMessage??"Kanna could not install the update. Try again later.",closeLabel:"OK"});return}if(Z.ok&&Z.action==="reload"){window.location.reload();return}me.getState().setCommandError(null)}catch(Z){h(),me.getState().setCommandError(Z instanceof Error?Z.message:String(Z))}},[h,r,d,n]),Rt=_.useCallback(async()=>{d("awaiting_disconnect");try{const q=await n.command({type:"update.reload"});if(!q.ok){h(),me.getState().setCommandError(null),await r.alert({title:q.userTitle??"Re-deploy failed",description:q.userMessage??"Kanna could not re-deploy. Try again later.",closeLabel:"OK"});return}if(q.action==="reload"){window.location.reload();return}me.getState().setCommandError(null)}catch(q){h(),me.getState().setCommandError(q instanceof Error?q.message:String(q))}},[h,r,d,n]),bt=_.useCallback(async()=>{try{const q=await fetch("/auth/logout",{method:"POST",headers:{Accept:"application/json"}});if(!q.ok)throw new Error(`Sign out failed with status ${q.status}`);me.getState().setCommandError(null),window.location.reload()}catch(q){me.getState().setCommandError(q instanceof Error?q.message:String(q))}},[]),Be=_.useCallback(async(q,Z)=>{var B;const xe=(Z==null?void 0:Z.attachments)??[],et=Sf(),Cn=Sf(),Rr=aL(q,xe),ki=e??T6;me.getState().setOptimisticProcessing({scopeId:ki,ackedAt:null});const Ce={traceId:Cn,optimisticId:et,startedAt:performance.now(),serverChatId:e,routeChatIdAtSend:e,contentPreview:q.slice(0,80)};V.current.set(Cn,Ce),$u(Ce,"handle_send_called",{optimisticScopeId:ki,attachments:xe.length,contentLength:q.length,contentPreview:Ce.contentPreview});const He=xPe(_t,Rr)+F.filter(Te=>Te.scopeId===ki&&Te.signature===Rr).length+1;me.getState().setOptimisticUserPrompts(Te=>[...Te,{id:et,scopeId:ki,signature:Rr,requiredMatchCount:He,entry:{_id:`optimistic:${et}`,kind:"user_prompt",content:q,attachments:xe,createdAt:Date.now()}}]),$u(Ce,"optimistic_prompt_added",{optimisticId:et,optimisticScopeId:ki});try{let Te=P??((B=ee[0])==null?void 0:B.groupKey)??null;if(!e&&!Te&&rn&&(Te=(await n.command({type:"project.open",localPath:rn})).projectId,me.getState().setSelectedProjectId(Te)),!e&&!Te)throw new Error("Open a project first");const Qt=$R.getState().autoResumeOnRateLimit,Xn=await n.command({type:"chat.send",chatId:e??void 0,projectId:e?void 0:Te??void 0,clientTraceId:Cn,provider:Z==null?void 0:Z.provider,content:q,attachments:xe,model:Z==null?void 0:Z.model,modelOptions:Z==null?void 0:Z.modelOptions,planMode:Z==null?void 0:Z.planMode,autoResumeOnRateLimit:Qt});if(Ce.ackAt=performance.now(),Ce.serverChatId=Xn.chatId??Ce.serverChatId,Xn.queued?(me.getState().setOptimisticUserPrompts(Ei=>_Pe(Ei,et,{queued:!0})),me.getState().setOptimisticProcessing(null)):me.getState().setOptimisticProcessing(Ei=>Ei&&{scopeId:!e&&Xn.chatId?Xn.chatId:Ei.scopeId,ackedAt:performance.now()}),$u(Ce,"chat_send_ack_received",{resultChatId:Xn.chatId??null,queued:Xn.queued??!1}),!e&&Xn.chatId){me.getState().setOptimisticUserPrompts(Ol=>Ol.map(Dl=>Dl.id===et?{...Dl,scopeId:Xn.chatId}:Dl));const Ei=Ts.getState();Ei.setComposerState(Xn.chatId,TPe(Z)??Ei.getComposerState(hb)),me.getState().setPendingChatId(Xn.chatId),t(`/chat/${Xn.chatId}`)}me.getState().setCommandError(null)}catch(Te){throw me.getState().setOptimisticUserPrompts(Qt=>Qt.filter(Xn=>Xn.id!==et)),me.getState().setOptimisticProcessing(null),$u(Ce,"handle_send_failed",{error:Te instanceof Error?Te.message:String(Te)}),V.current.delete(Cn),me.getState().setCommandError(Te instanceof Error?Te.message:String(Te)),Te}},[e,rn,t,F,P,_t,ee,n]),Ot=_.useCallback(async q=>{if(e)try{await n.command({type:"message.steer",chatId:e,queuedMessageId:q}),me.getState().setCommandError(null)}catch(Z){me.getState().setCommandError(Z instanceof Error?Z.message:String(Z))}},[e,n]),Ln=_.useCallback(async q=>{if(e)try{await n.command({type:"message.dequeue",chatId:e,queuedMessageId:q}),me.getState().setCommandError(null)}catch(Z){me.getState().setCommandError(Z instanceof Error?Z.message:String(Z))}},[e,n]),Ht=_.useCallback(async()=>{if(e)try{await n.command({type:"chat.cancel",chatId:e})}catch(q){me.getState().setCommandError(q instanceof Error?q.message:String(q))}},[e,n]),Gt=_.useCallback(async()=>{if(e)try{await n.command({type:"chat.stopDraining",chatId:e})}catch(q){me.getState().setCommandError(q instanceof Error?q.message:String(q))}},[e,n]),yr=_.useCallback(async q=>{const Z=await r.prompt({title:"Rename Chat",initialValue:q.title,confirmLabel:"Rename"});if(!(!Z||Z===q.title))try{await n.command({type:"chat.rename",chatId:q.chatId,title:Z}),me.getState().setCommandError(null)}catch(xe){me.getState().setCommandError(xe instanceof Error?xe.message:String(xe))}},[r,n]),Mn=_.useCallback(async q=>{if(await r.confirm({title:"Delete Chat",description:`Delete "${q.title}"? This cannot be undone.`,confirmLabel:"Delete",confirmVariant:"destructive"}))try{if(await n.command({type:"chat.delete",chatId:q.chatId}),q.chatId===e){const xe=A6(ee,q.chatId);t(xe?`/chat/${xe}`:"/")}}catch(xe){me.getState().setCommandError(xe instanceof Error?xe.message:String(xe))}},[e,r,t,ee,n]),qn=_.useCallback(async q=>{try{if(await n.command({type:"chat.archive",chatId:q.chatId}),q.chatId===e){const Z=A6(ee,q.chatId);t(Z?`/chat/${Z}`:"/")}me.getState().setCommandError(null)}catch(Z){me.getState().setCommandError(Z instanceof Error?Z.message:String(Z))}},[e,t,ee,n]),Yn=_.useCallback(async q=>{try{me.getState().setPendingChatId(q),await n.command({type:"chat.unarchive",chatId:q}),t(`/chat/${q}`),me.getState().setCommandError(null)}catch(Z){me.getState().setPendingChatId(null),me.getState().setCommandError(Z instanceof Error?Z.message:String(Z))}},[t,n]),ye=_.useCallback(async q=>{try{await n.command({type:"project.remove",projectId:q}),Ku.getState().clearProject(q),Ks.getState().clearProject(q),(Ue==null?void 0:Ue.projectId)===q&&t("/"),me.getState().setCommandError(null)}catch(Z){me.getState().setCommandError(Z instanceof Error?Z.message:String(Z))}},[t,Ue,n]),tt=_.useCallback(async(q,Z)=>{try{await n.command({type:"project.setStar",projectId:q,starred:Z}),me.getState().setCommandError(null)}catch(xe){me.getState().setCommandError(xe instanceof Error?xe.message:String(xe))}},[n]),zn=_.useCallback(async q=>{me.getState().setOptimisticSidebarProjectOrder(q);try{await n.command({type:"sidebar.reorderProjectGroups",projectIds:q}),me.getState().setCommandError(null)}catch(Z){me.getState().setOptimisticSidebarProjectOrder(null),me.getState().setCommandError(Z instanceof Error?Z.message:String(Z))}},[n]),qr=_.useCallback(async(q,Z)=>{try{await n.command({type:"stack.create",title:q,projectIds:Z}),me.getState().setCommandError(null)}catch(xe){me.getState().setCommandError(xe instanceof Error?xe.message:String(xe))}},[n]),ce=_.useCallback(async(q,Z)=>{try{await n.command({type:"stack.rename",stackId:q,title:Z}),me.getState().setCommandError(null)}catch(xe){me.getState().setCommandError(xe instanceof Error?xe.message:String(xe))}},[n]),Je=_.useCallback(async q=>{try{await n.command({type:"stack.remove",stackId:q}),me.getState().setCommandError(null)}catch(Z){me.getState().setCommandError(Z instanceof Error?Z.message:String(Z))}},[n]),ut=_.useCallback(async(q,Z)=>{try{await n.command({type:"stack.addProject",stackId:q,projectId:Z}),me.getState().setCommandError(null)}catch(xe){me.getState().setCommandError(xe instanceof Error?xe.message:String(xe))}},[n]),it=_.useCallback(async(q,Z)=>{try{await n.command({type:"stack.removeProject",stackId:q,projectId:Z}),me.getState().setCommandError(null)}catch(xe){me.getState().setCommandError(xe instanceof Error?xe.message:String(xe))}},[n]),jn=_.useCallback(async(q,Z,xe)=>{try{const et=Ts.getState(),Cn=e?et.getComposerState(e):et.getComposerState(hb),Rr=await n.command({type:"chat.create",projectId:q,stackId:Z,stackBindings:xe});et.initializeComposerForChat(Rr.chatId,{sourceState:Cn});const ki=me.getState();ki.setSelectedProjectId(q),ki.setPendingChatId(Rr.chatId),t(`/chat/${Rr.chatId}`),ki.setSidebarOpen(!1),ki.setCommandError(null)}catch(et){me.getState().setCommandError(et instanceof Error?et.message:String(et))}},[e,t,n]),Dt=_.useCallback(async q=>{try{const Z=await n.command({type:"stack.listWorktrees",projectId:q});return me.getState().setCommandError(null),Z.worktrees}catch(Z){return me.getState().setCommandError(Z instanceof Error?Z.message:String(Z)),[]}},[n]),Yr=_.useCallback(async()=>await n.command({type:"sessions.importClaude"}),[n]),li=_.useCallback(async q=>{const Z=ws.getState();me.getState().setCommandError(null),await n.command({type:"system.openExternal",...q,editor:q.action==="open_editor"?q.editor??{preset:Z.editorPreset,commandTemplate:Z.editorCommandTemplate}:void 0})},[n]),Pl=_.useCallback(async(q,Z)=>{var et,Cn;const xe=(Ue==null?void 0:Ue.localPath)??((et=o==null?void 0:o.projects[0])==null?void 0:et.localPath)??((Cn=ee[0])==null?void 0:Cn.localPath);if(xe)try{await li({action:q,localPath:xe,editor:Z})}catch(Rr){me.getState().setCommandError(Rr instanceof Error?Rr.message:String(Rr))}},[o==null?void 0:o.projects,li,Ue==null?void 0:Ue.localPath,ee]),Ds=_.useCallback(async q=>{var Z;try{if(typeof navigator>"u"||!((Z=navigator.clipboard)!=null&&Z.writeText))throw new Error("Clipboard is not available");await navigator.clipboard.writeText(q),me.getState().setCommandError(null)}catch(xe){me.getState().setCommandError(xe instanceof Error?xe.message:String(xe))}},[]),pa=_.useCallback(async(q,Z="open_editor",xe)=>{try{await li({action:Z,localPath:q.path,line:q.line,column:q.column,editor:xe})}catch(et){me.getState().setCommandError(et instanceof Error?et.message:String(et))}},[li]),$s=_.useCallback(async(q,Z)=>{try{await li({action:q,localPath:Z})}catch(xe){me.getState().setCommandError(xe instanceof Error?xe.message:String(xe))}},[li]),$t=_.useCallback(()=>{var Z;const q=UPe({selectedProjectId:P,sidebarProjectId:(Z=ee[0])==null?void 0:Z.groupKey,fallbackLocalProjectPath:rn});if(q){Me(q);return}t("/")},[rn,t,P,ee,Me]),wn=_.useCallback(()=>me.getState().setSidebarOpen(!0),[]),Bn=_.useCallback(()=>me.getState().setSidebarOpen(!1),[]),Rn=_.useCallback(()=>me.getState().setSidebarCollapsed(!0),[]),ma=_.useCallback(()=>me.getState().setSidebarCollapsed(!1),[]),lu=_.useCallback(()=>me.getState().setAddProjectModalOpen(!0),[]),ss=_.useCallback(()=>me.getState().setAddProjectModalOpen(!1),[]),Ll=_.useCallback(async(q,Z,xe)=>{if(e)try{await n.command({type:"chat.respondTool",chatId:e,toolUseId:q,result:{questions:Z,answers:xe}})}catch(et){me.getState().setCommandError(et instanceof Error?et.message:String(et))}},[e,n]),ga=_.useCallback(async(q,Z,xe,et)=>{if(e){Z&&Ts.getState().setChatComposerPlanMode(e,!1);try{await n.command({type:"chat.respondTool",chatId:e,toolUseId:q,result:{confirmed:Z,...xe?{clearContext:!0}:{},...et?{message:et}:{}}})}catch(Cn){me.getState().setCommandError(Cn instanceof Error?Cn.message:String(Cn))}}},[e,n]),cu=_.useCallback(async(q,Z,xe,et)=>{if(e)try{await n.command({type:"chat.respondSubagentTool",chatId:e,runId:q,toolUseId:Z,result:{questions:xe,answers:et}})}catch(Cn){me.getState().setCommandError(Cn instanceof Error?Cn.message:String(Cn))}},[e,n]),ci=_.useCallback(async(q,Z,xe)=>{if(e)try{await n.command({type:"chat.respondSubagentTool",chatId:e,runId:q,toolUseId:Z,result:xe})}catch(et){me.getState().setCommandError(et instanceof Error?et.message:String(et))}},[e,n]),qa=_.useCallback(async(q,Z)=>{if(e)try{await n.command({type:"chat.toolRequestAnswer",chatId:e,toolRequestId:q,decision:Z})}catch(xe){me.getState().setCommandError(xe instanceof Error?xe.message:String(xe))}},[e,n]),Ro=MPe(l,a==null?void 0:a.status);return{socket:n,activeChatId:e,activeProjectId:Pt,sidebarData:ie,localProjects:o,updateSnapshot:a,chatSnapshot:p,chatDiffSnapshot:gn,keybindings:C,appSettings:k,pushConfig:w,llmProvider:N,connectionStatus:A,sidebarReady:T,uiRestartActive:Ro.active,uiRestartLabel:Ro.label,localProjectsReady:M,commandError:$,startingLocalPath:H,sidebarOpen:D,sidebarCollapsed:L,messages:Vt,queuedMessages:nn,previousPrompt:an,latestToolIds:Nn,runtime:Ue,runtimeStatus:Le,isHistoryLoading:v,hasOlderHistory:x,availableProviders:ot,isProcessing:Kt,canCancel:ln,isDraining:Sn,navbarLocalPath:At,editorLabel:de,hasSelectedProject:Lt,addProjectModalOpen:I,openSidebar:wn,closeSidebar:Bn,collapseSidebar:Rn,expandSidebar:ma,openAddProjectModal:lu,closeAddProjectModal:ss,loadOlderHistory:Zt,handleCreateChat:pt,handleForkChat:Ee,handleOpenLocalProject:Ve,handleCreateProject:qe,handleCheckForUpdates:Qe,handleInstallUpdate:mt,handleForceReload:Rt,handleReadAppSettings:ae,handleWriteAppSettings:ke,handleTestMcpServer:Se,handleStartMcpOAuth:Ne,handleCompleteMcpOAuth:Xe,handleSetChatPolicyOverride:Q,handleWriteCloudflareTunnel:ht,handleWriteClaudeAuth:St,handleTestOAuthToken:Bt,handleReadLlmProvider:Yt,handleWriteLlmProvider:Mt,handleValidateLlmProvider:mn,handleSignOut:bt,handleSend:Be,handleSteerQueuedMessage:Ot,handleRemoveQueuedMessage:Ln,handleCancel:Ht,handleStopDraining:Gt,handleRenameChat:yr,handleArchiveChat:qn,handleOpenArchivedChat:Yn,handleDeleteChat:Mn,handleHideProject:ye,handleToggleProjectStar:tt,handleReorderProjectGroups:zn,stacks:ie.stacks,handleCreateStack:qr,handleRenameStack:ce,handleRemoveStack:Je,handleAddProjectToStack:ut,handleRemoveProjectFromStack:it,handleCreateStackChat:jn,handleListStackWorktrees:Dt,importClaudeSessions:Yr,handleCopyPath:Ds,handleOpenExternal:Pl,handleOpenExternalPath:$s,handleOpenLocalLink:pa,handleCompose:$t,handleAskUserQuestion:Ll,handleExitPlanMode:ga,handleSubagentAskUserQuestion:cu,handleSubagentExitPlanMode:ci,handleToolRequestAnswer:qa}}const zR=tn("KannaTranscript",()=>e=>({toolGroupExpanded:{},setToolGroupExpanded:(t,n)=>e(r=>r.toolGroupExpanded[t]===n?r:{toolGroupExpanded:{...r.toolGroupExpanded,[t]:n}})})),VPe=new Set([".c",".cc",".cfg",".conf",".cpp",".cs",".css",".diff",".env",".go",".graphql",".h",".hpp",".html",".ini",".java",".js",".json",".jsonc",".jsx",".kt",".log",".lua",".md",".mjs",".patch",".php",".pl",".properties",".py",".rb",".rs",".scss",".sh",".sql",".swift",".toml",".ts",".tsx",".txt",".vue",".xml",".yaml",".yml",".zsh"]),KPe=new Set([".gitignore",".npmrc",".prettierrc",".python-version",".ruby-version",".tool-versions","Dockerfile","Gemfile","Makefile","Procfile"]);function I0(e){if(!e)return;const t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:void 0}function I6(e){var r,i;const t=/^(?<path>\/.+?)#L(?<line>\d+)(?:C(?<column>\d+))?$/.exec(e);if((r=t==null?void 0:t.groups)!=null&&r.path)return{path:t.groups.path,line:I0(t.groups.line),column:I0(t.groups.column)};const n=/^(?<path>\/.+?):(?<line>\d+)(?::(?<column>\d+))?$/.exec(e);return(i=n==null?void 0:n.groups)!=null&&i.path?{path:n.groups.path,line:I0(n.groups.line),column:I0(n.groups.column)}:e.startsWith("/")?{path:e}:null}function GPe(e){if(!e)return null;const t=e.trim();if(!t||/^(mailto:|ftp:|file:)/i.test(t))return null;if(/^https?:/i.test(t)){if(typeof window>"u")return null;try{const n=new URL(t);return n.origin!==window.location.origin||!n.pathname.startsWith("/")?null:I6(`${n.pathname}${n.hash}`)}catch{return null}}return I6(t)}function qPe(e){const t=e.split(/[\\/]/);for(;t.length>0&&t[t.length-1]==="";)t.pop();const n=t.length>0?t[t.length-1]:e;if(KPe.has(n))return!0;const r=n.lastIndexOf(".");if(r<0)return!0;const i=n.slice(r).toLowerCase();return VPe.has(i)}const YPe=["/Users/","/home/","/private/","/tmp/","/var/","/opt/","/root/"];function XPe(e){return e?e.startsWith("file://")?!0:YPe.some(t=>e.startsWith(t)):!1}function cZ(e){let t=e;if(t.startsWith("file://"))try{t=decodeURIComponent(new URL(t).pathname)}catch{t=t.slice(7)}return`/api/local-file?path=${encodeURIComponent(t)}`}function cd(e,t){if(!e)return"";if(t){const n=t.endsWith("/")?t:`${t}/`;if(e.startsWith(n))return e.slice(n.length);if(e===t)return""}return e.replace(/^\/home\/user\/workspace\//,"")}const P6=/<thinking>([\s\S]*?)<\/thinking>/gi;function JPe(e){const t=[];let n=0;P6.lastIndex=0;let r;for(;(r=P6.exec(e))!==null;){if(r.index>n){const o=e.slice(n,r.index);o.length>0&&t.push({kind:"text",content:o})}t.push({kind:"thinking",content:r[1]??""}),n=r.index+r[0].length}const i=e.slice(n),s=i.search(/<thinking>/i);if(s!==-1){const o=i.slice(0,s);o.length>0&&t.push({kind:"text",content:o});const a=i.slice(s+10);t.push({kind:"thinking",content:a})}else i.length>0&&t.push({kind:"text",content:i});return ZPe(t)}function ZPe(e){const t=[];for(const n of e){const r=t[t.length-1];n.kind==="text"&&r&&r.kind==="text"?r.content+=n.content:t.push(n)}return t}const QPe=/^[ \t]*(`{3,}|~{3,})/,eLe=/https?:\/\/[^\s<>)\]'"]+/g,tLe=new RegExp("(?<![a-zA-Z0-9_])((?:PR|pull\\s+request|merge\\s+request|MR|issue|fix(?:es|ed)?|close[sd]?|resolve[sd]?|bug|task|ticket|story)\\s+)?#(\\d+)","gi"),nLe=/[.,;:!?)\]]+$/;function rLe(e){if(!e.includes("#")||!e.includes("http"))return e;const t=e.split(`
2672
+ `:"").join("");return u.jsx(kJ,{source:r,lang:n},Ai())}if(kt(e)){const n=e.getListType(),r=Ou(e),i=Ai();return n==="number"?u.jsx("ol",{className:"list-decimal ml-5 my-2",children:r},i):u.jsx("ul",{className:"list-disc ml-5 my-2",children:r},i)}if(xn(e)){const n=e.getChecked(),r=Ou(e),i=Ai();return n!==void 0?u.jsxs("li",{className:"my-0.5 list-none flex items-start gap-1.5",children:[u.jsx("input",{type:"checkbox",readOnly:!0,checked:n,className:"mt-[3px] shrink-0"}),u.jsx("span",{children:r})]},i):u.jsx("li",{className:"my-0.5",children:r},i)}if(Gs(e)||ed(e)){const n=e.getURL();return u.jsx("a",{href:n,className:"transition-all underline decoration-2 text-logo decoration-logo/50 hover:text-logo/70 dark:text-logo dark:decoration-logo/70 dark:hover:text-logo/60 dark:hover:decoration-logo/40",target:"_blank",rel:"noopener noreferrer",children:Ou(e)},Ai())}if(pr(e)){const n=e.getChildren(),r=n[0],i=r!==void 0&&ur(r)&&r.getChildren().every(a=>yt(a)&&(a.getHeaderStyles()&An.ROW)!==0),s=i?r:void 0,o=i?n.slice(1):n;return u.jsx("div",{className:"border border-border rounded-xl overflow-x-auto",children:u.jsxs("table",{className:"table-auto min-w-full divide-y divide-border bg-background",children:[s!==void 0&&u.jsx("thead",{children:u.jsx("tr",{children:s.getChildren().map(a=>u.jsx("th",{className:"text-left text-xs uppercase text-muted-foreground tracking-wider p-2 pl-0 first:pl-3 bg-muted dark:bg-card [&_*]:font-semibold",children:Ou(a)},Ai()))})}),u.jsx("tbody",{className:"divide-y divide-border",children:o.map(a=>ur(a)?u.jsx("tr",{children:a.getChildren().map(l=>yt(l)?u.jsx("td",{className:"text-left p-2 pl-0 first:pl-3 [&_*]:font-normal",children:Ou(l)},Ai()):null)},Ai()):null)})]})},Ai())}if(oi(e))return u.jsx("br",{},Ai());if(Pe(e))return lMe(e);if(Dm(e))return u.jsx("code",{className:"break-all px-1 bg-border/60 py-0.5 rounded text-sm",children:e.getTextContent()},Ai());const t=e.getTextContent();return t?u.jsx("span",{children:t},Ai()):null}function lMe(e){const t=e.getFormat(),n=e.getTextContent(),r=(t&ex)!==0,i=(t&tx)!==0,s=(t&nx)!==0,o=(t&qI)!==0;let a=n;return o?u.jsx("code",{className:"break-all px-1 bg-border/60 py-0.5 rounded text-sm",children:n},Ai()):(s&&(a=u.jsx("del",{className:"line-through",children:a},Ai())),i&&(a=u.jsx("em",{className:"italic",children:a},Ai())),r&&(a=u.jsx("strong",{className:"font-semibold",children:a},Ai())),!r&&!i&&!s?n:a)}function Ou(e){return e.getChildren().map(NJ)}function cMe(){EJ=0;const t=Pn().getChildren();return u.jsx(u.Fragment,{children:t.map(NJ)})}function Gc(e,t=SJ){const n=DY(WP({namespace:"kanna-md-renderer",nodes:aMe,editable:!1}));return n.update(()=>{dJ(e,t,void 0,!0)},{discrete:!0}),n.getEditorState().read(()=>cMe())}const kS=new Map;function uMe(e){return`${e.id}|${e.contentUrl}|${e.size??0}`}function dMe(e,t){return t.type==="setLoadState"?{...e,loadState:t.payload}:{lastKey:t.newKey,loadState:kS.get(t.newKey)??{status:"loading"}}}function py(e){const t=uMe(e),n=kS.get(t),[{loadState:r,lastKey:i},s]=_.useReducer(dMe,{loadState:n??{status:"loading"},lastKey:t}),o=_.useRef(t);return o.current=t,i!==t&&s({type:"resetForKey",newKey:t}),_.useEffect(()=>{if(n&&n.status!=="loading")return;let a=!1;const l=t;return KI(e.contentUrl,VG).then(d=>{if(a||o.current!==l)return;const h={status:"ready",content:d.content,truncated:d.truncated};kS.set(l,h),s({payload:h,type:"setLoadState"})}).catch(d=>{if(a||o.current!==l)return;const p={status:"error",message:d instanceof Error?d.message:"Unable to load preview."};kS.set(l,p),s({payload:p,type:"setLoadState"})}),()=>{a=!0}},[n,t,e.contentUrl]),r}function fMe({source:e}){const t=py(e);return t.status==="loading"?u.jsxs("div",{className:"p-4 text-sm text-muted-foreground",children:[u.jsx("div",{className:"prose hidden"})," Loading…"]}):t.status==="error"?u.jsx("div",{className:"p-4 text-sm text-destructive",children:t.message}):u.jsxs("div",{className:"space-y-2 p-3",children:[t.truncated?u.jsx("div",{className:"rounded-xl border border-border bg-background px-3 py-2 text-xs text-muted-foreground",children:"Preview truncated to 1024 KB."}):null,u.jsx("div",{className:"prose prose-sm prose-invert max-w-none rounded-xl border border-border bg-background p-4",children:Gc(t.content)})]})}const MR=tn("TableBody",e=>t=>({state:e.initialState,setState:n=>t({state:n})})),ES=new Map;function TJ(e){return`${e.id}|${e.contentUrl}|${e.size??0}|${e.mimeType}`}function hMe({source:e}){const t=TJ(e),n=ES.get(t),r=MR.useScopedStore(h=>h.state),i=MR.useScopedStore(h=>h.setState),s=_.useRef(t);if(s.current=t,_.useEffect(()=>{if(n&&n.status!=="loading")return;const h=e.mimeType==="text/tab-separated-values"?" ":",";let p=!1;const m=t;return KI(e.contentUrl,VG).then(v=>{if(p||s.current!==m)return;const b={status:"ready",table:Gke(v.content,h),truncated:v.truncated};ES.set(m,b),i(b)}).catch(v=>{if(p||s.current!==m)return;const b={status:"error",message:v instanceof Error?v.message:"Unable to load preview."};ES.set(m,b),i(b)}),()=>{p=!0}},[n,t,e.contentUrl,e.mimeType,i]),r.status==="loading")return u.jsxs("div",{className:"p-4 text-sm text-muted-foreground",children:[u.jsx("table",{className:"sr-only"})," Loading…"]});if(r.status==="error")return u.jsxs("div",{className:"p-4 text-sm text-destructive",children:[u.jsx("table",{className:"sr-only"})," ",r.message]});const{table:o}=r,[a,...l]=o.rows,d=[r.truncated?"Preview truncated to 1024 KB.":null,o.truncatedRows?`Showing first ${o.rows.length} of ${o.rowCount} rows.`:null,o.truncatedColumns?`Showing first ${SA} of ${o.columnCount} columns.`:null].filter(Boolean);return u.jsxs("div",{className:"space-y-2 p-3",children:[d.length?u.jsx("div",{className:"rounded-xl border border-border bg-background px-3 py-2 text-xs text-muted-foreground",children:d.join(" ")}):null,u.jsx("div",{className:"overflow-x-auto rounded-xl border border-border bg-background",children:u.jsxs("table",{className:"min-w-full border-collapse text-xs",children:[a?u.jsx("thead",{className:"sticky top-0 bg-muted",children:u.jsx("tr",{children:a.map((h,p)=>u.jsx("th",{className:"border-b border-border px-3 py-2 text-left font-medium",children:h||" "},p))})}):null,u.jsx("tbody",{children:l.map((h,p)=>u.jsx("tr",{className:"odd:bg-background even:bg-muted/20",children:h.map((m,v)=>u.jsx("td",{className:"max-w-[320px] border-b border-border px-3 py-2 align-top",children:u.jsx("div",{className:"whitespace-pre-wrap break-words",children:m||" "})},v))},p))})]})})]})}function pMe({source:e}){const t=TJ(e),n=ES.get(t);return u.jsx(MR.Provider,{init:{initialState:n??{status:"loading"}},children:u.jsx(hMe,{source:e})})}function mMe({source:e}){const t=py(e);return t.status==="loading"?u.jsxs("div",{className:"p-4 text-sm text-muted-foreground",children:[u.jsx("pre",{className:"sr-only"})," Loading…"]}):t.status==="error"?u.jsxs("div",{className:"p-4 text-sm text-destructive",children:[u.jsx("pre",{className:"sr-only"})," ",t.message]}):u.jsxs("div",{className:"space-y-2 p-3",children:[t.truncated?u.jsx(gMe,{children:"Preview truncated to 1024 KB."}):null,u.jsx("pre",{className:"whitespace-pre-wrap break-words rounded-xl border border-border bg-background p-3 text-xs",children:t.content})]})}function gMe({children:e}){return u.jsx("div",{className:"rounded-xl border border-border bg-background px-3 py-2 text-xs text-muted-foreground",children:e})}function vMe({source:e}){const t=py(e),n=_.useMemo(()=>t.status==="ready"?Kke(t.content):"",[t]);return t.status==="loading"?u.jsxs("div",{className:"p-4 text-sm text-muted-foreground",children:[u.jsx("pre",{className:"sr-only"})," Loading…"]}):t.status==="error"?u.jsxs("div",{className:"p-4 text-sm text-destructive",children:[u.jsx("pre",{className:"sr-only"})," ",t.message]}):u.jsxs("div",{className:"space-y-2 p-3",children:[t.truncated?u.jsx("div",{className:"rounded-xl border border-border bg-background px-3 py-2 text-xs text-muted-foreground",children:"Preview truncated to 1024 KB."}):null,u.jsx("pre",{className:"whitespace-pre-wrap break-words rounded-xl border border-border bg-background p-3 text-xs",children:n})]})}function bMe({source:e}){return u.jsxs("div",{className:"flex h-full flex-col items-stretch justify-center gap-3 p-4",children:[u.jsx("div",{className:"text-sm font-medium text-foreground",children:e.displayName}),u.jsx("audio",{src:e.contentUrl,controls:!0,preload:"metadata",className:"w-full"})]})}function xMe({source:e}){return u.jsx("div",{className:"flex h-full items-center justify-center bg-black/40 p-2",children:u.jsx("video",{src:e.contentUrl,controls:!0,playsInline:!0,preload:"metadata",className:"max-h-[60dvh] w-full rounded-xl"})})}const jR=tn("CodeBody",()=>e=>({highlighted:null,setHighlighted:t=>e({highlighted:t})})),yMe=200*1024;function _Me(e){const t=e.lastIndexOf(".");if(t<0)return"text";const n=e.slice(t+1).toLowerCase();return{ts:"typescript",tsx:"tsx",js:"javascript",jsx:"jsx",py:"python",go:"go",rs:"rust",java:"java",rb:"ruby",sh:"bash",zsh:"bash",yml:"yaml",yaml:"yaml",css:"css",scss:"scss",html:"html",json:"json",md:"markdown",sql:"sql",cpp:"cpp",c:"c",h:"c",swift:"swift",kt:"kotlin",php:"php",toml:"toml"}[n]??"text"}function SMe({source:e}){const t=py(e),n=t.status==="ready"&&t.content.length<=yMe,r=n?`${e.id}|${e.contentUrl}|${e.size??0}|${t.content.length}`:null,i=jR.useScopedStore(o=>o.highlighted),s=jR.useScopedStore(o=>o.setHighlighted);return _.useEffect(()=>{if(!n||t.status!=="ready"||r===null)return;let o=!1;const a=r;return J(()=>Promise.resolve().then(()=>OG),void 0).then(async l=>{if(o)return;const d=await l.codeToHtml(t.content,{lang:_Me(e.fileName),theme:"github-dark"});o||s({key:a,html:d})}).catch(()=>{Qs.warn("[file-preview] Shiki unavailable; falling back to plain text")}),()=>{o=!0}},[n,r,t,e.fileName,s]),t.status==="loading"?u.jsxs("div",{className:"p-4 text-sm text-muted-foreground",children:[u.jsx("pre",{className:"sr-only"})," Loading…"]}):t.status==="error"?u.jsxs("div",{className:"p-4 text-sm text-destructive",children:[u.jsx("pre",{className:"sr-only"})," ",t.message]}):i&&i.key===r?u.jsx("div",{className:"overflow-x-auto p-3 text-xs",dangerouslySetInnerHTML:{__html:i.html}}):u.jsxs("div",{className:"space-y-2 p-3",children:[t.truncated?u.jsx("div",{className:"rounded-xl border border-border bg-background px-3 py-2 text-xs text-muted-foreground",children:"Preview truncated to 1024 KB."}):null,u.jsx("pre",{className:"whitespace-pre-wrap break-words rounded-xl border border-border bg-background p-3 text-xs",children:t.content})]})}function wMe({source:e}){return u.jsx(jR.Provider,{init:void 0,children:u.jsx(SMe,{source:e})})}const gf=tn("MermaidZoomModal",()=>e=>({scale:1,offset:{x:0,y:0},drag:null,setScale:t=>e({scale:t}),setOffset:t=>e({offset:t}),setDrag:t=>e({drag:t})}));function CMe({svg:e,onClose:t}){const n=gf.useScopedStore(m=>m.scale),r=gf.useScopedStore(m=>m.offset),i=gf.useScopedStore(m=>m.drag),s=gf.useScopedStore(m=>m.setScale),o=gf.useScopedStore(m=>m.setOffset),a=gf.useScopedStore(m=>m.setDrag);_.useEffect(()=>{const m=v=>{v.key==="Escape"&&t()};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[t]);const l=m=>Math.min(8,Math.max(.25,m)),d=m=>{a({x:m.clientX-r.x,y:m.clientY-r.y})},h=m=>{i&&o({x:m.clientX-i.x,y:m.clientY-i.y})},p=()=>a(null);return Rs.createPortal(u.jsxs("div",{className:"fixed inset-0 z-[100] flex flex-col bg-background/95",role:"dialog","aria-modal":"true","aria-label":"Diagram zoom view",children:[u.jsxs("div",{className:"flex justify-end gap-1 p-2",children:[u.jsx(Ie,{variant:"ghost",size:"icon","aria-label":"Zoom out",className:"h-9 w-9",onClick:()=>s(l(n-.25)),children:u.jsx(mH,{className:"h-4 w-4"})}),u.jsx(Ie,{variant:"ghost",size:"icon","aria-label":"Zoom in",className:"h-9 w-9",onClick:()=>s(l(n+.25)),children:u.jsx(Eo,{className:"h-4 w-4"})}),u.jsx(Ie,{variant:"ghost",size:"icon","aria-label":"Reset view",className:"h-9 w-9",onClick:()=>{s(1),o({x:0,y:0})},children:u.jsx(zoe,{className:"h-4 w-4"})}),u.jsx(Ie,{variant:"ghost",size:"icon","aria-label":"Close",className:"h-9 w-9",onClick:t,children:u.jsx(da,{className:"h-4 w-4"})})]}),u.jsx("div",{className:"flex-1 overflow-hidden touch-none cursor-grab active:cursor-grabbing",onPointerDown:d,onPointerMove:h,onPointerUp:p,onPointerLeave:p,children:u.jsx("div",{"data-mermaid-stage":!0,className:"w-full h-full flex items-center justify-center",style:{transform:`translate(${r.x}px, ${r.y}px) scale(${n})`},dangerouslySetInnerHTML:{__html:e}})})]}),document.body)}function kMe({svg:e,onClose:t}){return u.jsx(gf.Provider,{init:void 0,children:u.jsx(CMe,{svg:e,onClose:t})})}const uc=tn("MermaidDiagram",()=>e=>({renderState:{status:"loading"},showSource:!1,zoomOpen:!1,copied:!1,setRenderState:t=>e({renderState:t}),setShowSource:t=>e({showSource:t}),setZoomOpen:t=>e({zoomOpen:t}),setCopied:t=>e({copied:t})}));let _T=null;function EMe(){return _T||(_T=J(()=>import("./mermaid.core-BeCusr1Y.js").then(e=>e.bm),[]).then(e=>e.default)),_T}function NMe({source:e}){const{resolvedTheme:t}=A1(),n=t==="dark"?"dark":"default",r=uc.useScopedStore(x=>x.renderState),i=uc.useScopedStore(x=>x.showSource),s=uc.useScopedStore(x=>x.zoomOpen),o=uc.useScopedStore(x=>x.copied),a=uc.useScopedStore(x=>x.setRenderState),l=uc.useScopedStore(x=>x.setShowSource),d=uc.useScopedStore(x=>x.setZoomOpen),h=uc.useScopedStore(x=>x.setCopied),m=`mermaid-${_.useId().replace(/[^a-zA-Z0-9_-]/g,"")}`,v=_.useCallback(()=>d(!1),[d]),b=async()=>{await navigator.clipboard.writeText(e),h(!0),setTimeout(()=>h(!1),2e3)};return _.useEffect(()=>{let x=!1;return EMe().then(async S=>{S.initialize({startOnLoad:!1,securityLevel:"strict",theme:n});const{svg:C}=await S.render(m,e);x||a({status:"ready",svg:C})}).catch(()=>{x||a({status:"error"})}),()=>{x=!0}},[e,n,m,a]),r.status==="error"?u.jsx(QN,{source:e}):r.status==="loading"?u.jsx("div",{className:"relative group/mermaid",children:u.jsx(QN,{source:e})}):i?u.jsxs("div",{className:"relative group/mermaid",children:[u.jsx(QN,{source:e}),u.jsx(n6,{showSource:i,onToggleSource:()=>l(!i),onCopy:b,copied:o,onZoom:void 0})]}):u.jsxs("div",{className:"relative group/mermaid my-3",children:[u.jsx("div",{className:"flex justify-center overflow-x-auto",dangerouslySetInnerHTML:{__html:r.svg}}),u.jsx(n6,{showSource:i,onToggleSource:()=>l(!i),onCopy:b,copied:o,onZoom:()=>d(!0)}),s&&u.jsx(kMe,{svg:r.svg,onClose:v})]})}function AJ({source:e}){return u.jsx(uc.Provider,{init:void 0,children:u.jsx(NMe,{source:e})})}function n6({showSource:e,onToggleSource:t,onCopy:n,copied:r,onZoom:i}){return u.jsxs("div",{className:"absolute top-1.5 right-1.5 flex gap-1 opacity-100 md:opacity-0 md:group-hover/mermaid:opacity-100 transition-opacity [@media(hover:none)]:!opacity-100",children:[i&&!e&&u.jsx(Ie,{variant:"ghost",size:"icon","aria-label":"Zoom diagram",className:"h-8 w-8 rounded-md text-muted-foreground hover:text-foreground",onClick:i,children:u.jsx(uoe,{className:"h-4 w-4"})}),u.jsx(Ie,{variant:"ghost",size:"icon","aria-label":e?"View rendered diagram":"View diagram source",className:"h-8 w-8 rounded-md text-muted-foreground hover:text-foreground",onClick:t,children:u.jsx(a2,{className:"h-4 w-4"})}),u.jsx(Ie,{variant:"ghost",size:"icon","aria-label":r?"Copied":"Copy diagram source",className:he("h-8 w-8 rounded-md text-muted-foreground",!r&&"hover:text-foreground",r&&"hover:!bg-transparent"),onClick:n,children:r?u.jsx(ro,{className:"h-4 w-4 text-success"}):u.jsx(Oa,{className:"h-4 w-4"})})]})}function TMe({source:e}){const t=py(e);return t.status==="loading"?u.jsxs("div",{className:"p-4 text-sm text-muted-foreground",children:[u.jsx("div",{className:"hidden"})," Loading…"]}):t.status==="error"?u.jsx("div",{className:"p-4 text-sm text-destructive",children:t.message}):u.jsx("div",{className:"p-4",children:u.jsx(AJ,{source:t.content})})}async function AMe(e){var n;const t=MMe(e.contentUrl);if("share"in navigator&&typeof navigator.share=="function")try{return await navigator.share({title:e.displayName,url:t}),"shared"}catch(r){if(r instanceof DOMException&&r.name==="AbortError")return"shared"}if((n=navigator.clipboard)!=null&&n.writeText)try{return await navigator.clipboard.writeText(t),"copied"}catch{return"failed"}return"failed"}function RMe(e){const t=document.createElement("a");t.href=e.contentUrl,t.download=e.fileName,t.rel="noopener",document.body.appendChild(t),t.click(),t.remove()}function MMe(e){return typeof window>"u"?e:new URL(e,document.baseURI||window.location.href).toString()}const IR=tn("SheetBody",()=>e=>({dy:0,setDy:t=>e({dy:t})}));function Mh({source:e,open:t,onOpenChange:n}){const r=_.useCallback(()=>n(!1),[n]);return u.jsx($a,{open:t&&e!==null,onOpenChange:n,children:u.jsx(ia,{size:"lg",className:"inset-0 h-[100dvh] max-h-none w-full max-w-none translate-x-0 translate-y-0 rounded-none p-0 md:inset-auto md:left-1/2 md:top-1/2 md:h-auto md:max-h-[90dvh] md:w-auto md:max-w-3xl md:-translate-x-1/2 md:-translate-y-1/2 md:rounded-2xl",children:e?u.jsx(OMe,{source:e,onClose:r}):null})})}const jMe=120,IMe=.5;function PMe({startY:e,lastY:t,lastT:n,endY:r,now:i}){const s=r-e,o=Math.max(1,i-n),a=(r-t)/o;return s>jMe||a>IMe}function LMe({source:e,onClose:t}){const n=$Me(e),r=IR.useScopedStore(p=>p.dy),i=IR.useScopedStore(p=>p.setDy),s=_.useRef(null),o=_.useCallback(p=>{s.current={y:p.clientY,lastY:p.clientY,lastT:Date.now()};try{p.currentTarget.setPointerCapture(p.pointerId)}catch{}},[]),a=_.useCallback(p=>{if(!s.current)return;const m=p.clientY-s.current.y;m<0||(s.current.lastY=p.clientY,s.current.lastT=Date.now(),i(m))},[i]),l=_.useCallback(p=>{const m=s.current;s.current=null;try{p.currentTarget.releasePointerCapture(p.pointerId)}catch{}m&&(PMe({startY:m.y,lastY:m.lastY,lastT:m.lastT,endY:p.clientY,now:Date.now()})?t():i(0))},[t,i]),d=_.useCallback(()=>{AMe(e)},[e]),h=_.useCallback(()=>RMe(e),[e]);return u.jsxs("div",{className:"flex min-h-0 flex-1 flex-col",style:r>0?{transform:`translateY(${r}px)`,transition:"none"}:void 0,children:[u.jsxs("div",{onPointerDown:o,onPointerMove:a,onPointerUp:l,onPointerCancel:l,className:"border-b border-border px-4 py-3 touch-none",children:[u.jsx("div",{className:"mx-auto mb-2 h-1 w-12 rounded-full bg-muted md:hidden",role:"button","aria-label":"Drag down to close"}),u.jsx(za,{className:"truncate text-base",children:e.displayName}),u.jsx(jx,{className:"truncate text-xs",children:n})]}),u.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto overscroll-contain touch-pan-y [-webkit-overflow-scrolling:touch]",role:"region","aria-label":"File preview",children:_.createElement(DMe(e),{source:e})},e.id),u.jsxs("div",{className:"flex items-center justify-end gap-2 border-t border-border px-4 py-3",children:[u.jsxs(Ie,{type:"button",variant:"outline",onClick:d,children:[u.jsx(eae,{className:"mr-2 h-4 w-4"}),"Share"]}),e.origin==="offer_download"?u.jsxs(Ie,{type:"button",onClick:h,children:[u.jsx(qM,{className:"mr-2 h-4 w-4"}),"Download"]}):null]})]})}function OMe({source:e,onClose:t}){return u.jsx(IR.Provider,{init:void 0,children:u.jsx(LMe,{source:e,onClose:t})})}function DMe(e){const t={id:e.id,displayName:e.displayName,mimeType:e.mimeType,size:e.size??0,contentUrl:e.contentUrl,relativePath:e.relativePath??""},n=Ch(t);return n==="image"?lEe:n==="pdf"?Hz:n==="audio"?bMe:n==="video"?xMe:n==="table"?pMe:n==="markdown"?fMe:n==="json"?vMe:n==="mermaid"?TMe:n==="code"?wMe:ag(t).kind==="external"?Hz:mMe}function $Me(e){const t={id:e.id,displayName:e.displayName,mimeType:e.mimeType,size:e.size??0,contentUrl:e.contentUrl,relativePath:e.relativePath??""},n=Ch(t),r=Xx(n,e.mimeType),i=e.size?` · ${kh(e.size)}`:"";return`${r}${i}`}function mg(e,t){return{id:e.id,contentUrl:e.contentUrl,displayName:e.displayName,fileName:e.displayName,relativePath:e.relativePath,mimeType:e.mimeType,size:e.size,origin:t}}const jc=_.forwardRef(({className:e,...t},n)=>u.jsx("textarea",{"data-gramm":"false","data-gramm_editor":"false","data-enable-grammarly":"false","data-1p-ignore":!0,autoComplete:"off",className:he("flex w-full rounded-lg border border-border bg-background px-2.5 py-2 text-sm placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),ref:n,...t}));jc.displayName="Textarea";const zMe=new Set(["changes","history"]),BMe=new Set(["public","private"]),FMe=new Set(["branches","pull_requests"]);function UMe(e){return zMe.has(e)}function HMe(e){return BMe.has(e)}function WMe(e){return FMe.has(e)}const k0={};function r6(e){return!e.isCollapsed&&!e.hasPreviewAttachment&&e.patch===void 0&&e.patchError===void 0&&!e.isPatchLoading}function VMe(e,t){return!e||!t.mimeType||typeof t.size!="number"||t.changeType==="deleted"||!t.mimeType.startsWith("image/")&&t.mimeType!=="application/pdf"?null:{id:`diff:${t.path}`,kind:t.mimeType.startsWith("image/")?"image":"file",displayName:t.path.split("/").pop()??t.path,absolutePath:t.path,relativePath:t.path,contentUrl:`/api/projects/${e}/files/${encodeURIComponent(t.path)}/content`,mimeType:t.mimeType,size:t.size}}function RJ(e){return e.isUntracked}function KMe(e){return RJ(e)?e.path.includes("/"):!1}function ST(e){return u.jsxs(Js,{delayDuration:0,children:[u.jsx(Zs,{asChild:!0,children:u.jsx("button",{type:"button","aria-label":e.label,title:e.label,onClick:e.onClick,className:he("flex h-11 w-11 md:h-7 md:w-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",e.active&&"bg-accent text-foreground"),children:e.children})}),u.jsx(js,{children:e.label})]})}function MJ({checked:e,mixed:t=!1,label:n,className:r,onClick:i}){let s;return t?s=u.jsx(mH,{className:"h-3 w-3",strokeWidth:3}):e?s=u.jsx(ro,{className:"h-3 w-3",strokeWidth:3}):s=null,u.jsx("button",{type:"button","aria-label":n??(e?"Exclude file from commit":"Include file in commit"),"aria-checked":t?"mixed":e,"aria-pressed":t?"mixed":e,onClick:o=>{o.stopPropagation(),i()},className:he("flex size-4.5 shrink-0 items-center justify-center rounded border transition-colors",e||t?"border-foreground bg-foreground text-background":"border-border bg-background text-transparent",r),children:s})}function VP(e){const t=Date.parse(e);if(!Number.isFinite(t))return"";const n=Date.now()-t,r=6e4,i=60*r,s=24*i,o=7*s,a=30*s,l=365*s;return n<r?"just now":n<i?`${Math.round(n/r)}m ago`:n<s?`${Math.round(n/i)}hr ago`:n<o?`${Math.round(n/s)}d ago`:n<a?`${Math.round(n/o)}wk ago`:n<l?`${Math.round(n/a)}mo ago`:`${Math.round(n/l)}yr ago`}function GMe(e){return e?`Last fetched ${VP(e)}`:"No local fetch recorded"}function qMe({entry:e,isPendingPush:t=!1}){const n=VP(e.authoredAt),r=!!e.githubUrl;let i;return e.tags.length>0?i=u.jsxs("div",{className:"flex shrink-0 flex-wrap justify-end gap-1",children:[e.tags.map(s=>u.jsx("span",{className:"inline-flex items-center rounded-full bg-muted border border-border px-2 py-0.5 text-[11px]",children:s},s)),t?u.jsx("span",{className:"inline-flex items-center rounded-full bg-muted border border-border px-2 py-0.5 text-[11px]",children:u.jsx(vb,{className:"size-3"})}):null]}):t?i=u.jsx("div",{className:"flex shrink-0 flex-wrap justify-end gap-1",children:u.jsx("span",{className:"inline-flex items-center rounded-full bg-muted border border-border px-2 py-0.5 text-[11px]",children:u.jsx(vb,{className:"size-3"})})}):i=null,u.jsxs("button",{type:"button",disabled:!r,onClick:()=>{!e.githubUrl||typeof window>"u"||window.open(e.githubUrl,"_blank","noopener,noreferrer")},className:he("flex w-full items-start gap-3 rounded-lg border border-border bg-background pl-3 pr-2 py-2 text-left transition-colors",r?"hover:bg-accent":"cursor-default opacity-60"),children:[u.jsxs("div",{className:"min-w-0 flex-1",children:[u.jsx("div",{className:"truncate text-sm font-medium text-foreground",children:e.summary}),e.description?u.jsx("div",{className:"mt-1 line-clamp-2 whitespace-pre-wrap text-xs text-muted-foreground",children:e.description}):null,u.jsxs("div",{className:"mt-1 flex min-w-0 items-center gap-1 text-xs text-muted-foreground",children:[e.authorName?u.jsx("span",{className:"truncate",children:e.authorName}):null,e.authorName&&n?u.jsx("span",{"aria-hidden":"true",children:"•"}):null,n?u.jsx("span",{children:n}):null]})]}),i]})}function i6(e){switch(e.kind){case"local":return 0;case"pull_request":return 1;case"remote":default:return 2}}function YMe(e){const t=new Map;for(const n of e){const r=t.get(n.name);(!r||i6(n)<i6(r))&&t.set(n.name,n)}return t}function XMe(e,t){const n=YMe([...e.local,...e.pullRequests,...e.remote]);t&&n.delete(t);const r=new Set,i=e.defaultBranchName?n.get(e.defaultBranchName):void 0;i&&r.add(i.name);const s=e.recent.map(a=>n.get(a.name)??a).filter(a=>!!a&&!r.has(a.name));for(const a of s)r.add(a.name);const o=[...n.values()].filter(a=>!r.has(a.name)).sort((a,l)=>a.displayName.localeCompare(l.displayName));return{defaultBranch:i,recent:s,other:o}}function JMe({open:e,onOpenChange:t,onGetGitHubPublishInfo:n,onCheckGitHubRepoAvailability:r,onPublish:i}){const s=at(L=>L.publishInfo),o=at(L=>L.isLoadingPublishInfo),a=at(L=>L.publishOwner),l=at(L=>L.publishName),d=at(L=>L.publishVisibility),h=at(L=>L.publishDescription),p=at(L=>L.publishAvailability),m=at(L=>L.isCheckingPublishAvailability),v=at(L=>L.isPublishing),b=at(L=>L.setPublishInfo),x=at(L=>L.setIsLoadingPublishInfo),S=at(L=>L.setPublishOwner),C=at(L=>L.setPublishName),k=at(L=>L.setPublishVisibility),w=at(L=>L.setPublishDescription),N=at(L=>L.setPublishAvailability),A=at(L=>L.setIsCheckingPublishAvailability),T=at(L=>L.setIsPublishing);_.useEffect(()=>{if(!e)return;let L=!1;return x(!0),N(null),n().then(I=>{L||(b(I),S(I.owners[0]??I.activeAccountLogin??""),C(I.suggestedRepoName),k("private"),w(""))}).finally(()=>{L||x(!1)}),()=>{L=!0}},[n,e,N,w,b,x,C,S,k]),_.useEffect(()=>{if(!e||!(s!=null&&s.ghInstalled)||!s.authenticated)return;const L=a.trim(),I=l.trim();if(!L||!I){N(null);return}let $=!1;A(!0);const H=window.setTimeout(()=>{r({owner:L,name:I}).then(z=>{$||N(z)}).finally(()=>{$||A(!1)})},250);return()=>{$=!0,window.clearTimeout(H)}},[s==null?void 0:s.authenticated,s==null?void 0:s.ghInstalled,l,r,e,a,N,A]);async function M(){if(!(!a.trim()||!l.trim())){T(!0);try{const L=await i({owner:a.trim(),name:l.trim(),visibility:d,description:h});Wi(L)&&L.ok&&t(!1)}finally{T(!1)}}}const j=!!(s!=null&&s.ghInstalled&&s.authenticated&&a.trim()&&l.trim()&&(p!=null&&p.available)&&!m&&!v);let P;m?P=u.jsx("div",{className:"pointer-events-none absolute inset-y-0 right-3 flex items-center text-muted-foreground",children:u.jsx(In,{className:"size-4 animate-spin"})}):p?P=u.jsx("div",{className:"absolute inset-y-0 right-2 flex items-center",children:u.jsxs(Js,{delayDuration:0,children:[u.jsx(Zs,{asChild:!0,children:u.jsx("button",{type:"button",tabIndex:-1,"aria-label":p.message,className:he("flex size-6 items-center justify-center rounded-md",p.available?"text-success":"text-destructive"),children:p.available?u.jsx(ro,{className:"size-4"}):u.jsx(xb,{className:"size-4"})})}),u.jsx(js,{children:p.message})]})}):P=null;let D;return o?D=u.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[u.jsx(In,{className:"size-4 animate-spin"}),u.jsx("span",{children:"Checking GitHub CLI…"})]}):s&&!s.ghInstalled?D=u.jsxs("div",{className:"space-y-2 text-sm text-muted-foreground",children:[u.jsx("p",{children:"GitHub CLI is not installed."}),u.jsx("div",{className:"rounded-lg border border-border px-3 py-2 font-mono text-xs text-foreground",children:"brew install gh"}),u.jsx("p",{children:"Then run:"}),u.jsx("div",{className:"rounded-lg border border-border px-3 py-2 font-mono text-xs text-foreground",children:"gh auth login"})]}):s&&!s.authenticated?D=u.jsxs("div",{className:"space-y-2 text-sm text-muted-foreground",children:[u.jsx("p",{children:"GitHub CLI is installed but not signed in."}),u.jsx("div",{className:"rounded-lg border border-border px-3 py-2 font-mono text-xs text-foreground",children:"gh auth login"})]}):D=u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"space-y-2",children:u.jsxs(Yo,{value:a,onValueChange:S,children:[u.jsx(So,{className:"pl-[11px] [&>span]:flex [&>span]:items-center [&>span]:gap-2",children:u.jsx(Ta,{placeholder:"Select owner"})}),u.jsx(wo,{children:((s==null?void 0:s.owners)??[]).map(L=>u.jsx(ri,{value:L,children:u.jsxs("span",{className:"flex items-center gap-2",children:[L===(s==null?void 0:s.activeAccountLogin)?u.jsx(dC,{className:"size-4 text-muted-foreground"}):u.jsx(Nie,{className:"size-4 text-muted-foreground"}),u.jsx("span",{className:"pl-[1px]",children:L})]})},L))})]})}),u.jsx("div",{className:"space-y-2",children:u.jsxs("div",{className:"relative",children:[u.jsx(dn,{value:l,onChange:L=>C(L.target.value),placeholder:"my-repo",className:"pl-9 pr-10"}),u.jsx(Noe,{className:"pointer-events-none absolute inset-y-0 left-3 my-auto size-4 text-muted-foreground"}),P]})}),u.jsx("div",{className:"space-y-2",children:u.jsxs("div",{className:"relative",children:[u.jsx(Ax,{className:"pointer-events-none absolute left-3 top-3 size-4 text-muted-foreground"}),u.jsx(jc,{value:h,onChange:L=>w(L.target.value),rows:3,placeholder:"Optional description",className:"pl-9 outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"})]})}),u.jsx("div",{className:"space-y-2",children:u.jsxs(Yo,{value:d,onValueChange:L=>{HMe(L)&&k(L)},children:[u.jsx(So,{className:"pl-[11px] [&>span]:flex [&>span]:items-center [&>span]:gap-2",children:u.jsx(Ta,{placeholder:"Select visibility"})}),u.jsxs(wo,{children:[u.jsx(ri,{value:"private",children:u.jsxs("span",{className:"flex items-center gap-2",children:[u.jsx(ooe,{className:"size-4 text-muted-foreground"}),u.jsx("span",{className:"pl-[1px]",children:"Private"})]})}),u.jsx(ri,{value:"public",children:u.jsxs("span",{className:"flex items-center gap-2",children:[u.jsx(Wse,{className:"size-4 text-muted-foreground"}),u.jsx("span",{className:"pl-[1px]",children:"Public"})]})})]})]})})]}),u.jsx($a,{open:e,onOpenChange:t,children:u.jsxs(ia,{size:"sm",className:"max-w-[min(92vw,475px)]",children:[u.jsxs(El,{className:"space-y-2 px-4 pb-4 pt-4",children:[u.jsxs("div",{className:"space-y-1",children:[u.jsx(za,{children:"Push to GitHub"}),u.jsx(jx,{children:"Create a GitHub repository from this local project using GitHub CLI."})]}),D]}),u.jsxs(bd,{children:[u.jsx(Ie,{variant:"ghost",size:"sm",onClick:()=>t(!1),children:"Cancel"}),u.jsx(Ie,{size:"sm",disabled:!j,onClick:()=>void M(),children:v?u.jsxs(u.Fragment,{children:[u.jsx(In,{className:"mr-1.5 size-3.5 animate-spin"}),"Publishing…"]}):"Push to GitHub"})]})]})})}function jJ({value:e,onChange:t,placeholder:n,disabled:r,trailingAction:i}){return u.jsxs("div",{className:"relative",children:[u.jsx(Yp,{className:"pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),u.jsx(dn,{value:e,onChange:s=>t(s.target.value),placeholder:n,className:he("h-9 pl-7 text-sm",i?"pr-14":void 0),disabled:r}),i?u.jsx("div",{className:"absolute right-1 top-1/2 -translate-y-1/2",children:i}):null]})}function Of({title:e,entries:t,emptyLabel:n,selectedName:r,disabled:i,stickyTitle:s=!1,onSelect:o}){return t.length===0&&!n?null:u.jsxs("div",{className:"space-y-1",children:[u.jsx("div",{className:he("px-1 py-1 text-[11px] font-medium uppercase tracking-[0.08em] text-muted-foreground",s&&"sticky top-0 z-10 bg-background"),children:e}),t.length===0?u.jsx("div",{className:"px-1 py-1 text-xs text-muted-foreground",children:n}):t.map(a=>{const l=r===a.name;return u.jsxs("button",{type:"button",disabled:i,onClick:()=>o(a),className:he("flex w-full items-start gap-2 rounded-lg px-2 py-2 text-left transition-colors disabled:opacity-60",l?"bg-accent text-foreground":"hover:bg-accent"),children:[a.kind==="pull_request"?u.jsx(dH,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}):u.jsx(Sc,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}),u.jsxs("div",{className:"min-w-0 flex-1",children:[u.jsxs("div",{className:"flex w-full items-center gap-3",children:[u.jsx("div",{className:"min-w-0 flex-1 overflow-hidden whitespace-nowrap text-sm text-foreground",children:a.displayName}),a.updatedAt?u.jsx("div",{className:"ml-auto shrink-0 text-right text-[11px] text-muted-foreground",children:VP(a.updatedAt)}):null]}),a.kind==="pull_request"&&a.description||a.headLabel?u.jsx("div",{className:"truncate text-xs text-muted-foreground",children:a.kind==="pull_request"?a.description??a.headLabel??a.name:a.headLabel??void 0}):null]})]},a.id)})]})}function ZMe({open:e,onOpenChange:t,branchList:n,currentBranchName:r,onPreviewMergeBranch:i,onMergeBranch:s}){const o=at(z=>z.mergeBranchQuery),a=at(z=>z.mergeBranchSelectedName),l=at(z=>z.mergePreview),d=at(z=>z.mergePreviewError),h=at(z=>z.isMergePreviewLoading),p=at(z=>z.isMergeBranching),m=at(z=>z.setMergeBranchQuery),v=at(z=>z.setMergeBranchSelectedName),b=at(z=>z.setMergePreview),x=at(z=>z.setMergePreviewError),S=at(z=>z.setIsMergePreviewLoading),C=at(z=>z.setIsMergeBranching),k=at(z=>z.resetMergeBranchModal),w=at(z=>z.resetMergePreview),N=_.useMemo(()=>n?XMe(n,r):{defaultBranch:void 0,recent:[],other:[]},[n,r]),A=o.trim().toLowerCase(),T=_.useCallback(z=>A?[z.displayName,z.name,z.description,z.prTitle,z.headLabel].some(F=>F==null?void 0:F.toLowerCase().includes(A)):!0,[A]),M=N.defaultBranch&&T(N.defaultBranch)?N.defaultBranch:void 0,j=N.recent.filter(T),P=N.other.filter(T),D=_.useMemo(()=>a?[N.defaultBranch,...N.recent,...N.other].find(z=>z!==void 0&&z.name===a)??null:null,[N.defaultBranch,N.other,N.recent,a]);_.useEffect(()=>{e||k()},[e,k]),_.useEffect(()=>{if(!e||!D){w();return}let z=!1;return b(null),x(null),S(!0),i(D).then(F=>{z||b(F)}).catch(F=>{z||x(F instanceof Error?F.message:String(F))}).finally(()=>{z||S(!1)}),()=>{z=!0}},[i,e,w,D,S,b,x]);const L=!D||!l||h||p||l.status!=="mergeable";async function I(){if(!(!D||L)){C(!0);try{const z=await s(D);z!=null&&z.ok&&t(!1)}finally{C(!1)}}}let $;l?l.status==="up_to_date"?$=u.jsx(ro,{className:"mt-1 size-3.5 shrink-0 text-success"}):l.status==="conflicts"?$=u.jsx(xb,{className:"mt-1 size-3.5 shrink-0 text-warning"}):l.status==="mergeable"?$=u.jsx(uH,{className:"mt-1 size-3.5 shrink-0 text-muted-foreground"}):$=u.jsx(xb,{className:"mt-1 size-3.5 shrink-0 text-destructive"}):$=null;let H;return D?h?H=u.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[u.jsx(In,{className:"size-3.5 animate-spin"}),u.jsx("span",{children:"Checking merge preview…"})]}):d?H=u.jsx("div",{className:"text-sm text-destructive",children:d}):l?H=u.jsxs("div",{className:"flex items-start gap-2",children:[$,u.jsxs("div",{className:"min-w-0 space-y-1",children:[u.jsx("div",{className:"text-sm font-medium text-foreground",children:l.message}),l.detail?u.jsx("div",{className:"line-clamp-2 whitespace-pre-wrap text-xs text-muted-foreground",children:l.detail}):null]})]}):H=u.jsx("div",{className:"text-sm text-muted-foreground",children:"Preview unavailable."}):H=u.jsx("div",{className:"text-sm text-muted-foreground",children:"Select a branch to preview the merge."}),u.jsx($a,{open:e,onOpenChange:t,children:u.jsxs(ia,{size:"sm",className:"max-w-[min(92vw,475px)]",children:[u.jsxs(El,{className:"flex min-h-0 flex-col gap-3 px-4 pb-4 pt-4",children:[u.jsxs("div",{className:"space-y-1",children:[u.jsxs(za,{children:["Merge into ",r??"current branch"]}),u.jsx(jx,{children:"Choose a branch to continue."})]}),u.jsx(jJ,{value:o,onChange:m,placeholder:"Search branches"}),u.jsxs("div",{className:"max-h-[375px] space-y-3 overflow-y-auto pr-1",children:[u.jsx(Of,{title:"Default Branch",entries:M?[M]:[],emptyLabel:"No default branch available.",selectedName:a,onSelect:z=>v(z.name)}),u.jsx(Of,{title:"Recent Branches",entries:j,emptyLabel:"No recent branches.",selectedName:a,onSelect:z=>v(z.name)}),u.jsx(Of,{title:"Other Branches",entries:P,emptyLabel:"No other branches match this search.",selectedName:a,onSelect:z=>v(z.name)})]}),u.jsx("div",{className:"px-2",children:H})]}),u.jsx(bd,{children:u.jsxs("div",{className:"flex min-w-0 w-full items-center justify-end gap-2",children:[u.jsx(Ie,{variant:"ghost",size:"sm",onClick:()=>t(!1),children:"Cancel"}),u.jsx(Ie,{className:"max-w-full min-w-0",size:"sm",disabled:L,onClick:()=>void I(),children:p?u.jsxs(u.Fragment,{children:[u.jsx(In,{className:"mr-1.5 h-3.5 w-3.5 animate-spin"}),"Merging…"]}):u.jsx("span",{className:"block max-w-full truncate",children:"Merge"})})]})})]})})}function QMe({currentBranchName:e,onListBranches:t,onPreviewMergeBranch:n,onMergeBranch:r,onCheckoutBranch:i,onCreateBranch:s}){const o=at(X=>X.branchSwitcherOpen),a=at(X=>X.mergeModalOpen),l=at(X=>X.branchSwitcherIsLoading),d=at(X=>X.branchSwitcherIsMutating),h=at(X=>X.branchSwitcherQuery),p=at(X=>X.branchSwitcherEntryView),m=at(X=>X.branchList),v=at(X=>X.branchSwitcherError),b=at(X=>X.setBranchSwitcherOpen),x=at(X=>X.setMergeModalOpen),S=at(X=>X.setBranchSwitcherIsLoading),C=at(X=>X.setBranchSwitcherIsMutating),k=at(X=>X.setBranchSwitcherQuery),w=at(X=>X.setBranchSwitcherEntryView),N=at(X=>X.setBranchList),A=at(X=>X.setBranchSwitcherError);_.useEffect(()=>{o&&(S(!0),A(null),t().then(X=>N(X)).catch(X=>{A(X instanceof Error?X.message:String(X))}).finally(()=>{S(!1)}))},[t,o,N,A,S]);const T=h.trim().toLowerCase(),M=X=>X.filter(G=>T?[G.displayName,G.name,G.description,G.prTitle,G.headLabel].some(te=>te==null?void 0:te.toLowerCase().includes(T)):!0),j=(m==null?void 0:m.currentBranchName)??e,P=new Set(((m==null?void 0:m.pullRequests)??[]).map(X=>X.headRefName??X.name)),D=M((m==null?void 0:m.recent)??[]).filter(X=>X.name!==j),L=M((m==null?void 0:m.local)??[]).filter(X=>X.name!==j),I=M((m==null?void 0:m.remote)??[]).filter(X=>X.name!==j&&!P.has(X.name)),$=M((m==null?void 0:m.pullRequests)??[]).filter(X=>X.name!==j),H=(m==null?void 0:m.pullRequests.length)??0;async function z(X){C(!0);try{await i(X),b(!1),k(""),w("branches")}finally{C(!1)}}async function F(){C(!0);try{await s(),b(!1),k(""),w("branches")}finally{C(!1)}}function K(){b(!1),x(!0)}let W;(m==null?void 0:m.pullRequestsStatus)==="error"?W=m.pullRequestsError??"Could not load pull requests.":(m==null?void 0:m.pullRequestsStatus)==="unavailable"?W="Pull requests unavailable for this repository.":W="No open pull requests.";let V;return l?V=u.jsxs("div",{className:"flex items-center justify-center gap-2 py-6 text-sm text-muted-foreground",children:[u.jsx(In,{className:"h-4 w-4 animate-spin"}),u.jsx("span",{children:"Loading branches…"})]}):v?V=u.jsx("div",{className:"rounded-lg border border-border px-3 py-2 text-sm text-muted-foreground",children:v}):p==="pull_requests"?V=u.jsx(Of,{title:"Open PRs",entries:$,emptyLabel:W,disabled:d,stickyTitle:!0,onSelect:X=>{z(X)}}):V=u.jsxs("div",{className:"space-y-3",children:[u.jsx(Of,{title:"Recent",entries:D,emptyLabel:"No recent branches.",disabled:d,stickyTitle:!0,onSelect:X=>{z(X)}}),u.jsx(Of,{title:"Local",entries:L,emptyLabel:"No local branches.",disabled:d,stickyTitle:!0,onSelect:X=>{z(X)}}),u.jsx(Of,{title:"Remote",entries:I,emptyLabel:"No remote branches.",disabled:d,stickyTitle:!0,onSelect:X=>{z(X)}})]}),u.jsxs(Ld,{open:o,onOpenChange:b,children:[u.jsx(Od,{asChild:!0,children:u.jsxs("button",{type:"button",className:"flex min-w-0 max-w-full items-center gap-1 rounded-md px-1.5 py-1 text-sm transition-colors hover:bg-accent hover:text-foreground","aria-label":"Open branch switcher",children:[u.jsx(Sc,{className:"h-3.5 w-3.5 shrink-0"}),u.jsx("span",{className:"truncate",children:e??"Detached HEAD"}),u.jsx(Gm,{className:"h-3.5 w-3.5 shrink-0"})]})}),u.jsx(Zc,{align:"start",className:"w-[320px] p-2",children:u.jsxs("div",{className:"space-y-2",children:[u.jsx(jJ,{value:h,onChange:k,placeholder:p==="pull_requests"?"Search pull requests":"Search branches",disabled:l||d,trailingAction:u.jsx(Ie,{variant:"ghost",size:"sm",onClick:()=>void F(),disabled:l||d,className:"h-7 px-2 text-xs hover:!bg-transparent hover:!border-border/0",children:"+ New"})}),u.jsx(Ns,{value:p,onValueChange:X=>{WMe(X)&&w(X)},size:"sm",className:"w-full",optionClassName:"flex-1 justify-center",options:[{value:"branches",label:"Branches"},{value:"pull_requests",label:`Open PRs ${H}`}]}),u.jsx("div",{className:"max-h-[420px] overflow-y-auto pr-1.5 -mr-[8px]",children:V}),j?u.jsx(Ie,{variant:"default",size:"sm",disabled:l||d||!!v,onClick:K,className:"h-9 w-full justify-center rounded-lg px-3 text-sm",children:u.jsxs("span",{className:"block max-w-full truncate",children:[u.jsx(zse,{className:"mr-1.5 inline h-3.5 w-3.5 shrink-0"}),"Merge branch into ",j,"..."]})}):null]})}),u.jsx(ZMe,{open:a,onOpenChange:x,branchList:m,currentBranchName:j,onPreviewMergeBranch:n,onMergeBranch:r})]})}function eje({file:e,rootRef:t,projectId:n,isCollapsed:r,isChecked:i,editorLabel:s,diffRenderMode:o,wrapLines:a,onToggleCollapsed:l,onToggleChecked:d,fileActions:h,patch:p,patchError:m,isPatchLoading:v,onLoadPatch:b}){const x=RJ(e),S=KMe(e),C=_A.useScopedStore(z=>z.selectedAttachmentId),k=_A.useScopedStore(z=>z.setSelectedAttachmentId),w=_.useRef(null),N=_.useRef(null),{sentinelRef:A,isStuck:T}=Oke({rootRef:t,disabled:r}),M=_.useMemo(()=>VMe(n,e),[e,n]),j=M!==null,P=r6({isCollapsed:r,hasPreviewAttachment:j,patch:p,patchError:m,isPatchLoading:v});_.useEffect(()=>{if(!P)return;const z=`${e.path}\0${e.patchDigest}`;N.current!==z&&(N.current=z,b(e.path).catch(()=>{}))},[e.patchDigest,e.path,b,P]);function D(z){if(ag(z).openInNewTab){typeof window<"u"&&window.open(new URL(z.contentUrl,window.location.origin).toString(),"_blank","noopener,noreferrer");return}k(z.id)}function L(z){var K;z.preventDefault(),z.stopPropagation();const F=z.currentTarget.getBoundingClientRect();(K=w.current)==null||K.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,cancelable:!0,clientX:F.left+F.width/2,clientY:F.bottom,view:window}))}function I(){if(!r){l();return}if(j||p!==void 0){l();return}if(v)return;if(!(m!==void 0||r6({isCollapsed:!1,hasPreviewAttachment:j,patch:p,patchError:m,isPatchLoading:v}))){l();return}b(e.path).then(()=>{l()}).catch(()=>{})}let $;v&&r&&!M?$=u.jsx(In,{className:"h-3.5 w-3.5 shrink-0 animate-spin"}):r?$=u.jsx(Gm,{className:"h-3.5 w-3.5 shrink-0"}):$=u.jsx(sH,{className:"h-3.5 w-3.5 shrink-0"});let H;return M?H=u.jsx("div",{className:"flex justify-center p-3",children:M.kind==="image"?u.jsx(t1,{attachment:M,onClick:()=>D(M)}):u.jsx(ko,{attachment:M,onClick:()=>D(M)})}):v?H=u.jsxs("div",{className:"flex items-center justify-center px-3 py-8 text-sm text-muted-foreground",children:[u.jsx(In,{className:"mr-2 h-4 w-4 animate-spin"}),"Loading diff..."]}):m?H=u.jsx("div",{className:"px-3 py-4 text-sm text-destructive",children:m}):p!==void 0?H=u.jsx(Pke,{patch:p,options:{diffStyle:o,disableFileHeader:!0,disableBackground:!1,overflow:a?"wrap":"scroll",lineDiffType:"word",diffIndicators:"classic"}}):H=u.jsx("div",{className:"px-3 py-4 text-sm text-muted-foreground",children:"Diff unavailable."}),u.jsxs(bh,{children:[u.jsx(xh,{asChild:!0,children:u.jsxs("div",{ref:w,className:"relative rounded-lg border border-border bg-background",children:[r?null:u.jsx("div",{ref:A,className:"pointer-events-none absolute inset-x-0 top-0 h-px","aria-hidden":"true"}),u.jsxs("div",{role:"button",tabIndex:0,onClick:I,onKeyDown:z=>{z.key!=="Enter"&&z.key!==" "||(z.preventDefault(),I())},className:he("group/header sticky top-0 z-20 flex cursor-pointer items-center justify-between gap-3 bg-background pl-[7px] pr-2.5 py-1.5 text-[13px] text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",!r&&!T&&"rounded-t-[calc(theme(borderRadius.lg)-1px)]",r&&"rounded-[calc(theme(borderRadius.lg)-1px)]",!r&&"border-b border-border/50"),children:[u.jsxs("div",{className:"flex min-w-0 items-center",children:[u.jsx(MJ,{checked:i,onClick:d}),u.jsx("div",{className:"min-w-0 truncate select-none ml-2 mr-1",children:e.path})]}),u.jsxs("div",{className:"flex shrink-0 items-center gap-2 select-none",children:[u.jsxs("span",{className:"whitespace-nowrap text-xs font-mono",children:[e.additions>0?u.jsxs("span",{className:"text-success",children:["+",e.additions]}):null,e.deletions>0?u.jsxs("span",{className:e.additions>0?"ml-2 text-destructive":"text-destructive",children:["-",e.deletions]}):null]}),u.jsx("button",{type:"button","aria-label":`Open actions for ${e.path}`,onClick:L,className:"flex h-5 w-5 shrink-0 items-center justify-center rounded-sm text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",children:u.jsx(bb,{className:"h-3.5 w-3.5 shrink-0"})}),$]})]}),r?null:u.jsx("div",{className:"kanna-diff-patch overflow-hidden rounded-b-[calc(theme(borderRadius.lg)-1px)] pb-[1px]",children:H}),u.jsx(Mh,{source:M&&C===M.id?mg(M,"user_attachment"):null,open:M!==null&&C===M.id,onOpenChange:z=>!z&&k(null)})]},e.path)}),u.jsxs(Id,{children:[u.jsxs(br,{onSelect:z=>{z.stopPropagation(),h.onOpenFile(e.path)},children:[u.jsx(GM,{className:"h-3.5 w-3.5"}),u.jsxs("span",{className:"text-xs font-medium",children:["Open in ",s]})]}),u.jsxs(br,{onSelect:z=>{z.stopPropagation(),h.onOpenInFinder(e.path)},children:[u.jsx(cC,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"text-xs font-medium",children:"Open in Finder"})]}),u.jsxs(br,{onSelect:z=>{z.stopPropagation(),h.onDiscardFile(e.path)},className:"text-destructive hover:bg-destructive/10 focus:bg-destructive/10",children:[u.jsx(Yc,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"text-xs font-medium",children:"Discard Changes"})]}),u.jsxs(br,{disabled:!x,onSelect:z=>{z.stopPropagation(),x&&h.onIgnoreFile(e.path)},children:[u.jsx(k3,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"text-xs font-medium",children:"Ignore File"})]}),u.jsxs(br,{disabled:!S,onSelect:z=>{z.stopPropagation(),S&&h.onIgnoreFolder(e.path)},children:[u.jsx(k3,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"text-xs font-medium",children:"Ignore folder..."})]}),u.jsx(Y9,{}),u.jsxs(br,{onSelect:z=>{z.stopPropagation(),h.onCopyFilePath(e.path)},children:[u.jsx(Oa,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"text-xs font-medium",children:"Copy File Path"})]}),u.jsxs(br,{onSelect:z=>{z.stopPropagation(),h.onCopyRelativePath(e.path)},children:[u.jsx(Oa,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"text-xs font-medium",children:"Copy Relative Path"})]})]})]})}function tje({projectId:e,diffs:t,editorLabel:n,diffRenderMode:r,wrapLines:i,onOpenFile:s,onOpenInFinder:o,onDiscardFile:a,onIgnoreFile:l,onIgnoreFolder:d,onCopyFilePath:h,onCopyRelativePath:p,onListBranches:m,onPreviewMergeBranch:v,onMergeBranch:b,onCheckoutBranch:x,onCreateBranch:S,onGenerateCommitMessage:C,onInitializeGit:k,onGetGitHubPublishInfo:w,onCheckGitHubRepoAvailability:N,onSetupGitHub:A,onCommit:T,onSyncWithRemote:M,onLoadPatch:j,onDiffRenderModeChange:P,onWrapLinesChange:D}){var Yn;const L=_.useMemo(()=>({onOpenFile:s,onOpenInFinder:o,onDiscardFile:a,onIgnoreFile:l,onIgnoreFolder:d,onCopyFilePath:h,onCopyRelativePath:p}),[s,o,a,l,d,h,p]),I=t.files.length>0,$=at(ye=>ye.isGenerating),H=at(ye=>ye.commitModeInFlight),z=at(ye=>ye.isSyncing),F=at(ye=>ye.isGitHubPublishModalOpen),K=at(ye=>ye.patchesByPath),W=at(ye=>ye.patchErrorsByPath),V=at(ye=>ye.loadingPatchPaths),X=at(ye=>ye.setIsGenerating),G=at(ye=>ye.setCommitModeInFlight),te=at(ye=>ye.setIsSyncing),oe=at(ye=>ye.setIsGitHubPublishModalOpen),ue=at(ye=>ye.reconcilePatches),de=at(ye=>ye.setPatchLoading),ee=at(ye=>ye.clearPatchLoading),ne=at(ye=>ye.clearPatchError),ie=at(ye=>ye.setPatchResult),ae=at(ye=>ye.setPatchError),Q=_.useRef(null),ke=_.useRef(null),Se=_.useRef({}),Ne=_.useMemo(()=>t.files.map(ye=>ye.path),[t.files]),Xe=_.useMemo(()=>Ne.join("\0"),[Ne]),ht=I?"changes":"history",St=Ks(ye=>{var tt;return e?((tt=ye.projectUi[e])==null?void 0:tt.viewMode)??ht:ht}),Bt=Ks(ye=>{var tt;return e?((tt=ye.projectUi[e])==null?void 0:tt.collapsedPaths)??k0:k0}),Yt=Ks(ye=>{var tt;return e?((tt=ye.projectUi[e])==null?void 0:tt.summary)??"":""}),Mt=Ks(ye=>{var tt;return e?((tt=ye.projectUi[e])==null?void 0:tt.description)??"":""}),mn=Ks(ye=>ye.reconcileCollapsedPaths),Ge=Ks(ye=>ye.toggleCollapsedPath),Pt=Ks(ye=>ye.setViewMode),gn=Ks(ye=>ye.setCommitDraft),_t=Ks(ye=>ye.clearCommitDraft),jt=d0(ye=>e?ye.checkedPathsByProjectId[e]??k0:k0),Jt=d0(ye=>ye.reconcileProject),Wt=d0(ye=>ye.setChecked),Vt=d0(ye=>ye.setAllChecked),an=_.useRef(I);_.useEffect(()=>{e&&mn(e,Ne)},[Ne,Xe,e,mn]),_.useEffect(()=>{const ye=Object.fromEntries(t.files.map(zn=>[zn.path,zn.patchDigest]));ue(Ne,zn=>Se.current[zn]===ye[zn]),Se.current=ye},[t.files,Ne,Xe,ue]),_.useEffect(()=>{e&&Jt(e,Ne)},[Ne,Xe,e,Jt]),_.useEffect(()=>{if(!e)return;if(an.current!==I){Pt(e,I?"changes":"history"),an.current=I;return}an.current=I},[I,e,Pt]);const Nn=_.useMemo(()=>t.files.filter(ye=>jt[ye.path]??!0).map(ye=>ye.path),[jt,t.files]),Ue=Nn.length,nn=t.files.length>0&&Ue===t.files.length,_n=Ue>0&&Ue<t.files.length,Le=Yt.trim(),Ze=Le.length>0,Fe=H!==null,ot=$||Fe,Kt=((Yn=t.branchHistory)==null?void 0:Yn.entries)??[],ln=t.behindCount??0,Sn=t.aheadCount??0,rn=t.hasUpstream===!0,At=t.hasUpstream===!1&&!!t.branchName,Lt=t.hasOriginRemote===!0,Zt=t.branchName?t.branchName.split("/").map(ye=>encodeURIComponent(ye)).join("/"):null;let It;At?It="publish":ln>0?It="pull":It="fetch";const re=t.originRepoSlug&&Zt?`https://github.com/${t.originRepoSlug}/compare/${Zt}?expand=1`:null,Me=!!(rn&&re&&t.branchName&&t.branchName!==t.defaultBranchName),pt=t.status==="ready"&&Ue>0&&!ot,Ee=t.status==="ready"&&Ue>0&&Ze&&!ot,Ve=Lt?"commit_and_push":"commit_only",qe=t.branchName??"current branch";async function Qe(ye){if(Ee){G(ye);try{const tt=await T({paths:Nn,summary:Le,description:Mt.trim(),mode:ye});(tt!=null&&tt.ok||tt!=null&&tt.localCommitCreated)&&e&&_t(e)}finally{G(null)}}}async function mt(){if(pt){X(!0);try{const ye=await C({paths:Nn});e&&gn(e,{summary:ye.subject,description:ye.body})}finally{X(!1)}}}function Rt(ye){if(!(!(ye.metaKey||ye.ctrlKey)||ye.key!=="Enter")){if(ye.preventDefault(),Ze){Qe(Ve);return}mt()}}async function bt(ye=It){if(!(t.status!=="ready"||z)){te(!0);try{await M(ye)}finally{te(!1)}}}const Be=_.useCallback(async ye=>{var qr;const{patchesByPath:tt,loadingPatchPaths:zn}=at.getState();if(tt[ye]!==void 0||zn[ye])return tt[ye]??"";de(ye),ne(ye);try{const ce=await j(ye);ie(ye,ce);const Je=(qr=t.files.find(ut=>ut.path===ye))==null?void 0:qr.patchDigest;return Je&&(Se.current={...Se.current,[ye]:Je}),ce}catch(ce){const Je=ce instanceof Error?ce.message:String(ce);throw ae(ye,Je),ce}finally{ee(ye)}},[ne,ee,t.files,j,ae,de,ie]),Ot=_.useCallback(ye=>ye.path,[]),Ln=_.useCallback(({item:ye})=>{const tt=Bt[ye.path]??!0,zn=jt[ye.path]??!0;return u.jsx("div",{className:"pb-1.5",children:u.jsx(_A.Provider,{init:void 0,children:u.jsx(eje,{file:ye,rootRef:Q,projectId:e,isCollapsed:tt,isChecked:zn,editorLabel:n,diffRenderMode:r,wrapLines:i,onToggleCollapsed:()=>{e&&Ge(e,ye.path)},onToggleChecked:()=>{e&&Wt(e,ye.path,!zn)},fileActions:L,patch:K[ye.path],patchError:W[ye.path],isPatchLoading:!!V[ye.path],onLoadPatch:Be})})})},[jt,Bt,r,n,L,Be,V,W,K,e,Wt,Ge,i]);_.useEffect(()=>{var tt,zn;const ye=(zn=(tt=ke.current)==null?void 0:tt.getScrollableNode)==null?void 0:zn.call(tt);Q.current=ye instanceof HTMLElement?ye:null},[St,t.files.length]);let Ht;_n?Ht="Select all files for commit":nn?Ht="Unselect all files from commit":Ht="Select all files for commit";let Gt;t.status==="ready"?Lt?It==="publish"?Gt=u.jsxs(Ie,{variant:"ghost",size:"sm",onClick:()=>void bt(),disabled:z,className:"h-7 gap-1.5 px-2 text-xs hover:!bg-transparent hover:!border-border/0",children:[z?u.jsx(In,{className:"h-3.5 w-3.5 animate-spin"}):u.jsx(q0,{className:"h-3.5 w-3.5"}),u.jsx("span",{children:"Publish Branch"})]}):Gt=u.jsxs("div",{className:"flex items-center gap-1",children:[It==="fetch"?u.jsxs(Js,{delayDuration:0,children:[u.jsx(Zs,{asChild:!0,children:u.jsxs(Ie,{variant:"ghost",size:"sm",onClick:()=>void bt(),disabled:z,className:"h-7 gap-1.5 px-2 text-xs hover:!bg-transparent hover:!border-border/0",children:[z?u.jsx(In,{className:"h-3.5 w-3.5 animate-spin"}):u.jsx(ZM,{className:"h-3.5 w-3.5"}),u.jsx("span",{children:"Fetch"})]})}),u.jsx(js,{children:GMe(t.lastFetchedAt)})]}):u.jsxs(Ie,{variant:"ghost",size:"sm",onClick:()=>void bt(),disabled:z,className:"h-7 gap-1.5 px-2 text-xs hover:!bg-transparent hover:!border-border/0",children:[z?u.jsx(In,{className:"h-3.5 w-3.5 animate-spin"}):u.jsx(qM,{className:"h-3.5 w-3.5"}),u.jsx("span",{children:"Pull"}),u.jsx("span",{className:"inline-flex min-w-4 items-center justify-center rounded-full bg-muted px-1 text-[10px] text-muted-foreground",children:ln})]}),rn&&Sn>0?u.jsxs(Ie,{variant:"default",size:"sm",onClick:()=>void bt("push"),disabled:z,className:"h-7 gap-1.5 px-2 text-xs",children:[z?u.jsx(In,{className:"h-3.5 w-3.5 animate-spin"}):u.jsx(q0,{className:"h-3.5 w-3.5"}),u.jsx("span",{children:"Push"}),u.jsx("span",{className:"inline-flex min-w-4 items-center justify-center rounded-full bg-primary-foreground/15 px-1 text-[10px] text-primary-foreground",children:Sn})]}):null,Me&&re?u.jsxs(Ie,{variant:"ghost",size:"sm",onClick:()=>{typeof window>"u"||window.open(re,"_blank","noopener,noreferrer")},className:"h-7 gap-1.5 px-2 text-xs hover:!bg-transparent hover:!border-border/0",children:[u.jsx(dH,{className:"h-3.5 w-3.5"}),u.jsx("span",{children:"PR"})]}):null]}):Gt=u.jsxs(Ie,{variant:"default",size:"sm",onClick:()=>oe(!0),className:"h-7 gap-1.5 px-3 text-xs",children:[u.jsx(Use,{className:"h-3.5 w-3.5"}),u.jsx("span",{children:"Push to GitHub"})]}):Gt=null;let yr;t.status==="no_repo"?yr=u.jsx("div",{className:"flex h-full items-center justify-center px-6 py-3 text-center",children:u.jsxs("div",{className:"flex max-w-[280px] flex-col items-center gap-3",children:[u.jsx("p",{className:"text-sm text-muted-foreground",children:"Initialize git here to start tracking branches, diffs, and history."}),u.jsx(Ie,{size:"sm",onClick:()=>void k(),children:"Init Git"})]})}):St==="history"?Kt.length===0?yr=u.jsx("div",{className:"flex h-full items-center justify-center px-6 py-3 text-center",children:u.jsxs("p",{className:"text-sm text-muted-foreground",children:["No recent commits on ",t.branchName??"this branch","."]})}):yr=u.jsx("div",{className:"h-full overflow-y-auto [scrollbar-gutter:stable] space-y-1.5 p-1.5",children:Kt.map((ye,tt)=>u.jsx(qMe,{entry:ye,isPendingPush:tt<Sn},ye.sha))}):t.files.length===0?yr=u.jsx("div",{className:"flex h-full items-center justify-center px-6 py-3 text-center",children:u.jsx("p",{className:"text-sm text-muted-foreground",children:"No file changes."})}):yr=null;let Mn;Ze?Fe?Mn=u.jsx(In,{strokeWidth:2.5,className:"size-3 shrink-0 animate-spin"}):Ve==="commit_and_push"&&t.hasUpstream?Mn=u.jsx(q0,{strokeWidth:2.5,className:"size-3 shrink-0"}):Ve==="commit_and_push"?Mn=u.jsx(uH,{strokeWidth:2.5,className:"size-3 shrink-0"}):Mn=u.jsx(ro,{strokeWidth:2.5,className:"size-3 shrink-0"}):$?Mn=u.jsx(In,{strokeWidth:2.5,className:"size-3 shrink-0 animate-spin"}):Mn=u.jsx(koe,{strokeWidth:2.5,className:"size-3 shrink-0"});let qn;return Ze?Fe?qn=H==="commit_only"?"Committing...":"Committing & Pushing...":Ve==="commit_only"?qn=u.jsxs(u.Fragment,{children:["Commit to ",u.jsx(Sc,{strokeWidth:2.5,className:"mr-[4.5px] ml-0.5 inline size-3 "}),qe]}):t.hasUpstream?qn=u.jsxs(u.Fragment,{children:["Commit & push to ",u.jsx(Sc,{strokeWidth:2.5,className:"mr-[4.5px] ml-0.5 inline size-3 "}),qe]}):qn=u.jsxs(u.Fragment,{children:["Commit & publish ",u.jsx(Sc,{strokeWidth:2.5,className:"mr-[4.5px] ml-0.5 inline size-3 "}),qe]}):$?qn="Generating...":qn=u.jsxs(u.Fragment,{children:["Generate message for ",u.jsx(Sc,{strokeWidth:2.5,className:"mr-[4.5px] ml-0.5 inline size-3 "}),qe]}),u.jsx("div",{className:"h-full min-h-0 border-l border-border bg-background md:min-w-[370px]",children:u.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[u.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border pl-2.5 pr-2 py-2",children:[u.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:u.jsx(QMe,{currentBranchName:t.branchName,onListBranches:m,onPreviewMergeBranch:v,onMergeBranch:b,onCheckoutBranch:x,onCreateBranch:S})}),Gt]}),u.jsxs("div",{className:"relative min-h-0 flex-1",children:[u.jsx("div",{className:"sticky top-0 z-30 pl-[14px] pr-[12px] pt-[6px] bg-gradient-to-b from-background to-transparent",children:u.jsx("div",{className:"relative h-[40px] flex min-w-0 items-center justify-center gap-[13px]",children:u.jsxs("div",{className:"flex min-w-0 flex-1 items-center justify-between gap-[13px] relative",children:[St==="changes"?u.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground/70",children:[u.jsx(MJ,{checked:nn,mixed:_n,label:Ht,onClick:()=>{!e||t.files.length===0||Vt(e,Ne,_n?!0:!nn)}}),u.jsxs("span",{children:[Ue," files"]})]}):u.jsx("div",{}),u.jsx("div",{className:"pointer-events-none absolute left-1/2 -translate-x-1/2 top-1/2 -translate-y-1/2",children:u.jsx("div",{className:"pointer-events-auto",children:u.jsx(Ns,{value:St,onValueChange:ye=>{e&&UMe(ye)&&Pt(e,ye)},size:"sm",optionClassName:"flex-1 justify-center",options:[{value:"changes",label:"Changes"},{value:"history",label:"History"}]})})}),St==="changes"?u.jsxs("div",{className:"flex items-center gap-1",children:[u.jsx(ST,{label:"Unified diff",active:r==="unified",onClick:()=>P("unified"),children:u.jsx(Hoe,{className:"h-4 w-4"})}),u.jsx(ST,{label:"Side-by-side diff",active:r==="split",onClick:()=>P("split"),children:u.jsx(Gie,{className:"h-4 w-4"})}),u.jsx(ST,{label:i?"Disable word wrap":"Enable word wrap",active:i,onClick:()=>D(!i),children:u.jsx(xae,{className:"h-4 w-4"})})]}):u.jsx("div",{})]})})}),u.jsxs("div",{className:"h-full min-h-0",children:[yr,t.status!=="no_repo"&&St!=="history"&&t.files.length>0&&u.jsxs("div",{className:"relative h-full min-h-0",children:[u.jsx(rK,{ref:ke,data:t.files,keyExtractor:Ot,renderItem:Ln,extraData:{collapsedPaths:Bt,checkedPaths:jt,patchesByPath:K,patchErrorsByPath:W,loadingPatchPaths:V,diffRenderMode:r,wrapLines:i},estimatedItemSize:44,className:"h-full overflow-y-auto [scrollbar-gutter:stable] p-1.5",contentContainerStyle:{paddingBottom:St==="changes"?220:40}}),St==="changes"?u.jsxs("div",{className:"pointer-events-none absolute inset-x-0 bottom-0 py-1 pb-6 z-30",children:[u.jsx("div",{className:"absolute inset-x-0 bottom-0 top-0 bg-gradient-to-t from-background to-transparent"}),u.jsx("div",{className:"pointer-events-auto relative",children:u.jsxs("div",{className:"space-y-0 rounded-xl mx-auto max-w-[700px]",children:[u.jsx(dn,{value:Yt,onChange:ye=>{e&&gn(e,{summary:ye.target.value,description:Mt})},onKeyDown:Rt,placeholder:"Commit message (override)",className:"rounded-t-xl rounded-b-none px-3",disabled:ot||t.status!=="ready"}),u.jsx(jc,{value:Mt,onChange:ye=>{e&&gn(e,{summary:Yt,description:ye.target.value})},onKeyDown:Rt,placeholder:"Description",rows:5,className:"-mt-px rounded-t-none rounded-b-xl px-3 outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background mb-2",disabled:ot||t.status!=="ready"}),u.jsx("div",{className:"w-full flex flex-row",children:u.jsxs(bh,{children:[u.jsx(xh,{asChild:!0,children:u.jsx(Ie,{type:"button",className:"-mt-px w-full rounded-xl",disabled:Ze?!Ee:!pt,onClick:()=>{if(Ze){Qe(Ve);return}mt()},children:u.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[Mn,u.jsx("span",{className:"min-w-0 truncate text-left",children:qn})]})})}),t.hasUpstream?u.jsx(Id,{children:u.jsx(br,{disabled:!Ze||!Ee,onSelect:ye=>{ye.stopPropagation(),Qe("commit_only")},children:"Commit Only"})}):null]})})]})})]}):null]})]})]}),u.jsx(JMe,{open:F,onOpenChange:oe,onGetGitHubPublishInfo:w,onCheckGitHubRepoAvailability:N,onPublish:A})]})})}const nje=_.memo(tje);function rje(e,t){const n=getComputedStyle(e),r=parseFloat(n.fontSize);return t*r}function ije(e,t){const n=getComputedStyle(e.ownerDocument.body),r=parseFloat(n.fontSize);return t*r}function sje(e){return e/100*window.innerHeight}function oje(e){return e/100*window.innerWidth}function aje(e){switch(typeof e){case"number":return[e,"px"];case"string":{const t=parseFloat(e);return e.endsWith("%")?[t,"%"]:e.endsWith("px")?[t,"px"]:e.endsWith("rem")?[t,"rem"]:e.endsWith("em")?[t,"em"]:e.endsWith("vh")?[t,"vh"]:e.endsWith("vw")?[t,"vw"]:[t,"%"]}}}function Dv({groupSize:e,panelElement:t,styleProp:n}){let r;const[i,s]=aje(n);switch(s){case"%":{r=i/100*e;break}case"px":{r=i;break}case"rem":{r=ije(t,i);break}case"em":{r=rje(t,i);break}case"vh":{r=sje(i);break}case"vw":{r=oje(i);break}}return r}function Xs(e){return parseFloat(e.toFixed(3))}function Bm({group:e}){const{orientation:t,panels:n}=e;return n.reduce((r,i)=>(r+=t==="horizontal"?i.element.offsetWidth:i.element.offsetHeight,r),0)}function PR(e){const{panels:t}=e,n=Bm({group:e});return n===0?t.map(r=>({groupResizeBehavior:r.panelConstraints.groupResizeBehavior,collapsedSize:0,collapsible:r.panelConstraints.collapsible===!0,defaultSize:void 0,disabled:r.panelConstraints.disabled,minSize:0,maxSize:100,panelId:r.id})):t.map(r=>{const{element:i,panelConstraints:s}=r;let o=0;if(s.collapsedSize!==void 0){const h=Dv({groupSize:n,panelElement:i,styleProp:s.collapsedSize});o=Xs(h/n*100)}let a;if(s.defaultSize!==void 0){const h=Dv({groupSize:n,panelElement:i,styleProp:s.defaultSize});a=Xs(h/n*100)}let l=0;if(s.minSize!==void 0){const h=Dv({groupSize:n,panelElement:i,styleProp:s.minSize});l=Xs(h/n*100)}let d=100;if(s.maxSize!==void 0){const h=Dv({groupSize:n,panelElement:i,styleProp:s.maxSize});d=Xs(h/n*100)}return{groupResizeBehavior:s.groupResizeBehavior,collapsedSize:o,collapsible:s.collapsible===!0,defaultSize:a,disabled:s.disabled,minSize:l,maxSize:d,panelId:r.id}})}function ar(e,t="Assertion error"){if(!e)throw Error(t)}function LR(e,t){return Array.from(t).sort(e==="horizontal"?lje:cje)}function lje(e,t){const n=e.element.offsetLeft-t.element.offsetLeft;return n!==0?n:e.element.offsetWidth-t.element.offsetWidth}function cje(e,t){const n=e.element.offsetTop-t.element.offsetTop;return n!==0?n:e.element.offsetHeight-t.element.offsetHeight}function IJ(e){return e!==null&&typeof e=="object"&&"nodeType"in e&&e.nodeType===Node.ELEMENT_NODE}function PJ(e,t){return{x:e.x>=t.left&&e.x<=t.right?0:Math.min(Math.abs(e.x-t.left),Math.abs(e.x-t.right)),y:e.y>=t.top&&e.y<=t.bottom?0:Math.min(Math.abs(e.y-t.top),Math.abs(e.y-t.bottom))}}function uje({orientation:e,rects:t,targetRect:n}){const r={x:n.x+n.width/2,y:n.y+n.height/2};let i,s=Number.MAX_VALUE;for(const o of t){const{x:a,y:l}=PJ(r,o),d=e==="horizontal"?a:l;d<s&&(s=d,i=o)}return ar(i,"No rect found"),i}let E0;function dje(){return E0===void 0&&(typeof matchMedia=="function"?E0=!!matchMedia("(pointer:coarse)").matches:E0=!1),E0}function LJ(e){const{element:t,orientation:n,panels:r,separators:i}=e,s=LR(n,Array.from(t.children).filter(IJ).map(b=>({element:b}))).map(({element:b})=>b),o=[];let a=!1,l=!1,d=-1,h=-1,p=0,m,v=[];{let b=-1;for(const x of s)x.hasAttribute("data-panel")&&(b++,x.ariaDisabled===null&&(p++,d===-1&&(d=b),h=b))}if(p>1){let b=-1;for(const x of s)if(x.hasAttribute("data-panel")){b++;const S=r.find(C=>C.element===x);if(S){if(m){const C=m.element.getBoundingClientRect(),k=x.getBoundingClientRect();let w;if(l){const N=n==="horizontal"?new DOMRect(C.right,C.top,0,C.height):new DOMRect(C.left,C.bottom,C.width,0),A=n==="horizontal"?new DOMRect(k.left,k.top,0,k.height):new DOMRect(k.left,k.top,k.width,0);switch(v.length){case 0:{w=[N,A];break}case 1:{const T=v[0],M=uje({orientation:n,rects:[C,k],targetRect:T.element.getBoundingClientRect()});w=[T,M===C?A:N];break}default:{w=v;break}}}else v.length?w=v:w=[n==="horizontal"?new DOMRect(C.right,k.top,k.left-C.right,k.height):new DOMRect(k.left,C.bottom,k.width,k.top-C.bottom)];for(const N of w){let A="width"in N?N:N.element.getBoundingClientRect();const T=dje()?e.resizeTargetMinimumSize.coarse:e.resizeTargetMinimumSize.fine;if(A.width<T){const j=T-A.width;A=new DOMRect(A.x-j/2,A.y,A.width+j,A.height)}if(A.height<T){const j=T-A.height;A=new DOMRect(A.x,A.y-j/2,A.width,A.height+j)}const M=b<=d||b>h;!a&&!M&&o.push({group:e,groupSize:Bm({group:e}),panels:[m,S],separator:"width"in N?void 0:N,rect:A}),a=!1}}l=!1,m=S,v=[]}}else if(x.hasAttribute("data-separator")){x.ariaDisabled!==null&&(a=!0);const S=i.find(C=>C.element===x);S?v.push(S):(m=void 0,v=[])}else l=!0}return o}var sd,MU;let OJ=(MU=class{constructor(){Iu(this,sd,{})}addListener(t,n){const r=di(this,sd)[t];return r===void 0?di(this,sd)[t]=[n]:r.includes(n)||r.push(n),()=>{this.removeListener(t,n)}}emit(t,n){const r=di(this,sd)[t];if(r!==void 0)if(r.length===1)r[0].call(null,n);else{let i=!1,s=null;const o=Array.from(r);for(let a=0;a<o.length;a++){const l=o[a];try{l.call(null,n)}catch(d){s===null&&(i=!0,s=d)}}if(i)throw s}}removeAllListeners(){zo(this,sd,{})}removeListener(t,n){const r=di(this,sd)[t];if(r!==void 0){const i=r.indexOf(n);i>=0&&r.splice(i,1)}}},sd=new WeakMap,MU),vl=new Map;const DJ=new OJ;function fje(e){vl=new Map(vl),vl.delete(e)}function s6(e,t){for(const[n]of vl)if(n.id===e)return n}function md(e,t){for(const[n,r]of vl)if(n.id===e)return r;if(t)throw Error(`Could not find data for Group with id ${e}`)}function jh(){return vl}function KP(e,t){return DJ.addListener("groupChange",n=>{n.group.id===e&&t(n)})}function qc(e,t){const n=vl.get(e);vl=new Map(vl),vl.set(e,t),DJ.emit("groupChange",{group:e,prev:n,next:t})}function hje(e,t,n){let r,i={x:1/0,y:1/0};for(const s of t){const o=PJ(n,s.rect);switch(e){case"horizontal":{o.x<=i.x&&(r=s,i=o);break}case"vertical":{o.y<=i.y&&(r=s,i=o);break}}}return r?{distance:i,hitRegion:r}:void 0}function pje(e){return e!==null&&typeof e=="object"&&"nodeType"in e&&e.nodeType===Node.DOCUMENT_FRAGMENT_NODE}function mje(e,t){if(e===t)throw new Error("Cannot compare node with itself");const n={a:l6(e),b:l6(t)};let r;for(;n.a.at(-1)===n.b.at(-1);)r=n.a.pop(),n.b.pop();ar(r,"Stacking order can only be calculated for elements with a common ancestor");const i={a:a6(o6(n.a)),b:a6(o6(n.b))};if(i.a===i.b){const s=r.childNodes,o={a:n.a.at(-1),b:n.b.at(-1)};let a=s.length;for(;a--;){const l=s[a];if(l===o.a)return 1;if(l===o.b)return-1}}return Math.sign(i.a-i.b)}const gje=/\b(?:position|zIndex|opacity|transform|webkitTransform|mixBlendMode|filter|webkitFilter|isolation)\b/;function vje(e){const t=getComputedStyle($J(e)??e).display;return t==="flex"||t==="inline-flex"}function bje(e){const t=getComputedStyle(e);return!!(t.position==="fixed"||t.zIndex!=="auto"&&(t.position!=="static"||vje(e))||+t.opacity<1||"transform"in t&&t.transform!=="none"||"webkitTransform"in t&&t.webkitTransform!=="none"||"mixBlendMode"in t&&t.mixBlendMode!=="normal"||"filter"in t&&t.filter!=="none"||"webkitFilter"in t&&t.webkitFilter!=="none"||"isolation"in t&&t.isolation==="isolate"||gje.test(t.willChange)||t.webkitOverflowScrolling==="touch")}function o6(e){let t=e.length;for(;t--;){const n=e[t];if(ar(n,"Missing node"),bje(n))return n}return null}function a6(e){return e&&Number(getComputedStyle(e).zIndex)||0}function l6(e){const t=[];for(;e;)t.push(e),e=$J(e);return t}function $J(e){const{parentNode:t}=e;return pje(t)?t.host:t}function xje(e,t){return e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y}function yje({groupElement:e,hitRegion:t,pointerEventTarget:n}){if(!IJ(n)||n.contains(e)||e.contains(n))return!0;if(mje(n,e)>0){let r=n;for(;r;){if(r.contains(e))return!0;if(xje(r.getBoundingClientRect(),t))return!1;r=r.parentElement}}return!0}function GP(e,t){const n=[];return t.forEach((r,i)=>{if(i.disabled)return;const s=LJ(i),o=hje(i.orientation,s,{x:e.clientX,y:e.clientY});o&&o.distance.x<=0&&o.distance.y<=0&&yje({groupElement:i.element,hitRegion:o.hitRegion.rect,pointerEventTarget:e.target})&&n.push(o.hitRegion)}),n}function _je(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!=t[n])return!1;return!0}function ks(e,t,n=0){return Math.abs(Xs(e)-Xs(t))<=n}function ol(e,t){return ks(e,t)?0:e>t?1:-1}function Hp({overrideDisabledPanels:e,panelConstraints:t,prevSize:n,size:r}){const{collapsedSize:i=0,collapsible:s,disabled:o,maxSize:a=100,minSize:l=0}=t;if(o&&!e)return n;if(ol(r,l)<0)if(s){const d=(i+l)/2;ol(r,d)<0?r=i:r=l}else r=l;return r=Math.min(a,r),r=Xs(r),r}function bx({delta:e,initialLayout:t,panelConstraints:n,pivotIndices:r,prevLayout:i,trigger:s}){if(ks(e,0))return t;const o=s==="imperative-api",a=Object.values(t),l=Object.values(i),d=[...a],[h,p]=r;ar(h!=null,"Invalid first pivot index"),ar(p!=null,"Invalid second pivot index");let m=0;switch(s){case"keyboard":{{const x=e<0?p:h,S=n[x];ar(S,`Panel constraints not found for index ${x}`);const{collapsedSize:C=0,collapsible:k,minSize:w=0}=S;if(k){const N=a[x];if(ar(N!=null,`Previous layout not found for panel index ${x}`),ks(N,C)){const A=w-N;ol(A,Math.abs(e))>0&&(e=e<0?0-A:A)}}}{const x=e<0?h:p,S=n[x];ar(S,`No panel constraints found for index ${x}`);const{collapsedSize:C=0,collapsible:k,minSize:w=0}=S;if(k){const N=a[x];if(ar(N!=null,`Previous layout not found for panel index ${x}`),ks(N,w)){const A=N-C;ol(A,Math.abs(e))>0&&(e=e<0?0-A:A)}}}break}default:{const x=e<0?p:h,S=n[x];ar(S,`Panel constraints not found for index ${x}`);const C=a[x],{collapsible:k,collapsedSize:w,minSize:N}=S;if(k&&ol(C,N)<0)if(e>0){const A=N-w,T=A/2,M=C+e;ol(M,N)<0&&(e=ol(e,T)<=0?0:A)}else{const A=N-w,T=100-A/2,M=C-e;ol(M,N)<0&&(e=ol(100+e,T)>0?0:-A)}break}}{const x=e<0?1:-1;let S=e<0?p:h,C=0;for(;;){const w=a[S];ar(w!=null,`Previous layout not found for panel index ${S}`);const N=Hp({overrideDisabledPanels:o,panelConstraints:n[S],prevSize:w,size:100})-w;if(C+=N,S+=x,S<0||S>=n.length)break}const k=Math.min(Math.abs(e),Math.abs(C));e=e<0?0-k:k}{let x=e<0?h:p;for(;x>=0&&x<n.length;){const S=Math.abs(e)-Math.abs(m),C=a[x];ar(C!=null,`Previous layout not found for panel index ${x}`);const k=C-S,w=Hp({overrideDisabledPanels:o,panelConstraints:n[x],prevSize:C,size:k});if(!ks(C,w)&&(m+=C-w,d[x]=w,m.toFixed(3).localeCompare(Math.abs(e).toFixed(3),void 0,{numeric:!0})>=0))break;e<0?x--:x++}}if(_je(l,d))return i;{const x=e<0?p:h,S=a[x];ar(S!=null,`Previous layout not found for panel index ${x}`);const C=S+m,k=Hp({overrideDisabledPanels:o,panelConstraints:n[x],prevSize:S,size:C});if(d[x]=k,!ks(k,C)){let w=C-k,N=e<0?p:h;for(;N>=0&&N<n.length;){const A=d[N];ar(A!=null,`Previous layout not found for panel index ${N}`);const T=A+w,M=Hp({overrideDisabledPanels:o,panelConstraints:n[N],prevSize:A,size:T});if(ks(A,M)||(w-=M-A,d[N]=M),ks(w,0))break;e>0?N--:N++}}}const v=Object.values(d).reduce((x,S)=>S+x,0);if(!ks(v,100,.1))return i;const b=Object.keys(i);return d.reduce((x,S,C)=>(x[b[C]]=S,x),{})}function ch(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(t[n]===void 0||ol(e[n],t[n])!==0)return!1;return!0}function uh({layout:e,panelConstraints:t}){const n=Object.values(e),r=[...n],i=r.reduce((a,l)=>a+l,0);if(r.length!==t.length)throw Error(`Invalid ${t.length} panel layout: ${r.map(a=>`${a}%`).join(", ")}`);if(!ks(i,100)&&r.length>0)for(let a=0;a<t.length;a++){const l=r[a];ar(l!=null,`No layout data found for index ${a}`);const d=100/i*l;r[a]=d}let s=0;for(let a=0;a<t.length;a++){const l=n[a];ar(l!=null,`No layout data found for index ${a}`);const d=r[a];ar(d!=null,`No layout data found for index ${a}`);const h=Hp({overrideDisabledPanels:!0,panelConstraints:t[a],prevSize:l,size:d});d!=h&&(s+=d-h,r[a]=h)}if(!ks(s,0))for(let a=0;a<t.length;a++){const l=r[a];ar(l!=null,`No layout data found for index ${a}`);const d=l+s,h=Hp({overrideDisabledPanels:!0,panelConstraints:t[a],prevSize:l,size:d});if(l!==h&&(s-=h-l,r[a]=h,ks(s,0)))break}const o=Object.keys(e);return r.reduce((a,l,d)=>(a[o[d]]=l,a),{})}function zJ({groupId:e,panelId:t}){const n=()=>{const a=jh();for(const[l,{defaultLayoutDeferred:d,derivedPanelConstraints:h,layout:p,groupSize:m,separatorToPanels:v}]of a)if(l.id===e)return{defaultLayoutDeferred:d,derivedPanelConstraints:h,group:l,groupSize:m,layout:p,separatorToPanels:v};throw Error(`Group ${e} not found`)},r=()=>{const a=n().derivedPanelConstraints.find(l=>l.panelId===t);if(a!==void 0)return a;throw Error(`Panel constraints not found for Panel ${t}`)},i=()=>{const a=n().group.panels.find(l=>l.id===t);if(a!==void 0)return a;throw Error(`Layout not found for Panel ${t}`)},s=()=>{const a=n().layout[t];if(a!==void 0)return a;throw Error(`Layout not found for Panel ${t}`)},o=a=>{const l=s();if(a===l)return;const{defaultLayoutDeferred:d,derivedPanelConstraints:h,group:p,groupSize:m,layout:v,separatorToPanels:b}=n(),x=p.panels.findIndex(w=>w.id===t),S=x===p.panels.length-1,C=bx({delta:S?l-a:a-l,initialLayout:v,panelConstraints:h,pivotIndices:S?[x-1,x]:[x,x+1],prevLayout:v,trigger:"imperative-api"}),k=uh({layout:C,panelConstraints:h});ch(v,k)||qc(p,{defaultLayoutDeferred:d,derivedPanelConstraints:h,groupSize:m,layout:k,separatorToPanels:b})};return{collapse:()=>{const{collapsible:a,collapsedSize:l}=r(),{mutableValues:d}=i(),h=s();a&&h!==l&&(d.expandToSize=h,o(l))},expand:()=>{const{collapsible:a,collapsedSize:l,minSize:d}=r(),{mutableValues:h}=i(),p=s();if(a&&p===l){let m=h.expandToSize??d;m===0&&(m=1),o(m)}},getSize:()=>{const{group:a}=n(),l=s(),{element:d}=i(),h=a.orientation==="horizontal"?d.offsetWidth:d.offsetHeight;return{asPercentage:l,inPixels:h}},isCollapsed:()=>{const{collapsible:a,collapsedSize:l}=r(),d=s();return a&&ks(l,d)},resize:a=>{const{group:l}=n(),{element:d}=i(),h=Bm({group:l}),p=Dv({groupSize:h,panelElement:d,styleProp:a}),m=Xs(p/h*100);o(m)}}}function c6(e){if(e.defaultPrevented)return;const t=jh();GP(e,t).forEach(n=>{if(n.separator){const r=n.panels.find(i=>i.panelConstraints.defaultSize!==void 0);if(r){const i=r.panelConstraints.defaultSize,s=zJ({groupId:n.group.id,panelId:r.id});s&&i!==void 0&&(s.resize(i),e.preventDefault())}}})}function NS(e){const t=jh();for(const[n]of t)if(n.separators.some(r=>r.element===e))return n;throw Error("Could not find parent Group for separator element")}function BJ({groupId:e}){const t=()=>{const n=jh();for(const[r,i]of n)if(r.id===e)return{group:r,...i};throw Error(`Could not find Group with id "${e}"`)};return{getLayout(){const{defaultLayoutDeferred:n,layout:r}=t();return n?{}:r},setLayout(n){const{defaultLayoutDeferred:r,derivedPanelConstraints:i,group:s,groupSize:o,layout:a,separatorToPanels:l}=t(),d=uh({layout:n,panelConstraints:i});return r?a:(ch(a,d)||qc(s,{defaultLayoutDeferred:r,derivedPanelConstraints:i,groupSize:o,layout:d,separatorToPanels:l}),d)}}}function cf(e,t){const n=NS(e),r=md(n.id,!0),i=n.separators.find(h=>h.element===e);ar(i,"Matching separator not found");const s=r.separatorToPanels.get(i);ar(s,"Matching panels not found");const o=s.map(h=>n.panels.indexOf(h)),a=BJ({groupId:n.id}).getLayout(),l=bx({delta:t,initialLayout:a,panelConstraints:r.derivedPanelConstraints,pivotIndices:o,prevLayout:a,trigger:"keyboard"}),d=uh({layout:l,panelConstraints:r.derivedPanelConstraints});ch(a,d)||qc(n,{defaultLayoutDeferred:r.defaultLayoutDeferred,derivedPanelConstraints:r.derivedPanelConstraints,groupSize:r.groupSize,layout:d,separatorToPanels:r.separatorToPanels})}function u6(e){if(e.defaultPrevented)return;const t=e.currentTarget,n=NS(t);if(!n.disabled)switch(e.key){case"ArrowDown":{e.preventDefault(),n.orientation==="vertical"&&cf(t,5);break}case"ArrowLeft":{e.preventDefault(),n.orientation==="horizontal"&&cf(t,-5);break}case"ArrowRight":{e.preventDefault(),n.orientation==="horizontal"&&cf(t,5);break}case"ArrowUp":{e.preventDefault(),n.orientation==="vertical"&&cf(t,-5);break}case"End":{e.preventDefault(),cf(t,100);break}case"Enter":{e.preventDefault();const r=NS(t),i=md(r.id,!0),{derivedPanelConstraints:s,layout:o,separatorToPanels:a}=i,l=r.separators.find(m=>m.element===t);ar(l,"Matching separator not found");const d=a.get(l);ar(d,"Matching panels not found");const h=d[0],p=s.find(m=>m.panelId===h.id);if(ar(p,"Panel metadata not found"),p.collapsible){const m=o[h.id],v=p.collapsedSize===m?r.mutableState.expandedPanelSizes[h.id]??p.minSize:p.collapsedSize;cf(t,v-m)}break}case"F6":{e.preventDefault();const r=NS(t).separators.map(o=>o.element),i=Array.from(r).findIndex(o=>o===e.currentTarget);ar(i!==null,"Index not found");const s=e.shiftKey?i>0?i-1:r.length-1:i+1<r.length?i+1:0;r[s].focus({preventScroll:!0});break}case"Home":{e.preventDefault(),cf(t,-100);break}}}let hm={cursorFlags:0,state:"inactive"};const qP=new OJ;function dh(){return hm}function Sje(e){return qP.addListener("change",e)}function wje(e){const t=hm,n={...hm};n.cursorFlags=e,hm=n,qP.emit("change",{prev:t,next:n})}function pm(e){const t=hm;hm=e,qP.emit("change",{prev:t,next:e})}function d6(e){if(e.defaultPrevented||e.pointerType==="mouse"&&e.button>0)return;const t=jh(),n=GP(e,t),r=new Map;let i=!1;n.forEach(s=>{s.separator&&(i||(i=!0,s.separator.element.focus({preventScroll:!0})));const o=t.get(s.group);o&&r.set(s.group,o.layout)}),pm({cursorFlags:0,hitRegions:n,initialLayoutMap:r,pointerDownAtPoint:{x:e.clientX,y:e.clientY},state:"active"}),n.length&&e.preventDefault()}const Cje=e=>e,wT=()=>{},FJ=1,UJ=2,HJ=4,WJ=8,f6=3,h6=12;let N0;function p6(){return N0===void 0&&(N0=!1,typeof window<"u"&&(window.navigator.userAgent.includes("Chrome")||window.navigator.userAgent.includes("Firefox"))&&(N0=!0)),N0}function kje({cursorFlags:e,groups:t,state:n}){let r=0,i=0;switch(n){case"active":case"hover":t.forEach(s=>{if(!s.mutableState.disableCursor)switch(s.orientation){case"horizontal":{r++;break}case"vertical":{i++;break}}})}if(!(r===0&&i===0)){switch(n){case"active":{if(e&&p6()){const s=(e&FJ)!==0,o=(e&UJ)!==0,a=(e&HJ)!==0,l=(e&WJ)!==0;if(s)return a?"se-resize":l?"ne-resize":"e-resize";if(o)return a?"sw-resize":l?"nw-resize":"w-resize";if(a)return"s-resize";if(l)return"n-resize"}break}}return p6()?r>0&&i>0?"move":r>0?"ew-resize":"ns-resize":r>0&&i>0?"grab":r>0?"col-resize":"row-resize"}}const m6=new WeakMap;function YP(e){if(e.defaultView===null||e.defaultView===void 0)return;let{prevStyle:t,styleSheet:n}=m6.get(e)??{};n===void 0&&(n=new e.defaultView.CSSStyleSheet,e.adoptedStyleSheets&&e.adoptedStyleSheets.push(n));const r=dh();switch(r.state){case"active":case"hover":{const i=kje({cursorFlags:r.cursorFlags,groups:r.hitRegions.map(o=>o.group),state:r.state}),s=`*, *:hover {cursor: ${i} !important; }`;if(t===s)return;t=s,i?n.cssRules.length===0?n.insertRule(s):n.replaceSync(s):n.cssRules.length===1&&n.deleteRule(0);break}case"inactive":{t=void 0,n.cssRules.length===1&&n.deleteRule(0);break}}m6.set(e,{prevStyle:t,styleSheet:n})}function VJ({document:e,event:t,hitRegions:n,initialLayoutMap:r,mountedGroups:i,pointerDownAtPoint:s,prevCursorFlags:o}){let a=0;n.forEach(d=>{const{group:h,groupSize:p}=d,{orientation:m,panels:v}=h,{disableCursor:b}=h.mutableState;let x=0;s?m==="horizontal"?x=(t.clientX-s.x)/p*100:x=(t.clientY-s.y)/p*100:m==="horizontal"?x=t.clientX<0?-100:100:x=t.clientY<0?-100:100;const S=r.get(h),C=i.get(h);if(!S||!C)return;const{defaultLayoutDeferred:k,derivedPanelConstraints:w,groupSize:N,layout:A,separatorToPanels:T}=C;if(w&&A&&T){const M=bx({delta:x,initialLayout:S,panelConstraints:w,pivotIndices:d.panels.map(j=>v.indexOf(j)),prevLayout:A,trigger:"mouse-or-touch"});if(ch(M,A)){if(x!==0&&!b)switch(m){case"horizontal":{a|=x<0?FJ:UJ;break}case"vertical":{a|=x<0?HJ:WJ;break}}}else qc(d.group,{defaultLayoutDeferred:k,derivedPanelConstraints:w,groupSize:N,layout:M,separatorToPanels:T})}});let l=0;t.movementX===0?l|=o&f6:l|=a&f6,t.movementY===0?l|=o&h6:l|=a&h6,wje(l),YP(e)}function g6(e){const t=jh(),n=dh();switch(n.state){case"active":VJ({document:e.currentTarget,event:e,hitRegions:n.hitRegions,initialLayoutMap:n.initialLayoutMap,mountedGroups:t,prevCursorFlags:n.cursorFlags})}}function v6(e){if(e.defaultPrevented)return;const t=dh(),n=jh();switch(t.state){case"active":{if(e.buttons===0){pm({cursorFlags:0,state:"inactive"}),t.hitRegions.forEach(r=>{const i=md(r.group.id,!0);qc(r.group,i)});return}VJ({document:e.currentTarget,event:e,hitRegions:t.hitRegions,initialLayoutMap:t.initialLayoutMap,mountedGroups:n,pointerDownAtPoint:t.pointerDownAtPoint,prevCursorFlags:t.cursorFlags});break}default:{const r=GP(e,n);r.length===0?t.state!=="inactive"&&pm({cursorFlags:0,state:"inactive"}):pm({cursorFlags:0,hitRegions:r,state:"hover"}),YP(e.currentTarget);break}}}function b6(e){if(e.relatedTarget instanceof HTMLIFrameElement)switch(dh().state){case"hover":pm({cursorFlags:0,state:"inactive"})}}function x6(e){if(e.defaultPrevented||e.pointerType==="mouse"&&e.button>0)return;const t=dh();switch(t.state){case"active":pm({cursorFlags:0,state:"inactive"}),t.hitRegions.length>0&&(YP(e.currentTarget),t.hitRegions.forEach(n=>{const r=md(n.group.id,!0);qc(n.group,r)}),e.preventDefault())}}function y6(e){let t=0,n=0;const r={};for(const s of e)if(s.defaultSize!==void 0){t++;const o=Xs(s.defaultSize);n+=o,r[s.panelId]=o}else r[s.panelId]=void 0;const i=e.length-t;if(i!==0){const s=Xs((100-n)/i);for(const o of e)o.defaultSize===void 0&&(r[o.panelId]=s)}return r}function Eje(e,t,n){if(!n[0])return;const r=e.panels.find(l=>l.element===t);if(!r||!r.onResize)return;const i=Bm({group:e}),s=e.orientation==="horizontal"?r.element.offsetWidth:r.element.offsetHeight,o=r.mutableValues.prevSize,a={asPercentage:Xs(s/i*100),inPixels:s};r.mutableValues.prevSize=a,r.onResize(a,r.id,o)}function Nje(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}function Tje({group:e,nextGroupSize:t,prevGroupSize:n,prevLayout:r}){if(n<=0||t<=0||n===t)return r;let i=0,s=0,o=!1;const a=new Map,l=[];for(const p of e.panels){const m=r[p.id]??0;switch(p.panelConstraints.groupResizeBehavior){case"preserve-pixel-size":{o=!0;const v=m/100*n,b=Xs(v/t*100);a.set(p.id,b),i+=b;break}case"preserve-relative-size":default:{l.push(p.id),s+=m;break}}}if(!o||l.length===0)return r;const d=100-i,h={...r};if(a.forEach((p,m)=>{h[m]=p}),s>0)for(const p of l){const m=r[p]??0;h[p]=Xs(m/s*d)}else{const p=Xs(d/l.length);for(const m of l)h[m]=p}return h}function Aje(e,t){const n=e.map(i=>i.id),r=Object.keys(t);if(n.length!==r.length)return!1;for(const i of n)if(!r.includes(i))return!1;return!0}const kp=new Map;function Rje(e){let t=!0;ar(e.element.ownerDocument.defaultView,"Cannot register an unmounted Group");const n=e.element.ownerDocument.defaultView.ResizeObserver,r=new Set,i=new Set,s=new n(b=>{for(const x of b){const{borderBoxSize:S,target:C}=x;if(C===e.element){if(t){const k=Bm({group:e});if(k===0)return;const w=md(e.id);if(!w)return;const N=PR(e),A=w.defaultLayoutDeferred?y6(N):w.layout,T=Tje({group:e,nextGroupSize:k,prevGroupSize:w.groupSize,prevLayout:A}),M=uh({layout:T,panelConstraints:N});if(!w.defaultLayoutDeferred&&ch(w.layout,M)&&Nje(w.derivedPanelConstraints,N)&&w.groupSize===k)return;qc(e,{defaultLayoutDeferred:!1,derivedPanelConstraints:N,groupSize:k,layout:M,separatorToPanels:w.separatorToPanels})}}else Eje(e,C,S)}});s.observe(e.element),e.panels.forEach(b=>{ar(!r.has(b.id),`Panel ids must be unique; id "${b.id}" was used more than once`),r.add(b.id),b.onResize&&s.observe(b.element)});const o=Bm({group:e}),a=PR(e),l=e.panels.map(({id:b})=>b).join(",");let d=e.mutableState.defaultLayout;d&&(Aje(e.panels,d)||(d=void 0));const h=e.mutableState.layouts[l]??d??y6(a),p=uh({layout:h,panelConstraints:a}),m=e.element.ownerDocument;kp.set(m,(kp.get(m)??0)+1);const v=new Map;return LJ(e).forEach(b=>{b.separator&&v.set(b.separator,b.panels)}),qc(e,{defaultLayoutDeferred:o===0,derivedPanelConstraints:a,groupSize:o,layout:p,separatorToPanels:v}),e.separators.forEach(b=>{ar(!i.has(b.id),`Separator ids must be unique; id "${b.id}" was used more than once`),i.add(b.id),b.element.addEventListener("keydown",u6)}),kp.get(m)===1&&(m.addEventListener("dblclick",c6,!0),m.addEventListener("pointerdown",d6,!0),m.addEventListener("pointerleave",g6),m.addEventListener("pointermove",v6),m.addEventListener("pointerout",b6),m.addEventListener("pointerup",x6,!0)),function(){t=!1,kp.set(m,Math.max(0,(kp.get(m)??0)-1)),fje(e),e.separators.forEach(b=>{b.element.removeEventListener("keydown",u6)}),kp.get(m)||(m.removeEventListener("dblclick",c6,!0),m.removeEventListener("pointerdown",d6,!0),m.removeEventListener("pointerleave",g6),m.removeEventListener("pointermove",v6),m.removeEventListener("pointerout",b6),m.removeEventListener("pointerup",x6,!0)),s.disconnect()}}function Mje(){const[e,t]=_.useState({}),n=_.useCallback(()=>t({}),[]);return[e,n]}function XP(e){const t=_.useId();return`${e??t}`}const Ih=typeof window<"u"?_.useLayoutEffect:_.useEffect;function fb(e){const t=_.useRef(e);return Ih(()=>{t.current=e},[e]),_.useCallback((...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[t])}function JP(...e){return fb(t=>{e.forEach(n=>{if(n)switch(typeof n){case"function":{n(t);break}case"object":{n.current=t;break}}})})}function ZP(e){const t=_.useRef({...e});return Ih(()=>{for(const n in e)t.current[n]=e[n]},[e]),t.current}const KJ=_.createContext(null);function jje(e,t){const n=_.useRef({getLayout:()=>({}),setLayout:Cje});_.useImperativeHandle(t,()=>n.current,[]),Ih(()=>{Object.assign(n.current,BJ({groupId:e}))})}function GJ({children:e,className:t,defaultLayout:n,disableCursor:r,disabled:i,elementRef:s,groupRef:o,id:a,onLayoutChange:l,onLayoutChanged:d,orientation:h="horizontal",resizeTargetMinimumSize:p={coarse:20,fine:10},style:m,...v}){const b=_.useRef({onLayoutChange:{},onLayoutChanged:{}}),x=fb(L=>{ch(b.current.onLayoutChange,L)||(b.current.onLayoutChange=L,l==null||l(L))}),S=fb(L=>{ch(b.current.onLayoutChanged,L)||(b.current.onLayoutChanged=L,d==null||d(L))}),C=XP(a),k=_.useRef(null),[w,N]=Mje(),A=_.useRef({lastExpandedPanelSizes:{},layouts:{},panels:[],resizeTargetMinimumSize:p,separators:[]}),T=JP(k,s);jje(C,o);const M=fb((L,I)=>{const $=dh(),H=s6(L),z=md(L);if(z){let F=!1;switch($.state){case"active":{F=$.hitRegions.some(K=>K.group===H);break}}return{flexGrow:z.layout[I]??1,pointerEvents:F?"none":void 0}}return{flexGrow:(n==null?void 0:n[I])??1}}),j=ZP({defaultLayout:n,disableCursor:r}),P=_.useMemo(()=>({get disableCursor(){return!!j.disableCursor},getPanelStyles:M,id:C,orientation:h,registerPanel:L=>{const I=A.current;return I.panels=LR(h,[...I.panels,L]),N(),()=>{I.panels=I.panels.filter($=>$!==L),N()}},registerSeparator:L=>{const I=A.current;return I.separators=LR(h,[...I.separators,L]),N(),()=>{I.separators=I.separators.filter($=>$!==L),N()}},togglePanelDisabled:(L,I)=>{const $=A.current.panels.find(F=>F.id===L);$&&($.panelConstraints.disabled=I);const H=s6(C),z=md(C);H&&z&&qc(H,{...z,derivedPanelConstraints:PR(H)})},toggleSeparatorDisabled:(L,I)=>{const $=A.current.separators.find(H=>H.id===L);$&&($.disabled=I)}}),[M,C,N,h,j]),D=_.useRef(null);return Ih(()=>{const L=k.current;if(L===null)return;const I=A.current;let $;if(j.defaultLayout!==void 0&&Object.keys(j.defaultLayout).length===I.panels.length){$={};for(const X of I.panels){const G=j.defaultLayout[X.id];G!==void 0&&($[X.id]=G)}}const H={disabled:!!i,element:L,id:C,mutableState:{defaultLayout:$,disableCursor:!!j.disableCursor,expandedPanelSizes:A.current.lastExpandedPanelSizes,layouts:A.current.layouts},orientation:h,panels:I.panels,resizeTargetMinimumSize:I.resizeTargetMinimumSize,separators:I.separators};D.current=H;const z=Rje(H),{defaultLayoutDeferred:F,derivedPanelConstraints:K,layout:W}=md(H.id,!0);!F&&K.length>0&&(x(W),S(W));const V=KP(C,X=>{const{defaultLayoutDeferred:G,derivedPanelConstraints:te,layout:oe}=X.next;if(G||te.length===0)return;const ue=H.panels.map(({id:ee})=>ee).join(",");H.mutableState.layouts[ue]=oe,te.forEach(ee=>{if(ee.collapsible){const{layout:ne}=X.prev??{};if(ne){const ie=ks(ee.collapsedSize,oe[ee.panelId]),ae=ks(ee.collapsedSize,ne[ee.panelId]);ie&&!ae&&(H.mutableState.expandedPanelSizes[ee.panelId]=ne[ee.panelId])}}});const de=dh().state!=="active";x(oe),de&&S(oe)});return()=>{D.current=null,z(),V()}},[i,C,S,x,h,w,j]),_.useEffect(()=>{const L=D.current;L&&(L.mutableState.defaultLayout=n,L.mutableState.disableCursor=!!r)}),u.jsx(KJ.Provider,{value:P,children:u.jsx("div",{...v,className:t,"data-group":!0,"data-testid":C,id:C,ref:T,style:{height:"100%",width:"100%",overflow:"hidden",...m,display:"flex",flexDirection:h==="horizontal"?"row":"column",flexWrap:"nowrap",touchAction:h==="horizontal"?"pan-y":"pan-x"},children:e})})}GJ.displayName="Group";function QP(){const e=_.useContext(KJ);return ar(e,"Group Context not found; did you render a Panel or Separator outside of a Group?"),e}function Ije(e,t){const{id:n}=QP(),r=_.useRef({collapse:wT,expand:wT,getSize:()=>({asPercentage:0,inPixels:0}),isCollapsed:()=>!1,resize:wT});_.useImperativeHandle(t,()=>r.current,[]),Ih(()=>{Object.assign(r.current,zJ({groupId:n,panelId:e}))})}function qJ({children:e,className:t,collapsedSize:n="0%",collapsible:r=!1,defaultSize:i,disabled:s,elementRef:o,groupResizeBehavior:a="preserve-relative-size",id:l,maxSize:d="100%",minSize:h="0%",onResize:p,panelRef:m,style:v,...b}){const x=!!l,S=XP(l),C=ZP({disabled:s}),k=_.useRef(null),w=JP(k,o),{getPanelStyles:N,id:A,orientation:T,registerPanel:M,togglePanelDisabled:j}=QP(),P=p!==null,D=fb((I,$,H)=>{p==null||p(I,l,H)});Ih(()=>{const I=k.current;if(I!==null){const $={element:I,id:S,idIsStable:x,mutableValues:{expandToSize:void 0,prevSize:void 0},onResize:P?D:void 0,panelConstraints:{groupResizeBehavior:a,collapsedSize:n,collapsible:r,defaultSize:i,disabled:C.disabled,maxSize:d,minSize:h}};return M($)}},[a,n,r,i,P,S,x,d,h,D,M,C]),_.useEffect(()=>{j(S,!!s)},[s,S,j]),Ije(S,m);const L=_.useSyncExternalStore(I=>KP(A,I),()=>JSON.stringify(N(A,S)),()=>JSON.stringify(N(A,S)));return u.jsx("div",{...b,"aria-disabled":s||void 0,"data-panel":!0,"data-testid":S,id:S,ref:w,style:{...Pje,display:"flex",flexBasis:0,flexShrink:1,overflow:"visible",...JSON.parse(L)},children:u.jsx("div",{className:t,style:{maxHeight:"100%",maxWidth:"100%",flexGrow:1,overflow:"auto",...v,touchAction:T==="horizontal"?"pan-y":"pan-x"},children:e})})}qJ.displayName="Panel";const Pje={minHeight:0,maxHeight:"100%",height:"auto",minWidth:0,maxWidth:"100%",width:"auto",border:"none",borderWidth:0,padding:0,margin:0};function Lje({layout:e,panelConstraints:t,panelId:n,panelIndex:r}){let i,s;const o=e[n],a=t.find(l=>l.panelId===n);if(a){const l=a.maxSize,d=a.collapsible?a.collapsedSize:a.minSize,h=[r,r+1];s=uh({layout:bx({delta:d-o,initialLayout:e,panelConstraints:t,pivotIndices:h,prevLayout:e}),panelConstraints:t})[n],i=uh({layout:bx({delta:l-o,initialLayout:e,panelConstraints:t,pivotIndices:h,prevLayout:e}),panelConstraints:t})[n]}return{valueControls:n,valueMax:i,valueMin:s,valueNow:o}}function YJ({children:e,className:t,disabled:n,elementRef:r,id:i,style:s,...o}){const a=XP(i),l=ZP({disabled:n}),[d,h]=_.useState({}),[p,m]=_.useState("inactive"),v=_.useRef(null),b=JP(v,r),{disableCursor:x,id:S,orientation:C,registerSeparator:k,toggleSeparatorDisabled:w}=QP(),N=C==="horizontal"?"vertical":"horizontal";Ih(()=>{const T=v.current;if(T!==null){const M={disabled:l.disabled,element:T,id:a},j=k(M),P=Sje(L=>{m(L.next.state!=="inactive"&&L.next.hitRegions.some(I=>I.separator===M)?L.next.state:"inactive")}),D=KP(S,L=>{const{derivedPanelConstraints:I,layout:$,separatorToPanels:H}=L.next,z=H.get(M);if(z){const F=z[0],K=z.indexOf(F);h(Lje({layout:$,panelConstraints:I,panelId:F.id,panelIndex:K}))}});return()=>{P(),D(),j()}}},[S,a,k,l]),_.useEffect(()=>{w(a,!!n)},[n,a,w]);let A;return n&&!x&&(A="not-allowed"),u.jsx("div",{...o,"aria-controls":d.valueControls,"aria-disabled":n||void 0,"aria-orientation":N,"aria-valuemax":d.valueMax,"aria-valuemin":d.valueMin,"aria-valuenow":d.valueNow,children:e,className:t,"data-separator":n?"disabled":p,"data-testid":a,id:a,ref:b,role:"separator",style:{flexBasis:"auto",cursor:A,...s,flexGrow:0,flexShrink:0,touchAction:"none"},tabIndex:n?void 0:0})}YJ.displayName="Separator";const eL=({className:e,...t})=>u.jsx(GJ,{className:he("flex h-full w-full",e),...t}),xx=e=>u.jsx(qJ,{...e}),tL=({withHandle:e,orientation:t,disabled:n,className:r,...i})=>u.jsx(YJ,{disabled:n,className:he("relative flex items-center justify-center bg-transparent focus-visible:outline-none",t==="vertical"?"h-2 w-full -my-1 cursor-row-resize":"h-full w-2 -mx-1 cursor-col-resize",e&&(t==="vertical"?"before:absolute before:inset-x-0 before:top-1/2 before:h-0.5 before:-translate-y-1/2 before:bg-border":"before:absolute before:inset-y-0 before:left-1/2 before:w-px before:-translate-x-1/2 before:bg-border"),r),...i,children:u.jsx("span",{className:"sr-only",children:t==="vertical"?"Resize rows":"Resize columns"})});function XJ(e,t,n){const r=typeof e.maxTokens=="number"&&Number.isFinite(e.maxTokens)?e.maxTokens:null,i=r&&r>0?Math.min(100,e.usedTokens/r*100):null,s=r!==null?Math.max(0,Math.round(r-e.usedTokens)):null,o=i!==null?Math.max(0,100-i):null;return{...e,compactsAutomatically:e.compactsAutomatically||n,maxTokens:r??void 0,remainingTokens:s,usedPercentage:i,remainingPercentage:o,updatedAt:t}}function Oje(e){const t=e.some(n=>n.kind==="compact_boundary"||n.kind==="compact_summary"||n.kind==="context_cleared");for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r&&!(r.kind!=="context_window_updated"||r.usage.usedTokens<=0))return XJ(r.usage,new Date(r.createdAt).toISOString(),t)}return null}function Dje(e,t){return!e||t===null||!Number.isFinite(t)||t<=0?e:XJ({...e,maxTokens:t},e.updatedAt,e.compactsAutomatically)}function Du(e){return e===void 0||!Number.isFinite(e)||e<0?0:e}function $je(e,t){let n=0,r=0,i=0,s=0;for(const a of e){if(a.kind!=="result")continue;const l=a.usage;l&&(n+=Du(l.inputTokens),r+=Du(l.outputTokens),i+=Du(l.cachedInputTokens)),s+=Du(a.costUsd??(l==null?void 0:l.costUsd))}for(const a of t){const l=a.usage;l&&(n+=Du(l.inputTokens),r+=Du(l.outputTokens),i+=Du(l.cachedInputTokens),s+=Du(l.costUsd))}if(n===0&&r===0&&i===0&&s===0)return null;const o=n>0?i/n*100:null;return{inputTokens:n,outputTokens:r,cachedTokens:i,costUsd:s,cacheHitPercentage:o}}function zje(e){return!Number.isFinite(e)||e<=0?"$0.00":e<.01?"<$0.01":`$${e.toFixed(2)}`}function qs(e){return e==null||!Number.isFinite(e)?"0":e<1e3?`${Math.round(e)}`:e<1e4?`${(e/1e3).toFixed(1).replace(/\.0$/,"")}k`:e<1e6?`${Math.round(e/1e3)}k`:`${(e/1e6).toFixed(1).replace(/\.0$/,"")}m`}const Bje=typeof window>"u"?0:window.innerWidth,Vn=dr()(e=>({typedEmptyStateText:"",isEmptyStateTypingComplete:!1,setTypedEmptyStateText:t=>e({typedEmptyStateText:t}),setIsEmptyStateTypingComplete:t=>e({isEmptyStateTypingComplete:t}),resetEmptyStateTyping:()=>e({typedEmptyStateText:"",isEmptyStateTypingComplete:!1}),isPageFileDragActive:!1,setIsPageFileDragActive:t=>e({isPageFileDragActive:t}),layoutWidth:0,setLayoutWidth:t=>e({layoutWidth:t}),inputHeight:148,setInputHeight:t=>e({inputHeight:t}),viewportWidth:Bje,setViewportWidth:t=>e({viewportWidth:t}),fixedTerminalHeight:0,setFixedTerminalHeight:t=>e({fixedTerminalHeight:t}),showScrollToBottom:!1,setShowScrollToBottom:t=>e({showScrollToBottom:t}),toolGroupExpanded:{},setToolGroupExpanded:t=>e(n=>({toolGroupExpanded:t(n.toolGroupExpanded)})),resetToolGroupExpanded:()=>e({toolGroupExpanded:{}}),localLinkMenuTarget:null,setLocalLinkMenuTarget:t=>e({localLinkMenuTarget:t}),diffRenderMode:"unified",wrapDiffLines:!1,setDiffRenderMode:t=>e({diffRenderMode:t}),setWrapDiffLines:t=>e({wrapDiffLines:t}),terminalFocusRequestVersion:0,incrementTerminalFocusRequestVersion:()=>e(t=>({terminalFocusRequestVersion:t.terminalFocusRequestVersion+1}))})),nL=[68,32];function Fje(){return{isVisible:!1,mainSizes:[...nL],terminals:[],nextTerminalIndex:0}}function Uje(e,t){return e[t]??Fje()}function CT(e){if(e.length===0)return[];const t=e.reduce((n,r)=>n+Math.max(r,0),0);return!Number.isFinite(t)||t<=0?Array.from({length:e.length},()=>100/e.length):e.map(n=>Math.max(n,0)/t*100)}function Hje(e){let t=e,n="";do n=String.fromCharCode(65+t%26)+n,t=Math.floor(t/26)-1;while(t>=0);return`Terminal ${n}`}function Wje(e){if(e.length===0)return e;const t=e.length+1;return e.map(n=>({...n,size:n.size*e.length/t}))}function Ep(e,t,n){return{...e,[t]:n(Uje(e,t))}}const Ku=dr()(og(e=>({projects:{},addTerminal:(t,n)=>e(r=>({projects:Ep(r.projects,t,i=>{var l,d;const s=Wje(i.terminals),o={id:((d=(l=globalThis.crypto)==null?void 0:l.randomUUID)==null?void 0:d.call(l))??`terminal-${Date.now()}-${i.nextTerminalIndex}`,title:Hje(i.nextTerminalIndex),size:100/(s.length+1)},a=n?Math.max(s.findIndex(h=>h.id===n)+1,0):s.length;return{...i,isVisible:!0,nextTerminalIndex:i.nextTerminalIndex+1,terminals:[...s.slice(0,a),o,...s.slice(a)]}})})),removeTerminal:(t,n)=>e(r=>({projects:Ep(r.projects,t,i=>{const s=i.terminals.filter(a=>a.id!==n);if(s.length===0)return{...i,isVisible:!1,terminals:[]};const o=CT(s.map(a=>a.size));return{...i,terminals:s.map((a,l)=>({...a,size:o[l]??100/s.length}))}})})),toggleVisibility:t=>e(n=>({projects:Ep(n.projects,t,r=>({...r,isVisible:r.terminals.length>0?!r.isVisible:!1}))})),resetMainSizes:t=>e(n=>({projects:Ep(n.projects,t,r=>({...r,mainSizes:[...nL]}))})),setMainSizes:(t,n)=>e(r=>{if(n.length!==2)return r;const[i=50,s=50]=CT(n),o=[i,s];return{projects:Ep(r.projects,t,a=>({...a,mainSizes:o}))}}),setTerminalSizes:(t,n)=>e(r=>({projects:Ep(r.projects,t,i=>{if(n.length!==i.terminals.length)return i;const s=CT(n);return{...i,terminals:i.terminals.map((o,a)=>({...o,size:s[a]??o.size}))}})})),clearProject:t=>e(n=>{const{[t]:r,...i}=n.projects;return{projects:i}})}),{name:"terminal-layouts",version:1})),Vje={isVisible:!1,mainSizes:[...nL],terminals:[],nextTerminalIndex:0},Kje=35;function Gje(e,t){return!Number.isFinite(e)||e<=0||!Number.isFinite(t)||t<=0?0:e*(t/100)}function qje(e,t){const n=Gje(e,t);return n>=0&&n<Kje}const R1=350,Yje=[.4,0,.2,1],Xje=8,_6=1e-6;function Jje(e,t,n){const r=1-e;return 3*r*r*e*t+3*r*e*e*n+e*e*e}function Zje(e,t,n){const r=1-e;return 3*r*r*e*t+3*r*e*e*n+e*e*e}function Qje(e,t,n){const r=1-e;return 3*r*r*t+6*r*e*(n-t)+3*e*e*(1-n)}function eIe(e,t,n){let r=e;for(let i=0;i<Xje;i+=1){const s=Jje(r,t,n)-e;if(Math.abs(s)<_6)return r;const o=Qje(r,t,n);if(Math.abs(o)<_6)break;r-=s/o}return r}function tIe(e){if(e<=0)return 0;if(e>=1)return 1;const[t,n,r,i]=Yje,s=eIe(e,t,r);return Zje(s,n,i)}function JJ(e,t,n){const r=tIe(n);return[e[0]+(t[0]-e[0])*r,e[1]+(t[1]-e[1])*r]}function nIe({projectId:e,shouldRenderRightSidebarLayout:t,showRightSidebar:n,rightSidebarSize:r}){const i=_.useRef(null),s=_.useRef(null),o=_.useRef(null),a=_.useRef(null),l=_.useRef(null),d=_.useRef(!1),h=_.useRef(null),p=_.useRef(!1),m=_.useRef(!1);return _.useEffect(()=>()=>{a.current!==null&&window.cancelAnimationFrame(a.current),l.current!==null&&window.clearTimeout(l.current)},[]),_.useLayoutEffect(()=>{var M,j,P,D,L,I;if(!t){a.current!==null&&(window.cancelAnimationFrame(a.current),a.current=null),l.current!==null&&(window.clearTimeout(l.current),l.current=null),d.current=!1;return}const v=i.current;if(!v)return;a.current!==null&&(window.cancelAnimationFrame(a.current),a.current=null),l.current!==null&&(window.clearTimeout(l.current),l.current=null);const b=h.current,x=b!==null&&b!==e,S=n&&!m.current,C=!p.current,k=n?[100-r,r]:[100,0],w=x||C&&n,N=S||C?[100,0]:[v.getLayout().workspace??k[0],v.getLayout().rightSidebar??k[1]];if(h.current=e,p.current=t,m.current=n,w||Math.abs(N[0]-k[0])<.1&&Math.abs(N[1]-k[1])<.1){v.setLayout({workspace:k[0],rightSidebar:k[1]}),(M=s.current)==null||M.setAttribute("data-right-sidebar-open",n?"true":"false"),(j=o.current)==null||j.setAttribute("data-right-sidebar-open",n?"true":"false"),(P=o.current)==null||P.setAttribute("data-right-sidebar-animated","false");return}d.current=!0,(D=s.current)==null||D.setAttribute("data-right-sidebar-open",n?"true":"false"),(L=o.current)==null||L.setAttribute("data-right-sidebar-open",n?"true":"false"),(I=o.current)==null||I.setAttribute("data-right-sidebar-animated","true"),v.setLayout({workspace:N[0],rightSidebar:N[1]});const A=performance.now(),T=$=>{const H=Math.min(1,($-A)/R1),z=JJ(N,k,H);if(v.setLayout({workspace:z[0],rightSidebar:z[1]}),H<1){a.current=window.requestAnimationFrame(T);return}v.setLayout({workspace:k[0],rightSidebar:k[1]}),a.current=null,l.current=window.setTimeout(()=>{d.current=!1,l.current=null},0)};a.current=window.requestAnimationFrame(T)},[e,r,t,n]),_.useEffect(()=>{t||(p.current=!1,m.current=!1)},[t]),{isAnimating:d,panelGroupRef:i,sidebarPanelRef:s,sidebarVisualRef:o}}function rIe(e){return e.visibilityState==="visible"?e.activeChatId:null}function iIe(e){e.socket.setFocusedChat(rIe({activeChatId:e.activeChatId,visibilityState:e.visibilityState}))}function sIe({socket:e,activeChatId:t}){_.useEffect(()=>{if(typeof document>"u")return;const n=()=>{iIe({socket:e,activeChatId:t,visibilityState:document.visibilityState})};return n(),document.addEventListener("visibilitychange",n),window.addEventListener("pagehide",n),window.addEventListener("pageshow",n),()=>{document.removeEventListener("visibilitychange",n),window.removeEventListener("pagehide",n),window.removeEventListener("pageshow",n),e.setFocusedChat(null)}},[e,t])}function oIe({rootRef:e,fallbackRef:t,enabled:n,canCancel:r}){_.useEffect(()=>{if(!n)return;let i=0,s=null;const o=p=>{const m=p instanceof Element?p:null,v=e.current,b=t.current;if(t$({trigger:"pointer",activeElement:document.activeElement,pointerStartTarget:s,pointerEndTarget:m,root:v,fallback:b,hasActiveOverlay:e$(document),hasActiveSelection:tue(window.getSelection())})!=="restore"){s=null;return}b==null||b.focus({preventScroll:!0}),s=null},a=p=>{cancelAnimationFrame(i),s=p.target instanceof Element?p.target:null},l=p=>{cancelAnimationFrame(i),i=window.requestAnimationFrame(()=>{o(p.target)})},d=()=>{s=null;const p=t.current;!p||p.disabled||p.focus({preventScroll:!0})},h=p=>{if(p.key!=="Escape")return;const m=t.current;t$({trigger:"escape",activeElement:document.activeElement,fallback:m,hasActiveOverlay:e$(document),canCancel:r,defaultPrevented:p.defaultPrevented})==="escape-focus"&&(p.preventDefault(),m==null||m.focus({preventScroll:!0}))};return window.addEventListener("pointerdown",a,!0),window.addEventListener("pointerup",l,!0),window.addEventListener("keydown",h,!0),window.addEventListener(FS,d),()=>{cancelAnimationFrame(i),window.removeEventListener("pointerdown",a,!0),window.removeEventListener("pointerup",l,!0),window.removeEventListener("keydown",h,!0),window.removeEventListener(FS,d)}},[r,n,t,e])}function aIe(e){const t=e.previousProjectId!==null&&e.previousProjectId!==e.projectId,n=e.previousProjectId===null&&e.projectId!==null;return!t&&!n&&e.showTerminalPane&&!e.wasTerminalVisible}function lIe({previousProjectId:e,projectId:t,previousShouldRenderTerminalLayout:n,previousShowTerminalPane:r,showTerminalPane:i,terminalLayout:s,liveLayout:o}){const a=e!==null&&e!==t,l=i&&!r,d=!n,h=e===null&&t!==null,p=i?s.mainSizes:[100,0];return{currentLayout:l||d?[100,0]:o,shouldSkipAnimation:a||h&&d,targetLayout:p}}function cIe({chatInputRef:e,projectId:t,shouldRenderTerminalLayout:n,showTerminalPane:r,terminalLayout:i}){const s=_.useRef(null),o=_.useRef(null),a=_.useRef(null),l=_.useRef(null),d=_.useRef(null),h=_.useRef(!1),p=_.useRef(null),m=_.useRef(!1),v=_.useRef(!1),b=_.useRef(!1),x=Vn(C=>C.terminalFocusRequestVersion),S=Vn(C=>C.incrementTerminalFocusRequestVersion);return _.useEffect(()=>{var w;const C=p.current,k=b.current;aIe({previousProjectId:C,projectId:t,showTerminalPane:r,wasTerminalVisible:k})&&S(),C!==null&&C===t&&!r&&k&&((w=e.current)==null||w.focus({preventScroll:!0})),b.current=r,p.current=t},[e,S,t,r]),_.useEffect(()=>()=>{l.current!==null&&window.cancelAnimationFrame(l.current),d.current!==null&&window.clearTimeout(d.current)},[]),_.useLayoutEffect(()=>{var j,P,D,L,I,$;if(!n){l.current!==null&&(window.cancelAnimationFrame(l.current),l.current=null),d.current!==null&&(window.clearTimeout(d.current),d.current=null),h.current=!1;return}const C=s.current;if(!C)return;l.current!==null&&(window.cancelAnimationFrame(l.current),l.current=null),d.current!==null&&(window.clearTimeout(d.current),d.current=null);const k=p.current,{currentLayout:w,shouldSkipAnimation:N,targetLayout:A}=lIe({previousProjectId:k,projectId:t,previousShouldRenderTerminalLayout:m.current,previousShowTerminalPane:v.current,showTerminalPane:r,terminalLayout:i,liveLayout:[C.getLayout().chat??i.mainSizes[0],C.getLayout().terminal??i.mainSizes[1]]});if(m.current=n,v.current=r,N||Math.abs(w[0]-A[0])<.1&&Math.abs(w[1]-A[1])<.1){C.setLayout({chat:A[0],terminal:A[1]}),(j=o.current)==null||j.setAttribute("data-terminal-open",r?"true":"false"),(P=a.current)==null||P.setAttribute("data-terminal-open",r?"true":"false"),(D=a.current)==null||D.setAttribute("data-terminal-animated","false");return}h.current=!0,(L=o.current)==null||L.setAttribute("data-terminal-open",r?"true":"false"),(I=a.current)==null||I.setAttribute("data-terminal-open",r?"true":"false"),($=a.current)==null||$.setAttribute("data-terminal-animated","true"),C.setLayout({chat:w[0],terminal:w[1]});const T=performance.now(),M=H=>{const z=Math.min(1,(H-T)/R1),F=JJ(w,A,z);if(C.setLayout({chat:F[0],terminal:F[1]}),z<1){l.current=window.requestAnimationFrame(M);return}C.setLayout({chat:A[0],terminal:A[1]}),l.current=null,d.current=window.setTimeout(()=>{h.current=!1,d.current=null},0)};l.current=window.requestAnimationFrame(M)},[t,n,r,i]),_.useEffect(()=>{n||(m.current=!1,v.current=!1)},[n]),{isAnimating:h,mainPanelGroupRef:s,terminalFocusRequestVersion:x,terminalPanelRef:o,terminalVisualRef:a}}const S6=e=>Symbol.iterator in e,w6=e=>"entries"in e,C6=(e,t)=>{const n=e instanceof Map?e:new Map(e.entries()),r=t instanceof Map?t:new Map(t.entries());if(n.size!==r.size)return!1;for(const[i,s]of n)if(!r.has(i)||!Object.is(s,r.get(i)))return!1;return!0},uIe=(e,t)=>{const n=e[Symbol.iterator](),r=t[Symbol.iterator]();let i=n.next(),s=r.next();for(;!i.done&&!s.done;){if(!Object.is(i.value,s.value))return!1;i=n.next(),s=r.next()}return!!i.done&&!!s.done};function dIe(e,t){return Object.is(e,t)?!0:typeof e!="object"||e===null||typeof t!="object"||t===null||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:S6(e)&&S6(t)?w6(e)&&w6(t)?C6(e,t):uIe(e,t):C6({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function mm(e){const t=$n.useRef(void 0);return n=>{const r=e(n);return dIe(t.current,r)?t.current:t.current=r}}function bv(){var e;return((e=Ir.getState().settings)==null?void 0:e.customModels)??[]}const hb="__new__";function Np(e,t){var o,a;const n=(o=e==null?void 0:e.modelOptions)==null?void 0:o.reasoningEffort;let r;tw(n)?r=n:tw(e==null?void 0:e.effort)?r=e.effort:r=_o.reasoningEffort;const i=yge(e==null?void 0:e.model,void 0,t),s=Zj(i,(a=e==null?void 0:e.modelOptions)==null?void 0:a.contextWindow,t);return{model:i,modelOptions:{reasoningEffort:!jW(i,t)&&r==="max"?"high":r,contextWindow:s},planMode:!!(e!=null&&e.planMode)}}function T0(e,t){var i,s;const n=(i=e==null?void 0:e.modelOptions)==null?void 0:i.reasoningEffort;let r;return nw(n)?r=n:nw(e==null?void 0:e.effort)?r=e.effort:r=fd.reasoningEffort,{model:_ge(e==null?void 0:e.model,void 0,t),modelOptions:{reasoningEffort:r,fastMode:typeof((s=e==null?void 0:e.modelOptions)==null?void 0:s.fastMode)=="boolean"?e.modelOptions.fastMode:fd.fastMode},planMode:!!(e!=null&&e.planMode)}}function fIe(){return{claude:{model:"claude-opus-4-7",modelOptions:{..._o},planMode:!1},codex:{model:"gpt-5.5",modelOptions:{...fd},planMode:!1},openrouter:{model:jC,modelOptions:{},planMode:!1}}}function hIe(e,t){return e.reasoningEffort===t.reasoningEffort&&e.contextWindow===t.contextWindow}function pIe(e,t){return e.reasoningEffort===t.reasoningEffort&&e.fastMode===t.fastMode}function mIe(e,t){return e.claude.model===t.claude.model&&e.claude.planMode===t.claude.planMode&&hIe(e.claude.modelOptions,t.claude.modelOptions)&&e.codex.model===t.codex.model&&e.codex.planMode===t.codex.planMode&&pIe(e.codex.modelOptions,t.codex.modelOptions)&&e.openrouter.model===t.openrouter.model&&e.openrouter.planMode===t.openrouter.planMode}function gIe(e,t){if(t===void 0){Qs.info(`[chat-preferences] ${e}`);return}Qs.info(`[chat-preferences] ${e}`,t)}function pb(e,t){if(e==="claude"){const r=t.claude;return{provider:"claude",model:r.model,modelOptions:{...r.modelOptions},planMode:r.planMode}}if(e==="openrouter"){const r=t.openrouter;return{provider:"openrouter",model:r.model,modelOptions:{...r.modelOptions},planMode:r.planMode}}const n=t.codex;return{provider:"codex",model:n.model,modelOptions:{...n.modelOptions},planMode:n.planMode}}function OR(e){return e.provider==="claude"?{provider:"claude",model:e.model,modelOptions:{...e.modelOptions},planMode:e.planMode}:e.provider==="openrouter"?{provider:"openrouter",model:e.model,modelOptions:{...e.modelOptions},planMode:e.planMode}:{provider:"codex",model:e.model,modelOptions:{...e.modelOptions},planMode:e.planMode}}function ZJ(e){return e.providerHint?pb(e.providerHint,e.providerDefaults):e.defaultProvider==="last_used"?e.sourceState?OR(e.sourceState):pb("claude",e.providerDefaults):pb(e.defaultProvider,e.providerDefaults)}function QJ(e,t){const n=e.chatStates[t];return n||ZJ({defaultProvider:e.defaultProvider,providerDefaults:e.providerDefaults,legacyComposerState:e.legacyComposerState})}function A0(e,t,n){const r=QJ(e,t);return{chatStates:{...e.chatStates,[t]:n(r)}}}const Ts=dr()(og((e,t)=>({defaultProvider:"last_used",providerDefaults:fIe(),chatStates:{},legacyComposerState:{provider:"claude",model:"claude-opus-4-7",modelOptions:{..._o},planMode:!1},setDefaultProvider:n=>e({defaultProvider:n}),applyServerDefaults:(n,r)=>e(i=>{if(i.defaultProvider===n&&mIe(i.providerDefaults,r))return{defaultProvider:n,providerDefaults:r};const{[hb]:o,...a}=i.chatStates;return{defaultProvider:n,providerDefaults:r,chatStates:a}}),setProviderDefaultModel:(n,r)=>e(i=>{const s=bv();return n==="claude"?{providerDefaults:{...i.providerDefaults,[n]:Np({...i.providerDefaults.claude,model:r},s)}}:n==="openrouter"?{providerDefaults:{...i.providerDefaults,[n]:{...i.providerDefaults.openrouter,model:r}}}:{providerDefaults:{...i.providerDefaults,[n]:T0({...i.providerDefaults.codex,model:r},s)}}}),setProviderDefaultModelOptions:(n,r)=>e(i=>{const s=bv();if(n==="claude"){const a=r;return{providerDefaults:{...i.providerDefaults,[n]:Np({...i.providerDefaults.claude,modelOptions:{...i.providerDefaults.claude.modelOptions,...a}},s)}}}if(n==="openrouter")return{providerDefaults:{...i.providerDefaults,[n]:{...i.providerDefaults.openrouter,modelOptions:{}}}};const o=r;return{providerDefaults:{...i.providerDefaults,[n]:T0({...i.providerDefaults.codex,modelOptions:{...i.providerDefaults.codex.modelOptions,...o}},s)}}}),setProviderDefaultPlanMode:(n,r)=>e(i=>({providerDefaults:{...i.providerDefaults,[n]:{...i.providerDefaults[n],planMode:r}}})),getComposerState:n=>OR(QJ(t(),n)),initializeComposerForChat:(n,r)=>e(i=>{if(i.chatStates[n])return i;const s=ZJ({defaultProvider:i.defaultProvider,providerDefaults:i.providerDefaults,sourceState:r==null?void 0:r.sourceState,legacyComposerState:i.legacyComposerState,providerHint:r==null?void 0:r.providerHint});return gIe("initializeComposerForChat",{chatId:n,composerState:s}),{chatStates:{...i.chatStates,[n]:s}}}),setComposerState:(n,r)=>e(i=>{const s=bv();return{chatStates:{...i.chatStates,[n]:r.provider==="claude"?{provider:"claude",model:Np(r,s).model,modelOptions:Np(r,s).modelOptions,planMode:r.planMode}:OR(r)}}}),setChatComposerProvider:(n,r)=>e(i=>A0(i,n,()=>pb(r,i.providerDefaults))),setChatComposerModel:(n,r)=>e(i=>A0(i,n,s=>{const o=bv();if(s.provider==="claude"){const a=Np({...s,model:r},o);return{provider:"claude",model:a.model,modelOptions:a.modelOptions,planMode:s.planMode}}return s.provider==="openrouter"?{provider:"openrouter",model:r,modelOptions:{},planMode:s.planMode}:{provider:"codex",model:r,modelOptions:T0({...s,model:r},o).modelOptions,planMode:s.planMode}})),setChatComposerModelOptions:(n,r)=>e(i=>A0(i,n,s=>{const o=bv();if(s.provider==="claude"){const l=r;return{provider:"claude",model:s.model,modelOptions:Np({...s,modelOptions:{...s.modelOptions,...l}},o).modelOptions,planMode:s.planMode}}if(s.provider==="openrouter")return{provider:"openrouter",model:s.model,modelOptions:{},planMode:s.planMode};const a=r;return{provider:"codex",model:s.model,modelOptions:T0({...s,modelOptions:{...s.modelOptions,...a}},o).modelOptions,planMode:s.planMode}})),setChatComposerPlanMode:(n,r)=>e(i=>A0(i,n,s=>({...s,planMode:r}))),resetChatComposerFromProvider:(n,r)=>e(i=>({chatStates:{...i.chatStates,[n]:pb(r,i.providerDefaults)}}))}),{name:"chat-preferences-state",version:1,partialize:e=>({chatStates:e.chatStates,legacyComposerState:e.legacyComposerState})}));function vIe(e){return e===void 0?null:typeof e=="string"?e?{text:e}:null:e.text||e.lexicalState?e:null}const DR=dr()(og((e,t)=>({drafts:{},attachmentDrafts:{},setDraft:(n,r,i)=>e(s=>{let o;if(typeof r=="string"){if(!r){const{[n]:a,...l}=s.drafts;return{drafts:l}}o={text:r}}else{const a=i??"";if(!a){const{[n]:l,...d}=s.drafts;return{drafts:d}}o={text:a,lexicalState:r}}return{drafts:{...s.drafts,[n]:o}}}),clearDraft:n=>e(r=>{const{[n]:i,...s}=r.drafts;return{drafts:s}}),getDraft:n=>vIe(t().drafts[n]),setAttachmentDrafts:(n,r)=>e(i=>{if(r.length===0){const{[n]:s,...o}=i.attachmentDrafts;return{attachmentDrafts:o}}return{attachmentDrafts:{...i.attachmentDrafts,[n]:r}}}),clearAttachmentDrafts:n=>e(r=>{const{[n]:i,...s}=r.attachmentDrafts;return{attachmentDrafts:s}}),getAttachmentDrafts:n=>t().attachmentDrafts[n]??[]}),{name:"chat-input-drafts"})),rL=dr()(e=>({byChatId:{},loadingByChatId:{},setForChat:(t,n)=>e(r=>({byChatId:{...r.byChatId,[t]:n}})),setLoadingForChat:(t,n)=>e(r=>(r.loadingByChatId[t]??!1)===n?r:{loadingByChatId:{...r.loadingByChatId,[t]:n}}),clear:t=>e(n=>{const r=t in n.byChatId,i=t in n.loadingByChatId;if(!r&&!i)return n;const{[t]:s,...o}=n.byChatId,{[t]:a,...l}=n.loadingByChatId;return{byChatId:o,loadingByChatId:l}})}));function bIe(e){return{autoResumeOnRateLimit:!!(e!=null&&e.autoResumeOnRateLimit)}}const $R=dr()(og(e=>({autoResumeOnRateLimit:!1,setAutoResumeOnRateLimit:t=>e({autoResumeOnRateLimit:t})}),{name:"kanna-preferences",version:1,migrate:e=>bIe(e)})),xIe="kanna",yIe=`mcp__${xIe}__preview_file`;function uf(e){return Wi(e)?e:null}function xv(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}function _Ie(e){let t;Wi(e)&&"content"in e&&Array.isArray(e.content)?t=e.content:Array.isArray(e)?t=e:t=[];const n=[];for(const r of t)if(!(!r||typeof r!="object"||!("type"in r))){if(r.type==="text"&&"text"in r&&typeof r.text=="string"){n.push({type:"text",text:r.text});continue}if(r.type==="image"){if("data"in r&&typeof r.data=="string"){n.push({type:"image",data:r.data,mimeType:"mimeType"in r&&typeof r.mimeType=="string"?r.mimeType:void 0});continue}"source"in r&&r.source&&typeof r.source=="object"&&"type"in r.source&&r.source.type==="base64"&&"data"in r.source&&typeof r.source.data=="string"&&n.push({type:"image",data:r.source.data,mimeType:"media_type"in r.source&&typeof r.source.media_type=="string"?r.source.media_type:void 0})}}return n}function R0(e){let t;if(Wi(e)&&"content"in e&&Array.isArray(e.content)?t=e.content:Array.isArray(e)?t=e:t=null,!t)return null;const n=[];for(const r of t)r&&typeof r=="object"&&"type"in r&&r.type==="text"&&"text"in r&&typeof r.text=="string"&&n.push(r.text);return n.length>0?n.join(""):null}function SIe(e,t){var r;const n=xv(t);switch(e.toolKind){case"ask_user_question":{const i=R0(n),s=i!==null?xv(i):n,o=uf(s),a=uf(o==null?void 0:o.answers)??(o||{}),l={};for(const[d,h]of Object.entries(a))Array.isArray(h)?l[d]=h.map(p=>String(p)):Wi(h)&&Array.isArray(h.answers)?l[d]=h.answers.map(p=>String(p)):h==null||h===""?l[d]=[]:l[d]=[String(h)];return{answers:l,...(o==null?void 0:o.discarded)===!0?{discarded:!0}:{}}}case"exit_plan_mode":{const i=R0(n),s=i!==null?xv(i):n,o=uf(s);return{confirmed:typeof(o==null?void 0:o.confirmed)=="boolean"?o.confirmed:void 0,clearContext:typeof(o==null?void 0:o.clearContext)=="boolean"?o.clearContext:void 0,message:typeof(o==null?void 0:o.message)=="string"?o.message:void 0,...(o==null?void 0:o.discarded)===!0?{discarded:!0}:{}}}case"offer_download":{const i=R0(n),s=i?xv(i):n,o=uf(s);let a;return typeof(o==null?void 0:o.displayName)=="string"?a=o.displayName:typeof(o==null?void 0:o.fileName)=="string"?a=o.fileName:a="",{contentUrl:typeof(o==null?void 0:o.contentUrl)=="string"?o.contentUrl:"",relativePath:typeof(o==null?void 0:o.relativePath)=="string"?o.relativePath:"",fileName:typeof(o==null?void 0:o.fileName)=="string"?o.fileName:"",displayName:a,size:typeof(o==null?void 0:o.size)=="number"?o.size:0,...typeof(o==null?void 0:o.mimeType)=="string"?{mimeType:o.mimeType}:{}}}case"preview_file":{const i=R0(n),s=i?xv(i):n,o=uf(s);let a;return typeof(o==null?void 0:o.displayName)=="string"?a=o.displayName:typeof(o==null?void 0:o.fileName)=="string"?a=o.fileName:a="",{contentUrl:typeof(o==null?void 0:o.contentUrl)=="string"?o.contentUrl:"",relativePath:typeof(o==null?void 0:o.relativePath)=="string"?o.relativePath:"",fileName:typeof(o==null?void 0:o.fileName)=="string"?o.fileName:"",displayName:a,size:typeof(o==null?void 0:o.size)=="number"?o.size:0,mimeType:typeof(o==null?void 0:o.mimeType)=="string"?o.mimeType:"application/octet-stream"}}case"image_generation":{const i=uf(n);return{contentUrl:typeof(i==null?void 0:i.contentUrl)=="string"?i.contentUrl:"",relativePath:typeof(i==null?void 0:i.relativePath)=="string"?i.relativePath:"",fileName:typeof(i==null?void 0:i.fileName)=="string"?i.fileName:""}}case"workflow":{const i=typeof t=="string"?t:"";return{taskId:(r=i.match(/Task ID:\s*(\S+)/))==null?void 0:r[1],text:i}}case"read_file":{if(typeof n=="string")return n;const i=_Ie(n);if(i.length>0)return{content:i.flatMap(o=>o.type==="text"?[o.text]:[]).join(""),blocks:i};const s=uf(n);return{content:typeof(s==null?void 0:s.content)=="string"?s.content:JSON.stringify(n,null,2)}}default:return n}}function wIe(e){return e.kind==="tool"}function eZ(e){return new Date(e).toISOString()}function Ti(e){return{id:e._id,messageId:e.messageId,timestamp:eZ(e.createdAt),hidden:e.hidden}}function CIe(e){return{id:e._id,messageId:e.messageId,hidden:e.hidden,kind:"tool",toolKind:e.tool.toolKind,toolName:e.tool.toolName,toolId:e.tool.toolId,input:e.tool.input,timestamp:eZ(e.createdAt)}}function kIe(e){if(e.debugRaw)try{const t=JSON.parse(e.debugRaw);return(t==null?void 0:t.tool_use_result)??void 0}catch{return}}function al(e){return typeof e=="number"?e:void 0}function M0(e){return typeof e=="string"?e:void 0}function EIe(e){if(!Wi(e))return;const t=e,n={readCount:al(t.readCount),searchCount:al(t.searchCount),bashCount:al(t.bashCount),editFileCount:al(t.editFileCount),linesAdded:al(t.linesAdded),linesRemoved:al(t.linesRemoved),otherToolCount:al(t.otherToolCount)};return Object.values(n).some(r=>r!==void 0)?n:void 0}function NIe(e){if(!e.debugRaw)return;let t;try{t=JSON.parse(e.debugRaw).toolUseResult}catch{return}if(!Wi(t))return;const n=t,r={agentId:M0(n.agentId),agentType:M0(n.agentType),status:M0(n.status),totalTokens:al(n.totalTokens),totalDurationMs:al(n.totalDurationMs),totalToolUseCount:al(n.totalToolUseCount),toolStats:EIe(n.toolStats),content:M0(n.content)};return r.agentId!==void 0||r.agentType!==void 0||r.totalTokens!==void 0||r.totalDurationMs!==void 0||r.status!==void 0?r:void 0}function M1(e){const t=new Map,n=[];for(const r of e)switch(r.kind){case"user_prompt":n.push({...Ti(r),kind:"user_prompt",content:r.content,attachments:r.attachments??[],steered:r.steered,autoContinue:r.autoContinue});break;case"system_init":n.push({...Ti(r),kind:"system_init",provider:r.provider,model:r.model,tools:r.tools,agents:r.agents,slashCommands:r.slashCommands,mcpServers:r.mcpServers,debugRaw:r.debugRaw});break;case"account_info":n.push({...Ti(r),kind:"account_info",accountInfo:r.accountInfo});break;case"assistant_text":n.push({...Ti(r),kind:"assistant_text",text:r.text});break;case"assistant_thinking":n.push({...Ti(r),kind:"assistant_thinking",text:r.text,signature:r.signature});break;case"api_error":n.push({...Ti(r),kind:"api_error",status:r.status,text:r.text,requestId:r.requestId});break;case"policy_refusal":n.push({...Ti(r),kind:"policy_refusal",text:r.text,requestId:r.requestId});break;case"tool_call":{const i=CIe(r);t.set(r.tool.toolId,{hydrated:i,normalized:r.tool}),wIe(i)&&n.push(i);break}case"tool_result":{const i=t.get(r.toolId);if(i){const s=i.normalized.toolKind==="ask_user_question"||i.normalized.toolKind==="exit_plan_mode"?kIe(r)??r.content:r.content;i.normalized.toolKind==="subagent_task"?i.hydrated.result=NIe(r):i.hydrated.result=SIe(i.normalized,s),i.hydrated.rawResult=s,i.hydrated.isError=r.isError,r.persisted&&(i.hydrated.persisted=r.persisted)}break}case"result":n.push({...Ti(r),kind:"result",success:!r.isError,cancelled:r.subtype==="cancelled",result:r.result,durationMs:r.durationMs,costUsd:r.costUsd});break;case"status":n.push({...Ti(r),kind:"status",status:r.status});break;case"context_window_updated":n.push({...Ti(r),kind:"context_window_updated",usage:r.usage});break;case"compact_boundary":n.push({...Ti(r),kind:"compact_boundary"});break;case"compact_summary":n.push({...Ti(r),kind:"compact_summary",summary:r.summary});break;case"context_cleared":n.push({...Ti(r),kind:"context_cleared"});break;case"interrupted":n.push({...Ti(r),kind:"interrupted"});break;case"memory_loaded":n.push({...Ti(r),kind:"memory_loaded",path:r.path});break;case"auto_continue_prompt":n.push({...Ti(r),kind:"auto_continue_prompt",scheduleId:r.scheduleId});break;case"pending_tool_request":n.push({...Ti(r),kind:"pending_tool_request",toolRequestId:r.toolRequestId,toolName:r.toolName,arguments:r.arguments});break;case"tool_request_resolved":break;default:n.push({...Ti(r),kind:"unknown",json:JSON.stringify(r,null,2)});break}return n}function tZ(e){return e.kind==="tool"}const TIe=["AskUserQuestion","ExitPlanMode","TodoWrite"],AIe=new Set(["TodoWrite"]);function RIe(e,t){for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(tZ(r)&&r.toolName===t&&!r.result)return r.id}return null}function MIe(e,t){for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(tZ(r)&&r.toolName===t)return r.id}return null}function jIe(e){const t={};for(const n of TIe)t[n]=AIe.has(n)?MIe(e,n):RIe(e,n);return t}function IIe(e){return e==="starting"||e==="running"||e==="waiting_for_user"}function PIe(e){return e==="starting"||e==="running"||e==="waiting_for_user"}const iL="pushDeviceId";function nZ(){return typeof localStorage>"u"?null:localStorage.getItem(iL)}function LIe(e){typeof localStorage>"u"||localStorage.setItem(iL,e)}function OIe(){typeof localStorage>"u"||localStorage.removeItem(iL)}function DIe(){return!(typeof window>"u"||typeof Notification>"u"||!("serviceWorker"in navigator)||typeof Reflect.get(globalThis,"PushManager")>"u")}function $Ie(){var t;if(typeof window>"u")return!1;if(window.isSecureContext)return!0;const e=((t=window.location)==null?void 0:t.hostname)??"";return e==="localhost"||e==="127.0.0.1"||e==="::1"}function sL(){if(!DIe())return{state:"unsupported"};if(!$Ie())return{state:"insecure-context"};switch(Notification.permission){case"granted":return{state:"granted"};case"denied":return{state:"denied"};default:return{state:"default"}}}function zIe(e){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64url"));const t="=".repeat((4-e.length%4)%4),n=(e+t).replace(/-/g,"+").replace(/_/g,"/"),r=atob(n),i=new Uint8Array(r.length);for(let s=0;s<r.length;s+=1)i[s]=r.charCodeAt(s);return i}function BIe(e){const t=e||"";return/iPhone|iPad/i.test(t)?"iPhone / iPad":/Android/i.test(t)?"Android":/Macintosh/i.test(t)?"Mac":/Windows/i.test(t)?"Windows PC":t||"Browser"}async function FIe(e){const t=sL();if(t.state==="unsupported")throw new Error("Push not supported in this browser");if(t.state==="insecure-context")throw new Error("Push requires a secure context (HTTPS)");if(t.state==="denied")throw new Error("Notification permission previously denied");if(await Notification.requestPermission()!=="granted")throw new Error("Notification permission was not granted");const r=await navigator.serviceWorker.register("/sw.js");await navigator.serviceWorker.ready;const i=await r.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:zIe(e.vapidPublicKey)}),s=i.toJSON(),o=s.endpoint??i.endpoint,a=s.keys??{};if(!o||!a.p256dh||!a.auth)throw new Error("Subscription returned without endpoint or keys");const l=navigator.userAgent??"",{id:d}=await e.sendToServer({subscription:{endpoint:o,keys:{p256dh:a.p256dh,auth:a.auth}},label:BIe(l),userAgent:l});return d}async function UIe(e){const n=await(await navigator.serviceWorker.ready).pushManager.getSubscription();n&&await n.unsubscribe(),await e.sendToServer(e.pushDeviceId)}typeof navigator<"u"&&"serviceWorker"in navigator&&navigator.serviceWorker.addEventListener("message",e=>{const t=e.data;(t==null?void 0:t.type)==="kanna.navigate"&&typeof t.url=="string"&&(window.location.href=t.url)});const HIe=25e3,WIe=15e3,VIe=4e3,k6="kanna:profile-send-to-starting";function E6(){try{return window.sessionStorage.getItem(k6)==="1"||window.localStorage.getItem(k6)==="1"}catch{return!1}}class KIe{constructor(t){U(this,"url");U(this,"ws",null);U(this,"started",!1);U(this,"reconnectTimer",null);U(this,"reconnectDelayMs",750);U(this,"subscriptions",new Map);U(this,"pending",new Map);U(this,"outboundQueue",[]);U(this,"statusListeners",new Set);U(this,"heartbeatTimer",null);U(this,"pingTimeoutTimer",null);U(this,"pingPromise",null);U(this,"lastOpenAt",0);U(this,"lastMessageAt",0);U(this,"reconnectImmediatelyOnClose",!1);U(this,"handleWindowFocus",()=>{this.ensureHealthyConnection()});U(this,"handleVisibilityChange",()=>{if(document.visibilityState==="visible"){this.startHeartbeat(),this.ensureHealthyConnection();return}this.stopHeartbeat()});U(this,"handleOnline",()=>{this.ensureHealthyConnection()});this.url=t}start(){this.started||(this.started=!0,window.addEventListener("focus",this.handleWindowFocus),window.addEventListener("online",this.handleOnline),document.addEventListener("visibilitychange",this.handleVisibilityChange),this.connect())}dispose(){var t;this.started=!1,this.reconnectTimer&&(window.clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.stopHeartbeat(),this.clearPingState(),window.removeEventListener("focus",this.handleWindowFocus),window.removeEventListener("online",this.handleOnline),document.removeEventListener("visibilitychange",this.handleVisibilityChange),(t=this.ws)==null||t.close(),this.ws=null;for(const n of this.pending.values())n.reject(new Error("Socket disposed"));this.pending.clear()}onStatus(t){return this.statusListeners.add(t),t(this.getStatus()),()=>{this.statusListeners.delete(t)}}subscribe(t,n,r){const i=Sf(),s={topic:t,listener:n,eventListener:r};return this.subscriptions.set(i,s),this.enqueue({v:1,type:"subscribe",id:i,topic:t}),()=>{this.subscriptions.delete(i),this.enqueue({v:1,type:"unsubscribe",id:i})}}subscribeTerminal(t,n){const r=Sf(),i={type:"terminal",terminalId:t},s={topic:i,listener:n.onSnapshot,eventListener:n.onEvent};return this.subscriptions.set(r,s),this.enqueue({v:1,type:"subscribe",id:r,topic:i}),()=>{this.subscriptions.delete(r),this.enqueue({v:1,type:"unsubscribe",id:r})}}command(t){const n=Sf(),r={v:1,type:"command",id:n,command:t};return new Promise((i,s)=>{this.pending.set(n,{resolve:i,reject:s}),this.enqueue(r)})}setFocusedChat(t){const n=Sf();this.enqueue({v:1,type:"command",id:n,command:{type:"push.setFocusedChat",chatId:t}})}ensureHealthyConnection(){return!this.ws||this.ws.readyState===WebSocket.CLOSED||this.ws.readyState===WebSocket.CLOSING?(this.reconnectNow(),Promise.resolve()):this.ws.readyState===WebSocket.CONNECTING||!this.isConnectionStale()?Promise.resolve():this.sendPing()}connect(){this.started&&(this.emitStatus("connecting"),this.ws=new WebSocket(this.url),this.ws.addEventListener("open",()=>{this.reconnectDelayMs=750,this.reconnectImmediatelyOnClose=!1,this.lastOpenAt=Date.now(),this.lastMessageAt=this.lastOpenAt,this.emitStatus("connected"),this.startHeartbeat();for(const[n,r]of this.subscriptions.entries())this.sendNow({v:1,type:"subscribe",id:n,topic:r.topic});for(;this.outboundQueue.length>0;){const n=this.outboundQueue.shift();n&&this.sendNow(n)}const t=nZ();t&&this.sendNow({v:1,type:"command",id:Sf(),command:{type:"push.identifyDevice",pushDeviceId:t}})}),this.ws.addEventListener("message",t=>{var s,o;this.lastMessageAt=Date.now();const n=performance.now(),r=String(t.data);let i;try{i=JSON.parse(r)}catch{return}if(E6()&&i.type==="snapshot"&&i.snapshot.type==="chat"&&((s=i.snapshot.data)==null?void 0:s.runtime.status)==="starting"&&Qs.debug("[kanna/send->starting][client-ws]",{stage:"socket_message_received",receivedAt:n,payloadBytes:r.length,chatId:i.snapshot.data.runtime.chatId,status:i.snapshot.data.runtime.status,messageCount:i.snapshot.data.messages.length}),E6()&&i.type==="ack"&&Qs.debug("[kanna/send->starting][client-ws]",{stage:"socket_ack_received",receivedAt:n,payloadBytes:r.length,commandId:i.id}),i.type==="snapshot"){const a=this.subscriptions.get(i.id);a==null||a.listener(i.snapshot.data);return}if(i.type==="event"){const a=this.subscriptions.get(i.id);(o=a==null?void 0:a.eventListener)==null||o.call(a,i.event);return}if(i.type==="ack"){const a=this.pending.get(i.id);if(!a)return;this.pending.delete(i.id),a.resolve(i.result);return}if(i.type==="error"){if(!i.id){Qs.error(sfe,i.message);return}const a=this.pending.get(i.id);if(!a)return;this.pending.delete(i.id),a.reject(new Error(i.message))}}),this.ws.addEventListener("close",()=>{if(!this.started)return;const t=this.reconnectImmediatelyOnClose;this.reconnectImmediatelyOnClose=!1,this.stopHeartbeat(),this.clearPingState(),this.emitStatus("disconnected");for(const n of this.pending.values())n.reject(new Error("Disconnected"));if(this.pending.clear(),t){this.connect();return}this.scheduleReconnect()}))}scheduleReconnect(){this.reconnectTimer===null&&(this.reconnectTimer=window.setTimeout(()=>{this.reconnectTimer=null,this.connect(),this.reconnectDelayMs=Math.min(this.reconnectDelayMs*2,5e3)},this.reconnectDelayMs))}getStatus(){var t,n;return((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN?"connected":((n=this.ws)==null?void 0:n.readyState)===WebSocket.CONNECTING?"connecting":"disconnected"}emitStatus(t){for(const n of this.statusListeners)n(t)}isConnectionStale(){const t=Math.max(this.lastMessageAt,this.lastOpenAt);return t>0&&Date.now()-t>=HIe}sendPing(){if(this.pingPromise)return this.pingPromise;const t=this.command({type:"system.ping"}).then(()=>{this.clearPingState()}).catch(n=>{throw this.clearPingState(),this.reconnectNow(),n});return this.pingTimeoutTimer=window.setTimeout(()=>{this.clearPingState(),this.reconnectNow()},VIe),this.pingPromise=t,t}reconnectNow(){if(this.reconnectTimer!==null&&(window.clearTimeout(this.reconnectTimer),this.reconnectTimer=null),!this.ws||this.ws.readyState===WebSocket.CLOSED){this.connect();return}this.ws.readyState!==WebSocket.CONNECTING&&(this.reconnectImmediatelyOnClose=!0,this.ws.close())}startHeartbeat(){document.visibilityState==="visible"&&this.heartbeatTimer===null&&(this.heartbeatTimer=window.setInterval(()=>{var t;if(document.visibilityState!=="visible"){this.stopHeartbeat();return}((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN&&this.ensureHealthyConnection()},WIe))}stopHeartbeat(){this.heartbeatTimer!==null&&(window.clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}clearPingState(){this.pingTimeoutTimer!==null&&(window.clearTimeout(this.pingTimeoutTimer),this.pingTimeoutTimer=null),this.pingPromise=null}enqueue(t){var n;if(((n=this.ws)==null?void 0:n.readyState)===WebSocket.OPEN){this.sendNow(t);return}this.outboundQueue.push(t)}sendNow(t){var n;(n=this.ws)==null||n.send(JSON.stringify(t))}}const GIe=[],j1=dr()(e=>({byChat:{},setRuns:(t,n)=>e(r=>({byChat:{...r.byChat,[t]:n}}))}));function oL(e){return t=>t.byChat[e]??GIe}const qIe=[],j0=dr()(e=>({models:qIe,status:"idle",error:null,setLoading:()=>e({status:"loading",error:null}),setModels:t=>e({models:t,status:"ready",error:null}),setError:t=>e({status:"error",error:t})})),YIe=[],XIe=[],JIe={},ZIe={starredProjectGroups:[],projectGroups:[],stacks:[]};function QIe(){return typeof window>"u"?null:window.sessionStorage.getItem("kanna:ui-update-restart")}const me=dr()(e=>({sidebarData:ZIe,optimisticSidebarProjectOrder:null,localProjects:null,updateSnapshot:null,uiRestartPhase:QIe(),chatSnapshot:null,olderHistoryEntries:XIe,isHistoryLoading:!1,historyCursor:null,hasOlderHistory:!1,projectDiffSnapshots:JIe,keybindings:null,appSettings:null,pushConfig:null,llmProvider:null,connectionStatus:"connecting",sidebarReady:!1,localProjectsReady:!1,chatReady:!1,selectedProjectId:null,sidebarOpen:!1,sidebarCollapsed:!1,addProjectModalOpen:!1,commandError:null,startingLocalPath:null,pendingChatId:null,optimisticUserPrompts:YIe,optimisticProcessing:null,focusEpoch:0,setSidebarData:t=>e({sidebarData:t}),setOptimisticSidebarProjectOrder:t=>e(n=>({optimisticSidebarProjectOrder:typeof t=="function"?t(n.optimisticSidebarProjectOrder):t})),setLocalProjects:t=>e({localProjects:t}),setUpdateSnapshot:t=>e({updateSnapshot:t}),setUiRestartPhase:t=>e({uiRestartPhase:t}),setChatSnapshot:t=>e(n=>({chatSnapshot:typeof t=="function"?t(n.chatSnapshot):t})),setOlderHistoryEntries:t=>e(n=>({olderHistoryEntries:typeof t=="function"?t(n.olderHistoryEntries):t})),setIsHistoryLoading:t=>e({isHistoryLoading:t}),setHistoryCursor:t=>e({historyCursor:t}),setHasOlderHistory:t=>e({hasOlderHistory:t}),setProjectDiffSnapshots:t=>e(n=>({projectDiffSnapshots:typeof t=="function"?t(n.projectDiffSnapshots):t})),setKeybindings:t=>e({keybindings:t}),setAppSettings:t=>e({appSettings:t}),setPushConfig:t=>e({pushConfig:t}),setLlmProvider:t=>e({llmProvider:t}),setConnectionStatus:t=>e({connectionStatus:t}),setSidebarReady:t=>e({sidebarReady:t}),setLocalProjectsReady:t=>e({localProjectsReady:t}),setChatReady:t=>e({chatReady:t}),setSelectedProjectId:t=>e({selectedProjectId:t}),setSidebarOpen:t=>e({sidebarOpen:t}),setSidebarCollapsed:t=>e({sidebarCollapsed:t}),setAddProjectModalOpen:t=>e({addProjectModalOpen:t}),setCommandError:t=>e({commandError:t}),setStartingLocalPath:t=>e({startingLocalPath:t}),setPendingChatId:t=>e({pendingChatId:t}),setOptimisticUserPrompts:t=>e(n=>({optimisticUserPrompts:typeof t=="function"?t(n.optimisticUserPrompts):t})),setOptimisticProcessing:t=>e(n=>({optimisticProcessing:typeof t=="function"?t(n.optimisticProcessing):t})),incrementFocusEpoch:()=>e(t=>({focusEpoch:t.focusEpoch+1}))}));function ePe(e,t){const n=["claude","codex","openrouter"];for(const r of n)if(e[r]!==t[r])return!1;return!0}function tPe(e,t){return e===t?!0:!e||!t?!1:e.chatId===t.chatId&&e.projectId===t.projectId&&e.localPath===t.localPath&&e.title===t.title&&e.status===t.status&&e.isDraining===t.isDraining&&e.provider===t.provider&&e.planMode===t.planMode&&ePe(e.sessionTokensByProvider,t.sessionTokensByProvider)}function nPe(e,t){return e===t?!0:!e||!t||e.length!==t.length?!1:e.every((n,r)=>{var i;return n._id===((i=t[r])==null?void 0:i._id)})}function rPe(e,t){return t.length===0?e:e.map(n=>n.id!=="openrouter"?n:{...n,models:t.map(r=>({id:r.id,label:r.label,supportsEffort:!1}))})}function iPe(e,t){return e===t?!0:!e||!t||e.length!==t.length?!1:e.every((n,r)=>{var i;return n.id===((i=t[r])==null?void 0:i.id)})}function sPe(e,t){return e===t?!0:!e||!t?!1:e.hasOlder===t.hasOlder&&e.olderCursor===t.olderCursor&&e.recentLimit===t.recentLimit}function oPe(e,t){return e.id===t.id&&e.content===t.content&&e.createdAt===t.createdAt&&e.provider===t.provider&&e.model===t.model&&e.planMode===t.planMode&&JSON.stringify(e.modelOptions)===JSON.stringify(t.modelOptions)&&aPe(e.attachments,t.attachments)}function aPe(e,t){return e===t?!0:e.length!==t.length?!1:e.every((n,r)=>{const i=t[r];return!!i&&n.id===i.id&&n.kind===i.kind&&n.displayName===i.displayName&&n.absolutePath===i.absolutePath&&n.relativePath===i.relativePath&&n.contentUrl===i.contentUrl&&n.mimeType===i.mimeType&&n.size===i.size})}function lPe(e,t){return e===t?!0:!e||!t||e.length!==t.length?!1:e.every((n,r)=>oPe(n,t[r]))}function cPe(e,t){var s,o;if(e===t)return!0;if(!e||!t||e.status!==t.status||e.branchName!==t.branchName||e.defaultBranchName!==t.defaultBranchName||e.hasOriginRemote!==t.hasOriginRemote||e.originRepoSlug!==t.originRepoSlug||e.hasUpstream!==t.hasUpstream||e.aheadCount!==t.aheadCount||e.behindCount!==t.behindCount||e.lastFetchedAt!==t.lastFetchedAt)return!1;const n=((s=e.branchHistory)==null?void 0:s.entries)??[],r=((o=t.branchHistory)==null?void 0:o.entries)??[];return n.length!==r.length||!n.every((a,l)=>{const d=r[l];return!!d&&a.sha===d.sha&&a.summary===d.summary&&a.description===d.description&&a.authorName===d.authorName&&a.authoredAt===d.authoredAt&&a.githubUrl===d.githubUrl&&a.tags.length===d.tags.length&&a.tags.every((h,p)=>h===d.tags[p])})||e.files.length!==t.files.length?!1:e.files.every((a,l)=>{const d=t.files[l];return!!d&&a.path===d.path&&a.changeType===d.changeType&&a.isUntracked===d.isUntracked&&a.additions===d.additions&&a.deletions===d.deletions&&a.patchDigest===d.patchDigest&&a.mimeType===d.mimeType&&a.size===d.size})}function uPe(e,t){return!!(e&&e.status!=="unknown"&&t&&t.status==="unknown"&&t.files.length===0)}function dPe(e,t){if(e===t)return!0;if(!e||!t)return!1;const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(i=>{const s=e[i],o=t[i];return!s||!o?!1:s.state===o.state&&s.scheduledAt===o.scheduledAt&&s.resetAt===o.resetAt&&s.detectedAt===o.detectedAt&&s.tz===o.tz})}function fPe(e,t){if(e===t)return!0;if(!e||!t)return!1;const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(i=>{const s=e[i],o=t[i];return!s||!o?!1:s.state===o.state&&s.url===o.url&&s.error===o.error&&s.port===o.port&&s.activatedAt===o.activatedAt&&s.stoppedAt===o.stoppedAt})}function hPe(e,t){if(e===t)return!0;if(!e||!t)return!1;const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(i=>{var a,l,d,h,p,m;const s=e[i],o=t[i];return!s||!o?!1:s.status===o.status&&s.entries.length===o.entries.length&&(s.finalText??"")===(o.finalText??"")&&(((a=s.pendingTool)==null?void 0:a.toolUseId)??null)===(((l=o.pendingTool)==null?void 0:l.toolUseId)??null)&&(((d=s.usage)==null?void 0:d.outputTokens)??null)===(((h=o.usage)==null?void 0:h.outputTokens)??null)&&s.finishedAt===o.finishedAt&&(((p=s.error)==null?void 0:p.code)??null)===(((m=o.error)==null?void 0:m.code)??null)})}function pPe(e,t){return e===t?!0:!e||!t?!1:tPe(e.runtime,t.runtime)&&lPe(e.queuedMessages,t.queuedMessages)&&nPe(e.messages,t.messages)&&sPe(e.history,t.history)&&iPe(e.availableProviders,t.availableProviders)&&dPe(e.schedules,t.schedules)&&e.liveScheduleId===t.liveScheduleId&&fPe(e.tunnels,t.tunnels)&&e.liveTunnelId===t.liveTunnelId&&hPe(e.subagentRuns,t.subagentRuns)}function N6(e,t){const n=new Map;for(const r of e)n.set(r._id,r);for(const r of t)n.set(r._id,r);return[...n.values()]}function mPe(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if((n==null?void 0:n.kind)==="user_prompt"&&n.content.trim().length>0)return n.content}return null}const T6="__new_chat__",rZ="lever-theme",iZ="chat-sound-preferences",sZ="terminal-preferences",oZ="chat-preferences";function kT(e){if(typeof window>"u")return null;const t=window.localStorage.getItem(e);if(!t)return null;try{const n=JSON.parse(t);return Wi(n.state)?n.state:null}catch{return null}}function gPe(){if(typeof window>"u")return null;const e={},t=window.localStorage.getItem(rZ);(t==="light"||t==="dark"||t==="system")&&(e.theme=t);const n=kT(iZ);((n==null?void 0:n.chatSoundPreference)==="never"||(n==null?void 0:n.chatSoundPreference)==="unfocused"||(n==null?void 0:n.chatSoundPreference)==="always")&&(e.chatSoundPreference=n.chatSoundPreference),((n==null?void 0:n.chatSoundId)==="blow"||(n==null?void 0:n.chatSoundId)==="bottle"||(n==null?void 0:n.chatSoundId)==="frog"||(n==null?void 0:n.chatSoundId)==="funk"||(n==null?void 0:n.chatSoundId)==="glass"||(n==null?void 0:n.chatSoundId)==="ping"||(n==null?void 0:n.chatSoundId)==="pop"||(n==null?void 0:n.chatSoundId)==="purr"||(n==null?void 0:n.chatSoundId)==="tink")&&(e.chatSoundId=n.chatSoundId);const r=kT(sZ);if(r){e.terminal={},typeof r.scrollbackLines=="number"&&(e.terminal.scrollbackLines=r.scrollbackLines),typeof r.minColumnWidth=="number"&&(e.terminal.minColumnWidth=r.minColumnWidth);const s={};(r.editorPreset==="cursor"||r.editorPreset==="vscode"||r.editorPreset==="xcode"||r.editorPreset==="windsurf"||r.editorPreset==="custom")&&(s.preset=r.editorPreset),typeof r.editorCommandTemplate=="string"&&(s.commandTemplate=r.editorCommandTemplate),Object.keys(s).length>0&&(e.editor=s)}const i=kT(oZ);if(((i==null?void 0:i.defaultProvider)==="last_used"||(i==null?void 0:i.defaultProvider)==="claude"||(i==null?void 0:i.defaultProvider)==="codex")&&(e.defaultProvider=i.defaultProvider),Wi(i==null?void 0:i.providerDefaults)){const s=i.providerDefaults;e.providerDefaults=s}return e.browserSettingsMigrated=!0,Object.keys(e).length>1?e:null}function vPe(){typeof window>"u"||(window.localStorage.removeItem(rZ),window.localStorage.removeItem(iZ),window.localStorage.removeItem(sZ),window.localStorage.removeItem(oZ))}function yv(e){Ir.getState().setFromServer(e);const t=ws.getState();t.setScrollbackLines(e.terminal.scrollbackLines),t.setMinColumnWidth(e.terminal.minColumnWidth),t.setEditorPreset(e.editor.preset),t.setEditorCommandTemplate(e.editor.commandTemplate);const n=Af.getState();n.setChatSoundPreference(e.chatSoundPreference),n.setChatSoundId(e.chatSoundId),Ts.getState().applyServerDefaults(e.defaultProvider,e.providerDefaults)}function bPe(e){return JSON.stringify({id:e.id,kind:e.kind,displayName:e.displayName,relativePath:e.relativePath,mimeType:e.mimeType,size:e.size,contentUrl:e.contentUrl})}function aL(e,t=[]){return JSON.stringify({content:e,attachments:t.map(bPe)})}function xPe(e,t){return e.reduce((n,r)=>r.kind!=="user_prompt"?n:n+(aL(r.content,r.attachments??[])===t?1:0),0)}function yPe(e,t,n){const r=new Map;for(const i of n){if(i.kind!=="user_prompt")continue;const s=aL(i.content,i.attachments??[]);r.set(s,(r.get(s)??0)+1)}return e.filter(i=>i.scopeId!==t?!0:(r.get(i.signature)??0)<i.requiredMatchCount)}function _Pe(e,t,n){return e.some(r=>r.id===t)?e.filter(r=>r.id!==t):e}const SPe=200,wPe=500;function A6(e,t){var r;const n=e.find(i=>i.chats.some(s=>s.chatId===t));return n?((r=n.chats.find(i=>i.chatId!==t))==null?void 0:r.chatId)??null:null}function R6(e,t){if(!(t!=null&&t.length)||e.length<=1)return e;const n=new Map(e.map((o,a)=>[o.groupKey,a])),r=new Set,i=t.map(o=>{if(r.has(o))return null;r.add(o);const a=n.get(o);return a===void 0?null:e[a]}).filter(o=>!!o);if(i.length===0)return e;const s=[...i,...e.filter(o=>!r.has(o.groupKey))];return s.every((o,a)=>o===e[a])?e:s}function CPe(e=document){return e.visibilityState==="visible"&&e.hasFocus()}function kPe(){return`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`}function EPe(){const e=_.useMemo(()=>new KIe(kPe()),[]);return _.useEffect(()=>(e.start(),()=>{e.dispose()}),[e]),e}const M6="kanna:profile-send-to-starting";function NPe(){try{return window.sessionStorage.getItem(M6)==="1"||window.localStorage.getItem(M6)==="1"}catch{return!1}}function aZ(e){return Number((performance.now()-e).toFixed(1))}function $u(e,t,n){!e||!NPe()||Qs.debug("[kanna/send->starting][client]",{traceId:e.traceId,stage:t,elapsedMs:aZ(e.startedAt),serverChatId:e.serverChatId,routeChatIdAtSend:e.routeChatIdAtSend,...n})}function TPe(e){var t,n;return(e==null?void 0:e.provider)==="claude"&&e.model&&((t=e.modelOptions)!=null&&t.claude)?{provider:"claude",model:e.model,modelOptions:{reasoningEffort:e.modelOptions.claude.reasoningEffort??"high",contextWindow:e.modelOptions.claude.contextWindow??"200k"},planMode:!!e.planMode}:(e==null?void 0:e.provider)==="codex"&&e.model&&((n=e.modelOptions)!=null&&n.codex)?{provider:"codex",model:e.model,modelOptions:{reasoningEffort:e.modelOptions.codex.reasoningEffort??"high",fastMode:e.modelOptions.codex.fastMode??!1},planMode:!!e.planMode}:null}function APe(e,t){var n;return t?((n=e.find(r=>r.chats.some(i=>i.chatId===t)))==null?void 0:n.groupKey)??null:null}function RPe(e,t){return e==="awaiting_disconnect"&&t==="disconnected"?"awaiting_server_ready":"none"}function MPe(e,t){return t==="updating"||t==="restart_pending"?{active:!0,label:"Installing update"}:e==="awaiting_disconnect"||e==="awaiting_server_ready"?{active:!0,label:"Re-deploying Kanna"}:{active:!1,label:""}}const jPe=30,lL="kanna:ui-update-restart",lZ="kanna:last-update-reload-request";function IPe(e){return e+jPe}function PPe(e,t){return t>0?t:e}function j6(){return window.sessionStorage.getItem(lL)}function LPe(e){window.sessionStorage.setItem(lL,e)}function OPe(){window.sessionStorage.removeItem(lL)}function DPe(e,t){return e?String(e)!==t:!1}function $Pe(){return window.sessionStorage.getItem(lZ)}function zPe(e){window.sessionStorage.setItem(lZ,String(e))}function BPe(){return"/auth/status"}async function FPe(e=fetch){return(await e(BPe(),{method:"GET",cache:"no-store",headers:{Accept:"application/json"}})).ok}function UPe(e){const t=e.selectedProjectId??e.sidebarProjectId??null;return t?{kind:"project_id",projectId:t}:e.fallbackLocalProjectPath?{kind:"local_path",localPath:e.fallbackLocalProjectPath}:null}function HPe(e,t){return!e||!t?null:e.runtime.chatId!==t?(e.runtime.chatId,e.runtime.provider,null):e}function WPe(e){var va,vs,Ya;const t=Ad(),n=EPe(),r=Ox(),i=me(q=>q.sidebarData),s=me(q=>q.optimisticSidebarProjectOrder),o=me(q=>q.localProjects),a=me(q=>q.updateSnapshot),l=me(q=>q.uiRestartPhase),d=_.useCallback(q=>{LPe(q),me.getState().setUiRestartPhase(q)},[]),h=_.useCallback(()=>{OPe(),me.getState().setUiRestartPhase(null)},[]),p=me(q=>q.chatSnapshot),m=me(q=>q.olderHistoryEntries),v=me(q=>q.isHistoryLoading),b=me(q=>q.historyCursor),x=me(q=>q.hasOlderHistory),S=me(q=>q.projectDiffSnapshots),C=me(q=>q.keybindings),k=me(q=>q.appSettings),w=me(q=>q.pushConfig),N=me(q=>q.llmProvider),A=me(q=>q.connectionStatus),T=me(q=>q.sidebarReady),M=me(q=>q.localProjectsReady),j=me(q=>q.chatReady),P=me(q=>q.selectedProjectId),D=me(q=>q.sidebarOpen),L=me(q=>q.sidebarCollapsed),I=me(q=>q.addProjectModalOpen),$=me(q=>q.commandError),H=me(q=>q.startingLocalPath),z=me(q=>q.pendingChatId),F=me(q=>q.optimisticUserPrompts),K=me(q=>q.optimisticProcessing),W=me(q=>q.focusEpoch),V=_.useRef(new Map),X=DR(mm(q=>Object.keys(q.drafts).sort())),G=DR(mm(q=>Object.keys(q.attachmentDrafts).sort())),te=_.useRef(0),oe=_.useRef(null),ue=_.useRef({projectId:null,diffs:null}),de=ive(ws(q=>q.editorPreset)),ee=_.useMemo(()=>R6(i.projectGroups,s),[s,i.projectGroups]),ne=_.useRef(ee);_.useLayoutEffect(()=>{ne.current=ee});const ie=_.useMemo(()=>ee===i.projectGroups?i:{...i,projectGroups:ee},[i,ee]);_.useEffect(()=>n.onStatus(q=>me.getState().setConnectionStatus(q)),[n]),_.useEffect(()=>n.subscribe({type:"sidebar"},q=>{const Z=me.getState();Z.setSidebarData(q),Z.setOptimisticSidebarProjectOrder(xe=>xe&&R6(q.projectGroups,xe)===q.projectGroups?null:xe),Z.setSidebarReady(!0),Z.setCommandError(null)}),[n]),_.useEffect(()=>{if(A!=="connected")return;const q=[...new Set([...X,...G])].sort();n.command({type:"chat.setDraftProtection",chatIds:q}).catch(Z=>{me.getState().setCommandError(Z instanceof Error?Z.message:String(Z))})},[G,A,X,n]),_.useEffect(()=>n.subscribe({type:"local-projects"},q=>{const Z=me.getState();Z.setLocalProjects(q),Z.setLocalProjectsReady(!0),Z.setCommandError(null)}),[n]),_.useEffect(()=>n.subscribe({type:"update"},q=>{const Z=me.getState();Z.setUpdateSnapshot(q),Z.setCommandError(null)}),[n]),_.useEffect(()=>{A==="connected"&&n.command({type:"update.check",force:!0}).catch(q=>{me.getState().setCommandError(q instanceof Error?q.message:String(q))})},[A,n]),_.useEffect(()=>{const q=a==null?void 0:a.reloadRequestedAt;DPe(q,$Pe())&&q&&(zPe(q),d("awaiting_disconnect"))},[d,a==null?void 0:a.reloadRequestedAt]),_.useEffect(()=>{const q=j6();RPe(q,A)==="awaiting_server_ready"&&d("awaiting_server_ready")},[A,d]),_.useEffect(()=>{if(j6()!=="awaiting_server_ready")return;let q=!1,Z=null;const xe=async()=>{try{if(await FPe()){if(q)return;h(),window.location.reload();return}}catch{}q||(Z=window.setTimeout(()=>{xe()},500))};return xe(),()=>{q=!0,Z!==null&&window.clearTimeout(Z)}},[A,h]),_.useEffect(()=>{function q(){a!=null&&a.lastCheckedAt&&(Date.now()-a.lastCheckedAt<=3600*1e3||n.command({type:"update.check"}).catch(Z=>{me.getState().setCommandError(Z instanceof Error?Z.message:String(Z))}))}return window.addEventListener("focus",q),()=>{window.removeEventListener("focus",q)}},[n,a==null?void 0:a.lastCheckedAt]),_.useEffect(()=>n.subscribe({type:"keybindings"},q=>{const Z=me.getState();Z.setKeybindings(q),Z.setCommandError(null)}),[n]),_.useEffect(()=>n.subscribe({type:"app-settings"},q=>{const Z=me.getState();Z.setAppSettings(q),yv(q),Z.setCommandError(null)}),[n]),_.useEffect(()=>n.subscribe({type:"push-config"},q=>{me.getState().setPushConfig(q)}),[n]),_.useEffect(()=>n.subscribe({type:"pty-instances"},q=>{wc.getState().applySnapshot(q.instances)},q=>{q.type==="pty-instances.added"?wc.getState().applyDiff({op:"added",instance:q.instance}):q.type==="pty-instances.updated"?wc.getState().applyDiff({op:"updated",instance:q.instance}):wc.getState().applyDiff({op:"removed",chatId:q.chatId})}),[n]);const ae=_.useCallback(async()=>{try{Ir.getState().setHydrationStatus("loading");const q=await n.command({type:"settings.readAppSettings"}),Z=me.getState();Z.setAppSettings(q),yv(q),Z.setCommandError(null)}catch(q){Ir.getState().setHydrationStatus("error"),me.getState().setCommandError(q instanceof Error?q.message:String(q))}},[n]),Q=_.useCallback(async(q,Z)=>{try{await n.command({type:"chat.setPolicyOverride",chatId:q,policyOverride:Z}),me.getState().setCommandError(null)}catch(xe){throw me.getState().setCommandError(xe instanceof Error?xe.message:String(xe)),xe}},[n]),ke=_.useCallback(async q=>{try{Ir.getState().applyOptimisticPatch(q);const Z=await n.command({type:"settings.writeAppSettingsPatch",patch:q}),xe=me.getState();xe.setAppSettings(Z),yv(Z),xe.setCommandError(null)}catch(Z){throw me.getState().setCommandError(Z instanceof Error?Z.message:String(Z)),await ae(),Z}},[ae,n]),Se=_.useCallback(async q=>{try{await n.command({type:"settings.testMcpServer",id:q}),me.getState().setCommandError(null)}catch(Z){throw me.getState().setCommandError(Z instanceof Error?Z.message:String(Z)),Z}},[n]),Ne=_.useCallback(async q=>{try{const Z=await n.command({type:"settings.startMcpOAuth",id:q});return me.getState().setCommandError(null),Z}catch(Z){const xe=Z instanceof Error?Z.message:String(Z);return me.getState().setCommandError(xe),{ok:!1,error:xe}}},[n]),Xe=_.useCallback(async(q,Z)=>{try{const xe=await n.command({type:"settings.completeMcpOAuth",id:q,callbackUrl:Z});return me.getState().setCommandError(null),xe}catch(xe){const et=xe instanceof Error?xe.message:String(xe);return me.getState().setCommandError(et),{ok:!1,error:et}}},[n]),ht=_.useCallback(async q=>{try{Ir.getState().applyOptimisticPatch({cloudflareTunnel:q});const Z=await n.command({type:"appSettings.setCloudflareTunnel",patch:q}),xe=me.getState();xe.setAppSettings(Z),yv(Z),xe.setCommandError(null)}catch(Z){throw me.getState().setCommandError(Z instanceof Error?Z.message:String(Z)),await ae(),Z}},[ae,n]),St=_.useCallback(async q=>{try{Ir.getState().applyOptimisticPatch({claudeAuth:q});const Z=await n.command({type:"appSettings.setClaudeAuth",patch:q}),xe=me.getState();xe.setAppSettings(Z),yv(Z),xe.setCommandError(null)}catch(Z){throw me.getState().setCommandError(Z instanceof Error?Z.message:String(Z)),await ae(),Z}},[ae,n]),Bt=_.useCallback(async q=>await n.command({type:"appSettings.testOAuthToken",token:q}),[n]),Yt=_.useCallback(async()=>{try{const q=await n.command({type:"settings.readLlmProvider"}),Z=me.getState();Z.setLlmProvider(q),Z.setCommandError(null)}catch(q){me.getState().setCommandError(q instanceof Error?q.message:String(q))}},[n]),Mt=_.useCallback(async q=>{try{const Z=await n.command({type:"settings.writeLlmProvider",provider:q.provider,apiKey:q.apiKey,model:q.model,baseUrl:q.baseUrl}),xe=me.getState();xe.setLlmProvider(Z),xe.setCommandError(null)}catch(Z){throw me.getState().setCommandError(Z instanceof Error?Z.message:String(Z)),Z}},[n]),mn=_.useCallback(async q=>await n.command({type:"settings.validateLlmProvider",provider:q.provider,apiKey:q.apiKey,model:q.model,baseUrl:q.baseUrl}),[n]);_.useEffect(()=>{A==="connected"&&ae()},[A,ae]),_.useEffect(()=>{if(A!=="connected")return;j0.getState().setLoading(),n.command({type:"settings.listOpenRouterModels"}).then(Z=>{j0.getState().setModels(Z)}).catch(Z=>{const xe=Z instanceof Error?Z.message:String(Z);j0.getState().setError(xe)})},[A,n]),_.useEffect(()=>{if(A!=="connected"||(k==null?void 0:k.browserSettingsMigrated)!==!1)return;const q=gPe();q&&ke(q).then(vPe).catch(()=>{})},[k==null?void 0:k.browserSettingsMigrated,A,ke]),_.useEffect(()=>{A==="connected"&&Yt()},[A,Yt]),_.useEffect(()=>{function q(){me.getState().incrementFocusEpoch()}return window.addEventListener("focus",q),document.addEventListener("visibilitychange",q),()=>{window.removeEventListener("focus",q),document.removeEventListener("visibilitychange",q)}},[]),_.useEffect(()=>{if(!e){me.getState().setChatSnapshot(null),me.getState().setChatReady(!0);return}++te.current,ne.current.length,ne.current.reduce((Z,xe)=>Z+xe.chats.length,0),me.getState().setChatSnapshot(null),me.getState().setChatReady(!1);const q=n.subscribe({type:"chat",chatId:e,recentLimit:SPe},Z=>{if(Z!=null&&Z.runtime.chatId){const et=[...V.current.values()].filter(Cn=>Cn.serverChatId===Z.runtime.chatId).sort((Cn,Rr)=>Rr.startedAt-Cn.startedAt)[0];et&&et.snapshotAt===void 0&&(et.snapshotAt=performance.now(),$u(et,"chat_snapshot_received",{status:Z.runtime.status,messageCount:Z.messages.length}))}me.getState().setChatSnapshot(et=>{const Cn=pPe(et,Z);return Z==null||Z.runtime.chatId,Z==null||Z.runtime.provider,Z==null||Z.runtime.status,Z==null||Z.messages.length,Cn?et:Z});const xe=me.getState();if(xe.setHistoryCursor((Z==null?void 0:Z.history.olderCursor)??null),xe.setHasOlderHistory((Z==null?void 0:Z.history.hasOlder)??!1),xe.setChatReady(!0),xe.setCommandError(null),Z){const et=rL.getState();et.setForChat(Z.runtime.chatId,Z.slashCommands??[]),et.setLoadingForChat(Z.runtime.chatId,Z.slashCommandsLoading??!1)}});return()=>{ne.current.length,ne.current.reduce((Z,xe)=>Z+xe.chats.length,0),q()}},[e,n]),_.useEffect(()=>{if(e)return n.subscribe({type:"workflows",chatId:e},q=>{j1.getState().setRuns(q.chatId,q.runs)})},[e,n]),_.useEffect(()=>{if(P)return;const q=ee[0];q&&me.getState().setSelectedProjectId(q.groupKey)},[P,ee]),_.useEffect(()=>{if(!e||!T||!j)return;if(ee.some(Z=>Z.chats.some(xe=>xe.chatId===e))){z===e&&me.getState().setPendingChatId(null);return}z!==e&&t("/")},[e,j,t,z,ee,T]),_.useEffect(()=>{p&&(me.getState().setSelectedProjectId(p.runtime.projectId),z===p.runtime.chatId&&me.getState().setPendingChatId(null))},[p,z]),_.useEffect(()=>{if(!e||!T||!CPe())return;const q=ee.flatMap(Z=>Z.chats).find(Z=>Z.chatId===e);q!=null&&q.unread&&n.command({type:"chat.markRead",chatId:e}).catch(Z=>{me.getState().setCommandError(Z instanceof Error?Z.message:String(Z))})},[e,W,ee,T,n]),_.useEffect(()=>{const q=me.getState();q.setOlderHistoryEntries([]),q.setIsHistoryLoading(!1),q.setHistoryCursor(null),q.setHasOlderHistory(!1)},[e]);const Ge=_.useMemo(()=>HPe(p,e),[e,p]),Pt=_.useMemo(()=>(Ge==null?void 0:Ge.runtime.projectId)??APe(ee,e)??P,[e,Ge==null?void 0:Ge.runtime.projectId,P,ee]),gn=_.useMemo(()=>{const q=Pt?S[Pt]??null:null;return Pt&&q?(ue.current={projectId:Pt,diffs:q},q):Pt&&ue.current.projectId===Pt?ue.current.diffs:q},[Pt,S]);_.useEffect(()=>Pt?n.subscribe({type:"project-git",projectId:Pt},Z=>{me.getState().setProjectDiffSnapshots(xe=>{const et=Z??null;return uPe(xe[Pt]??null,et)||cPe(xe[Pt]??null,et)?xe:{...xe,[Pt]:et}}),me.getState().setCommandError(null)}):void 0,[Pt,n]),_.useEffect(()=>{p==null||p.runtime.chatId,p==null||p.runtime.provider,Ge==null||Ge.runtime.chatId,Ge==null||Ge.runtime.provider},[e,Ge,p,z]);const _t=_.useMemo(()=>N6(m,(Ge==null?void 0:Ge.messages)??[]),[Ge==null?void 0:Ge.messages,m]),jt=e??T6,Jt=_.useMemo(()=>F.filter(q=>q.scopeId===jt).map(q=>q.entry),[jt,F]),Wt=_.useMemo(()=>[..._t,...Jt],[Jt,_t]),Vt=_.useMemo(()=>M1(Wt),[Wt]),an=_.useMemo(()=>mPe(Vt),[Vt]),Nn=_.useMemo(()=>jIe(Vt),[Vt]),Ue=(Ge==null?void 0:Ge.runtime)??null,nn=(Ge==null?void 0:Ge.queuedMessages)??[],Le=((K==null?void 0:K.scopeId)===jt&&(!Ue||Ue.status==="idle")?"starting":null)??(Ue==null?void 0:Ue.status)??null,Ze=(Ge==null?void 0:Ge.availableProviders)??Mb,Fe=j0(mm(q=>q.models)),ot=_.useMemo(()=>rPe(Ze,Fe),[Ze,Fe]),Kt=PIe(Le??void 0),ln=IIe(Le??void 0),Sn=(Ue==null?void 0:Ue.isDraining)??!1,rn=((va=o==null?void 0:o.projects[0])==null?void 0:va.localPath)??null,At=(Ue==null?void 0:Ue.localPath)??rn??((vs=ee[0])==null?void 0:vs.localPath),Lt=!!(P??(Ue==null?void 0:Ue.projectId)??((Ya=ee[0])==null?void 0:Ya.groupKey)??rn);_.useEffect(()=>{(K==null?void 0:K.scopeId)===jt&&Ue!=null&&Ue.status&&Ue.status!=="idle"&&me.getState().setOptimisticProcessing(null)},[K,jt,Ue==null?void 0:Ue.status]),_.useEffect(()=>{if(!(K!=null&&K.ackedAt)||K.scopeId!==jt||Ue!=null&&Ue.status&&Ue.status!=="idle")return;const q=K.ackedAt,Z=window.setTimeout(()=>{me.getState().setOptimisticProcessing(xe=>(xe==null?void 0:xe.scopeId)===jt&&xe.ackedAt===q?null:xe)},300);return()=>window.clearTimeout(Z)},[K,jt,Ue==null?void 0:Ue.status]),_.useEffect(()=>{if(!e||(Ue==null?void 0:Ue.status)!=="starting")return;const q=[...V.current.values()].filter(Z=>Z.serverChatId===e).sort((Z,xe)=>xe.startedAt-Z.startedAt)[0];!q||q.startingStatusAt!==void 0||(q.startingStatusAt=performance.now(),$u(q,"runtime_status_starting",{status:Ue.status}))},[e,Ue==null?void 0:Ue.status]),_.useEffect(()=>{if(!e||!Ue||Ue.status==="starting")return;const q=[...V.current.values()].filter(Z=>Z.serverChatId===e).sort((Z,xe)=>xe.startedAt-Z.startedAt)[0];!q||q.startingRenderedAt!==void 0||($u(q,"starting_not_observed",{status:Ue.status}),V.current.delete(q.traceId))},[e,Ue]),_.useLayoutEffect(()=>{if(!e||(Ue==null?void 0:Ue.status)!=="starting"){oe.current=null;return}const q=[...V.current.values()].filter(Z=>Z.serverChatId===e).sort((Z,xe)=>xe.startedAt-Z.startedAt)[0];q&&oe.current!==q.traceId&&(oe.current=q.traceId,q.startingRenderedAt=performance.now(),$u(q,"starting_render_committed",{totalMs:aZ(q.startedAt)}),V.current.delete(q.traceId))},[e,Ue==null?void 0:Ue.status]),_.useEffect(()=>{me.getState().setOptimisticUserPrompts(q=>{const Z=yPe(q,jt,_t);return Z.length===q.length&&Z.every((xe,et)=>xe===q[et])?q:Z})},[jt,_t]);const Zt=_.useCallback(async()=>{if(!(!e||!b||v||!x)){me.getState().setIsHistoryLoading(!0);try{const q=await n.command({type:"chat.loadHistory",chatId:e,beforeCursor:b,limit:wPe}),Z=me.getState();Z.setOlderHistoryEntries(xe=>N6(q.messages,xe)),Z.setHistoryCursor(q.olderCursor),Z.setHasOlderHistory(q.hasOlder),Z.setCommandError(null)}catch(q){const Z=q instanceof Error?q.message:String(q);me.getState().setCommandError(Z)}finally{me.getState().setIsHistoryLoading(!1)}}},[e,x,b,v,n]),It=_.useCallback(async q=>{const Z=Ts.getState(),xe=e?Z.getComposerState(e):Z.getComposerState(hb),et=await n.command({type:"chat.create",projectId:q});Z.initializeComposerForChat(et.chatId,{sourceState:xe});const Cn=me.getState();Cn.setSelectedProjectId(q),Cn.setPendingChatId(et.chatId),t(`/chat/${et.chatId}`),Cn.setSidebarOpen(!1),Cn.setCommandError(null)},[e,t,n]),re=_.useCallback(async q=>q.kind==="project_id"?{projectId:q.projectId}:q.kind==="local_path"?{projectId:(await n.command({type:"project.open",localPath:q.localPath})).projectId,localPath:q.localPath}:{projectId:(await n.command(q.project.mode==="new"?{type:"project.create",localPath:q.project.localPath,title:q.project.title}:{type:"project.open",localPath:q.project.localPath})).projectId,localPath:q.project.localPath},[n]),Me=_.useCallback(async q=>{try{let Z;q.kind==="project_id"?Z=null:q.kind==="local_path"?Z=q.localPath:Z=q.project.localPath,Z&&me.getState().setStartingLocalPath(Z);const{projectId:xe}=await re(q);await It(xe)}catch(Z){me.getState().setCommandError(Z instanceof Error?Z.message:String(Z))}finally{me.getState().setStartingLocalPath(null)}},[It,re]),pt=_.useCallback(async q=>{await Me({kind:"project_id",projectId:q})},[Me]),Ee=_.useCallback(async q=>{try{const Z=await n.command({type:"chat.fork",chatId:q.chatId}),xe=Ts.getState();xe.initializeComposerForChat(Z.chatId,{sourceState:xe.getComposerState(q.chatId)});const et=me.getState();et.setPendingChatId(Z.chatId),t(`/chat/${Z.chatId}`),et.setSidebarOpen(!1),et.setCommandError(null)}catch(Z){me.getState().setCommandError(Z instanceof Error?Z.message:String(Z))}},[t,n]),Ve=_.useCallback(async q=>{await Me({kind:"local_path",localPath:q})},[Me]),qe=_.useCallback(async q=>{await Me({kind:"project_request",project:q})},[Me]),Qe=_.useCallback(async q=>{try{await n.command({type:"update.check",force:q==null?void 0:q.force}),me.getState().setCommandError(null)}catch(Z){me.getState().setCommandError(Z instanceof Error?Z.message:String(Z))}},[n]),mt=_.useCallback(async q=>{d("awaiting_disconnect");try{const Z=await n.command({type:"update.install",version:q});if(!Z.ok){h(),me.getState().setCommandError(null),await r.alert({title:Z.userTitle??"Update failed",description:Z.userMessage??"Kanna could not install the update. Try again later.",closeLabel:"OK"});return}if(Z.ok&&Z.action==="reload"){window.location.reload();return}me.getState().setCommandError(null)}catch(Z){h(),me.getState().setCommandError(Z instanceof Error?Z.message:String(Z))}},[h,r,d,n]),Rt=_.useCallback(async()=>{d("awaiting_disconnect");try{const q=await n.command({type:"update.reload"});if(!q.ok){h(),me.getState().setCommandError(null),await r.alert({title:q.userTitle??"Re-deploy failed",description:q.userMessage??"Kanna could not re-deploy. Try again later.",closeLabel:"OK"});return}if(q.action==="reload"){window.location.reload();return}me.getState().setCommandError(null)}catch(q){h(),me.getState().setCommandError(q instanceof Error?q.message:String(q))}},[h,r,d,n]),bt=_.useCallback(async()=>{try{const q=await fetch("/auth/logout",{method:"POST",headers:{Accept:"application/json"}});if(!q.ok)throw new Error(`Sign out failed with status ${q.status}`);me.getState().setCommandError(null),window.location.reload()}catch(q){me.getState().setCommandError(q instanceof Error?q.message:String(q))}},[]),Be=_.useCallback(async(q,Z)=>{var B;const xe=(Z==null?void 0:Z.attachments)??[],et=Sf(),Cn=Sf(),Rr=aL(q,xe),ki=e??T6;me.getState().setOptimisticProcessing({scopeId:ki,ackedAt:null});const Ce={traceId:Cn,optimisticId:et,startedAt:performance.now(),serverChatId:e,routeChatIdAtSend:e,contentPreview:q.slice(0,80)};V.current.set(Cn,Ce),$u(Ce,"handle_send_called",{optimisticScopeId:ki,attachments:xe.length,contentLength:q.length,contentPreview:Ce.contentPreview});const He=xPe(_t,Rr)+F.filter(Te=>Te.scopeId===ki&&Te.signature===Rr).length+1;me.getState().setOptimisticUserPrompts(Te=>[...Te,{id:et,scopeId:ki,signature:Rr,requiredMatchCount:He,entry:{_id:`optimistic:${et}`,kind:"user_prompt",content:q,attachments:xe,createdAt:Date.now()}}]),$u(Ce,"optimistic_prompt_added",{optimisticId:et,optimisticScopeId:ki});try{let Te=P??((B=ee[0])==null?void 0:B.groupKey)??null;if(!e&&!Te&&rn&&(Te=(await n.command({type:"project.open",localPath:rn})).projectId,me.getState().setSelectedProjectId(Te)),!e&&!Te)throw new Error("Open a project first");const Qt=$R.getState().autoResumeOnRateLimit,Xn=await n.command({type:"chat.send",chatId:e??void 0,projectId:e?void 0:Te??void 0,clientTraceId:Cn,provider:Z==null?void 0:Z.provider,content:q,attachments:xe,model:Z==null?void 0:Z.model,modelOptions:Z==null?void 0:Z.modelOptions,planMode:Z==null?void 0:Z.planMode,autoResumeOnRateLimit:Qt});if(Ce.ackAt=performance.now(),Ce.serverChatId=Xn.chatId??Ce.serverChatId,Xn.queued?(me.getState().setOptimisticUserPrompts(Ei=>_Pe(Ei,et,{queued:!0})),me.getState().setOptimisticProcessing(null)):me.getState().setOptimisticProcessing(Ei=>Ei&&{scopeId:!e&&Xn.chatId?Xn.chatId:Ei.scopeId,ackedAt:performance.now()}),$u(Ce,"chat_send_ack_received",{resultChatId:Xn.chatId??null,queued:Xn.queued??!1}),!e&&Xn.chatId){me.getState().setOptimisticUserPrompts(Ol=>Ol.map(Dl=>Dl.id===et?{...Dl,scopeId:Xn.chatId}:Dl));const Ei=Ts.getState();Ei.setComposerState(Xn.chatId,TPe(Z)??Ei.getComposerState(hb)),me.getState().setPendingChatId(Xn.chatId),t(`/chat/${Xn.chatId}`)}me.getState().setCommandError(null)}catch(Te){throw me.getState().setOptimisticUserPrompts(Qt=>Qt.filter(Xn=>Xn.id!==et)),me.getState().setOptimisticProcessing(null),$u(Ce,"handle_send_failed",{error:Te instanceof Error?Te.message:String(Te)}),V.current.delete(Cn),me.getState().setCommandError(Te instanceof Error?Te.message:String(Te)),Te}},[e,rn,t,F,P,_t,ee,n]),Ot=_.useCallback(async q=>{if(e)try{await n.command({type:"message.steer",chatId:e,queuedMessageId:q}),me.getState().setCommandError(null)}catch(Z){me.getState().setCommandError(Z instanceof Error?Z.message:String(Z))}},[e,n]),Ln=_.useCallback(async q=>{if(e)try{await n.command({type:"message.dequeue",chatId:e,queuedMessageId:q}),me.getState().setCommandError(null)}catch(Z){me.getState().setCommandError(Z instanceof Error?Z.message:String(Z))}},[e,n]),Ht=_.useCallback(async()=>{if(e)try{await n.command({type:"chat.cancel",chatId:e})}catch(q){me.getState().setCommandError(q instanceof Error?q.message:String(q))}},[e,n]),Gt=_.useCallback(async()=>{if(e)try{await n.command({type:"chat.stopDraining",chatId:e})}catch(q){me.getState().setCommandError(q instanceof Error?q.message:String(q))}},[e,n]),yr=_.useCallback(async q=>{const Z=await r.prompt({title:"Rename Chat",initialValue:q.title,confirmLabel:"Rename"});if(!(!Z||Z===q.title))try{await n.command({type:"chat.rename",chatId:q.chatId,title:Z}),me.getState().setCommandError(null)}catch(xe){me.getState().setCommandError(xe instanceof Error?xe.message:String(xe))}},[r,n]),Mn=_.useCallback(async q=>{if(await r.confirm({title:"Delete Chat",description:`Delete "${q.title}"? This cannot be undone.`,confirmLabel:"Delete",confirmVariant:"destructive"}))try{if(await n.command({type:"chat.delete",chatId:q.chatId}),q.chatId===e){const xe=A6(ee,q.chatId);t(xe?`/chat/${xe}`:"/")}}catch(xe){me.getState().setCommandError(xe instanceof Error?xe.message:String(xe))}},[e,r,t,ee,n]),qn=_.useCallback(async q=>{try{if(await n.command({type:"chat.archive",chatId:q.chatId}),q.chatId===e){const Z=A6(ee,q.chatId);t(Z?`/chat/${Z}`:"/")}me.getState().setCommandError(null)}catch(Z){me.getState().setCommandError(Z instanceof Error?Z.message:String(Z))}},[e,t,ee,n]),Yn=_.useCallback(async q=>{try{me.getState().setPendingChatId(q),await n.command({type:"chat.unarchive",chatId:q}),t(`/chat/${q}`),me.getState().setCommandError(null)}catch(Z){me.getState().setPendingChatId(null),me.getState().setCommandError(Z instanceof Error?Z.message:String(Z))}},[t,n]),ye=_.useCallback(async q=>{try{await n.command({type:"project.remove",projectId:q}),Ku.getState().clearProject(q),Ks.getState().clearProject(q),(Ue==null?void 0:Ue.projectId)===q&&t("/"),me.getState().setCommandError(null)}catch(Z){me.getState().setCommandError(Z instanceof Error?Z.message:String(Z))}},[t,Ue,n]),tt=_.useCallback(async(q,Z)=>{try{await n.command({type:"project.setStar",projectId:q,starred:Z}),me.getState().setCommandError(null)}catch(xe){me.getState().setCommandError(xe instanceof Error?xe.message:String(xe))}},[n]),zn=_.useCallback(async q=>{me.getState().setOptimisticSidebarProjectOrder(q);try{await n.command({type:"sidebar.reorderProjectGroups",projectIds:q}),me.getState().setCommandError(null)}catch(Z){me.getState().setOptimisticSidebarProjectOrder(null),me.getState().setCommandError(Z instanceof Error?Z.message:String(Z))}},[n]),qr=_.useCallback(async(q,Z)=>{try{await n.command({type:"stack.create",title:q,projectIds:Z}),me.getState().setCommandError(null)}catch(xe){me.getState().setCommandError(xe instanceof Error?xe.message:String(xe))}},[n]),ce=_.useCallback(async(q,Z)=>{try{await n.command({type:"stack.rename",stackId:q,title:Z}),me.getState().setCommandError(null)}catch(xe){me.getState().setCommandError(xe instanceof Error?xe.message:String(xe))}},[n]),Je=_.useCallback(async q=>{try{await n.command({type:"stack.remove",stackId:q}),me.getState().setCommandError(null)}catch(Z){me.getState().setCommandError(Z instanceof Error?Z.message:String(Z))}},[n]),ut=_.useCallback(async(q,Z)=>{try{await n.command({type:"stack.addProject",stackId:q,projectId:Z}),me.getState().setCommandError(null)}catch(xe){me.getState().setCommandError(xe instanceof Error?xe.message:String(xe))}},[n]),it=_.useCallback(async(q,Z)=>{try{await n.command({type:"stack.removeProject",stackId:q,projectId:Z}),me.getState().setCommandError(null)}catch(xe){me.getState().setCommandError(xe instanceof Error?xe.message:String(xe))}},[n]),jn=_.useCallback(async(q,Z,xe)=>{try{const et=Ts.getState(),Cn=e?et.getComposerState(e):et.getComposerState(hb),Rr=await n.command({type:"chat.create",projectId:q,stackId:Z,stackBindings:xe});et.initializeComposerForChat(Rr.chatId,{sourceState:Cn});const ki=me.getState();ki.setSelectedProjectId(q),ki.setPendingChatId(Rr.chatId),t(`/chat/${Rr.chatId}`),ki.setSidebarOpen(!1),ki.setCommandError(null)}catch(et){me.getState().setCommandError(et instanceof Error?et.message:String(et))}},[e,t,n]),Dt=_.useCallback(async q=>{try{const Z=await n.command({type:"stack.listWorktrees",projectId:q});return me.getState().setCommandError(null),Z.worktrees}catch(Z){return me.getState().setCommandError(Z instanceof Error?Z.message:String(Z)),[]}},[n]),Yr=_.useCallback(async()=>await n.command({type:"sessions.importClaude"}),[n]),li=_.useCallback(async q=>{const Z=ws.getState();me.getState().setCommandError(null),await n.command({type:"system.openExternal",...q,editor:q.action==="open_editor"?q.editor??{preset:Z.editorPreset,commandTemplate:Z.editorCommandTemplate}:void 0})},[n]),Pl=_.useCallback(async(q,Z)=>{var et,Cn;const xe=(Ue==null?void 0:Ue.localPath)??((et=o==null?void 0:o.projects[0])==null?void 0:et.localPath)??((Cn=ee[0])==null?void 0:Cn.localPath);if(xe)try{await li({action:q,localPath:xe,editor:Z})}catch(Rr){me.getState().setCommandError(Rr instanceof Error?Rr.message:String(Rr))}},[o==null?void 0:o.projects,li,Ue==null?void 0:Ue.localPath,ee]),Ds=_.useCallback(async q=>{var Z;try{if(typeof navigator>"u"||!((Z=navigator.clipboard)!=null&&Z.writeText))throw new Error("Clipboard is not available");await navigator.clipboard.writeText(q),me.getState().setCommandError(null)}catch(xe){me.getState().setCommandError(xe instanceof Error?xe.message:String(xe))}},[]),pa=_.useCallback(async(q,Z="open_editor",xe)=>{try{await li({action:Z,localPath:q.path,line:q.line,column:q.column,editor:xe})}catch(et){me.getState().setCommandError(et instanceof Error?et.message:String(et))}},[li]),$s=_.useCallback(async(q,Z)=>{try{await li({action:q,localPath:Z})}catch(xe){me.getState().setCommandError(xe instanceof Error?xe.message:String(xe))}},[li]),$t=_.useCallback(()=>{var Z;const q=UPe({selectedProjectId:P,sidebarProjectId:(Z=ee[0])==null?void 0:Z.groupKey,fallbackLocalProjectPath:rn});if(q){Me(q);return}t("/")},[rn,t,P,ee,Me]),wn=_.useCallback(()=>me.getState().setSidebarOpen(!0),[]),Bn=_.useCallback(()=>me.getState().setSidebarOpen(!1),[]),Rn=_.useCallback(()=>me.getState().setSidebarCollapsed(!0),[]),ma=_.useCallback(()=>me.getState().setSidebarCollapsed(!1),[]),lu=_.useCallback(()=>me.getState().setAddProjectModalOpen(!0),[]),ss=_.useCallback(()=>me.getState().setAddProjectModalOpen(!1),[]),Ll=_.useCallback(async(q,Z,xe)=>{if(e)try{await n.command({type:"chat.respondTool",chatId:e,toolUseId:q,result:{questions:Z,answers:xe}})}catch(et){me.getState().setCommandError(et instanceof Error?et.message:String(et))}},[e,n]),ga=_.useCallback(async(q,Z,xe,et)=>{if(e){Z&&Ts.getState().setChatComposerPlanMode(e,!1);try{await n.command({type:"chat.respondTool",chatId:e,toolUseId:q,result:{confirmed:Z,...xe?{clearContext:!0}:{},...et?{message:et}:{}}})}catch(Cn){me.getState().setCommandError(Cn instanceof Error?Cn.message:String(Cn))}}},[e,n]),cu=_.useCallback(async(q,Z,xe,et)=>{if(e)try{await n.command({type:"chat.respondSubagentTool",chatId:e,runId:q,toolUseId:Z,result:{questions:xe,answers:et}})}catch(Cn){me.getState().setCommandError(Cn instanceof Error?Cn.message:String(Cn))}},[e,n]),ci=_.useCallback(async(q,Z,xe)=>{if(e)try{await n.command({type:"chat.respondSubagentTool",chatId:e,runId:q,toolUseId:Z,result:xe})}catch(et){me.getState().setCommandError(et instanceof Error?et.message:String(et))}},[e,n]),qa=_.useCallback(async(q,Z)=>{if(e)try{await n.command({type:"chat.toolRequestAnswer",chatId:e,toolRequestId:q,decision:Z})}catch(xe){me.getState().setCommandError(xe instanceof Error?xe.message:String(xe))}},[e,n]),Ro=MPe(l,a==null?void 0:a.status);return{socket:n,activeChatId:e,activeProjectId:Pt,sidebarData:ie,localProjects:o,updateSnapshot:a,chatSnapshot:p,chatDiffSnapshot:gn,keybindings:C,appSettings:k,pushConfig:w,llmProvider:N,connectionStatus:A,sidebarReady:T,uiRestartActive:Ro.active,uiRestartLabel:Ro.label,localProjectsReady:M,commandError:$,startingLocalPath:H,sidebarOpen:D,sidebarCollapsed:L,messages:Vt,queuedMessages:nn,previousPrompt:an,latestToolIds:Nn,runtime:Ue,runtimeStatus:Le,isHistoryLoading:v,hasOlderHistory:x,availableProviders:ot,isProcessing:Kt,canCancel:ln,isDraining:Sn,navbarLocalPath:At,editorLabel:de,hasSelectedProject:Lt,addProjectModalOpen:I,openSidebar:wn,closeSidebar:Bn,collapseSidebar:Rn,expandSidebar:ma,openAddProjectModal:lu,closeAddProjectModal:ss,loadOlderHistory:Zt,handleCreateChat:pt,handleForkChat:Ee,handleOpenLocalProject:Ve,handleCreateProject:qe,handleCheckForUpdates:Qe,handleInstallUpdate:mt,handleForceReload:Rt,handleReadAppSettings:ae,handleWriteAppSettings:ke,handleTestMcpServer:Se,handleStartMcpOAuth:Ne,handleCompleteMcpOAuth:Xe,handleSetChatPolicyOverride:Q,handleWriteCloudflareTunnel:ht,handleWriteClaudeAuth:St,handleTestOAuthToken:Bt,handleReadLlmProvider:Yt,handleWriteLlmProvider:Mt,handleValidateLlmProvider:mn,handleSignOut:bt,handleSend:Be,handleSteerQueuedMessage:Ot,handleRemoveQueuedMessage:Ln,handleCancel:Ht,handleStopDraining:Gt,handleRenameChat:yr,handleArchiveChat:qn,handleOpenArchivedChat:Yn,handleDeleteChat:Mn,handleHideProject:ye,handleToggleProjectStar:tt,handleReorderProjectGroups:zn,stacks:ie.stacks,handleCreateStack:qr,handleRenameStack:ce,handleRemoveStack:Je,handleAddProjectToStack:ut,handleRemoveProjectFromStack:it,handleCreateStackChat:jn,handleListStackWorktrees:Dt,importClaudeSessions:Yr,handleCopyPath:Ds,handleOpenExternal:Pl,handleOpenExternalPath:$s,handleOpenLocalLink:pa,handleCompose:$t,handleAskUserQuestion:Ll,handleExitPlanMode:ga,handleSubagentAskUserQuestion:cu,handleSubagentExitPlanMode:ci,handleToolRequestAnswer:qa}}const zR=tn("KannaTranscript",()=>e=>({toolGroupExpanded:{},setToolGroupExpanded:(t,n)=>e(r=>r.toolGroupExpanded[t]===n?r:{toolGroupExpanded:{...r.toolGroupExpanded,[t]:n}})})),VPe=new Set([".c",".cc",".cfg",".conf",".cpp",".cs",".css",".diff",".env",".go",".graphql",".h",".hpp",".html",".ini",".java",".js",".json",".jsonc",".jsx",".kt",".log",".lua",".md",".mjs",".patch",".php",".pl",".properties",".py",".rb",".rs",".scss",".sh",".sql",".swift",".toml",".ts",".tsx",".txt",".vue",".xml",".yaml",".yml",".zsh"]),KPe=new Set([".gitignore",".npmrc",".prettierrc",".python-version",".ruby-version",".tool-versions","Dockerfile","Gemfile","Makefile","Procfile"]);function I0(e){if(!e)return;const t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:void 0}function I6(e){var r,i;const t=/^(?<path>\/.+?)#L(?<line>\d+)(?:C(?<column>\d+))?$/.exec(e);if((r=t==null?void 0:t.groups)!=null&&r.path)return{path:t.groups.path,line:I0(t.groups.line),column:I0(t.groups.column)};const n=/^(?<path>\/.+?):(?<line>\d+)(?::(?<column>\d+))?$/.exec(e);return(i=n==null?void 0:n.groups)!=null&&i.path?{path:n.groups.path,line:I0(n.groups.line),column:I0(n.groups.column)}:e.startsWith("/")?{path:e}:null}function GPe(e){if(!e)return null;const t=e.trim();if(!t||/^(mailto:|ftp:|file:)/i.test(t))return null;if(/^https?:/i.test(t)){if(typeof window>"u")return null;try{const n=new URL(t);return n.origin!==window.location.origin||!n.pathname.startsWith("/")?null:I6(`${n.pathname}${n.hash}`)}catch{return null}}return I6(t)}function qPe(e){const t=e.split(/[\\/]/);for(;t.length>0&&t[t.length-1]==="";)t.pop();const n=t.length>0?t[t.length-1]:e;if(KPe.has(n))return!0;const r=n.lastIndexOf(".");if(r<0)return!0;const i=n.slice(r).toLowerCase();return VPe.has(i)}const YPe=["/Users/","/home/","/private/","/tmp/","/var/","/opt/","/root/"];function XPe(e){return e?e.startsWith("file://")?!0:YPe.some(t=>e.startsWith(t)):!1}function cZ(e){let t=e;if(t.startsWith("file://"))try{t=decodeURIComponent(new URL(t).pathname)}catch{t=t.slice(7)}return`/api/local-file?path=${encodeURIComponent(t)}`}function cd(e,t){if(!e)return"";if(t){const n=t.endsWith("/")?t:`${t}/`;if(e.startsWith(n))return e.slice(n.length);if(e===t)return""}return e.replace(/^\/home\/user\/workspace\//,"")}const P6=/<thinking>([\s\S]*?)<\/thinking>/gi;function JPe(e){const t=[];let n=0;P6.lastIndex=0;let r;for(;(r=P6.exec(e))!==null;){if(r.index>n){const o=e.slice(n,r.index);o.length>0&&t.push({kind:"text",content:o})}t.push({kind:"thinking",content:r[1]??""}),n=r.index+r[0].length}const i=e.slice(n),s=i.search(/<thinking>/i);if(s!==-1){const o=i.slice(0,s);o.length>0&&t.push({kind:"text",content:o});const a=i.slice(s+10);t.push({kind:"thinking",content:a})}else i.length>0&&t.push({kind:"text",content:i});return ZPe(t)}function ZPe(e){const t=[];for(const n of e){const r=t[t.length-1];n.kind==="text"&&r&&r.kind==="text"?r.content+=n.content:t.push(n)}return t}const QPe=/^[ \t]*(`{3,}|~{3,})/,eLe=/https?:\/\/[^\s<>)\]'"]+/g,tLe=new RegExp("(?<![a-zA-Z0-9_])((?:PR|pull\\s+request|merge\\s+request|MR|issue|fix(?:es|ed)?|close[sd]?|resolve[sd]?|bug|task|ticket|story)\\s+)?#(\\d+)","gi"),nLe=/[.,;:!?)\]]+$/;function rLe(e){if(!e.includes("#")||!e.includes("http"))return e;const t=e.split(`
2673
2673
  `);let n=!1,r=!1;const i=[];for(const s of t){if(QPe.test(s)){n=!n,i.push(s);continue}if(n){i.push(s);continue}const o=iLe(s);o!==s&&(r=!0),i.push(o)}return r?i.join(`
2674
2674
  `):e}function iLe(e){if(!e.includes("#")||!e.includes("http"))return e;const t=[],n=new RegExp(eLe.source,"g");let r;for(;(r=n.exec(e))!==null;){let d=r[0];const h=d.match(nLe);h&&(d=d.slice(0,-h[0].length)),t.push({start:r.index,end:r.index+d.length,url:d})}if(t.length===0)return e;const i=[],s=new RegExp(tLe.source,"gi");for(;(r=s.exec(e))!==null;){const d=e.slice(0,r.index);d.lastIndexOf("[")>d.lastIndexOf("]")||i.push({start:r.index,end:r.index+r[0].length,full:r[0],num:r[2]??""})}if(i.length===0)return e;const o=new Map;for(const d of i){const h=t.find(m=>{try{const{pathname:v,search:b}=new URL(m.url),x=v+b;return new RegExp(`(?:/|\\.|-|=)${d.num}(?:[/?&#]|$)`).test(x)}catch{return!1}});if(h){o.set(d.start,h.url);continue}const p=t.find(m=>m.start>d.end);if(p){const m=e.slice(d.end,p.start);!/[.!?]\s/.test(m)&&m.length<200&&o.set(d.start,p.url)}}if(o.size===0)return e;const a=i.filter(d=>o.has(d.start)).sort((d,h)=>h.start-d.start);let l=e;for(const d of a){const h=o.get(d.start);l=`${l.slice(0,d.start)}[${d.full}](${h})${l.slice(d.end)}`}return l}const BR=tn("ThinkingBlock",()=>e=>({expanded:!1,setExpanded:t=>e({expanded:t})}));function sLe({content:e}){const t=BR.useScopedStore(i=>i.expanded),n=BR.useScopedStore(i=>i.setExpanded),r=e.trim();return r.length===0?null:u.jsxs("div",{className:"my-3 first:mt-0 last:mb-0",children:[u.jsxs("button",{type:"button",onClick:()=>n(!t),"aria-expanded":t,className:"group/thinking flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground transition-colors cursor-pointer",children:[u.jsx(G0,{className:"h-3.5 w-3.5"}),u.jsx("span",{className:"font-medium uppercase tracking-wider",children:"Thinking"}),u.jsx(ra,{className:he("h-3.5 w-3.5 transition-transform duration-200",t&&"rotate-90")})]}),t&&u.jsx("div",{className:"mt-2 border-l-2 border-muted-foreground/20 pl-3 text-sm text-muted-foreground italic prose prose-sm dark:prose-invert max-w-[70ch]",children:Gc(r)})]})}const I1=_.memo(({content:e})=>u.jsx(BR.Provider,{init:void 0,children:u.jsx(sLe,{content:e})}));class yx extends nu{constructor(n,r,i,s){super(s);U(this,"__mentionKind");U(this,"__value");U(this,"__label");this.__mentionKind=n,this.__value=r,this.__label=i}static getType(){return"kanna-mention"}static clone(n){return new yx(n.__mentionKind,n.__value,n.__label,n.__key)}static importJSON(n){return FR({mentionKind:n.mentionKind,value:n.value,label:n.label})}exportJSON(){return{type:yx.getType(),version:1,mentionKind:this.__mentionKind,value:this.__value,label:this.__label}}createDOM(n,r){const i=document.createElement("span");return i.dataset.lexicalDecorator="true",i}updateDOM(){return!1}isInline(){return!0}isKeyboardSelectable(){return!0}getTextContent(){return this.__mentionKind==="agent"?`@agent/${this.__value}`:`@${this.__value}`}decorate(n,r){const i=this.__label;return this.__mentionKind==="agent"?u.jsx("span",{className:he("inline-flex items-center rounded px-1 text-sm","bg-primary/10 text-primary border border-primary/20"),children:i}):u.jsx("span",{className:he("inline-flex items-center rounded px-1 text-sm","bg-muted text-muted-foreground border border-border"),children:i})}}function FR(e){return ai(new yx(e.mentionKind,e.value,e.label))}class _x extends nu{constructor(n,r,i){super(i);U(this,"__commandName");U(this,"__hasArgument");this.__commandName=n,this.__hasArgument=r}static getType(){return"kanna-slash-command"}static clone(n){return new _x(n.__commandName,n.__hasArgument,n.__key)}static importJSON(n){return uZ({commandName:n.commandName,hasArgument:n.hasArgument})}exportJSON(){return{type:_x.getType(),version:1,commandName:this.__commandName,hasArgument:this.__hasArgument}}createDOM(n,r){const i=document.createElement("span");return i.dataset.lexicalDecorator="true",i}updateDOM(){return!1}isInline(){return!0}isKeyboardSelectable(){return!0}getTextContent(){return this.__hasArgument?`/${this.__commandName} `:`/${this.__commandName}`}decorate(n,r){return u.jsx("span",{className:he("inline-flex items-center rounded px-1 text-sm font-mono","bg-muted text-muted-foreground border border-border"),children:`/${this.__commandName}`})}}function uZ(e){return ai(new _x(e.commandName,e.hasArgument))}class Fm extends nu{constructor(n,r){super(r);U(this,"__attachment");this.__attachment=n}static getType(){return"kanna-attachment"}static clone(n){return new Fm(n.__attachment,n.__key)}static importJSON(n){return cL(n.attachment)}getAttachment(){return this.getLatest().__attachment}isInline(){return!0}isKeyboardSelectable(){return!0}getTextContent(){return""}createDOM(n,r){return document.createElement("span")}updateDOM(){return!1}exportJSON(){return{type:Fm.getType(),version:1,attachment:this.__attachment}}decorate(n,r){const i=this.getLatest().__attachment;return i.kind==="image"&&i.contentUrl?u.jsx(t1,{attachment:i,size:"composer"}):u.jsx(ko,{attachment:i})}}function cL(e){return ai(new Fm(e))}function oLe(){return CNe(Fm)}class Nd extends nu{constructor(n,r){super(r);U(this,"__source");this.__source=n}static getType(){return"kanna-mermaid"}static clone(n){return new Nd(n.__source,n.__key)}static importJSON(n){return dZ(n.source)}exportJSON(){return{type:Nd.getType(),version:1,source:this.__source}}createDOM(n,r){return document.createElement("div")}updateDOM(){return!1}isInline(){return!1}getTextContent(){return this.__source}decorate(n,r){return u.jsx(AJ,{source:this.__source})}}function dZ(e){return ai(new Nd(e))}function aLe(e){return e instanceof Nd}function lLe(e,t=28){if(e.length<=t)return e;const n="…",r=e.lastIndexOf("."),i=r>0&&e.length-r<=6,s=i?e.slice(r):"",o=i?e.slice(0,r):e,a=t-n.length-s.length;if(a<=2){const h=t-n.length,p=Math.ceil(h/2),m=Math.floor(h/2);return`${e.slice(0,p)}${n}${e.slice(e.length-m)}`}const l=Math.ceil(a/2),d=a-l;return`${o.slice(0,l)}${n}${o.slice(o.length-d)}${s}`}const $v=tn("LocalFileLinkCard",()=>e=>({probe:{kind:"loading"},previewOpen:!1,setProbe:t=>e({probe:t}),setPreviewOpen:t=>e({previewOpen:t})}));function cLe(e){const t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}function uLe({path:e,linkText:t}){const n=_.useMemo(()=>cZ(e),[e]),r=$v.useScopedStore(T=>T.probe),i=$v.useScopedStore(T=>T.previewOpen),s=$v.useScopedStore(T=>T.setProbe),o=$v.useScopedStore(T=>T.setPreviewOpen);_.useEffect(()=>{const T=new AbortController;return fetch(n,{method:"HEAD",signal:T.signal}).then(M=>{var D,L;if(T.signal.aborted)return;if(!M.ok){s({kind:M.status===404?"missing":"error"});return}const j=((L=(D=M.headers.get("Content-Type"))==null?void 0:D.split(";")[0])==null?void 0:L.trim())||"application/octet-stream",P=Number.parseInt(M.headers.get("Content-Length")??"0",10)||0;s({kind:"ready",mimeType:j,size:P})}).catch(()=>{T.signal.aborted||s({kind:"error"})}),()=>T.abort()},[n,s]);const a=cLe(e),l=t||a,d=lLe(l,28),h=r.kind==="ready"?r.mimeType:"application/octet-stream",p=r.kind==="ready"?r.size:0,m={id:`local-file-${n}`,kind:"file",displayName:d,absolutePath:e,relativePath:e,contentUrl:n,mimeType:h,size:p};if(r.kind==="missing")return u.jsx("span",{className:"inline-flex align-bottom","data-testid":"local-file-link",children:u.jsx(ko,{attachment:m,disabledReason:"File no longer available"})});const v=Ch(m),b=Xx(v,h),x=p>0?kh(p):null,S=r.kind==="loading",C=r.kind==="error";let k;S?k=u.jsx("span",{className:"text-muted-foreground",children:"Fetching…"}):C?k=u.jsx("span",{className:"text-muted-foreground",children:"Unable to load"}):k=u.jsxs(u.Fragment,{children:[b,x?u.jsxs(u.Fragment,{children:[" · ",u.jsx("span",{className:"tabular-nums",children:x})]}):null]});const w=r.kind==="ready"?ag(m):null,N=w!==null&&!w.openInNewTab,A=[N?"Preview":"Download",l,b,x].filter(T=>!!T);return N?u.jsxs(u.Fragment,{children:[u.jsx("span",{className:"inline-flex align-bottom","data-testid":"local-file-link",children:u.jsx(ko,{attachment:m,onClick:()=>o(!0),meta:k,ariaLabel:A.join(", ")})}),u.jsx(Mh,{source:i?mg(m,"local_file_link"):null,open:i,onOpenChange:o})]}):u.jsx("span",{className:"inline-flex align-bottom","data-testid":"local-file-link",children:u.jsx(ko,{attachment:m,href:n,download:a,meta:k,ariaLabel:A.join(", ")})})}function dLe({path:e,linkText:t}){return u.jsx($v.Provider,{init:void 0,children:u.jsx(uLe,{path:e,linkText:t})})}class Td extends nu{constructor(n,r,i,s){super(s);U(this,"__path");U(this,"__line");U(this,"__column");this.__path=n,this.__line=r,this.__column=i}static getType(){return"kanna-local-file-link"}static clone(n){return new Td(n.__path,n.__line,n.__column,n.__key)}static importJSON(n){return fZ({path:n.path,line:n.line,column:n.column})}exportJSON(){const n={type:Td.getType(),version:1,path:this.__path};return this.__line!==void 0&&(n.line=this.__line),this.__column!==void 0&&(n.column=this.__column),n}createDOM(n,r){return document.createElement("span")}updateDOM(){return!1}isInline(){return!0}getTextContent(){return this.__path}decorate(n,r){const i=this.__line!==void 0?`${this.__path}:${this.__line}${this.__column!==void 0?`:${this.__column}`:""}`:void 0;return u.jsx(dLe,{path:this.__path,linkText:i})}}function fZ(e){return ai(new Td(e.path,e.line,e.column))}function fLe(e){return e instanceof Td}class Sx extends nu{constructor(n,r){super(r);U(this,"__content");this.__content=n}static getType(){return"kanna-thinking"}static clone(n){return new Sx(n.__content,n.__key)}static importJSON(n){return hLe(n.content)}exportJSON(){return{type:Sx.getType(),version:1,content:this.__content}}createDOM(n,r){return document.createElement("div")}updateDOM(){return!1}isInline(){return!1}getTextContent(){return this.__content}decorate(n,r){return u.jsx(I1,{content:this.__content})}}function hLe(e){return ai(new Sx(e))}const pLe=[yx,_x,Fm],mLe=[Nd,Td,Sx],gLe=/^[ \t]*(`{3,})[ \t]*mermaid[ \t]*$/i,L6=/^[ \t]*`{3,}[ \t]*$/,vLe={type:"multiline-element",dependencies:[Nd],regExpStart:gLe,regExpEnd:{optional:!0,regExp:L6},handleImportAfterStartMatch({lines:e,rootNode:t,startLineIndex:n,startMatch:r}){const s=(r[1]??"```").length,o=new RegExp(`^[ \\t]\`{${s},}[ \\t]*$`),a=[];let l=n;for(let p=n+1;p<e.length;p++){const m=e[p];if(m===void 0)break;if(L6.test(m)||o.test(m)){l=p;break}a.push(m),l=p}const d=a.join(`
2675
2675
  `),h=dZ(d);return t.append(h),[!0,l]},replace(e,t,n,r,i,s){return!1},export(e){return e instanceof Nd?`\`\`\`mermaid